The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

276941 lines
7.4MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #else
  51. #define JUCE_MAC 1
  52. #endif
  53. #else
  54. #error "Unknown platform!"
  55. #endif
  56. #if JUCE_WINDOWS
  57. #ifdef _MSC_VER
  58. #ifdef _WIN64
  59. #define JUCE_64BIT 1
  60. #else
  61. #define JUCE_32BIT 1
  62. #endif
  63. #endif
  64. #ifdef _DEBUG
  65. #define JUCE_DEBUG 1
  66. #endif
  67. #ifdef __MINGW32__
  68. #define JUCE_MINGW 1
  69. #endif
  70. /** If defined, this indicates that the processor is little-endian. */
  71. #define JUCE_LITTLE_ENDIAN 1
  72. #define JUCE_INTEL 1
  73. #endif
  74. #if JUCE_MAC
  75. #ifndef NDEBUG
  76. #define JUCE_DEBUG 1
  77. #endif
  78. #ifdef __LITTLE_ENDIAN__
  79. #define JUCE_LITTLE_ENDIAN 1
  80. #else
  81. #define JUCE_BIG_ENDIAN 1
  82. #endif
  83. #if defined (__ppc__) || defined (__ppc64__)
  84. #define JUCE_PPC 1
  85. #else
  86. #define JUCE_INTEL 1
  87. #endif
  88. #ifdef __LP64__
  89. #define JUCE_64BIT 1
  90. #else
  91. #define JUCE_32BIT 1
  92. #endif
  93. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  94. #error "Building for OSX 10.3 is no longer supported!"
  95. #endif
  96. #ifndef MAC_OS_X_VERSION_10_5
  97. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  98. #endif
  99. #endif
  100. #if JUCE_IPHONE
  101. #ifndef NDEBUG
  102. #define JUCE_DEBUG 1
  103. #endif
  104. #ifdef __LITTLE_ENDIAN__
  105. #define JUCE_LITTLE_ENDIAN 1
  106. #else
  107. #define JUCE_BIG_ENDIAN 1
  108. #endif
  109. #endif
  110. #if JUCE_LINUX
  111. #ifdef _DEBUG
  112. #define JUCE_DEBUG 1
  113. #endif
  114. // Allow override for big-endian Linux platforms
  115. #ifndef JUCE_BIG_ENDIAN
  116. #define JUCE_LITTLE_ENDIAN 1
  117. #endif
  118. #if defined (__LP64__) || defined (_LP64)
  119. #define JUCE_64BIT 1
  120. #else
  121. #define JUCE_32BIT 1
  122. #endif
  123. #define JUCE_INTEL 1
  124. #endif
  125. // Compiler type macros.
  126. #ifdef __GNUC__
  127. #define JUCE_GCC 1
  128. #elif defined (_MSC_VER)
  129. #define JUCE_MSVC 1
  130. #if _MSC_VER >= 1400
  131. #define JUCE_USE_INTRINSICS 1
  132. #endif
  133. #else
  134. #error unknown compiler
  135. #endif
  136. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  137. /*** End of inlined file: juce_TargetPlatform.h ***/
  138. // FORCE_AMALGAMATOR_INCLUDE
  139. /*** Start of inlined file: juce_Config.h ***/
  140. #ifndef __JUCE_CONFIG_JUCEHEADER__
  141. #define __JUCE_CONFIG_JUCEHEADER__
  142. /*
  143. This file contains macros that enable/disable various JUCE features.
  144. */
  145. /** The name of the namespace that all Juce classes and functions will be
  146. put inside. If this is not defined, no namespace will be used.
  147. */
  148. #ifndef JUCE_NAMESPACE
  149. #define JUCE_NAMESPACE juce
  150. #endif
  151. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  152. project settings, but if you define this value, you can override this to force
  153. it to be true or false.
  154. */
  155. #ifndef JUCE_FORCE_DEBUG
  156. //#define JUCE_FORCE_DEBUG 0
  157. #endif
  158. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  159. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  160. Enabling it will also leave this turned on in release builds. When it's disabled,
  161. however, the jassert and jassertfalse macros will not be compiled in a
  162. release build.
  163. @see jassert, jassertfalse, Logger
  164. */
  165. #ifndef JUCE_LOG_ASSERTIONS
  166. #define JUCE_LOG_ASSERTIONS 0
  167. #endif
  168. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  169. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  170. on your Windows build machine.
  171. See the comments in the ASIOAudioIODevice class's header file for more
  172. info about this.
  173. */
  174. #ifndef JUCE_ASIO
  175. #define JUCE_ASIO 0
  176. #endif
  177. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  178. */
  179. #ifndef JUCE_WASAPI
  180. #define JUCE_WASAPI 0
  181. #endif
  182. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  183. */
  184. #ifndef JUCE_DIRECTSOUND
  185. #define JUCE_DIRECTSOUND 1
  186. #endif
  187. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  188. #ifndef JUCE_ALSA
  189. #define JUCE_ALSA 1
  190. #endif
  191. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  192. #ifndef JUCE_JACK
  193. #define JUCE_JACK 0
  194. #endif
  195. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  196. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  197. installed, and its header files will need to be on your include path.
  198. */
  199. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  200. #define JUCE_QUICKTIME 0
  201. #endif
  202. #if (JUCE_IPHONE || JUCE_LINUX) && JUCE_QUICKTIME
  203. #undef JUCE_QUICKTIME
  204. #endif
  205. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  206. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  207. */
  208. #ifndef JUCE_OPENGL
  209. #define JUCE_OPENGL 1
  210. #endif
  211. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  212. If your app doesn't need to read FLAC files, you might want to disable this to
  213. reduce the size of your codebase and build time.
  214. */
  215. #ifndef JUCE_USE_FLAC
  216. #define JUCE_USE_FLAC 1
  217. #endif
  218. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  219. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_OGGVORBIS
  223. #define JUCE_USE_OGGVORBIS 1
  224. #endif
  225. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  226. Unless you're using CD-burning, you should probably turn this flag off to
  227. reduce code size.
  228. */
  229. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  230. #define JUCE_USE_CDBURNER 0
  231. #endif
  232. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-reading, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #ifndef JUCE_USE_CDREADER
  237. #define JUCE_USE_CDREADER 0
  238. #endif
  239. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  240. */
  241. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  242. #define JUCE_USE_CAMERA 0
  243. #endif
  244. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  245. gets repainted will flash in a random colour, so that you can check exactly how much and how
  246. often your components are being drawn.
  247. */
  248. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  249. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  250. #endif
  251. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  252. Unless you specifically want to disable this, it's best to leave this option turned on.
  253. */
  254. #ifndef JUCE_USE_XINERAMA
  255. #define JUCE_USE_XINERAMA 1
  256. #endif
  257. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  258. turned on unless you have a good reason to disable it.
  259. */
  260. #ifndef JUCE_USE_XSHM
  261. #define JUCE_USE_XSHM 1
  262. #endif
  263. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  264. */
  265. #ifndef JUCE_USE_XRENDER
  266. #define JUCE_USE_XRENDER 0
  267. #endif
  268. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  269. unless you have a good reason to disable it.
  270. */
  271. #ifndef JUCE_USE_XCURSOR
  272. #define JUCE_USE_XCURSOR 1
  273. #endif
  274. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  275. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  276. you're building a plugin hosting app.
  277. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  278. */
  279. #ifndef JUCE_PLUGINHOST_VST
  280. #define JUCE_PLUGINHOST_VST 0
  281. #endif
  282. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  283. of course, and should only be enabled if you're building a plugin hosting app.
  284. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  285. */
  286. #ifndef JUCE_PLUGINHOST_AU
  287. #define JUCE_PLUGINHOST_AU 0
  288. #endif
  289. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  290. This should be enabled if you're writing a console application.
  291. */
  292. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  293. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  294. #endif
  295. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  296. If you're not using any embedded web-pages, turning this off may reduce your code size.
  297. */
  298. #ifndef JUCE_WEB_BROWSER
  299. #define JUCE_WEB_BROWSER 1
  300. #endif
  301. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  302. Carbon isn't required for a normal app, but may be needed by specialised classes like
  303. plugin-hosts, which support older APIs.
  304. */
  305. #ifndef JUCE_SUPPORT_CARBON
  306. #define JUCE_SUPPORT_CARBON 1
  307. #endif
  308. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  309. You might need to tweak this if you're linking to an external zlib library in your app,
  310. but for normal apps, this option should be left alone.
  311. */
  312. #ifndef JUCE_INCLUDE_ZLIB_CODE
  313. #define JUCE_INCLUDE_ZLIB_CODE 1
  314. #endif
  315. #ifndef JUCE_INCLUDE_FLAC_CODE
  316. #define JUCE_INCLUDE_FLAC_CODE 1
  317. #endif
  318. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  319. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  320. #endif
  321. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  322. #define JUCE_INCLUDE_PNGLIB_CODE 1
  323. #endif
  324. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  325. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  326. #endif
  327. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  328. (Currently, this only affects Windows builds in debug mode).
  329. */
  330. #ifndef JUCE_CHECK_MEMORY_LEAKS
  331. #define JUCE_CHECK_MEMORY_LEAKS 1
  332. #endif
  333. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  334. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  335. are passed to the JUCEApplication::unhandledException() callback for logging.
  336. */
  337. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  338. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  339. #endif
  340. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  341. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  342. #undef JUCE_QUICKTIME
  343. #define JUCE_QUICKTIME 0
  344. #undef JUCE_OPENGL
  345. #define JUCE_OPENGL 0
  346. #undef JUCE_USE_CDBURNER
  347. #define JUCE_USE_CDBURNER 0
  348. #undef JUCE_USE_CDREADER
  349. #define JUCE_USE_CDREADER 0
  350. #undef JUCE_WEB_BROWSER
  351. #define JUCE_WEB_BROWSER 0
  352. #undef JUCE_PLUGINHOST_AU
  353. #define JUCE_PLUGINHOST_AU 0
  354. #undef JUCE_PLUGINHOST_VST
  355. #define JUCE_PLUGINHOST_VST 0
  356. #endif
  357. #endif
  358. /*** End of inlined file: juce_Config.h ***/
  359. // FORCE_AMALGAMATOR_INCLUDE
  360. #ifndef JUCE_BUILD_CORE
  361. #define JUCE_BUILD_CORE 1
  362. #endif
  363. #ifndef JUCE_BUILD_MISC
  364. #define JUCE_BUILD_MISC 1
  365. #endif
  366. #ifndef JUCE_BUILD_GUI
  367. #define JUCE_BUILD_GUI 1
  368. #endif
  369. #ifndef JUCE_BUILD_NATIVE
  370. #define JUCE_BUILD_NATIVE 1
  371. #endif
  372. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  373. #undef JUCE_BUILD_MISC
  374. #undef JUCE_BUILD_GUI
  375. #endif
  376. //==============================================================================
  377. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  378. #if JUCE_WINDOWS
  379. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  380. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  381. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  382. #ifndef STRICT
  383. #define STRICT 1
  384. #endif
  385. #undef WIN32_LEAN_AND_MEAN
  386. #define WIN32_LEAN_AND_MEAN 1
  387. #if JUCE_MSVC
  388. #pragma warning (push)
  389. #pragma warning (disable : 4100 4201 4514 4312 4995)
  390. #endif
  391. #define _WIN32_WINNT 0x0500
  392. #define _UNICODE 1
  393. #define UNICODE 1
  394. #ifndef _WIN32_IE
  395. #define _WIN32_IE 0x0400
  396. #endif
  397. #include <windows.h>
  398. #include <windowsx.h>
  399. #include <commdlg.h>
  400. #include <shellapi.h>
  401. #include <mmsystem.h>
  402. #include <vfw.h>
  403. #include <tchar.h>
  404. #include <stddef.h>
  405. #include <ctime>
  406. #include <wininet.h>
  407. #include <nb30.h>
  408. #include <iphlpapi.h>
  409. #include <mapi.h>
  410. #include <float.h>
  411. #include <process.h>
  412. #include <Exdisp.h>
  413. #include <exdispid.h>
  414. #include <shlobj.h>
  415. #if ! JUCE_MINGW
  416. #include <crtdbg.h>
  417. #include <comutil.h>
  418. #endif
  419. #if JUCE_OPENGL
  420. #include <gl/gl.h>
  421. #endif
  422. #undef PACKED
  423. #if JUCE_ASIO
  424. /*
  425. This is very frustrating - we only need to use a handful of definitions from
  426. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  427. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  428. implementation...
  429. ..unfortunately that would break Steinberg's license agreement for use of
  430. their SDK, so I'm not allowed to do this.
  431. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  432. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  433. (see www.steinberg.net/Steinberg/Developers.asp).
  434. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  435. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  436. if you prefer). Make sure that your header search path will find the
  437. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  438. files are actually needed - so to simplify things, you could just copy
  439. these into your JUCE directory).
  440. If you're compiling and you get an error here because you don't have the
  441. ASIO SDK installed, you can disable ASIO support by commenting-out the
  442. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  443. */
  444. #include "iasiodrv.h"
  445. #endif
  446. #if JUCE_USE_CDBURNER
  447. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  448. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  449. flag in juce_Config.h to avoid these includes.
  450. */
  451. #include <imapi.h>
  452. #include <imapierror.h>
  453. #endif
  454. #if JUCE_USE_CAMERA
  455. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  456. These files are provided in the normal Windows SDK, but some Microsoft plonker
  457. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  458. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  459. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  460. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  461. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  462. The dummy file just needs to contain the following content:
  463. #define __IDxtCompositor_INTERFACE_DEFINED__
  464. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  465. #define __IDxtJpeg_INTERFACE_DEFINED__
  466. #define __IDxtKey_INTERFACE_DEFINED__
  467. ..and that should be enough to convince qedit.h that you have the SDK!
  468. */
  469. #include <dshow.h>
  470. #include <qedit.h>
  471. #include <dshowasf.h>
  472. #endif
  473. #if JUCE_WASAPI
  474. #include <MMReg.h>
  475. #include <mmdeviceapi.h>
  476. #include <Audioclient.h>
  477. #include <Avrt.h>
  478. #include <functiondiscoverykeys.h>
  479. #endif
  480. #if JUCE_QUICKTIME
  481. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  482. add its header directory to your include path.
  483. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  484. flag in juce_Config.h
  485. */
  486. #include <Movies.h>
  487. #include <QTML.h>
  488. #include <QuickTimeComponents.h>
  489. #include <MediaHandlers.h>
  490. #include <ImageCodec.h>
  491. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  492. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  493. your include search path to make these import statements work.
  494. */
  495. #import <QTOLibrary.dll>
  496. #import <QTOControl.dll>
  497. #endif
  498. #if JUCE_MSVC
  499. #pragma warning (pop)
  500. #endif
  501. /** A simple COM smart pointer.
  502. Avoids having to include ATL just to get one of these.
  503. */
  504. template <class ComClass>
  505. class ComSmartPtr
  506. {
  507. public:
  508. ComSmartPtr() throw() : p (0) {}
  509. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  510. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  511. ~ComSmartPtr() { if (p != 0) p->Release(); }
  512. operator ComClass*() const throw() { return p; }
  513. ComClass& operator*() const throw() { return *p; }
  514. ComClass** operator&() throw() { return &p; }
  515. ComClass* operator->() const throw() { return p; }
  516. ComClass* operator= (ComClass* const newP)
  517. {
  518. if (newP != 0) newP->AddRef();
  519. if (p != 0) p->Release();
  520. p = newP;
  521. return newP;
  522. }
  523. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  524. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  525. {
  526. #ifndef __MINGW32__
  527. operator= (0);
  528. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  529. #else
  530. return S_FALSE;
  531. #endif
  532. }
  533. private:
  534. ComClass* p;
  535. };
  536. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  537. */
  538. template <class ComClass>
  539. class ComBaseClassHelper : public ComClass
  540. {
  541. public:
  542. ComBaseClassHelper() : refCount (1) {}
  543. virtual ~ComBaseClassHelper() {}
  544. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  545. {
  546. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  547. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  548. *result = 0;
  549. return E_NOINTERFACE;
  550. }
  551. ULONG __stdcall AddRef() { return ++refCount; }
  552. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  553. protected:
  554. int refCount;
  555. };
  556. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  557. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  558. #elif JUCE_LINUX
  559. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  560. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  561. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  562. /*
  563. This file wraps together all the linux-specific headers, so
  564. that we can include them all just once, and compile all our
  565. platform-specific stuff in one big lump, keeping it out of the
  566. way of the rest of the codebase.
  567. */
  568. #include <sched.h>
  569. #include <pthread.h>
  570. #include <sys/time.h>
  571. #include <errno.h>
  572. #include <sys/stat.h>
  573. #include <sys/dir.h>
  574. #include <sys/ptrace.h>
  575. #include <sys/vfs.h>
  576. #include <sys/wait.h>
  577. #include <fnmatch.h>
  578. #include <utime.h>
  579. #include <pwd.h>
  580. #include <fcntl.h>
  581. #include <dlfcn.h>
  582. #include <netdb.h>
  583. #include <arpa/inet.h>
  584. #include <netinet/in.h>
  585. #include <sys/types.h>
  586. #include <sys/ioctl.h>
  587. #include <sys/socket.h>
  588. #include <linux/if.h>
  589. #include <sys/sysinfo.h>
  590. #include <sys/file.h>
  591. #include <signal.h>
  592. /* Got a build error here? You'll need to install the freetype library...
  593. The name of the package to install is "libfreetype6-dev".
  594. */
  595. #include <ft2build.h>
  596. #include FT_FREETYPE_H
  597. #include <X11/Xlib.h>
  598. #include <X11/Xatom.h>
  599. #include <X11/Xresource.h>
  600. #include <X11/Xutil.h>
  601. #include <X11/Xmd.h>
  602. #include <X11/keysym.h>
  603. #include <X11/cursorfont.h>
  604. #if JUCE_USE_XINERAMA
  605. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  606. #include <X11/extensions/Xinerama.h>
  607. #endif
  608. #if JUCE_USE_XSHM
  609. #include <X11/extensions/XShm.h>
  610. #include <sys/shm.h>
  611. #include <sys/ipc.h>
  612. #endif
  613. #if JUCE_USE_XRENDER
  614. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  615. #include <X11/extensions/Xrender.h>
  616. #include <X11/extensions/Xcomposite.h>
  617. #endif
  618. #if JUCE_USE_XCURSOR
  619. // If you're missing this header, try installing the libxcursor-dev package
  620. #include <X11/Xcursor/Xcursor.h>
  621. #endif
  622. #if JUCE_OPENGL
  623. /* Got an include error here?
  624. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  625. and "freeglut3-dev".
  626. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  627. want to disable it.
  628. */
  629. #include <GL/glx.h>
  630. #endif
  631. #undef KeyPress
  632. #if JUCE_ALSA
  633. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  634. not got your paths set up correctly to find its header files.
  635. The package you need to install to get ASLA support is "libasound2-dev".
  636. If you don't have the ALSA library and don't want to build Juce with audio support,
  637. just disable the JUCE_ALSA flag in juce_Config.h
  638. */
  639. #include <alsa/asoundlib.h>
  640. #endif
  641. #if JUCE_JACK
  642. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  643. installed, or you've not got your paths set up correctly to find its header files.
  644. The package you need to install to get JACK support is "libjack-dev".
  645. If you don't have the jack-audio-connection-kit library and don't want to build
  646. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  647. */
  648. #include <jack/jack.h>
  649. //#include <jack/transport.h>
  650. #endif
  651. #undef SIZEOF
  652. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  653. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  654. #elif JUCE_MAC || JUCE_IPHONE
  655. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  656. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  657. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  658. /*
  659. This file wraps together all the mac-specific code, so that
  660. we can include all the native headers just once, and compile all our
  661. platform-specific stuff in one big lump, keeping it out of the way of
  662. the rest of the codebase.
  663. */
  664. #define USE_COREGRAPHICS_RENDERING 1
  665. #if JUCE_IPHONE
  666. #import <Foundation/Foundation.h>
  667. #import <UIKit/UIKit.h>
  668. #import <AudioToolbox/AudioToolbox.h>
  669. #import <AVFoundation/AVFoundation.h>
  670. #import <CoreData/CoreData.h>
  671. #import <MobileCoreServices/MobileCoreServices.h>
  672. #import <QuartzCore/QuartzCore.h>
  673. #include <sys/fcntl.h>
  674. #if JUCE_OPENGL
  675. #include <OpenGLES/ES1/gl.h>
  676. #include <OpenGLES/ES1/glext.h>
  677. #endif
  678. #else
  679. #import <Cocoa/Cocoa.h>
  680. #import <CoreAudio/HostTime.h>
  681. #import <CoreAudio/AudioHardware.h>
  682. #import <CoreMIDI/MIDIServices.h>
  683. #import <QTKit/QTKit.h>
  684. #import <WebKit/WebKit.h>
  685. #import <DiscRecording/DiscRecording.h>
  686. #import <IOKit/IOKitLib.h>
  687. #import <IOKit/IOCFPlugIn.h>
  688. #import <IOKit/hid/IOHIDLib.h>
  689. #import <IOKit/hid/IOHIDKeys.h>
  690. #import <IOKit/pwr_mgt/IOPMLib.h>
  691. #include <Carbon/Carbon.h>
  692. #include <sys/dir.h>
  693. #endif
  694. #include <sys/socket.h>
  695. #include <sys/sysctl.h>
  696. #include <sys/stat.h>
  697. #include <sys/param.h>
  698. #include <sys/mount.h>
  699. #include <fnmatch.h>
  700. #include <utime.h>
  701. #include <dlfcn.h>
  702. #include <ifaddrs.h>
  703. #include <net/if_dl.h>
  704. #include <mach/mach_time.h>
  705. #if MACOS_10_4_OR_EARLIER
  706. #include <GLUT/glut.h>
  707. #endif
  708. #if ! CGFLOAT_DEFINED
  709. #define CGFloat float
  710. #endif
  711. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  712. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  713. #else
  714. #error "Unknown platform!"
  715. #endif
  716. #endif
  717. //==============================================================================
  718. #define DONT_SET_USING_JUCE_NAMESPACE 1
  719. #undef max
  720. #undef min
  721. #define NO_DUMMY_DECL
  722. #if JUCE_BUILD_NATIVE
  723. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  724. #endif
  725. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  726. #pragma warning (disable: 4309 4305)
  727. #endif
  728. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  729. BEGIN_JUCE_NAMESPACE
  730. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  731. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  732. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  733. /**
  734. Creates a floating carbon window that can be used to hold a carbon UI.
  735. This is a handy class that's designed to be inlined where needed, e.g.
  736. in the audio plugin hosting code.
  737. */
  738. class CarbonViewWrapperComponent : public Component,
  739. public ComponentMovementWatcher,
  740. public Timer
  741. {
  742. public:
  743. CarbonViewWrapperComponent()
  744. : ComponentMovementWatcher (this),
  745. wrapperWindow (0),
  746. embeddedView (0),
  747. recursiveResize (false)
  748. {
  749. }
  750. virtual ~CarbonViewWrapperComponent()
  751. {
  752. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  753. }
  754. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  755. virtual void removeView (HIViewRef embeddedView) = 0;
  756. virtual void mouseDown (int, int) {}
  757. virtual void paint() {}
  758. virtual bool getEmbeddedViewSize (int& w, int& h)
  759. {
  760. if (embeddedView == 0)
  761. return false;
  762. HIRect bounds;
  763. HIViewGetBounds (embeddedView, &bounds);
  764. w = jmax (1, roundToInt (bounds.size.width));
  765. h = jmax (1, roundToInt (bounds.size.height));
  766. return true;
  767. }
  768. void createWindow()
  769. {
  770. if (wrapperWindow == 0)
  771. {
  772. Rect r;
  773. r.left = getScreenX();
  774. r.top = getScreenY();
  775. r.right = r.left + getWidth();
  776. r.bottom = r.top + getHeight();
  777. CreateNewWindow (kDocumentWindowClass,
  778. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  779. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  780. &r, &wrapperWindow);
  781. jassert (wrapperWindow != 0);
  782. if (wrapperWindow == 0)
  783. return;
  784. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  785. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  786. [ownerWindow addChildWindow: carbonWindow
  787. ordered: NSWindowAbove];
  788. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  789. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  790. { kEventClassWindow, kEventWindowHandleDeactivate } };
  791. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  792. InstallWindowEventHandler (wrapperWindow, upp,
  793. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  794. windowEventTypes, this, &eventHandlerRef);
  795. setOurSizeToEmbeddedViewSize();
  796. setEmbeddedWindowToOurSize();
  797. creationTime = Time::getCurrentTime();
  798. }
  799. }
  800. void deleteWindow()
  801. {
  802. removeView (embeddedView);
  803. embeddedView = 0;
  804. if (wrapperWindow != 0)
  805. {
  806. RemoveEventHandler (eventHandlerRef);
  807. DisposeWindow (wrapperWindow);
  808. wrapperWindow = 0;
  809. }
  810. }
  811. void setOurSizeToEmbeddedViewSize()
  812. {
  813. int w, h;
  814. if (getEmbeddedViewSize (w, h))
  815. {
  816. if (w != getWidth() || h != getHeight())
  817. {
  818. startTimer (50);
  819. setSize (w, h);
  820. if (getParentComponent() != 0)
  821. getParentComponent()->setSize (w, h);
  822. }
  823. else
  824. {
  825. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  826. }
  827. }
  828. else
  829. {
  830. stopTimer();
  831. }
  832. }
  833. void setEmbeddedWindowToOurSize()
  834. {
  835. if (! recursiveResize)
  836. {
  837. recursiveResize = true;
  838. if (embeddedView != 0)
  839. {
  840. HIRect r;
  841. r.origin.x = 0;
  842. r.origin.y = 0;
  843. r.size.width = (float) getWidth();
  844. r.size.height = (float) getHeight();
  845. HIViewSetFrame (embeddedView, &r);
  846. }
  847. if (wrapperWindow != 0)
  848. {
  849. Rect wr;
  850. wr.left = getScreenX();
  851. wr.top = getScreenY();
  852. wr.right = wr.left + getWidth();
  853. wr.bottom = wr.top + getHeight();
  854. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  855. ShowWindow (wrapperWindow);
  856. }
  857. recursiveResize = false;
  858. }
  859. }
  860. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  861. {
  862. setEmbeddedWindowToOurSize();
  863. }
  864. void componentPeerChanged()
  865. {
  866. deleteWindow();
  867. createWindow();
  868. }
  869. void componentVisibilityChanged (Component&)
  870. {
  871. if (isShowing())
  872. createWindow();
  873. else
  874. deleteWindow();
  875. setEmbeddedWindowToOurSize();
  876. }
  877. static void recursiveHIViewRepaint (HIViewRef view)
  878. {
  879. HIViewSetNeedsDisplay (view, true);
  880. HIViewRef child = HIViewGetFirstSubview (view);
  881. while (child != 0)
  882. {
  883. recursiveHIViewRepaint (child);
  884. child = HIViewGetNextView (child);
  885. }
  886. }
  887. void timerCallback()
  888. {
  889. setOurSizeToEmbeddedViewSize();
  890. // To avoid strange overpainting problems when the UI is first opened, we'll
  891. // repaint it a few times during the first second that it's on-screen..
  892. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  893. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  894. }
  895. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  896. EventRef event)
  897. {
  898. switch (GetEventKind (event))
  899. {
  900. case kEventWindowHandleDeactivate:
  901. ActivateWindow (wrapperWindow, TRUE);
  902. break;
  903. case kEventWindowGetClickActivation:
  904. {
  905. getTopLevelComponent()->toFront (false);
  906. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  907. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  908. sizeof (ClickActivationResult), &howToHandleClick);
  909. HIViewSetNeedsDisplay (embeddedView, true);
  910. }
  911. break;
  912. }
  913. return noErr;
  914. }
  915. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  916. EventRef event, void* userData)
  917. {
  918. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  919. }
  920. protected:
  921. WindowRef wrapperWindow;
  922. HIViewRef embeddedView;
  923. bool recursiveResize;
  924. Time creationTime;
  925. EventHandlerRef eventHandlerRef;
  926. };
  927. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  928. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  929. END_JUCE_NAMESPACE
  930. #endif
  931. #define JUCE_AMALGAMATED_TEMPLATE 1
  932. //==============================================================================
  933. #if JUCE_BUILD_CORE
  934. /*** Start of inlined file: juce_FileLogger.cpp ***/
  935. BEGIN_JUCE_NAMESPACE
  936. FileLogger::FileLogger (const File& logFile_,
  937. const String& welcomeMessage,
  938. const int maxInitialFileSizeBytes)
  939. : logFile (logFile_)
  940. {
  941. if (maxInitialFileSizeBytes >= 0)
  942. trimFileSize (maxInitialFileSizeBytes);
  943. if (! logFile_.exists())
  944. {
  945. // do this so that the parent directories get created..
  946. logFile_.create();
  947. }
  948. logStream = logFile_.createOutputStream (256);
  949. jassert (logStream != 0);
  950. String welcome;
  951. welcome << "\r\n**********************************************************\r\n"
  952. << welcomeMessage
  953. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  954. << "\r\n";
  955. logMessage (welcome);
  956. }
  957. FileLogger::~FileLogger()
  958. {
  959. }
  960. void FileLogger::logMessage (const String& message)
  961. {
  962. if (logStream != 0)
  963. {
  964. DBG (message);
  965. const ScopedLock sl (logLock);
  966. (*logStream) << message << "\r\n";
  967. logStream->flush();
  968. }
  969. }
  970. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  971. {
  972. if (maxFileSizeBytes <= 0)
  973. {
  974. logFile.deleteFile();
  975. }
  976. else
  977. {
  978. const int64 fileSize = logFile.getSize();
  979. if (fileSize > maxFileSizeBytes)
  980. {
  981. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  982. jassert (in != 0);
  983. if (in != 0)
  984. {
  985. in->setPosition (fileSize - maxFileSizeBytes);
  986. String content;
  987. {
  988. MemoryBlock contentToSave;
  989. contentToSave.setSize (maxFileSizeBytes + 4);
  990. contentToSave.fillWith (0);
  991. in->read (contentToSave.getData(), maxFileSizeBytes);
  992. in = 0;
  993. content = contentToSave.toString();
  994. }
  995. int newStart = 0;
  996. while (newStart < fileSize
  997. && content[newStart] != '\n'
  998. && content[newStart] != '\r')
  999. ++newStart;
  1000. logFile.deleteFile();
  1001. logFile.appendText (content.substring (newStart), false, false);
  1002. }
  1003. }
  1004. }
  1005. }
  1006. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1007. const String& logFileName,
  1008. const String& welcomeMessage,
  1009. const int maxInitialFileSizeBytes)
  1010. {
  1011. #if JUCE_MAC
  1012. File logFile ("~/Library/Logs");
  1013. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1014. .getChildFile (logFileName);
  1015. #else
  1016. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1017. if (logFile.isDirectory())
  1018. {
  1019. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1020. .getChildFile (logFileName);
  1021. }
  1022. #endif
  1023. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1024. }
  1025. END_JUCE_NAMESPACE
  1026. /*** End of inlined file: juce_FileLogger.cpp ***/
  1027. /*** Start of inlined file: juce_Logger.cpp ***/
  1028. BEGIN_JUCE_NAMESPACE
  1029. Logger::Logger()
  1030. {
  1031. }
  1032. Logger::~Logger()
  1033. {
  1034. }
  1035. static Logger* currentLogger = 0;
  1036. void Logger::setCurrentLogger (Logger* const newLogger,
  1037. const bool deleteOldLogger)
  1038. {
  1039. Logger* const oldLogger = currentLogger;
  1040. currentLogger = newLogger;
  1041. if (deleteOldLogger)
  1042. delete oldLogger;
  1043. }
  1044. void Logger::writeToLog (const String& message)
  1045. {
  1046. if (currentLogger != 0)
  1047. currentLogger->logMessage (message);
  1048. else
  1049. outputDebugString (message);
  1050. }
  1051. #if JUCE_LOG_ASSERTIONS
  1052. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1053. {
  1054. String m ("JUCE Assertion failure in ");
  1055. m << filename << ", line " << lineNum;
  1056. Logger::writeToLog (m);
  1057. }
  1058. #endif
  1059. END_JUCE_NAMESPACE
  1060. /*** End of inlined file: juce_Logger.cpp ***/
  1061. /*** Start of inlined file: juce_Random.cpp ***/
  1062. BEGIN_JUCE_NAMESPACE
  1063. Random::Random (const int64 seedValue) throw()
  1064. : seed (seedValue)
  1065. {
  1066. }
  1067. Random::~Random() throw()
  1068. {
  1069. }
  1070. void Random::setSeed (const int64 newSeed) throw()
  1071. {
  1072. seed = newSeed;
  1073. }
  1074. void Random::combineSeed (const int64 seedValue) throw()
  1075. {
  1076. seed ^= nextInt64() ^ seedValue;
  1077. }
  1078. void Random::setSeedRandomly()
  1079. {
  1080. combineSeed ((int64) (pointer_sized_int) this);
  1081. combineSeed (Time::getMillisecondCounter());
  1082. combineSeed (Time::getHighResolutionTicks());
  1083. combineSeed (Time::getHighResolutionTicksPerSecond());
  1084. combineSeed (Time::currentTimeMillis());
  1085. }
  1086. int Random::nextInt() throw()
  1087. {
  1088. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1089. return (int) (seed >> 16);
  1090. }
  1091. int Random::nextInt (const int maxValue) throw()
  1092. {
  1093. jassert (maxValue > 0);
  1094. return (nextInt() & 0x7fffffff) % maxValue;
  1095. }
  1096. int64 Random::nextInt64() throw()
  1097. {
  1098. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1099. }
  1100. bool Random::nextBool() throw()
  1101. {
  1102. return (nextInt() & 0x80000000) != 0;
  1103. }
  1104. float Random::nextFloat() throw()
  1105. {
  1106. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1107. }
  1108. double Random::nextDouble() throw()
  1109. {
  1110. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1111. }
  1112. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1113. {
  1114. BigInteger n;
  1115. do
  1116. {
  1117. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1118. }
  1119. while (n >= maximumValue);
  1120. return n;
  1121. }
  1122. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1123. {
  1124. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1125. while ((startBit & 31) != 0 && numBits > 0)
  1126. {
  1127. arrayToChange.setBit (startBit++, nextBool());
  1128. --numBits;
  1129. }
  1130. while (numBits >= 32)
  1131. {
  1132. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1133. startBit += 32;
  1134. numBits -= 32;
  1135. }
  1136. while (--numBits >= 0)
  1137. arrayToChange.setBit (startBit + numBits, nextBool());
  1138. }
  1139. Random& Random::getSystemRandom() throw()
  1140. {
  1141. static Random sysRand (1);
  1142. return sysRand;
  1143. }
  1144. END_JUCE_NAMESPACE
  1145. /*** End of inlined file: juce_Random.cpp ***/
  1146. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1147. BEGIN_JUCE_NAMESPACE
  1148. RelativeTime::RelativeTime (const double seconds_) throw()
  1149. : seconds (seconds_)
  1150. {
  1151. }
  1152. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1153. : seconds (other.seconds)
  1154. {
  1155. }
  1156. RelativeTime::~RelativeTime() throw()
  1157. {
  1158. }
  1159. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1160. {
  1161. return RelativeTime (milliseconds * 0.001);
  1162. }
  1163. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1164. {
  1165. return RelativeTime (milliseconds * 0.001);
  1166. }
  1167. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1168. {
  1169. return RelativeTime (numberOfMinutes * 60.0);
  1170. }
  1171. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1172. {
  1173. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1174. }
  1175. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1176. {
  1177. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1178. }
  1179. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1180. {
  1181. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1182. }
  1183. int64 RelativeTime::inMilliseconds() const throw()
  1184. {
  1185. return (int64)(seconds * 1000.0);
  1186. }
  1187. double RelativeTime::inMinutes() const throw()
  1188. {
  1189. return seconds / 60.0;
  1190. }
  1191. double RelativeTime::inHours() const throw()
  1192. {
  1193. return seconds / (60.0 * 60.0);
  1194. }
  1195. double RelativeTime::inDays() const throw()
  1196. {
  1197. return seconds / (60.0 * 60.0 * 24.0);
  1198. }
  1199. double RelativeTime::inWeeks() const throw()
  1200. {
  1201. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1202. }
  1203. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1204. {
  1205. if (seconds < 0.001 && seconds > -0.001)
  1206. return returnValueForZeroTime;
  1207. String result;
  1208. if (seconds < 0)
  1209. result = "-";
  1210. int fieldsShown = 0;
  1211. int n = abs ((int) inWeeks());
  1212. if (n > 0)
  1213. {
  1214. result << n << ((n == 1) ? TRANS(" week ")
  1215. : TRANS(" weeks "));
  1216. ++fieldsShown;
  1217. }
  1218. n = abs ((int) inDays()) % 7;
  1219. if (n > 0)
  1220. {
  1221. result << n << ((n == 1) ? TRANS(" day ")
  1222. : TRANS(" days "));
  1223. ++fieldsShown;
  1224. }
  1225. if (fieldsShown < 2)
  1226. {
  1227. n = abs ((int) inHours()) % 24;
  1228. if (n > 0)
  1229. {
  1230. result << n << ((n == 1) ? TRANS(" hr ")
  1231. : TRANS(" hrs "));
  1232. ++fieldsShown;
  1233. }
  1234. if (fieldsShown < 2)
  1235. {
  1236. n = abs ((int) inMinutes()) % 60;
  1237. if (n > 0)
  1238. {
  1239. result << n << ((n == 1) ? TRANS(" min ")
  1240. : TRANS(" mins "));
  1241. ++fieldsShown;
  1242. }
  1243. if (fieldsShown < 2)
  1244. {
  1245. n = abs ((int) inSeconds()) % 60;
  1246. if (n > 0)
  1247. {
  1248. result << n << ((n == 1) ? TRANS(" sec ")
  1249. : TRANS(" secs "));
  1250. ++fieldsShown;
  1251. }
  1252. if (fieldsShown < 1)
  1253. {
  1254. n = abs ((int) inMilliseconds()) % 1000;
  1255. if (n > 0)
  1256. {
  1257. result << n << TRANS(" ms");
  1258. ++fieldsShown;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. }
  1264. return result.trimEnd();
  1265. }
  1266. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1267. {
  1268. seconds = other.seconds;
  1269. return *this;
  1270. }
  1271. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1272. {
  1273. return seconds == other.seconds;
  1274. }
  1275. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1276. {
  1277. return seconds != other.seconds;
  1278. }
  1279. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1280. {
  1281. return seconds > other.seconds;
  1282. }
  1283. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1284. {
  1285. return seconds < other.seconds;
  1286. }
  1287. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1288. {
  1289. return seconds >= other.seconds;
  1290. }
  1291. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1292. {
  1293. return seconds <= other.seconds;
  1294. }
  1295. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1296. {
  1297. return RelativeTime (seconds + timeToAdd.seconds);
  1298. }
  1299. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1300. {
  1301. return RelativeTime (seconds - timeToSubtract.seconds);
  1302. }
  1303. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1304. {
  1305. return RelativeTime (seconds + secondsToAdd);
  1306. }
  1307. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1308. {
  1309. return RelativeTime (seconds - secondsToSubtract);
  1310. }
  1311. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1312. {
  1313. seconds += timeToAdd.seconds;
  1314. return *this;
  1315. }
  1316. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1317. {
  1318. seconds -= timeToSubtract.seconds;
  1319. return *this;
  1320. }
  1321. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1322. {
  1323. seconds += secondsToAdd;
  1324. return *this;
  1325. }
  1326. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1327. {
  1328. seconds -= secondsToSubtract;
  1329. return *this;
  1330. }
  1331. END_JUCE_NAMESPACE
  1332. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1333. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1334. BEGIN_JUCE_NAMESPACE
  1335. const String SystemStats::getJUCEVersion()
  1336. {
  1337. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1338. + "." + String (JUCE_MINOR_VERSION)
  1339. + "." + String (JUCE_BUILDNUMBER);
  1340. }
  1341. const StringArray SystemStats::getMACAddressStrings()
  1342. {
  1343. int64 macAddresses [16];
  1344. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1345. StringArray s;
  1346. for (int i = 0; i < numAddresses; ++i)
  1347. {
  1348. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1349. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1350. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1351. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1352. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1353. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1354. }
  1355. return s;
  1356. }
  1357. static bool juceInitialisedNonGUI = false;
  1358. #if JUCE_DEBUG
  1359. template <typename Type>
  1360. static void juce_testAtomicType (Type)
  1361. {
  1362. Atomic<Type> a, b;
  1363. a.set ((Type) 10);
  1364. a += (Type) 15;
  1365. a.memoryBarrier();
  1366. a -= (Type) 5;
  1367. ++a;
  1368. ++a;
  1369. --a;
  1370. a.memoryBarrier();
  1371. /* These are some simple test cases to check the atomics - let me know
  1372. if any of these assertions fail on your system!
  1373. */
  1374. jassert (a.get() == (Type) 21);
  1375. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1376. jassert (a.get() == (Type) 21);
  1377. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1378. jassert (a.get() == (Type) 101);
  1379. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1380. jassert (a.get() == (Type) 101);
  1381. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1382. jassert (a.get() == (Type) 200);
  1383. jassert (a.exchange ((Type) 300) == (Type) 200);
  1384. jassert (a.get() == (Type) 300);
  1385. b = a;
  1386. jassert (b.get() == a.get());
  1387. }
  1388. static void juce_testAtomics()
  1389. {
  1390. juce_testAtomicType ((int) 0);
  1391. juce_testAtomicType ((unsigned int) 0);
  1392. juce_testAtomicType ((int32) 0);
  1393. juce_testAtomicType ((uint32) 0);
  1394. juce_testAtomicType ((long) 0);
  1395. juce_testAtomicType ((void*) 0);
  1396. juce_testAtomicType ((int*) 0);
  1397. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1398. juce_testAtomicType ((int64) 0);
  1399. juce_testAtomicType ((uint64) 0);
  1400. #endif
  1401. }
  1402. #endif
  1403. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1404. {
  1405. if (! juceInitialisedNonGUI)
  1406. {
  1407. #if JUCE_MAC || JUCE_IPHONE
  1408. const ScopedAutoReleasePool pool;
  1409. #endif
  1410. #if JUCE_DEBUG
  1411. {
  1412. // Some simple test code to keep an eye on things and make sure these functions
  1413. // work ok on all platforms. Let me know if any of these assertions fail!
  1414. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1415. static_jassert (sizeof (int8) == 1);
  1416. static_jassert (sizeof (uint8) == 1);
  1417. static_jassert (sizeof (int16) == 2);
  1418. static_jassert (sizeof (uint16) == 2);
  1419. static_jassert (sizeof (int32) == 4);
  1420. static_jassert (sizeof (uint32) == 4);
  1421. static_jassert (sizeof (int64) == 8);
  1422. static_jassert (sizeof (uint64) == 8);
  1423. char a1[7];
  1424. jassert (numElementsInArray(a1) == 7);
  1425. int a2[3];
  1426. jassert (numElementsInArray(a2) == 3);
  1427. juce_testAtomics();
  1428. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1429. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1430. // Some quick stream tests..
  1431. int randomInt = Random::getSystemRandom().nextInt();
  1432. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1433. double randomDouble = Random::getSystemRandom().nextDouble();
  1434. String randomString;
  1435. for (int i = 50; --i >= 0;)
  1436. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1437. MemoryOutputStream mo;
  1438. mo.writeInt (randomInt);
  1439. mo.writeIntBigEndian (randomInt);
  1440. mo.writeCompressedInt (randomInt);
  1441. mo.writeString (randomString);
  1442. mo.writeInt64 (randomInt64);
  1443. mo.writeInt64BigEndian (randomInt64);
  1444. mo.writeDouble (randomDouble);
  1445. mo.writeDoubleBigEndian (randomDouble);
  1446. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1447. jassert (mi.readInt() == randomInt);
  1448. jassert (mi.readIntBigEndian() == randomInt);
  1449. jassert (mi.readCompressedInt() == randomInt);
  1450. jassert (mi.readString() == randomString);
  1451. jassert (mi.readInt64() == randomInt64);
  1452. jassert (mi.readInt64BigEndian() == randomInt64);
  1453. jassert (mi.readDouble() == randomDouble);
  1454. jassert (mi.readDoubleBigEndian() == randomDouble);
  1455. }
  1456. #endif
  1457. // Now the real initialisation..
  1458. juceInitialisedNonGUI = true;
  1459. DBG (SystemStats::getJUCEVersion());
  1460. SystemStats::initialiseStats();
  1461. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1462. }
  1463. }
  1464. #if JUCE_WINDOWS
  1465. // This is imported from the sockets code..
  1466. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  1467. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  1468. #endif
  1469. #if JUCE_DEBUG
  1470. extern void juce_CheckForDanglingStreams();
  1471. #endif
  1472. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1473. {
  1474. if (juceInitialisedNonGUI)
  1475. {
  1476. #if JUCE_MAC || JUCE_IPHONE
  1477. const ScopedAutoReleasePool pool;
  1478. #endif
  1479. #if JUCE_WINDOWS
  1480. // need to shut down sockets if they were used..
  1481. if (juce_CloseWin32SocketLib != 0)
  1482. (*juce_CloseWin32SocketLib)();
  1483. #endif
  1484. LocalisedStrings::setCurrentMappings (0);
  1485. Thread::stopAllThreads (3000);
  1486. #if JUCE_DEBUG
  1487. juce_CheckForDanglingStreams();
  1488. #endif
  1489. juceInitialisedNonGUI = false;
  1490. }
  1491. }
  1492. #ifdef JUCE_DLL
  1493. void* juce_Malloc (const int size)
  1494. {
  1495. return malloc (size);
  1496. }
  1497. void* juce_Calloc (const int size)
  1498. {
  1499. return calloc (1, size);
  1500. }
  1501. void* juce_Realloc (void* const block, const int size)
  1502. {
  1503. return realloc (block, size);
  1504. }
  1505. void juce_Free (void* const block)
  1506. {
  1507. free (block);
  1508. }
  1509. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1510. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1511. {
  1512. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1513. }
  1514. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1515. {
  1516. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1517. }
  1518. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1519. {
  1520. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1521. }
  1522. void juce_DebugFree (void* const block)
  1523. {
  1524. _free_dbg (block, _NORMAL_BLOCK);
  1525. }
  1526. #endif
  1527. #endif
  1528. END_JUCE_NAMESPACE
  1529. /*** End of inlined file: juce_SystemStats.cpp ***/
  1530. /*** Start of inlined file: juce_Time.cpp ***/
  1531. #if JUCE_MSVC
  1532. #pragma warning (push)
  1533. #pragma warning (disable: 4514)
  1534. #endif
  1535. #ifndef JUCE_WINDOWS
  1536. #include <sys/time.h>
  1537. #else
  1538. #include <ctime>
  1539. #endif
  1540. #include <sys/timeb.h>
  1541. #if JUCE_MSVC
  1542. #pragma warning (pop)
  1543. #ifdef _INC_TIME_INL
  1544. #define USE_NEW_SECURE_TIME_FNS
  1545. #endif
  1546. #endif
  1547. BEGIN_JUCE_NAMESPACE
  1548. namespace TimeHelpers
  1549. {
  1550. static struct tm millisToLocal (const int64 millis) throw()
  1551. {
  1552. struct tm result;
  1553. const int64 seconds = millis / 1000;
  1554. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1555. {
  1556. // use extended maths for dates beyond 1970 to 2037..
  1557. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1558. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1559. const int days = (int) (jdm / literal64bit (86400));
  1560. const int a = 32044 + days;
  1561. const int b = (4 * a + 3) / 146097;
  1562. const int c = a - (b * 146097) / 4;
  1563. const int d = (4 * c + 3) / 1461;
  1564. const int e = c - (d * 1461) / 4;
  1565. const int m = (5 * e + 2) / 153;
  1566. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1567. result.tm_mon = m + 2 - 12 * (m / 10);
  1568. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1569. result.tm_wday = (days + 1) % 7;
  1570. result.tm_yday = -1;
  1571. int t = (int) (jdm % literal64bit (86400));
  1572. result.tm_hour = t / 3600;
  1573. t %= 3600;
  1574. result.tm_min = t / 60;
  1575. result.tm_sec = t % 60;
  1576. result.tm_isdst = -1;
  1577. }
  1578. else
  1579. {
  1580. time_t now = static_cast <time_t> (seconds);
  1581. #if JUCE_WINDOWS
  1582. #ifdef USE_NEW_SECURE_TIME_FNS
  1583. if (now >= 0 && now <= 0x793406fff)
  1584. localtime_s (&result, &now);
  1585. else
  1586. zeromem (&result, sizeof (result));
  1587. #else
  1588. result = *localtime (&now);
  1589. #endif
  1590. #else
  1591. // more thread-safe
  1592. localtime_r (&now, &result);
  1593. #endif
  1594. }
  1595. return result;
  1596. }
  1597. static int extendedModulo (const int64 value, const int modulo) throw()
  1598. {
  1599. return (int) (value >= 0 ? (value % modulo)
  1600. : (value - ((value / modulo) + 1) * modulo));
  1601. }
  1602. static uint32 lastMSCounterValue = 0;
  1603. }
  1604. Time::Time() throw()
  1605. : millisSinceEpoch (0)
  1606. {
  1607. }
  1608. Time::Time (const Time& other) throw()
  1609. : millisSinceEpoch (other.millisSinceEpoch)
  1610. {
  1611. }
  1612. Time::Time (const int64 ms) throw()
  1613. : millisSinceEpoch (ms)
  1614. {
  1615. }
  1616. Time::Time (const int year,
  1617. const int month,
  1618. const int day,
  1619. const int hours,
  1620. const int minutes,
  1621. const int seconds,
  1622. const int milliseconds,
  1623. const bool useLocalTime) throw()
  1624. {
  1625. jassert (year > 100); // year must be a 4-digit version
  1626. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1627. {
  1628. // use extended maths for dates beyond 1970 to 2037..
  1629. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1630. : 0;
  1631. const int a = (13 - month) / 12;
  1632. const int y = year + 4800 - a;
  1633. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1634. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1635. - 32045;
  1636. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1637. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1638. + milliseconds;
  1639. }
  1640. else
  1641. {
  1642. struct tm t;
  1643. t.tm_year = year - 1900;
  1644. t.tm_mon = month;
  1645. t.tm_mday = day;
  1646. t.tm_hour = hours;
  1647. t.tm_min = minutes;
  1648. t.tm_sec = seconds;
  1649. t.tm_isdst = -1;
  1650. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1651. if (millisSinceEpoch < 0)
  1652. millisSinceEpoch = 0;
  1653. else
  1654. millisSinceEpoch += milliseconds;
  1655. }
  1656. }
  1657. Time::~Time() throw()
  1658. {
  1659. }
  1660. Time& Time::operator= (const Time& other) throw()
  1661. {
  1662. millisSinceEpoch = other.millisSinceEpoch;
  1663. return *this;
  1664. }
  1665. int64 Time::currentTimeMillis() throw()
  1666. {
  1667. static uint32 lastCounterResult = 0xffffffff;
  1668. static int64 correction = 0;
  1669. const uint32 now = getMillisecondCounter();
  1670. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1671. if (now < lastCounterResult)
  1672. {
  1673. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1674. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1675. {
  1676. // get the time once using normal library calls, and store the difference needed to
  1677. // turn the millisecond counter into a real time.
  1678. #if JUCE_WINDOWS
  1679. struct _timeb t;
  1680. #ifdef USE_NEW_SECURE_TIME_FNS
  1681. _ftime_s (&t);
  1682. #else
  1683. _ftime (&t);
  1684. #endif
  1685. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1686. #else
  1687. struct timeval tv;
  1688. struct timezone tz;
  1689. gettimeofday (&tv, &tz);
  1690. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1691. #endif
  1692. }
  1693. }
  1694. lastCounterResult = now;
  1695. return correction + now;
  1696. }
  1697. uint32 juce_millisecondsSinceStartup() throw();
  1698. uint32 Time::getMillisecondCounter() throw()
  1699. {
  1700. const uint32 now = juce_millisecondsSinceStartup();
  1701. if (now < TimeHelpers::lastMSCounterValue)
  1702. {
  1703. // in multi-threaded apps this might be called concurrently, so
  1704. // make sure that our last counter value only increases and doesn't
  1705. // go backwards..
  1706. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1707. TimeHelpers::lastMSCounterValue = now;
  1708. }
  1709. else
  1710. {
  1711. TimeHelpers::lastMSCounterValue = now;
  1712. }
  1713. return now;
  1714. }
  1715. uint32 Time::getApproximateMillisecondCounter() throw()
  1716. {
  1717. jassert (TimeHelpers::lastMSCounterValue != 0);
  1718. return TimeHelpers::lastMSCounterValue;
  1719. }
  1720. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1721. {
  1722. for (;;)
  1723. {
  1724. const uint32 now = getMillisecondCounter();
  1725. if (now >= targetTime)
  1726. break;
  1727. const int toWait = targetTime - now;
  1728. if (toWait > 2)
  1729. {
  1730. Thread::sleep (jmin (20, toWait >> 1));
  1731. }
  1732. else
  1733. {
  1734. // xxx should consider using mutex_pause on the mac as it apparently
  1735. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1736. for (int i = 10; --i >= 0;)
  1737. Thread::yield();
  1738. }
  1739. }
  1740. }
  1741. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1742. {
  1743. return ticks / (double) getHighResolutionTicksPerSecond();
  1744. }
  1745. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1746. {
  1747. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1748. }
  1749. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1750. {
  1751. return Time (currentTimeMillis());
  1752. }
  1753. const String Time::toString (const bool includeDate,
  1754. const bool includeTime,
  1755. const bool includeSeconds,
  1756. const bool use24HourClock) const throw()
  1757. {
  1758. String result;
  1759. if (includeDate)
  1760. {
  1761. result << getDayOfMonth() << ' '
  1762. << getMonthName (true) << ' '
  1763. << getYear();
  1764. if (includeTime)
  1765. result << ' ';
  1766. }
  1767. if (includeTime)
  1768. {
  1769. const int mins = getMinutes();
  1770. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1771. << (mins < 10 ? ":0" : ":") << mins;
  1772. if (includeSeconds)
  1773. {
  1774. const int secs = getSeconds();
  1775. result << (secs < 10 ? ":0" : ":") << secs;
  1776. }
  1777. if (! use24HourClock)
  1778. result << (isAfternoon() ? "pm" : "am");
  1779. }
  1780. return result.trimEnd();
  1781. }
  1782. const String Time::formatted (const String& format) const throw()
  1783. {
  1784. String buffer;
  1785. int bufferSize = 128;
  1786. buffer.preallocateStorage (bufferSize);
  1787. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1788. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1789. {
  1790. bufferSize += 128;
  1791. buffer.preallocateStorage (bufferSize);
  1792. }
  1793. return buffer;
  1794. }
  1795. int Time::getYear() const throw()
  1796. {
  1797. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1798. }
  1799. int Time::getMonth() const throw()
  1800. {
  1801. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1802. }
  1803. int Time::getDayOfMonth() const throw()
  1804. {
  1805. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1806. }
  1807. int Time::getDayOfWeek() const throw()
  1808. {
  1809. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1810. }
  1811. int Time::getHours() const throw()
  1812. {
  1813. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1814. }
  1815. int Time::getHoursInAmPmFormat() const throw()
  1816. {
  1817. const int hours = getHours();
  1818. if (hours == 0)
  1819. return 12;
  1820. else if (hours <= 12)
  1821. return hours;
  1822. else
  1823. return hours - 12;
  1824. }
  1825. bool Time::isAfternoon() const throw()
  1826. {
  1827. return getHours() >= 12;
  1828. }
  1829. int Time::getMinutes() const throw()
  1830. {
  1831. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1832. }
  1833. int Time::getSeconds() const throw()
  1834. {
  1835. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1836. }
  1837. int Time::getMilliseconds() const throw()
  1838. {
  1839. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1840. }
  1841. bool Time::isDaylightSavingTime() const throw()
  1842. {
  1843. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1844. }
  1845. const String Time::getTimeZone() const throw()
  1846. {
  1847. String zone[2];
  1848. #if JUCE_WINDOWS
  1849. _tzset();
  1850. #ifdef USE_NEW_SECURE_TIME_FNS
  1851. {
  1852. char name [128];
  1853. size_t length;
  1854. for (int i = 0; i < 2; ++i)
  1855. {
  1856. zeromem (name, sizeof (name));
  1857. _get_tzname (&length, name, 127, i);
  1858. zone[i] = name;
  1859. }
  1860. }
  1861. #else
  1862. const char** const zonePtr = (const char**) _tzname;
  1863. zone[0] = zonePtr[0];
  1864. zone[1] = zonePtr[1];
  1865. #endif
  1866. #else
  1867. tzset();
  1868. const char** const zonePtr = (const char**) tzname;
  1869. zone[0] = zonePtr[0];
  1870. zone[1] = zonePtr[1];
  1871. #endif
  1872. if (isDaylightSavingTime())
  1873. {
  1874. zone[0] = zone[1];
  1875. if (zone[0].length() > 3
  1876. && zone[0].containsIgnoreCase ("daylight")
  1877. && zone[0].contains ("GMT"))
  1878. zone[0] = "BST";
  1879. }
  1880. return zone[0].substring (0, 3);
  1881. }
  1882. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1883. {
  1884. return getMonthName (getMonth(), threeLetterVersion);
  1885. }
  1886. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1887. {
  1888. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1889. }
  1890. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1891. {
  1892. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1893. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1894. monthNumber %= 12;
  1895. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1896. : longMonthNames [monthNumber]);
  1897. }
  1898. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1899. {
  1900. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1901. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1902. day %= 7;
  1903. return TRANS (threeLetterVersion ? shortDayNames [day]
  1904. : longDayNames [day]);
  1905. }
  1906. END_JUCE_NAMESPACE
  1907. /*** End of inlined file: juce_Time.cpp ***/
  1908. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1909. BEGIN_JUCE_NAMESPACE
  1910. BigInteger::BigInteger()
  1911. : numValues (4),
  1912. highestBit (-1),
  1913. negative (false)
  1914. {
  1915. values.calloc (numValues + 1);
  1916. }
  1917. BigInteger::BigInteger (const int value)
  1918. : numValues (4),
  1919. highestBit (31),
  1920. negative (value < 0)
  1921. {
  1922. values.calloc (numValues + 1);
  1923. values[0] = abs (value);
  1924. highestBit = getHighestBit();
  1925. }
  1926. BigInteger::BigInteger (int64 value)
  1927. : numValues (4),
  1928. highestBit (63),
  1929. negative (value < 0)
  1930. {
  1931. values.calloc (numValues + 1);
  1932. if (value < 0)
  1933. value = -value;
  1934. values[0] = (unsigned int) value;
  1935. values[1] = (unsigned int) (value >> 32);
  1936. highestBit = getHighestBit();
  1937. }
  1938. BigInteger::BigInteger (const unsigned int value)
  1939. : numValues (4),
  1940. highestBit (31),
  1941. negative (false)
  1942. {
  1943. values.calloc (numValues + 1);
  1944. values[0] = value;
  1945. highestBit = getHighestBit();
  1946. }
  1947. BigInteger::BigInteger (const BigInteger& other)
  1948. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1949. highestBit (other.getHighestBit()),
  1950. negative (other.negative)
  1951. {
  1952. values.malloc (numValues + 1);
  1953. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1954. }
  1955. BigInteger::~BigInteger()
  1956. {
  1957. }
  1958. void BigInteger::swapWith (BigInteger& other) throw()
  1959. {
  1960. values.swapWith (other.values);
  1961. swapVariables (numValues, other.numValues);
  1962. swapVariables (highestBit, other.highestBit);
  1963. swapVariables (negative, other.negative);
  1964. }
  1965. BigInteger& BigInteger::operator= (const BigInteger& other)
  1966. {
  1967. if (this != &other)
  1968. {
  1969. highestBit = other.getHighestBit();
  1970. numValues = jmax (4, (highestBit >> 5) + 1);
  1971. negative = other.negative;
  1972. values.malloc (numValues + 1);
  1973. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1974. }
  1975. return *this;
  1976. }
  1977. void BigInteger::ensureSize (const int numVals)
  1978. {
  1979. if (numVals + 2 >= numValues)
  1980. {
  1981. int oldSize = numValues;
  1982. numValues = ((numVals + 2) * 3) / 2;
  1983. values.realloc (numValues + 1);
  1984. while (oldSize < numValues)
  1985. values [oldSize++] = 0;
  1986. }
  1987. }
  1988. bool BigInteger::operator[] (const int bit) const throw()
  1989. {
  1990. return bit <= highestBit && bit >= 0
  1991. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1992. }
  1993. int BigInteger::toInteger() const throw()
  1994. {
  1995. const int n = (int) (values[0] & 0x7fffffff);
  1996. return negative ? -n : n;
  1997. }
  1998. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  1999. {
  2000. BigInteger r;
  2001. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2002. r.ensureSize (numBits >> 5);
  2003. r.highestBit = numBits;
  2004. int i = 0;
  2005. while (numBits > 0)
  2006. {
  2007. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2008. numBits -= 32;
  2009. startBit += 32;
  2010. }
  2011. r.highestBit = r.getHighestBit();
  2012. return r;
  2013. }
  2014. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2015. {
  2016. if (numBits > 32)
  2017. {
  2018. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2019. numBits = 32;
  2020. }
  2021. numBits = jmin (numBits, highestBit + 1 - startBit);
  2022. if (numBits <= 0)
  2023. return 0;
  2024. const int pos = startBit >> 5;
  2025. const int offset = startBit & 31;
  2026. const int endSpace = 32 - numBits;
  2027. uint32 n = ((uint32) values [pos]) >> offset;
  2028. if (offset > endSpace)
  2029. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2030. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2031. }
  2032. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2033. {
  2034. if (numBits > 32)
  2035. {
  2036. jassertfalse;
  2037. numBits = 32;
  2038. }
  2039. for (int i = 0; i < numBits; ++i)
  2040. {
  2041. setBit (startBit + i, (valueToSet & 1) != 0);
  2042. valueToSet >>= 1;
  2043. }
  2044. }
  2045. void BigInteger::clear()
  2046. {
  2047. if (numValues > 16)
  2048. {
  2049. numValues = 4;
  2050. values.calloc (numValues + 1);
  2051. }
  2052. else
  2053. {
  2054. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2055. }
  2056. highestBit = -1;
  2057. negative = false;
  2058. }
  2059. void BigInteger::setBit (const int bit)
  2060. {
  2061. if (bit >= 0)
  2062. {
  2063. if (bit > highestBit)
  2064. {
  2065. ensureSize (bit >> 5);
  2066. highestBit = bit;
  2067. }
  2068. values [bit >> 5] |= (1 << (bit & 31));
  2069. }
  2070. }
  2071. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2072. {
  2073. if (shouldBeSet)
  2074. setBit (bit);
  2075. else
  2076. clearBit (bit);
  2077. }
  2078. void BigInteger::clearBit (const int bit) throw()
  2079. {
  2080. if (bit >= 0 && bit <= highestBit)
  2081. values [bit >> 5] &= ~(1 << (bit & 31));
  2082. }
  2083. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2084. {
  2085. while (--numBits >= 0)
  2086. setBit (startBit++, shouldBeSet);
  2087. }
  2088. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2089. {
  2090. if (bit >= 0)
  2091. shiftBits (1, bit);
  2092. setBit (bit, shouldBeSet);
  2093. }
  2094. bool BigInteger::isZero() const throw()
  2095. {
  2096. return getHighestBit() < 0;
  2097. }
  2098. bool BigInteger::isOne() const throw()
  2099. {
  2100. return getHighestBit() == 0 && ! negative;
  2101. }
  2102. bool BigInteger::isNegative() const throw()
  2103. {
  2104. return negative && ! isZero();
  2105. }
  2106. void BigInteger::setNegative (const bool neg) throw()
  2107. {
  2108. negative = neg;
  2109. }
  2110. void BigInteger::negate() throw()
  2111. {
  2112. negative = (! negative) && ! isZero();
  2113. }
  2114. int BigInteger::countNumberOfSetBits() const throw()
  2115. {
  2116. int total = 0;
  2117. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2118. {
  2119. unsigned int n = values[i];
  2120. if (n == 0xffffffff)
  2121. {
  2122. total += 32;
  2123. }
  2124. else
  2125. {
  2126. while (n != 0)
  2127. {
  2128. total += (n & 1);
  2129. n >>= 1;
  2130. }
  2131. }
  2132. }
  2133. return total;
  2134. }
  2135. int BigInteger::getHighestBit() const throw()
  2136. {
  2137. for (int i = highestBit + 1; --i >= 0;)
  2138. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2139. return i;
  2140. return -1;
  2141. }
  2142. int BigInteger::findNextSetBit (int i) const throw()
  2143. {
  2144. for (; i <= highestBit; ++i)
  2145. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2146. return i;
  2147. return -1;
  2148. }
  2149. int BigInteger::findNextClearBit (int i) const throw()
  2150. {
  2151. for (; i <= highestBit; ++i)
  2152. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2153. break;
  2154. return i;
  2155. }
  2156. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2157. {
  2158. if (other.isNegative())
  2159. return operator-= (-other);
  2160. if (isNegative())
  2161. {
  2162. if (compareAbsolute (other) < 0)
  2163. {
  2164. BigInteger temp (*this);
  2165. temp.negate();
  2166. *this = other;
  2167. operator-= (temp);
  2168. }
  2169. else
  2170. {
  2171. negate();
  2172. operator-= (other);
  2173. negate();
  2174. }
  2175. }
  2176. else
  2177. {
  2178. if (other.highestBit > highestBit)
  2179. highestBit = other.highestBit;
  2180. ++highestBit;
  2181. const int numInts = (highestBit >> 5) + 1;
  2182. ensureSize (numInts);
  2183. int64 remainder = 0;
  2184. for (int i = 0; i <= numInts; ++i)
  2185. {
  2186. if (i < numValues)
  2187. remainder += values[i];
  2188. if (i < other.numValues)
  2189. remainder += other.values[i];
  2190. values[i] = (unsigned int) remainder;
  2191. remainder >>= 32;
  2192. }
  2193. jassert (remainder == 0);
  2194. highestBit = getHighestBit();
  2195. }
  2196. return *this;
  2197. }
  2198. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2199. {
  2200. if (other.isNegative())
  2201. return operator+= (-other);
  2202. if (! isNegative())
  2203. {
  2204. if (compareAbsolute (other) < 0)
  2205. {
  2206. BigInteger temp (other);
  2207. swapWith (temp);
  2208. operator-= (temp);
  2209. negate();
  2210. return *this;
  2211. }
  2212. }
  2213. else
  2214. {
  2215. negate();
  2216. operator+= (other);
  2217. negate();
  2218. return *this;
  2219. }
  2220. const int numInts = (highestBit >> 5) + 1;
  2221. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2222. int64 amountToSubtract = 0;
  2223. for (int i = 0; i <= numInts; ++i)
  2224. {
  2225. if (i <= maxOtherInts)
  2226. amountToSubtract += (int64) other.values[i];
  2227. if (values[i] >= amountToSubtract)
  2228. {
  2229. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2230. amountToSubtract = 0;
  2231. }
  2232. else
  2233. {
  2234. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2235. values[i] = (unsigned int) n;
  2236. amountToSubtract = 1;
  2237. }
  2238. }
  2239. return *this;
  2240. }
  2241. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2242. {
  2243. BigInteger total;
  2244. highestBit = getHighestBit();
  2245. const bool wasNegative = isNegative();
  2246. setNegative (false);
  2247. for (int i = 0; i <= highestBit; ++i)
  2248. {
  2249. if (operator[](i))
  2250. {
  2251. BigInteger n (other);
  2252. n.setNegative (false);
  2253. n <<= i;
  2254. total += n;
  2255. }
  2256. }
  2257. total.setNegative (wasNegative ^ other.isNegative());
  2258. swapWith (total);
  2259. return *this;
  2260. }
  2261. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2262. {
  2263. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2264. const int divHB = divisor.getHighestBit();
  2265. const int ourHB = getHighestBit();
  2266. if (divHB < 0 || ourHB < 0)
  2267. {
  2268. // division by zero
  2269. remainder.clear();
  2270. clear();
  2271. }
  2272. else
  2273. {
  2274. const bool wasNegative = isNegative();
  2275. swapWith (remainder);
  2276. remainder.setNegative (false);
  2277. clear();
  2278. BigInteger temp (divisor);
  2279. temp.setNegative (false);
  2280. int leftShift = ourHB - divHB;
  2281. temp <<= leftShift;
  2282. while (leftShift >= 0)
  2283. {
  2284. if (remainder.compareAbsolute (temp) >= 0)
  2285. {
  2286. remainder -= temp;
  2287. setBit (leftShift);
  2288. }
  2289. if (--leftShift >= 0)
  2290. temp >>= 1;
  2291. }
  2292. negative = wasNegative ^ divisor.isNegative();
  2293. remainder.setNegative (wasNegative);
  2294. }
  2295. }
  2296. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2297. {
  2298. BigInteger remainder;
  2299. divideBy (other, remainder);
  2300. return *this;
  2301. }
  2302. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2303. {
  2304. // this operation doesn't take into account negative values..
  2305. jassert (isNegative() == other.isNegative());
  2306. if (other.highestBit >= 0)
  2307. {
  2308. ensureSize (other.highestBit >> 5);
  2309. int n = (other.highestBit >> 5) + 1;
  2310. while (--n >= 0)
  2311. values[n] |= other.values[n];
  2312. if (other.highestBit > highestBit)
  2313. highestBit = other.highestBit;
  2314. highestBit = getHighestBit();
  2315. }
  2316. return *this;
  2317. }
  2318. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2319. {
  2320. // this operation doesn't take into account negative values..
  2321. jassert (isNegative() == other.isNegative());
  2322. int n = numValues;
  2323. while (n > other.numValues)
  2324. values[--n] = 0;
  2325. while (--n >= 0)
  2326. values[n] &= other.values[n];
  2327. if (other.highestBit < highestBit)
  2328. highestBit = other.highestBit;
  2329. highestBit = getHighestBit();
  2330. return *this;
  2331. }
  2332. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2333. {
  2334. // this operation will only work with the absolute values
  2335. jassert (isNegative() == other.isNegative());
  2336. if (other.highestBit >= 0)
  2337. {
  2338. ensureSize (other.highestBit >> 5);
  2339. int n = (other.highestBit >> 5) + 1;
  2340. while (--n >= 0)
  2341. values[n] ^= other.values[n];
  2342. if (other.highestBit > highestBit)
  2343. highestBit = other.highestBit;
  2344. highestBit = getHighestBit();
  2345. }
  2346. return *this;
  2347. }
  2348. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2349. {
  2350. BigInteger remainder;
  2351. divideBy (divisor, remainder);
  2352. swapWith (remainder);
  2353. return *this;
  2354. }
  2355. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2356. {
  2357. shiftBits (numBitsToShift, 0);
  2358. return *this;
  2359. }
  2360. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2361. {
  2362. return operator<<= (-numBitsToShift);
  2363. }
  2364. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2365. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2366. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2367. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2368. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2369. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2370. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2371. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2372. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2373. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2374. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2375. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2376. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2377. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2378. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2379. int BigInteger::compare (const BigInteger& other) const throw()
  2380. {
  2381. if (isNegative() == other.isNegative())
  2382. {
  2383. const int absComp = compareAbsolute (other);
  2384. return isNegative() ? -absComp : absComp;
  2385. }
  2386. else
  2387. {
  2388. return isNegative() ? -1 : 1;
  2389. }
  2390. }
  2391. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2392. {
  2393. const int h1 = getHighestBit();
  2394. const int h2 = other.getHighestBit();
  2395. if (h1 > h2)
  2396. return 1;
  2397. else if (h1 < h2)
  2398. return -1;
  2399. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2400. if (values[i] != other.values[i])
  2401. return (values[i] > other.values[i]) ? 1 : -1;
  2402. return 0;
  2403. }
  2404. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2405. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2406. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2407. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2408. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2409. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2410. void BigInteger::shiftBits (int bits, const int startBit)
  2411. {
  2412. if (highestBit < 0)
  2413. return;
  2414. if (startBit > 0)
  2415. {
  2416. if (bits < 0)
  2417. {
  2418. // right shift
  2419. for (int i = startBit; i <= highestBit; ++i)
  2420. setBit (i, operator[] (i - bits));
  2421. highestBit = getHighestBit();
  2422. }
  2423. else if (bits > 0)
  2424. {
  2425. // left shift
  2426. for (int i = highestBit + 1; --i >= startBit;)
  2427. setBit (i + bits, operator[] (i));
  2428. while (--bits >= 0)
  2429. clearBit (bits + startBit);
  2430. }
  2431. }
  2432. else
  2433. {
  2434. if (bits < 0)
  2435. {
  2436. // right shift
  2437. bits = -bits;
  2438. if (bits > highestBit)
  2439. {
  2440. clear();
  2441. }
  2442. else
  2443. {
  2444. const int wordsToMove = bits >> 5;
  2445. int top = 1 + (highestBit >> 5) - wordsToMove;
  2446. highestBit -= bits;
  2447. if (wordsToMove > 0)
  2448. {
  2449. int i;
  2450. for (i = 0; i < top; ++i)
  2451. values [i] = values [i + wordsToMove];
  2452. for (i = 0; i < wordsToMove; ++i)
  2453. values [top + i] = 0;
  2454. bits &= 31;
  2455. }
  2456. if (bits != 0)
  2457. {
  2458. const int invBits = 32 - bits;
  2459. --top;
  2460. for (int i = 0; i < top; ++i)
  2461. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2462. values[top] = (values[top] >> bits);
  2463. }
  2464. highestBit = getHighestBit();
  2465. }
  2466. }
  2467. else if (bits > 0)
  2468. {
  2469. // left shift
  2470. ensureSize (((highestBit + bits) >> 5) + 1);
  2471. const int wordsToMove = bits >> 5;
  2472. int top = 1 + (highestBit >> 5);
  2473. highestBit += bits;
  2474. if (wordsToMove > 0)
  2475. {
  2476. int i;
  2477. for (i = top; --i >= 0;)
  2478. values [i + wordsToMove] = values [i];
  2479. for (i = 0; i < wordsToMove; ++i)
  2480. values [i] = 0;
  2481. bits &= 31;
  2482. }
  2483. if (bits != 0)
  2484. {
  2485. const int invBits = 32 - bits;
  2486. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2487. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2488. values [wordsToMove] = values [wordsToMove] << bits;
  2489. }
  2490. highestBit = getHighestBit();
  2491. }
  2492. }
  2493. }
  2494. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2495. {
  2496. while (! m->isZero())
  2497. {
  2498. if (n->compareAbsolute (*m) > 0)
  2499. swapVariables (m, n);
  2500. *m -= *n;
  2501. }
  2502. return *n;
  2503. }
  2504. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2505. {
  2506. BigInteger m (*this);
  2507. while (! n.isZero())
  2508. {
  2509. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2510. return simpleGCD (&m, &n);
  2511. BigInteger temp1 (m), temp2;
  2512. temp1.divideBy (n, temp2);
  2513. m = n;
  2514. n = temp2;
  2515. }
  2516. return m;
  2517. }
  2518. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2519. {
  2520. BigInteger exp (exponent);
  2521. exp %= modulus;
  2522. BigInteger value (1);
  2523. swapWith (value);
  2524. value %= modulus;
  2525. while (! exp.isZero())
  2526. {
  2527. if (exp [0])
  2528. {
  2529. operator*= (value);
  2530. operator%= (modulus);
  2531. }
  2532. value *= value;
  2533. value %= modulus;
  2534. exp >>= 1;
  2535. }
  2536. }
  2537. void BigInteger::inverseModulo (const BigInteger& modulus)
  2538. {
  2539. if (modulus.isOne() || modulus.isNegative())
  2540. {
  2541. clear();
  2542. return;
  2543. }
  2544. if (isNegative() || compareAbsolute (modulus) >= 0)
  2545. operator%= (modulus);
  2546. if (isOne())
  2547. return;
  2548. if (! (*this)[0])
  2549. {
  2550. // not invertible
  2551. clear();
  2552. return;
  2553. }
  2554. BigInteger a1 (modulus);
  2555. BigInteger a2 (*this);
  2556. BigInteger b1 (modulus);
  2557. BigInteger b2 (1);
  2558. while (! a2.isOne())
  2559. {
  2560. BigInteger temp1, temp2, multiplier (a1);
  2561. multiplier.divideBy (a2, temp1);
  2562. temp1 = a2;
  2563. temp1 *= multiplier;
  2564. temp2 = a1;
  2565. temp2 -= temp1;
  2566. a1 = a2;
  2567. a2 = temp2;
  2568. temp1 = b2;
  2569. temp1 *= multiplier;
  2570. temp2 = b1;
  2571. temp2 -= temp1;
  2572. b1 = b2;
  2573. b2 = temp2;
  2574. }
  2575. while (b2.isNegative())
  2576. b2 += modulus;
  2577. b2 %= modulus;
  2578. swapWith (b2);
  2579. }
  2580. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2581. {
  2582. return stream << value.toString (10);
  2583. }
  2584. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2585. {
  2586. String s;
  2587. BigInteger v (*this);
  2588. if (base == 2 || base == 8 || base == 16)
  2589. {
  2590. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2591. static const char* const hexDigits = "0123456789abcdef";
  2592. for (;;)
  2593. {
  2594. const int remainder = v.getBitRangeAsInt (0, bits);
  2595. v >>= bits;
  2596. if (remainder == 0 && v.isZero())
  2597. break;
  2598. s = String::charToString (hexDigits [remainder]) + s;
  2599. }
  2600. }
  2601. else if (base == 10)
  2602. {
  2603. const BigInteger ten (10);
  2604. BigInteger remainder;
  2605. for (;;)
  2606. {
  2607. v.divideBy (ten, remainder);
  2608. if (remainder.isZero() && v.isZero())
  2609. break;
  2610. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2611. }
  2612. }
  2613. else
  2614. {
  2615. jassertfalse; // can't do the specified base!
  2616. return String::empty;
  2617. }
  2618. s = s.paddedLeft ('0', minimumNumCharacters);
  2619. return isNegative() ? "-" + s : s;
  2620. }
  2621. void BigInteger::parseString (const String& text, const int base)
  2622. {
  2623. clear();
  2624. const juce_wchar* t = text;
  2625. if (base == 2 || base == 8 || base == 16)
  2626. {
  2627. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2628. for (;;)
  2629. {
  2630. const juce_wchar c = *t++;
  2631. const int digit = CharacterFunctions::getHexDigitValue (c);
  2632. if (((unsigned int) digit) < (unsigned int) base)
  2633. {
  2634. operator<<= (bits);
  2635. operator+= (digit);
  2636. }
  2637. else if (c == 0)
  2638. {
  2639. break;
  2640. }
  2641. }
  2642. }
  2643. else if (base == 10)
  2644. {
  2645. const BigInteger ten ((unsigned int) 10);
  2646. for (;;)
  2647. {
  2648. const juce_wchar c = *t++;
  2649. if (c >= '0' && c <= '9')
  2650. {
  2651. operator*= (ten);
  2652. operator+= ((int) (c - '0'));
  2653. }
  2654. else if (c == 0)
  2655. {
  2656. break;
  2657. }
  2658. }
  2659. }
  2660. setNegative (text.trimStart().startsWithChar ('-'));
  2661. }
  2662. const MemoryBlock BigInteger::toMemoryBlock() const
  2663. {
  2664. const int numBytes = (getHighestBit() + 8) >> 3;
  2665. MemoryBlock mb ((size_t) numBytes);
  2666. for (int i = 0; i < numBytes; ++i)
  2667. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2668. return mb;
  2669. }
  2670. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2671. {
  2672. clear();
  2673. for (int i = (int) data.getSize(); --i >= 0;)
  2674. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2675. }
  2676. END_JUCE_NAMESPACE
  2677. /*** End of inlined file: juce_BigInteger.cpp ***/
  2678. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2679. BEGIN_JUCE_NAMESPACE
  2680. MemoryBlock::MemoryBlock() throw()
  2681. : size (0)
  2682. {
  2683. }
  2684. MemoryBlock::MemoryBlock (const size_t initialSize,
  2685. const bool initialiseToZero) throw()
  2686. {
  2687. if (initialSize > 0)
  2688. {
  2689. size = initialSize;
  2690. data.allocate (initialSize, initialiseToZero);
  2691. }
  2692. else
  2693. {
  2694. size = 0;
  2695. }
  2696. }
  2697. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2698. : size (other.size)
  2699. {
  2700. if (size > 0)
  2701. {
  2702. jassert (other.data != 0);
  2703. data.malloc (size);
  2704. memcpy (data, other.data, size);
  2705. }
  2706. }
  2707. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2708. const size_t sizeInBytes) throw()
  2709. : size (jmax ((size_t) 0, sizeInBytes))
  2710. {
  2711. jassert (sizeInBytes >= 0);
  2712. if (size > 0)
  2713. {
  2714. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2715. data.malloc (size);
  2716. if (dataToInitialiseFrom != 0)
  2717. memcpy (data, dataToInitialiseFrom, size);
  2718. }
  2719. }
  2720. MemoryBlock::~MemoryBlock() throw()
  2721. {
  2722. jassert (size >= 0); // should never happen
  2723. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2724. }
  2725. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2726. {
  2727. if (this != &other)
  2728. {
  2729. setSize (other.size, false);
  2730. memcpy (data, other.data, size);
  2731. }
  2732. return *this;
  2733. }
  2734. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2735. {
  2736. return matches (other.data, other.size);
  2737. }
  2738. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2739. {
  2740. return ! operator== (other);
  2741. }
  2742. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2743. {
  2744. return size == dataSize
  2745. && memcmp (data, dataToCompare, size) == 0;
  2746. }
  2747. // this will resize the block to this size
  2748. void MemoryBlock::setSize (const size_t newSize,
  2749. const bool initialiseToZero) throw()
  2750. {
  2751. if (size != newSize)
  2752. {
  2753. if (newSize <= 0)
  2754. {
  2755. data.free();
  2756. size = 0;
  2757. }
  2758. else
  2759. {
  2760. if (data != 0)
  2761. {
  2762. data.realloc (newSize);
  2763. if (initialiseToZero && (newSize > size))
  2764. zeromem (data + size, newSize - size);
  2765. }
  2766. else
  2767. {
  2768. data.allocate (newSize, initialiseToZero);
  2769. }
  2770. size = newSize;
  2771. }
  2772. }
  2773. }
  2774. void MemoryBlock::ensureSize (const size_t minimumSize,
  2775. const bool initialiseToZero) throw()
  2776. {
  2777. if (size < minimumSize)
  2778. setSize (minimumSize, initialiseToZero);
  2779. }
  2780. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2781. {
  2782. swapVariables (size, other.size);
  2783. data.swapWith (other.data);
  2784. }
  2785. void MemoryBlock::fillWith (const uint8 value) throw()
  2786. {
  2787. memset (data, (int) value, size);
  2788. }
  2789. void MemoryBlock::append (const void* const srcData,
  2790. const size_t numBytes) throw()
  2791. {
  2792. if (numBytes > 0)
  2793. {
  2794. const size_t oldSize = size;
  2795. setSize (size + numBytes);
  2796. memcpy (data + oldSize, srcData, numBytes);
  2797. }
  2798. }
  2799. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2800. {
  2801. const char* d = static_cast<const char*> (src);
  2802. if (offset < 0)
  2803. {
  2804. d -= offset;
  2805. num -= offset;
  2806. offset = 0;
  2807. }
  2808. if (offset + num > size)
  2809. num = size - offset;
  2810. if (num > 0)
  2811. memcpy (data + offset, d, num);
  2812. }
  2813. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2814. {
  2815. char* d = static_cast<char*> (dst);
  2816. if (offset < 0)
  2817. {
  2818. zeromem (d, -offset);
  2819. d -= offset;
  2820. num += offset;
  2821. offset = 0;
  2822. }
  2823. if (offset + num > size)
  2824. {
  2825. const size_t newNum = size - offset;
  2826. zeromem (d + newNum, num - newNum);
  2827. num = newNum;
  2828. }
  2829. if (num > 0)
  2830. memcpy (d, data + offset, num);
  2831. }
  2832. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove) throw()
  2833. {
  2834. if (startByte < 0)
  2835. {
  2836. numBytesToRemove += startByte;
  2837. startByte = 0;
  2838. }
  2839. if (startByte + numBytesToRemove >= size)
  2840. {
  2841. setSize (startByte);
  2842. }
  2843. else if (numBytesToRemove > 0)
  2844. {
  2845. memmove (data + startByte,
  2846. data + startByte + numBytesToRemove,
  2847. size - (startByte + numBytesToRemove));
  2848. setSize (size - numBytesToRemove);
  2849. }
  2850. }
  2851. const String MemoryBlock::toString() const throw()
  2852. {
  2853. return String (static_cast <const char*> (getData()), size);
  2854. }
  2855. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2856. {
  2857. int res = 0;
  2858. size_t byte = bitRangeStart >> 3;
  2859. int offsetInByte = (int) bitRangeStart & 7;
  2860. size_t bitsSoFar = 0;
  2861. while (numBits > 0 && (size_t) byte < size)
  2862. {
  2863. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2864. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2865. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2866. bitsSoFar += bitsThisTime;
  2867. numBits -= bitsThisTime;
  2868. ++byte;
  2869. offsetInByte = 0;
  2870. }
  2871. return res;
  2872. }
  2873. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2874. {
  2875. size_t byte = bitRangeStart >> 3;
  2876. int offsetInByte = (int) bitRangeStart & 7;
  2877. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2878. while (numBits > 0 && (size_t) byte < size)
  2879. {
  2880. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2881. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2882. const unsigned int tempBits = bitsToSet << offsetInByte;
  2883. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2884. ++byte;
  2885. numBits -= bitsThisTime;
  2886. bitsToSet >>= bitsThisTime;
  2887. mask >>= bitsThisTime;
  2888. offsetInByte = 0;
  2889. }
  2890. }
  2891. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2892. {
  2893. ensureSize (hex.length() >> 1);
  2894. char* dest = data;
  2895. int i = 0;
  2896. for (;;)
  2897. {
  2898. int byte = 0;
  2899. for (int loop = 2; --loop >= 0;)
  2900. {
  2901. byte <<= 4;
  2902. for (;;)
  2903. {
  2904. const juce_wchar c = hex [i++];
  2905. if (c >= '0' && c <= '9')
  2906. {
  2907. byte |= c - '0';
  2908. break;
  2909. }
  2910. else if (c >= 'a' && c <= 'z')
  2911. {
  2912. byte |= c - ('a' - 10);
  2913. break;
  2914. }
  2915. else if (c >= 'A' && c <= 'Z')
  2916. {
  2917. byte |= c - ('A' - 10);
  2918. break;
  2919. }
  2920. else if (c == 0)
  2921. {
  2922. setSize (static_cast <size_t> (dest - data));
  2923. return;
  2924. }
  2925. }
  2926. }
  2927. *dest++ = (char) byte;
  2928. }
  2929. }
  2930. static const char* const encodingTable
  2931. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2932. const String MemoryBlock::toBase64Encoding() const throw()
  2933. {
  2934. const size_t numChars = ((size << 3) + 5) / 6;
  2935. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  2936. const int initialLen = destString.length();
  2937. destString.preallocateStorage (initialLen + 2 + numChars);
  2938. juce_wchar* d = destString;
  2939. d += initialLen;
  2940. *d++ = '.';
  2941. for (size_t i = 0; i < numChars; ++i)
  2942. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2943. *d++ = 0;
  2944. return destString;
  2945. }
  2946. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2947. {
  2948. const int startPos = s.indexOfChar ('.') + 1;
  2949. if (startPos <= 0)
  2950. return false;
  2951. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2952. setSize (numBytesNeeded, true);
  2953. const int numChars = s.length() - startPos;
  2954. const juce_wchar* srcChars = s;
  2955. srcChars += startPos;
  2956. int pos = 0;
  2957. for (int i = 0; i < numChars; ++i)
  2958. {
  2959. const char c = (char) srcChars[i];
  2960. for (int j = 0; j < 64; ++j)
  2961. {
  2962. if (encodingTable[j] == c)
  2963. {
  2964. setBitRange (pos, 6, j);
  2965. pos += 6;
  2966. break;
  2967. }
  2968. }
  2969. }
  2970. return true;
  2971. }
  2972. END_JUCE_NAMESPACE
  2973. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  2974. /*** Start of inlined file: juce_PropertySet.cpp ***/
  2975. BEGIN_JUCE_NAMESPACE
  2976. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2977. : properties (ignoreCaseOfKeyNames),
  2978. fallbackProperties (0),
  2979. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2980. {
  2981. }
  2982. PropertySet::PropertySet (const PropertySet& other) throw()
  2983. : properties (other.properties),
  2984. fallbackProperties (other.fallbackProperties),
  2985. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2986. {
  2987. }
  2988. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2989. {
  2990. properties = other.properties;
  2991. fallbackProperties = other.fallbackProperties;
  2992. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2993. propertyChanged();
  2994. return *this;
  2995. }
  2996. PropertySet::~PropertySet()
  2997. {
  2998. }
  2999. void PropertySet::clear()
  3000. {
  3001. const ScopedLock sl (lock);
  3002. if (properties.size() > 0)
  3003. {
  3004. properties.clear();
  3005. propertyChanged();
  3006. }
  3007. }
  3008. const String PropertySet::getValue (const String& keyName,
  3009. const String& defaultValue) const throw()
  3010. {
  3011. const ScopedLock sl (lock);
  3012. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3013. if (index >= 0)
  3014. return properties.getAllValues() [index];
  3015. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3016. : defaultValue;
  3017. }
  3018. int PropertySet::getIntValue (const String& keyName,
  3019. const int defaultValue) const throw()
  3020. {
  3021. const ScopedLock sl (lock);
  3022. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3023. if (index >= 0)
  3024. return properties.getAllValues() [index].getIntValue();
  3025. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3026. : defaultValue;
  3027. }
  3028. double PropertySet::getDoubleValue (const String& keyName,
  3029. const double defaultValue) const throw()
  3030. {
  3031. const ScopedLock sl (lock);
  3032. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3033. if (index >= 0)
  3034. return properties.getAllValues()[index].getDoubleValue();
  3035. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3036. : defaultValue;
  3037. }
  3038. bool PropertySet::getBoolValue (const String& keyName,
  3039. const bool defaultValue) const throw()
  3040. {
  3041. const ScopedLock sl (lock);
  3042. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3043. if (index >= 0)
  3044. return properties.getAllValues() [index].getIntValue() != 0;
  3045. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3046. : defaultValue;
  3047. }
  3048. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3049. {
  3050. XmlDocument doc (getValue (keyName));
  3051. return doc.getDocumentElement();
  3052. }
  3053. void PropertySet::setValue (const String& keyName,
  3054. const String& value) throw()
  3055. {
  3056. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3057. if (keyName.isNotEmpty())
  3058. {
  3059. const ScopedLock sl (lock);
  3060. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3061. if (index < 0 || properties.getAllValues() [index] != value)
  3062. {
  3063. properties.set (keyName, value);
  3064. propertyChanged();
  3065. }
  3066. }
  3067. }
  3068. void PropertySet::removeValue (const String& keyName) throw()
  3069. {
  3070. if (keyName.isNotEmpty())
  3071. {
  3072. const ScopedLock sl (lock);
  3073. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3074. if (index >= 0)
  3075. {
  3076. properties.remove (keyName);
  3077. propertyChanged();
  3078. }
  3079. }
  3080. }
  3081. void PropertySet::setValue (const String& keyName, const int value) throw()
  3082. {
  3083. setValue (keyName, String (value));
  3084. }
  3085. void PropertySet::setValue (const String& keyName, const double value) throw()
  3086. {
  3087. setValue (keyName, String (value));
  3088. }
  3089. void PropertySet::setValue (const String& keyName, const bool value) throw()
  3090. {
  3091. setValue (keyName, String (value ? "1" : "0"));
  3092. }
  3093. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3094. {
  3095. setValue (keyName, (xml == 0) ? String::empty
  3096. : xml->createDocument (String::empty, true));
  3097. }
  3098. bool PropertySet::containsKey (const String& keyName) const throw()
  3099. {
  3100. const ScopedLock sl (lock);
  3101. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3102. }
  3103. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3104. {
  3105. const ScopedLock sl (lock);
  3106. fallbackProperties = fallbackProperties_;
  3107. }
  3108. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3109. {
  3110. const ScopedLock sl (lock);
  3111. XmlElement* const xml = new XmlElement (nodeName);
  3112. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3113. {
  3114. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3115. e->setAttribute ("name", properties.getAllKeys()[i]);
  3116. e->setAttribute ("val", properties.getAllValues()[i]);
  3117. }
  3118. return xml;
  3119. }
  3120. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3121. {
  3122. const ScopedLock sl (lock);
  3123. clear();
  3124. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3125. {
  3126. if (e->hasAttribute ("name")
  3127. && e->hasAttribute ("val"))
  3128. {
  3129. properties.set (e->getStringAttribute ("name"),
  3130. e->getStringAttribute ("val"));
  3131. }
  3132. }
  3133. if (properties.size() > 0)
  3134. propertyChanged();
  3135. }
  3136. void PropertySet::propertyChanged()
  3137. {
  3138. }
  3139. END_JUCE_NAMESPACE
  3140. /*** End of inlined file: juce_PropertySet.cpp ***/
  3141. /*** Start of inlined file: juce_Identifier.cpp ***/
  3142. BEGIN_JUCE_NAMESPACE
  3143. StringPool& Identifier::getPool()
  3144. {
  3145. static StringPool pool;
  3146. return pool;
  3147. }
  3148. Identifier::Identifier() throw()
  3149. : name (0)
  3150. {
  3151. }
  3152. Identifier::Identifier (const Identifier& other) throw()
  3153. : name (other.name)
  3154. {
  3155. }
  3156. Identifier& Identifier::operator= (const Identifier& other) throw()
  3157. {
  3158. name = other.name;
  3159. return *this;
  3160. }
  3161. Identifier::Identifier (const String& name_)
  3162. : name (Identifier::getPool().getPooledString (name_))
  3163. {
  3164. /* An Identifier string must be suitable for use as a script variable or XML
  3165. attribute, so it can only contain this limited set of characters.. */
  3166. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3167. }
  3168. Identifier::Identifier (const char* const name_)
  3169. : name (Identifier::getPool().getPooledString (name_))
  3170. {
  3171. /* An Identifier string must be suitable for use as a script variable or XML
  3172. attribute, so it can only contain this limited set of characters.. */
  3173. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3174. }
  3175. Identifier::~Identifier()
  3176. {
  3177. }
  3178. END_JUCE_NAMESPACE
  3179. /*** End of inlined file: juce_Identifier.cpp ***/
  3180. /*** Start of inlined file: juce_Variant.cpp ***/
  3181. BEGIN_JUCE_NAMESPACE
  3182. var::var() throw()
  3183. : type (voidType)
  3184. {
  3185. value.doubleValue = 0;
  3186. }
  3187. var::~var() throw()
  3188. {
  3189. if (type == stringType)
  3190. delete value.stringValue;
  3191. else if (type == objectType && value.objectValue != 0)
  3192. value.objectValue->decReferenceCount();
  3193. }
  3194. const var var::null;
  3195. var::var (const var& valueToCopy)
  3196. : type (valueToCopy.type),
  3197. value (valueToCopy.value)
  3198. {
  3199. if (type == stringType)
  3200. value.stringValue = new String (*(value.stringValue));
  3201. else if (type == objectType && value.objectValue != 0)
  3202. value.objectValue->incReferenceCount();
  3203. }
  3204. var::var (const int value_) throw()
  3205. : type (intType)
  3206. {
  3207. value.intValue = value_;
  3208. }
  3209. var::var (const bool value_) throw()
  3210. : type (boolType)
  3211. {
  3212. value.boolValue = value_;
  3213. }
  3214. var::var (const double value_) throw()
  3215. : type (doubleType)
  3216. {
  3217. value.doubleValue = value_;
  3218. }
  3219. var::var (const String& value_)
  3220. : type (stringType)
  3221. {
  3222. value.stringValue = new String (value_);
  3223. }
  3224. var::var (const char* const value_)
  3225. : type (stringType)
  3226. {
  3227. value.stringValue = new String (value_);
  3228. }
  3229. var::var (const juce_wchar* const value_)
  3230. : type (stringType)
  3231. {
  3232. value.stringValue = new String (value_);
  3233. }
  3234. var::var (DynamicObject* const object)
  3235. : type (objectType)
  3236. {
  3237. value.objectValue = object;
  3238. if (object != 0)
  3239. object->incReferenceCount();
  3240. }
  3241. var::var (MethodFunction method_) throw()
  3242. : type (methodType)
  3243. {
  3244. value.methodValue = method_;
  3245. }
  3246. void var::swapWith (var& other) throw()
  3247. {
  3248. swapVariables (type, other.type);
  3249. swapVariables (value, other.value);
  3250. }
  3251. var& var::operator= (const var& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3252. var& var::operator= (int value_) { var newValue (value_); swapWith (newValue); return *this; }
  3253. var& var::operator= (bool value_) { var newValue (value_); swapWith (newValue); return *this; }
  3254. var& var::operator= (double value_) { var newValue (value_); swapWith (newValue); return *this; }
  3255. var& var::operator= (const char* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3256. var& var::operator= (const juce_wchar* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3257. var& var::operator= (const String& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3258. var& var::operator= (DynamicObject* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3259. var& var::operator= (MethodFunction value_) { var newValue (value_); swapWith (newValue); return *this; }
  3260. var::operator int() const
  3261. {
  3262. switch (type)
  3263. {
  3264. case voidType: break;
  3265. case intType: return value.intValue;
  3266. case boolType: return value.boolValue ? 1 : 0;
  3267. case doubleType: return static_cast <int> (value.doubleValue);
  3268. case stringType: return value.stringValue->getIntValue();
  3269. case objectType: break;
  3270. default: jassertfalse; break;
  3271. }
  3272. return 0;
  3273. }
  3274. var::operator bool() const
  3275. {
  3276. switch (type)
  3277. {
  3278. case voidType: break;
  3279. case intType: return value.intValue != 0;
  3280. case boolType: return value.boolValue;
  3281. case doubleType: return value.doubleValue != 0;
  3282. case stringType: return value.stringValue->getIntValue() != 0
  3283. || value.stringValue->trim().equalsIgnoreCase ("true")
  3284. || value.stringValue->trim().equalsIgnoreCase ("yes");
  3285. case objectType: return value.objectValue != 0;
  3286. default: jassertfalse; break;
  3287. }
  3288. return false;
  3289. }
  3290. var::operator float() const
  3291. {
  3292. return (float) operator double();
  3293. }
  3294. var::operator double() const
  3295. {
  3296. switch (type)
  3297. {
  3298. case voidType: break;
  3299. case intType: return value.intValue;
  3300. case boolType: return value.boolValue ? 1.0 : 0.0;
  3301. case doubleType: return value.doubleValue;
  3302. case stringType: return value.stringValue->getDoubleValue();
  3303. case objectType: break;
  3304. default: jassertfalse; break;
  3305. }
  3306. return 0.0;
  3307. }
  3308. const String var::toString() const
  3309. {
  3310. switch (type)
  3311. {
  3312. case voidType: return String::empty;
  3313. case intType: return String (value.intValue);
  3314. case boolType: return String::charToString (value.boolValue ? '1' : '0');
  3315. case doubleType: return String (value.doubleValue);
  3316. case stringType: return *(value.stringValue);
  3317. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  3318. case methodType: return "Method";
  3319. default: jassertfalse; break;
  3320. }
  3321. return String::empty;
  3322. }
  3323. var::operator const String() const
  3324. {
  3325. return toString();
  3326. }
  3327. DynamicObject* var::getObject() const
  3328. {
  3329. return type == objectType ? value.objectValue : 0;
  3330. }
  3331. bool var::equals (const var& other) const throw()
  3332. {
  3333. switch (type)
  3334. {
  3335. case voidType: return other.isVoid();
  3336. case intType: return value.intValue == static_cast <int> (other);
  3337. case boolType: return value.boolValue == static_cast <bool> (other);
  3338. case doubleType: return value.doubleValue == static_cast <double> (other);
  3339. case stringType: return (*(value.stringValue)) == other.toString();
  3340. case objectType: return value.objectValue == other.getObject();
  3341. case methodType: return value.methodValue == other.value.methodValue && other.isMethod();
  3342. default: jassertfalse; break;
  3343. }
  3344. return false;
  3345. }
  3346. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3347. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3348. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3349. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3350. void var::writeToStream (OutputStream& output) const
  3351. {
  3352. switch (type)
  3353. {
  3354. case voidType: output.writeCompressedInt (0); break;
  3355. case intType: output.writeCompressedInt (5); output.writeByte (1); output.writeInt (value.intValue); break;
  3356. case boolType: output.writeCompressedInt (1); output.writeByte (value.boolValue ? 2 : 3); break;
  3357. case doubleType: output.writeCompressedInt (9); output.writeByte (4); output.writeDouble (value.doubleValue); break;
  3358. case stringType:
  3359. {
  3360. const int len = value.stringValue->getNumBytesAsUTF8() + 1;
  3361. output.writeCompressedInt (len + 1);
  3362. output.writeByte (5);
  3363. HeapBlock<char> temp (len);
  3364. value.stringValue->copyToUTF8 (temp, len);
  3365. output.write (temp, len);
  3366. break;
  3367. }
  3368. case objectType:
  3369. case methodType: output.writeCompressedInt (0); jassertfalse; break; // Can't write an object to a stream!
  3370. default: jassertfalse; break; // Is this a corrupted object?
  3371. }
  3372. }
  3373. const var var::readFromStream (InputStream& input)
  3374. {
  3375. const int numBytes = input.readCompressedInt();
  3376. if (numBytes > 0)
  3377. {
  3378. switch (input.readByte())
  3379. {
  3380. case 1: return var (input.readInt());
  3381. case 2: return var (true);
  3382. case 3: return var (false);
  3383. case 4: return var (input.readDouble());
  3384. case 5:
  3385. {
  3386. MemoryBlock mb;
  3387. input.readIntoMemoryBlock (mb, numBytes - 1);
  3388. return var (String::fromUTF8 (static_cast <const char*> (mb.getData()), (int) mb.getSize()));
  3389. }
  3390. default: input.skipNextBytes (numBytes - 1); break;
  3391. }
  3392. }
  3393. return var::null;
  3394. }
  3395. const var var::operator[] (const Identifier& propertyName) const
  3396. {
  3397. if (type == objectType && value.objectValue != 0)
  3398. return value.objectValue->getProperty (propertyName);
  3399. return var::null;
  3400. }
  3401. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3402. {
  3403. if (type == objectType && value.objectValue != 0)
  3404. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3405. return var::null;
  3406. }
  3407. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3408. {
  3409. if (isMethod())
  3410. {
  3411. DynamicObject* const target = targetObject.getObject();
  3412. if (target != 0)
  3413. return (target->*(value.methodValue)) (arguments, numArguments);
  3414. }
  3415. return var::null;
  3416. }
  3417. const var var::call (const Identifier& method) const
  3418. {
  3419. return invoke (method, 0, 0);
  3420. }
  3421. const var var::call (const Identifier& method, const var& arg1) const
  3422. {
  3423. return invoke (method, &arg1, 1);
  3424. }
  3425. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3426. {
  3427. var args[] = { arg1, arg2 };
  3428. return invoke (method, args, 2);
  3429. }
  3430. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3431. {
  3432. var args[] = { arg1, arg2, arg3 };
  3433. return invoke (method, args, 3);
  3434. }
  3435. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3436. {
  3437. var args[] = { arg1, arg2, arg3, arg4 };
  3438. return invoke (method, args, 4);
  3439. }
  3440. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3441. {
  3442. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3443. return invoke (method, args, 5);
  3444. }
  3445. END_JUCE_NAMESPACE
  3446. /*** End of inlined file: juce_Variant.cpp ***/
  3447. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3448. BEGIN_JUCE_NAMESPACE
  3449. NamedValueSet::NamedValue::NamedValue() throw()
  3450. {
  3451. }
  3452. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3453. : name (name_), value (value_)
  3454. {
  3455. }
  3456. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3457. {
  3458. return name == other.name && value == other.value;
  3459. }
  3460. NamedValueSet::NamedValueSet() throw()
  3461. {
  3462. }
  3463. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3464. : values (other.values)
  3465. {
  3466. }
  3467. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3468. {
  3469. values = other.values;
  3470. return *this;
  3471. }
  3472. NamedValueSet::~NamedValueSet()
  3473. {
  3474. }
  3475. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3476. {
  3477. return values == other.values;
  3478. }
  3479. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3480. {
  3481. return ! operator== (other);
  3482. }
  3483. int NamedValueSet::size() const throw()
  3484. {
  3485. return values.size();
  3486. }
  3487. const var& NamedValueSet::operator[] (const Identifier& name) const
  3488. {
  3489. for (int i = values.size(); --i >= 0;)
  3490. {
  3491. const NamedValue& v = values.getReference(i);
  3492. if (v.name == name)
  3493. return v.value;
  3494. }
  3495. return var::null;
  3496. }
  3497. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3498. {
  3499. const var* v = getItem (name);
  3500. return v != 0 ? *v : defaultReturnValue;
  3501. }
  3502. var* NamedValueSet::getItem (const Identifier& name) const
  3503. {
  3504. for (int i = values.size(); --i >= 0;)
  3505. {
  3506. NamedValue& v = values.getReference(i);
  3507. if (v.name == name)
  3508. return &(v.value);
  3509. }
  3510. return 0;
  3511. }
  3512. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3513. {
  3514. for (int i = values.size(); --i >= 0;)
  3515. {
  3516. NamedValue& v = values.getReference(i);
  3517. if (v.name == name)
  3518. {
  3519. if (v.value == newValue)
  3520. return false;
  3521. v.value = newValue;
  3522. return true;
  3523. }
  3524. }
  3525. values.add (NamedValue (name, newValue));
  3526. return true;
  3527. }
  3528. bool NamedValueSet::contains (const Identifier& name) const
  3529. {
  3530. return getItem (name) != 0;
  3531. }
  3532. bool NamedValueSet::remove (const Identifier& name)
  3533. {
  3534. for (int i = values.size(); --i >= 0;)
  3535. {
  3536. if (values.getReference(i).name == name)
  3537. {
  3538. values.remove (i);
  3539. return true;
  3540. }
  3541. }
  3542. return false;
  3543. }
  3544. const Identifier NamedValueSet::getName (const int index) const
  3545. {
  3546. jassert (((unsigned int) index) < (unsigned int) values.size());
  3547. return values [index].name;
  3548. }
  3549. const var NamedValueSet::getValueAt (const int index) const
  3550. {
  3551. jassert (((unsigned int) index) < (unsigned int) values.size());
  3552. return values [index].value;
  3553. }
  3554. void NamedValueSet::clear()
  3555. {
  3556. values.clear();
  3557. }
  3558. END_JUCE_NAMESPACE
  3559. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3560. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3561. BEGIN_JUCE_NAMESPACE
  3562. DynamicObject::DynamicObject()
  3563. {
  3564. }
  3565. DynamicObject::~DynamicObject()
  3566. {
  3567. }
  3568. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3569. {
  3570. var* const v = properties.getItem (propertyName);
  3571. return v != 0 && ! v->isMethod();
  3572. }
  3573. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3574. {
  3575. return properties [propertyName];
  3576. }
  3577. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3578. {
  3579. properties.set (propertyName, newValue);
  3580. }
  3581. void DynamicObject::removeProperty (const Identifier& propertyName)
  3582. {
  3583. properties.remove (propertyName);
  3584. }
  3585. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3586. {
  3587. return getProperty (methodName).isMethod();
  3588. }
  3589. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3590. const var* parameters,
  3591. int numParameters)
  3592. {
  3593. return properties [methodName].invoke (var (this), parameters, numParameters);
  3594. }
  3595. void DynamicObject::setMethod (const Identifier& name,
  3596. var::MethodFunction methodFunction)
  3597. {
  3598. properties.set (name, var (methodFunction));
  3599. }
  3600. void DynamicObject::clear()
  3601. {
  3602. properties.clear();
  3603. }
  3604. END_JUCE_NAMESPACE
  3605. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3606. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3607. BEGIN_JUCE_NAMESPACE
  3608. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3609. {
  3610. jassert (keyData != 0);
  3611. jassert (keyBytes > 0);
  3612. static const uint32 initialPValues [18] =
  3613. {
  3614. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3615. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3616. 0x9216d5d9, 0x8979fb1b
  3617. };
  3618. static const uint32 initialSValues [4 * 256] =
  3619. {
  3620. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3621. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3622. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3623. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3624. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3625. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3626. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3627. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3628. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3629. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3630. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3631. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3632. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3633. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3634. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3635. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3636. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3637. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3638. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3639. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3640. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3641. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3642. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3643. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3644. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3645. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3646. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3647. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3648. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3649. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3650. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3651. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3652. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3653. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3654. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3655. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3656. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3657. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3658. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3659. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3660. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3661. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3662. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3663. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3664. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3665. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3666. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3667. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3668. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3669. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3670. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3671. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3672. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3673. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3674. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3675. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3676. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3677. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3678. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3679. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3680. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3681. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3682. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3683. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3684. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3685. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3686. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3687. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3688. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3689. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3690. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3691. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3692. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3693. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3694. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3695. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3696. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3697. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3698. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3699. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3700. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3701. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3702. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3703. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3704. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3705. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3706. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3707. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3708. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3709. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3710. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3711. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3712. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3713. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3714. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3715. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3716. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3717. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3718. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3719. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3720. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3721. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3722. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3723. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3724. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3725. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3726. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3727. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3728. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3729. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3730. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3731. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3732. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3733. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3734. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3735. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3736. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3737. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3738. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3739. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3740. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3741. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3742. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3743. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3744. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3745. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3746. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3747. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3748. };
  3749. memcpy (p, initialPValues, sizeof (p));
  3750. int i, j = 0;
  3751. for (i = 4; --i >= 0;)
  3752. {
  3753. s[i].malloc (256);
  3754. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3755. }
  3756. for (i = 0; i < 18; ++i)
  3757. {
  3758. uint32 d = 0;
  3759. for (int k = 0; k < 4; ++k)
  3760. {
  3761. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3762. if (++j >= keyBytes)
  3763. j = 0;
  3764. }
  3765. p[i] = initialPValues[i] ^ d;
  3766. }
  3767. uint32 l = 0, r = 0;
  3768. for (i = 0; i < 18; i += 2)
  3769. {
  3770. encrypt (l, r);
  3771. p[i] = l;
  3772. p[i + 1] = r;
  3773. }
  3774. for (i = 0; i < 4; ++i)
  3775. {
  3776. for (j = 0; j < 256; j += 2)
  3777. {
  3778. encrypt (l, r);
  3779. s[i][j] = l;
  3780. s[i][j + 1] = r;
  3781. }
  3782. }
  3783. }
  3784. BlowFish::BlowFish (const BlowFish& other)
  3785. {
  3786. for (int i = 4; --i >= 0;)
  3787. s[i].malloc (256);
  3788. operator= (other);
  3789. }
  3790. BlowFish& BlowFish::operator= (const BlowFish& other)
  3791. {
  3792. memcpy (p, other.p, sizeof (p));
  3793. for (int i = 4; --i >= 0;)
  3794. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3795. return *this;
  3796. }
  3797. BlowFish::~BlowFish()
  3798. {
  3799. }
  3800. uint32 BlowFish::F (const uint32 x) const throw()
  3801. {
  3802. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3803. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3804. }
  3805. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3806. {
  3807. uint32 l = data1;
  3808. uint32 r = data2;
  3809. for (int i = 0; i < 16; ++i)
  3810. {
  3811. l ^= p[i];
  3812. r ^= F(l);
  3813. swapVariables (l, r);
  3814. }
  3815. data1 = r ^ p[17];
  3816. data2 = l ^ p[16];
  3817. }
  3818. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3819. {
  3820. uint32 l = data1;
  3821. uint32 r = data2;
  3822. for (int i = 17; i > 1; --i)
  3823. {
  3824. l ^= p[i];
  3825. r ^= F(l);
  3826. swapVariables (l, r);
  3827. }
  3828. data1 = r ^ p[0];
  3829. data2 = l ^ p[1];
  3830. }
  3831. END_JUCE_NAMESPACE
  3832. /*** End of inlined file: juce_BlowFish.cpp ***/
  3833. /*** Start of inlined file: juce_MD5.cpp ***/
  3834. BEGIN_JUCE_NAMESPACE
  3835. MD5::MD5()
  3836. {
  3837. zerostruct (result);
  3838. }
  3839. MD5::MD5 (const MD5& other)
  3840. {
  3841. memcpy (result, other.result, sizeof (result));
  3842. }
  3843. MD5& MD5::operator= (const MD5& other)
  3844. {
  3845. memcpy (result, other.result, sizeof (result));
  3846. return *this;
  3847. }
  3848. MD5::MD5 (const MemoryBlock& data)
  3849. {
  3850. ProcessContext context;
  3851. context.processBlock (data.getData(), data.getSize());
  3852. context.finish (result);
  3853. }
  3854. MD5::MD5 (const void* data, const size_t numBytes)
  3855. {
  3856. ProcessContext context;
  3857. context.processBlock (data, numBytes);
  3858. context.finish (result);
  3859. }
  3860. MD5::MD5 (const String& text)
  3861. {
  3862. ProcessContext context;
  3863. const int len = text.length();
  3864. const juce_wchar* const t = text;
  3865. for (int i = 0; i < len; ++i)
  3866. {
  3867. // force the string into integer-sized unicode characters, to try to make it
  3868. // get the same results on all platforms + compilers.
  3869. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3870. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3871. }
  3872. context.finish (result);
  3873. }
  3874. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3875. {
  3876. ProcessContext context;
  3877. if (numBytesToRead < 0)
  3878. numBytesToRead = std::numeric_limits<int64>::max();
  3879. while (numBytesToRead > 0)
  3880. {
  3881. uint8 tempBuffer [512];
  3882. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3883. if (bytesRead <= 0)
  3884. break;
  3885. numBytesToRead -= bytesRead;
  3886. context.processBlock (tempBuffer, bytesRead);
  3887. }
  3888. context.finish (result);
  3889. }
  3890. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  3891. {
  3892. processStream (input, numBytesToRead);
  3893. }
  3894. MD5::MD5 (const File& file)
  3895. {
  3896. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  3897. if (fin != 0)
  3898. processStream (*fin, -1);
  3899. else
  3900. zerostruct (result);
  3901. }
  3902. MD5::~MD5()
  3903. {
  3904. }
  3905. namespace MD5Functions
  3906. {
  3907. static void encode (void* const output, const void* const input, const int numBytes) throw()
  3908. {
  3909. for (int i = 0; i < (numBytes >> 2); ++i)
  3910. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  3911. }
  3912. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  3913. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  3914. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  3915. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  3916. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  3917. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3918. {
  3919. a += F (b, c, d) + x + ac;
  3920. a = rotateLeft (a, s) + b;
  3921. }
  3922. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3923. {
  3924. a += G (b, c, d) + x + ac;
  3925. a = rotateLeft (a, s) + b;
  3926. }
  3927. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3928. {
  3929. a += H (b, c, d) + x + ac;
  3930. a = rotateLeft (a, s) + b;
  3931. }
  3932. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3933. {
  3934. a += I (b, c, d) + x + ac;
  3935. a = rotateLeft (a, s) + b;
  3936. }
  3937. }
  3938. MD5::ProcessContext::ProcessContext()
  3939. {
  3940. state[0] = 0x67452301;
  3941. state[1] = 0xefcdab89;
  3942. state[2] = 0x98badcfe;
  3943. state[3] = 0x10325476;
  3944. count[0] = 0;
  3945. count[1] = 0;
  3946. }
  3947. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  3948. {
  3949. int bufferPos = ((count[0] >> 3) & 0x3F);
  3950. count[0] += (uint32) (dataSize << 3);
  3951. if (count[0] < ((uint32) dataSize << 3))
  3952. count[1]++;
  3953. count[1] += (uint32) (dataSize >> 29);
  3954. const size_t spaceLeft = 64 - bufferPos;
  3955. size_t i = 0;
  3956. if (dataSize >= spaceLeft)
  3957. {
  3958. memcpy (buffer + bufferPos, data, spaceLeft);
  3959. transform (buffer);
  3960. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  3961. transform (static_cast <const char*> (data) + i);
  3962. bufferPos = 0;
  3963. }
  3964. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  3965. }
  3966. void MD5::ProcessContext::finish (void* const result)
  3967. {
  3968. unsigned char encodedLength[8];
  3969. MD5Functions::encode (encodedLength, count, 8);
  3970. // Pad out to 56 mod 64.
  3971. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3972. const int paddingLength = (index < 56) ? (56 - index)
  3973. : (120 - index);
  3974. uint8 paddingBuffer [64];
  3975. zeromem (paddingBuffer, paddingLength);
  3976. paddingBuffer [0] = 0x80;
  3977. processBlock (paddingBuffer, paddingLength);
  3978. processBlock (encodedLength, 8);
  3979. MD5Functions::encode (result, state, 16);
  3980. zerostruct (buffer);
  3981. }
  3982. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  3983. {
  3984. using namespace MD5Functions;
  3985. uint32 a = state[0];
  3986. uint32 b = state[1];
  3987. uint32 c = state[2];
  3988. uint32 d = state[3];
  3989. uint32 x[16];
  3990. encode (x, bufferToTransform, 64);
  3991. enum Constants
  3992. {
  3993. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  3994. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  3995. };
  3996. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  3997. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  3998. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  3999. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4000. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4001. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4002. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4003. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4004. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4005. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4006. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4007. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4008. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4009. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4010. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4011. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4012. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4013. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4014. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4015. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4016. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4017. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4018. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4019. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4020. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4021. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4022. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4023. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4024. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4025. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4026. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4027. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4028. state[0] += a;
  4029. state[1] += b;
  4030. state[2] += c;
  4031. state[3] += d;
  4032. zerostruct (x);
  4033. }
  4034. const MemoryBlock MD5::getRawChecksumData() const
  4035. {
  4036. return MemoryBlock (result, sizeof (result));
  4037. }
  4038. const String MD5::toHexString() const
  4039. {
  4040. return String::toHexString (result, sizeof (result), 0);
  4041. }
  4042. bool MD5::operator== (const MD5& other) const
  4043. {
  4044. return memcmp (result, other.result, sizeof (result)) == 0;
  4045. }
  4046. bool MD5::operator!= (const MD5& other) const
  4047. {
  4048. return ! operator== (other);
  4049. }
  4050. END_JUCE_NAMESPACE
  4051. /*** End of inlined file: juce_MD5.cpp ***/
  4052. /*** Start of inlined file: juce_Primes.cpp ***/
  4053. BEGIN_JUCE_NAMESPACE
  4054. namespace PrimesHelpers
  4055. {
  4056. static void createSmallSieve (const int numBits, BigInteger& result)
  4057. {
  4058. result.setBit (numBits);
  4059. result.clearBit (numBits); // to enlarge the array
  4060. result.setBit (0);
  4061. int n = 2;
  4062. do
  4063. {
  4064. for (int i = n + n; i < numBits; i += n)
  4065. result.setBit (i);
  4066. n = result.findNextClearBit (n + 1);
  4067. }
  4068. while (n <= (numBits >> 1));
  4069. }
  4070. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4071. const BigInteger& smallSieve, const int smallSieveSize)
  4072. {
  4073. jassert (! base[0]); // must be even!
  4074. result.setBit (numBits);
  4075. result.clearBit (numBits); // to enlarge the array
  4076. int index = smallSieve.findNextClearBit (0);
  4077. do
  4078. {
  4079. const int prime = (index << 1) + 1;
  4080. BigInteger r (base), remainder;
  4081. r.divideBy (prime, remainder);
  4082. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4083. if (r.isZero())
  4084. i += prime;
  4085. if ((i & 1) == 0)
  4086. i += prime;
  4087. i = (i - 1) >> 1;
  4088. while (i < numBits)
  4089. {
  4090. result.setBit (i);
  4091. i += prime;
  4092. }
  4093. index = smallSieve.findNextClearBit (index + 1);
  4094. }
  4095. while (index < smallSieveSize);
  4096. }
  4097. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4098. const int numBits, BigInteger& result, const int certainty)
  4099. {
  4100. for (int i = 0; i < numBits; ++i)
  4101. {
  4102. if (! sieve[i])
  4103. {
  4104. result = base + (unsigned int) ((i << 1) + 1);
  4105. if (Primes::isProbablyPrime (result, certainty))
  4106. return true;
  4107. }
  4108. }
  4109. return false;
  4110. }
  4111. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4112. {
  4113. const BigInteger one (1), two (2);
  4114. const BigInteger nMinusOne (n - one);
  4115. BigInteger d (nMinusOne);
  4116. const int s = d.findNextSetBit (0);
  4117. d >>= s;
  4118. BigInteger smallPrimes;
  4119. int numBitsInSmallPrimes = 0;
  4120. for (;;)
  4121. {
  4122. numBitsInSmallPrimes += 256;
  4123. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4124. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4125. if (numPrimesFound > iterations + 1)
  4126. break;
  4127. }
  4128. int smallPrime = 2;
  4129. while (--iterations >= 0)
  4130. {
  4131. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4132. BigInteger r (smallPrime);
  4133. r.exponentModulo (d, n);
  4134. if (r != one && r != nMinusOne)
  4135. {
  4136. for (int j = 0; j < s; ++j)
  4137. {
  4138. r.exponentModulo (two, n);
  4139. if (r == nMinusOne)
  4140. break;
  4141. }
  4142. if (r != nMinusOne)
  4143. return false;
  4144. }
  4145. }
  4146. return true;
  4147. }
  4148. }
  4149. const BigInteger Primes::createProbablePrime (const int bitLength,
  4150. const int certainty,
  4151. const int* randomSeeds,
  4152. int numRandomSeeds)
  4153. {
  4154. using namespace PrimesHelpers;
  4155. int defaultSeeds [16];
  4156. if (numRandomSeeds <= 0)
  4157. {
  4158. randomSeeds = defaultSeeds;
  4159. numRandomSeeds = numElementsInArray (defaultSeeds);
  4160. Random r (0);
  4161. for (int j = 10; --j >= 0;)
  4162. {
  4163. r.setSeedRandomly();
  4164. for (int i = numRandomSeeds; --i >= 0;)
  4165. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4166. }
  4167. }
  4168. BigInteger smallSieve;
  4169. const int smallSieveSize = 15000;
  4170. createSmallSieve (smallSieveSize, smallSieve);
  4171. BigInteger p;
  4172. for (int i = numRandomSeeds; --i >= 0;)
  4173. {
  4174. BigInteger p2;
  4175. Random r (randomSeeds[i]);
  4176. r.fillBitsRandomly (p2, 0, bitLength);
  4177. p ^= p2;
  4178. }
  4179. p.setBit (bitLength - 1);
  4180. p.clearBit (0);
  4181. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4182. while (p.getHighestBit() < bitLength)
  4183. {
  4184. p += 2 * searchLen;
  4185. BigInteger sieve;
  4186. bigSieve (p, searchLen, sieve,
  4187. smallSieve, smallSieveSize);
  4188. BigInteger candidate;
  4189. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4190. return candidate;
  4191. }
  4192. jassertfalse;
  4193. return BigInteger();
  4194. }
  4195. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4196. {
  4197. using namespace PrimesHelpers;
  4198. if (! number[0])
  4199. return false;
  4200. if (number.getHighestBit() <= 10)
  4201. {
  4202. const int num = number.getBitRangeAsInt (0, 10);
  4203. for (int i = num / 2; --i > 1;)
  4204. if (num % i == 0)
  4205. return false;
  4206. return true;
  4207. }
  4208. else
  4209. {
  4210. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4211. return false;
  4212. return passesMillerRabin (number, certainty);
  4213. }
  4214. }
  4215. END_JUCE_NAMESPACE
  4216. /*** End of inlined file: juce_Primes.cpp ***/
  4217. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4218. BEGIN_JUCE_NAMESPACE
  4219. RSAKey::RSAKey()
  4220. {
  4221. }
  4222. RSAKey::RSAKey (const String& s)
  4223. {
  4224. if (s.containsChar (','))
  4225. {
  4226. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4227. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4228. }
  4229. else
  4230. {
  4231. // the string needs to be two hex numbers, comma-separated..
  4232. jassertfalse;
  4233. }
  4234. }
  4235. RSAKey::~RSAKey()
  4236. {
  4237. }
  4238. bool RSAKey::operator== (const RSAKey& other) const throw()
  4239. {
  4240. return part1 == other.part1 && part2 == other.part2;
  4241. }
  4242. bool RSAKey::operator!= (const RSAKey& other) const throw()
  4243. {
  4244. return ! operator== (other);
  4245. }
  4246. const String RSAKey::toString() const
  4247. {
  4248. return part1.toString (16) + "," + part2.toString (16);
  4249. }
  4250. bool RSAKey::applyToValue (BigInteger& value) const
  4251. {
  4252. if (part1.isZero() || part2.isZero() || value <= 0)
  4253. {
  4254. jassertfalse; // using an uninitialised key
  4255. value.clear();
  4256. return false;
  4257. }
  4258. BigInteger result;
  4259. while (! value.isZero())
  4260. {
  4261. result *= part2;
  4262. BigInteger remainder;
  4263. value.divideBy (part2, remainder);
  4264. remainder.exponentModulo (part1, part2);
  4265. result += remainder;
  4266. }
  4267. value.swapWith (result);
  4268. return true;
  4269. }
  4270. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4271. {
  4272. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4273. // are fast to divide + multiply
  4274. for (int i = 2; i <= 65536; i *= 2)
  4275. {
  4276. const BigInteger e (1 + i);
  4277. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4278. return e;
  4279. }
  4280. BigInteger e (4);
  4281. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4282. ++e;
  4283. return e;
  4284. }
  4285. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4286. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4287. {
  4288. jassert (numBits > 16); // not much point using less than this..
  4289. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4290. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4291. const BigInteger n (p * q);
  4292. const BigInteger m (--p * --q);
  4293. const BigInteger e (findBestCommonDivisor (p, q));
  4294. BigInteger d (e);
  4295. d.inverseModulo (m);
  4296. publicKey.part1 = e;
  4297. publicKey.part2 = n;
  4298. privateKey.part1 = d;
  4299. privateKey.part2 = n;
  4300. }
  4301. END_JUCE_NAMESPACE
  4302. /*** End of inlined file: juce_RSAKey.cpp ***/
  4303. /*** Start of inlined file: juce_InputStream.cpp ***/
  4304. BEGIN_JUCE_NAMESPACE
  4305. char InputStream::readByte()
  4306. {
  4307. char temp = 0;
  4308. read (&temp, 1);
  4309. return temp;
  4310. }
  4311. bool InputStream::readBool()
  4312. {
  4313. return readByte() != 0;
  4314. }
  4315. short InputStream::readShort()
  4316. {
  4317. char temp[2];
  4318. if (read (temp, 2) == 2)
  4319. return (short) ByteOrder::littleEndianShort (temp);
  4320. return 0;
  4321. }
  4322. short InputStream::readShortBigEndian()
  4323. {
  4324. char temp[2];
  4325. if (read (temp, 2) == 2)
  4326. return (short) ByteOrder::bigEndianShort (temp);
  4327. return 0;
  4328. }
  4329. int InputStream::readInt()
  4330. {
  4331. char temp[4];
  4332. if (read (temp, 4) == 4)
  4333. return (int) ByteOrder::littleEndianInt (temp);
  4334. return 0;
  4335. }
  4336. int InputStream::readIntBigEndian()
  4337. {
  4338. char temp[4];
  4339. if (read (temp, 4) == 4)
  4340. return (int) ByteOrder::bigEndianInt (temp);
  4341. return 0;
  4342. }
  4343. int InputStream::readCompressedInt()
  4344. {
  4345. const unsigned char sizeByte = readByte();
  4346. if (sizeByte == 0)
  4347. return 0;
  4348. const int numBytes = (sizeByte & 0x7f);
  4349. if (numBytes > 4)
  4350. {
  4351. jassertfalse; // trying to read corrupt data - this method must only be used
  4352. // to read data that was written by OutputStream::writeCompressedInt()
  4353. return 0;
  4354. }
  4355. char bytes[4] = { 0, 0, 0, 0 };
  4356. if (read (bytes, numBytes) != numBytes)
  4357. return 0;
  4358. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4359. return (sizeByte >> 7) ? -num : num;
  4360. }
  4361. int64 InputStream::readInt64()
  4362. {
  4363. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4364. if (read (n.asBytes, 8) == 8)
  4365. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4366. return 0;
  4367. }
  4368. int64 InputStream::readInt64BigEndian()
  4369. {
  4370. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4371. if (read (n.asBytes, 8) == 8)
  4372. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4373. return 0;
  4374. }
  4375. float InputStream::readFloat()
  4376. {
  4377. // the union below relies on these types being the same size...
  4378. static_jassert (sizeof (int32) == sizeof (float));
  4379. union { int32 asInt; float asFloat; } n;
  4380. n.asInt = (int32) readInt();
  4381. return n.asFloat;
  4382. }
  4383. float InputStream::readFloatBigEndian()
  4384. {
  4385. union { int32 asInt; float asFloat; } n;
  4386. n.asInt = (int32) readIntBigEndian();
  4387. return n.asFloat;
  4388. }
  4389. double InputStream::readDouble()
  4390. {
  4391. union { int64 asInt; double asDouble; } n;
  4392. n.asInt = readInt64();
  4393. return n.asDouble;
  4394. }
  4395. double InputStream::readDoubleBigEndian()
  4396. {
  4397. union { int64 asInt; double asDouble; } n;
  4398. n.asInt = readInt64BigEndian();
  4399. return n.asDouble;
  4400. }
  4401. const String InputStream::readString()
  4402. {
  4403. MemoryBlock buffer (256);
  4404. char* data = static_cast<char*> (buffer.getData());
  4405. size_t i = 0;
  4406. while ((data[i] = readByte()) != 0)
  4407. {
  4408. if (++i >= buffer.getSize())
  4409. {
  4410. buffer.setSize (buffer.getSize() + 512);
  4411. data = static_cast<char*> (buffer.getData());
  4412. }
  4413. }
  4414. return String::fromUTF8 (data, (int) i);
  4415. }
  4416. const String InputStream::readNextLine()
  4417. {
  4418. MemoryBlock buffer (256);
  4419. char* data = static_cast<char*> (buffer.getData());
  4420. size_t i = 0;
  4421. while ((data[i] = readByte()) != 0)
  4422. {
  4423. if (data[i] == '\n')
  4424. break;
  4425. if (data[i] == '\r')
  4426. {
  4427. const int64 lastPos = getPosition();
  4428. if (readByte() != '\n')
  4429. setPosition (lastPos);
  4430. break;
  4431. }
  4432. if (++i >= buffer.getSize())
  4433. {
  4434. buffer.setSize (buffer.getSize() + 512);
  4435. data = static_cast<char*> (buffer.getData());
  4436. }
  4437. }
  4438. return String::fromUTF8 (data, (int) i);
  4439. }
  4440. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4441. {
  4442. const int64 totalLength = getTotalLength();
  4443. if (totalLength >= 0)
  4444. {
  4445. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4446. totalLength - getPosition());
  4447. if (numBytes < 0)
  4448. numBytes = totalBytesRemaining;
  4449. else if (numBytes > 0)
  4450. numBytes = jmin (numBytes, totalBytesRemaining);
  4451. else
  4452. return 0;
  4453. }
  4454. const size_t originalBlockSize = block.getSize();
  4455. int totalBytesRead = 0;
  4456. if (numBytes > 0)
  4457. {
  4458. // know how many bytes we want, so we can resize the block first..
  4459. block.setSize (originalBlockSize + numBytes, false);
  4460. totalBytesRead = read (static_cast<char*> (block.getData()) + originalBlockSize, numBytes);
  4461. }
  4462. else
  4463. {
  4464. // read until end of stram..
  4465. const int chunkSize = 32768;
  4466. for (;;)
  4467. {
  4468. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4469. const int bytesJustIn = read (static_cast<char*> (block.getData())
  4470. + originalBlockSize
  4471. + totalBytesRead,
  4472. chunkSize);
  4473. if (bytesJustIn == 0)
  4474. break;
  4475. totalBytesRead += bytesJustIn;
  4476. }
  4477. }
  4478. // trim off any excess left at the end
  4479. block.setSize (originalBlockSize + totalBytesRead, false);
  4480. return totalBytesRead;
  4481. }
  4482. const String InputStream::readEntireStreamAsString()
  4483. {
  4484. MemoryBlock mb;
  4485. const int size = readIntoMemoryBlock (mb);
  4486. return String::createStringFromData (static_cast<const char*> (mb.getData()), size);
  4487. }
  4488. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4489. {
  4490. if (numBytesToSkip > 0)
  4491. {
  4492. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4493. HeapBlock<char> temp (skipBufferSize);
  4494. while (numBytesToSkip > 0 && ! isExhausted())
  4495. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4496. }
  4497. }
  4498. END_JUCE_NAMESPACE
  4499. /*** End of inlined file: juce_InputStream.cpp ***/
  4500. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4501. BEGIN_JUCE_NAMESPACE
  4502. #if JUCE_DEBUG
  4503. static CriticalSection activeStreamLock;
  4504. static Array<void*> activeStreams;
  4505. void juce_CheckForDanglingStreams()
  4506. {
  4507. /*
  4508. It's always a bad idea to leak any object, but if you're leaking output
  4509. streams, then there's a good chance that you're failing to flush a file
  4510. to disk properly, which could result in corrupted data and other similar
  4511. nastiness..
  4512. */
  4513. jassert (activeStreams.size() == 0);
  4514. };
  4515. #endif
  4516. OutputStream::OutputStream()
  4517. {
  4518. #if JUCE_DEBUG
  4519. const ScopedLock sl (activeStreamLock);
  4520. activeStreams.add (this);
  4521. #endif
  4522. }
  4523. OutputStream::~OutputStream()
  4524. {
  4525. #if JUCE_DEBUG
  4526. const ScopedLock sl (activeStreamLock);
  4527. activeStreams.removeValue (this);
  4528. #endif
  4529. }
  4530. void OutputStream::writeBool (const bool b)
  4531. {
  4532. writeByte (b ? (char) 1
  4533. : (char) 0);
  4534. }
  4535. void OutputStream::writeByte (char byte)
  4536. {
  4537. write (&byte, 1);
  4538. }
  4539. void OutputStream::writeShort (short value)
  4540. {
  4541. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4542. write (&v, 2);
  4543. }
  4544. void OutputStream::writeShortBigEndian (short value)
  4545. {
  4546. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4547. write (&v, 2);
  4548. }
  4549. void OutputStream::writeInt (int value)
  4550. {
  4551. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4552. write (&v, 4);
  4553. }
  4554. void OutputStream::writeIntBigEndian (int value)
  4555. {
  4556. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4557. write (&v, 4);
  4558. }
  4559. void OutputStream::writeCompressedInt (int value)
  4560. {
  4561. unsigned int un = (value < 0) ? (unsigned int) -value
  4562. : (unsigned int) value;
  4563. uint8 data[5];
  4564. int num = 0;
  4565. while (un > 0)
  4566. {
  4567. data[++num] = (uint8) un;
  4568. un >>= 8;
  4569. }
  4570. data[0] = (uint8) num;
  4571. if (value < 0)
  4572. data[0] |= 0x80;
  4573. write (data, num + 1);
  4574. }
  4575. void OutputStream::writeInt64 (int64 value)
  4576. {
  4577. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4578. write (&v, 8);
  4579. }
  4580. void OutputStream::writeInt64BigEndian (int64 value)
  4581. {
  4582. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4583. write (&v, 8);
  4584. }
  4585. void OutputStream::writeFloat (float value)
  4586. {
  4587. union { int asInt; float asFloat; } n;
  4588. n.asFloat = value;
  4589. writeInt (n.asInt);
  4590. }
  4591. void OutputStream::writeFloatBigEndian (float value)
  4592. {
  4593. union { int asInt; float asFloat; } n;
  4594. n.asFloat = value;
  4595. writeIntBigEndian (n.asInt);
  4596. }
  4597. void OutputStream::writeDouble (double value)
  4598. {
  4599. union { int64 asInt; double asDouble; } n;
  4600. n.asDouble = value;
  4601. writeInt64 (n.asInt);
  4602. }
  4603. void OutputStream::writeDoubleBigEndian (double value)
  4604. {
  4605. union { int64 asInt; double asDouble; } n;
  4606. n.asDouble = value;
  4607. writeInt64BigEndian (n.asInt);
  4608. }
  4609. void OutputStream::writeString (const String& text)
  4610. {
  4611. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4612. // if lots of large, persistent strings were to be written to streams).
  4613. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4614. HeapBlock<char> temp (numBytes);
  4615. text.copyToUTF8 (temp, numBytes);
  4616. write (temp, numBytes);
  4617. }
  4618. void OutputStream::writeText (const String& text, const bool asUnicode,
  4619. const bool writeUnicodeHeaderBytes)
  4620. {
  4621. if (asUnicode)
  4622. {
  4623. if (writeUnicodeHeaderBytes)
  4624. write ("\x0ff\x0fe", 2);
  4625. const juce_wchar* src = text;
  4626. bool lastCharWasReturn = false;
  4627. while (*src != 0)
  4628. {
  4629. if (*src == L'\n' && ! lastCharWasReturn)
  4630. writeShort ((short) L'\r');
  4631. lastCharWasReturn = (*src == L'\r');
  4632. writeShort ((short) *src++);
  4633. }
  4634. }
  4635. else
  4636. {
  4637. const char* src = text.toUTF8();
  4638. const char* t = src;
  4639. for (;;)
  4640. {
  4641. if (*t == '\n')
  4642. {
  4643. if (t > src)
  4644. write (src, (int) (t - src));
  4645. write ("\r\n", 2);
  4646. src = t + 1;
  4647. }
  4648. else if (*t == '\r')
  4649. {
  4650. if (t[1] == '\n')
  4651. ++t;
  4652. }
  4653. else if (*t == 0)
  4654. {
  4655. if (t > src)
  4656. write (src, (int) (t - src));
  4657. break;
  4658. }
  4659. ++t;
  4660. }
  4661. }
  4662. }
  4663. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4664. {
  4665. if (numBytesToWrite < 0)
  4666. numBytesToWrite = std::numeric_limits<int64>::max();
  4667. int numWritten = 0;
  4668. while (numBytesToWrite > 0 && ! source.isExhausted())
  4669. {
  4670. char buffer [8192];
  4671. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4672. if (num <= 0)
  4673. break;
  4674. write (buffer, num);
  4675. numBytesToWrite -= num;
  4676. numWritten += num;
  4677. }
  4678. return numWritten;
  4679. }
  4680. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4681. {
  4682. return stream << String (number);
  4683. }
  4684. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4685. {
  4686. return stream << String (number);
  4687. }
  4688. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4689. {
  4690. stream.writeByte (character);
  4691. return stream;
  4692. }
  4693. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4694. {
  4695. stream.write (text, (int) strlen (text));
  4696. return stream;
  4697. }
  4698. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4699. {
  4700. stream.write (data.getData(), (int) data.getSize());
  4701. return stream;
  4702. }
  4703. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4704. {
  4705. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4706. if (in != 0)
  4707. stream.writeFromInputStream (*in, -1);
  4708. return stream;
  4709. }
  4710. END_JUCE_NAMESPACE
  4711. /*** End of inlined file: juce_OutputStream.cpp ***/
  4712. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4713. BEGIN_JUCE_NAMESPACE
  4714. DirectoryIterator::DirectoryIterator (const File& directory,
  4715. bool isRecursive_,
  4716. const String& wildCard_,
  4717. const int whatToLookFor_)
  4718. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  4719. wildCard (wildCard_),
  4720. path (File::addTrailingSeparator (directory.getFullPathName())),
  4721. index (-1),
  4722. totalNumFiles (-1),
  4723. whatToLookFor (whatToLookFor_),
  4724. isRecursive (isRecursive_)
  4725. {
  4726. // you have to specify the type of files you're looking for!
  4727. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4728. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4729. }
  4730. DirectoryIterator::~DirectoryIterator()
  4731. {
  4732. }
  4733. bool DirectoryIterator::next()
  4734. {
  4735. return next (0, 0, 0, 0, 0, 0);
  4736. }
  4737. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4738. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4739. {
  4740. if (subIterator != 0)
  4741. {
  4742. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4743. return true;
  4744. subIterator = 0;
  4745. }
  4746. String filename;
  4747. bool isDirectory, isHidden;
  4748. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4749. {
  4750. ++index;
  4751. if (! filename.containsOnly ("."))
  4752. {
  4753. const File fileFound (path + filename, 0);
  4754. bool matches = false;
  4755. if (isDirectory)
  4756. {
  4757. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4758. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4759. matches = (whatToLookFor & File::findDirectories) != 0;
  4760. }
  4761. else
  4762. {
  4763. matches = (whatToLookFor & File::findFiles) != 0;
  4764. }
  4765. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4766. if (matches && isRecursive)
  4767. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4768. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4769. matches = ! isHidden;
  4770. if (matches)
  4771. {
  4772. currentFile = fileFound;
  4773. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4774. if (isDirResult != 0) *isDirResult = isDirectory;
  4775. return true;
  4776. }
  4777. else if (subIterator != 0)
  4778. {
  4779. return next();
  4780. }
  4781. }
  4782. }
  4783. return false;
  4784. }
  4785. const File DirectoryIterator::getFile() const
  4786. {
  4787. if (subIterator != 0)
  4788. return subIterator->getFile();
  4789. return currentFile;
  4790. }
  4791. float DirectoryIterator::getEstimatedProgress() const
  4792. {
  4793. if (totalNumFiles < 0)
  4794. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4795. if (totalNumFiles <= 0)
  4796. return 0.0f;
  4797. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4798. : (float) index;
  4799. return detailedIndex / totalNumFiles;
  4800. }
  4801. END_JUCE_NAMESPACE
  4802. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4803. /*** Start of inlined file: juce_File.cpp ***/
  4804. #if ! JUCE_WINDOWS
  4805. #include <pwd.h>
  4806. #endif
  4807. BEGIN_JUCE_NAMESPACE
  4808. File::File (const String& fullPathName)
  4809. : fullPath (parseAbsolutePath (fullPathName))
  4810. {
  4811. }
  4812. File::File (const String& path, int)
  4813. : fullPath (path)
  4814. {
  4815. }
  4816. const File File::createFileWithoutCheckingPath (const String& path)
  4817. {
  4818. return File (path, 0);
  4819. }
  4820. File::File (const File& other)
  4821. : fullPath (other.fullPath)
  4822. {
  4823. }
  4824. File& File::operator= (const String& newPath)
  4825. {
  4826. fullPath = parseAbsolutePath (newPath);
  4827. return *this;
  4828. }
  4829. File& File::operator= (const File& other)
  4830. {
  4831. fullPath = other.fullPath;
  4832. return *this;
  4833. }
  4834. const File File::nonexistent;
  4835. const String File::parseAbsolutePath (const String& p)
  4836. {
  4837. if (p.isEmpty())
  4838. return String::empty;
  4839. #if JUCE_WINDOWS
  4840. // Windows..
  4841. String path (p.replaceCharacter ('/', '\\'));
  4842. if (path.startsWithChar (File::separator))
  4843. {
  4844. if (path[1] != File::separator)
  4845. {
  4846. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4847. If you're trying to parse a string that may be either a relative path or an absolute path,
  4848. you MUST provide a context against which the partial path can be evaluated - you can do
  4849. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4850. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4851. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4852. */
  4853. jassertfalse;
  4854. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4855. }
  4856. }
  4857. else if (! path.containsChar (':'))
  4858. {
  4859. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4860. If you're trying to parse a string that may be either a relative path or an absolute path,
  4861. you MUST provide a context against which the partial path can be evaluated - you can do
  4862. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4863. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4864. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4865. */
  4866. jassertfalse;
  4867. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4868. }
  4869. #else
  4870. // Mac or Linux..
  4871. String path (p.replaceCharacter ('\\', '/'));
  4872. if (path.startsWithChar ('~'))
  4873. {
  4874. if (path[1] == File::separator || path[1] == 0)
  4875. {
  4876. // expand a name of the form "~/abc"
  4877. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4878. + path.substring (1);
  4879. }
  4880. else
  4881. {
  4882. // expand a name of type "~dave/abc"
  4883. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4884. struct passwd* const pw = getpwnam (userName.toUTF8());
  4885. if (pw != 0)
  4886. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4887. }
  4888. }
  4889. else if (! path.startsWithChar (File::separator))
  4890. {
  4891. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4892. If you're trying to parse a string that may be either a relative path or an absolute path,
  4893. you MUST provide a context against which the partial path can be evaluated - you can do
  4894. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4895. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4896. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4897. */
  4898. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4899. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4900. }
  4901. #endif
  4902. return path.trimCharactersAtEnd (separatorString);
  4903. }
  4904. const String File::addTrailingSeparator (const String& path)
  4905. {
  4906. return path.endsWithChar (File::separator) ? path
  4907. : path + File::separator;
  4908. }
  4909. #if JUCE_LINUX
  4910. #define NAMES_ARE_CASE_SENSITIVE 1
  4911. #endif
  4912. bool File::areFileNamesCaseSensitive()
  4913. {
  4914. #if NAMES_ARE_CASE_SENSITIVE
  4915. return true;
  4916. #else
  4917. return false;
  4918. #endif
  4919. }
  4920. bool File::operator== (const File& other) const
  4921. {
  4922. #if NAMES_ARE_CASE_SENSITIVE
  4923. return fullPath == other.fullPath;
  4924. #else
  4925. return fullPath.equalsIgnoreCase (other.fullPath);
  4926. #endif
  4927. }
  4928. bool File::operator!= (const File& other) const
  4929. {
  4930. return ! operator== (other);
  4931. }
  4932. bool File::operator< (const File& other) const
  4933. {
  4934. #if NAMES_ARE_CASE_SENSITIVE
  4935. return fullPath < other.fullPath;
  4936. #else
  4937. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  4938. #endif
  4939. }
  4940. bool File::operator> (const File& other) const
  4941. {
  4942. #if NAMES_ARE_CASE_SENSITIVE
  4943. return fullPath > other.fullPath;
  4944. #else
  4945. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  4946. #endif
  4947. }
  4948. bool File::setReadOnly (const bool shouldBeReadOnly,
  4949. const bool applyRecursively) const
  4950. {
  4951. bool worked = true;
  4952. if (applyRecursively && isDirectory())
  4953. {
  4954. Array <File> subFiles;
  4955. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4956. for (int i = subFiles.size(); --i >= 0;)
  4957. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  4958. }
  4959. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  4960. }
  4961. bool File::deleteRecursively() const
  4962. {
  4963. bool worked = true;
  4964. if (isDirectory())
  4965. {
  4966. Array<File> subFiles;
  4967. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4968. for (int i = subFiles.size(); --i >= 0;)
  4969. worked = subFiles.getReference(i).deleteRecursively() && worked;
  4970. }
  4971. return deleteFile() && worked;
  4972. }
  4973. bool File::moveFileTo (const File& newFile) const
  4974. {
  4975. if (newFile.fullPath == fullPath)
  4976. return true;
  4977. #if ! NAMES_ARE_CASE_SENSITIVE
  4978. if (*this != newFile)
  4979. #endif
  4980. if (! newFile.deleteFile())
  4981. return false;
  4982. return moveInternal (newFile);
  4983. }
  4984. bool File::copyFileTo (const File& newFile) const
  4985. {
  4986. return (*this == newFile)
  4987. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  4988. }
  4989. bool File::copyDirectoryTo (const File& newDirectory) const
  4990. {
  4991. if (isDirectory() && newDirectory.createDirectory())
  4992. {
  4993. Array<File> subFiles;
  4994. findChildFiles (subFiles, File::findFiles, false);
  4995. int i;
  4996. for (i = 0; i < subFiles.size(); ++i)
  4997. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  4998. return false;
  4999. subFiles.clear();
  5000. findChildFiles (subFiles, File::findDirectories, false);
  5001. for (i = 0; i < subFiles.size(); ++i)
  5002. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5003. return false;
  5004. return true;
  5005. }
  5006. return false;
  5007. }
  5008. const String File::getPathUpToLastSlash() const
  5009. {
  5010. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5011. if (lastSlash > 0)
  5012. return fullPath.substring (0, lastSlash);
  5013. else if (lastSlash == 0)
  5014. return separatorString;
  5015. else
  5016. return fullPath;
  5017. }
  5018. const File File::getParentDirectory() const
  5019. {
  5020. return File (getPathUpToLastSlash(), (int) 0);
  5021. }
  5022. const String File::getFileName() const
  5023. {
  5024. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5025. }
  5026. int File::hashCode() const
  5027. {
  5028. return fullPath.hashCode();
  5029. }
  5030. int64 File::hashCode64() const
  5031. {
  5032. return fullPath.hashCode64();
  5033. }
  5034. const String File::getFileNameWithoutExtension() const
  5035. {
  5036. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5037. const int lastDot = fullPath.lastIndexOfChar ('.');
  5038. if (lastDot > lastSlash)
  5039. return fullPath.substring (lastSlash, lastDot);
  5040. else
  5041. return fullPath.substring (lastSlash);
  5042. }
  5043. bool File::isAChildOf (const File& potentialParent) const
  5044. {
  5045. if (potentialParent == File::nonexistent)
  5046. return false;
  5047. const String ourPath (getPathUpToLastSlash());
  5048. #if NAMES_ARE_CASE_SENSITIVE
  5049. if (potentialParent.fullPath == ourPath)
  5050. #else
  5051. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5052. #endif
  5053. {
  5054. return true;
  5055. }
  5056. else if (potentialParent.fullPath.length() >= ourPath.length())
  5057. {
  5058. return false;
  5059. }
  5060. else
  5061. {
  5062. return getParentDirectory().isAChildOf (potentialParent);
  5063. }
  5064. }
  5065. bool File::isAbsolutePath (const String& path)
  5066. {
  5067. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5068. #if JUCE_WINDOWS
  5069. || (path.isNotEmpty() && path[1] == ':');
  5070. #else
  5071. || path.startsWithChar ('~');
  5072. #endif
  5073. }
  5074. const File File::getChildFile (String relativePath) const
  5075. {
  5076. if (isAbsolutePath (relativePath))
  5077. {
  5078. // the path is really absolute..
  5079. return File (relativePath);
  5080. }
  5081. else
  5082. {
  5083. // it's relative, so remove any ../ or ./ bits at the start.
  5084. String path (fullPath);
  5085. if (relativePath[0] == '.')
  5086. {
  5087. #if JUCE_WINDOWS
  5088. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5089. #else
  5090. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5091. #endif
  5092. while (relativePath[0] == '.')
  5093. {
  5094. if (relativePath[1] == '.')
  5095. {
  5096. if (relativePath [2] == 0 || relativePath[2] == separator)
  5097. {
  5098. const int lastSlash = path.lastIndexOfChar (separator);
  5099. if (lastSlash >= 0)
  5100. path = path.substring (0, lastSlash);
  5101. relativePath = relativePath.substring (3);
  5102. }
  5103. else
  5104. {
  5105. break;
  5106. }
  5107. }
  5108. else if (relativePath[1] == separator)
  5109. {
  5110. relativePath = relativePath.substring (2);
  5111. }
  5112. else
  5113. {
  5114. break;
  5115. }
  5116. }
  5117. }
  5118. return File (addTrailingSeparator (path) + relativePath);
  5119. }
  5120. }
  5121. const File File::getSiblingFile (const String& fileName) const
  5122. {
  5123. return getParentDirectory().getChildFile (fileName);
  5124. }
  5125. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5126. {
  5127. if (bytes == 1)
  5128. {
  5129. return "1 byte";
  5130. }
  5131. else if (bytes < 1024)
  5132. {
  5133. return String ((int) bytes) + " bytes";
  5134. }
  5135. else if (bytes < 1024 * 1024)
  5136. {
  5137. return String (bytes / 1024.0, 1) + " KB";
  5138. }
  5139. else if (bytes < 1024 * 1024 * 1024)
  5140. {
  5141. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5142. }
  5143. else
  5144. {
  5145. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5146. }
  5147. }
  5148. bool File::create() const
  5149. {
  5150. if (exists())
  5151. return true;
  5152. {
  5153. const File parentDir (getParentDirectory());
  5154. if (parentDir == *this || ! parentDir.createDirectory())
  5155. return false;
  5156. FileOutputStream fo (*this, 8);
  5157. }
  5158. return exists();
  5159. }
  5160. bool File::createDirectory() const
  5161. {
  5162. if (! isDirectory())
  5163. {
  5164. const File parentDir (getParentDirectory());
  5165. if (parentDir == *this || ! parentDir.createDirectory())
  5166. return false;
  5167. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5168. return isDirectory();
  5169. }
  5170. return true;
  5171. }
  5172. const Time File::getCreationTime() const
  5173. {
  5174. int64 m, a, c;
  5175. getFileTimesInternal (m, a, c);
  5176. return Time (c);
  5177. }
  5178. const Time File::getLastModificationTime() const
  5179. {
  5180. int64 m, a, c;
  5181. getFileTimesInternal (m, a, c);
  5182. return Time (m);
  5183. }
  5184. const Time File::getLastAccessTime() const
  5185. {
  5186. int64 m, a, c;
  5187. getFileTimesInternal (m, a, c);
  5188. return Time (a);
  5189. }
  5190. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5191. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5192. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5193. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5194. {
  5195. if (! existsAsFile())
  5196. return false;
  5197. FileInputStream in (*this);
  5198. return getSize() == in.readIntoMemoryBlock (destBlock);
  5199. }
  5200. const String File::loadFileAsString() const
  5201. {
  5202. if (! existsAsFile())
  5203. return String::empty;
  5204. FileInputStream in (*this);
  5205. return in.readEntireStreamAsString();
  5206. }
  5207. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5208. {
  5209. return (whatToLookFor & (isDir ? findDirectories
  5210. : findFiles)) != 0
  5211. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5212. }
  5213. int File::findChildFiles (Array<File>& results,
  5214. const int whatToLookFor,
  5215. const bool searchRecursively,
  5216. const String& wildCardPattern) const
  5217. {
  5218. // you have to specify the type of files you're looking for!
  5219. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5220. int total = 0;
  5221. if (isDirectory())
  5222. {
  5223. // find child files or directories in this directory first..
  5224. String path (addTrailingSeparator (fullPath)), filename;
  5225. bool itemIsDirectory, itemIsHidden;
  5226. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5227. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5228. {
  5229. if (! filename.containsOnly ("."))
  5230. {
  5231. const File fileFound (path + filename, 0);
  5232. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5233. {
  5234. results.add (fileFound);
  5235. ++total;
  5236. }
  5237. if (searchRecursively && itemIsDirectory
  5238. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5239. {
  5240. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5241. }
  5242. }
  5243. }
  5244. }
  5245. return total;
  5246. }
  5247. int File::getNumberOfChildFiles (const int whatToLookFor,
  5248. const String& wildCardPattern) const
  5249. {
  5250. // you have to specify the type of files you're looking for!
  5251. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5252. int count = 0;
  5253. if (isDirectory())
  5254. {
  5255. String filename;
  5256. bool itemIsDirectory, itemIsHidden;
  5257. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5258. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5259. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5260. && ! filename.containsOnly ("."))
  5261. ++count;
  5262. }
  5263. else
  5264. {
  5265. // trying to search for files inside a non-directory?
  5266. jassertfalse;
  5267. }
  5268. return count;
  5269. }
  5270. bool File::containsSubDirectories() const
  5271. {
  5272. if (isDirectory())
  5273. {
  5274. String filename;
  5275. bool itemIsDirectory;
  5276. DirectoryIterator::NativeIterator i (*this, "*");
  5277. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5278. if (itemIsDirectory)
  5279. return true;
  5280. }
  5281. return false;
  5282. }
  5283. const File File::getNonexistentChildFile (const String& prefix_,
  5284. const String& suffix,
  5285. bool putNumbersInBrackets) const
  5286. {
  5287. File f (getChildFile (prefix_ + suffix));
  5288. if (f.exists())
  5289. {
  5290. int num = 2;
  5291. String prefix (prefix_);
  5292. // remove any bracketed numbers that may already be on the end..
  5293. if (prefix.trim().endsWithChar (')'))
  5294. {
  5295. putNumbersInBrackets = true;
  5296. const int openBracks = prefix.lastIndexOfChar ('(');
  5297. const int closeBracks = prefix.lastIndexOfChar (')');
  5298. if (openBracks > 0
  5299. && closeBracks > openBracks
  5300. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5301. {
  5302. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5303. prefix = prefix.substring (0, openBracks);
  5304. }
  5305. }
  5306. // also use brackets if it ends in a digit.
  5307. putNumbersInBrackets = putNumbersInBrackets
  5308. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5309. do
  5310. {
  5311. if (putNumbersInBrackets)
  5312. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5313. else
  5314. f = getChildFile (prefix + String (num++) + suffix);
  5315. } while (f.exists());
  5316. }
  5317. return f;
  5318. }
  5319. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5320. {
  5321. if (exists())
  5322. {
  5323. return getParentDirectory()
  5324. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5325. getFileExtension(),
  5326. putNumbersInBrackets);
  5327. }
  5328. else
  5329. {
  5330. return *this;
  5331. }
  5332. }
  5333. const String File::getFileExtension() const
  5334. {
  5335. String ext;
  5336. if (! isDirectory())
  5337. {
  5338. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5339. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5340. ext = fullPath.substring (indexOfDot);
  5341. }
  5342. return ext;
  5343. }
  5344. bool File::hasFileExtension (const String& possibleSuffix) const
  5345. {
  5346. if (possibleSuffix.isEmpty())
  5347. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5348. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5349. if (semicolon >= 0)
  5350. {
  5351. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5352. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5353. }
  5354. else
  5355. {
  5356. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5357. {
  5358. if (possibleSuffix.startsWithChar ('.'))
  5359. return true;
  5360. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5361. if (dotPos >= 0)
  5362. return fullPath [dotPos] == '.';
  5363. }
  5364. }
  5365. return false;
  5366. }
  5367. const File File::withFileExtension (const String& newExtension) const
  5368. {
  5369. if (fullPath.isEmpty())
  5370. return File::nonexistent;
  5371. String filePart (getFileName());
  5372. int i = filePart.lastIndexOfChar ('.');
  5373. if (i >= 0)
  5374. filePart = filePart.substring (0, i);
  5375. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5376. filePart << '.';
  5377. return getSiblingFile (filePart + newExtension);
  5378. }
  5379. bool File::startAsProcess (const String& parameters) const
  5380. {
  5381. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5382. }
  5383. FileInputStream* File::createInputStream() const
  5384. {
  5385. if (existsAsFile())
  5386. return new FileInputStream (*this);
  5387. return 0;
  5388. }
  5389. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5390. {
  5391. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5392. if (out->failedToOpen())
  5393. return 0;
  5394. return out.release();
  5395. }
  5396. bool File::appendData (const void* const dataToAppend,
  5397. const int numberOfBytes) const
  5398. {
  5399. if (numberOfBytes > 0)
  5400. {
  5401. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5402. if (out == 0)
  5403. return false;
  5404. out->write (dataToAppend, numberOfBytes);
  5405. }
  5406. return true;
  5407. }
  5408. bool File::replaceWithData (const void* const dataToWrite,
  5409. const int numberOfBytes) const
  5410. {
  5411. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5412. if (numberOfBytes <= 0)
  5413. return deleteFile();
  5414. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5415. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5416. return tempFile.overwriteTargetFileWithTemporary();
  5417. }
  5418. bool File::appendText (const String& text,
  5419. const bool asUnicode,
  5420. const bool writeUnicodeHeaderBytes) const
  5421. {
  5422. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5423. if (out != 0)
  5424. {
  5425. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5426. return true;
  5427. }
  5428. return false;
  5429. }
  5430. bool File::replaceWithText (const String& textToWrite,
  5431. const bool asUnicode,
  5432. const bool writeUnicodeHeaderBytes) const
  5433. {
  5434. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5435. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5436. return tempFile.overwriteTargetFileWithTemporary();
  5437. }
  5438. bool File::hasIdenticalContentTo (const File& other) const
  5439. {
  5440. if (other == *this)
  5441. return true;
  5442. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  5443. {
  5444. FileInputStream in1 (*this), in2 (other);
  5445. const int bufferSize = 4096;
  5446. HeapBlock <char> buffer1, buffer2;
  5447. buffer1.malloc (bufferSize);
  5448. buffer2.malloc (bufferSize);
  5449. for (;;)
  5450. {
  5451. const int num1 = in1.read (buffer1, bufferSize);
  5452. const int num2 = in2.read (buffer2, bufferSize);
  5453. if (num1 != num2)
  5454. break;
  5455. if (num1 <= 0)
  5456. return true;
  5457. if (memcmp (buffer1, buffer2, num1) != 0)
  5458. break;
  5459. }
  5460. }
  5461. return false;
  5462. }
  5463. const String File::createLegalPathName (const String& original)
  5464. {
  5465. String s (original);
  5466. String start;
  5467. if (s[1] == ':')
  5468. {
  5469. start = s.substring (0, 2);
  5470. s = s.substring (2);
  5471. }
  5472. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5473. .substring (0, 1024);
  5474. }
  5475. const String File::createLegalFileName (const String& original)
  5476. {
  5477. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5478. const int maxLength = 128; // only the length of the filename, not the whole path
  5479. const int len = s.length();
  5480. if (len > maxLength)
  5481. {
  5482. const int lastDot = s.lastIndexOfChar ('.');
  5483. if (lastDot > jmax (0, len - 12))
  5484. {
  5485. s = s.substring (0, maxLength - (len - lastDot))
  5486. + s.substring (lastDot);
  5487. }
  5488. else
  5489. {
  5490. s = s.substring (0, maxLength);
  5491. }
  5492. }
  5493. return s;
  5494. }
  5495. const String File::getRelativePathFrom (const File& dir) const
  5496. {
  5497. String thisPath (fullPath);
  5498. {
  5499. int len = thisPath.length();
  5500. while (--len >= 0 && thisPath [len] == File::separator)
  5501. thisPath [len] = 0;
  5502. }
  5503. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5504. : dir.fullPath));
  5505. const int len = jmin (thisPath.length(), dirPath.length());
  5506. int commonBitLength = 0;
  5507. for (int i = 0; i < len; ++i)
  5508. {
  5509. #if NAMES_ARE_CASE_SENSITIVE
  5510. if (thisPath[i] != dirPath[i])
  5511. #else
  5512. if (CharacterFunctions::toLowerCase (thisPath[i])
  5513. != CharacterFunctions::toLowerCase (dirPath[i]))
  5514. #endif
  5515. {
  5516. break;
  5517. }
  5518. ++commonBitLength;
  5519. }
  5520. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5521. --commonBitLength;
  5522. // if the only common bit is the root, then just return the full path..
  5523. if (commonBitLength <= 0
  5524. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5525. return fullPath;
  5526. thisPath = thisPath.substring (commonBitLength);
  5527. dirPath = dirPath.substring (commonBitLength);
  5528. while (dirPath.isNotEmpty())
  5529. {
  5530. #if JUCE_WINDOWS
  5531. thisPath = "..\\" + thisPath;
  5532. #else
  5533. thisPath = "../" + thisPath;
  5534. #endif
  5535. const int sep = dirPath.indexOfChar (separator);
  5536. if (sep >= 0)
  5537. dirPath = dirPath.substring (sep + 1);
  5538. else
  5539. dirPath = String::empty;
  5540. }
  5541. return thisPath;
  5542. }
  5543. const File File::createTempFile (const String& fileNameEnding)
  5544. {
  5545. const File tempFile (getSpecialLocation (tempDirectory)
  5546. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5547. .withFileExtension (fileNameEnding));
  5548. if (tempFile.exists())
  5549. return createTempFile (fileNameEnding);
  5550. else
  5551. return tempFile;
  5552. }
  5553. END_JUCE_NAMESPACE
  5554. /*** End of inlined file: juce_File.cpp ***/
  5555. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5556. BEGIN_JUCE_NAMESPACE
  5557. void* juce_fileOpen (const File& file, bool forWriting);
  5558. void juce_fileClose (void* handle);
  5559. int juce_fileRead (void* handle, void* buffer, int size);
  5560. int64 juce_fileSetPosition (void* handle, int64 pos);
  5561. FileInputStream::FileInputStream (const File& f)
  5562. : file (f),
  5563. currentPosition (0),
  5564. needToSeek (true)
  5565. {
  5566. totalSize = f.getSize();
  5567. fileHandle = juce_fileOpen (f, false);
  5568. }
  5569. FileInputStream::~FileInputStream()
  5570. {
  5571. juce_fileClose (fileHandle);
  5572. }
  5573. int64 FileInputStream::getTotalLength()
  5574. {
  5575. return totalSize;
  5576. }
  5577. int FileInputStream::read (void* buffer, int bytesToRead)
  5578. {
  5579. int num = 0;
  5580. if (needToSeek)
  5581. {
  5582. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5583. return 0;
  5584. needToSeek = false;
  5585. }
  5586. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5587. currentPosition += num;
  5588. return num;
  5589. }
  5590. bool FileInputStream::isExhausted()
  5591. {
  5592. return currentPosition >= totalSize;
  5593. }
  5594. int64 FileInputStream::getPosition()
  5595. {
  5596. return currentPosition;
  5597. }
  5598. bool FileInputStream::setPosition (int64 pos)
  5599. {
  5600. pos = jlimit ((int64) 0, totalSize, pos);
  5601. needToSeek |= (currentPosition != pos);
  5602. currentPosition = pos;
  5603. return true;
  5604. }
  5605. END_JUCE_NAMESPACE
  5606. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5607. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5608. BEGIN_JUCE_NAMESPACE
  5609. void* juce_fileOpen (const File& file, bool forWriting);
  5610. void juce_fileClose (void* handle);
  5611. int juce_fileWrite (void* handle, const void* buffer, int size);
  5612. int64 juce_fileSetPosition (void* handle, int64 pos);
  5613. FileOutputStream::FileOutputStream (const File& f,
  5614. const int bufferSize_)
  5615. : file (f),
  5616. bufferSize (bufferSize_),
  5617. bytesInBuffer (0)
  5618. {
  5619. fileHandle = juce_fileOpen (f, true);
  5620. if (fileHandle != 0)
  5621. {
  5622. currentPosition = getPositionInternal();
  5623. if (currentPosition < 0)
  5624. {
  5625. jassertfalse;
  5626. juce_fileClose (fileHandle);
  5627. fileHandle = 0;
  5628. }
  5629. }
  5630. buffer.malloc (jmax (bufferSize_, 16));
  5631. }
  5632. FileOutputStream::~FileOutputStream()
  5633. {
  5634. flush();
  5635. juce_fileClose (fileHandle);
  5636. }
  5637. int64 FileOutputStream::getPosition()
  5638. {
  5639. return currentPosition;
  5640. }
  5641. bool FileOutputStream::setPosition (int64 newPosition)
  5642. {
  5643. if (newPosition != currentPosition)
  5644. {
  5645. flush();
  5646. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5647. }
  5648. return newPosition == currentPosition;
  5649. }
  5650. void FileOutputStream::flush()
  5651. {
  5652. if (bytesInBuffer > 0)
  5653. {
  5654. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5655. bytesInBuffer = 0;
  5656. }
  5657. flushInternal();
  5658. }
  5659. bool FileOutputStream::write (const void* const src, const int numBytes)
  5660. {
  5661. if (bytesInBuffer + numBytes < bufferSize)
  5662. {
  5663. memcpy (buffer + bytesInBuffer, src, numBytes);
  5664. bytesInBuffer += numBytes;
  5665. currentPosition += numBytes;
  5666. }
  5667. else
  5668. {
  5669. if (bytesInBuffer > 0)
  5670. {
  5671. // flush the reservoir
  5672. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5673. bytesInBuffer = 0;
  5674. if (! wroteOk)
  5675. return false;
  5676. }
  5677. if (numBytes < bufferSize)
  5678. {
  5679. memcpy (buffer + bytesInBuffer, src, numBytes);
  5680. bytesInBuffer += numBytes;
  5681. currentPosition += numBytes;
  5682. }
  5683. else
  5684. {
  5685. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5686. currentPosition += bytesWritten;
  5687. return bytesWritten == numBytes;
  5688. }
  5689. }
  5690. return true;
  5691. }
  5692. END_JUCE_NAMESPACE
  5693. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5694. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5695. BEGIN_JUCE_NAMESPACE
  5696. FileSearchPath::FileSearchPath()
  5697. {
  5698. }
  5699. FileSearchPath::FileSearchPath (const String& path)
  5700. {
  5701. init (path);
  5702. }
  5703. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5704. : directories (other.directories)
  5705. {
  5706. }
  5707. FileSearchPath::~FileSearchPath()
  5708. {
  5709. }
  5710. FileSearchPath& FileSearchPath::operator= (const String& path)
  5711. {
  5712. init (path);
  5713. return *this;
  5714. }
  5715. void FileSearchPath::init (const String& path)
  5716. {
  5717. directories.clear();
  5718. directories.addTokens (path, ";", "\"");
  5719. directories.trim();
  5720. directories.removeEmptyStrings();
  5721. for (int i = directories.size(); --i >= 0;)
  5722. directories.set (i, directories[i].unquoted());
  5723. }
  5724. int FileSearchPath::getNumPaths() const
  5725. {
  5726. return directories.size();
  5727. }
  5728. const File FileSearchPath::operator[] (const int index) const
  5729. {
  5730. return File (directories [index]);
  5731. }
  5732. const String FileSearchPath::toString() const
  5733. {
  5734. StringArray directories2 (directories);
  5735. for (int i = directories2.size(); --i >= 0;)
  5736. if (directories2[i].containsChar (';'))
  5737. directories2.set (i, directories2[i].quoted());
  5738. return directories2.joinIntoString (";");
  5739. }
  5740. void FileSearchPath::add (const File& dir, const int insertIndex)
  5741. {
  5742. directories.insert (insertIndex, dir.getFullPathName());
  5743. }
  5744. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5745. {
  5746. for (int i = 0; i < directories.size(); ++i)
  5747. if (File (directories[i]) == dir)
  5748. return;
  5749. add (dir);
  5750. }
  5751. void FileSearchPath::remove (const int index)
  5752. {
  5753. directories.remove (index);
  5754. }
  5755. void FileSearchPath::addPath (const FileSearchPath& other)
  5756. {
  5757. for (int i = 0; i < other.getNumPaths(); ++i)
  5758. addIfNotAlreadyThere (other[i]);
  5759. }
  5760. void FileSearchPath::removeRedundantPaths()
  5761. {
  5762. for (int i = directories.size(); --i >= 0;)
  5763. {
  5764. const File d1 (directories[i]);
  5765. for (int j = directories.size(); --j >= 0;)
  5766. {
  5767. const File d2 (directories[j]);
  5768. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5769. {
  5770. directories.remove (i);
  5771. break;
  5772. }
  5773. }
  5774. }
  5775. }
  5776. void FileSearchPath::removeNonExistentPaths()
  5777. {
  5778. for (int i = directories.size(); --i >= 0;)
  5779. if (! File (directories[i]).isDirectory())
  5780. directories.remove (i);
  5781. }
  5782. int FileSearchPath::findChildFiles (Array<File>& results,
  5783. const int whatToLookFor,
  5784. const bool searchRecursively,
  5785. const String& wildCardPattern) const
  5786. {
  5787. int total = 0;
  5788. for (int i = 0; i < directories.size(); ++i)
  5789. total += operator[] (i).findChildFiles (results,
  5790. whatToLookFor,
  5791. searchRecursively,
  5792. wildCardPattern);
  5793. return total;
  5794. }
  5795. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5796. const bool checkRecursively) const
  5797. {
  5798. for (int i = directories.size(); --i >= 0;)
  5799. {
  5800. const File d (directories[i]);
  5801. if (checkRecursively)
  5802. {
  5803. if (fileToCheck.isAChildOf (d))
  5804. return true;
  5805. }
  5806. else
  5807. {
  5808. if (fileToCheck.getParentDirectory() == d)
  5809. return true;
  5810. }
  5811. }
  5812. return false;
  5813. }
  5814. END_JUCE_NAMESPACE
  5815. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5816. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5817. BEGIN_JUCE_NAMESPACE
  5818. NamedPipe::NamedPipe()
  5819. : internal (0)
  5820. {
  5821. }
  5822. NamedPipe::~NamedPipe()
  5823. {
  5824. close();
  5825. }
  5826. bool NamedPipe::openExisting (const String& pipeName)
  5827. {
  5828. currentPipeName = pipeName;
  5829. return openInternal (pipeName, false);
  5830. }
  5831. bool NamedPipe::createNewPipe (const String& pipeName)
  5832. {
  5833. currentPipeName = pipeName;
  5834. return openInternal (pipeName, true);
  5835. }
  5836. bool NamedPipe::isOpen() const
  5837. {
  5838. return internal != 0;
  5839. }
  5840. const String NamedPipe::getName() const
  5841. {
  5842. return currentPipeName;
  5843. }
  5844. // other methods for this class are implemented in the platform-specific files
  5845. END_JUCE_NAMESPACE
  5846. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5847. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5848. BEGIN_JUCE_NAMESPACE
  5849. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5850. {
  5851. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5852. "temp_" + String (Random::getSystemRandom().nextInt()),
  5853. suffix,
  5854. optionFlags);
  5855. }
  5856. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5857. : targetFile (targetFile_)
  5858. {
  5859. // If you use this constructor, you need to give it a valid target file!
  5860. jassert (targetFile != File::nonexistent);
  5861. createTempFile (targetFile.getParentDirectory(),
  5862. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5863. targetFile.getFileExtension(),
  5864. optionFlags);
  5865. }
  5866. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5867. const String& suffix, const int optionFlags)
  5868. {
  5869. if ((optionFlags & useHiddenFile) != 0)
  5870. name = "." + name;
  5871. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5872. }
  5873. TemporaryFile::~TemporaryFile()
  5874. {
  5875. // Have a few attempts at deleting the file before giving up..
  5876. for (int i = 5; --i >= 0;)
  5877. {
  5878. if (temporaryFile.deleteFile())
  5879. return;
  5880. Thread::sleep (50);
  5881. }
  5882. // Failed to delete our temporary file! Check that you've deleted all the
  5883. // file output streams that were using it!
  5884. jassertfalse;
  5885. }
  5886. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5887. {
  5888. // This method only works if you created this object with the constructor
  5889. // that takes a target file!
  5890. jassert (targetFile != File::nonexistent);
  5891. if (temporaryFile.exists())
  5892. {
  5893. // Have a few attempts at overwriting the file before giving up..
  5894. for (int i = 5; --i >= 0;)
  5895. {
  5896. if (temporaryFile.moveFileTo (targetFile))
  5897. return true;
  5898. Thread::sleep (100);
  5899. }
  5900. }
  5901. else
  5902. {
  5903. // There's no temporary file to use. If your write failed, you should
  5904. // probably check, and not bother calling this method.
  5905. jassertfalse;
  5906. }
  5907. return false;
  5908. }
  5909. END_JUCE_NAMESPACE
  5910. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5911. /*** Start of inlined file: juce_Socket.cpp ***/
  5912. #if JUCE_WINDOWS
  5913. #include <winsock2.h>
  5914. #if JUCE_MSVC
  5915. #pragma warning (push)
  5916. #pragma warning (disable : 4127 4389 4018)
  5917. #endif
  5918. #else
  5919. #if JUCE_LINUX
  5920. #include <sys/types.h>
  5921. #include <sys/socket.h>
  5922. #include <sys/errno.h>
  5923. #include <unistd.h>
  5924. #include <netinet/in.h>
  5925. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IPHONE
  5926. #include <CoreServices/CoreServices.h>
  5927. #endif
  5928. #include <fcntl.h>
  5929. #include <netdb.h>
  5930. #include <arpa/inet.h>
  5931. #include <netinet/tcp.h>
  5932. #endif
  5933. BEGIN_JUCE_NAMESPACE
  5934. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IPHONE)
  5935. typedef socklen_t juce_socklen_t;
  5936. #else
  5937. typedef int juce_socklen_t;
  5938. #endif
  5939. #if JUCE_WINDOWS
  5940. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5941. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5942. static void initWin32Sockets()
  5943. {
  5944. static CriticalSection lock;
  5945. const ScopedLock sl (lock);
  5946. if (juce_CloseWin32SocketLib == 0)
  5947. {
  5948. WSADATA wsaData;
  5949. const WORD wVersionRequested = MAKEWORD (1, 1);
  5950. WSAStartup (wVersionRequested, &wsaData);
  5951. juce_CloseWin32SocketLib = &WSACleanup;
  5952. }
  5953. }
  5954. #endif
  5955. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5956. {
  5957. const int sndBufSize = 65536;
  5958. const int rcvBufSize = 65536;
  5959. const int one = 1;
  5960. return handle > 0
  5961. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5962. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5963. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5964. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5965. }
  5966. static bool bindSocketToPort (const int handle, const int port) throw()
  5967. {
  5968. if (handle <= 0 || port <= 0)
  5969. return false;
  5970. struct sockaddr_in servTmpAddr;
  5971. zerostruct (servTmpAddr);
  5972. servTmpAddr.sin_family = PF_INET;
  5973. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5974. servTmpAddr.sin_port = htons ((uint16) port);
  5975. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5976. }
  5977. static int readSocket (const int handle,
  5978. void* const destBuffer, const int maxBytesToRead,
  5979. bool volatile& connected,
  5980. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5981. {
  5982. int bytesRead = 0;
  5983. while (bytesRead < maxBytesToRead)
  5984. {
  5985. int bytesThisTime;
  5986. #if JUCE_WINDOWS
  5987. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  5988. #else
  5989. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  5990. && errno == EINTR
  5991. && connected)
  5992. {
  5993. }
  5994. #endif
  5995. if (bytesThisTime <= 0 || ! connected)
  5996. {
  5997. if (bytesRead == 0)
  5998. bytesRead = -1;
  5999. break;
  6000. }
  6001. bytesRead += bytesThisTime;
  6002. if (! blockUntilSpecifiedAmountHasArrived)
  6003. break;
  6004. }
  6005. return bytesRead;
  6006. }
  6007. static int waitForReadiness (const int handle, const bool forReading,
  6008. const int timeoutMsecs) throw()
  6009. {
  6010. struct timeval timeout;
  6011. struct timeval* timeoutp;
  6012. if (timeoutMsecs >= 0)
  6013. {
  6014. timeout.tv_sec = timeoutMsecs / 1000;
  6015. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6016. timeoutp = &timeout;
  6017. }
  6018. else
  6019. {
  6020. timeoutp = 0;
  6021. }
  6022. fd_set rset, wset;
  6023. FD_ZERO (&rset);
  6024. FD_SET (handle, &rset);
  6025. FD_ZERO (&wset);
  6026. FD_SET (handle, &wset);
  6027. fd_set* const prset = forReading ? &rset : 0;
  6028. fd_set* const pwset = forReading ? 0 : &wset;
  6029. #if JUCE_WINDOWS
  6030. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6031. return -1;
  6032. #else
  6033. {
  6034. int result;
  6035. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6036. && errno == EINTR)
  6037. {
  6038. }
  6039. if (result < 0)
  6040. return -1;
  6041. }
  6042. #endif
  6043. {
  6044. int opt;
  6045. juce_socklen_t len = sizeof (opt);
  6046. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6047. || opt != 0)
  6048. return -1;
  6049. }
  6050. if ((forReading && FD_ISSET (handle, &rset))
  6051. || ((! forReading) && FD_ISSET (handle, &wset)))
  6052. return 1;
  6053. return 0;
  6054. }
  6055. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6056. {
  6057. #if JUCE_WINDOWS
  6058. u_long nonBlocking = shouldBlock ? 0 : 1;
  6059. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6060. return false;
  6061. #else
  6062. int socketFlags = fcntl (handle, F_GETFL, 0);
  6063. if (socketFlags == -1)
  6064. return false;
  6065. if (shouldBlock)
  6066. socketFlags &= ~O_NONBLOCK;
  6067. else
  6068. socketFlags |= O_NONBLOCK;
  6069. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6070. return false;
  6071. #endif
  6072. return true;
  6073. }
  6074. static bool connectSocket (int volatile& handle,
  6075. const bool isDatagram,
  6076. void** serverAddress,
  6077. const String& hostName,
  6078. const int portNumber,
  6079. const int timeOutMillisecs) throw()
  6080. {
  6081. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6082. if (hostEnt == 0)
  6083. return false;
  6084. struct in_addr targetAddress;
  6085. memcpy (&targetAddress.s_addr,
  6086. *(hostEnt->h_addr_list),
  6087. sizeof (targetAddress.s_addr));
  6088. struct sockaddr_in servTmpAddr;
  6089. zerostruct (servTmpAddr);
  6090. servTmpAddr.sin_family = PF_INET;
  6091. servTmpAddr.sin_addr = targetAddress;
  6092. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6093. if (handle < 0)
  6094. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6095. if (handle < 0)
  6096. return false;
  6097. if (isDatagram)
  6098. {
  6099. *serverAddress = new struct sockaddr_in();
  6100. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6101. return true;
  6102. }
  6103. setSocketBlockingState (handle, false);
  6104. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6105. if (result < 0)
  6106. {
  6107. #if JUCE_WINDOWS
  6108. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6109. #else
  6110. if (errno == EINPROGRESS)
  6111. #endif
  6112. {
  6113. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6114. {
  6115. setSocketBlockingState (handle, true);
  6116. return false;
  6117. }
  6118. }
  6119. }
  6120. setSocketBlockingState (handle, true);
  6121. resetSocketOptions (handle, false, false);
  6122. return true;
  6123. }
  6124. StreamingSocket::StreamingSocket()
  6125. : portNumber (0),
  6126. handle (-1),
  6127. connected (false),
  6128. isListener (false)
  6129. {
  6130. #if JUCE_WINDOWS
  6131. initWin32Sockets();
  6132. #endif
  6133. }
  6134. StreamingSocket::StreamingSocket (const String& hostName_,
  6135. const int portNumber_,
  6136. const int handle_)
  6137. : hostName (hostName_),
  6138. portNumber (portNumber_),
  6139. handle (handle_),
  6140. connected (true),
  6141. isListener (false)
  6142. {
  6143. #if JUCE_WINDOWS
  6144. initWin32Sockets();
  6145. #endif
  6146. resetSocketOptions (handle_, false, false);
  6147. }
  6148. StreamingSocket::~StreamingSocket()
  6149. {
  6150. close();
  6151. }
  6152. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6153. {
  6154. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6155. : -1;
  6156. }
  6157. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6158. {
  6159. if (isListener || ! connected)
  6160. return -1;
  6161. #if JUCE_WINDOWS
  6162. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6163. #else
  6164. int result;
  6165. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6166. && errno == EINTR)
  6167. {
  6168. }
  6169. return result;
  6170. #endif
  6171. }
  6172. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6173. const int timeoutMsecs) const
  6174. {
  6175. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6176. : -1;
  6177. }
  6178. bool StreamingSocket::bindToPort (const int port)
  6179. {
  6180. return bindSocketToPort (handle, port);
  6181. }
  6182. bool StreamingSocket::connect (const String& remoteHostName,
  6183. const int remotePortNumber,
  6184. const int timeOutMillisecs)
  6185. {
  6186. if (isListener)
  6187. {
  6188. jassertfalse; // a listener socket can't connect to another one!
  6189. return false;
  6190. }
  6191. if (connected)
  6192. close();
  6193. hostName = remoteHostName;
  6194. portNumber = remotePortNumber;
  6195. isListener = false;
  6196. connected = connectSocket (handle, false, 0, remoteHostName,
  6197. remotePortNumber, timeOutMillisecs);
  6198. if (! (connected && resetSocketOptions (handle, false, false)))
  6199. {
  6200. close();
  6201. return false;
  6202. }
  6203. return true;
  6204. }
  6205. void StreamingSocket::close()
  6206. {
  6207. #if JUCE_WINDOWS
  6208. if (handle != SOCKET_ERROR || connected)
  6209. closesocket (handle);
  6210. connected = false;
  6211. #else
  6212. if (connected)
  6213. {
  6214. connected = false;
  6215. if (isListener)
  6216. {
  6217. // need to do this to interrupt the accept() function..
  6218. StreamingSocket temp;
  6219. temp.connect ("localhost", portNumber, 1000);
  6220. }
  6221. }
  6222. if (handle != -1)
  6223. ::close (handle);
  6224. #endif
  6225. hostName = String::empty;
  6226. portNumber = 0;
  6227. handle = -1;
  6228. isListener = false;
  6229. }
  6230. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6231. {
  6232. if (connected)
  6233. close();
  6234. hostName = "listener";
  6235. portNumber = newPortNumber;
  6236. isListener = true;
  6237. struct sockaddr_in servTmpAddr;
  6238. zerostruct (servTmpAddr);
  6239. servTmpAddr.sin_family = PF_INET;
  6240. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6241. if (localHostName.isNotEmpty())
  6242. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6243. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6244. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6245. if (handle < 0)
  6246. return false;
  6247. const int reuse = 1;
  6248. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6249. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6250. || listen (handle, SOMAXCONN) < 0)
  6251. {
  6252. close();
  6253. return false;
  6254. }
  6255. connected = true;
  6256. return true;
  6257. }
  6258. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6259. {
  6260. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6261. // prepare this socket as a listener.
  6262. if (connected && isListener)
  6263. {
  6264. struct sockaddr address;
  6265. juce_socklen_t len = sizeof (sockaddr);
  6266. const int newSocket = (int) accept (handle, &address, &len);
  6267. if (newSocket >= 0 && connected)
  6268. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6269. portNumber, newSocket);
  6270. }
  6271. return 0;
  6272. }
  6273. bool StreamingSocket::isLocal() const throw()
  6274. {
  6275. return hostName == "127.0.0.1";
  6276. }
  6277. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6278. : portNumber (0),
  6279. handle (-1),
  6280. connected (true),
  6281. allowBroadcast (allowBroadcast_),
  6282. serverAddress (0)
  6283. {
  6284. #if JUCE_WINDOWS
  6285. initWin32Sockets();
  6286. #endif
  6287. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6288. bindToPort (localPortNumber);
  6289. }
  6290. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6291. const int handle_, const int localPortNumber)
  6292. : hostName (hostName_),
  6293. portNumber (portNumber_),
  6294. handle (handle_),
  6295. connected (true),
  6296. allowBroadcast (false),
  6297. serverAddress (0)
  6298. {
  6299. #if JUCE_WINDOWS
  6300. initWin32Sockets();
  6301. #endif
  6302. resetSocketOptions (handle_, true, allowBroadcast);
  6303. bindToPort (localPortNumber);
  6304. }
  6305. DatagramSocket::~DatagramSocket()
  6306. {
  6307. close();
  6308. delete ((struct sockaddr_in*) serverAddress);
  6309. serverAddress = 0;
  6310. }
  6311. void DatagramSocket::close()
  6312. {
  6313. #if JUCE_WINDOWS
  6314. closesocket (handle);
  6315. connected = false;
  6316. #else
  6317. connected = false;
  6318. ::close (handle);
  6319. #endif
  6320. hostName = String::empty;
  6321. portNumber = 0;
  6322. handle = -1;
  6323. }
  6324. bool DatagramSocket::bindToPort (const int port)
  6325. {
  6326. return bindSocketToPort (handle, port);
  6327. }
  6328. bool DatagramSocket::connect (const String& remoteHostName,
  6329. const int remotePortNumber,
  6330. const int timeOutMillisecs)
  6331. {
  6332. if (connected)
  6333. close();
  6334. hostName = remoteHostName;
  6335. portNumber = remotePortNumber;
  6336. connected = connectSocket (handle, true, &serverAddress,
  6337. remoteHostName, remotePortNumber,
  6338. timeOutMillisecs);
  6339. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6340. {
  6341. close();
  6342. return false;
  6343. }
  6344. return true;
  6345. }
  6346. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6347. {
  6348. struct sockaddr address;
  6349. juce_socklen_t len = sizeof (sockaddr);
  6350. while (waitUntilReady (true, -1) == 1)
  6351. {
  6352. char buf[1];
  6353. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6354. {
  6355. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6356. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6357. -1, -1);
  6358. }
  6359. }
  6360. return 0;
  6361. }
  6362. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6363. const int timeoutMsecs) const
  6364. {
  6365. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6366. : -1;
  6367. }
  6368. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6369. {
  6370. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6371. : -1;
  6372. }
  6373. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6374. {
  6375. // You need to call connect() first to set the server address..
  6376. jassert (serverAddress != 0 && connected);
  6377. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6378. numBytesToWrite, 0,
  6379. (const struct sockaddr*) serverAddress,
  6380. sizeof (struct sockaddr_in))
  6381. : -1;
  6382. }
  6383. bool DatagramSocket::isLocal() const throw()
  6384. {
  6385. return hostName == "127.0.0.1";
  6386. }
  6387. #if JUCE_MSVC
  6388. #pragma warning (pop)
  6389. #endif
  6390. END_JUCE_NAMESPACE
  6391. /*** End of inlined file: juce_Socket.cpp ***/
  6392. /*** Start of inlined file: juce_URL.cpp ***/
  6393. BEGIN_JUCE_NAMESPACE
  6394. URL::URL()
  6395. {
  6396. }
  6397. URL::URL (const String& url_)
  6398. : url (url_)
  6399. {
  6400. int i = url.indexOfChar ('?');
  6401. if (i >= 0)
  6402. {
  6403. do
  6404. {
  6405. const int nextAmp = url.indexOfChar (i + 1, '&');
  6406. const int equalsPos = url.indexOfChar (i + 1, '=');
  6407. if (equalsPos > i + 1)
  6408. {
  6409. if (nextAmp < 0)
  6410. {
  6411. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6412. removeEscapeChars (url.substring (equalsPos + 1)));
  6413. }
  6414. else if (nextAmp > 0 && equalsPos < nextAmp)
  6415. {
  6416. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6417. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6418. }
  6419. }
  6420. i = nextAmp;
  6421. }
  6422. while (i >= 0);
  6423. url = url.upToFirstOccurrenceOf ("?", false, false);
  6424. }
  6425. }
  6426. URL::URL (const URL& other)
  6427. : url (other.url),
  6428. postData (other.postData),
  6429. parameters (other.parameters),
  6430. filesToUpload (other.filesToUpload),
  6431. mimeTypes (other.mimeTypes)
  6432. {
  6433. }
  6434. URL& URL::operator= (const URL& other)
  6435. {
  6436. url = other.url;
  6437. postData = other.postData;
  6438. parameters = other.parameters;
  6439. filesToUpload = other.filesToUpload;
  6440. mimeTypes = other.mimeTypes;
  6441. return *this;
  6442. }
  6443. URL::~URL()
  6444. {
  6445. }
  6446. static const String getMangledParameters (const StringPairArray& parameters)
  6447. {
  6448. String p;
  6449. for (int i = 0; i < parameters.size(); ++i)
  6450. {
  6451. if (i > 0)
  6452. p += '&';
  6453. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6454. << '='
  6455. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6456. }
  6457. return p;
  6458. }
  6459. const String URL::toString (const bool includeGetParameters) const
  6460. {
  6461. if (includeGetParameters && parameters.size() > 0)
  6462. return url + "?" + getMangledParameters (parameters);
  6463. else
  6464. return url;
  6465. }
  6466. bool URL::isWellFormed() const
  6467. {
  6468. //xxx TODO
  6469. return url.isNotEmpty();
  6470. }
  6471. static int findStartOfDomain (const String& url)
  6472. {
  6473. int i = 0;
  6474. while (CharacterFunctions::isLetterOrDigit (url[i])
  6475. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6476. ++i;
  6477. return url[i] == ':' ? i + 1 : 0;
  6478. }
  6479. const String URL::getDomain() const
  6480. {
  6481. int start = findStartOfDomain (url);
  6482. while (url[start] == '/')
  6483. ++start;
  6484. const int end1 = url.indexOfChar (start, '/');
  6485. const int end2 = url.indexOfChar (start, ':');
  6486. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6487. : jmin (end1, end2);
  6488. return url.substring (start, end);
  6489. }
  6490. const String URL::getSubPath() const
  6491. {
  6492. int start = findStartOfDomain (url);
  6493. while (url[start] == '/')
  6494. ++start;
  6495. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6496. return startOfPath <= 0 ? String::empty
  6497. : url.substring (startOfPath);
  6498. }
  6499. const String URL::getScheme() const
  6500. {
  6501. return url.substring (0, findStartOfDomain (url) - 1);
  6502. }
  6503. const URL URL::withNewSubPath (const String& newPath) const
  6504. {
  6505. int start = findStartOfDomain (url);
  6506. while (url[start] == '/')
  6507. ++start;
  6508. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6509. URL u (*this);
  6510. if (startOfPath > 0)
  6511. u.url = url.substring (0, startOfPath);
  6512. if (! u.url.endsWithChar ('/'))
  6513. u.url << '/';
  6514. if (newPath.startsWithChar ('/'))
  6515. u.url << newPath.substring (1);
  6516. else
  6517. u.url << newPath;
  6518. return u;
  6519. }
  6520. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6521. {
  6522. if (possibleURL.startsWithIgnoreCase ("http:")
  6523. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6524. return true;
  6525. if (possibleURL.startsWithIgnoreCase ("file:")
  6526. || possibleURL.containsChar ('@')
  6527. || possibleURL.endsWithChar ('.')
  6528. || (! possibleURL.containsChar ('.')))
  6529. return false;
  6530. if (possibleURL.startsWithIgnoreCase ("www.")
  6531. && possibleURL.substring (5).containsChar ('.'))
  6532. return true;
  6533. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6534. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6535. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6536. return true;
  6537. return false;
  6538. }
  6539. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6540. {
  6541. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6542. return atSign > 0
  6543. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6544. && (! possibleEmailAddress.endsWithChar ('.'));
  6545. }
  6546. void* juce_openInternetFile (const String& url,
  6547. const String& headers,
  6548. const MemoryBlock& optionalPostData,
  6549. const bool isPost,
  6550. URL::OpenStreamProgressCallback* callback,
  6551. void* callbackContext,
  6552. int timeOutMs);
  6553. void juce_closeInternetFile (void* handle);
  6554. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6555. int juce_seekInInternetFile (void* handle, int newPosition);
  6556. int64 juce_getInternetFileContentLength (void* handle);
  6557. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  6558. class WebInputStream : public InputStream
  6559. {
  6560. public:
  6561. WebInputStream (const URL& url,
  6562. const bool isPost_,
  6563. URL::OpenStreamProgressCallback* const progressCallback_,
  6564. void* const progressCallbackContext_,
  6565. const String& extraHeaders,
  6566. const int timeOutMs_,
  6567. StringPairArray* const responseHeaders)
  6568. : position (0),
  6569. finished (false),
  6570. isPost (isPost_),
  6571. progressCallback (progressCallback_),
  6572. progressCallbackContext (progressCallbackContext_),
  6573. timeOutMs (timeOutMs_)
  6574. {
  6575. server = url.toString (! isPost);
  6576. if (isPost_)
  6577. createHeadersAndPostData (url);
  6578. headers += extraHeaders;
  6579. if (! headers.endsWithChar ('\n'))
  6580. headers << "\r\n";
  6581. handle = juce_openInternetFile (server, headers, postData, isPost,
  6582. progressCallback_, progressCallbackContext_,
  6583. timeOutMs);
  6584. if (responseHeaders != 0)
  6585. juce_getInternetFileHeaders (handle, *responseHeaders);
  6586. }
  6587. ~WebInputStream()
  6588. {
  6589. juce_closeInternetFile (handle);
  6590. }
  6591. bool isError() const { return handle == 0; }
  6592. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6593. bool isExhausted() { return finished; }
  6594. int64 getPosition() { return position; }
  6595. int read (void* dest, int bytes)
  6596. {
  6597. if (finished || isError())
  6598. {
  6599. return 0;
  6600. }
  6601. else
  6602. {
  6603. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6604. position += bytesRead;
  6605. if (bytesRead == 0)
  6606. finished = true;
  6607. return bytesRead;
  6608. }
  6609. }
  6610. bool setPosition (int64 wantedPos)
  6611. {
  6612. if (wantedPos != position)
  6613. {
  6614. finished = false;
  6615. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6616. if (actualPos == wantedPos)
  6617. {
  6618. position = wantedPos;
  6619. }
  6620. else
  6621. {
  6622. if (wantedPos < position)
  6623. {
  6624. juce_closeInternetFile (handle);
  6625. position = 0;
  6626. finished = false;
  6627. handle = juce_openInternetFile (server, headers, postData, isPost,
  6628. progressCallback, progressCallbackContext,
  6629. timeOutMs);
  6630. }
  6631. skipNextBytes (wantedPos - position);
  6632. }
  6633. }
  6634. return true;
  6635. }
  6636. juce_UseDebuggingNewOperator
  6637. private:
  6638. String server, headers;
  6639. MemoryBlock postData;
  6640. int64 position;
  6641. bool finished;
  6642. const bool isPost;
  6643. void* handle;
  6644. URL::OpenStreamProgressCallback* const progressCallback;
  6645. void* const progressCallbackContext;
  6646. const int timeOutMs;
  6647. void createHeadersAndPostData (const URL& url)
  6648. {
  6649. MemoryOutputStream data (256, 256, &postData);
  6650. if (url.getFilesToUpload().size() > 0)
  6651. {
  6652. // need to upload some files, so do it as multi-part...
  6653. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6654. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6655. data << "--" << boundary;
  6656. int i;
  6657. for (i = 0; i < url.getParameters().size(); ++i)
  6658. {
  6659. data << "\r\nContent-Disposition: form-data; name=\""
  6660. << url.getParameters().getAllKeys() [i]
  6661. << "\"\r\n\r\n"
  6662. << url.getParameters().getAllValues() [i]
  6663. << "\r\n--"
  6664. << boundary;
  6665. }
  6666. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6667. {
  6668. const File file (url.getFilesToUpload().getAllValues() [i]);
  6669. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6670. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6671. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6672. const String mimeType (url.getMimeTypesOfUploadFiles()
  6673. .getValue (paramName, String::empty));
  6674. if (mimeType.isNotEmpty())
  6675. data << "Content-Type: " << mimeType << "\r\n";
  6676. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6677. << file << "\r\n--" << boundary;
  6678. }
  6679. data << "--\r\n";
  6680. }
  6681. else
  6682. {
  6683. data << getMangledParameters (url.getParameters())
  6684. << url.getPostData();
  6685. // just a short text attachment, so use simple url encoding..
  6686. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6687. + String ((unsigned int) postData.getSize())
  6688. + "\r\n";
  6689. }
  6690. }
  6691. WebInputStream (const WebInputStream&);
  6692. WebInputStream& operator= (const WebInputStream&);
  6693. };
  6694. InputStream* URL::createInputStream (const bool usePostCommand,
  6695. OpenStreamProgressCallback* const progressCallback,
  6696. void* const progressCallbackContext,
  6697. const String& extraHeaders,
  6698. const int timeOutMs,
  6699. StringPairArray* const responseHeaders) const
  6700. {
  6701. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6702. progressCallback, progressCallbackContext,
  6703. extraHeaders, timeOutMs, responseHeaders));
  6704. return wi->isError() ? 0 : wi.release();
  6705. }
  6706. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6707. const bool usePostCommand) const
  6708. {
  6709. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6710. if (in != 0)
  6711. {
  6712. in->readIntoMemoryBlock (destData, -1);
  6713. return true;
  6714. }
  6715. return false;
  6716. }
  6717. const String URL::readEntireTextStream (const bool usePostCommand) const
  6718. {
  6719. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6720. if (in != 0)
  6721. return in->readEntireStreamAsString();
  6722. return String::empty;
  6723. }
  6724. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6725. {
  6726. XmlDocument doc (readEntireTextStream (usePostCommand));
  6727. return doc.getDocumentElement();
  6728. }
  6729. const URL URL::withParameter (const String& parameterName,
  6730. const String& parameterValue) const
  6731. {
  6732. URL u (*this);
  6733. u.parameters.set (parameterName, parameterValue);
  6734. return u;
  6735. }
  6736. const URL URL::withFileToUpload (const String& parameterName,
  6737. const File& fileToUpload,
  6738. const String& mimeType) const
  6739. {
  6740. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6741. URL u (*this);
  6742. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6743. u.mimeTypes.set (parameterName, mimeType);
  6744. return u;
  6745. }
  6746. const URL URL::withPOSTData (const String& postData_) const
  6747. {
  6748. URL u (*this);
  6749. u.postData = postData_;
  6750. return u;
  6751. }
  6752. const StringPairArray& URL::getParameters() const
  6753. {
  6754. return parameters;
  6755. }
  6756. const StringPairArray& URL::getFilesToUpload() const
  6757. {
  6758. return filesToUpload;
  6759. }
  6760. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6761. {
  6762. return mimeTypes;
  6763. }
  6764. const String URL::removeEscapeChars (const String& s)
  6765. {
  6766. String result (s.replaceCharacter ('+', ' '));
  6767. int nextPercent = 0;
  6768. for (;;)
  6769. {
  6770. nextPercent = result.indexOfChar (nextPercent, '%');
  6771. if (nextPercent < 0)
  6772. break;
  6773. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6774. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6775. ++nextPercent;
  6776. }
  6777. return result;
  6778. }
  6779. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6780. {
  6781. String result;
  6782. result.preallocateStorage (s.length() + 8);
  6783. const char* utf8 = s.toUTF8();
  6784. const char* legalChars = isParameter ? "_-.*!'()"
  6785. : "_-$.*!'(),";
  6786. while (*utf8 != 0)
  6787. {
  6788. const char c = *utf8++;
  6789. if (CharacterFunctions::isLetterOrDigit (c)
  6790. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6791. {
  6792. result << c;
  6793. }
  6794. else
  6795. {
  6796. const int v = (int) (uint8) c;
  6797. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6798. }
  6799. }
  6800. return result;
  6801. }
  6802. bool URL::launchInDefaultBrowser() const
  6803. {
  6804. String u (toString (true));
  6805. if (u.containsChar ('@') && ! u.containsChar (':'))
  6806. u = "mailto:" + u;
  6807. return PlatformUtilities::openDocument (u, String::empty);
  6808. }
  6809. END_JUCE_NAMESPACE
  6810. /*** End of inlined file: juce_URL.cpp ***/
  6811. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6812. BEGIN_JUCE_NAMESPACE
  6813. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6814. const int bufferSize_,
  6815. const bool deleteSourceWhenDestroyed)
  6816. : source (source_),
  6817. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6818. bufferSize (jmax (256, bufferSize_)),
  6819. position (source_->getPosition()),
  6820. lastReadPos (0),
  6821. bufferOverlap (128)
  6822. {
  6823. const int sourceSize = (int) source_->getTotalLength();
  6824. if (sourceSize >= 0)
  6825. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6826. bufferStart = position;
  6827. buffer.malloc (bufferSize);
  6828. }
  6829. BufferedInputStream::~BufferedInputStream()
  6830. {
  6831. }
  6832. int64 BufferedInputStream::getTotalLength()
  6833. {
  6834. return source->getTotalLength();
  6835. }
  6836. int64 BufferedInputStream::getPosition()
  6837. {
  6838. return position;
  6839. }
  6840. bool BufferedInputStream::setPosition (int64 newPosition)
  6841. {
  6842. position = jmax ((int64) 0, newPosition);
  6843. return true;
  6844. }
  6845. bool BufferedInputStream::isExhausted()
  6846. {
  6847. return (position >= lastReadPos)
  6848. && source->isExhausted();
  6849. }
  6850. void BufferedInputStream::ensureBuffered()
  6851. {
  6852. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6853. if (position < bufferStart || position >= bufferEndOverlap)
  6854. {
  6855. int bytesRead;
  6856. if (position < lastReadPos
  6857. && position >= bufferEndOverlap
  6858. && position >= bufferStart)
  6859. {
  6860. const int bytesToKeep = (int) (lastReadPos - position);
  6861. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6862. bufferStart = position;
  6863. bytesRead = source->read (buffer + bytesToKeep,
  6864. bufferSize - bytesToKeep);
  6865. lastReadPos += bytesRead;
  6866. bytesRead += bytesToKeep;
  6867. }
  6868. else
  6869. {
  6870. bufferStart = position;
  6871. source->setPosition (bufferStart);
  6872. bytesRead = source->read (buffer, bufferSize);
  6873. lastReadPos = bufferStart + bytesRead;
  6874. }
  6875. while (bytesRead < bufferSize)
  6876. buffer [bytesRead++] = 0;
  6877. }
  6878. }
  6879. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6880. {
  6881. if (position >= bufferStart
  6882. && position + maxBytesToRead <= lastReadPos)
  6883. {
  6884. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6885. position += maxBytesToRead;
  6886. return maxBytesToRead;
  6887. }
  6888. else
  6889. {
  6890. if (position < bufferStart || position >= lastReadPos)
  6891. ensureBuffered();
  6892. int bytesRead = 0;
  6893. while (maxBytesToRead > 0)
  6894. {
  6895. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6896. if (bytesAvailable > 0)
  6897. {
  6898. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6899. maxBytesToRead -= bytesAvailable;
  6900. bytesRead += bytesAvailable;
  6901. position += bytesAvailable;
  6902. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6903. }
  6904. const int64 oldLastReadPos = lastReadPos;
  6905. ensureBuffered();
  6906. if (oldLastReadPos == lastReadPos)
  6907. break; // if ensureBuffered() failed to read any more data, bail out
  6908. if (isExhausted())
  6909. break;
  6910. }
  6911. return bytesRead;
  6912. }
  6913. }
  6914. const String BufferedInputStream::readString()
  6915. {
  6916. if (position >= bufferStart
  6917. && position < lastReadPos)
  6918. {
  6919. const int maxChars = (int) (lastReadPos - position);
  6920. const char* const src = buffer + (int) (position - bufferStart);
  6921. for (int i = 0; i < maxChars; ++i)
  6922. {
  6923. if (src[i] == 0)
  6924. {
  6925. position += i + 1;
  6926. return String::fromUTF8 (src, i);
  6927. }
  6928. }
  6929. }
  6930. return InputStream::readString();
  6931. }
  6932. END_JUCE_NAMESPACE
  6933. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  6934. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  6935. BEGIN_JUCE_NAMESPACE
  6936. FileInputSource::FileInputSource (const File& file_)
  6937. : file (file_)
  6938. {
  6939. }
  6940. FileInputSource::~FileInputSource()
  6941. {
  6942. }
  6943. InputStream* FileInputSource::createInputStream()
  6944. {
  6945. return file.createInputStream();
  6946. }
  6947. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6948. {
  6949. return file.getSiblingFile (relatedItemPath).createInputStream();
  6950. }
  6951. int64 FileInputSource::hashCode() const
  6952. {
  6953. return file.hashCode();
  6954. }
  6955. END_JUCE_NAMESPACE
  6956. /*** End of inlined file: juce_FileInputSource.cpp ***/
  6957. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  6958. BEGIN_JUCE_NAMESPACE
  6959. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6960. const size_t sourceDataSize,
  6961. const bool keepInternalCopy)
  6962. : data (static_cast <const char*> (sourceData)),
  6963. dataSize (sourceDataSize),
  6964. position (0)
  6965. {
  6966. if (keepInternalCopy)
  6967. {
  6968. internalCopy.append (data, sourceDataSize);
  6969. data = static_cast <const char*> (internalCopy.getData());
  6970. }
  6971. }
  6972. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  6973. const bool keepInternalCopy)
  6974. : data (static_cast <const char*> (sourceData.getData())),
  6975. dataSize (sourceData.getSize()),
  6976. position (0)
  6977. {
  6978. if (keepInternalCopy)
  6979. {
  6980. internalCopy = sourceData;
  6981. data = static_cast <const char*> (internalCopy.getData());
  6982. }
  6983. }
  6984. MemoryInputStream::~MemoryInputStream()
  6985. {
  6986. }
  6987. int64 MemoryInputStream::getTotalLength()
  6988. {
  6989. return dataSize;
  6990. }
  6991. int MemoryInputStream::read (void* const buffer, const int howMany)
  6992. {
  6993. jassert (howMany >= 0);
  6994. const int num = jmin (howMany, (int) (dataSize - position));
  6995. memcpy (buffer, data + position, num);
  6996. position += num;
  6997. return (int) num;
  6998. }
  6999. bool MemoryInputStream::isExhausted()
  7000. {
  7001. return (position >= dataSize);
  7002. }
  7003. bool MemoryInputStream::setPosition (const int64 pos)
  7004. {
  7005. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7006. return true;
  7007. }
  7008. int64 MemoryInputStream::getPosition()
  7009. {
  7010. return position;
  7011. }
  7012. END_JUCE_NAMESPACE
  7013. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7014. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7015. BEGIN_JUCE_NAMESPACE
  7016. MemoryOutputStream::MemoryOutputStream (const size_t initialSize,
  7017. const size_t blockSizeToIncreaseBy,
  7018. MemoryBlock* const memoryBlockToWriteTo)
  7019. : data (memoryBlockToWriteTo),
  7020. position (0),
  7021. size (0),
  7022. blockSize (jmax ((size_t) 16, blockSizeToIncreaseBy))
  7023. {
  7024. if (data == 0)
  7025. dataToDelete = data = new MemoryBlock (initialSize);
  7026. else
  7027. data->setSize (initialSize, false);
  7028. }
  7029. MemoryOutputStream::~MemoryOutputStream()
  7030. {
  7031. flush();
  7032. }
  7033. void MemoryOutputStream::flush()
  7034. {
  7035. if (dataToDelete == 0)
  7036. data->setSize (size, false);
  7037. }
  7038. void MemoryOutputStream::reset() throw()
  7039. {
  7040. position = 0;
  7041. size = 0;
  7042. }
  7043. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7044. {
  7045. if (howMany > 0)
  7046. {
  7047. size_t storageNeeded = position + howMany;
  7048. if (storageNeeded >= data->getSize())
  7049. {
  7050. // if we need more space, increase the block by at least 10%..
  7051. storageNeeded += jmax (blockSize, storageNeeded / 10);
  7052. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  7053. data->ensureSize (storageNeeded);
  7054. }
  7055. data->copyFrom (buffer, (int) position, howMany);
  7056. position += howMany;
  7057. size = jmax (size, position);
  7058. }
  7059. return true;
  7060. }
  7061. const char* MemoryOutputStream::getData() const throw()
  7062. {
  7063. char* const d = static_cast <char*> (data->getData());
  7064. if (data->getSize() > size)
  7065. d [size] = 0;
  7066. return d;
  7067. }
  7068. bool MemoryOutputStream::setPosition (int64 newPosition)
  7069. {
  7070. if (newPosition <= (int64) size)
  7071. {
  7072. // ok to seek backwards
  7073. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7074. return true;
  7075. }
  7076. else
  7077. {
  7078. // trying to make it bigger isn't a good thing to do..
  7079. return false;
  7080. }
  7081. }
  7082. const String MemoryOutputStream::toUTF8() const
  7083. {
  7084. return String (getData(), getDataSize());
  7085. }
  7086. END_JUCE_NAMESPACE
  7087. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7088. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7089. BEGIN_JUCE_NAMESPACE
  7090. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7091. const int64 startPositionInSourceStream_,
  7092. const int64 lengthOfSourceStream_,
  7093. const bool deleteSourceWhenDestroyed)
  7094. : source (sourceStream),
  7095. startPositionInSourceStream (startPositionInSourceStream_),
  7096. lengthOfSourceStream (lengthOfSourceStream_)
  7097. {
  7098. if (deleteSourceWhenDestroyed)
  7099. sourceToDelete = source;
  7100. setPosition (0);
  7101. }
  7102. SubregionStream::~SubregionStream()
  7103. {
  7104. }
  7105. int64 SubregionStream::getTotalLength()
  7106. {
  7107. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7108. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7109. : srcLen;
  7110. }
  7111. int64 SubregionStream::getPosition()
  7112. {
  7113. return source->getPosition() - startPositionInSourceStream;
  7114. }
  7115. bool SubregionStream::setPosition (int64 newPosition)
  7116. {
  7117. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7118. }
  7119. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7120. {
  7121. if (lengthOfSourceStream < 0)
  7122. {
  7123. return source->read (destBuffer, maxBytesToRead);
  7124. }
  7125. else
  7126. {
  7127. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7128. if (maxBytesToRead <= 0)
  7129. return 0;
  7130. return source->read (destBuffer, maxBytesToRead);
  7131. }
  7132. }
  7133. bool SubregionStream::isExhausted()
  7134. {
  7135. if (lengthOfSourceStream >= 0)
  7136. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7137. else
  7138. return source->isExhausted();
  7139. }
  7140. END_JUCE_NAMESPACE
  7141. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7142. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7143. BEGIN_JUCE_NAMESPACE
  7144. PerformanceCounter::PerformanceCounter (const String& name_,
  7145. int runsPerPrintout,
  7146. const File& loggingFile)
  7147. : name (name_),
  7148. numRuns (0),
  7149. runsPerPrint (runsPerPrintout),
  7150. totalTime (0),
  7151. outputFile (loggingFile)
  7152. {
  7153. if (outputFile != File::nonexistent)
  7154. {
  7155. String s ("**** Counter for \"");
  7156. s << name_ << "\" started at: "
  7157. << Time::getCurrentTime().toString (true, true)
  7158. << "\r\n";
  7159. outputFile.appendText (s, false, false);
  7160. }
  7161. }
  7162. PerformanceCounter::~PerformanceCounter()
  7163. {
  7164. printStatistics();
  7165. }
  7166. void PerformanceCounter::start()
  7167. {
  7168. started = Time::getHighResolutionTicks();
  7169. }
  7170. void PerformanceCounter::stop()
  7171. {
  7172. const int64 now = Time::getHighResolutionTicks();
  7173. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7174. if (++numRuns == runsPerPrint)
  7175. printStatistics();
  7176. }
  7177. void PerformanceCounter::printStatistics()
  7178. {
  7179. if (numRuns > 0)
  7180. {
  7181. String s ("Performance count for \"");
  7182. s << name << "\" - average over " << numRuns << " run(s) = ";
  7183. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7184. if (micros > 10000)
  7185. s << (micros/1000) << " millisecs";
  7186. else
  7187. s << micros << " microsecs";
  7188. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7189. Logger::outputDebugString (s);
  7190. s << "\r\n";
  7191. if (outputFile != File::nonexistent)
  7192. outputFile.appendText (s, false, false);
  7193. numRuns = 0;
  7194. totalTime = 0;
  7195. }
  7196. }
  7197. END_JUCE_NAMESPACE
  7198. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7199. /*** Start of inlined file: juce_Uuid.cpp ***/
  7200. BEGIN_JUCE_NAMESPACE
  7201. Uuid::Uuid()
  7202. {
  7203. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7204. // to make it very very unlikely that two UUIDs will ever be the same..
  7205. static int64 macAddresses[2];
  7206. static bool hasCheckedMacAddresses = false;
  7207. if (! hasCheckedMacAddresses)
  7208. {
  7209. hasCheckedMacAddresses = true;
  7210. SystemStats::getMACAddresses (macAddresses, 2);
  7211. }
  7212. value.asInt64[0] = macAddresses[0];
  7213. value.asInt64[1] = macAddresses[1];
  7214. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7215. // whose seed will carry over between calls to this method.
  7216. Random r (macAddresses[0] ^ macAddresses[1]
  7217. ^ Random::getSystemRandom().nextInt64());
  7218. for (int i = 4; --i >= 0;)
  7219. {
  7220. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7221. value.asInt[i] ^= r.nextInt();
  7222. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7223. }
  7224. }
  7225. Uuid::~Uuid() throw()
  7226. {
  7227. }
  7228. Uuid::Uuid (const Uuid& other)
  7229. : value (other.value)
  7230. {
  7231. }
  7232. Uuid& Uuid::operator= (const Uuid& other)
  7233. {
  7234. value = other.value;
  7235. return *this;
  7236. }
  7237. bool Uuid::operator== (const Uuid& other) const
  7238. {
  7239. return value.asInt64[0] == other.value.asInt64[0]
  7240. && value.asInt64[1] == other.value.asInt64[1];
  7241. }
  7242. bool Uuid::operator!= (const Uuid& other) const
  7243. {
  7244. return ! operator== (other);
  7245. }
  7246. bool Uuid::isNull() const throw()
  7247. {
  7248. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7249. }
  7250. const String Uuid::toString() const
  7251. {
  7252. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7253. }
  7254. Uuid::Uuid (const String& uuidString)
  7255. {
  7256. operator= (uuidString);
  7257. }
  7258. Uuid& Uuid::operator= (const String& uuidString)
  7259. {
  7260. MemoryBlock mb;
  7261. mb.loadFromHexString (uuidString);
  7262. mb.ensureSize (sizeof (value.asBytes), true);
  7263. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7264. return *this;
  7265. }
  7266. Uuid::Uuid (const uint8* const rawData)
  7267. {
  7268. operator= (rawData);
  7269. }
  7270. Uuid& Uuid::operator= (const uint8* const rawData)
  7271. {
  7272. if (rawData != 0)
  7273. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7274. else
  7275. zeromem (value.asBytes, sizeof (value.asBytes));
  7276. return *this;
  7277. }
  7278. END_JUCE_NAMESPACE
  7279. /*** End of inlined file: juce_Uuid.cpp ***/
  7280. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7281. BEGIN_JUCE_NAMESPACE
  7282. class ZipFile::ZipEntryInfo
  7283. {
  7284. public:
  7285. ZipFile::ZipEntry entry;
  7286. int streamOffset;
  7287. int compressedSize;
  7288. bool compressed;
  7289. };
  7290. class ZipFile::ZipInputStream : public InputStream
  7291. {
  7292. public:
  7293. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7294. : file (file_),
  7295. zipEntryInfo (zei),
  7296. pos (0),
  7297. headerSize (0),
  7298. inputStream (0)
  7299. {
  7300. inputStream = file_.inputStream;
  7301. if (file_.inputSource != 0)
  7302. {
  7303. inputStream = file.inputSource->createInputStream();
  7304. }
  7305. else
  7306. {
  7307. #if JUCE_DEBUG
  7308. file_.numOpenStreams++;
  7309. #endif
  7310. }
  7311. char buffer [30];
  7312. if (inputStream != 0
  7313. && inputStream->setPosition (zei.streamOffset)
  7314. && inputStream->read (buffer, 30) == 30
  7315. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7316. {
  7317. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7318. + ByteOrder::littleEndianShort (buffer + 28);
  7319. }
  7320. }
  7321. ~ZipInputStream() throw()
  7322. {
  7323. #if JUCE_DEBUG
  7324. if (inputStream != 0 && inputStream == file.inputStream)
  7325. file.numOpenStreams--;
  7326. #endif
  7327. if (inputStream != file.inputStream)
  7328. delete inputStream;
  7329. }
  7330. int64 getTotalLength() throw()
  7331. {
  7332. return zipEntryInfo.compressedSize;
  7333. }
  7334. int read (void* buffer, int howMany) throw()
  7335. {
  7336. if (headerSize <= 0)
  7337. return 0;
  7338. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7339. if (inputStream == 0)
  7340. return 0;
  7341. int num;
  7342. if (inputStream == file.inputStream)
  7343. {
  7344. const ScopedLock sl (file.lock);
  7345. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7346. num = inputStream->read (buffer, howMany);
  7347. }
  7348. else
  7349. {
  7350. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7351. num = inputStream->read (buffer, howMany);
  7352. }
  7353. pos += num;
  7354. return num;
  7355. }
  7356. bool isExhausted() throw()
  7357. {
  7358. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7359. }
  7360. int64 getPosition() throw()
  7361. {
  7362. return pos;
  7363. }
  7364. bool setPosition (int64 newPos) throw()
  7365. {
  7366. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7367. return true;
  7368. }
  7369. private:
  7370. ZipFile& file;
  7371. ZipEntryInfo zipEntryInfo;
  7372. int64 pos;
  7373. int headerSize;
  7374. InputStream* inputStream;
  7375. ZipInputStream (const ZipInputStream&);
  7376. ZipInputStream& operator= (const ZipInputStream&);
  7377. };
  7378. ZipFile::ZipFile (InputStream* const source_,
  7379. const bool deleteStreamWhenDestroyed) throw()
  7380. : inputStream (source_)
  7381. #if JUCE_DEBUG
  7382. , numOpenStreams (0)
  7383. #endif
  7384. {
  7385. if (deleteStreamWhenDestroyed)
  7386. streamToDelete = inputStream;
  7387. init();
  7388. }
  7389. ZipFile::ZipFile (const File& file)
  7390. : inputStream (0)
  7391. #if JUCE_DEBUG
  7392. , numOpenStreams (0)
  7393. #endif
  7394. {
  7395. inputSource = new FileInputSource (file);
  7396. init();
  7397. }
  7398. ZipFile::ZipFile (InputSource* const inputSource_)
  7399. : inputStream (0),
  7400. inputSource (inputSource_)
  7401. #if JUCE_DEBUG
  7402. , numOpenStreams (0)
  7403. #endif
  7404. {
  7405. init();
  7406. }
  7407. ZipFile::~ZipFile() throw()
  7408. {
  7409. #if JUCE_DEBUG
  7410. entries.clear();
  7411. // If you hit this assertion, it means you've created a stream to read
  7412. // one of the items in the zipfile, but you've forgotten to delete that
  7413. // stream object before deleting the file.. Streams can't be kept open
  7414. // after the file is deleted because they need to share the input
  7415. // stream that the file uses to read itself.
  7416. jassert (numOpenStreams == 0);
  7417. #endif
  7418. }
  7419. int ZipFile::getNumEntries() const throw()
  7420. {
  7421. return entries.size();
  7422. }
  7423. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7424. {
  7425. ZipEntryInfo* const zei = entries [index];
  7426. return zei != 0 ? &(zei->entry) : 0;
  7427. }
  7428. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7429. {
  7430. for (int i = 0; i < entries.size(); ++i)
  7431. if (entries.getUnchecked (i)->entry.filename == fileName)
  7432. return i;
  7433. return -1;
  7434. }
  7435. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7436. {
  7437. return getEntry (getIndexOfFileName (fileName));
  7438. }
  7439. InputStream* ZipFile::createStreamForEntry (const int index)
  7440. {
  7441. ZipEntryInfo* const zei = entries[index];
  7442. InputStream* stream = 0;
  7443. if (zei != 0)
  7444. {
  7445. stream = new ZipInputStream (*this, *zei);
  7446. if (zei->compressed)
  7447. {
  7448. stream = new GZIPDecompressorInputStream (stream, true, true,
  7449. zei->entry.uncompressedSize);
  7450. // (much faster to unzip in big blocks using a buffer..)
  7451. stream = new BufferedInputStream (stream, 32768, true);
  7452. }
  7453. }
  7454. return stream;
  7455. }
  7456. class ZipFile::ZipFilenameComparator
  7457. {
  7458. public:
  7459. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7460. {
  7461. return first->entry.filename.compare (second->entry.filename);
  7462. }
  7463. };
  7464. void ZipFile::sortEntriesByFilename()
  7465. {
  7466. ZipFilenameComparator sorter;
  7467. entries.sort (sorter);
  7468. }
  7469. void ZipFile::init()
  7470. {
  7471. ScopedPointer <InputStream> toDelete;
  7472. InputStream* in = inputStream;
  7473. if (inputSource != 0)
  7474. {
  7475. in = inputSource->createInputStream();
  7476. toDelete = in;
  7477. }
  7478. if (in != 0)
  7479. {
  7480. int numEntries = 0;
  7481. int pos = findEndOfZipEntryTable (in, numEntries);
  7482. if (pos >= 0 && pos < in->getTotalLength())
  7483. {
  7484. const int size = (int) (in->getTotalLength() - pos);
  7485. in->setPosition (pos);
  7486. MemoryBlock headerData;
  7487. if (in->readIntoMemoryBlock (headerData, size) == size)
  7488. {
  7489. pos = 0;
  7490. for (int i = 0; i < numEntries; ++i)
  7491. {
  7492. if (pos + 46 > size)
  7493. break;
  7494. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7495. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7496. if (pos + 46 + fileNameLen > size)
  7497. break;
  7498. ZipEntryInfo* const zei = new ZipEntryInfo();
  7499. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7500. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7501. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7502. const int year = 1980 + (date >> 9);
  7503. const int month = ((date >> 5) & 15) - 1;
  7504. const int day = date & 31;
  7505. const int hours = time >> 11;
  7506. const int minutes = (time >> 5) & 63;
  7507. const int seconds = (time & 31) << 1;
  7508. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7509. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7510. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7511. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7512. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7513. entries.add (zei);
  7514. pos += 46 + fileNameLen
  7515. + ByteOrder::littleEndianShort (buffer + 30)
  7516. + ByteOrder::littleEndianShort (buffer + 32);
  7517. }
  7518. }
  7519. }
  7520. }
  7521. }
  7522. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7523. {
  7524. BufferedInputStream in (input, 8192, false);
  7525. in.setPosition (in.getTotalLength());
  7526. int64 pos = in.getPosition();
  7527. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7528. char buffer [32];
  7529. zeromem (buffer, sizeof (buffer));
  7530. while (pos > lowestPos)
  7531. {
  7532. in.setPosition (pos - 22);
  7533. pos = in.getPosition();
  7534. memcpy (buffer + 22, buffer, 4);
  7535. if (in.read (buffer, 22) != 22)
  7536. return 0;
  7537. for (int i = 0; i < 22; ++i)
  7538. {
  7539. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7540. {
  7541. in.setPosition (pos + i);
  7542. in.read (buffer, 22);
  7543. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7544. return ByteOrder::littleEndianInt (buffer + 16);
  7545. }
  7546. }
  7547. }
  7548. return 0;
  7549. }
  7550. void ZipFile::uncompressTo (const File& targetDirectory,
  7551. const bool shouldOverwriteFiles)
  7552. {
  7553. for (int i = 0; i < entries.size(); ++i)
  7554. {
  7555. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7556. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7557. if (zei.filename.endsWithChar ('/'))
  7558. {
  7559. targetFile.createDirectory(); // (entry is a directory, not a file)
  7560. }
  7561. else
  7562. {
  7563. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7564. if (in != 0)
  7565. {
  7566. if (shouldOverwriteFiles)
  7567. targetFile.deleteFile();
  7568. if ((! targetFile.exists())
  7569. && targetFile.getParentDirectory().createDirectory())
  7570. {
  7571. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7572. if (out != 0)
  7573. {
  7574. out->writeFromInputStream (*in, -1);
  7575. out = 0;
  7576. targetFile.setCreationTime (zei.fileTime);
  7577. targetFile.setLastModificationTime (zei.fileTime);
  7578. targetFile.setLastAccessTime (zei.fileTime);
  7579. }
  7580. }
  7581. }
  7582. }
  7583. }
  7584. }
  7585. END_JUCE_NAMESPACE
  7586. /*** End of inlined file: juce_ZipFile.cpp ***/
  7587. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7588. #if JUCE_MSVC
  7589. #pragma warning (push)
  7590. #pragma warning (disable: 4514 4996)
  7591. #endif
  7592. #include <cwctype>
  7593. #include <cctype>
  7594. #include <ctime>
  7595. BEGIN_JUCE_NAMESPACE
  7596. int CharacterFunctions::length (const char* const s) throw()
  7597. {
  7598. return (int) strlen (s);
  7599. }
  7600. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7601. {
  7602. return (int) wcslen (s);
  7603. }
  7604. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7605. {
  7606. strncpy (dest, src, maxChars);
  7607. }
  7608. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7609. {
  7610. wcsncpy (dest, src, maxChars);
  7611. }
  7612. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7613. {
  7614. mbstowcs (dest, src, maxChars);
  7615. }
  7616. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7617. {
  7618. wcstombs (dest, src, maxChars);
  7619. }
  7620. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7621. {
  7622. return (int) wcstombs (0, src, 0);
  7623. }
  7624. void CharacterFunctions::append (char* dest, const char* src) throw()
  7625. {
  7626. strcat (dest, src);
  7627. }
  7628. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7629. {
  7630. wcscat (dest, src);
  7631. }
  7632. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7633. {
  7634. return strcmp (s1, s2);
  7635. }
  7636. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7637. {
  7638. jassert (s1 != 0 && s2 != 0);
  7639. return wcscmp (s1, s2);
  7640. }
  7641. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7642. {
  7643. jassert (s1 != 0 && s2 != 0);
  7644. return strncmp (s1, s2, maxChars);
  7645. }
  7646. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7647. {
  7648. jassert (s1 != 0 && s2 != 0);
  7649. return wcsncmp (s1, s2, maxChars);
  7650. }
  7651. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7652. {
  7653. jassert (s1 != 0 && s2 != 0);
  7654. for (;;)
  7655. {
  7656. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7657. if (diff != 0)
  7658. return diff;
  7659. else if (*s1 == 0)
  7660. break;
  7661. ++s1;
  7662. ++s2;
  7663. }
  7664. return 0;
  7665. }
  7666. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7667. {
  7668. return -compare (s2, s1);
  7669. }
  7670. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7671. {
  7672. jassert (s1 != 0 && s2 != 0);
  7673. #if JUCE_WINDOWS
  7674. return stricmp (s1, s2);
  7675. #else
  7676. return strcasecmp (s1, s2);
  7677. #endif
  7678. }
  7679. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7680. {
  7681. jassert (s1 != 0 && s2 != 0);
  7682. #if JUCE_WINDOWS
  7683. return _wcsicmp (s1, s2);
  7684. #else
  7685. for (;;)
  7686. {
  7687. if (*s1 != *s2)
  7688. {
  7689. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7690. if (diff != 0)
  7691. return diff < 0 ? -1 : 1;
  7692. }
  7693. else if (*s1 == 0)
  7694. break;
  7695. ++s1;
  7696. ++s2;
  7697. }
  7698. return 0;
  7699. #endif
  7700. }
  7701. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7702. {
  7703. jassert (s1 != 0 && s2 != 0);
  7704. for (;;)
  7705. {
  7706. if (*s1 != *s2)
  7707. {
  7708. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7709. if (diff != 0)
  7710. return diff < 0 ? -1 : 1;
  7711. }
  7712. else if (*s1 == 0)
  7713. break;
  7714. ++s1;
  7715. ++s2;
  7716. }
  7717. return 0;
  7718. }
  7719. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7720. {
  7721. jassert (s1 != 0 && s2 != 0);
  7722. #if JUCE_WINDOWS
  7723. return strnicmp (s1, s2, maxChars);
  7724. #else
  7725. return strncasecmp (s1, s2, maxChars);
  7726. #endif
  7727. }
  7728. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7729. {
  7730. jassert (s1 != 0 && s2 != 0);
  7731. #if JUCE_WINDOWS
  7732. return _wcsnicmp (s1, s2, maxChars);
  7733. #else
  7734. while (--maxChars >= 0)
  7735. {
  7736. if (*s1 != *s2)
  7737. {
  7738. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7739. if (diff != 0)
  7740. return diff < 0 ? -1 : 1;
  7741. }
  7742. else if (*s1 == 0)
  7743. break;
  7744. ++s1;
  7745. ++s2;
  7746. }
  7747. return 0;
  7748. #endif
  7749. }
  7750. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7751. {
  7752. return strstr (haystack, needle);
  7753. }
  7754. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7755. {
  7756. return wcsstr (haystack, needle);
  7757. }
  7758. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7759. {
  7760. if (haystack != 0)
  7761. {
  7762. int i = 0;
  7763. if (ignoreCase)
  7764. {
  7765. const char n1 = toLowerCase (needle);
  7766. const char n2 = toUpperCase (needle);
  7767. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7768. {
  7769. while (haystack[i] != 0)
  7770. {
  7771. if (haystack[i] == n1 || haystack[i] == n2)
  7772. return i;
  7773. ++i;
  7774. }
  7775. return -1;
  7776. }
  7777. jassert (n1 == needle);
  7778. }
  7779. while (haystack[i] != 0)
  7780. {
  7781. if (haystack[i] == needle)
  7782. return i;
  7783. ++i;
  7784. }
  7785. }
  7786. return -1;
  7787. }
  7788. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7789. {
  7790. if (haystack != 0)
  7791. {
  7792. int i = 0;
  7793. if (ignoreCase)
  7794. {
  7795. const juce_wchar n1 = toLowerCase (needle);
  7796. const juce_wchar n2 = toUpperCase (needle);
  7797. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7798. {
  7799. while (haystack[i] != 0)
  7800. {
  7801. if (haystack[i] == n1 || haystack[i] == n2)
  7802. return i;
  7803. ++i;
  7804. }
  7805. return -1;
  7806. }
  7807. jassert (n1 == needle);
  7808. }
  7809. while (haystack[i] != 0)
  7810. {
  7811. if (haystack[i] == needle)
  7812. return i;
  7813. ++i;
  7814. }
  7815. }
  7816. return -1;
  7817. }
  7818. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7819. {
  7820. jassert (haystack != 0);
  7821. int i = 0;
  7822. while (haystack[i] != 0)
  7823. {
  7824. if (haystack[i] == needle)
  7825. return i;
  7826. ++i;
  7827. }
  7828. return -1;
  7829. }
  7830. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7831. {
  7832. jassert (haystack != 0);
  7833. int i = 0;
  7834. while (haystack[i] != 0)
  7835. {
  7836. if (haystack[i] == needle)
  7837. return i;
  7838. ++i;
  7839. }
  7840. return -1;
  7841. }
  7842. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7843. {
  7844. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7845. }
  7846. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7847. {
  7848. if (allowedChars == 0)
  7849. return 0;
  7850. int i = 0;
  7851. for (;;)
  7852. {
  7853. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7854. break;
  7855. ++i;
  7856. }
  7857. return i;
  7858. }
  7859. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7860. {
  7861. return (int) strftime (dest, maxChars, format, tm);
  7862. }
  7863. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7864. {
  7865. return (int) wcsftime (dest, maxChars, format, tm);
  7866. }
  7867. int CharacterFunctions::getIntValue (const char* const s) throw()
  7868. {
  7869. return atoi (s);
  7870. }
  7871. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7872. {
  7873. #if JUCE_WINDOWS
  7874. return _wtoi (s);
  7875. #else
  7876. int v = 0;
  7877. while (isWhitespace (*s))
  7878. ++s;
  7879. const bool isNeg = *s == '-';
  7880. if (isNeg)
  7881. ++s;
  7882. for (;;)
  7883. {
  7884. const wchar_t c = *s++;
  7885. if (c >= '0' && c <= '9')
  7886. v = v * 10 + (int) (c - '0');
  7887. else
  7888. break;
  7889. }
  7890. return isNeg ? -v : v;
  7891. #endif
  7892. }
  7893. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7894. {
  7895. #if JUCE_LINUX
  7896. return atoll (s);
  7897. #elif JUCE_WINDOWS
  7898. return _atoi64 (s);
  7899. #else
  7900. int64 v = 0;
  7901. while (isWhitespace (*s))
  7902. ++s;
  7903. const bool isNeg = *s == '-';
  7904. if (isNeg)
  7905. ++s;
  7906. for (;;)
  7907. {
  7908. const char c = *s++;
  7909. if (c >= '0' && c <= '9')
  7910. v = v * 10 + (int64) (c - '0');
  7911. else
  7912. break;
  7913. }
  7914. return isNeg ? -v : v;
  7915. #endif
  7916. }
  7917. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7918. {
  7919. #if JUCE_WINDOWS
  7920. return _wtoi64 (s);
  7921. #else
  7922. int64 v = 0;
  7923. while (isWhitespace (*s))
  7924. ++s;
  7925. const bool isNeg = *s == '-';
  7926. if (isNeg)
  7927. ++s;
  7928. for (;;)
  7929. {
  7930. const juce_wchar c = *s++;
  7931. if (c >= '0' && c <= '9')
  7932. v = v * 10 + (int64) (c - '0');
  7933. else
  7934. break;
  7935. }
  7936. return isNeg ? -v : v;
  7937. #endif
  7938. }
  7939. static double juce_mulexp10 (const double value, int exponent) throw()
  7940. {
  7941. if (exponent == 0)
  7942. return value;
  7943. if (value == 0)
  7944. return 0;
  7945. const bool negative = (exponent < 0);
  7946. if (negative)
  7947. exponent = -exponent;
  7948. double result = 1.0, power = 10.0;
  7949. for (int bit = 1; exponent != 0; bit <<= 1)
  7950. {
  7951. if ((exponent & bit) != 0)
  7952. {
  7953. exponent ^= bit;
  7954. result *= power;
  7955. if (exponent == 0)
  7956. break;
  7957. }
  7958. power *= power;
  7959. }
  7960. return negative ? (value / result) : (value * result);
  7961. }
  7962. template <class CharType>
  7963. double juce_atof (const CharType* const original) throw()
  7964. {
  7965. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  7966. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  7967. int exponent = 0, decPointIndex = 0, digit = 0;
  7968. int lastDigit = 0, numSignificantDigits = 0;
  7969. bool isNegative = false, digitsFound = false;
  7970. const int maxSignificantDigits = 15 + 2;
  7971. const CharType* s = original;
  7972. while (CharacterFunctions::isWhitespace (*s))
  7973. ++s;
  7974. switch (*s)
  7975. {
  7976. case '-': isNegative = true; // fall-through..
  7977. case '+': ++s;
  7978. }
  7979. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  7980. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  7981. for (;;)
  7982. {
  7983. if (CharacterFunctions::isDigit (*s))
  7984. {
  7985. lastDigit = digit;
  7986. digit = *s++ - '0';
  7987. digitsFound = true;
  7988. if (decPointIndex != 0)
  7989. exponentAdjustment[1]++;
  7990. if (numSignificantDigits == 0 && digit == 0)
  7991. continue;
  7992. if (++numSignificantDigits > maxSignificantDigits)
  7993. {
  7994. if (digit > 5)
  7995. ++accumulator [decPointIndex];
  7996. else if (digit == 5 && (lastDigit & 1) != 0)
  7997. ++accumulator [decPointIndex];
  7998. if (decPointIndex > 0)
  7999. exponentAdjustment[1]--;
  8000. else
  8001. exponentAdjustment[0]++;
  8002. while (CharacterFunctions::isDigit (*s))
  8003. {
  8004. ++s;
  8005. if (decPointIndex == 0)
  8006. exponentAdjustment[0]++;
  8007. }
  8008. }
  8009. else
  8010. {
  8011. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8012. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8013. {
  8014. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8015. + accumulator [decPointIndex];
  8016. accumulator [decPointIndex] = 0;
  8017. exponentAccumulator [decPointIndex] = 0;
  8018. }
  8019. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8020. exponentAccumulator [decPointIndex]++;
  8021. }
  8022. }
  8023. else if (decPointIndex == 0 && *s == '.')
  8024. {
  8025. ++s;
  8026. decPointIndex = 1;
  8027. if (numSignificantDigits > maxSignificantDigits)
  8028. {
  8029. while (CharacterFunctions::isDigit (*s))
  8030. ++s;
  8031. break;
  8032. }
  8033. }
  8034. else
  8035. {
  8036. break;
  8037. }
  8038. }
  8039. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8040. if (decPointIndex != 0)
  8041. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8042. if ((*s == 'e' || *s == 'E') && digitsFound)
  8043. {
  8044. bool negativeExponent = false;
  8045. switch (*++s)
  8046. {
  8047. case '-': negativeExponent = true; // fall-through..
  8048. case '+': ++s;
  8049. }
  8050. while (CharacterFunctions::isDigit (*s))
  8051. exponent = (exponent * 10) + (*s++ - '0');
  8052. if (negativeExponent)
  8053. exponent = -exponent;
  8054. }
  8055. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8056. if (decPointIndex != 0)
  8057. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8058. return isNegative ? -r : r;
  8059. }
  8060. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8061. {
  8062. return juce_atof <char> (s);
  8063. }
  8064. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8065. {
  8066. return juce_atof <juce_wchar> (s);
  8067. }
  8068. char CharacterFunctions::toUpperCase (const char character) throw()
  8069. {
  8070. return (char) toupper (character);
  8071. }
  8072. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8073. {
  8074. return towupper (character);
  8075. }
  8076. void CharacterFunctions::toUpperCase (char* s) throw()
  8077. {
  8078. #if JUCE_WINDOWS
  8079. strupr (s);
  8080. #else
  8081. while (*s != 0)
  8082. {
  8083. *s = toUpperCase (*s);
  8084. ++s;
  8085. }
  8086. #endif
  8087. }
  8088. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8089. {
  8090. #if JUCE_WINDOWS
  8091. _wcsupr (s);
  8092. #else
  8093. while (*s != 0)
  8094. {
  8095. *s = toUpperCase (*s);
  8096. ++s;
  8097. }
  8098. #endif
  8099. }
  8100. bool CharacterFunctions::isUpperCase (const char character) throw()
  8101. {
  8102. return isupper (character) != 0;
  8103. }
  8104. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8105. {
  8106. #if JUCE_WINDOWS
  8107. return iswupper (character) != 0;
  8108. #else
  8109. return toLowerCase (character) != character;
  8110. #endif
  8111. }
  8112. char CharacterFunctions::toLowerCase (const char character) throw()
  8113. {
  8114. return (char) tolower (character);
  8115. }
  8116. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8117. {
  8118. return towlower (character);
  8119. }
  8120. void CharacterFunctions::toLowerCase (char* s) throw()
  8121. {
  8122. #if JUCE_WINDOWS
  8123. strlwr (s);
  8124. #else
  8125. while (*s != 0)
  8126. {
  8127. *s = toLowerCase (*s);
  8128. ++s;
  8129. }
  8130. #endif
  8131. }
  8132. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8133. {
  8134. #if JUCE_WINDOWS
  8135. _wcslwr (s);
  8136. #else
  8137. while (*s != 0)
  8138. {
  8139. *s = toLowerCase (*s);
  8140. ++s;
  8141. }
  8142. #endif
  8143. }
  8144. bool CharacterFunctions::isLowerCase (const char character) throw()
  8145. {
  8146. return islower (character) != 0;
  8147. }
  8148. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8149. {
  8150. #if JUCE_WINDOWS
  8151. return iswlower (character) != 0;
  8152. #else
  8153. return toUpperCase (character) != character;
  8154. #endif
  8155. }
  8156. bool CharacterFunctions::isWhitespace (const char character) throw()
  8157. {
  8158. return character == ' ' || (character <= 13 && character >= 9);
  8159. }
  8160. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8161. {
  8162. return iswspace (character) != 0;
  8163. }
  8164. bool CharacterFunctions::isDigit (const char character) throw()
  8165. {
  8166. return (character >= '0' && character <= '9');
  8167. }
  8168. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8169. {
  8170. return iswdigit (character) != 0;
  8171. }
  8172. bool CharacterFunctions::isLetter (const char character) throw()
  8173. {
  8174. return (character >= 'a' && character <= 'z')
  8175. || (character >= 'A' && character <= 'Z');
  8176. }
  8177. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8178. {
  8179. return iswalpha (character) != 0;
  8180. }
  8181. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8182. {
  8183. return (character >= 'a' && character <= 'z')
  8184. || (character >= 'A' && character <= 'Z')
  8185. || (character >= '0' && character <= '9');
  8186. }
  8187. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8188. {
  8189. return iswalnum (character) != 0;
  8190. }
  8191. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8192. {
  8193. unsigned int d = digit - '0';
  8194. if (d < (unsigned int) 10)
  8195. return (int) d;
  8196. d += (unsigned int) ('0' - 'a');
  8197. if (d < (unsigned int) 6)
  8198. return (int) d + 10;
  8199. d += (unsigned int) ('a' - 'A');
  8200. if (d < (unsigned int) 6)
  8201. return (int) d + 10;
  8202. return -1;
  8203. }
  8204. #if JUCE_MSVC
  8205. #pragma warning (pop)
  8206. #endif
  8207. END_JUCE_NAMESPACE
  8208. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8209. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8210. BEGIN_JUCE_NAMESPACE
  8211. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8212. {
  8213. loadFromText (fileContents);
  8214. }
  8215. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8216. {
  8217. loadFromText (fileToLoad.loadFileAsString());
  8218. }
  8219. LocalisedStrings::~LocalisedStrings()
  8220. {
  8221. }
  8222. const String LocalisedStrings::translate (const String& text) const
  8223. {
  8224. return translations.getValue (text, text);
  8225. }
  8226. static int findCloseQuote (const String& text, int startPos)
  8227. {
  8228. juce_wchar lastChar = 0;
  8229. for (;;)
  8230. {
  8231. const juce_wchar c = text [startPos];
  8232. if (c == 0 || (c == '"' && lastChar != '\\'))
  8233. break;
  8234. lastChar = c;
  8235. ++startPos;
  8236. }
  8237. return startPos;
  8238. }
  8239. static const String unescapeString (const String& s)
  8240. {
  8241. return s.replace ("\\\"", "\"")
  8242. .replace ("\\\'", "\'")
  8243. .replace ("\\t", "\t")
  8244. .replace ("\\r", "\r")
  8245. .replace ("\\n", "\n");
  8246. }
  8247. void LocalisedStrings::loadFromText (const String& fileContents)
  8248. {
  8249. StringArray lines;
  8250. lines.addLines (fileContents);
  8251. for (int i = 0; i < lines.size(); ++i)
  8252. {
  8253. String line (lines[i].trim());
  8254. if (line.startsWithChar ('"'))
  8255. {
  8256. int closeQuote = findCloseQuote (line, 1);
  8257. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8258. if (originalText.isNotEmpty())
  8259. {
  8260. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8261. closeQuote = findCloseQuote (line, openingQuote + 1);
  8262. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8263. if (newText.isNotEmpty())
  8264. translations.set (originalText, newText);
  8265. }
  8266. }
  8267. else if (line.startsWithIgnoreCase ("language:"))
  8268. {
  8269. languageName = line.substring (9).trim();
  8270. }
  8271. else if (line.startsWithIgnoreCase ("countries:"))
  8272. {
  8273. countryCodes.addTokens (line.substring (10).trim(), true);
  8274. countryCodes.trim();
  8275. countryCodes.removeEmptyStrings();
  8276. }
  8277. }
  8278. }
  8279. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8280. {
  8281. translations.setIgnoresCase (shouldIgnoreCase);
  8282. }
  8283. static CriticalSection currentMappingsLock;
  8284. static LocalisedStrings* currentMappings = 0;
  8285. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8286. {
  8287. const ScopedLock sl (currentMappingsLock);
  8288. delete currentMappings;
  8289. currentMappings = newTranslations;
  8290. }
  8291. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8292. {
  8293. return currentMappings;
  8294. }
  8295. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8296. {
  8297. const ScopedLock sl (currentMappingsLock);
  8298. if (currentMappings != 0)
  8299. return currentMappings->translate (text);
  8300. return text;
  8301. }
  8302. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8303. {
  8304. return translateWithCurrentMappings (String (text));
  8305. }
  8306. END_JUCE_NAMESPACE
  8307. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8308. /*** Start of inlined file: juce_String.cpp ***/
  8309. #if JUCE_MSVC
  8310. #pragma warning (push)
  8311. #pragma warning (disable: 4514)
  8312. #endif
  8313. #include <locale>
  8314. BEGIN_JUCE_NAMESPACE
  8315. #if JUCE_MSVC
  8316. #pragma warning (pop)
  8317. #endif
  8318. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8319. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8320. #endif
  8321. class StringHolder
  8322. {
  8323. public:
  8324. StringHolder()
  8325. : refCount (0x3fffffff), allocatedNumChars (0)
  8326. {
  8327. text[0] = 0;
  8328. }
  8329. static juce_wchar* createUninitialised (const size_t numChars)
  8330. {
  8331. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8332. s->refCount.value = 0;
  8333. s->allocatedNumChars = numChars;
  8334. return &(s->text[0]);
  8335. }
  8336. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8337. {
  8338. juce_wchar* const dest = createUninitialised (numChars);
  8339. copyChars (dest, src, numChars);
  8340. return dest;
  8341. }
  8342. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8343. {
  8344. juce_wchar* const dest = createUninitialised (numChars);
  8345. CharacterFunctions::copy (dest, src, (int) numChars);
  8346. dest [numChars] = 0;
  8347. return dest;
  8348. }
  8349. static inline juce_wchar* getEmpty() throw()
  8350. {
  8351. return &(empty.text[0]);
  8352. }
  8353. static void retain (juce_wchar* const text) throw()
  8354. {
  8355. ++(bufferFromText (text)->refCount);
  8356. }
  8357. static inline void release (StringHolder* const b) throw()
  8358. {
  8359. if (--(b->refCount) == -1 && b != &empty)
  8360. delete[] reinterpret_cast <char*> (b);
  8361. }
  8362. static void release (juce_wchar* const text) throw()
  8363. {
  8364. release (bufferFromText (text));
  8365. }
  8366. static juce_wchar* makeUnique (juce_wchar* const text)
  8367. {
  8368. StringHolder* const b = bufferFromText (text);
  8369. if (b->refCount.get() <= 0)
  8370. return text;
  8371. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8372. release (b);
  8373. return newText;
  8374. }
  8375. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8376. {
  8377. StringHolder* const b = bufferFromText (text);
  8378. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8379. return text;
  8380. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8381. copyChars (newText, text, b->allocatedNumChars);
  8382. release (b);
  8383. return newText;
  8384. }
  8385. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8386. {
  8387. return bufferFromText (text)->allocatedNumChars;
  8388. }
  8389. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8390. {
  8391. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8392. dest [numChars] = 0;
  8393. }
  8394. Atomic<int> refCount;
  8395. size_t allocatedNumChars;
  8396. juce_wchar text[1];
  8397. static StringHolder empty;
  8398. private:
  8399. static inline StringHolder* bufferFromText (void* const text) throw()
  8400. {
  8401. // (Can't use offsetof() here because of warnings about this not being a POD)
  8402. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8403. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8404. }
  8405. };
  8406. StringHolder StringHolder::empty;
  8407. const String String::empty;
  8408. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8409. {
  8410. jassert (t[numChars] == 0); // must have a null terminator
  8411. text = StringHolder::createCopy (t, numChars);
  8412. }
  8413. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8414. {
  8415. if (numExtraChars > 0)
  8416. {
  8417. const int oldLen = length();
  8418. const int newTotalLen = oldLen + numExtraChars;
  8419. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8420. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8421. }
  8422. }
  8423. void String::preallocateStorage (const size_t numChars)
  8424. {
  8425. text = StringHolder::makeUniqueWithSize (text, numChars);
  8426. }
  8427. String::String() throw()
  8428. : text (StringHolder::getEmpty())
  8429. {
  8430. }
  8431. String::~String() throw()
  8432. {
  8433. StringHolder::release (text);
  8434. }
  8435. String::String (const String& other) throw()
  8436. : text (other.text)
  8437. {
  8438. StringHolder::retain (text);
  8439. }
  8440. void String::swapWith (String& other) throw()
  8441. {
  8442. swapVariables (text, other.text);
  8443. }
  8444. String& String::operator= (const String& other) throw()
  8445. {
  8446. juce_wchar* const newText = other.text;
  8447. StringHolder::retain (newText);
  8448. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8449. return *this;
  8450. }
  8451. String::String (const size_t numChars, const int /*dummyVariable*/)
  8452. : text (StringHolder::createUninitialised (numChars))
  8453. {
  8454. }
  8455. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8456. {
  8457. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8458. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8459. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8460. }
  8461. String::String (const char* const t)
  8462. {
  8463. if (t != 0 && *t != 0)
  8464. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8465. else
  8466. text = StringHolder::getEmpty();
  8467. }
  8468. String::String (const juce_wchar* const t)
  8469. {
  8470. if (t != 0 && *t != 0)
  8471. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8472. else
  8473. text = StringHolder::getEmpty();
  8474. }
  8475. String::String (const char* const t, const size_t maxChars)
  8476. {
  8477. int i;
  8478. for (i = 0; (size_t) i < maxChars; ++i)
  8479. if (t[i] == 0)
  8480. break;
  8481. if (i > 0)
  8482. text = StringHolder::createCopy (t, i);
  8483. else
  8484. text = StringHolder::getEmpty();
  8485. }
  8486. String::String (const juce_wchar* const t, const size_t maxChars)
  8487. {
  8488. int i;
  8489. for (i = 0; (size_t) i < maxChars; ++i)
  8490. if (t[i] == 0)
  8491. break;
  8492. if (i > 0)
  8493. text = StringHolder::createCopy (t, i);
  8494. else
  8495. text = StringHolder::getEmpty();
  8496. }
  8497. const String String::charToString (const juce_wchar character)
  8498. {
  8499. String result ((size_t) 1, (int) 0);
  8500. result.text[0] = character;
  8501. result.text[1] = 0;
  8502. return result;
  8503. }
  8504. namespace NumberToStringConverters
  8505. {
  8506. // pass in a pointer to the END of a buffer..
  8507. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8508. {
  8509. *--t = 0;
  8510. int64 v = (n >= 0) ? n : -n;
  8511. do
  8512. {
  8513. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8514. v /= 10;
  8515. } while (v > 0);
  8516. if (n < 0)
  8517. *--t = '-';
  8518. return t;
  8519. }
  8520. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8521. {
  8522. *--t = 0;
  8523. do
  8524. {
  8525. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8526. v /= 10;
  8527. } while (v > 0);
  8528. return t;
  8529. }
  8530. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8531. {
  8532. if (n == (int) 0x80000000) // (would cause an overflow)
  8533. return int64ToString (t, n);
  8534. *--t = 0;
  8535. int v = abs (n);
  8536. do
  8537. {
  8538. *--t = (juce_wchar) ('0' + (v % 10));
  8539. v /= 10;
  8540. } while (v > 0);
  8541. if (n < 0)
  8542. *--t = '-';
  8543. return t;
  8544. }
  8545. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8546. {
  8547. *--t = 0;
  8548. do
  8549. {
  8550. *--t = (juce_wchar) ('0' + (v % 10));
  8551. v /= 10;
  8552. } while (v > 0);
  8553. return t;
  8554. }
  8555. static juce_wchar getDecimalPoint()
  8556. {
  8557. #if JUCE_WINDOWS && _MSC_VER < 1400
  8558. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8559. #else
  8560. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8561. #endif
  8562. return dp;
  8563. }
  8564. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8565. {
  8566. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8567. {
  8568. juce_wchar* const end = buffer + numChars;
  8569. juce_wchar* t = end;
  8570. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  8571. *--t = (juce_wchar) 0;
  8572. while (numDecPlaces >= 0 || v > 0)
  8573. {
  8574. if (numDecPlaces == 0)
  8575. *--t = getDecimalPoint();
  8576. *--t = (juce_wchar) ('0' + (v % 10));
  8577. v /= 10;
  8578. --numDecPlaces;
  8579. }
  8580. if (n < 0)
  8581. *--t = '-';
  8582. len = end - t - 1;
  8583. return t;
  8584. }
  8585. else
  8586. {
  8587. #if JUCE_WINDOWS
  8588. #if _MSC_VER <= 1400
  8589. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8590. #else
  8591. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8592. #endif
  8593. #else
  8594. len = swprintf (buffer, numChars, L"%.9g", n);
  8595. #endif
  8596. return buffer;
  8597. }
  8598. }
  8599. }
  8600. String::String (const int number)
  8601. {
  8602. juce_wchar buffer [16];
  8603. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8604. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8605. createInternal (start, end - start - 1);
  8606. }
  8607. String::String (const unsigned int number)
  8608. {
  8609. juce_wchar buffer [16];
  8610. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8611. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8612. createInternal (start, end - start - 1);
  8613. }
  8614. String::String (const short number)
  8615. {
  8616. juce_wchar buffer [16];
  8617. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8618. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8619. createInternal (start, end - start - 1);
  8620. }
  8621. String::String (const unsigned short number)
  8622. {
  8623. juce_wchar buffer [16];
  8624. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8625. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8626. createInternal (start, end - start - 1);
  8627. }
  8628. String::String (const int64 number)
  8629. {
  8630. juce_wchar buffer [32];
  8631. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8632. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8633. createInternal (start, end - start - 1);
  8634. }
  8635. String::String (const uint64 number)
  8636. {
  8637. juce_wchar buffer [32];
  8638. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8639. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8640. createInternal (start, end - start - 1);
  8641. }
  8642. String::String (const float number, const int numberOfDecimalPlaces)
  8643. {
  8644. juce_wchar buffer [48];
  8645. size_t len;
  8646. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8647. createInternal (start, len);
  8648. }
  8649. String::String (const double number, const int numberOfDecimalPlaces)
  8650. {
  8651. juce_wchar buffer [48];
  8652. size_t len;
  8653. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8654. createInternal (start, len);
  8655. }
  8656. int String::length() const throw()
  8657. {
  8658. return CharacterFunctions::length (text);
  8659. }
  8660. int String::hashCode() const throw()
  8661. {
  8662. const juce_wchar* t = text;
  8663. int result = 0;
  8664. while (*t != (juce_wchar) 0)
  8665. result = 31 * result + *t++;
  8666. return result;
  8667. }
  8668. int64 String::hashCode64() const throw()
  8669. {
  8670. const juce_wchar* t = text;
  8671. int64 result = 0;
  8672. while (*t != (juce_wchar) 0)
  8673. result = 101 * result + *t++;
  8674. return result;
  8675. }
  8676. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  8677. {
  8678. return string1.compare (string2) == 0;
  8679. }
  8680. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  8681. {
  8682. return string1.compare (string2) == 0;
  8683. }
  8684. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  8685. {
  8686. return string1.compare (string2) == 0;
  8687. }
  8688. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  8689. {
  8690. return string1.compare (string2) != 0;
  8691. }
  8692. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  8693. {
  8694. return string1.compare (string2) != 0;
  8695. }
  8696. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  8697. {
  8698. return string1.compare (string2) != 0;
  8699. }
  8700. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  8701. {
  8702. return string1.compare (string2) > 0;
  8703. }
  8704. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  8705. {
  8706. return string1.compare (string2) < 0;
  8707. }
  8708. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  8709. {
  8710. return string1.compare (string2) >= 0;
  8711. }
  8712. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  8713. {
  8714. return string1.compare (string2) <= 0;
  8715. }
  8716. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8717. {
  8718. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8719. : isEmpty();
  8720. }
  8721. bool String::equalsIgnoreCase (const char* t) const throw()
  8722. {
  8723. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8724. : isEmpty();
  8725. }
  8726. bool String::equalsIgnoreCase (const String& other) const throw()
  8727. {
  8728. return text == other.text
  8729. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8730. }
  8731. int String::compare (const String& other) const throw()
  8732. {
  8733. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8734. }
  8735. int String::compare (const char* other) const throw()
  8736. {
  8737. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8738. }
  8739. int String::compare (const juce_wchar* other) const throw()
  8740. {
  8741. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8742. }
  8743. int String::compareIgnoreCase (const String& other) const throw()
  8744. {
  8745. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8746. }
  8747. int String::compareLexicographically (const String& other) const throw()
  8748. {
  8749. const juce_wchar* s1 = text;
  8750. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8751. ++s1;
  8752. const juce_wchar* s2 = other.text;
  8753. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8754. ++s2;
  8755. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8756. }
  8757. String& String::operator+= (const juce_wchar* const t)
  8758. {
  8759. if (t != 0)
  8760. appendInternal (t, CharacterFunctions::length (t));
  8761. return *this;
  8762. }
  8763. String& String::operator+= (const String& other)
  8764. {
  8765. if (isEmpty())
  8766. operator= (other);
  8767. else
  8768. appendInternal (other.text, other.length());
  8769. return *this;
  8770. }
  8771. String& String::operator+= (const char ch)
  8772. {
  8773. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8774. return operator+= (static_cast <const juce_wchar*> (asString));
  8775. }
  8776. String& String::operator+= (const juce_wchar ch)
  8777. {
  8778. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8779. return operator+= (static_cast <const juce_wchar*> (asString));
  8780. }
  8781. String& String::operator+= (const int number)
  8782. {
  8783. juce_wchar buffer [16];
  8784. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8785. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8786. appendInternal (start, (int) (end - start));
  8787. return *this;
  8788. }
  8789. String& String::operator+= (const unsigned int number)
  8790. {
  8791. juce_wchar buffer [16];
  8792. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8793. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8794. appendInternal (start, (int) (end - start));
  8795. return *this;
  8796. }
  8797. void String::append (const juce_wchar* const other, const int howMany)
  8798. {
  8799. if (howMany > 0)
  8800. {
  8801. int i;
  8802. for (i = 0; i < howMany; ++i)
  8803. if (other[i] == 0)
  8804. break;
  8805. appendInternal (other, i);
  8806. }
  8807. }
  8808. const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  8809. {
  8810. String s (string1);
  8811. return s += string2;
  8812. }
  8813. const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  8814. {
  8815. String s (string1);
  8816. return s += string2;
  8817. }
  8818. const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  8819. {
  8820. return String::charToString (string1) + string2;
  8821. }
  8822. const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  8823. {
  8824. return String::charToString (string1) + string2;
  8825. }
  8826. const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  8827. {
  8828. return string1 += string2;
  8829. }
  8830. const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  8831. {
  8832. return string1 += string2;
  8833. }
  8834. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  8835. {
  8836. return string1 += string2;
  8837. }
  8838. const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  8839. {
  8840. return string1 += string2;
  8841. }
  8842. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  8843. {
  8844. return string1 += string2;
  8845. }
  8846. String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  8847. {
  8848. return string1 += characterToAppend;
  8849. }
  8850. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  8851. {
  8852. return string1 += characterToAppend;
  8853. }
  8854. String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  8855. {
  8856. return string1 += string2;
  8857. }
  8858. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  8859. {
  8860. return string1 += string2;
  8861. }
  8862. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  8863. {
  8864. return string1 += string2;
  8865. }
  8866. String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  8867. {
  8868. return string1 += (int) number;
  8869. }
  8870. String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  8871. {
  8872. return string1 += number;
  8873. }
  8874. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  8875. {
  8876. return string1 += number;
  8877. }
  8878. String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  8879. {
  8880. return string1 += (int) number;
  8881. }
  8882. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  8883. {
  8884. return string1 += (unsigned int) number;
  8885. }
  8886. String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  8887. {
  8888. return string1 += String (number);
  8889. }
  8890. String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  8891. {
  8892. return string1 += String (number);
  8893. }
  8894. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  8895. {
  8896. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  8897. // if lots of large, persistent strings were to be written to streams).
  8898. const int numBytes = text.getNumBytesAsUTF8();
  8899. HeapBlock<char> temp (numBytes + 1);
  8900. text.copyToUTF8 (temp, numBytes + 1);
  8901. stream.write (temp, numBytes);
  8902. return stream;
  8903. }
  8904. int String::indexOfChar (const juce_wchar character) const throw()
  8905. {
  8906. const juce_wchar* t = text;
  8907. for (;;)
  8908. {
  8909. if (*t == character)
  8910. return (int) (t - text);
  8911. if (*t++ == 0)
  8912. return -1;
  8913. }
  8914. }
  8915. int String::lastIndexOfChar (const juce_wchar character) const throw()
  8916. {
  8917. for (int i = length(); --i >= 0;)
  8918. if (text[i] == character)
  8919. return i;
  8920. return -1;
  8921. }
  8922. int String::indexOf (const String& t) const throw()
  8923. {
  8924. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  8925. return r == 0 ? -1 : (int) (r - text);
  8926. }
  8927. int String::indexOfChar (const int startIndex,
  8928. const juce_wchar character) const throw()
  8929. {
  8930. if (startIndex > 0 && startIndex >= length())
  8931. return -1;
  8932. const juce_wchar* t = text + jmax (0, startIndex);
  8933. for (;;)
  8934. {
  8935. if (*t == character)
  8936. return (int) (t - text);
  8937. if (*t == 0)
  8938. return -1;
  8939. ++t;
  8940. }
  8941. }
  8942. int String::indexOfAnyOf (const String& charactersToLookFor,
  8943. const int startIndex,
  8944. const bool ignoreCase) const throw()
  8945. {
  8946. if (startIndex > 0 && startIndex >= length())
  8947. return -1;
  8948. const juce_wchar* t = text + jmax (0, startIndex);
  8949. while (*t != 0)
  8950. {
  8951. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  8952. return (int) (t - text);
  8953. ++t;
  8954. }
  8955. return -1;
  8956. }
  8957. int String::indexOf (const int startIndex, const String& other) const throw()
  8958. {
  8959. if (startIndex > 0 && startIndex >= length())
  8960. return -1;
  8961. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  8962. return found == 0 ? -1 : (int) (found - text);
  8963. }
  8964. int String::indexOfIgnoreCase (const String& other) const throw()
  8965. {
  8966. if (other.isNotEmpty())
  8967. {
  8968. const int len = other.length();
  8969. const int end = length() - len;
  8970. for (int i = 0; i <= end; ++i)
  8971. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8972. return i;
  8973. }
  8974. return -1;
  8975. }
  8976. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  8977. {
  8978. if (other.isNotEmpty())
  8979. {
  8980. const int len = other.length();
  8981. const int end = length() - len;
  8982. for (int i = jmax (0, startIndex); i <= end; ++i)
  8983. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8984. return i;
  8985. }
  8986. return -1;
  8987. }
  8988. int String::lastIndexOf (const String& other) const throw()
  8989. {
  8990. if (other.isNotEmpty())
  8991. {
  8992. const int len = other.length();
  8993. int i = length() - len;
  8994. if (i >= 0)
  8995. {
  8996. const juce_wchar* n = text + i;
  8997. while (i >= 0)
  8998. {
  8999. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9000. return i;
  9001. --i;
  9002. }
  9003. }
  9004. }
  9005. return -1;
  9006. }
  9007. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9008. {
  9009. if (other.isNotEmpty())
  9010. {
  9011. const int len = other.length();
  9012. int i = length() - len;
  9013. if (i >= 0)
  9014. {
  9015. const juce_wchar* n = text + i;
  9016. while (i >= 0)
  9017. {
  9018. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9019. return i;
  9020. --i;
  9021. }
  9022. }
  9023. }
  9024. return -1;
  9025. }
  9026. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9027. {
  9028. for (int i = length(); --i >= 0;)
  9029. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9030. return i;
  9031. return -1;
  9032. }
  9033. bool String::contains (const String& other) const throw()
  9034. {
  9035. return indexOf (other) >= 0;
  9036. }
  9037. bool String::containsChar (const juce_wchar character) const throw()
  9038. {
  9039. const juce_wchar* t = text;
  9040. for (;;)
  9041. {
  9042. if (*t == 0)
  9043. return false;
  9044. if (*t == character)
  9045. return true;
  9046. ++t;
  9047. }
  9048. }
  9049. bool String::containsIgnoreCase (const String& t) const throw()
  9050. {
  9051. return indexOfIgnoreCase (t) >= 0;
  9052. }
  9053. int String::indexOfWholeWord (const String& word) const throw()
  9054. {
  9055. if (word.isNotEmpty())
  9056. {
  9057. const int wordLen = word.length();
  9058. const int end = length() - wordLen;
  9059. const juce_wchar* t = text;
  9060. for (int i = 0; i <= end; ++i)
  9061. {
  9062. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  9063. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9064. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9065. {
  9066. return i;
  9067. }
  9068. ++t;
  9069. }
  9070. }
  9071. return -1;
  9072. }
  9073. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9074. {
  9075. if (word.isNotEmpty())
  9076. {
  9077. const int wordLen = word.length();
  9078. const int end = length() - wordLen;
  9079. const juce_wchar* t = text;
  9080. for (int i = 0; i <= end; ++i)
  9081. {
  9082. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9083. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9084. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9085. {
  9086. return i;
  9087. }
  9088. ++t;
  9089. }
  9090. }
  9091. return -1;
  9092. }
  9093. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9094. {
  9095. return indexOfWholeWord (wordToLookFor) >= 0;
  9096. }
  9097. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9098. {
  9099. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9100. }
  9101. static int indexOfMatch (const juce_wchar* const wildcard,
  9102. const juce_wchar* const test,
  9103. const bool ignoreCase) throw()
  9104. {
  9105. int start = 0;
  9106. while (test [start] != 0)
  9107. {
  9108. int i = 0;
  9109. for (;;)
  9110. {
  9111. const juce_wchar wc = wildcard [i];
  9112. const juce_wchar c = test [i + start];
  9113. if (wc == c
  9114. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9115. || (wc == '?' && c != 0))
  9116. {
  9117. if (wc == 0)
  9118. return start;
  9119. ++i;
  9120. }
  9121. else
  9122. {
  9123. if (wc == '*' && (wildcard [i + 1] == 0
  9124. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  9125. {
  9126. return start;
  9127. }
  9128. break;
  9129. }
  9130. }
  9131. ++start;
  9132. }
  9133. return -1;
  9134. }
  9135. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9136. {
  9137. int i = 0;
  9138. for (;;)
  9139. {
  9140. const juce_wchar wc = wildcard.text [i];
  9141. const juce_wchar c = text [i];
  9142. if (wc == c
  9143. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9144. || (wc == '?' && c != 0))
  9145. {
  9146. if (wc == 0)
  9147. return true;
  9148. ++i;
  9149. }
  9150. else
  9151. {
  9152. return wc == '*' && (wildcard [i + 1] == 0
  9153. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  9154. }
  9155. }
  9156. }
  9157. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9158. {
  9159. const int len = stringToRepeat.length();
  9160. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9161. juce_wchar* n = result.text;
  9162. *n = 0;
  9163. while (--numberOfTimesToRepeat >= 0)
  9164. {
  9165. StringHolder::copyChars (n, stringToRepeat.text, len);
  9166. n += len;
  9167. }
  9168. return result;
  9169. }
  9170. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9171. {
  9172. jassert (padCharacter != 0);
  9173. const int len = length();
  9174. if (len >= minimumLength || padCharacter == 0)
  9175. return *this;
  9176. String result ((size_t) minimumLength + 1, (int) 0);
  9177. juce_wchar* n = result.text;
  9178. minimumLength -= len;
  9179. while (--minimumLength >= 0)
  9180. *n++ = padCharacter;
  9181. StringHolder::copyChars (n, text, len);
  9182. return result;
  9183. }
  9184. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9185. {
  9186. jassert (padCharacter != 0);
  9187. const int len = length();
  9188. if (len >= minimumLength || padCharacter == 0)
  9189. return *this;
  9190. String result (*this, (size_t) minimumLength);
  9191. juce_wchar* n = result.text + len;
  9192. minimumLength -= len;
  9193. while (--minimumLength >= 0)
  9194. *n++ = padCharacter;
  9195. *n = 0;
  9196. return result;
  9197. }
  9198. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9199. {
  9200. if (index < 0)
  9201. {
  9202. // a negative index to replace from?
  9203. jassertfalse;
  9204. index = 0;
  9205. }
  9206. if (numCharsToReplace < 0)
  9207. {
  9208. // replacing a negative number of characters?
  9209. numCharsToReplace = 0;
  9210. jassertfalse;
  9211. }
  9212. const int len = length();
  9213. if (index + numCharsToReplace > len)
  9214. {
  9215. if (index > len)
  9216. {
  9217. // replacing beyond the end of the string?
  9218. index = len;
  9219. jassertfalse;
  9220. }
  9221. numCharsToReplace = len - index;
  9222. }
  9223. const int newStringLen = stringToInsert.length();
  9224. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9225. if (newTotalLen <= 0)
  9226. return String::empty;
  9227. String result ((size_t) newTotalLen, (int) 0);
  9228. StringHolder::copyChars (result.text, text, index);
  9229. if (newStringLen > 0)
  9230. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9231. const int endStringLen = newTotalLen - (index + newStringLen);
  9232. if (endStringLen > 0)
  9233. StringHolder::copyChars (result.text + (index + newStringLen),
  9234. text + (index + numCharsToReplace),
  9235. endStringLen);
  9236. return result;
  9237. }
  9238. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9239. {
  9240. const int stringToReplaceLen = stringToReplace.length();
  9241. const int stringToInsertLen = stringToInsert.length();
  9242. int i = 0;
  9243. String result (*this);
  9244. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9245. : result.indexOf (i, stringToReplace))) >= 0)
  9246. {
  9247. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9248. i += stringToInsertLen;
  9249. }
  9250. return result;
  9251. }
  9252. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9253. {
  9254. const int index = indexOfChar (charToReplace);
  9255. if (index < 0)
  9256. return *this;
  9257. String result (*this, size_t());
  9258. juce_wchar* t = result.text + index;
  9259. while (*t != 0)
  9260. {
  9261. if (*t == charToReplace)
  9262. *t = charToInsert;
  9263. ++t;
  9264. }
  9265. return result;
  9266. }
  9267. const String String::replaceCharacters (const String& charactersToReplace,
  9268. const String& charactersToInsertInstead) const
  9269. {
  9270. String result (*this, size_t());
  9271. juce_wchar* t = result.text;
  9272. const int len2 = charactersToInsertInstead.length();
  9273. // the two strings passed in are supposed to be the same length!
  9274. jassert (len2 == charactersToReplace.length());
  9275. while (*t != 0)
  9276. {
  9277. const int index = charactersToReplace.indexOfChar (*t);
  9278. if (((unsigned int) index) < (unsigned int) len2)
  9279. *t = charactersToInsertInstead [index];
  9280. ++t;
  9281. }
  9282. return result;
  9283. }
  9284. bool String::startsWith (const String& other) const throw()
  9285. {
  9286. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9287. }
  9288. bool String::startsWithIgnoreCase (const String& other) const throw()
  9289. {
  9290. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9291. }
  9292. bool String::startsWithChar (const juce_wchar character) const throw()
  9293. {
  9294. jassert (character != 0); // strings can't contain a null character!
  9295. return text[0] == character;
  9296. }
  9297. bool String::endsWithChar (const juce_wchar character) const throw()
  9298. {
  9299. jassert (character != 0); // strings can't contain a null character!
  9300. return text[0] != 0
  9301. && text [length() - 1] == character;
  9302. }
  9303. bool String::endsWith (const String& other) const throw()
  9304. {
  9305. const int thisLen = length();
  9306. const int otherLen = other.length();
  9307. return thisLen >= otherLen
  9308. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9309. }
  9310. bool String::endsWithIgnoreCase (const String& other) const throw()
  9311. {
  9312. const int thisLen = length();
  9313. const int otherLen = other.length();
  9314. return thisLen >= otherLen
  9315. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9316. }
  9317. const String String::toUpperCase() const
  9318. {
  9319. String result (*this, size_t());
  9320. CharacterFunctions::toUpperCase (result.text);
  9321. return result;
  9322. }
  9323. const String String::toLowerCase() const
  9324. {
  9325. String result (*this, size_t());
  9326. CharacterFunctions::toLowerCase (result.text);
  9327. return result;
  9328. }
  9329. juce_wchar& String::operator[] (const int index)
  9330. {
  9331. jassert (((unsigned int) index) <= (unsigned int) length());
  9332. text = StringHolder::makeUnique (text);
  9333. return text [index];
  9334. }
  9335. juce_wchar String::getLastCharacter() const throw()
  9336. {
  9337. return isEmpty() ? juce_wchar() : text [length() - 1];
  9338. }
  9339. const String String::substring (int start, int end) const
  9340. {
  9341. if (start < 0)
  9342. start = 0;
  9343. else if (end <= start)
  9344. return empty;
  9345. int len = 0;
  9346. while (len <= end && text [len] != 0)
  9347. ++len;
  9348. if (end >= len)
  9349. {
  9350. if (start == 0)
  9351. return *this;
  9352. end = len;
  9353. }
  9354. return String (text + start, end - start);
  9355. }
  9356. const String String::substring (const int start) const
  9357. {
  9358. if (start <= 0)
  9359. return *this;
  9360. const int len = length();
  9361. if (start >= len)
  9362. return empty;
  9363. return String (text + start, len - start);
  9364. }
  9365. const String String::dropLastCharacters (const int numberToDrop) const
  9366. {
  9367. return String (text, jmax (0, length() - numberToDrop));
  9368. }
  9369. const String String::getLastCharacters (const int numCharacters) const
  9370. {
  9371. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9372. }
  9373. const String String::fromFirstOccurrenceOf (const String& sub,
  9374. const bool includeSubString,
  9375. const bool ignoreCase) const
  9376. {
  9377. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9378. : indexOf (sub);
  9379. if (i < 0)
  9380. return empty;
  9381. return substring (includeSubString ? i : i + sub.length());
  9382. }
  9383. const String String::fromLastOccurrenceOf (const String& sub,
  9384. const bool includeSubString,
  9385. const bool ignoreCase) const
  9386. {
  9387. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9388. : lastIndexOf (sub);
  9389. if (i < 0)
  9390. return *this;
  9391. return substring (includeSubString ? i : i + sub.length());
  9392. }
  9393. const String String::upToFirstOccurrenceOf (const String& sub,
  9394. const bool includeSubString,
  9395. const bool ignoreCase) const
  9396. {
  9397. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9398. : indexOf (sub);
  9399. if (i < 0)
  9400. return *this;
  9401. return substring (0, includeSubString ? i + sub.length() : i);
  9402. }
  9403. const String String::upToLastOccurrenceOf (const String& sub,
  9404. const bool includeSubString,
  9405. const bool ignoreCase) const
  9406. {
  9407. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9408. : lastIndexOf (sub);
  9409. if (i < 0)
  9410. return *this;
  9411. return substring (0, includeSubString ? i + sub.length() : i);
  9412. }
  9413. bool String::isQuotedString() const
  9414. {
  9415. const String trimmed (trimStart());
  9416. return trimmed[0] == '"'
  9417. || trimmed[0] == '\'';
  9418. }
  9419. const String String::unquoted() const
  9420. {
  9421. String s (*this);
  9422. if (s.text[0] == '"' || s.text[0] == '\'')
  9423. s = s.substring (1);
  9424. const int lastCharIndex = s.length() - 1;
  9425. if (lastCharIndex >= 0
  9426. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9427. s [lastCharIndex] = 0;
  9428. return s;
  9429. }
  9430. const String String::quoted (const juce_wchar quoteCharacter) const
  9431. {
  9432. if (isEmpty())
  9433. return charToString (quoteCharacter) + quoteCharacter;
  9434. String t (*this);
  9435. if (! t.startsWithChar (quoteCharacter))
  9436. t = charToString (quoteCharacter) + t;
  9437. if (! t.endsWithChar (quoteCharacter))
  9438. t += quoteCharacter;
  9439. return t;
  9440. }
  9441. const String String::trim() const
  9442. {
  9443. if (isEmpty())
  9444. return empty;
  9445. int start = 0;
  9446. while (CharacterFunctions::isWhitespace (text [start]))
  9447. ++start;
  9448. const int len = length();
  9449. int end = len - 1;
  9450. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9451. --end;
  9452. ++end;
  9453. if (end <= start)
  9454. return empty;
  9455. else if (start > 0 || end < len)
  9456. return String (text + start, end - start);
  9457. return *this;
  9458. }
  9459. const String String::trimStart() const
  9460. {
  9461. if (isEmpty())
  9462. return empty;
  9463. const juce_wchar* t = text;
  9464. while (CharacterFunctions::isWhitespace (*t))
  9465. ++t;
  9466. if (t == text)
  9467. return *this;
  9468. return String (t);
  9469. }
  9470. const String String::trimEnd() const
  9471. {
  9472. if (isEmpty())
  9473. return empty;
  9474. const juce_wchar* endT = text + (length() - 1);
  9475. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9476. --endT;
  9477. return String (text, (int) (++endT - text));
  9478. }
  9479. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9480. {
  9481. const juce_wchar* t = text;
  9482. while (charactersToTrim.containsChar (*t))
  9483. ++t;
  9484. return t == text ? *this : String (t);
  9485. }
  9486. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9487. {
  9488. if (isEmpty())
  9489. return empty;
  9490. const int len = length();
  9491. const juce_wchar* endT = text + (len - 1);
  9492. int numToRemove = 0;
  9493. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9494. {
  9495. ++numToRemove;
  9496. --endT;
  9497. }
  9498. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9499. }
  9500. const String String::retainCharacters (const String& charactersToRetain) const
  9501. {
  9502. if (isEmpty())
  9503. return empty;
  9504. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9505. juce_wchar* dst = result.text;
  9506. const juce_wchar* src = text;
  9507. while (*src != 0)
  9508. {
  9509. if (charactersToRetain.containsChar (*src))
  9510. *dst++ = *src;
  9511. ++src;
  9512. }
  9513. *dst = 0;
  9514. return result;
  9515. }
  9516. const String String::removeCharacters (const String& charactersToRemove) const
  9517. {
  9518. if (isEmpty())
  9519. return empty;
  9520. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9521. juce_wchar* dst = result.text;
  9522. const juce_wchar* src = text;
  9523. while (*src != 0)
  9524. {
  9525. if (! charactersToRemove.containsChar (*src))
  9526. *dst++ = *src;
  9527. ++src;
  9528. }
  9529. *dst = 0;
  9530. return result;
  9531. }
  9532. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9533. {
  9534. int i = 0;
  9535. for (;;)
  9536. {
  9537. if (! permittedCharacters.containsChar (text[i]))
  9538. break;
  9539. ++i;
  9540. }
  9541. return substring (0, i);
  9542. }
  9543. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9544. {
  9545. const juce_wchar* const t = text;
  9546. int i = 0;
  9547. while (t[i] != 0)
  9548. {
  9549. if (charactersToStopAt.containsChar (t[i]))
  9550. return String (text, i);
  9551. ++i;
  9552. }
  9553. return empty;
  9554. }
  9555. bool String::containsOnly (const String& chars) const throw()
  9556. {
  9557. const juce_wchar* t = text;
  9558. while (*t != 0)
  9559. if (! chars.containsChar (*t++))
  9560. return false;
  9561. return true;
  9562. }
  9563. bool String::containsAnyOf (const String& chars) const throw()
  9564. {
  9565. const juce_wchar* t = text;
  9566. while (*t != 0)
  9567. if (chars.containsChar (*t++))
  9568. return true;
  9569. return false;
  9570. }
  9571. bool String::containsNonWhitespaceChars() const throw()
  9572. {
  9573. const juce_wchar* t = text;
  9574. while (*t != 0)
  9575. if (! CharacterFunctions::isWhitespace (*t++))
  9576. return true;
  9577. return false;
  9578. }
  9579. const String String::formatted (const juce_wchar* const pf, ... )
  9580. {
  9581. jassert (pf != 0);
  9582. va_list args;
  9583. va_start (args, pf);
  9584. size_t bufferSize = 256;
  9585. String result (bufferSize, (int) 0);
  9586. result.text[0] = 0;
  9587. for (;;)
  9588. {
  9589. #if JUCE_LINUX && JUCE_64BIT
  9590. va_list tempArgs;
  9591. va_copy (tempArgs, args);
  9592. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9593. va_end (tempArgs);
  9594. #elif JUCE_WINDOWS
  9595. #if JUCE_MSVC
  9596. #pragma warning (push)
  9597. #pragma warning (disable: 4996)
  9598. #endif
  9599. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9600. #if JUCE_MSVC
  9601. #pragma warning (pop)
  9602. #endif
  9603. #else
  9604. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9605. #endif
  9606. if (num > 0)
  9607. return result;
  9608. bufferSize += 256;
  9609. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9610. break; // returns -1 because of an error rather than because it needs more space.
  9611. result.preallocateStorage (bufferSize);
  9612. }
  9613. return empty;
  9614. }
  9615. int String::getIntValue() const throw()
  9616. {
  9617. return CharacterFunctions::getIntValue (text);
  9618. }
  9619. int String::getTrailingIntValue() const throw()
  9620. {
  9621. int n = 0;
  9622. int mult = 1;
  9623. const juce_wchar* t = text + length();
  9624. while (--t >= text)
  9625. {
  9626. const juce_wchar c = *t;
  9627. if (! CharacterFunctions::isDigit (c))
  9628. {
  9629. if (c == '-')
  9630. n = -n;
  9631. break;
  9632. }
  9633. n += mult * (c - '0');
  9634. mult *= 10;
  9635. }
  9636. return n;
  9637. }
  9638. int64 String::getLargeIntValue() const throw()
  9639. {
  9640. return CharacterFunctions::getInt64Value (text);
  9641. }
  9642. float String::getFloatValue() const throw()
  9643. {
  9644. return (float) CharacterFunctions::getDoubleValue (text);
  9645. }
  9646. double String::getDoubleValue() const throw()
  9647. {
  9648. return CharacterFunctions::getDoubleValue (text);
  9649. }
  9650. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  9651. const String String::toHexString (const int number)
  9652. {
  9653. juce_wchar buffer[32];
  9654. juce_wchar* const end = buffer + 32;
  9655. juce_wchar* t = end;
  9656. *--t = 0;
  9657. unsigned int v = (unsigned int) number;
  9658. do
  9659. {
  9660. *--t = hexDigits [v & 15];
  9661. v >>= 4;
  9662. } while (v != 0);
  9663. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9664. }
  9665. const String String::toHexString (const int64 number)
  9666. {
  9667. juce_wchar buffer[32];
  9668. juce_wchar* const end = buffer + 32;
  9669. juce_wchar* t = end;
  9670. *--t = 0;
  9671. uint64 v = (uint64) number;
  9672. do
  9673. {
  9674. *--t = hexDigits [(int) (v & 15)];
  9675. v >>= 4;
  9676. } while (v != 0);
  9677. return String (t, (int) (((char*) end) - (char*) t));
  9678. }
  9679. const String String::toHexString (const short number)
  9680. {
  9681. return toHexString ((int) (unsigned short) number);
  9682. }
  9683. const String String::toHexString (const unsigned char* data,
  9684. const int size,
  9685. const int groupSize)
  9686. {
  9687. if (size <= 0)
  9688. return empty;
  9689. int numChars = (size * 2) + 2;
  9690. if (groupSize > 0)
  9691. numChars += size / groupSize;
  9692. String s ((size_t) numChars, (int) 0);
  9693. juce_wchar* d = s.text;
  9694. for (int i = 0; i < size; ++i)
  9695. {
  9696. *d++ = hexDigits [(*data) >> 4];
  9697. *d++ = hexDigits [(*data) & 0xf];
  9698. ++data;
  9699. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9700. *d++ = ' ';
  9701. }
  9702. *d = 0;
  9703. return s;
  9704. }
  9705. int String::getHexValue32() const throw()
  9706. {
  9707. int result = 0;
  9708. const juce_wchar* c = text;
  9709. for (;;)
  9710. {
  9711. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9712. if (hexValue >= 0)
  9713. result = (result << 4) | hexValue;
  9714. else if (*c == 0)
  9715. break;
  9716. ++c;
  9717. }
  9718. return result;
  9719. }
  9720. int64 String::getHexValue64() const throw()
  9721. {
  9722. int64 result = 0;
  9723. const juce_wchar* c = text;
  9724. for (;;)
  9725. {
  9726. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9727. if (hexValue >= 0)
  9728. result = (result << 4) | hexValue;
  9729. else if (*c == 0)
  9730. break;
  9731. ++c;
  9732. }
  9733. return result;
  9734. }
  9735. const String String::createStringFromData (const void* const data_, const int size)
  9736. {
  9737. const char* const data = static_cast <const char*> (data_);
  9738. if (size <= 0 || data == 0)
  9739. {
  9740. return empty;
  9741. }
  9742. else if (size < 2)
  9743. {
  9744. return charToString (data[0]);
  9745. }
  9746. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9747. || (data[0] == (char)-1 && data[1] == (char)-2))
  9748. {
  9749. // assume it's 16-bit unicode
  9750. const bool bigEndian = (data[0] == (char)-2);
  9751. const int numChars = size / 2 - 1;
  9752. String result;
  9753. result.preallocateStorage (numChars + 2);
  9754. const uint16* const src = (const uint16*) (data + 2);
  9755. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9756. if (bigEndian)
  9757. {
  9758. for (int i = 0; i < numChars; ++i)
  9759. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9760. }
  9761. else
  9762. {
  9763. for (int i = 0; i < numChars; ++i)
  9764. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9765. }
  9766. dst [numChars] = 0;
  9767. return result;
  9768. }
  9769. else
  9770. {
  9771. return String::fromUTF8 (data, size);
  9772. }
  9773. }
  9774. const char* String::toUTF8() const
  9775. {
  9776. if (isEmpty())
  9777. {
  9778. return reinterpret_cast <const char*> (text);
  9779. }
  9780. else
  9781. {
  9782. const int currentLen = length() + 1;
  9783. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9784. String* const mutableThis = const_cast <String*> (this);
  9785. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9786. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9787. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9788. return otherCopy;
  9789. }
  9790. }
  9791. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9792. {
  9793. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9794. int num = 0, index = 0;
  9795. for (;;)
  9796. {
  9797. const uint32 c = (uint32) text [index++];
  9798. if (c >= 0x80)
  9799. {
  9800. int numExtraBytes = 1;
  9801. if (c >= 0x800)
  9802. {
  9803. ++numExtraBytes;
  9804. if (c >= 0x10000)
  9805. {
  9806. ++numExtraBytes;
  9807. if (c >= 0x200000)
  9808. {
  9809. ++numExtraBytes;
  9810. if (c >= 0x4000000)
  9811. ++numExtraBytes;
  9812. }
  9813. }
  9814. }
  9815. if (buffer != 0)
  9816. {
  9817. if (num + numExtraBytes >= maxBufferSizeBytes)
  9818. {
  9819. buffer [num++] = 0;
  9820. break;
  9821. }
  9822. else
  9823. {
  9824. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9825. while (--numExtraBytes >= 0)
  9826. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9827. }
  9828. }
  9829. else
  9830. {
  9831. num += numExtraBytes + 1;
  9832. }
  9833. }
  9834. else
  9835. {
  9836. if (buffer != 0)
  9837. {
  9838. if (num + 1 >= maxBufferSizeBytes)
  9839. {
  9840. buffer [num++] = 0;
  9841. break;
  9842. }
  9843. buffer [num] = (uint8) c;
  9844. }
  9845. ++num;
  9846. }
  9847. if (c == 0)
  9848. break;
  9849. }
  9850. return num;
  9851. }
  9852. int String::getNumBytesAsUTF8() const throw()
  9853. {
  9854. int num = 0;
  9855. const juce_wchar* t = text;
  9856. for (;;)
  9857. {
  9858. const uint32 c = (uint32) *t;
  9859. if (c >= 0x80)
  9860. {
  9861. ++num;
  9862. if (c >= 0x800)
  9863. {
  9864. ++num;
  9865. if (c >= 0x10000)
  9866. {
  9867. ++num;
  9868. if (c >= 0x200000)
  9869. {
  9870. ++num;
  9871. if (c >= 0x4000000)
  9872. ++num;
  9873. }
  9874. }
  9875. }
  9876. }
  9877. else if (c == 0)
  9878. break;
  9879. ++num;
  9880. ++t;
  9881. }
  9882. return num;
  9883. }
  9884. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  9885. {
  9886. if (buffer == 0)
  9887. return empty;
  9888. if (bufferSizeBytes < 0)
  9889. bufferSizeBytes = std::numeric_limits<int>::max();
  9890. size_t numBytes;
  9891. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  9892. if (buffer [numBytes] == 0)
  9893. break;
  9894. String result ((size_t) numBytes + 1, (int) 0);
  9895. juce_wchar* dest = result.text;
  9896. size_t i = 0;
  9897. while (i < numBytes)
  9898. {
  9899. const char c = buffer [i++];
  9900. if (c < 0)
  9901. {
  9902. unsigned int mask = 0x7f;
  9903. int bit = 0x40;
  9904. int numExtraValues = 0;
  9905. while (bit != 0 && (c & bit) != 0)
  9906. {
  9907. bit >>= 1;
  9908. mask >>= 1;
  9909. ++numExtraValues;
  9910. }
  9911. int n = (mask & (unsigned char) c);
  9912. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  9913. {
  9914. const char nextByte = buffer[i];
  9915. if ((nextByte & 0xc0) != 0x80)
  9916. break;
  9917. n <<= 6;
  9918. n |= (nextByte & 0x3f);
  9919. ++i;
  9920. }
  9921. *dest++ = (juce_wchar) n;
  9922. }
  9923. else
  9924. {
  9925. *dest++ = (juce_wchar) c;
  9926. }
  9927. }
  9928. *dest = 0;
  9929. return result;
  9930. }
  9931. const char* String::toCString() const
  9932. {
  9933. if (isEmpty())
  9934. {
  9935. return reinterpret_cast <const char*> (text);
  9936. }
  9937. else
  9938. {
  9939. const int len = length();
  9940. String* const mutableThis = const_cast <String*> (this);
  9941. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  9942. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  9943. CharacterFunctions::copy (otherCopy, text, len);
  9944. otherCopy [len] = 0;
  9945. return otherCopy;
  9946. }
  9947. }
  9948. #if JUCE_MSVC
  9949. #pragma warning (push)
  9950. #pragma warning (disable: 4514 4996)
  9951. #endif
  9952. int String::getNumBytesAsCString() const throw()
  9953. {
  9954. return (int) wcstombs (0, text, 0);
  9955. }
  9956. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  9957. {
  9958. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  9959. if (destBuffer != 0 && numBytes >= 0)
  9960. destBuffer [numBytes] = 0;
  9961. return numBytes;
  9962. }
  9963. #if JUCE_MSVC
  9964. #pragma warning (pop)
  9965. #endif
  9966. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  9967. {
  9968. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  9969. }
  9970. String::Concatenator::Concatenator (String& stringToAppendTo)
  9971. : result (stringToAppendTo),
  9972. nextIndex (stringToAppendTo.length())
  9973. {
  9974. }
  9975. String::Concatenator::~Concatenator()
  9976. {
  9977. }
  9978. void String::Concatenator::append (const String& s)
  9979. {
  9980. const int len = s.length();
  9981. if (len > 0)
  9982. {
  9983. result.preallocateStorage (nextIndex + len);
  9984. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  9985. nextIndex += len;
  9986. }
  9987. }
  9988. END_JUCE_NAMESPACE
  9989. /*** End of inlined file: juce_String.cpp ***/
  9990. /*** Start of inlined file: juce_StringArray.cpp ***/
  9991. BEGIN_JUCE_NAMESPACE
  9992. StringArray::StringArray() throw()
  9993. {
  9994. }
  9995. StringArray::StringArray (const StringArray& other)
  9996. : strings (other.strings)
  9997. {
  9998. }
  9999. StringArray::StringArray (const String& firstValue)
  10000. {
  10001. strings.add (firstValue);
  10002. }
  10003. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  10004. const int numberOfStrings)
  10005. {
  10006. for (int i = 0; i < numberOfStrings; ++i)
  10007. strings.add (initialStrings [i]);
  10008. }
  10009. StringArray::StringArray (const char* const* const initialStrings,
  10010. const int numberOfStrings)
  10011. {
  10012. for (int i = 0; i < numberOfStrings; ++i)
  10013. strings.add (initialStrings [i]);
  10014. }
  10015. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  10016. {
  10017. int i = 0;
  10018. while (initialStrings[i] != 0)
  10019. strings.add (initialStrings [i++]);
  10020. }
  10021. StringArray::StringArray (const char* const* const initialStrings)
  10022. {
  10023. int i = 0;
  10024. while (initialStrings[i] != 0)
  10025. strings.add (initialStrings [i++]);
  10026. }
  10027. StringArray& StringArray::operator= (const StringArray& other)
  10028. {
  10029. strings = other.strings;
  10030. return *this;
  10031. }
  10032. StringArray::~StringArray()
  10033. {
  10034. }
  10035. bool StringArray::operator== (const StringArray& other) const throw()
  10036. {
  10037. if (other.size() != size())
  10038. return false;
  10039. for (int i = size(); --i >= 0;)
  10040. if (other.strings.getReference(i) != strings.getReference(i))
  10041. return false;
  10042. return true;
  10043. }
  10044. bool StringArray::operator!= (const StringArray& other) const throw()
  10045. {
  10046. return ! operator== (other);
  10047. }
  10048. void StringArray::clear()
  10049. {
  10050. strings.clear();
  10051. }
  10052. const String& StringArray::operator[] (const int index) const throw()
  10053. {
  10054. if (((unsigned int) index) < (unsigned int) strings.size())
  10055. return strings.getReference (index);
  10056. return String::empty;
  10057. }
  10058. String& StringArray::getReference (const int index) throw()
  10059. {
  10060. jassert (((unsigned int) index) < (unsigned int) strings.size());
  10061. return strings.getReference (index);
  10062. }
  10063. void StringArray::add (const String& newString)
  10064. {
  10065. strings.add (newString);
  10066. }
  10067. void StringArray::insert (const int index, const String& newString)
  10068. {
  10069. strings.insert (index, newString);
  10070. }
  10071. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10072. {
  10073. if (! contains (newString, ignoreCase))
  10074. add (newString);
  10075. }
  10076. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10077. {
  10078. if (startIndex < 0)
  10079. {
  10080. jassertfalse;
  10081. startIndex = 0;
  10082. }
  10083. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10084. numElementsToAdd = otherArray.size() - startIndex;
  10085. while (--numElementsToAdd >= 0)
  10086. strings.add (otherArray.strings.getReference (startIndex++));
  10087. }
  10088. void StringArray::set (const int index, const String& newString)
  10089. {
  10090. strings.set (index, newString);
  10091. }
  10092. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10093. {
  10094. if (ignoreCase)
  10095. {
  10096. for (int i = size(); --i >= 0;)
  10097. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10098. return true;
  10099. }
  10100. else
  10101. {
  10102. for (int i = size(); --i >= 0;)
  10103. if (stringToLookFor == strings.getReference(i))
  10104. return true;
  10105. }
  10106. return false;
  10107. }
  10108. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10109. {
  10110. if (i < 0)
  10111. i = 0;
  10112. const int numElements = size();
  10113. if (ignoreCase)
  10114. {
  10115. while (i < numElements)
  10116. {
  10117. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10118. return i;
  10119. ++i;
  10120. }
  10121. }
  10122. else
  10123. {
  10124. while (i < numElements)
  10125. {
  10126. if (stringToLookFor == strings.getReference (i))
  10127. return i;
  10128. ++i;
  10129. }
  10130. }
  10131. return -1;
  10132. }
  10133. void StringArray::remove (const int index)
  10134. {
  10135. strings.remove (index);
  10136. }
  10137. void StringArray::removeString (const String& stringToRemove,
  10138. const bool ignoreCase)
  10139. {
  10140. if (ignoreCase)
  10141. {
  10142. for (int i = size(); --i >= 0;)
  10143. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10144. strings.remove (i);
  10145. }
  10146. else
  10147. {
  10148. for (int i = size(); --i >= 0;)
  10149. if (stringToRemove == strings.getReference (i))
  10150. strings.remove (i);
  10151. }
  10152. }
  10153. void StringArray::removeRange (int startIndex, int numberToRemove)
  10154. {
  10155. strings.removeRange (startIndex, numberToRemove);
  10156. }
  10157. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10158. {
  10159. if (removeWhitespaceStrings)
  10160. {
  10161. for (int i = size(); --i >= 0;)
  10162. if (! strings.getReference(i).containsNonWhitespaceChars())
  10163. strings.remove (i);
  10164. }
  10165. else
  10166. {
  10167. for (int i = size(); --i >= 0;)
  10168. if (strings.getReference(i).isEmpty())
  10169. strings.remove (i);
  10170. }
  10171. }
  10172. void StringArray::trim()
  10173. {
  10174. for (int i = size(); --i >= 0;)
  10175. {
  10176. String& s = strings.getReference(i);
  10177. s = s.trim();
  10178. }
  10179. }
  10180. class InternalStringArrayComparator_CaseSensitive
  10181. {
  10182. public:
  10183. static int compareElements (String& first, String& second) { return first.compare (second); }
  10184. };
  10185. class InternalStringArrayComparator_CaseInsensitive
  10186. {
  10187. public:
  10188. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10189. };
  10190. void StringArray::sort (const bool ignoreCase)
  10191. {
  10192. if (ignoreCase)
  10193. {
  10194. InternalStringArrayComparator_CaseInsensitive comp;
  10195. strings.sort (comp);
  10196. }
  10197. else
  10198. {
  10199. InternalStringArrayComparator_CaseSensitive comp;
  10200. strings.sort (comp);
  10201. }
  10202. }
  10203. void StringArray::move (const int currentIndex, int newIndex) throw()
  10204. {
  10205. strings.move (currentIndex, newIndex);
  10206. }
  10207. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10208. {
  10209. const int last = (numberToJoin < 0) ? size()
  10210. : jmin (size(), start + numberToJoin);
  10211. if (start < 0)
  10212. start = 0;
  10213. if (start >= last)
  10214. return String::empty;
  10215. if (start == last - 1)
  10216. return strings.getReference (start);
  10217. const int separatorLen = separator.length();
  10218. int charsNeeded = separatorLen * (last - start - 1);
  10219. for (int i = start; i < last; ++i)
  10220. charsNeeded += strings.getReference(i).length();
  10221. String result;
  10222. result.preallocateStorage (charsNeeded);
  10223. juce_wchar* dest = result;
  10224. while (start < last)
  10225. {
  10226. const String& s = strings.getReference (start);
  10227. const int len = s.length();
  10228. if (len > 0)
  10229. {
  10230. s.copyToUnicode (dest, len);
  10231. dest += len;
  10232. }
  10233. if (++start < last && separatorLen > 0)
  10234. {
  10235. separator.copyToUnicode (dest, separatorLen);
  10236. dest += separatorLen;
  10237. }
  10238. }
  10239. *dest = 0;
  10240. return result;
  10241. }
  10242. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10243. {
  10244. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10245. }
  10246. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10247. {
  10248. int num = 0;
  10249. if (text.isNotEmpty())
  10250. {
  10251. bool insideQuotes = false;
  10252. juce_wchar currentQuoteChar = 0;
  10253. int i = 0;
  10254. int tokenStart = 0;
  10255. for (;;)
  10256. {
  10257. const juce_wchar c = text[i];
  10258. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10259. if (! isBreak)
  10260. {
  10261. if (quoteCharacters.containsChar (c))
  10262. {
  10263. if (insideQuotes)
  10264. {
  10265. // only break out of quotes-mode if we find a matching quote to the
  10266. // one that we opened with..
  10267. if (currentQuoteChar == c)
  10268. insideQuotes = false;
  10269. }
  10270. else
  10271. {
  10272. insideQuotes = true;
  10273. currentQuoteChar = c;
  10274. }
  10275. }
  10276. }
  10277. else
  10278. {
  10279. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10280. ++num;
  10281. tokenStart = i + 1;
  10282. }
  10283. if (c == 0)
  10284. break;
  10285. ++i;
  10286. }
  10287. }
  10288. return num;
  10289. }
  10290. int StringArray::addLines (const String& sourceText)
  10291. {
  10292. int numLines = 0;
  10293. const juce_wchar* text = sourceText;
  10294. while (*text != 0)
  10295. {
  10296. const juce_wchar* const startOfLine = text;
  10297. while (*text != 0)
  10298. {
  10299. if (*text == '\r')
  10300. {
  10301. ++text;
  10302. if (*text == '\n')
  10303. ++text;
  10304. break;
  10305. }
  10306. if (*text == '\n')
  10307. {
  10308. ++text;
  10309. break;
  10310. }
  10311. ++text;
  10312. }
  10313. const juce_wchar* endOfLine = text;
  10314. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10315. --endOfLine;
  10316. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10317. --endOfLine;
  10318. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10319. ++numLines;
  10320. }
  10321. return numLines;
  10322. }
  10323. void StringArray::removeDuplicates (const bool ignoreCase)
  10324. {
  10325. for (int i = 0; i < size() - 1; ++i)
  10326. {
  10327. const String s (strings.getReference(i));
  10328. int nextIndex = i + 1;
  10329. for (;;)
  10330. {
  10331. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10332. if (nextIndex < 0)
  10333. break;
  10334. strings.remove (nextIndex);
  10335. }
  10336. }
  10337. }
  10338. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10339. const bool appendNumberToFirstInstance,
  10340. const juce_wchar* preNumberString,
  10341. const juce_wchar* postNumberString)
  10342. {
  10343. if (preNumberString == 0)
  10344. preNumberString = L" (";
  10345. if (postNumberString == 0)
  10346. postNumberString = L")";
  10347. for (int i = 0; i < size() - 1; ++i)
  10348. {
  10349. String& s = strings.getReference(i);
  10350. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10351. if (nextIndex >= 0)
  10352. {
  10353. const String original (s);
  10354. int number = 0;
  10355. if (appendNumberToFirstInstance)
  10356. s = original + preNumberString + String (++number) + postNumberString;
  10357. else
  10358. ++number;
  10359. while (nextIndex >= 0)
  10360. {
  10361. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10362. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10363. }
  10364. }
  10365. }
  10366. }
  10367. void StringArray::minimiseStorageOverheads()
  10368. {
  10369. strings.minimiseStorageOverheads();
  10370. }
  10371. END_JUCE_NAMESPACE
  10372. /*** End of inlined file: juce_StringArray.cpp ***/
  10373. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10374. BEGIN_JUCE_NAMESPACE
  10375. StringPairArray::StringPairArray (const bool ignoreCase_)
  10376. : ignoreCase (ignoreCase_)
  10377. {
  10378. }
  10379. StringPairArray::StringPairArray (const StringPairArray& other)
  10380. : keys (other.keys),
  10381. values (other.values),
  10382. ignoreCase (other.ignoreCase)
  10383. {
  10384. }
  10385. StringPairArray::~StringPairArray()
  10386. {
  10387. }
  10388. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10389. {
  10390. keys = other.keys;
  10391. values = other.values;
  10392. return *this;
  10393. }
  10394. bool StringPairArray::operator== (const StringPairArray& other) const
  10395. {
  10396. for (int i = keys.size(); --i >= 0;)
  10397. if (other [keys[i]] != values[i])
  10398. return false;
  10399. return true;
  10400. }
  10401. bool StringPairArray::operator!= (const StringPairArray& other) const
  10402. {
  10403. return ! operator== (other);
  10404. }
  10405. const String& StringPairArray::operator[] (const String& key) const
  10406. {
  10407. return values [keys.indexOf (key, ignoreCase)];
  10408. }
  10409. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10410. {
  10411. const int i = keys.indexOf (key, ignoreCase);
  10412. if (i >= 0)
  10413. return values[i];
  10414. return defaultReturnValue;
  10415. }
  10416. void StringPairArray::set (const String& key, const String& value)
  10417. {
  10418. const int i = keys.indexOf (key, ignoreCase);
  10419. if (i >= 0)
  10420. {
  10421. values.set (i, value);
  10422. }
  10423. else
  10424. {
  10425. keys.add (key);
  10426. values.add (value);
  10427. }
  10428. }
  10429. void StringPairArray::addArray (const StringPairArray& other)
  10430. {
  10431. for (int i = 0; i < other.size(); ++i)
  10432. set (other.keys[i], other.values[i]);
  10433. }
  10434. void StringPairArray::clear()
  10435. {
  10436. keys.clear();
  10437. values.clear();
  10438. }
  10439. void StringPairArray::remove (const String& key)
  10440. {
  10441. remove (keys.indexOf (key, ignoreCase));
  10442. }
  10443. void StringPairArray::remove (const int index)
  10444. {
  10445. keys.remove (index);
  10446. values.remove (index);
  10447. }
  10448. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10449. {
  10450. ignoreCase = shouldIgnoreCase;
  10451. }
  10452. const String StringPairArray::getDescription() const
  10453. {
  10454. String s;
  10455. for (int i = 0; i < keys.size(); ++i)
  10456. {
  10457. s << keys[i] << " = " << values[i];
  10458. if (i < keys.size())
  10459. s << ", ";
  10460. }
  10461. return s;
  10462. }
  10463. void StringPairArray::minimiseStorageOverheads()
  10464. {
  10465. keys.minimiseStorageOverheads();
  10466. values.minimiseStorageOverheads();
  10467. }
  10468. END_JUCE_NAMESPACE
  10469. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10470. /*** Start of inlined file: juce_StringPool.cpp ***/
  10471. BEGIN_JUCE_NAMESPACE
  10472. StringPool::StringPool() throw() {}
  10473. StringPool::~StringPool() {}
  10474. template <class StringType>
  10475. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  10476. {
  10477. int start = 0;
  10478. int end = strings.size();
  10479. for (;;)
  10480. {
  10481. if (start >= end)
  10482. {
  10483. jassert (start <= end);
  10484. strings.insert (start, newString);
  10485. return strings.getReference (start);
  10486. }
  10487. else
  10488. {
  10489. const String& startString = strings.getReference (start);
  10490. if (startString == newString)
  10491. return startString;
  10492. const int halfway = (start + end) >> 1;
  10493. if (halfway == start)
  10494. {
  10495. if (startString.compare (newString) < 0)
  10496. ++start;
  10497. strings.insert (start, newString);
  10498. return strings.getReference (start);
  10499. }
  10500. const int comp = strings.getReference (halfway).compare (newString);
  10501. if (comp == 0)
  10502. return strings.getReference (halfway);
  10503. else if (comp < 0)
  10504. start = halfway;
  10505. else
  10506. end = halfway;
  10507. }
  10508. }
  10509. }
  10510. const juce_wchar* StringPool::getPooledString (const String& s)
  10511. {
  10512. if (s.isEmpty())
  10513. return String::empty;
  10514. return getPooledStringFromArray (strings, s);
  10515. }
  10516. const juce_wchar* StringPool::getPooledString (const char* const s)
  10517. {
  10518. if (s == 0 || *s == 0)
  10519. return String::empty;
  10520. return getPooledStringFromArray (strings, s);
  10521. }
  10522. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  10523. {
  10524. if (s == 0 || *s == 0)
  10525. return String::empty;
  10526. return getPooledStringFromArray (strings, s);
  10527. }
  10528. int StringPool::size() const throw()
  10529. {
  10530. return strings.size();
  10531. }
  10532. const juce_wchar* StringPool::operator[] (const int index) const throw()
  10533. {
  10534. return strings [index];
  10535. }
  10536. END_JUCE_NAMESPACE
  10537. /*** End of inlined file: juce_StringPool.cpp ***/
  10538. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10539. BEGIN_JUCE_NAMESPACE
  10540. XmlDocument::XmlDocument (const String& documentText)
  10541. : originalText (documentText),
  10542. ignoreEmptyTextElements (true)
  10543. {
  10544. }
  10545. XmlDocument::XmlDocument (const File& file)
  10546. : ignoreEmptyTextElements (true)
  10547. {
  10548. inputSource = new FileInputSource (file);
  10549. }
  10550. XmlDocument::~XmlDocument()
  10551. {
  10552. }
  10553. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10554. {
  10555. inputSource = newSource;
  10556. }
  10557. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10558. {
  10559. ignoreEmptyTextElements = shouldBeIgnored;
  10560. }
  10561. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10562. {
  10563. return CharacterFunctions::isLetterOrDigit (c)
  10564. || c == '_' || c == '-' || c == ':' || c == '.';
  10565. }
  10566. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10567. {
  10568. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10569. : isXmlIdentifierCharSlow (c);
  10570. }
  10571. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10572. {
  10573. String textToParse (originalText);
  10574. if (textToParse.isEmpty() && inputSource != 0)
  10575. {
  10576. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10577. if (in != 0)
  10578. {
  10579. MemoryBlock data;
  10580. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10581. if (data.getSize() >= 2
  10582. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10583. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10584. {
  10585. textToParse = String::createStringFromData (static_cast <const char*> (data.getData()), (int) data.getSize());
  10586. }
  10587. else
  10588. {
  10589. textToParse = String::fromUTF8 (static_cast <const char*> (data.getData()), (int) data.getSize());
  10590. }
  10591. if (! onlyReadOuterDocumentElement)
  10592. originalText = textToParse;
  10593. }
  10594. }
  10595. input = textToParse;
  10596. lastError = String::empty;
  10597. errorOccurred = false;
  10598. outOfData = false;
  10599. needToLoadDTD = true;
  10600. for (int i = 0; i < 128; ++i)
  10601. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10602. if (textToParse.isEmpty())
  10603. {
  10604. lastError = "not enough input";
  10605. }
  10606. else
  10607. {
  10608. skipHeader();
  10609. if (input != 0)
  10610. {
  10611. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10612. if (! errorOccurred)
  10613. return result.release();
  10614. }
  10615. else
  10616. {
  10617. lastError = "incorrect xml header";
  10618. }
  10619. }
  10620. return 0;
  10621. }
  10622. const String& XmlDocument::getLastParseError() const throw()
  10623. {
  10624. return lastError;
  10625. }
  10626. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10627. {
  10628. lastError = desc;
  10629. errorOccurred = ! carryOn;
  10630. }
  10631. const String XmlDocument::getFileContents (const String& filename) const
  10632. {
  10633. if (inputSource != 0)
  10634. {
  10635. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10636. if (in != 0)
  10637. return in->readEntireStreamAsString();
  10638. }
  10639. return String::empty;
  10640. }
  10641. juce_wchar XmlDocument::readNextChar() throw()
  10642. {
  10643. if (*input != 0)
  10644. {
  10645. return *input++;
  10646. }
  10647. else
  10648. {
  10649. outOfData = true;
  10650. return 0;
  10651. }
  10652. }
  10653. int XmlDocument::findNextTokenLength() throw()
  10654. {
  10655. int len = 0;
  10656. juce_wchar c = *input;
  10657. while (isXmlIdentifierChar (c))
  10658. c = input [++len];
  10659. return len;
  10660. }
  10661. void XmlDocument::skipHeader()
  10662. {
  10663. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  10664. if (found != 0)
  10665. {
  10666. input = found;
  10667. input = CharacterFunctions::find (input, JUCE_T("?>"));
  10668. if (input == 0)
  10669. return;
  10670. input += 2;
  10671. }
  10672. skipNextWhiteSpace();
  10673. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  10674. if (docType == 0)
  10675. return;
  10676. input = docType + 9;
  10677. int n = 1;
  10678. while (n > 0)
  10679. {
  10680. const juce_wchar c = readNextChar();
  10681. if (outOfData)
  10682. return;
  10683. if (c == '<')
  10684. ++n;
  10685. else if (c == '>')
  10686. --n;
  10687. }
  10688. docType += 9;
  10689. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10690. }
  10691. void XmlDocument::skipNextWhiteSpace()
  10692. {
  10693. for (;;)
  10694. {
  10695. juce_wchar c = *input;
  10696. while (CharacterFunctions::isWhitespace (c))
  10697. c = *++input;
  10698. if (c == 0)
  10699. {
  10700. outOfData = true;
  10701. break;
  10702. }
  10703. else if (c == '<')
  10704. {
  10705. if (input[1] == '!'
  10706. && input[2] == '-'
  10707. && input[3] == '-')
  10708. {
  10709. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  10710. if (closeComment == 0)
  10711. {
  10712. outOfData = true;
  10713. break;
  10714. }
  10715. input = closeComment + 3;
  10716. continue;
  10717. }
  10718. else if (input[1] == '?')
  10719. {
  10720. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  10721. if (closeBracket == 0)
  10722. {
  10723. outOfData = true;
  10724. break;
  10725. }
  10726. input = closeBracket + 2;
  10727. continue;
  10728. }
  10729. }
  10730. break;
  10731. }
  10732. }
  10733. void XmlDocument::readQuotedString (String& result)
  10734. {
  10735. const juce_wchar quote = readNextChar();
  10736. while (! outOfData)
  10737. {
  10738. const juce_wchar c = readNextChar();
  10739. if (c == quote)
  10740. break;
  10741. if (c == '&')
  10742. {
  10743. --input;
  10744. readEntity (result);
  10745. }
  10746. else
  10747. {
  10748. --input;
  10749. const juce_wchar* const start = input;
  10750. for (;;)
  10751. {
  10752. const juce_wchar character = *input;
  10753. if (character == quote)
  10754. {
  10755. result.append (start, (int) (input - start));
  10756. ++input;
  10757. return;
  10758. }
  10759. else if (character == '&')
  10760. {
  10761. result.append (start, (int) (input - start));
  10762. break;
  10763. }
  10764. else if (character == 0)
  10765. {
  10766. outOfData = true;
  10767. setLastError ("unmatched quotes", false);
  10768. break;
  10769. }
  10770. ++input;
  10771. }
  10772. }
  10773. }
  10774. }
  10775. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10776. {
  10777. XmlElement* node = 0;
  10778. skipNextWhiteSpace();
  10779. if (outOfData)
  10780. return 0;
  10781. input = CharacterFunctions::find (input, JUCE_T("<"));
  10782. if (input != 0)
  10783. {
  10784. ++input;
  10785. int tagLen = findNextTokenLength();
  10786. if (tagLen == 0)
  10787. {
  10788. // no tag name - but allow for a gap after the '<' before giving an error
  10789. skipNextWhiteSpace();
  10790. tagLen = findNextTokenLength();
  10791. if (tagLen == 0)
  10792. {
  10793. setLastError ("tag name missing", false);
  10794. return node;
  10795. }
  10796. }
  10797. node = new XmlElement (String (input, tagLen));
  10798. input += tagLen;
  10799. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10800. // look for attributes
  10801. for (;;)
  10802. {
  10803. skipNextWhiteSpace();
  10804. const juce_wchar c = *input;
  10805. // empty tag..
  10806. if (c == '/' && input[1] == '>')
  10807. {
  10808. input += 2;
  10809. break;
  10810. }
  10811. // parse the guts of the element..
  10812. if (c == '>')
  10813. {
  10814. ++input;
  10815. skipNextWhiteSpace();
  10816. if (alsoParseSubElements)
  10817. readChildElements (node);
  10818. break;
  10819. }
  10820. // get an attribute..
  10821. if (isXmlIdentifierChar (c))
  10822. {
  10823. const int attNameLen = findNextTokenLength();
  10824. if (attNameLen > 0)
  10825. {
  10826. const juce_wchar* attNameStart = input;
  10827. input += attNameLen;
  10828. skipNextWhiteSpace();
  10829. if (readNextChar() == '=')
  10830. {
  10831. skipNextWhiteSpace();
  10832. const juce_wchar nextChar = *input;
  10833. if (nextChar == '"' || nextChar == '\'')
  10834. {
  10835. XmlElement::XmlAttributeNode* const newAtt
  10836. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10837. String::empty);
  10838. readQuotedString (newAtt->value);
  10839. if (lastAttribute == 0)
  10840. node->attributes = newAtt;
  10841. else
  10842. lastAttribute->next = newAtt;
  10843. lastAttribute = newAtt;
  10844. continue;
  10845. }
  10846. }
  10847. }
  10848. }
  10849. else
  10850. {
  10851. if (! outOfData)
  10852. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10853. }
  10854. break;
  10855. }
  10856. }
  10857. return node;
  10858. }
  10859. void XmlDocument::readChildElements (XmlElement* parent)
  10860. {
  10861. XmlElement* lastChildNode = 0;
  10862. for (;;)
  10863. {
  10864. skipNextWhiteSpace();
  10865. if (outOfData)
  10866. {
  10867. setLastError ("unmatched tags", false);
  10868. break;
  10869. }
  10870. if (*input == '<')
  10871. {
  10872. if (input[1] == '/')
  10873. {
  10874. // our close tag..
  10875. input = CharacterFunctions::find (input, JUCE_T(">"));
  10876. ++input;
  10877. break;
  10878. }
  10879. else if (input[1] == '!'
  10880. && input[2] == '['
  10881. && input[3] == 'C'
  10882. && input[4] == 'D'
  10883. && input[5] == 'A'
  10884. && input[6] == 'T'
  10885. && input[7] == 'A'
  10886. && input[8] == '[')
  10887. {
  10888. input += 9;
  10889. const juce_wchar* const inputStart = input;
  10890. int len = 0;
  10891. for (;;)
  10892. {
  10893. if (*input == 0)
  10894. {
  10895. setLastError ("unterminated CDATA section", false);
  10896. outOfData = true;
  10897. break;
  10898. }
  10899. else if (input[0] == ']'
  10900. && input[1] == ']'
  10901. && input[2] == '>')
  10902. {
  10903. input += 3;
  10904. break;
  10905. }
  10906. ++input;
  10907. ++len;
  10908. }
  10909. XmlElement* const e = new XmlElement ((int) 0);
  10910. e->setText (String (inputStart, len));
  10911. if (lastChildNode != 0)
  10912. lastChildNode->nextElement = e;
  10913. else
  10914. parent->addChildElement (e);
  10915. lastChildNode = e;
  10916. }
  10917. else
  10918. {
  10919. // this is some other element, so parse and add it..
  10920. XmlElement* const n = readNextElement (true);
  10921. if (n != 0)
  10922. {
  10923. if (lastChildNode == 0)
  10924. parent->addChildElement (n);
  10925. else
  10926. lastChildNode->nextElement = n;
  10927. lastChildNode = n;
  10928. }
  10929. else
  10930. {
  10931. return;
  10932. }
  10933. }
  10934. }
  10935. else
  10936. {
  10937. // read character block..
  10938. XmlElement* const e = new XmlElement ((int)0);
  10939. if (lastChildNode != 0)
  10940. lastChildNode->nextElement = e;
  10941. else
  10942. parent->addChildElement (e);
  10943. lastChildNode = e;
  10944. String textElementContent;
  10945. for (;;)
  10946. {
  10947. const juce_wchar c = *input;
  10948. if (c == '<')
  10949. break;
  10950. if (c == 0)
  10951. {
  10952. setLastError ("unmatched tags", false);
  10953. outOfData = true;
  10954. return;
  10955. }
  10956. if (c == '&')
  10957. {
  10958. String entity;
  10959. readEntity (entity);
  10960. if (entity.startsWithChar ('<') && entity [1] != 0)
  10961. {
  10962. const juce_wchar* const oldInput = input;
  10963. const bool oldOutOfData = outOfData;
  10964. input = entity;
  10965. outOfData = false;
  10966. for (;;)
  10967. {
  10968. XmlElement* const n = readNextElement (true);
  10969. if (n == 0)
  10970. break;
  10971. if (lastChildNode == 0)
  10972. parent->addChildElement (n);
  10973. else
  10974. lastChildNode->nextElement = n;
  10975. lastChildNode = n;
  10976. }
  10977. input = oldInput;
  10978. outOfData = oldOutOfData;
  10979. }
  10980. else
  10981. {
  10982. textElementContent += entity;
  10983. }
  10984. }
  10985. else
  10986. {
  10987. const juce_wchar* start = input;
  10988. int len = 0;
  10989. for (;;)
  10990. {
  10991. const juce_wchar nextChar = *input;
  10992. if (nextChar == '<' || nextChar == '&')
  10993. {
  10994. break;
  10995. }
  10996. else if (nextChar == 0)
  10997. {
  10998. setLastError ("unmatched tags", false);
  10999. outOfData = true;
  11000. return;
  11001. }
  11002. ++input;
  11003. ++len;
  11004. }
  11005. textElementContent.append (start, len);
  11006. }
  11007. }
  11008. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11009. : textElementContent.isNotEmpty())
  11010. e->setText (textElementContent);
  11011. }
  11012. }
  11013. }
  11014. void XmlDocument::readEntity (String& result)
  11015. {
  11016. // skip over the ampersand
  11017. ++input;
  11018. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  11019. {
  11020. input += 4;
  11021. result += '&';
  11022. }
  11023. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  11024. {
  11025. input += 5;
  11026. result += '"';
  11027. }
  11028. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  11029. {
  11030. input += 5;
  11031. result += '\'';
  11032. }
  11033. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  11034. {
  11035. input += 3;
  11036. result += '<';
  11037. }
  11038. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  11039. {
  11040. input += 3;
  11041. result += '>';
  11042. }
  11043. else if (*input == '#')
  11044. {
  11045. int charCode = 0;
  11046. ++input;
  11047. if (*input == 'x' || *input == 'X')
  11048. {
  11049. ++input;
  11050. int numChars = 0;
  11051. while (input[0] != ';')
  11052. {
  11053. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11054. if (hexValue < 0 || ++numChars > 8)
  11055. {
  11056. setLastError ("illegal escape sequence", true);
  11057. break;
  11058. }
  11059. charCode = (charCode << 4) | hexValue;
  11060. ++input;
  11061. }
  11062. ++input;
  11063. }
  11064. else if (input[0] >= '0' && input[0] <= '9')
  11065. {
  11066. int numChars = 0;
  11067. while (input[0] != ';')
  11068. {
  11069. if (++numChars > 12)
  11070. {
  11071. setLastError ("illegal escape sequence", true);
  11072. break;
  11073. }
  11074. charCode = charCode * 10 + (input[0] - '0');
  11075. ++input;
  11076. }
  11077. ++input;
  11078. }
  11079. else
  11080. {
  11081. setLastError ("illegal escape sequence", true);
  11082. result += '&';
  11083. return;
  11084. }
  11085. result << (juce_wchar) charCode;
  11086. }
  11087. else
  11088. {
  11089. const juce_wchar* const entityNameStart = input;
  11090. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  11091. if (closingSemiColon == 0)
  11092. {
  11093. outOfData = true;
  11094. result += '&';
  11095. }
  11096. else
  11097. {
  11098. input = closingSemiColon + 1;
  11099. result += expandExternalEntity (String (entityNameStart,
  11100. (int) (closingSemiColon - entityNameStart)));
  11101. }
  11102. }
  11103. }
  11104. const String XmlDocument::expandEntity (const String& ent)
  11105. {
  11106. if (ent.equalsIgnoreCase ("amp"))
  11107. return String::charToString ('&');
  11108. if (ent.equalsIgnoreCase ("quot"))
  11109. return String::charToString ('"');
  11110. if (ent.equalsIgnoreCase ("apos"))
  11111. return String::charToString ('\'');
  11112. if (ent.equalsIgnoreCase ("lt"))
  11113. return String::charToString ('<');
  11114. if (ent.equalsIgnoreCase ("gt"))
  11115. return String::charToString ('>');
  11116. if (ent[0] == '#')
  11117. {
  11118. if (ent[1] == 'x' || ent[1] == 'X')
  11119. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  11120. if (ent[1] >= '0' && ent[1] <= '9')
  11121. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  11122. setLastError ("illegal escape sequence", false);
  11123. return String::charToString ('&');
  11124. }
  11125. return expandExternalEntity (ent);
  11126. }
  11127. const String XmlDocument::expandExternalEntity (const String& entity)
  11128. {
  11129. if (needToLoadDTD)
  11130. {
  11131. if (dtdText.isNotEmpty())
  11132. {
  11133. dtdText = dtdText.trimCharactersAtEnd (">");
  11134. tokenisedDTD.addTokens (dtdText, true);
  11135. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  11136. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11137. {
  11138. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11139. tokenisedDTD.clear();
  11140. tokenisedDTD.addTokens (getFileContents (fn), true);
  11141. }
  11142. else
  11143. {
  11144. tokenisedDTD.clear();
  11145. const int openBracket = dtdText.indexOfChar ('[');
  11146. if (openBracket > 0)
  11147. {
  11148. const int closeBracket = dtdText.lastIndexOfChar (']');
  11149. if (closeBracket > openBracket)
  11150. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11151. closeBracket), true);
  11152. }
  11153. }
  11154. for (int i = tokenisedDTD.size(); --i >= 0;)
  11155. {
  11156. if (tokenisedDTD[i].startsWithChar ('%')
  11157. && tokenisedDTD[i].endsWithChar (';'))
  11158. {
  11159. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11160. StringArray newToks;
  11161. newToks.addTokens (parsed, true);
  11162. tokenisedDTD.remove (i);
  11163. for (int j = newToks.size(); --j >= 0;)
  11164. tokenisedDTD.insert (i, newToks[j]);
  11165. }
  11166. }
  11167. }
  11168. needToLoadDTD = false;
  11169. }
  11170. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11171. {
  11172. if (tokenisedDTD[i] == entity)
  11173. {
  11174. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11175. {
  11176. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11177. // check for sub-entities..
  11178. int ampersand = ent.indexOfChar ('&');
  11179. while (ampersand >= 0)
  11180. {
  11181. const int semiColon = ent.indexOf (i + 1, ";");
  11182. if (semiColon < 0)
  11183. {
  11184. setLastError ("entity without terminating semi-colon", false);
  11185. break;
  11186. }
  11187. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11188. ent = ent.substring (0, ampersand)
  11189. + resolved
  11190. + ent.substring (semiColon + 1);
  11191. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11192. }
  11193. return ent;
  11194. }
  11195. }
  11196. }
  11197. setLastError ("unknown entity", true);
  11198. return entity;
  11199. }
  11200. const String XmlDocument::getParameterEntity (const String& entity)
  11201. {
  11202. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11203. {
  11204. if (tokenisedDTD[i] == entity)
  11205. {
  11206. if (tokenisedDTD [i - 1] == "%"
  11207. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11208. {
  11209. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11210. if (ent.equalsIgnoreCase ("system"))
  11211. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11212. else
  11213. return ent.trim().unquoted();
  11214. }
  11215. }
  11216. }
  11217. return entity;
  11218. }
  11219. END_JUCE_NAMESPACE
  11220. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11221. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11222. BEGIN_JUCE_NAMESPACE
  11223. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11224. : name (other.name),
  11225. value (other.value),
  11226. next (0)
  11227. {
  11228. }
  11229. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11230. : name (name_),
  11231. value (value_),
  11232. next (0)
  11233. {
  11234. }
  11235. XmlElement::XmlElement (const String& tagName_) throw()
  11236. : tagName (tagName_),
  11237. firstChildElement (0),
  11238. nextElement (0),
  11239. attributes (0)
  11240. {
  11241. // the tag name mustn't be empty, or it'll look like a text element!
  11242. jassert (tagName_.containsNonWhitespaceChars())
  11243. // The tag can't contain spaces or other characters that would create invalid XML!
  11244. jassert (! tagName_.containsAnyOf (" <>/&"));
  11245. }
  11246. XmlElement::XmlElement (int /*dummy*/) throw()
  11247. : firstChildElement (0),
  11248. nextElement (0),
  11249. attributes (0)
  11250. {
  11251. }
  11252. XmlElement::XmlElement (const XmlElement& other)
  11253. : tagName (other.tagName),
  11254. firstChildElement (0),
  11255. nextElement (0),
  11256. attributes (0)
  11257. {
  11258. copyChildrenAndAttributesFrom (other);
  11259. }
  11260. XmlElement& XmlElement::operator= (const XmlElement& other)
  11261. {
  11262. if (this != &other)
  11263. {
  11264. removeAllAttributes();
  11265. deleteAllChildElements();
  11266. tagName = other.tagName;
  11267. copyChildrenAndAttributesFrom (other);
  11268. }
  11269. return *this;
  11270. }
  11271. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  11272. {
  11273. XmlElement* child = other.firstChildElement;
  11274. XmlElement* lastChild = 0;
  11275. while (child != 0)
  11276. {
  11277. XmlElement* const copiedChild = new XmlElement (*child);
  11278. if (lastChild != 0)
  11279. lastChild->nextElement = copiedChild;
  11280. else
  11281. firstChildElement = copiedChild;
  11282. lastChild = copiedChild;
  11283. child = child->nextElement;
  11284. }
  11285. const XmlAttributeNode* att = other.attributes;
  11286. XmlAttributeNode* lastAtt = 0;
  11287. while (att != 0)
  11288. {
  11289. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11290. if (lastAtt != 0)
  11291. lastAtt->next = newAtt;
  11292. else
  11293. attributes = newAtt;
  11294. lastAtt = newAtt;
  11295. att = att->next;
  11296. }
  11297. }
  11298. XmlElement::~XmlElement() throw()
  11299. {
  11300. XmlElement* child = firstChildElement;
  11301. while (child != 0)
  11302. {
  11303. XmlElement* const nextChild = child->nextElement;
  11304. delete child;
  11305. child = nextChild;
  11306. }
  11307. XmlAttributeNode* att = attributes;
  11308. while (att != 0)
  11309. {
  11310. XmlAttributeNode* const nextAtt = att->next;
  11311. delete att;
  11312. att = nextAtt;
  11313. }
  11314. }
  11315. namespace XmlOutputFunctions
  11316. {
  11317. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11318. {
  11319. if ((character >= 'a' && character <= 'z')
  11320. || (character >= 'A' && character <= 'Z')
  11321. || (character >= '0' && character <= '9'))
  11322. return true;
  11323. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11324. do
  11325. {
  11326. if (((juce_wchar) (uint8) *t) == character)
  11327. return true;
  11328. }
  11329. while (*++t != 0);
  11330. return false;
  11331. }
  11332. static void generateLegalCharConstants()
  11333. {
  11334. uint8 n[32];
  11335. zerostruct (n);
  11336. for (int i = 0; i < 256; ++i)
  11337. if (isLegalXmlCharSlow (i))
  11338. n[i >> 3] |= (1 << (i & 7));
  11339. String s;
  11340. for (int i = 0; i < 32; ++i)
  11341. s << (int) n[i] << ", ";
  11342. DBG (s);
  11343. }*/
  11344. static bool isLegalXmlChar (const uint32 c) throw()
  11345. {
  11346. static const unsigned char legalChars[] = { 0, 0, 0, 0, 171, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 111 };
  11347. return c < sizeof (legalChars) * 8
  11348. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11349. }
  11350. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11351. {
  11352. const juce_wchar* t = text;
  11353. for (;;)
  11354. {
  11355. const juce_wchar character = *t++;
  11356. if (character == 0)
  11357. {
  11358. break;
  11359. }
  11360. else if (isLegalXmlChar ((uint32) character))
  11361. {
  11362. outputStream << (char) character;
  11363. }
  11364. else
  11365. {
  11366. switch (character)
  11367. {
  11368. case '&': outputStream << "&amp;"; break;
  11369. case '"': outputStream << "&quot;"; break;
  11370. case '>': outputStream << "&gt;"; break;
  11371. case '<': outputStream << "&lt;"; break;
  11372. case '\n':
  11373. if (changeNewLines)
  11374. outputStream << "&#10;";
  11375. else
  11376. outputStream << (char) character;
  11377. break;
  11378. case '\r':
  11379. if (changeNewLines)
  11380. outputStream << "&#13;";
  11381. else
  11382. outputStream << (char) character;
  11383. break;
  11384. default:
  11385. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11386. break;
  11387. }
  11388. }
  11389. }
  11390. }
  11391. static void writeSpaces (OutputStream& out, int numSpaces)
  11392. {
  11393. if (numSpaces > 0)
  11394. {
  11395. const char* const blanks = " ";
  11396. const int blankSize = (int) sizeof (blanks) - 1;
  11397. while (numSpaces > blankSize)
  11398. {
  11399. out.write (blanks, blankSize);
  11400. numSpaces -= blankSize;
  11401. }
  11402. out.write (blanks, numSpaces);
  11403. }
  11404. }
  11405. }
  11406. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11407. const int indentationLevel,
  11408. const int lineWrapLength) const
  11409. {
  11410. using namespace XmlOutputFunctions;
  11411. writeSpaces (outputStream, indentationLevel);
  11412. if (! isTextElement())
  11413. {
  11414. outputStream.writeByte ('<');
  11415. outputStream << tagName;
  11416. const int attIndent = indentationLevel + tagName.length() + 1;
  11417. int lineLen = 0;
  11418. const XmlAttributeNode* att = attributes;
  11419. while (att != 0)
  11420. {
  11421. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11422. {
  11423. outputStream.write ("\r\n", 2);
  11424. writeSpaces (outputStream, attIndent);
  11425. lineLen = 0;
  11426. }
  11427. const int64 startPos = outputStream.getPosition();
  11428. outputStream.writeByte (' ');
  11429. outputStream << att->name;
  11430. outputStream.write ("=\"", 2);
  11431. escapeIllegalXmlChars (outputStream, att->value, true);
  11432. outputStream.writeByte ('"');
  11433. lineLen += (int) (outputStream.getPosition() - startPos);
  11434. att = att->next;
  11435. }
  11436. if (firstChildElement != 0)
  11437. {
  11438. XmlElement* child = firstChildElement;
  11439. if (child->nextElement == 0 && child->isTextElement())
  11440. {
  11441. outputStream.writeByte ('>');
  11442. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11443. }
  11444. else
  11445. {
  11446. if (indentationLevel >= 0)
  11447. outputStream.write (">\r\n", 3);
  11448. else
  11449. outputStream.writeByte ('>');
  11450. bool lastWasTextNode = false;
  11451. while (child != 0)
  11452. {
  11453. if (child->isTextElement())
  11454. {
  11455. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11456. writeSpaces (outputStream, indentationLevel + 2);
  11457. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11458. lastWasTextNode = true;
  11459. }
  11460. else
  11461. {
  11462. if (indentationLevel >= 0)
  11463. {
  11464. if (lastWasTextNode)
  11465. outputStream.write ("\r\n", 2);
  11466. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11467. }
  11468. else
  11469. {
  11470. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11471. }
  11472. lastWasTextNode = false;
  11473. }
  11474. child = child->nextElement;
  11475. }
  11476. if (indentationLevel >= 0)
  11477. {
  11478. if (lastWasTextNode)
  11479. outputStream.write ("\r\n", 2);
  11480. writeSpaces (outputStream, indentationLevel);
  11481. }
  11482. }
  11483. outputStream.write ("</", 2);
  11484. outputStream << tagName;
  11485. if (indentationLevel >= 0)
  11486. outputStream.write (">\r\n", 3);
  11487. else
  11488. outputStream.writeByte ('>');
  11489. }
  11490. else
  11491. {
  11492. if (indentationLevel >= 0)
  11493. outputStream.write ("/>\r\n", 4);
  11494. else
  11495. outputStream.write ("/>", 2);
  11496. }
  11497. }
  11498. else
  11499. {
  11500. if (indentationLevel >= 0)
  11501. writeSpaces (outputStream, indentationLevel + 2);
  11502. escapeIllegalXmlChars (outputStream, getText(), false);
  11503. }
  11504. }
  11505. const String XmlElement::createDocument (const String& dtdToUse,
  11506. const bool allOnOneLine,
  11507. const bool includeXmlHeader,
  11508. const String& encodingType,
  11509. const int lineWrapLength) const
  11510. {
  11511. MemoryOutputStream mem (2048, 4096);
  11512. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11513. return mem.toUTF8();
  11514. }
  11515. void XmlElement::writeToStream (OutputStream& output,
  11516. const String& dtdToUse,
  11517. const bool allOnOneLine,
  11518. const bool includeXmlHeader,
  11519. const String& encodingType,
  11520. const int lineWrapLength) const
  11521. {
  11522. if (includeXmlHeader)
  11523. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11524. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11525. if (dtdToUse.isNotEmpty())
  11526. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11527. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11528. }
  11529. bool XmlElement::writeToFile (const File& file,
  11530. const String& dtdToUse,
  11531. const String& encodingType,
  11532. const int lineWrapLength) const
  11533. {
  11534. if (file.hasWriteAccess())
  11535. {
  11536. TemporaryFile tempFile (file);
  11537. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11538. if (out != 0)
  11539. {
  11540. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11541. out = 0;
  11542. return tempFile.overwriteTargetFileWithTemporary();
  11543. }
  11544. }
  11545. return false;
  11546. }
  11547. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11548. {
  11549. #if JUCE_DEBUG
  11550. // if debugging, check that the case is actually the same, because
  11551. // valid xml is case-sensitive, and although this lets it pass, it's
  11552. // better not to..
  11553. if (tagName.equalsIgnoreCase (tagNameWanted))
  11554. {
  11555. jassert (tagName == tagNameWanted);
  11556. return true;
  11557. }
  11558. else
  11559. {
  11560. return false;
  11561. }
  11562. #else
  11563. return tagName.equalsIgnoreCase (tagNameWanted);
  11564. #endif
  11565. }
  11566. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11567. {
  11568. XmlElement* e = nextElement;
  11569. while (e != 0 && ! e->hasTagName (requiredTagName))
  11570. e = e->nextElement;
  11571. return e;
  11572. }
  11573. int XmlElement::getNumAttributes() const throw()
  11574. {
  11575. const XmlAttributeNode* att = attributes;
  11576. int count = 0;
  11577. while (att != 0)
  11578. {
  11579. att = att->next;
  11580. ++count;
  11581. }
  11582. return count;
  11583. }
  11584. const String& XmlElement::getAttributeName (const int index) const throw()
  11585. {
  11586. const XmlAttributeNode* att = attributes;
  11587. int count = 0;
  11588. while (att != 0)
  11589. {
  11590. if (count == index)
  11591. return att->name;
  11592. att = att->next;
  11593. ++count;
  11594. }
  11595. return String::empty;
  11596. }
  11597. const String& XmlElement::getAttributeValue (const int index) const throw()
  11598. {
  11599. const XmlAttributeNode* att = attributes;
  11600. int count = 0;
  11601. while (att != 0)
  11602. {
  11603. if (count == index)
  11604. return att->value;
  11605. att = att->next;
  11606. ++count;
  11607. }
  11608. return String::empty;
  11609. }
  11610. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11611. {
  11612. const XmlAttributeNode* att = attributes;
  11613. while (att != 0)
  11614. {
  11615. if (att->name.equalsIgnoreCase (attributeName))
  11616. return true;
  11617. att = att->next;
  11618. }
  11619. return false;
  11620. }
  11621. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11622. {
  11623. const XmlAttributeNode* att = attributes;
  11624. while (att != 0)
  11625. {
  11626. if (att->name.equalsIgnoreCase (attributeName))
  11627. return att->value;
  11628. att = att->next;
  11629. }
  11630. return String::empty;
  11631. }
  11632. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11633. {
  11634. const XmlAttributeNode* att = attributes;
  11635. while (att != 0)
  11636. {
  11637. if (att->name.equalsIgnoreCase (attributeName))
  11638. return att->value;
  11639. att = att->next;
  11640. }
  11641. return defaultReturnValue;
  11642. }
  11643. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11644. {
  11645. const XmlAttributeNode* att = attributes;
  11646. while (att != 0)
  11647. {
  11648. if (att->name.equalsIgnoreCase (attributeName))
  11649. return att->value.getIntValue();
  11650. att = att->next;
  11651. }
  11652. return defaultReturnValue;
  11653. }
  11654. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11655. {
  11656. const XmlAttributeNode* att = attributes;
  11657. while (att != 0)
  11658. {
  11659. if (att->name.equalsIgnoreCase (attributeName))
  11660. return att->value.getDoubleValue();
  11661. att = att->next;
  11662. }
  11663. return defaultReturnValue;
  11664. }
  11665. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11666. {
  11667. const XmlAttributeNode* att = attributes;
  11668. while (att != 0)
  11669. {
  11670. if (att->name.equalsIgnoreCase (attributeName))
  11671. {
  11672. juce_wchar firstChar = att->value[0];
  11673. if (CharacterFunctions::isWhitespace (firstChar))
  11674. firstChar = att->value.trimStart() [0];
  11675. return firstChar == '1'
  11676. || firstChar == 't'
  11677. || firstChar == 'y'
  11678. || firstChar == 'T'
  11679. || firstChar == 'Y';
  11680. }
  11681. att = att->next;
  11682. }
  11683. return defaultReturnValue;
  11684. }
  11685. bool XmlElement::compareAttribute (const String& attributeName,
  11686. const String& stringToCompareAgainst,
  11687. const bool ignoreCase) const throw()
  11688. {
  11689. const XmlAttributeNode* att = attributes;
  11690. while (att != 0)
  11691. {
  11692. if (att->name.equalsIgnoreCase (attributeName))
  11693. {
  11694. if (ignoreCase)
  11695. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11696. else
  11697. return att->value == stringToCompareAgainst;
  11698. }
  11699. att = att->next;
  11700. }
  11701. return false;
  11702. }
  11703. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11704. {
  11705. #if JUCE_DEBUG
  11706. // check the identifier being passed in is legal..
  11707. const juce_wchar* t = attributeName;
  11708. while (*t != 0)
  11709. {
  11710. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11711. || *t == '_'
  11712. || *t == '-'
  11713. || *t == ':');
  11714. ++t;
  11715. }
  11716. #endif
  11717. if (attributes == 0)
  11718. {
  11719. attributes = new XmlAttributeNode (attributeName, value);
  11720. }
  11721. else
  11722. {
  11723. XmlAttributeNode* att = attributes;
  11724. for (;;)
  11725. {
  11726. if (att->name.equalsIgnoreCase (attributeName))
  11727. {
  11728. att->value = value;
  11729. break;
  11730. }
  11731. else if (att->next == 0)
  11732. {
  11733. att->next = new XmlAttributeNode (attributeName, value);
  11734. break;
  11735. }
  11736. att = att->next;
  11737. }
  11738. }
  11739. }
  11740. void XmlElement::setAttribute (const String& attributeName, const int number)
  11741. {
  11742. setAttribute (attributeName, String (number));
  11743. }
  11744. void XmlElement::setAttribute (const String& attributeName, const double number)
  11745. {
  11746. setAttribute (attributeName, String (number));
  11747. }
  11748. void XmlElement::removeAttribute (const String& attributeName) throw()
  11749. {
  11750. XmlAttributeNode* att = attributes;
  11751. XmlAttributeNode* lastAtt = 0;
  11752. while (att != 0)
  11753. {
  11754. if (att->name.equalsIgnoreCase (attributeName))
  11755. {
  11756. if (lastAtt == 0)
  11757. attributes = att->next;
  11758. else
  11759. lastAtt->next = att->next;
  11760. delete att;
  11761. break;
  11762. }
  11763. lastAtt = att;
  11764. att = att->next;
  11765. }
  11766. }
  11767. void XmlElement::removeAllAttributes() throw()
  11768. {
  11769. while (attributes != 0)
  11770. {
  11771. XmlAttributeNode* const nextAtt = attributes->next;
  11772. delete attributes;
  11773. attributes = nextAtt;
  11774. }
  11775. }
  11776. int XmlElement::getNumChildElements() const throw()
  11777. {
  11778. int count = 0;
  11779. const XmlElement* child = firstChildElement;
  11780. while (child != 0)
  11781. {
  11782. ++count;
  11783. child = child->nextElement;
  11784. }
  11785. return count;
  11786. }
  11787. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11788. {
  11789. int count = 0;
  11790. XmlElement* child = firstChildElement;
  11791. while (child != 0 && count < index)
  11792. {
  11793. child = child->nextElement;
  11794. ++count;
  11795. }
  11796. return child;
  11797. }
  11798. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11799. {
  11800. XmlElement* child = firstChildElement;
  11801. while (child != 0)
  11802. {
  11803. if (child->hasTagName (childName))
  11804. break;
  11805. child = child->nextElement;
  11806. }
  11807. return child;
  11808. }
  11809. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11810. {
  11811. if (newNode != 0)
  11812. {
  11813. if (firstChildElement == 0)
  11814. {
  11815. firstChildElement = newNode;
  11816. }
  11817. else
  11818. {
  11819. XmlElement* child = firstChildElement;
  11820. while (child->nextElement != 0)
  11821. child = child->nextElement;
  11822. child->nextElement = newNode;
  11823. // if this is non-zero, then something's probably
  11824. // gone wrong..
  11825. jassert (newNode->nextElement == 0);
  11826. }
  11827. }
  11828. }
  11829. void XmlElement::insertChildElement (XmlElement* const newNode,
  11830. int indexToInsertAt) throw()
  11831. {
  11832. if (newNode != 0)
  11833. {
  11834. removeChildElement (newNode, false);
  11835. if (indexToInsertAt == 0)
  11836. {
  11837. newNode->nextElement = firstChildElement;
  11838. firstChildElement = newNode;
  11839. }
  11840. else
  11841. {
  11842. if (firstChildElement == 0)
  11843. {
  11844. firstChildElement = newNode;
  11845. }
  11846. else
  11847. {
  11848. if (indexToInsertAt < 0)
  11849. indexToInsertAt = std::numeric_limits<int>::max();
  11850. XmlElement* child = firstChildElement;
  11851. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11852. child = child->nextElement;
  11853. newNode->nextElement = child->nextElement;
  11854. child->nextElement = newNode;
  11855. }
  11856. }
  11857. }
  11858. }
  11859. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  11860. {
  11861. XmlElement* const newElement = new XmlElement (childTagName);
  11862. addChildElement (newElement);
  11863. return newElement;
  11864. }
  11865. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11866. XmlElement* const newNode) throw()
  11867. {
  11868. if (newNode != 0)
  11869. {
  11870. XmlElement* child = firstChildElement;
  11871. XmlElement* previousNode = 0;
  11872. while (child != 0)
  11873. {
  11874. if (child == currentChildElement)
  11875. {
  11876. if (child != newNode)
  11877. {
  11878. if (previousNode == 0)
  11879. firstChildElement = newNode;
  11880. else
  11881. previousNode->nextElement = newNode;
  11882. newNode->nextElement = child->nextElement;
  11883. delete child;
  11884. }
  11885. return true;
  11886. }
  11887. previousNode = child;
  11888. child = child->nextElement;
  11889. }
  11890. }
  11891. return false;
  11892. }
  11893. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11894. const bool shouldDeleteTheChild) throw()
  11895. {
  11896. if (childToRemove != 0)
  11897. {
  11898. if (firstChildElement == childToRemove)
  11899. {
  11900. firstChildElement = childToRemove->nextElement;
  11901. childToRemove->nextElement = 0;
  11902. }
  11903. else
  11904. {
  11905. XmlElement* child = firstChildElement;
  11906. XmlElement* last = 0;
  11907. while (child != 0)
  11908. {
  11909. if (child == childToRemove)
  11910. {
  11911. if (last == 0)
  11912. firstChildElement = child->nextElement;
  11913. else
  11914. last->nextElement = child->nextElement;
  11915. childToRemove->nextElement = 0;
  11916. break;
  11917. }
  11918. last = child;
  11919. child = child->nextElement;
  11920. }
  11921. }
  11922. if (shouldDeleteTheChild)
  11923. delete childToRemove;
  11924. }
  11925. }
  11926. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  11927. const bool ignoreOrderOfAttributes) const throw()
  11928. {
  11929. if (this != other)
  11930. {
  11931. if (other == 0 || tagName != other->tagName)
  11932. {
  11933. return false;
  11934. }
  11935. if (ignoreOrderOfAttributes)
  11936. {
  11937. int totalAtts = 0;
  11938. const XmlAttributeNode* att = attributes;
  11939. while (att != 0)
  11940. {
  11941. if (! other->compareAttribute (att->name, att->value))
  11942. return false;
  11943. att = att->next;
  11944. ++totalAtts;
  11945. }
  11946. if (totalAtts != other->getNumAttributes())
  11947. return false;
  11948. }
  11949. else
  11950. {
  11951. const XmlAttributeNode* thisAtt = attributes;
  11952. const XmlAttributeNode* otherAtt = other->attributes;
  11953. for (;;)
  11954. {
  11955. if (thisAtt == 0 || otherAtt == 0)
  11956. {
  11957. if (thisAtt == otherAtt) // both 0, so it's a match
  11958. break;
  11959. return false;
  11960. }
  11961. if (thisAtt->name != otherAtt->name
  11962. || thisAtt->value != otherAtt->value)
  11963. {
  11964. return false;
  11965. }
  11966. thisAtt = thisAtt->next;
  11967. otherAtt = otherAtt->next;
  11968. }
  11969. }
  11970. const XmlElement* thisChild = firstChildElement;
  11971. const XmlElement* otherChild = other->firstChildElement;
  11972. for (;;)
  11973. {
  11974. if (thisChild == 0 || otherChild == 0)
  11975. {
  11976. if (thisChild == otherChild) // both 0, so it's a match
  11977. break;
  11978. return false;
  11979. }
  11980. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  11981. return false;
  11982. thisChild = thisChild->nextElement;
  11983. otherChild = otherChild->nextElement;
  11984. }
  11985. }
  11986. return true;
  11987. }
  11988. void XmlElement::deleteAllChildElements() throw()
  11989. {
  11990. while (firstChildElement != 0)
  11991. {
  11992. XmlElement* const nextChild = firstChildElement->nextElement;
  11993. delete firstChildElement;
  11994. firstChildElement = nextChild;
  11995. }
  11996. }
  11997. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  11998. {
  11999. XmlElement* child = firstChildElement;
  12000. while (child != 0)
  12001. {
  12002. if (child->hasTagName (name))
  12003. {
  12004. XmlElement* const nextChild = child->nextElement;
  12005. removeChildElement (child, true);
  12006. child = nextChild;
  12007. }
  12008. else
  12009. {
  12010. child = child->nextElement;
  12011. }
  12012. }
  12013. }
  12014. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12015. {
  12016. const XmlElement* child = firstChildElement;
  12017. while (child != 0)
  12018. {
  12019. if (child == possibleChild)
  12020. return true;
  12021. child = child->nextElement;
  12022. }
  12023. return false;
  12024. }
  12025. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12026. {
  12027. if (this == elementToLookFor || elementToLookFor == 0)
  12028. return 0;
  12029. XmlElement* child = firstChildElement;
  12030. while (child != 0)
  12031. {
  12032. if (elementToLookFor == child)
  12033. return this;
  12034. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12035. if (found != 0)
  12036. return found;
  12037. child = child->nextElement;
  12038. }
  12039. return 0;
  12040. }
  12041. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12042. {
  12043. XmlElement* e = firstChildElement;
  12044. while (e != 0)
  12045. {
  12046. *elems++ = e;
  12047. e = e->nextElement;
  12048. }
  12049. }
  12050. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12051. {
  12052. XmlElement* e = firstChildElement = elems[0];
  12053. for (int i = 1; i < num; ++i)
  12054. {
  12055. e->nextElement = elems[i];
  12056. e = e->nextElement;
  12057. }
  12058. e->nextElement = 0;
  12059. }
  12060. bool XmlElement::isTextElement() const throw()
  12061. {
  12062. return tagName.isEmpty();
  12063. }
  12064. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  12065. const String& XmlElement::getText() const throw()
  12066. {
  12067. jassert (isTextElement()); // you're trying to get the text from an element that
  12068. // isn't actually a text element.. If this contains text sub-nodes, you
  12069. // probably want to use getAllSubText instead.
  12070. return getStringAttribute (juce_xmltextContentAttributeName);
  12071. }
  12072. void XmlElement::setText (const String& newText)
  12073. {
  12074. if (isTextElement())
  12075. setAttribute (juce_xmltextContentAttributeName, newText);
  12076. else
  12077. jassertfalse; // you can only change the text in a text element, not a normal one.
  12078. }
  12079. const String XmlElement::getAllSubText() const
  12080. {
  12081. String result;
  12082. String::Concatenator concatenator (result);
  12083. const XmlElement* child = firstChildElement;
  12084. while (child != 0)
  12085. {
  12086. if (child->isTextElement())
  12087. concatenator.append (child->getText());
  12088. child = child->nextElement;
  12089. }
  12090. return result;
  12091. }
  12092. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12093. const String& defaultReturnValue) const
  12094. {
  12095. const XmlElement* const child = getChildByName (childTagName);
  12096. if (child != 0)
  12097. return child->getAllSubText();
  12098. return defaultReturnValue;
  12099. }
  12100. XmlElement* XmlElement::createTextElement (const String& text)
  12101. {
  12102. XmlElement* const e = new XmlElement ((int) 0);
  12103. e->setAttribute (juce_xmltextContentAttributeName, text);
  12104. return e;
  12105. }
  12106. void XmlElement::addTextElement (const String& text)
  12107. {
  12108. addChildElement (createTextElement (text));
  12109. }
  12110. void XmlElement::deleteAllTextElements() throw()
  12111. {
  12112. XmlElement* child = firstChildElement;
  12113. while (child != 0)
  12114. {
  12115. XmlElement* const next = child->nextElement;
  12116. if (child->isTextElement())
  12117. removeChildElement (child, true);
  12118. child = next;
  12119. }
  12120. }
  12121. END_JUCE_NAMESPACE
  12122. /*** End of inlined file: juce_XmlElement.cpp ***/
  12123. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12124. BEGIN_JUCE_NAMESPACE
  12125. ReadWriteLock::ReadWriteLock() throw()
  12126. : numWaitingWriters (0),
  12127. numWriters (0),
  12128. writerThreadId (0)
  12129. {
  12130. }
  12131. ReadWriteLock::~ReadWriteLock() throw()
  12132. {
  12133. jassert (readerThreads.size() == 0);
  12134. jassert (numWriters == 0);
  12135. }
  12136. void ReadWriteLock::enterRead() const throw()
  12137. {
  12138. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12139. const ScopedLock sl (accessLock);
  12140. for (;;)
  12141. {
  12142. jassert (readerThreads.size() % 2 == 0);
  12143. int i;
  12144. for (i = 0; i < readerThreads.size(); i += 2)
  12145. if (readerThreads.getUnchecked(i) == threadId)
  12146. break;
  12147. if (i < readerThreads.size()
  12148. || numWriters + numWaitingWriters == 0
  12149. || (threadId == writerThreadId && numWriters > 0))
  12150. {
  12151. if (i < readerThreads.size())
  12152. {
  12153. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12154. }
  12155. else
  12156. {
  12157. readerThreads.add (threadId);
  12158. readerThreads.add ((Thread::ThreadID) 1);
  12159. }
  12160. return;
  12161. }
  12162. const ScopedUnlock ul (accessLock);
  12163. waitEvent.wait (100);
  12164. }
  12165. }
  12166. void ReadWriteLock::exitRead() const throw()
  12167. {
  12168. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12169. const ScopedLock sl (accessLock);
  12170. for (int i = 0; i < readerThreads.size(); i += 2)
  12171. {
  12172. if (readerThreads.getUnchecked(i) == threadId)
  12173. {
  12174. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12175. if (newCount == 0)
  12176. {
  12177. readerThreads.removeRange (i, 2);
  12178. waitEvent.signal();
  12179. }
  12180. else
  12181. {
  12182. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12183. }
  12184. return;
  12185. }
  12186. }
  12187. jassertfalse; // unlocking a lock that wasn't locked..
  12188. }
  12189. void ReadWriteLock::enterWrite() const throw()
  12190. {
  12191. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12192. const ScopedLock sl (accessLock);
  12193. for (;;)
  12194. {
  12195. if (readerThreads.size() + numWriters == 0
  12196. || threadId == writerThreadId
  12197. || (readerThreads.size() == 2
  12198. && readerThreads.getUnchecked(0) == threadId))
  12199. {
  12200. writerThreadId = threadId;
  12201. ++numWriters;
  12202. break;
  12203. }
  12204. ++numWaitingWriters;
  12205. accessLock.exit();
  12206. waitEvent.wait (100);
  12207. accessLock.enter();
  12208. --numWaitingWriters;
  12209. }
  12210. }
  12211. bool ReadWriteLock::tryEnterWrite() const throw()
  12212. {
  12213. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12214. const ScopedLock sl (accessLock);
  12215. if (readerThreads.size() + numWriters == 0
  12216. || threadId == writerThreadId
  12217. || (readerThreads.size() == 2
  12218. && readerThreads.getUnchecked(0) == threadId))
  12219. {
  12220. writerThreadId = threadId;
  12221. ++numWriters;
  12222. return true;
  12223. }
  12224. return false;
  12225. }
  12226. void ReadWriteLock::exitWrite() const throw()
  12227. {
  12228. const ScopedLock sl (accessLock);
  12229. // check this thread actually had the lock..
  12230. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12231. if (--numWriters == 0)
  12232. {
  12233. writerThreadId = 0;
  12234. waitEvent.signal();
  12235. }
  12236. }
  12237. END_JUCE_NAMESPACE
  12238. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12239. /*** Start of inlined file: juce_Thread.cpp ***/
  12240. BEGIN_JUCE_NAMESPACE
  12241. // these functions are implemented in the platform-specific code.
  12242. void* juce_createThread (void* userData);
  12243. void juce_killThread (void* handle);
  12244. bool juce_setThreadPriority (void* handle, int priority);
  12245. void juce_setCurrentThreadName (const String& name);
  12246. #if JUCE_WINDOWS
  12247. void juce_CloseThreadHandle (void* handle);
  12248. #endif
  12249. void Thread::threadEntryPoint (Thread* const thread)
  12250. {
  12251. {
  12252. const ScopedLock sl (runningThreadsLock);
  12253. runningThreads.add (thread);
  12254. }
  12255. JUCE_TRY
  12256. {
  12257. thread->threadId_ = Thread::getCurrentThreadId();
  12258. if (thread->threadName_.isNotEmpty())
  12259. juce_setCurrentThreadName (thread->threadName_);
  12260. if (thread->startSuspensionEvent_.wait (10000))
  12261. {
  12262. if (thread->affinityMask_ != 0)
  12263. setCurrentThreadAffinityMask (thread->affinityMask_);
  12264. thread->run();
  12265. }
  12266. }
  12267. JUCE_CATCH_ALL_ASSERT
  12268. {
  12269. const ScopedLock sl (runningThreadsLock);
  12270. jassert (runningThreads.contains (thread));
  12271. runningThreads.removeValue (thread);
  12272. }
  12273. #if JUCE_WINDOWS
  12274. juce_CloseThreadHandle (thread->threadHandle_);
  12275. #endif
  12276. thread->threadHandle_ = 0;
  12277. thread->threadId_ = 0;
  12278. }
  12279. // used to wrap the incoming call from the platform-specific code
  12280. void JUCE_API juce_threadEntryPoint (void* userData)
  12281. {
  12282. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12283. }
  12284. Thread::Thread (const String& threadName)
  12285. : threadName_ (threadName),
  12286. threadHandle_ (0),
  12287. threadPriority_ (5),
  12288. threadId_ (0),
  12289. affinityMask_ (0),
  12290. threadShouldExit_ (false)
  12291. {
  12292. }
  12293. Thread::~Thread()
  12294. {
  12295. stopThread (100);
  12296. }
  12297. void Thread::startThread()
  12298. {
  12299. const ScopedLock sl (startStopLock);
  12300. threadShouldExit_ = false;
  12301. if (threadHandle_ == 0)
  12302. {
  12303. threadHandle_ = juce_createThread (this);
  12304. juce_setThreadPriority (threadHandle_, threadPriority_);
  12305. startSuspensionEvent_.signal();
  12306. }
  12307. }
  12308. void Thread::startThread (const int priority)
  12309. {
  12310. const ScopedLock sl (startStopLock);
  12311. if (threadHandle_ == 0)
  12312. {
  12313. threadPriority_ = priority;
  12314. startThread();
  12315. }
  12316. else
  12317. {
  12318. setPriority (priority);
  12319. }
  12320. }
  12321. bool Thread::isThreadRunning() const
  12322. {
  12323. return threadHandle_ != 0;
  12324. }
  12325. void Thread::signalThreadShouldExit()
  12326. {
  12327. threadShouldExit_ = true;
  12328. }
  12329. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12330. {
  12331. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12332. jassert (getThreadId() != getCurrentThreadId());
  12333. const int sleepMsPerIteration = 5;
  12334. int count = timeOutMilliseconds / sleepMsPerIteration;
  12335. while (isThreadRunning())
  12336. {
  12337. if (timeOutMilliseconds > 0 && --count < 0)
  12338. return false;
  12339. sleep (sleepMsPerIteration);
  12340. }
  12341. return true;
  12342. }
  12343. void Thread::stopThread (const int timeOutMilliseconds)
  12344. {
  12345. // agh! You can't stop the thread that's calling this method! How on earth
  12346. // would that work??
  12347. jassert (getCurrentThreadId() != getThreadId());
  12348. const ScopedLock sl (startStopLock);
  12349. if (isThreadRunning())
  12350. {
  12351. signalThreadShouldExit();
  12352. notify();
  12353. if (timeOutMilliseconds != 0)
  12354. waitForThreadToExit (timeOutMilliseconds);
  12355. if (isThreadRunning())
  12356. {
  12357. // very bad karma if this point is reached, as
  12358. // there are bound to be locks and events left in
  12359. // silly states when a thread is killed by force..
  12360. jassertfalse;
  12361. Logger::writeToLog ("!! killing thread by force !!");
  12362. juce_killThread (threadHandle_);
  12363. threadHandle_ = 0;
  12364. threadId_ = 0;
  12365. const ScopedLock sl2 (runningThreadsLock);
  12366. runningThreads.removeValue (this);
  12367. }
  12368. }
  12369. }
  12370. bool Thread::setPriority (const int priority)
  12371. {
  12372. const ScopedLock sl (startStopLock);
  12373. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12374. if (worked)
  12375. threadPriority_ = priority;
  12376. return worked;
  12377. }
  12378. bool Thread::setCurrentThreadPriority (const int priority)
  12379. {
  12380. return juce_setThreadPriority (0, priority);
  12381. }
  12382. void Thread::setAffinityMask (const uint32 affinityMask)
  12383. {
  12384. affinityMask_ = affinityMask;
  12385. }
  12386. bool Thread::wait (const int timeOutMilliseconds) const
  12387. {
  12388. return defaultEvent_.wait (timeOutMilliseconds);
  12389. }
  12390. void Thread::notify() const
  12391. {
  12392. defaultEvent_.signal();
  12393. }
  12394. int Thread::getNumRunningThreads()
  12395. {
  12396. return runningThreads.size();
  12397. }
  12398. Thread* Thread::getCurrentThread()
  12399. {
  12400. const ThreadID thisId = getCurrentThreadId();
  12401. const ScopedLock sl (runningThreadsLock);
  12402. for (int i = runningThreads.size(); --i >= 0;)
  12403. {
  12404. Thread* const t = runningThreads.getUnchecked(i);
  12405. if (t->threadId_ == thisId)
  12406. return t;
  12407. }
  12408. return 0;
  12409. }
  12410. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12411. {
  12412. {
  12413. const ScopedLock sl (runningThreadsLock);
  12414. for (int i = runningThreads.size(); --i >= 0;)
  12415. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12416. }
  12417. for (;;)
  12418. {
  12419. Thread* firstThread;
  12420. {
  12421. const ScopedLock sl (runningThreadsLock);
  12422. firstThread = runningThreads.getFirst();
  12423. }
  12424. if (firstThread == 0)
  12425. break;
  12426. firstThread->stopThread (timeOutMilliseconds);
  12427. }
  12428. }
  12429. Array<Thread*> Thread::runningThreads;
  12430. CriticalSection Thread::runningThreadsLock;
  12431. END_JUCE_NAMESPACE
  12432. /*** End of inlined file: juce_Thread.cpp ***/
  12433. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12434. BEGIN_JUCE_NAMESPACE
  12435. ThreadPoolJob::ThreadPoolJob (const String& name)
  12436. : jobName (name),
  12437. pool (0),
  12438. shouldStop (false),
  12439. isActive (false),
  12440. shouldBeDeleted (false)
  12441. {
  12442. }
  12443. ThreadPoolJob::~ThreadPoolJob()
  12444. {
  12445. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12446. // to remove it first!
  12447. jassert (pool == 0 || ! pool->contains (this));
  12448. }
  12449. const String ThreadPoolJob::getJobName() const
  12450. {
  12451. return jobName;
  12452. }
  12453. void ThreadPoolJob::setJobName (const String& newName)
  12454. {
  12455. jobName = newName;
  12456. }
  12457. void ThreadPoolJob::signalJobShouldExit()
  12458. {
  12459. shouldStop = true;
  12460. }
  12461. class ThreadPool::ThreadPoolThread : public Thread
  12462. {
  12463. public:
  12464. ThreadPoolThread (ThreadPool& pool_)
  12465. : Thread ("Pool"),
  12466. pool (pool_),
  12467. busy (false)
  12468. {
  12469. }
  12470. ~ThreadPoolThread()
  12471. {
  12472. }
  12473. void run()
  12474. {
  12475. while (! threadShouldExit())
  12476. {
  12477. if (! pool.runNextJob())
  12478. wait (500);
  12479. }
  12480. }
  12481. private:
  12482. ThreadPool& pool;
  12483. bool volatile busy;
  12484. ThreadPoolThread (const ThreadPoolThread&);
  12485. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12486. };
  12487. ThreadPool::ThreadPool (const int numThreads,
  12488. const bool startThreadsOnlyWhenNeeded,
  12489. const int stopThreadsWhenNotUsedTimeoutMs)
  12490. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12491. priority (5)
  12492. {
  12493. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12494. for (int i = jmax (1, numThreads); --i >= 0;)
  12495. threads.add (new ThreadPoolThread (*this));
  12496. if (! startThreadsOnlyWhenNeeded)
  12497. for (int i = threads.size(); --i >= 0;)
  12498. threads.getUnchecked(i)->startThread (priority);
  12499. }
  12500. ThreadPool::~ThreadPool()
  12501. {
  12502. removeAllJobs (true, 4000);
  12503. int i;
  12504. for (i = threads.size(); --i >= 0;)
  12505. threads.getUnchecked(i)->signalThreadShouldExit();
  12506. for (i = threads.size(); --i >= 0;)
  12507. threads.getUnchecked(i)->stopThread (500);
  12508. }
  12509. void ThreadPool::addJob (ThreadPoolJob* const job)
  12510. {
  12511. jassert (job != 0);
  12512. jassert (job->pool == 0);
  12513. if (job->pool == 0)
  12514. {
  12515. job->pool = this;
  12516. job->shouldStop = false;
  12517. job->isActive = false;
  12518. {
  12519. const ScopedLock sl (lock);
  12520. jobs.add (job);
  12521. int numRunning = 0;
  12522. for (int i = threads.size(); --i >= 0;)
  12523. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12524. ++numRunning;
  12525. if (numRunning < threads.size())
  12526. {
  12527. bool startedOne = false;
  12528. int n = 1000;
  12529. while (--n >= 0 && ! startedOne)
  12530. {
  12531. for (int i = threads.size(); --i >= 0;)
  12532. {
  12533. if (! threads.getUnchecked(i)->isThreadRunning())
  12534. {
  12535. threads.getUnchecked(i)->startThread (priority);
  12536. startedOne = true;
  12537. break;
  12538. }
  12539. }
  12540. if (! startedOne)
  12541. Thread::sleep (2);
  12542. }
  12543. }
  12544. }
  12545. for (int i = threads.size(); --i >= 0;)
  12546. threads.getUnchecked(i)->notify();
  12547. }
  12548. }
  12549. int ThreadPool::getNumJobs() const
  12550. {
  12551. return jobs.size();
  12552. }
  12553. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12554. {
  12555. const ScopedLock sl (lock);
  12556. return jobs [index];
  12557. }
  12558. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12559. {
  12560. const ScopedLock sl (lock);
  12561. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12562. }
  12563. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12564. {
  12565. const ScopedLock sl (lock);
  12566. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12567. }
  12568. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12569. const int timeOutMs) const
  12570. {
  12571. if (job != 0)
  12572. {
  12573. const uint32 start = Time::getMillisecondCounter();
  12574. while (contains (job))
  12575. {
  12576. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12577. return false;
  12578. jobFinishedSignal.wait (2);
  12579. }
  12580. }
  12581. return true;
  12582. }
  12583. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12584. const bool interruptIfRunning,
  12585. const int timeOutMs)
  12586. {
  12587. bool dontWait = true;
  12588. if (job != 0)
  12589. {
  12590. const ScopedLock sl (lock);
  12591. if (jobs.contains (job))
  12592. {
  12593. if (job->isActive)
  12594. {
  12595. if (interruptIfRunning)
  12596. job->signalJobShouldExit();
  12597. dontWait = false;
  12598. }
  12599. else
  12600. {
  12601. jobs.removeValue (job);
  12602. }
  12603. }
  12604. }
  12605. return dontWait || waitForJobToFinish (job, timeOutMs);
  12606. }
  12607. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12608. const int timeOutMs,
  12609. const bool deleteInactiveJobs,
  12610. ThreadPool::JobSelector* selectedJobsToRemove)
  12611. {
  12612. Array <ThreadPoolJob*> jobsToWaitFor;
  12613. {
  12614. const ScopedLock sl (lock);
  12615. for (int i = jobs.size(); --i >= 0;)
  12616. {
  12617. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12618. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12619. {
  12620. if (job->isActive)
  12621. {
  12622. jobsToWaitFor.add (job);
  12623. if (interruptRunningJobs)
  12624. job->signalJobShouldExit();
  12625. }
  12626. else
  12627. {
  12628. jobs.remove (i);
  12629. if (deleteInactiveJobs)
  12630. delete job;
  12631. }
  12632. }
  12633. }
  12634. }
  12635. const uint32 start = Time::getMillisecondCounter();
  12636. for (;;)
  12637. {
  12638. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12639. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12640. jobsToWaitFor.remove (i);
  12641. if (jobsToWaitFor.size() == 0)
  12642. break;
  12643. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12644. return false;
  12645. jobFinishedSignal.wait (20);
  12646. }
  12647. return true;
  12648. }
  12649. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12650. {
  12651. StringArray s;
  12652. const ScopedLock sl (lock);
  12653. for (int i = 0; i < jobs.size(); ++i)
  12654. {
  12655. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12656. if (job->isActive || ! onlyReturnActiveJobs)
  12657. s.add (job->getJobName());
  12658. }
  12659. return s;
  12660. }
  12661. bool ThreadPool::setThreadPriorities (const int newPriority)
  12662. {
  12663. bool ok = true;
  12664. if (priority != newPriority)
  12665. {
  12666. priority = newPriority;
  12667. for (int i = threads.size(); --i >= 0;)
  12668. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12669. ok = false;
  12670. }
  12671. return ok;
  12672. }
  12673. bool ThreadPool::runNextJob()
  12674. {
  12675. ThreadPoolJob* job = 0;
  12676. {
  12677. const ScopedLock sl (lock);
  12678. for (int i = 0; i < jobs.size(); ++i)
  12679. {
  12680. job = jobs[i];
  12681. if (job != 0 && ! (job->isActive || job->shouldStop))
  12682. break;
  12683. job = 0;
  12684. }
  12685. if (job != 0)
  12686. job->isActive = true;
  12687. }
  12688. if (job != 0)
  12689. {
  12690. JUCE_TRY
  12691. {
  12692. ThreadPoolJob::JobStatus result = job->runJob();
  12693. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12694. const ScopedLock sl (lock);
  12695. if (jobs.contains (job))
  12696. {
  12697. job->isActive = false;
  12698. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12699. {
  12700. job->pool = 0;
  12701. job->shouldStop = true;
  12702. jobs.removeValue (job);
  12703. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12704. delete job;
  12705. jobFinishedSignal.signal();
  12706. }
  12707. else
  12708. {
  12709. // move the job to the end of the queue if it wants another go
  12710. jobs.move (jobs.indexOf (job), -1);
  12711. }
  12712. }
  12713. }
  12714. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12715. catch (...)
  12716. {
  12717. const ScopedLock sl (lock);
  12718. jobs.removeValue (job);
  12719. }
  12720. #endif
  12721. }
  12722. else
  12723. {
  12724. if (threadStopTimeout > 0
  12725. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12726. {
  12727. const ScopedLock sl (lock);
  12728. if (jobs.size() == 0)
  12729. for (int i = threads.size(); --i >= 0;)
  12730. threads.getUnchecked(i)->signalThreadShouldExit();
  12731. }
  12732. else
  12733. {
  12734. return false;
  12735. }
  12736. }
  12737. return true;
  12738. }
  12739. END_JUCE_NAMESPACE
  12740. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12741. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12742. BEGIN_JUCE_NAMESPACE
  12743. TimeSliceThread::TimeSliceThread (const String& threadName)
  12744. : Thread (threadName),
  12745. index (0),
  12746. clientBeingCalled (0),
  12747. clientsChanged (false)
  12748. {
  12749. }
  12750. TimeSliceThread::~TimeSliceThread()
  12751. {
  12752. stopThread (2000);
  12753. }
  12754. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12755. {
  12756. const ScopedLock sl (listLock);
  12757. clients.addIfNotAlreadyThere (client);
  12758. clientsChanged = true;
  12759. notify();
  12760. }
  12761. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12762. {
  12763. const ScopedLock sl1 (listLock);
  12764. clientsChanged = true;
  12765. // if there's a chance we're in the middle of calling this client, we need to
  12766. // also lock the outer lock..
  12767. if (clientBeingCalled == client)
  12768. {
  12769. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12770. const ScopedLock sl2 (callbackLock);
  12771. const ScopedLock sl3 (listLock);
  12772. clients.removeValue (client);
  12773. }
  12774. else
  12775. {
  12776. clients.removeValue (client);
  12777. }
  12778. }
  12779. int TimeSliceThread::getNumClients() const
  12780. {
  12781. return clients.size();
  12782. }
  12783. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12784. {
  12785. const ScopedLock sl (listLock);
  12786. return clients [i];
  12787. }
  12788. void TimeSliceThread::run()
  12789. {
  12790. int numCallsSinceBusy = 0;
  12791. while (! threadShouldExit())
  12792. {
  12793. int timeToWait = 500;
  12794. {
  12795. const ScopedLock sl (callbackLock);
  12796. {
  12797. const ScopedLock sl2 (listLock);
  12798. if (clients.size() > 0)
  12799. {
  12800. index = (index + 1) % clients.size();
  12801. clientBeingCalled = clients [index];
  12802. }
  12803. else
  12804. {
  12805. index = 0;
  12806. clientBeingCalled = 0;
  12807. }
  12808. if (clientsChanged)
  12809. {
  12810. clientsChanged = false;
  12811. numCallsSinceBusy = 0;
  12812. }
  12813. }
  12814. if (clientBeingCalled != 0)
  12815. {
  12816. if (clientBeingCalled->useTimeSlice())
  12817. numCallsSinceBusy = 0;
  12818. else
  12819. ++numCallsSinceBusy;
  12820. if (numCallsSinceBusy >= clients.size())
  12821. timeToWait = 500;
  12822. else if (index == 0)
  12823. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12824. else
  12825. timeToWait = 0;
  12826. }
  12827. }
  12828. if (timeToWait > 0)
  12829. wait (timeToWait);
  12830. }
  12831. }
  12832. END_JUCE_NAMESPACE
  12833. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12834. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  12835. BEGIN_JUCE_NAMESPACE
  12836. DeletedAtShutdown::DeletedAtShutdown()
  12837. {
  12838. const ScopedLock sl (getLock());
  12839. getObjects().add (this);
  12840. }
  12841. DeletedAtShutdown::~DeletedAtShutdown()
  12842. {
  12843. const ScopedLock sl (getLock());
  12844. getObjects().removeValue (this);
  12845. }
  12846. void DeletedAtShutdown::deleteAll()
  12847. {
  12848. // make a local copy of the array, so it can't get into a loop if something
  12849. // creates another DeletedAtShutdown object during its destructor.
  12850. Array <DeletedAtShutdown*> localCopy;
  12851. {
  12852. const ScopedLock sl (getLock());
  12853. localCopy = getObjects();
  12854. }
  12855. for (int i = localCopy.size(); --i >= 0;)
  12856. {
  12857. JUCE_TRY
  12858. {
  12859. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  12860. // double-check that it's not already been deleted during another object's destructor.
  12861. {
  12862. const ScopedLock sl (getLock());
  12863. if (! getObjects().contains (deletee))
  12864. deletee = 0;
  12865. }
  12866. delete deletee;
  12867. }
  12868. JUCE_CATCH_EXCEPTION
  12869. }
  12870. // if no objects got re-created during shutdown, this should have been emptied by their
  12871. // destructors
  12872. jassert (getObjects().size() == 0);
  12873. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  12874. }
  12875. CriticalSection& DeletedAtShutdown::getLock()
  12876. {
  12877. static CriticalSection lock;
  12878. return lock;
  12879. }
  12880. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  12881. {
  12882. static Array <DeletedAtShutdown*> objects;
  12883. return objects;
  12884. }
  12885. END_JUCE_NAMESPACE
  12886. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  12887. #endif
  12888. #if JUCE_BUILD_MISC
  12889. /*** Start of inlined file: juce_ValueTree.cpp ***/
  12890. BEGIN_JUCE_NAMESPACE
  12891. class ValueTree::SetPropertyAction : public UndoableAction
  12892. {
  12893. public:
  12894. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  12895. const var& newValue_, const var& oldValue_,
  12896. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  12897. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  12898. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  12899. {
  12900. }
  12901. ~SetPropertyAction() {}
  12902. bool perform()
  12903. {
  12904. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  12905. if (isDeletingProperty)
  12906. target->removeProperty (name, 0);
  12907. else
  12908. target->setProperty (name, newValue, 0);
  12909. return true;
  12910. }
  12911. bool undo()
  12912. {
  12913. if (isAddingNewProperty)
  12914. target->removeProperty (name, 0);
  12915. else
  12916. target->setProperty (name, oldValue, 0);
  12917. return true;
  12918. }
  12919. int getSizeInUnits()
  12920. {
  12921. return (int) sizeof (*this); //xxx should be more accurate
  12922. }
  12923. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  12924. {
  12925. if (! (isAddingNewProperty || isDeletingProperty))
  12926. {
  12927. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  12928. if (next != 0 && next->target == target && next->name == name
  12929. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  12930. {
  12931. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  12932. }
  12933. }
  12934. return 0;
  12935. }
  12936. private:
  12937. const SharedObjectPtr target;
  12938. const Identifier name;
  12939. const var newValue;
  12940. var oldValue;
  12941. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  12942. SetPropertyAction (const SetPropertyAction&);
  12943. SetPropertyAction& operator= (const SetPropertyAction&);
  12944. };
  12945. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  12946. {
  12947. public:
  12948. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  12949. const SharedObjectPtr& newChild_)
  12950. : target (target_),
  12951. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  12952. childIndex (childIndex_),
  12953. isDeleting (newChild_ == 0)
  12954. {
  12955. jassert (child != 0);
  12956. }
  12957. ~AddOrRemoveChildAction() {}
  12958. bool perform()
  12959. {
  12960. if (isDeleting)
  12961. target->removeChild (childIndex, 0);
  12962. else
  12963. target->addChild (child, childIndex, 0);
  12964. return true;
  12965. }
  12966. bool undo()
  12967. {
  12968. if (isDeleting)
  12969. {
  12970. target->addChild (child, childIndex, 0);
  12971. }
  12972. else
  12973. {
  12974. // If you hit this, it seems that your object's state is getting confused - probably
  12975. // because you've interleaved some undoable and non-undoable operations?
  12976. jassert (childIndex < target->children.size());
  12977. target->removeChild (childIndex, 0);
  12978. }
  12979. return true;
  12980. }
  12981. int getSizeInUnits()
  12982. {
  12983. return (int) sizeof (*this); //xxx should be more accurate
  12984. }
  12985. private:
  12986. const SharedObjectPtr target, child;
  12987. const int childIndex;
  12988. const bool isDeleting;
  12989. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  12990. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  12991. };
  12992. class ValueTree::MoveChildAction : public UndoableAction
  12993. {
  12994. public:
  12995. MoveChildAction (const SharedObjectPtr& target_,
  12996. const int startIndex_, const int endIndex_)
  12997. : target (target_),
  12998. startIndex (startIndex_),
  12999. endIndex (endIndex_)
  13000. {
  13001. }
  13002. ~MoveChildAction() {}
  13003. bool perform()
  13004. {
  13005. target->moveChild (startIndex, endIndex, 0);
  13006. return true;
  13007. }
  13008. bool undo()
  13009. {
  13010. target->moveChild (endIndex, startIndex, 0);
  13011. return true;
  13012. }
  13013. int getSizeInUnits()
  13014. {
  13015. return (int) sizeof (*this); //xxx should be more accurate
  13016. }
  13017. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13018. {
  13019. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13020. if (next != 0 && next->target == target && next->child == child)
  13021. return new MoveChildAction (target, startIndex, next->endIndex);
  13022. return 0;
  13023. }
  13024. private:
  13025. const SharedObjectPtr target, child;
  13026. const int startIndex, endIndex;
  13027. MoveChildAction (const MoveChildAction&);
  13028. MoveChildAction& operator= (const MoveChildAction&);
  13029. };
  13030. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13031. : type (type_), parent (0)
  13032. {
  13033. }
  13034. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13035. : type (other.type), properties (other.properties), parent (0)
  13036. {
  13037. for (int i = 0; i < other.children.size(); ++i)
  13038. {
  13039. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13040. child->parent = this;
  13041. children.add (child);
  13042. }
  13043. }
  13044. ValueTree::SharedObject::~SharedObject()
  13045. {
  13046. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13047. for (int i = children.size(); --i >= 0;)
  13048. {
  13049. const SharedObjectPtr c (children.getUnchecked(i));
  13050. c->parent = 0;
  13051. children.remove (i);
  13052. c->sendParentChangeMessage();
  13053. }
  13054. }
  13055. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13056. {
  13057. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13058. {
  13059. ValueTree* const v = valueTreesWithListeners[i];
  13060. if (v != 0)
  13061. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13062. }
  13063. }
  13064. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13065. {
  13066. ValueTree tree (this);
  13067. ValueTree::SharedObject* t = this;
  13068. while (t != 0)
  13069. {
  13070. t->sendPropertyChangeMessage (tree, property);
  13071. t = t->parent;
  13072. }
  13073. }
  13074. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  13075. {
  13076. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13077. {
  13078. ValueTree* const v = valueTreesWithListeners[i];
  13079. if (v != 0)
  13080. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  13081. }
  13082. }
  13083. void ValueTree::SharedObject::sendChildChangeMessage()
  13084. {
  13085. ValueTree tree (this);
  13086. ValueTree::SharedObject* t = this;
  13087. while (t != 0)
  13088. {
  13089. t->sendChildChangeMessage (tree);
  13090. t = t->parent;
  13091. }
  13092. }
  13093. void ValueTree::SharedObject::sendParentChangeMessage()
  13094. {
  13095. ValueTree tree (this);
  13096. int i;
  13097. for (i = children.size(); --i >= 0;)
  13098. {
  13099. SharedObject* const t = children[i];
  13100. if (t != 0)
  13101. t->sendParentChangeMessage();
  13102. }
  13103. for (i = valueTreesWithListeners.size(); --i >= 0;)
  13104. {
  13105. ValueTree* const v = valueTreesWithListeners[i];
  13106. if (v != 0)
  13107. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  13108. }
  13109. }
  13110. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  13111. {
  13112. return properties [name];
  13113. }
  13114. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13115. {
  13116. return properties.getWithDefault (name, defaultReturnValue);
  13117. }
  13118. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13119. {
  13120. if (undoManager == 0)
  13121. {
  13122. if (properties.set (name, newValue))
  13123. sendPropertyChangeMessage (name);
  13124. }
  13125. else
  13126. {
  13127. var* const existingValue = properties.getItem (name);
  13128. if (existingValue != 0)
  13129. {
  13130. if (*existingValue != newValue)
  13131. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  13132. }
  13133. else
  13134. {
  13135. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  13136. }
  13137. }
  13138. }
  13139. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  13140. {
  13141. return properties.contains (name);
  13142. }
  13143. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13144. {
  13145. if (undoManager == 0)
  13146. {
  13147. if (properties.remove (name))
  13148. sendPropertyChangeMessage (name);
  13149. }
  13150. else
  13151. {
  13152. if (properties.contains (name))
  13153. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  13154. }
  13155. }
  13156. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  13157. {
  13158. if (undoManager == 0)
  13159. {
  13160. while (properties.size() > 0)
  13161. {
  13162. const Identifier name (properties.getName (properties.size() - 1));
  13163. properties.remove (name);
  13164. sendPropertyChangeMessage (name);
  13165. }
  13166. }
  13167. else
  13168. {
  13169. for (int i = properties.size(); --i >= 0;)
  13170. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  13171. }
  13172. }
  13173. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  13174. {
  13175. for (int i = 0; i < children.size(); ++i)
  13176. if (children.getUnchecked(i)->type == typeToMatch)
  13177. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13178. return ValueTree::invalid;
  13179. }
  13180. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  13181. {
  13182. for (int i = 0; i < children.size(); ++i)
  13183. if (children.getUnchecked(i)->type == typeToMatch)
  13184. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13185. SharedObject* const newObject = new SharedObject (typeToMatch);
  13186. addChild (newObject, -1, undoManager);
  13187. return ValueTree (newObject);
  13188. }
  13189. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13190. {
  13191. for (int i = 0; i < children.size(); ++i)
  13192. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  13193. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13194. return ValueTree::invalid;
  13195. }
  13196. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  13197. {
  13198. const SharedObject* p = parent;
  13199. while (p != 0)
  13200. {
  13201. if (p == possibleParent)
  13202. return true;
  13203. p = p->parent;
  13204. }
  13205. return false;
  13206. }
  13207. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  13208. {
  13209. return children.indexOf (child.object);
  13210. }
  13211. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  13212. {
  13213. if (child != 0 && child->parent != this)
  13214. {
  13215. if (child != this && ! isAChildOf (child))
  13216. {
  13217. // You should always make sure that a child is removed from its previous parent before
  13218. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13219. // undomanager should be used when removing it from its current parent..
  13220. jassert (child->parent == 0);
  13221. if (child->parent != 0)
  13222. {
  13223. jassert (child->parent->children.indexOf (child) >= 0);
  13224. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13225. }
  13226. if (undoManager == 0)
  13227. {
  13228. children.insert (index, child);
  13229. child->parent = this;
  13230. sendChildChangeMessage();
  13231. child->sendParentChangeMessage();
  13232. }
  13233. else
  13234. {
  13235. if (index < 0)
  13236. index = children.size();
  13237. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13238. }
  13239. }
  13240. else
  13241. {
  13242. // You're attempting to create a recursive loop! A node
  13243. // can't be a child of one of its own children!
  13244. jassertfalse;
  13245. }
  13246. }
  13247. }
  13248. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13249. {
  13250. const SharedObjectPtr child (children [childIndex]);
  13251. if (child != 0)
  13252. {
  13253. if (undoManager == 0)
  13254. {
  13255. children.remove (childIndex);
  13256. child->parent = 0;
  13257. sendChildChangeMessage();
  13258. child->sendParentChangeMessage();
  13259. }
  13260. else
  13261. {
  13262. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13263. }
  13264. }
  13265. }
  13266. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13267. {
  13268. while (children.size() > 0)
  13269. removeChild (children.size() - 1, undoManager);
  13270. }
  13271. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13272. {
  13273. // The source index must be a valid index!
  13274. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13275. if (currentIndex != newIndex
  13276. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13277. {
  13278. if (undoManager == 0)
  13279. {
  13280. children.move (currentIndex, newIndex);
  13281. sendChildChangeMessage();
  13282. }
  13283. else
  13284. {
  13285. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13286. newIndex = children.size() - 1;
  13287. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13288. }
  13289. }
  13290. }
  13291. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  13292. {
  13293. if (type != other.type
  13294. || properties.size() != other.properties.size()
  13295. || children.size() != other.children.size()
  13296. || properties != other.properties)
  13297. return false;
  13298. for (int i = 0; i < children.size(); ++i)
  13299. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  13300. return false;
  13301. return true;
  13302. }
  13303. ValueTree::ValueTree() throw()
  13304. : object (0)
  13305. {
  13306. }
  13307. const ValueTree ValueTree::invalid;
  13308. ValueTree::ValueTree (const Identifier& type_)
  13309. : object (new ValueTree::SharedObject (type_))
  13310. {
  13311. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  13312. }
  13313. ValueTree::ValueTree (SharedObject* const object_)
  13314. : object (object_)
  13315. {
  13316. }
  13317. ValueTree::ValueTree (const ValueTree& other)
  13318. : object (other.object)
  13319. {
  13320. }
  13321. ValueTree& ValueTree::operator= (const ValueTree& other)
  13322. {
  13323. if (listeners.size() > 0)
  13324. {
  13325. if (object != 0)
  13326. object->valueTreesWithListeners.removeValue (this);
  13327. if (other.object != 0)
  13328. other.object->valueTreesWithListeners.add (this);
  13329. }
  13330. object = other.object;
  13331. return *this;
  13332. }
  13333. ValueTree::~ValueTree()
  13334. {
  13335. if (listeners.size() > 0 && object != 0)
  13336. object->valueTreesWithListeners.removeValue (this);
  13337. }
  13338. bool ValueTree::operator== (const ValueTree& other) const throw()
  13339. {
  13340. return object == other.object;
  13341. }
  13342. bool ValueTree::operator!= (const ValueTree& other) const throw()
  13343. {
  13344. return object != other.object;
  13345. }
  13346. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  13347. {
  13348. return object == other.object
  13349. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  13350. }
  13351. ValueTree ValueTree::createCopy() const
  13352. {
  13353. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13354. }
  13355. bool ValueTree::hasType (const Identifier& typeName) const
  13356. {
  13357. return object != 0 && object->type == typeName;
  13358. }
  13359. const Identifier ValueTree::getType() const
  13360. {
  13361. return object != 0 ? object->type : Identifier();
  13362. }
  13363. ValueTree ValueTree::getParent() const
  13364. {
  13365. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13366. }
  13367. const var& ValueTree::operator[] (const Identifier& name) const
  13368. {
  13369. return object == 0 ? var::null : object->getProperty (name);
  13370. }
  13371. const var& ValueTree::getProperty (const Identifier& name) const
  13372. {
  13373. return object == 0 ? var::null : object->getProperty (name);
  13374. }
  13375. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13376. {
  13377. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13378. }
  13379. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13380. {
  13381. jassert (name.toString().isNotEmpty());
  13382. if (object != 0 && name.toString().isNotEmpty())
  13383. object->setProperty (name, newValue, undoManager);
  13384. }
  13385. bool ValueTree::hasProperty (const Identifier& name) const
  13386. {
  13387. return object != 0 && object->hasProperty (name);
  13388. }
  13389. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13390. {
  13391. if (object != 0)
  13392. object->removeProperty (name, undoManager);
  13393. }
  13394. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13395. {
  13396. if (object != 0)
  13397. object->removeAllProperties (undoManager);
  13398. }
  13399. int ValueTree::getNumProperties() const
  13400. {
  13401. return object == 0 ? 0 : object->properties.size();
  13402. }
  13403. const Identifier ValueTree::getPropertyName (const int index) const
  13404. {
  13405. return object == 0 ? Identifier()
  13406. : object->properties.getName (index);
  13407. }
  13408. class ValueTreePropertyValueSource : public Value::ValueSource,
  13409. public ValueTree::Listener
  13410. {
  13411. public:
  13412. ValueTreePropertyValueSource (const ValueTree& tree_,
  13413. const Identifier& property_,
  13414. UndoManager* const undoManager_)
  13415. : tree (tree_),
  13416. property (property_),
  13417. undoManager (undoManager_)
  13418. {
  13419. tree.addListener (this);
  13420. }
  13421. ~ValueTreePropertyValueSource()
  13422. {
  13423. tree.removeListener (this);
  13424. }
  13425. const var getValue() const
  13426. {
  13427. return tree [property];
  13428. }
  13429. void setValue (const var& newValue)
  13430. {
  13431. tree.setProperty (property, newValue, undoManager);
  13432. }
  13433. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  13434. {
  13435. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13436. sendChangeMessage (false);
  13437. }
  13438. void valueTreeChildrenChanged (ValueTree&) {}
  13439. void valueTreeParentChanged (ValueTree&) {}
  13440. private:
  13441. ValueTree tree;
  13442. const Identifier property;
  13443. UndoManager* const undoManager;
  13444. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13445. };
  13446. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  13447. {
  13448. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13449. }
  13450. int ValueTree::getNumChildren() const
  13451. {
  13452. return object == 0 ? 0 : object->children.size();
  13453. }
  13454. ValueTree ValueTree::getChild (int index) const
  13455. {
  13456. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13457. }
  13458. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  13459. {
  13460. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13461. }
  13462. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  13463. {
  13464. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  13465. }
  13466. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13467. {
  13468. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13469. }
  13470. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13471. {
  13472. return object != 0 && object->isAChildOf (possibleParent.object);
  13473. }
  13474. int ValueTree::indexOf (const ValueTree& child) const
  13475. {
  13476. return object != 0 ? object->indexOf (child) : -1;
  13477. }
  13478. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  13479. {
  13480. if (object != 0)
  13481. object->addChild (child.object, index, undoManager);
  13482. }
  13483. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13484. {
  13485. if (object != 0)
  13486. object->removeChild (childIndex, undoManager);
  13487. }
  13488. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13489. {
  13490. if (object != 0)
  13491. object->removeChild (object->children.indexOf (child.object), undoManager);
  13492. }
  13493. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13494. {
  13495. if (object != 0)
  13496. object->removeAllChildren (undoManager);
  13497. }
  13498. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13499. {
  13500. if (object != 0)
  13501. object->moveChild (currentIndex, newIndex, undoManager);
  13502. }
  13503. void ValueTree::addListener (Listener* listener)
  13504. {
  13505. if (listener != 0)
  13506. {
  13507. if (listeners.size() == 0 && object != 0)
  13508. object->valueTreesWithListeners.add (this);
  13509. listeners.add (listener);
  13510. }
  13511. }
  13512. void ValueTree::removeListener (Listener* listener)
  13513. {
  13514. listeners.remove (listener);
  13515. if (listeners.size() == 0 && object != 0)
  13516. object->valueTreesWithListeners.removeValue (this);
  13517. }
  13518. XmlElement* ValueTree::SharedObject::createXml() const
  13519. {
  13520. XmlElement* xml = new XmlElement (type.toString());
  13521. int i;
  13522. for (i = 0; i < properties.size(); ++i)
  13523. {
  13524. Identifier name (properties.getName(i));
  13525. const var& v = properties [name];
  13526. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13527. xml->setAttribute (name.toString(), v.toString());
  13528. }
  13529. for (i = 0; i < children.size(); ++i)
  13530. xml->addChildElement (children.getUnchecked(i)->createXml());
  13531. return xml;
  13532. }
  13533. XmlElement* ValueTree::createXml() const
  13534. {
  13535. return object != 0 ? object->createXml() : 0;
  13536. }
  13537. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13538. {
  13539. ValueTree v (xml.getTagName());
  13540. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13541. for (int i = 0; i < numAtts; ++i)
  13542. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13543. forEachXmlChildElement (xml, e)
  13544. {
  13545. v.addChild (fromXml (*e), -1, 0);
  13546. }
  13547. return v;
  13548. }
  13549. void ValueTree::writeToStream (OutputStream& output)
  13550. {
  13551. output.writeString (getType().toString());
  13552. const int numProps = getNumProperties();
  13553. output.writeCompressedInt (numProps);
  13554. int i;
  13555. for (i = 0; i < numProps; ++i)
  13556. {
  13557. const Identifier name (getPropertyName(i));
  13558. output.writeString (name.toString());
  13559. getProperty(name).writeToStream (output);
  13560. }
  13561. const int numChildren = getNumChildren();
  13562. output.writeCompressedInt (numChildren);
  13563. for (i = 0; i < numChildren; ++i)
  13564. getChild (i).writeToStream (output);
  13565. }
  13566. ValueTree ValueTree::readFromStream (InputStream& input)
  13567. {
  13568. const String type (input.readString());
  13569. if (type.isEmpty())
  13570. return ValueTree::invalid;
  13571. ValueTree v (type);
  13572. const int numProps = input.readCompressedInt();
  13573. if (numProps < 0)
  13574. {
  13575. jassertfalse; // trying to read corrupted data!
  13576. return v;
  13577. }
  13578. int i;
  13579. for (i = 0; i < numProps; ++i)
  13580. {
  13581. const String name (input.readString());
  13582. jassert (name.isNotEmpty());
  13583. const var value (var::readFromStream (input));
  13584. v.setProperty (name, value, 0);
  13585. }
  13586. const int numChildren = input.readCompressedInt();
  13587. for (i = 0; i < numChildren; ++i)
  13588. v.addChild (readFromStream (input), -1, 0);
  13589. return v;
  13590. }
  13591. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  13592. {
  13593. MemoryInputStream in (data, numBytes, false);
  13594. return readFromStream (in);
  13595. }
  13596. END_JUCE_NAMESPACE
  13597. /*** End of inlined file: juce_ValueTree.cpp ***/
  13598. /*** Start of inlined file: juce_Value.cpp ***/
  13599. BEGIN_JUCE_NAMESPACE
  13600. Value::ValueSource::ValueSource()
  13601. {
  13602. }
  13603. Value::ValueSource::~ValueSource()
  13604. {
  13605. }
  13606. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13607. {
  13608. if (synchronous)
  13609. {
  13610. for (int i = valuesWithListeners.size(); --i >= 0;)
  13611. {
  13612. Value* const v = valuesWithListeners[i];
  13613. if (v != 0)
  13614. v->callListeners();
  13615. }
  13616. }
  13617. else
  13618. {
  13619. triggerAsyncUpdate();
  13620. }
  13621. }
  13622. void Value::ValueSource::handleAsyncUpdate()
  13623. {
  13624. sendChangeMessage (true);
  13625. }
  13626. class SimpleValueSource : public Value::ValueSource
  13627. {
  13628. public:
  13629. SimpleValueSource()
  13630. {
  13631. }
  13632. SimpleValueSource (const var& initialValue)
  13633. : value (initialValue)
  13634. {
  13635. }
  13636. ~SimpleValueSource()
  13637. {
  13638. }
  13639. const var getValue() const
  13640. {
  13641. return value;
  13642. }
  13643. void setValue (const var& newValue)
  13644. {
  13645. if (newValue != value)
  13646. {
  13647. value = newValue;
  13648. sendChangeMessage (false);
  13649. }
  13650. }
  13651. private:
  13652. var value;
  13653. SimpleValueSource (const SimpleValueSource&);
  13654. SimpleValueSource& operator= (const SimpleValueSource&);
  13655. };
  13656. Value::Value()
  13657. : value (new SimpleValueSource())
  13658. {
  13659. }
  13660. Value::Value (ValueSource* const value_)
  13661. : value (value_)
  13662. {
  13663. jassert (value_ != 0);
  13664. }
  13665. Value::Value (const var& initialValue)
  13666. : value (new SimpleValueSource (initialValue))
  13667. {
  13668. }
  13669. Value::Value (const Value& other)
  13670. : value (other.value)
  13671. {
  13672. }
  13673. Value& Value::operator= (const Value& other)
  13674. {
  13675. value = other.value;
  13676. return *this;
  13677. }
  13678. Value::~Value()
  13679. {
  13680. if (listeners.size() > 0)
  13681. value->valuesWithListeners.removeValue (this);
  13682. }
  13683. const var Value::getValue() const
  13684. {
  13685. return value->getValue();
  13686. }
  13687. Value::operator const var() const
  13688. {
  13689. return getValue();
  13690. }
  13691. void Value::setValue (const var& newValue)
  13692. {
  13693. value->setValue (newValue);
  13694. }
  13695. const String Value::toString() const
  13696. {
  13697. return value->getValue().toString();
  13698. }
  13699. Value& Value::operator= (const var& newValue)
  13700. {
  13701. value->setValue (newValue);
  13702. return *this;
  13703. }
  13704. void Value::referTo (const Value& valueToReferTo)
  13705. {
  13706. if (valueToReferTo.value != value)
  13707. {
  13708. if (listeners.size() > 0)
  13709. {
  13710. value->valuesWithListeners.removeValue (this);
  13711. valueToReferTo.value->valuesWithListeners.add (this);
  13712. }
  13713. value = valueToReferTo.value;
  13714. callListeners();
  13715. }
  13716. }
  13717. bool Value::refersToSameSourceAs (const Value& other) const
  13718. {
  13719. return value == other.value;
  13720. }
  13721. bool Value::operator== (const Value& other) const
  13722. {
  13723. return value == other.value || value->getValue() == other.getValue();
  13724. }
  13725. bool Value::operator!= (const Value& other) const
  13726. {
  13727. return value != other.value && value->getValue() != other.getValue();
  13728. }
  13729. void Value::addListener (Listener* const listener)
  13730. {
  13731. if (listener != 0)
  13732. {
  13733. if (listeners.size() == 0)
  13734. value->valuesWithListeners.add (this);
  13735. listeners.add (listener);
  13736. }
  13737. }
  13738. void Value::removeListener (Listener* const listener)
  13739. {
  13740. listeners.remove (listener);
  13741. if (listeners.size() == 0)
  13742. value->valuesWithListeners.removeValue (this);
  13743. }
  13744. void Value::callListeners()
  13745. {
  13746. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13747. listeners.call (&Listener::valueChanged, v);
  13748. }
  13749. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13750. {
  13751. return stream << value.toString();
  13752. }
  13753. END_JUCE_NAMESPACE
  13754. /*** End of inlined file: juce_Value.cpp ***/
  13755. /*** Start of inlined file: juce_Application.cpp ***/
  13756. #if JUCE_MSVC
  13757. #pragma warning (push)
  13758. #pragma warning (disable: 4245 4514 4100)
  13759. #include <crtdbg.h>
  13760. #pragma warning (pop)
  13761. #endif
  13762. BEGIN_JUCE_NAMESPACE
  13763. void juce_setCurrentThreadName (const String& name);
  13764. static JUCEApplication* appInstance = 0;
  13765. JUCEApplication::JUCEApplication()
  13766. : appReturnValue (0),
  13767. stillInitialising (true)
  13768. {
  13769. }
  13770. JUCEApplication::~JUCEApplication()
  13771. {
  13772. if (appLock != 0)
  13773. {
  13774. appLock->exit();
  13775. appLock = 0;
  13776. }
  13777. }
  13778. JUCEApplication* JUCEApplication::getInstance() throw()
  13779. {
  13780. return appInstance;
  13781. }
  13782. bool JUCEApplication::isInitialising() const throw()
  13783. {
  13784. return stillInitialising;
  13785. }
  13786. const String JUCEApplication::getApplicationVersion()
  13787. {
  13788. return String::empty;
  13789. }
  13790. bool JUCEApplication::moreThanOneInstanceAllowed()
  13791. {
  13792. return true;
  13793. }
  13794. void JUCEApplication::anotherInstanceStarted (const String&)
  13795. {
  13796. }
  13797. void JUCEApplication::systemRequestedQuit()
  13798. {
  13799. quit();
  13800. }
  13801. void JUCEApplication::quit()
  13802. {
  13803. MessageManager::getInstance()->stopDispatchLoop();
  13804. }
  13805. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13806. {
  13807. appReturnValue = newReturnValue;
  13808. }
  13809. void JUCEApplication::unhandledException (const std::exception*,
  13810. const String&,
  13811. const int)
  13812. {
  13813. jassertfalse;
  13814. }
  13815. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13816. const char* const sourceFile,
  13817. const int lineNumber)
  13818. {
  13819. if (appInstance != 0)
  13820. appInstance->unhandledException (e, sourceFile, lineNumber);
  13821. }
  13822. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13823. {
  13824. return 0;
  13825. }
  13826. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13827. {
  13828. commands.add (StandardApplicationCommandIDs::quit);
  13829. }
  13830. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13831. {
  13832. if (commandID == StandardApplicationCommandIDs::quit)
  13833. {
  13834. result.setInfo (TRANS("Quit"),
  13835. TRANS("Quits the application"),
  13836. "Application",
  13837. 0);
  13838. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13839. }
  13840. }
  13841. bool JUCEApplication::perform (const InvocationInfo& info)
  13842. {
  13843. if (info.commandID == StandardApplicationCommandIDs::quit)
  13844. {
  13845. systemRequestedQuit();
  13846. return true;
  13847. }
  13848. return false;
  13849. }
  13850. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13851. {
  13852. if (! app->initialiseApp (commandLine))
  13853. return 0;
  13854. // now loop until a quit message is received..
  13855. JUCE_TRY
  13856. {
  13857. MessageManager::getInstance()->runDispatchLoop();
  13858. }
  13859. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13860. catch (const std::exception& e)
  13861. {
  13862. app->unhandledException (&e, __FILE__, __LINE__);
  13863. }
  13864. catch (...)
  13865. {
  13866. app->unhandledException (0, __FILE__, __LINE__);
  13867. }
  13868. #endif
  13869. return shutdownAppAndClearUp();
  13870. }
  13871. bool JUCEApplication::initialiseApp (String& commandLine)
  13872. {
  13873. jassert (appInstance == 0);
  13874. appInstance = this;
  13875. commandLineParameters = commandLine.trim();
  13876. commandLine = String::empty;
  13877. initialiseJuce_GUI();
  13878. #if ! JUCE_IPHONE
  13879. jassert (appLock == 0); // initialiseApp must only be called once!
  13880. if (! moreThanOneInstanceAllowed())
  13881. {
  13882. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13883. if (! appLock->enter(0))
  13884. {
  13885. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13886. delete appInstance;
  13887. appInstance = 0;
  13888. DBG ("Another instance is running - quitting...");
  13889. return false;
  13890. }
  13891. }
  13892. #endif
  13893. // let the app do its setting-up..
  13894. initialise (commandLineParameters);
  13895. // register for broadcast new app messages
  13896. MessageManager::getInstance()->registerBroadcastListener (this);
  13897. stillInitialising = false;
  13898. return true;
  13899. }
  13900. int JUCEApplication::shutdownAppAndClearUp()
  13901. {
  13902. jassert (appInstance != 0);
  13903. ScopedPointer<JUCEApplication> app (appInstance);
  13904. int returnValue = 0;
  13905. MessageManager::getInstance()->deregisterBroadcastListener (static_cast <JUCEApplication*> (app));
  13906. static bool reentrancyCheck = false;
  13907. if (! reentrancyCheck)
  13908. {
  13909. reentrancyCheck = true;
  13910. JUCE_TRY
  13911. {
  13912. // give the app a chance to clean up..
  13913. app->shutdown();
  13914. }
  13915. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13916. catch (const std::exception& e)
  13917. {
  13918. app->unhandledException (&e, __FILE__, __LINE__);
  13919. }
  13920. catch (...)
  13921. {
  13922. app->unhandledException (0, __FILE__, __LINE__);
  13923. }
  13924. #endif
  13925. JUCE_TRY
  13926. {
  13927. shutdownJuce_GUI();
  13928. returnValue = app->getApplicationReturnValue();
  13929. appInstance = 0;
  13930. app = 0;
  13931. }
  13932. JUCE_CATCH_ALL_ASSERT
  13933. reentrancyCheck = false;
  13934. }
  13935. return returnValue;
  13936. }
  13937. #if JUCE_IPHONE
  13938. extern int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app);
  13939. #endif
  13940. #if ! JUCE_WINDOWS
  13941. extern const char* juce_Argv0;
  13942. #endif
  13943. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  13944. {
  13945. #if ! JUCE_WINDOWS
  13946. juce_Argv0 = argv[0];
  13947. #endif
  13948. #if JUCE_IPHONE
  13949. const ScopedAutoReleasePool pool;
  13950. return juce_IPhoneMain (argc, argv, newApp);
  13951. #else
  13952. #if JUCE_MAC
  13953. const ScopedAutoReleasePool pool;
  13954. #endif
  13955. String cmd;
  13956. for (int i = 1; i < argc; ++i)
  13957. cmd << argv[i] << ' ';
  13958. return JUCEApplication::main (cmd, newApp);
  13959. #endif
  13960. }
  13961. void JUCEApplication::actionListenerCallback (const String& message)
  13962. {
  13963. if (message.startsWith (getApplicationName() + "/"))
  13964. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13965. }
  13966. static bool juceInitialisedGUI = false;
  13967. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13968. {
  13969. if (! juceInitialisedGUI)
  13970. {
  13971. #if JUCE_MAC || JUCE_IPHONE
  13972. const ScopedAutoReleasePool pool;
  13973. #endif
  13974. juceInitialisedGUI = true;
  13975. initialiseJuce_NonGUI();
  13976. MessageManager::getInstance();
  13977. LookAndFeel::setDefaultLookAndFeel (0);
  13978. juce_setCurrentThreadName ("Juce Message Thread");
  13979. #if JUCE_WINDOWS && JUCE_DEBUG
  13980. // This section is just for catching people who mess up their project settings and
  13981. // turn RTTI off..
  13982. try
  13983. {
  13984. TextButton tb (String::empty);
  13985. Component* c = &tb;
  13986. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  13987. c = dynamic_cast <Button*> (c);
  13988. }
  13989. catch (...)
  13990. {
  13991. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  13992. // got as far as this catch statement, then why haven't you got exception catching
  13993. // turned on in the debugger???
  13994. jassertfalse;
  13995. }
  13996. #endif
  13997. }
  13998. }
  13999. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  14000. {
  14001. if (juceInitialisedGUI)
  14002. {
  14003. #if JUCE_MAC
  14004. const ScopedAutoReleasePool pool;
  14005. #endif
  14006. {
  14007. DeletedAtShutdown::deleteAll();
  14008. LookAndFeel::clearDefaultLookAndFeel();
  14009. }
  14010. delete MessageManager::getInstance();
  14011. shutdownJuce_NonGUI();
  14012. juceInitialisedGUI = false;
  14013. }
  14014. }
  14015. END_JUCE_NAMESPACE
  14016. /*** End of inlined file: juce_Application.cpp ***/
  14017. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14018. BEGIN_JUCE_NAMESPACE
  14019. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14020. : commandID (commandID_),
  14021. flags (0)
  14022. {
  14023. }
  14024. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14025. const String& description_,
  14026. const String& categoryName_,
  14027. const int flags_) throw()
  14028. {
  14029. shortName = shortName_;
  14030. description = description_;
  14031. categoryName = categoryName_;
  14032. flags = flags_;
  14033. }
  14034. void ApplicationCommandInfo::setActive (const bool b) throw()
  14035. {
  14036. if (b)
  14037. flags &= ~isDisabled;
  14038. else
  14039. flags |= isDisabled;
  14040. }
  14041. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14042. {
  14043. if (b)
  14044. flags |= isTicked;
  14045. else
  14046. flags &= ~isTicked;
  14047. }
  14048. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14049. {
  14050. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14051. }
  14052. END_JUCE_NAMESPACE
  14053. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14054. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14055. BEGIN_JUCE_NAMESPACE
  14056. ApplicationCommandManager::ApplicationCommandManager()
  14057. : firstTarget (0)
  14058. {
  14059. keyMappings = new KeyPressMappingSet (this);
  14060. Desktop::getInstance().addFocusChangeListener (this);
  14061. }
  14062. ApplicationCommandManager::~ApplicationCommandManager()
  14063. {
  14064. Desktop::getInstance().removeFocusChangeListener (this);
  14065. keyMappings = 0;
  14066. }
  14067. void ApplicationCommandManager::clearCommands()
  14068. {
  14069. commands.clear();
  14070. keyMappings->clearAllKeyPresses();
  14071. triggerAsyncUpdate();
  14072. }
  14073. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14074. {
  14075. // zero isn't a valid command ID!
  14076. jassert (newCommand.commandID != 0);
  14077. // the name isn't optional!
  14078. jassert (newCommand.shortName.isNotEmpty());
  14079. if (getCommandForID (newCommand.commandID) == 0)
  14080. {
  14081. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14082. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14083. commands.add (newInfo);
  14084. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14085. triggerAsyncUpdate();
  14086. }
  14087. else
  14088. {
  14089. // trying to re-register the same command with different parameters?
  14090. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14091. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14092. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14093. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14094. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14095. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14096. }
  14097. }
  14098. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14099. {
  14100. if (target != 0)
  14101. {
  14102. Array <CommandID> commandIDs;
  14103. target->getAllCommands (commandIDs);
  14104. for (int i = 0; i < commandIDs.size(); ++i)
  14105. {
  14106. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14107. target->getCommandInfo (info.commandID, info);
  14108. registerCommand (info);
  14109. }
  14110. }
  14111. }
  14112. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14113. {
  14114. for (int i = commands.size(); --i >= 0;)
  14115. {
  14116. if (commands.getUnchecked (i)->commandID == commandID)
  14117. {
  14118. commands.remove (i);
  14119. triggerAsyncUpdate();
  14120. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14121. for (int j = keys.size(); --j >= 0;)
  14122. keyMappings->removeKeyPress (keys.getReference (j));
  14123. }
  14124. }
  14125. }
  14126. void ApplicationCommandManager::commandStatusChanged()
  14127. {
  14128. triggerAsyncUpdate();
  14129. }
  14130. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14131. {
  14132. for (int i = commands.size(); --i >= 0;)
  14133. if (commands.getUnchecked(i)->commandID == commandID)
  14134. return commands.getUnchecked(i);
  14135. return 0;
  14136. }
  14137. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14138. {
  14139. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14140. return (ci != 0) ? ci->shortName : String::empty;
  14141. }
  14142. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14143. {
  14144. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14145. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14146. : String::empty;
  14147. }
  14148. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  14149. {
  14150. StringArray s;
  14151. for (int i = 0; i < commands.size(); ++i)
  14152. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14153. return s;
  14154. }
  14155. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  14156. {
  14157. Array <CommandID> results;
  14158. for (int i = 0; i < commands.size(); ++i)
  14159. if (commands.getUnchecked(i)->categoryName == categoryName)
  14160. results.add (commands.getUnchecked(i)->commandID);
  14161. return results;
  14162. }
  14163. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14164. {
  14165. ApplicationCommandTarget::InvocationInfo info (commandID);
  14166. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14167. return invoke (info, asynchronously);
  14168. }
  14169. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  14170. {
  14171. // This call isn't thread-safe for use from a non-UI thread without locking the message
  14172. // manager first..
  14173. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  14174. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  14175. if (target == 0)
  14176. return false;
  14177. ApplicationCommandInfo commandInfo (0);
  14178. target->getCommandInfo (info_.commandID, commandInfo);
  14179. ApplicationCommandTarget::InvocationInfo info (info_);
  14180. info.commandFlags = commandInfo.flags;
  14181. sendListenerInvokeCallback (info);
  14182. const bool ok = target->invoke (info, asynchronously);
  14183. commandStatusChanged();
  14184. return ok;
  14185. }
  14186. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  14187. {
  14188. return firstTarget != 0 ? firstTarget
  14189. : findDefaultComponentTarget();
  14190. }
  14191. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  14192. {
  14193. firstTarget = newTarget;
  14194. }
  14195. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  14196. ApplicationCommandInfo& upToDateInfo)
  14197. {
  14198. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  14199. if (target == 0)
  14200. target = JUCEApplication::getInstance();
  14201. if (target != 0)
  14202. target = target->getTargetForCommand (commandID);
  14203. if (target != 0)
  14204. target->getCommandInfo (commandID, upToDateInfo);
  14205. return target;
  14206. }
  14207. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  14208. {
  14209. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  14210. if (target == 0 && c != 0)
  14211. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14212. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14213. return target;
  14214. }
  14215. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14216. {
  14217. Component* c = Component::getCurrentlyFocusedComponent();
  14218. if (c == 0)
  14219. {
  14220. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14221. if (activeWindow != 0)
  14222. {
  14223. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14224. if (c == 0)
  14225. c = activeWindow;
  14226. }
  14227. }
  14228. if (c == 0 && Process::isForegroundProcess())
  14229. {
  14230. // getting a bit desperate now - try all desktop comps..
  14231. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  14232. {
  14233. ApplicationCommandTarget* const target
  14234. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  14235. ->getPeer()->getLastFocusedSubcomponent());
  14236. if (target != 0)
  14237. return target;
  14238. }
  14239. }
  14240. if (c != 0)
  14241. {
  14242. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14243. // if we're focused on a ResizableWindow, chances are that it's the content
  14244. // component that really should get the event. And if not, the event will
  14245. // still be passed up to the top level window anyway, so let's send it to the
  14246. // content comp.
  14247. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14248. c = resizableWindow->getContentComponent();
  14249. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14250. if (target != 0)
  14251. return target;
  14252. }
  14253. return JUCEApplication::getInstance();
  14254. }
  14255. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14256. {
  14257. listeners.add (listener);
  14258. }
  14259. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14260. {
  14261. listeners.remove (listener);
  14262. }
  14263. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14264. {
  14265. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14266. }
  14267. void ApplicationCommandManager::handleAsyncUpdate()
  14268. {
  14269. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14270. }
  14271. void ApplicationCommandManager::globalFocusChanged (Component*)
  14272. {
  14273. commandStatusChanged();
  14274. }
  14275. END_JUCE_NAMESPACE
  14276. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14277. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14278. BEGIN_JUCE_NAMESPACE
  14279. ApplicationCommandTarget::ApplicationCommandTarget()
  14280. {
  14281. }
  14282. ApplicationCommandTarget::~ApplicationCommandTarget()
  14283. {
  14284. messageInvoker = 0;
  14285. }
  14286. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14287. {
  14288. if (isCommandActive (info.commandID))
  14289. {
  14290. if (async)
  14291. {
  14292. if (messageInvoker == 0)
  14293. messageInvoker = new CommandTargetMessageInvoker (this);
  14294. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14295. return true;
  14296. }
  14297. else
  14298. {
  14299. const bool success = perform (info);
  14300. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14301. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14302. // returns the command's info.
  14303. return success;
  14304. }
  14305. }
  14306. return false;
  14307. }
  14308. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14309. {
  14310. Component* c = dynamic_cast <Component*> (this);
  14311. if (c != 0)
  14312. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14313. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14314. return 0;
  14315. }
  14316. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14317. {
  14318. ApplicationCommandTarget* target = this;
  14319. int depth = 0;
  14320. while (target != 0)
  14321. {
  14322. Array <CommandID> commandIDs;
  14323. target->getAllCommands (commandIDs);
  14324. if (commandIDs.contains (commandID))
  14325. return target;
  14326. target = target->getNextCommandTarget();
  14327. ++depth;
  14328. jassert (depth < 100); // could be a recursive command chain??
  14329. jassert (target != this); // definitely a recursive command chain!
  14330. if (depth > 100 || target == this)
  14331. break;
  14332. }
  14333. if (target == 0)
  14334. {
  14335. target = JUCEApplication::getInstance();
  14336. if (target != 0)
  14337. {
  14338. Array <CommandID> commandIDs;
  14339. target->getAllCommands (commandIDs);
  14340. if (commandIDs.contains (commandID))
  14341. return target;
  14342. }
  14343. }
  14344. return 0;
  14345. }
  14346. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14347. {
  14348. ApplicationCommandInfo info (commandID);
  14349. info.flags = ApplicationCommandInfo::isDisabled;
  14350. getCommandInfo (commandID, info);
  14351. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14352. }
  14353. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14354. {
  14355. ApplicationCommandTarget* target = this;
  14356. int depth = 0;
  14357. while (target != 0)
  14358. {
  14359. if (target->tryToInvoke (info, async))
  14360. return true;
  14361. target = target->getNextCommandTarget();
  14362. ++depth;
  14363. jassert (depth < 100); // could be a recursive command chain??
  14364. jassert (target != this); // definitely a recursive command chain!
  14365. if (depth > 100 || target == this)
  14366. break;
  14367. }
  14368. if (target == 0)
  14369. {
  14370. target = JUCEApplication::getInstance();
  14371. if (target != 0)
  14372. return target->tryToInvoke (info, async);
  14373. }
  14374. return false;
  14375. }
  14376. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14377. {
  14378. ApplicationCommandTarget::InvocationInfo info (commandID);
  14379. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14380. return invoke (info, asynchronously);
  14381. }
  14382. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14383. : commandID (commandID_),
  14384. commandFlags (0),
  14385. invocationMethod (direct),
  14386. originatingComponent (0),
  14387. isKeyDown (false),
  14388. millisecsSinceKeyPressed (0)
  14389. {
  14390. }
  14391. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14392. : owner (owner_)
  14393. {
  14394. }
  14395. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14396. {
  14397. }
  14398. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14399. {
  14400. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14401. owner->tryToInvoke (*info, false);
  14402. }
  14403. END_JUCE_NAMESPACE
  14404. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14405. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14406. BEGIN_JUCE_NAMESPACE
  14407. juce_ImplementSingleton (ApplicationProperties)
  14408. ApplicationProperties::ApplicationProperties() throw()
  14409. : msBeforeSaving (3000),
  14410. options (PropertiesFile::storeAsBinary),
  14411. commonSettingsAreReadOnly (0)
  14412. {
  14413. }
  14414. ApplicationProperties::~ApplicationProperties()
  14415. {
  14416. closeFiles();
  14417. clearSingletonInstance();
  14418. }
  14419. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14420. const String& fileNameSuffix,
  14421. const String& folderName_,
  14422. const int millisecondsBeforeSaving,
  14423. const int propertiesFileOptions) throw()
  14424. {
  14425. appName = applicationName;
  14426. fileSuffix = fileNameSuffix;
  14427. folderName = folderName_;
  14428. msBeforeSaving = millisecondsBeforeSaving;
  14429. options = propertiesFileOptions;
  14430. }
  14431. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14432. const bool testCommonSettings,
  14433. const bool showWarningDialogOnFailure)
  14434. {
  14435. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14436. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14437. if (! (userOk && commonOk))
  14438. {
  14439. if (showWarningDialogOnFailure)
  14440. {
  14441. String filenames;
  14442. if (userProps != 0 && ! userOk)
  14443. filenames << '\n' << userProps->getFile().getFullPathName();
  14444. if (commonProps != 0 && ! commonOk)
  14445. filenames << '\n' << commonProps->getFile().getFullPathName();
  14446. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14447. appName + TRANS(" - Unable to save settings"),
  14448. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14449. + appName + TRANS(" needs to be able to write to the following files:\n")
  14450. + filenames
  14451. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14452. }
  14453. return false;
  14454. }
  14455. return true;
  14456. }
  14457. void ApplicationProperties::openFiles() throw()
  14458. {
  14459. // You need to call setStorageParameters() before trying to get hold of the
  14460. // properties!
  14461. jassert (appName.isNotEmpty());
  14462. if (appName.isNotEmpty())
  14463. {
  14464. if (userProps == 0)
  14465. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14466. false, msBeforeSaving, options);
  14467. if (commonProps == 0)
  14468. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14469. true, msBeforeSaving, options);
  14470. userProps->setFallbackPropertySet (commonProps);
  14471. }
  14472. }
  14473. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14474. {
  14475. if (userProps == 0)
  14476. openFiles();
  14477. return userProps;
  14478. }
  14479. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14480. {
  14481. if (commonProps == 0)
  14482. openFiles();
  14483. if (returnUserPropsIfReadOnly)
  14484. {
  14485. if (commonSettingsAreReadOnly == 0)
  14486. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14487. if (commonSettingsAreReadOnly > 0)
  14488. return userProps;
  14489. }
  14490. return commonProps;
  14491. }
  14492. bool ApplicationProperties::saveIfNeeded()
  14493. {
  14494. return (userProps == 0 || userProps->saveIfNeeded())
  14495. && (commonProps == 0 || commonProps->saveIfNeeded());
  14496. }
  14497. void ApplicationProperties::closeFiles()
  14498. {
  14499. userProps = 0;
  14500. commonProps = 0;
  14501. }
  14502. END_JUCE_NAMESPACE
  14503. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14504. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14505. BEGIN_JUCE_NAMESPACE
  14506. namespace PropertyFileConstants
  14507. {
  14508. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14509. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14510. static const char* const fileTag = "PROPERTIES";
  14511. static const char* const valueTag = "VALUE";
  14512. static const char* const nameAttribute = "name";
  14513. static const char* const valueAttribute = "val";
  14514. }
  14515. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14516. const int options_, InterProcessLock* const processLock_)
  14517. : PropertySet (ignoreCaseOfKeyNames),
  14518. file (f),
  14519. timerInterval (millisecondsBeforeSaving),
  14520. options (options_),
  14521. loadedOk (false),
  14522. needsWriting (false),
  14523. processLock (processLock_)
  14524. {
  14525. // You need to correctly specify just one storage format for the file
  14526. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14527. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14528. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14529. ProcessScopedLock pl (createProcessLock());
  14530. if (pl != 0 && ! pl->isLocked())
  14531. return; // locking failure..
  14532. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14533. if (fileStream != 0)
  14534. {
  14535. int magicNumber = fileStream->readInt();
  14536. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14537. {
  14538. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14539. magicNumber = PropertyFileConstants::magicNumber;
  14540. }
  14541. if (magicNumber == PropertyFileConstants::magicNumber)
  14542. {
  14543. loadedOk = true;
  14544. BufferedInputStream in (fileStream.release(), 2048, true);
  14545. int numValues = in.readInt();
  14546. while (--numValues >= 0 && ! in.isExhausted())
  14547. {
  14548. const String key (in.readString());
  14549. const String value (in.readString());
  14550. jassert (key.isNotEmpty());
  14551. if (key.isNotEmpty())
  14552. getAllProperties().set (key, value);
  14553. }
  14554. }
  14555. else
  14556. {
  14557. // Not a binary props file - let's see if it's XML..
  14558. fileStream = 0;
  14559. XmlDocument parser (f);
  14560. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14561. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14562. {
  14563. doc = parser.getDocumentElement();
  14564. if (doc != 0)
  14565. {
  14566. loadedOk = true;
  14567. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14568. {
  14569. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14570. if (name.isNotEmpty())
  14571. {
  14572. getAllProperties().set (name,
  14573. e->getFirstChildElement() != 0
  14574. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14575. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14576. }
  14577. }
  14578. }
  14579. else
  14580. {
  14581. // must be a pretty broken XML file we're trying to parse here,
  14582. // or a sign that this object needs an InterProcessLock,
  14583. // or just a failure reading the file. This last reason is why
  14584. // we don't jassertfalse here.
  14585. }
  14586. }
  14587. }
  14588. }
  14589. else
  14590. {
  14591. loadedOk = ! f.exists();
  14592. }
  14593. }
  14594. PropertiesFile::~PropertiesFile()
  14595. {
  14596. if (! saveIfNeeded())
  14597. jassertfalse;
  14598. }
  14599. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14600. {
  14601. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14602. }
  14603. bool PropertiesFile::saveIfNeeded()
  14604. {
  14605. const ScopedLock sl (getLock());
  14606. return (! needsWriting) || save();
  14607. }
  14608. bool PropertiesFile::needsToBeSaved() const
  14609. {
  14610. const ScopedLock sl (getLock());
  14611. return needsWriting;
  14612. }
  14613. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14614. {
  14615. const ScopedLock sl (getLock());
  14616. needsWriting = needsToBeSaved_;
  14617. }
  14618. bool PropertiesFile::save()
  14619. {
  14620. const ScopedLock sl (getLock());
  14621. stopTimer();
  14622. if (file == File::nonexistent
  14623. || file.isDirectory()
  14624. || ! file.getParentDirectory().createDirectory())
  14625. return false;
  14626. if ((options & storeAsXML) != 0)
  14627. {
  14628. XmlElement doc (PropertyFileConstants::fileTag);
  14629. for (int i = 0; i < getAllProperties().size(); ++i)
  14630. {
  14631. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14632. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14633. // if the value seems to contain xml, store it as such..
  14634. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14635. XmlElement* const childElement = xmlContent.getDocumentElement();
  14636. if (childElement != 0)
  14637. e->addChildElement (childElement);
  14638. else
  14639. e->setAttribute (PropertyFileConstants::valueAttribute,
  14640. getAllProperties().getAllValues() [i]);
  14641. }
  14642. ProcessScopedLock pl (createProcessLock());
  14643. if (pl != 0 && ! pl->isLocked())
  14644. return false; // locking failure..
  14645. if (doc.writeToFile (file, String::empty))
  14646. {
  14647. needsWriting = false;
  14648. return true;
  14649. }
  14650. }
  14651. else
  14652. {
  14653. ProcessScopedLock pl (createProcessLock());
  14654. if (pl != 0 && ! pl->isLocked())
  14655. return false; // locking failure..
  14656. TemporaryFile tempFile (file);
  14657. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14658. if (out != 0)
  14659. {
  14660. if ((options & storeAsCompressedBinary) != 0)
  14661. {
  14662. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14663. out->flush();
  14664. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14665. }
  14666. else
  14667. {
  14668. // have you set up the storage option flags correctly?
  14669. jassert ((options & storeAsBinary) != 0);
  14670. out->writeInt (PropertyFileConstants::magicNumber);
  14671. }
  14672. const int numProperties = getAllProperties().size();
  14673. out->writeInt (numProperties);
  14674. for (int i = 0; i < numProperties; ++i)
  14675. {
  14676. out->writeString (getAllProperties().getAllKeys() [i]);
  14677. out->writeString (getAllProperties().getAllValues() [i]);
  14678. }
  14679. out = 0;
  14680. if (tempFile.overwriteTargetFileWithTemporary())
  14681. {
  14682. needsWriting = false;
  14683. return true;
  14684. }
  14685. }
  14686. }
  14687. return false;
  14688. }
  14689. void PropertiesFile::timerCallback()
  14690. {
  14691. saveIfNeeded();
  14692. }
  14693. void PropertiesFile::propertyChanged()
  14694. {
  14695. sendChangeMessage (this);
  14696. needsWriting = true;
  14697. if (timerInterval > 0)
  14698. startTimer (timerInterval);
  14699. else if (timerInterval == 0)
  14700. saveIfNeeded();
  14701. }
  14702. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14703. const String& fileNameSuffix,
  14704. const String& folderName,
  14705. const bool commonToAllUsers)
  14706. {
  14707. // mustn't have illegal characters in this name..
  14708. jassert (applicationName == File::createLegalFileName (applicationName));
  14709. #if JUCE_MAC || JUCE_IPHONE
  14710. File dir (commonToAllUsers ? "/Library/Preferences"
  14711. : "~/Library/Preferences");
  14712. if (folderName.isNotEmpty())
  14713. dir = dir.getChildFile (folderName);
  14714. #endif
  14715. #ifdef JUCE_LINUX
  14716. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14717. + (folderName.isNotEmpty() ? folderName
  14718. : ("." + applicationName)));
  14719. #endif
  14720. #if JUCE_WINDOWS
  14721. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14722. : File::userApplicationDataDirectory));
  14723. if (dir == File::nonexistent)
  14724. return File::nonexistent;
  14725. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14726. : applicationName);
  14727. #endif
  14728. return dir.getChildFile (applicationName)
  14729. .withFileExtension (fileNameSuffix);
  14730. }
  14731. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14732. const String& fileNameSuffix,
  14733. const String& folderName,
  14734. const bool commonToAllUsers,
  14735. const int millisecondsBeforeSaving,
  14736. const int propertiesFileOptions,
  14737. InterProcessLock* processLock_)
  14738. {
  14739. const File file (getDefaultAppSettingsFile (applicationName,
  14740. fileNameSuffix,
  14741. folderName,
  14742. commonToAllUsers));
  14743. jassert (file != File::nonexistent);
  14744. if (file == File::nonexistent)
  14745. return 0;
  14746. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14747. }
  14748. END_JUCE_NAMESPACE
  14749. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14750. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14751. BEGIN_JUCE_NAMESPACE
  14752. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14753. const String& fileWildcard_,
  14754. const String& openFileDialogTitle_,
  14755. const String& saveFileDialogTitle_)
  14756. : changedSinceSave (false),
  14757. fileExtension (fileExtension_),
  14758. fileWildcard (fileWildcard_),
  14759. openFileDialogTitle (openFileDialogTitle_),
  14760. saveFileDialogTitle (saveFileDialogTitle_)
  14761. {
  14762. }
  14763. FileBasedDocument::~FileBasedDocument()
  14764. {
  14765. }
  14766. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14767. {
  14768. if (changedSinceSave != hasChanged)
  14769. {
  14770. changedSinceSave = hasChanged;
  14771. sendChangeMessage (this);
  14772. }
  14773. }
  14774. void FileBasedDocument::changed()
  14775. {
  14776. changedSinceSave = true;
  14777. sendChangeMessage (this);
  14778. }
  14779. void FileBasedDocument::setFile (const File& newFile)
  14780. {
  14781. if (documentFile != newFile)
  14782. {
  14783. documentFile = newFile;
  14784. changed();
  14785. }
  14786. }
  14787. bool FileBasedDocument::loadFrom (const File& newFile,
  14788. const bool showMessageOnFailure)
  14789. {
  14790. MouseCursor::showWaitCursor();
  14791. const File oldFile (documentFile);
  14792. documentFile = newFile;
  14793. String error;
  14794. if (newFile.existsAsFile())
  14795. {
  14796. error = loadDocument (newFile);
  14797. if (error.isEmpty())
  14798. {
  14799. setChangedFlag (false);
  14800. MouseCursor::hideWaitCursor();
  14801. setLastDocumentOpened (newFile);
  14802. return true;
  14803. }
  14804. }
  14805. else
  14806. {
  14807. error = "The file doesn't exist";
  14808. }
  14809. documentFile = oldFile;
  14810. MouseCursor::hideWaitCursor();
  14811. if (showMessageOnFailure)
  14812. {
  14813. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14814. TRANS("Failed to open file..."),
  14815. TRANS("There was an error while trying to load the file:\n\n")
  14816. + newFile.getFullPathName()
  14817. + "\n\n"
  14818. + error);
  14819. }
  14820. return false;
  14821. }
  14822. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14823. {
  14824. FileChooser fc (openFileDialogTitle,
  14825. getLastDocumentOpened(),
  14826. fileWildcard);
  14827. if (fc.browseForFileToOpen())
  14828. return loadFrom (fc.getResult(), showMessageOnFailure);
  14829. return false;
  14830. }
  14831. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14832. const bool showMessageOnFailure)
  14833. {
  14834. return saveAs (documentFile,
  14835. false,
  14836. askUserForFileIfNotSpecified,
  14837. showMessageOnFailure);
  14838. }
  14839. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14840. const bool warnAboutOverwritingExistingFiles,
  14841. const bool askUserForFileIfNotSpecified,
  14842. const bool showMessageOnFailure)
  14843. {
  14844. if (newFile == File::nonexistent)
  14845. {
  14846. if (askUserForFileIfNotSpecified)
  14847. {
  14848. return saveAsInteractive (true);
  14849. }
  14850. else
  14851. {
  14852. // can't save to an unspecified file
  14853. jassertfalse;
  14854. return failedToWriteToFile;
  14855. }
  14856. }
  14857. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14858. {
  14859. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14860. TRANS("File already exists"),
  14861. TRANS("There's already a file called:\n\n")
  14862. + newFile.getFullPathName()
  14863. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14864. TRANS("overwrite"),
  14865. TRANS("cancel")))
  14866. {
  14867. return userCancelledSave;
  14868. }
  14869. }
  14870. MouseCursor::showWaitCursor();
  14871. const File oldFile (documentFile);
  14872. documentFile = newFile;
  14873. String error (saveDocument (newFile));
  14874. if (error.isEmpty())
  14875. {
  14876. setChangedFlag (false);
  14877. MouseCursor::hideWaitCursor();
  14878. return savedOk;
  14879. }
  14880. documentFile = oldFile;
  14881. MouseCursor::hideWaitCursor();
  14882. if (showMessageOnFailure)
  14883. {
  14884. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14885. TRANS("Error writing to file..."),
  14886. TRANS("An error occurred while trying to save \"")
  14887. + getDocumentTitle()
  14888. + TRANS("\" to the file:\n\n")
  14889. + newFile.getFullPathName()
  14890. + "\n\n"
  14891. + error);
  14892. }
  14893. return failedToWriteToFile;
  14894. }
  14895. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14896. {
  14897. if (! hasChangedSinceSaved())
  14898. return savedOk;
  14899. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14900. TRANS("Closing document..."),
  14901. TRANS("Do you want to save the changes to \"")
  14902. + getDocumentTitle() + "\"?",
  14903. TRANS("save"),
  14904. TRANS("discard changes"),
  14905. TRANS("cancel"));
  14906. if (r == 1)
  14907. {
  14908. // save changes
  14909. return save (true, true);
  14910. }
  14911. else if (r == 2)
  14912. {
  14913. // discard changes
  14914. return savedOk;
  14915. }
  14916. return userCancelledSave;
  14917. }
  14918. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14919. {
  14920. File f;
  14921. if (documentFile.existsAsFile())
  14922. f = documentFile;
  14923. else
  14924. f = getLastDocumentOpened();
  14925. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14926. if (legalFilename.isEmpty())
  14927. legalFilename = "unnamed";
  14928. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14929. f = f.getSiblingFile (legalFilename);
  14930. else
  14931. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14932. f = f.withFileExtension (fileExtension)
  14933. .getNonexistentSibling (true);
  14934. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14935. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14936. {
  14937. setLastDocumentOpened (fc.getResult());
  14938. File chosen (fc.getResult());
  14939. if (chosen.getFileExtension().isEmpty())
  14940. {
  14941. chosen = chosen.withFileExtension (fileExtension);
  14942. if (chosen.exists())
  14943. {
  14944. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14945. TRANS("File already exists"),
  14946. TRANS("There's already a file called:")
  14947. + "\n\n" + chosen.getFullPathName()
  14948. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14949. TRANS("overwrite"),
  14950. TRANS("cancel")))
  14951. {
  14952. return userCancelledSave;
  14953. }
  14954. }
  14955. }
  14956. return saveAs (chosen, false, false, true);
  14957. }
  14958. return userCancelledSave;
  14959. }
  14960. END_JUCE_NAMESPACE
  14961. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14962. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14963. BEGIN_JUCE_NAMESPACE
  14964. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14965. : maxNumberOfItems (10)
  14966. {
  14967. }
  14968. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14969. {
  14970. }
  14971. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14972. {
  14973. maxNumberOfItems = jmax (1, newMaxNumber);
  14974. while (getNumFiles() > maxNumberOfItems)
  14975. files.remove (getNumFiles() - 1);
  14976. }
  14977. int RecentlyOpenedFilesList::getNumFiles() const
  14978. {
  14979. return files.size();
  14980. }
  14981. const File RecentlyOpenedFilesList::getFile (const int index) const
  14982. {
  14983. return File (files [index]);
  14984. }
  14985. void RecentlyOpenedFilesList::clear()
  14986. {
  14987. files.clear();
  14988. }
  14989. void RecentlyOpenedFilesList::addFile (const File& file)
  14990. {
  14991. const String path (file.getFullPathName());
  14992. files.removeString (path, true);
  14993. files.insert (0, path);
  14994. setMaxNumberOfItems (maxNumberOfItems);
  14995. }
  14996. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14997. {
  14998. for (int i = getNumFiles(); --i >= 0;)
  14999. if (! getFile(i).exists())
  15000. files.remove (i);
  15001. }
  15002. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15003. const int baseItemId,
  15004. const bool showFullPaths,
  15005. const bool dontAddNonExistentFiles,
  15006. const File** filesToAvoid)
  15007. {
  15008. int num = 0;
  15009. for (int i = 0; i < getNumFiles(); ++i)
  15010. {
  15011. const File f (getFile(i));
  15012. if ((! dontAddNonExistentFiles) || f.exists())
  15013. {
  15014. bool needsAvoiding = false;
  15015. if (filesToAvoid != 0)
  15016. {
  15017. const File** avoid = filesToAvoid;
  15018. while (*avoid != 0)
  15019. {
  15020. if (f == **avoid)
  15021. {
  15022. needsAvoiding = true;
  15023. break;
  15024. }
  15025. ++avoid;
  15026. }
  15027. }
  15028. if (! needsAvoiding)
  15029. {
  15030. menuToAddTo.addItem (baseItemId + i,
  15031. showFullPaths ? f.getFullPathName()
  15032. : f.getFileName());
  15033. ++num;
  15034. }
  15035. }
  15036. }
  15037. return num;
  15038. }
  15039. const String RecentlyOpenedFilesList::toString() const
  15040. {
  15041. return files.joinIntoString ("\n");
  15042. }
  15043. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15044. {
  15045. clear();
  15046. files.addLines (stringifiedVersion);
  15047. setMaxNumberOfItems (maxNumberOfItems);
  15048. }
  15049. END_JUCE_NAMESPACE
  15050. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15051. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15052. BEGIN_JUCE_NAMESPACE
  15053. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15054. const int minimumTransactions)
  15055. : totalUnitsStored (0),
  15056. nextIndex (0),
  15057. newTransaction (true),
  15058. reentrancyCheck (false)
  15059. {
  15060. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15061. minimumTransactions);
  15062. }
  15063. UndoManager::~UndoManager()
  15064. {
  15065. clearUndoHistory();
  15066. }
  15067. void UndoManager::clearUndoHistory()
  15068. {
  15069. transactions.clear();
  15070. transactionNames.clear();
  15071. totalUnitsStored = 0;
  15072. nextIndex = 0;
  15073. sendChangeMessage (this);
  15074. }
  15075. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15076. {
  15077. return totalUnitsStored;
  15078. }
  15079. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15080. const int minimumTransactions)
  15081. {
  15082. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15083. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15084. }
  15085. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15086. {
  15087. if (command_ != 0)
  15088. {
  15089. ScopedPointer<UndoableAction> command (command_);
  15090. if (actionName.isNotEmpty())
  15091. currentTransactionName = actionName;
  15092. if (reentrancyCheck)
  15093. {
  15094. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15095. // undo() methods, or else these actions won't actually get done.
  15096. return false;
  15097. }
  15098. else if (command->perform())
  15099. {
  15100. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15101. if (commandSet != 0 && ! newTransaction)
  15102. {
  15103. UndoableAction* lastAction = commandSet->getLast();
  15104. if (lastAction != 0)
  15105. {
  15106. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15107. if (coalescedAction != 0)
  15108. {
  15109. command = coalescedAction;
  15110. totalUnitsStored -= lastAction->getSizeInUnits();
  15111. commandSet->removeLast();
  15112. }
  15113. }
  15114. }
  15115. else
  15116. {
  15117. commandSet = new OwnedArray<UndoableAction>();
  15118. transactions.insert (nextIndex, commandSet);
  15119. transactionNames.insert (nextIndex, currentTransactionName);
  15120. ++nextIndex;
  15121. }
  15122. totalUnitsStored += command->getSizeInUnits();
  15123. commandSet->add (command.release());
  15124. newTransaction = false;
  15125. while (nextIndex < transactions.size())
  15126. {
  15127. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15128. for (int i = lastSet->size(); --i >= 0;)
  15129. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15130. transactions.removeLast();
  15131. transactionNames.remove (transactionNames.size() - 1);
  15132. }
  15133. while (nextIndex > 0
  15134. && totalUnitsStored > maxNumUnitsToKeep
  15135. && transactions.size() > minimumTransactionsToKeep)
  15136. {
  15137. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15138. for (int i = firstSet->size(); --i >= 0;)
  15139. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15140. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15141. transactions.remove (0);
  15142. transactionNames.remove (0);
  15143. --nextIndex;
  15144. }
  15145. sendChangeMessage (this);
  15146. return true;
  15147. }
  15148. }
  15149. return false;
  15150. }
  15151. void UndoManager::beginNewTransaction (const String& actionName)
  15152. {
  15153. newTransaction = true;
  15154. currentTransactionName = actionName;
  15155. }
  15156. void UndoManager::setCurrentTransactionName (const String& newName)
  15157. {
  15158. currentTransactionName = newName;
  15159. }
  15160. bool UndoManager::canUndo() const
  15161. {
  15162. return nextIndex > 0;
  15163. }
  15164. bool UndoManager::canRedo() const
  15165. {
  15166. return nextIndex < transactions.size();
  15167. }
  15168. const String UndoManager::getUndoDescription() const
  15169. {
  15170. return transactionNames [nextIndex - 1];
  15171. }
  15172. const String UndoManager::getRedoDescription() const
  15173. {
  15174. return transactionNames [nextIndex];
  15175. }
  15176. bool UndoManager::undo()
  15177. {
  15178. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15179. if (commandSet == 0)
  15180. return false;
  15181. reentrancyCheck = true;
  15182. bool failed = false;
  15183. for (int i = commandSet->size(); --i >= 0;)
  15184. {
  15185. if (! commandSet->getUnchecked(i)->undo())
  15186. {
  15187. jassertfalse;
  15188. failed = true;
  15189. break;
  15190. }
  15191. }
  15192. reentrancyCheck = false;
  15193. if (failed)
  15194. clearUndoHistory();
  15195. else
  15196. --nextIndex;
  15197. beginNewTransaction();
  15198. sendChangeMessage (this);
  15199. return true;
  15200. }
  15201. bool UndoManager::redo()
  15202. {
  15203. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15204. if (commandSet == 0)
  15205. return false;
  15206. reentrancyCheck = true;
  15207. bool failed = false;
  15208. for (int i = 0; i < commandSet->size(); ++i)
  15209. {
  15210. if (! commandSet->getUnchecked(i)->perform())
  15211. {
  15212. jassertfalse;
  15213. failed = true;
  15214. break;
  15215. }
  15216. }
  15217. reentrancyCheck = false;
  15218. if (failed)
  15219. clearUndoHistory();
  15220. else
  15221. ++nextIndex;
  15222. beginNewTransaction();
  15223. sendChangeMessage (this);
  15224. return true;
  15225. }
  15226. bool UndoManager::undoCurrentTransactionOnly()
  15227. {
  15228. return newTransaction ? false : undo();
  15229. }
  15230. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15231. {
  15232. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15233. if (commandSet != 0 && ! newTransaction)
  15234. {
  15235. for (int i = 0; i < commandSet->size(); ++i)
  15236. actionsFound.add (commandSet->getUnchecked(i));
  15237. }
  15238. }
  15239. int UndoManager::getNumActionsInCurrentTransaction() const
  15240. {
  15241. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15242. if (commandSet != 0 && ! newTransaction)
  15243. return commandSet->size();
  15244. return 0;
  15245. }
  15246. END_JUCE_NAMESPACE
  15247. /*** End of inlined file: juce_UndoManager.cpp ***/
  15248. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15249. BEGIN_JUCE_NAMESPACE
  15250. static const char* const aiffFormatName = "AIFF file";
  15251. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15252. class AiffAudioFormatReader : public AudioFormatReader
  15253. {
  15254. public:
  15255. int bytesPerFrame;
  15256. int64 dataChunkStart;
  15257. bool littleEndian;
  15258. AiffAudioFormatReader (InputStream* in)
  15259. : AudioFormatReader (in, TRANS (aiffFormatName))
  15260. {
  15261. if (input->readInt() == chunkName ("FORM"))
  15262. {
  15263. const int len = input->readIntBigEndian();
  15264. const int64 end = input->getPosition() + len;
  15265. const int nextType = input->readInt();
  15266. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15267. {
  15268. bool hasGotVer = false;
  15269. bool hasGotData = false;
  15270. bool hasGotType = false;
  15271. while (input->getPosition() < end)
  15272. {
  15273. const int type = input->readInt();
  15274. const uint32 length = (uint32) input->readIntBigEndian();
  15275. const int64 chunkEnd = input->getPosition() + length;
  15276. if (type == chunkName ("FVER"))
  15277. {
  15278. hasGotVer = true;
  15279. const int ver = input->readIntBigEndian();
  15280. if (ver != 0 && ver != (int)0xa2805140)
  15281. break;
  15282. }
  15283. else if (type == chunkName ("COMM"))
  15284. {
  15285. hasGotType = true;
  15286. numChannels = (unsigned int)input->readShortBigEndian();
  15287. lengthInSamples = input->readIntBigEndian();
  15288. bitsPerSample = input->readShortBigEndian();
  15289. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15290. unsigned char sampleRateBytes[10];
  15291. input->read (sampleRateBytes, 10);
  15292. const int byte0 = sampleRateBytes[0];
  15293. if ((byte0 & 0x80) != 0
  15294. || byte0 <= 0x3F || byte0 > 0x40
  15295. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15296. break;
  15297. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15298. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15299. sampleRate = (int) sampRate;
  15300. if (length <= 18)
  15301. {
  15302. // some types don't have a chunk large enough to include a compression
  15303. // type, so assume it's just big-endian pcm
  15304. littleEndian = false;
  15305. }
  15306. else
  15307. {
  15308. const int compType = input->readInt();
  15309. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15310. {
  15311. littleEndian = false;
  15312. }
  15313. else if (compType == chunkName ("sowt"))
  15314. {
  15315. littleEndian = true;
  15316. }
  15317. else
  15318. {
  15319. sampleRate = 0;
  15320. break;
  15321. }
  15322. }
  15323. }
  15324. else if (type == chunkName ("SSND"))
  15325. {
  15326. hasGotData = true;
  15327. const int offset = input->readIntBigEndian();
  15328. dataChunkStart = input->getPosition() + 4 + offset;
  15329. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15330. }
  15331. else if ((hasGotVer && hasGotData && hasGotType)
  15332. || chunkEnd < input->getPosition()
  15333. || input->isExhausted())
  15334. {
  15335. break;
  15336. }
  15337. input->setPosition (chunkEnd);
  15338. }
  15339. }
  15340. }
  15341. }
  15342. ~AiffAudioFormatReader()
  15343. {
  15344. }
  15345. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15346. int64 startSampleInFile, int numSamples)
  15347. {
  15348. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15349. if (samplesAvailable < numSamples)
  15350. {
  15351. for (int i = numDestChannels; --i >= 0;)
  15352. if (destSamples[i] != 0)
  15353. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15354. numSamples = (int) samplesAvailable;
  15355. }
  15356. if (numSamples <= 0)
  15357. return true;
  15358. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15359. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15360. char tempBuffer [tempBufSize];
  15361. while (numSamples > 0)
  15362. {
  15363. int* left = destSamples[0];
  15364. if (left != 0)
  15365. left += startOffsetInDestBuffer;
  15366. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15367. if (right != 0)
  15368. right += startOffsetInDestBuffer;
  15369. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15370. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15371. if (bytesRead < numThisTime * bytesPerFrame)
  15372. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15373. if (bitsPerSample == 16)
  15374. {
  15375. if (littleEndian)
  15376. {
  15377. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15378. if (numChannels > 1)
  15379. {
  15380. if (left == 0)
  15381. {
  15382. for (int i = numThisTime; --i >= 0;)
  15383. {
  15384. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15385. ++src;
  15386. }
  15387. }
  15388. else if (right == 0)
  15389. {
  15390. for (int i = numThisTime; --i >= 0;)
  15391. {
  15392. ++src;
  15393. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15394. }
  15395. }
  15396. else
  15397. {
  15398. for (int i = numThisTime; --i >= 0;)
  15399. {
  15400. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15401. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15402. }
  15403. }
  15404. }
  15405. else
  15406. {
  15407. for (int i = numThisTime; --i >= 0;)
  15408. {
  15409. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15410. }
  15411. }
  15412. }
  15413. else
  15414. {
  15415. const char* src = tempBuffer;
  15416. if (numChannels > 1)
  15417. {
  15418. if (left == 0)
  15419. {
  15420. for (int i = numThisTime; --i >= 0;)
  15421. {
  15422. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15423. src += 4;
  15424. }
  15425. }
  15426. else if (right == 0)
  15427. {
  15428. for (int i = numThisTime; --i >= 0;)
  15429. {
  15430. src += 2;
  15431. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15432. src += 2;
  15433. }
  15434. }
  15435. else
  15436. {
  15437. for (int i = numThisTime; --i >= 0;)
  15438. {
  15439. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15440. src += 2;
  15441. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15442. src += 2;
  15443. }
  15444. }
  15445. }
  15446. else
  15447. {
  15448. for (int i = numThisTime; --i >= 0;)
  15449. {
  15450. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15451. src += 2;
  15452. }
  15453. }
  15454. }
  15455. }
  15456. else if (bitsPerSample == 24)
  15457. {
  15458. const char* src = (const char*)tempBuffer;
  15459. if (littleEndian)
  15460. {
  15461. if (numChannels > 1)
  15462. {
  15463. if (left == 0)
  15464. {
  15465. for (int i = numThisTime; --i >= 0;)
  15466. {
  15467. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15468. src += 6;
  15469. }
  15470. }
  15471. else if (right == 0)
  15472. {
  15473. for (int i = numThisTime; --i >= 0;)
  15474. {
  15475. src += 3;
  15476. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15477. src += 3;
  15478. }
  15479. }
  15480. else
  15481. {
  15482. for (int i = numThisTime; --i >= 0;)
  15483. {
  15484. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15485. src += 3;
  15486. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15487. src += 3;
  15488. }
  15489. }
  15490. }
  15491. else
  15492. {
  15493. for (int i = numThisTime; --i >= 0;)
  15494. {
  15495. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15496. src += 3;
  15497. }
  15498. }
  15499. }
  15500. else
  15501. {
  15502. if (numChannels > 1)
  15503. {
  15504. if (left == 0)
  15505. {
  15506. for (int i = numThisTime; --i >= 0;)
  15507. {
  15508. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15509. src += 6;
  15510. }
  15511. }
  15512. else if (right == 0)
  15513. {
  15514. for (int i = numThisTime; --i >= 0;)
  15515. {
  15516. src += 3;
  15517. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15518. src += 3;
  15519. }
  15520. }
  15521. else
  15522. {
  15523. for (int i = numThisTime; --i >= 0;)
  15524. {
  15525. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15526. src += 3;
  15527. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15528. src += 3;
  15529. }
  15530. }
  15531. }
  15532. else
  15533. {
  15534. for (int i = numThisTime; --i >= 0;)
  15535. {
  15536. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15537. src += 3;
  15538. }
  15539. }
  15540. }
  15541. }
  15542. else if (bitsPerSample == 32)
  15543. {
  15544. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15545. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15546. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15547. if (littleEndian)
  15548. {
  15549. if (numChannels > 1)
  15550. {
  15551. if (l == 0)
  15552. {
  15553. for (int i = numThisTime; --i >= 0;)
  15554. {
  15555. ++src;
  15556. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15557. }
  15558. }
  15559. else if (r == 0)
  15560. {
  15561. for (int i = numThisTime; --i >= 0;)
  15562. {
  15563. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15564. ++src;
  15565. }
  15566. }
  15567. else
  15568. {
  15569. for (int i = numThisTime; --i >= 0;)
  15570. {
  15571. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15572. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15573. }
  15574. }
  15575. }
  15576. else
  15577. {
  15578. for (int i = numThisTime; --i >= 0;)
  15579. {
  15580. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15581. }
  15582. }
  15583. }
  15584. else
  15585. {
  15586. if (numChannels > 1)
  15587. {
  15588. if (l == 0)
  15589. {
  15590. for (int i = numThisTime; --i >= 0;)
  15591. {
  15592. ++src;
  15593. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15594. }
  15595. }
  15596. else if (r == 0)
  15597. {
  15598. for (int i = numThisTime; --i >= 0;)
  15599. {
  15600. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15601. ++src;
  15602. }
  15603. }
  15604. else
  15605. {
  15606. for (int i = numThisTime; --i >= 0;)
  15607. {
  15608. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15609. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15610. }
  15611. }
  15612. }
  15613. else
  15614. {
  15615. for (int i = numThisTime; --i >= 0;)
  15616. {
  15617. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15618. }
  15619. }
  15620. }
  15621. left = reinterpret_cast <int*> (l);
  15622. right = reinterpret_cast <int*> (r);
  15623. }
  15624. else if (bitsPerSample == 8)
  15625. {
  15626. const char* src = tempBuffer;
  15627. if (numChannels > 1)
  15628. {
  15629. if (left == 0)
  15630. {
  15631. for (int i = numThisTime; --i >= 0;)
  15632. {
  15633. *right++ = ((int) *src++) << 24;
  15634. ++src;
  15635. }
  15636. }
  15637. else if (right == 0)
  15638. {
  15639. for (int i = numThisTime; --i >= 0;)
  15640. {
  15641. ++src;
  15642. *left++ = ((int) *src++) << 24;
  15643. }
  15644. }
  15645. else
  15646. {
  15647. for (int i = numThisTime; --i >= 0;)
  15648. {
  15649. *left++ = ((int) *src++) << 24;
  15650. *right++ = ((int) *src++) << 24;
  15651. }
  15652. }
  15653. }
  15654. else
  15655. {
  15656. for (int i = numThisTime; --i >= 0;)
  15657. {
  15658. *left++ = ((int) *src++) << 24;
  15659. }
  15660. }
  15661. }
  15662. startOffsetInDestBuffer += numThisTime;
  15663. numSamples -= numThisTime;
  15664. }
  15665. if (numSamples > 0)
  15666. {
  15667. for (int i = numDestChannels; --i >= 0;)
  15668. if (destSamples[i] != 0)
  15669. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15670. sizeof (int) * numSamples);
  15671. }
  15672. return true;
  15673. }
  15674. juce_UseDebuggingNewOperator
  15675. private:
  15676. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15677. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15678. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15679. };
  15680. class AiffAudioFormatWriter : public AudioFormatWriter
  15681. {
  15682. MemoryBlock tempBlock;
  15683. uint32 lengthInSamples, bytesWritten;
  15684. int64 headerPosition;
  15685. bool writeFailed;
  15686. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15687. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15688. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15689. void writeHeader()
  15690. {
  15691. const bool couldSeekOk = output->setPosition (headerPosition);
  15692. (void) couldSeekOk;
  15693. // if this fails, you've given it an output stream that can't seek! It needs
  15694. // to be able to seek back to write the header
  15695. jassert (couldSeekOk);
  15696. const int headerLen = 54;
  15697. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15698. audioBytes += (audioBytes & 1);
  15699. output->writeInt (chunkName ("FORM"));
  15700. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15701. output->writeInt (chunkName ("AIFF"));
  15702. output->writeInt (chunkName ("COMM"));
  15703. output->writeIntBigEndian (18);
  15704. output->writeShortBigEndian ((short) numChannels);
  15705. output->writeIntBigEndian (lengthInSamples);
  15706. output->writeShortBigEndian ((short) bitsPerSample);
  15707. uint8 sampleRateBytes[10];
  15708. zeromem (sampleRateBytes, 10);
  15709. if (sampleRate <= 1)
  15710. {
  15711. sampleRateBytes[0] = 0x3f;
  15712. sampleRateBytes[1] = 0xff;
  15713. sampleRateBytes[2] = 0x80;
  15714. }
  15715. else
  15716. {
  15717. int mask = 0x40000000;
  15718. sampleRateBytes[0] = 0x40;
  15719. if (sampleRate >= mask)
  15720. {
  15721. jassertfalse;
  15722. sampleRateBytes[1] = 0x1d;
  15723. }
  15724. else
  15725. {
  15726. int n = (int) sampleRate;
  15727. int i;
  15728. for (i = 0; i <= 32 ; ++i)
  15729. {
  15730. if ((n & mask) != 0)
  15731. break;
  15732. mask >>= 1;
  15733. }
  15734. n = n << (i + 1);
  15735. sampleRateBytes[1] = (uint8) (29 - i);
  15736. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15737. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15738. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15739. sampleRateBytes[5] = (uint8) (n & 0xff);
  15740. }
  15741. }
  15742. output->write (sampleRateBytes, 10);
  15743. output->writeInt (chunkName ("SSND"));
  15744. output->writeIntBigEndian (audioBytes + 8);
  15745. output->writeInt (0);
  15746. output->writeInt (0);
  15747. jassert (output->getPosition() == headerLen);
  15748. }
  15749. public:
  15750. AiffAudioFormatWriter (OutputStream* out,
  15751. const double sampleRate_,
  15752. const unsigned int chans,
  15753. const int bits)
  15754. : AudioFormatWriter (out,
  15755. TRANS (aiffFormatName),
  15756. sampleRate_,
  15757. chans,
  15758. bits),
  15759. lengthInSamples (0),
  15760. bytesWritten (0),
  15761. writeFailed (false)
  15762. {
  15763. headerPosition = out->getPosition();
  15764. writeHeader();
  15765. }
  15766. ~AiffAudioFormatWriter()
  15767. {
  15768. if ((bytesWritten & 1) != 0)
  15769. output->writeByte (0);
  15770. writeHeader();
  15771. }
  15772. bool write (const int** data, int numSamples)
  15773. {
  15774. if (writeFailed)
  15775. return false;
  15776. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15777. tempBlock.ensureSize (bytes, false);
  15778. char* buffer = static_cast <char*> (tempBlock.getData());
  15779. const int* left = data[0];
  15780. const int* right = data[1];
  15781. if (right == 0)
  15782. right = left;
  15783. if (bitsPerSample == 16)
  15784. {
  15785. short* b = reinterpret_cast <short*> (buffer);
  15786. if (numChannels > 1)
  15787. {
  15788. for (int i = numSamples; --i >= 0;)
  15789. {
  15790. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15791. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15792. }
  15793. }
  15794. else
  15795. {
  15796. for (int i = numSamples; --i >= 0;)
  15797. {
  15798. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15799. }
  15800. }
  15801. }
  15802. else if (bitsPerSample == 24)
  15803. {
  15804. char* b = buffer;
  15805. if (numChannels > 1)
  15806. {
  15807. for (int i = numSamples; --i >= 0;)
  15808. {
  15809. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15810. b += 3;
  15811. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15812. b += 3;
  15813. }
  15814. }
  15815. else
  15816. {
  15817. for (int i = numSamples; --i >= 0;)
  15818. {
  15819. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15820. b += 3;
  15821. }
  15822. }
  15823. }
  15824. else if (bitsPerSample == 32)
  15825. {
  15826. uint32* b = reinterpret_cast <uint32*> (buffer);
  15827. if (numChannels > 1)
  15828. {
  15829. for (int i = numSamples; --i >= 0;)
  15830. {
  15831. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15832. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15833. }
  15834. }
  15835. else
  15836. {
  15837. for (int i = numSamples; --i >= 0;)
  15838. {
  15839. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15840. }
  15841. }
  15842. }
  15843. else if (bitsPerSample == 8)
  15844. {
  15845. char* b = buffer;
  15846. if (numChannels > 1)
  15847. {
  15848. for (int i = numSamples; --i >= 0;)
  15849. {
  15850. *b++ = (char) (*left++ >> 24);
  15851. *b++ = (char) (*right++ >> 24);
  15852. }
  15853. }
  15854. else
  15855. {
  15856. for (int i = numSamples; --i >= 0;)
  15857. {
  15858. *b++ = (char) (*left++ >> 24);
  15859. }
  15860. }
  15861. }
  15862. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15863. || ! output->write (buffer, bytes))
  15864. {
  15865. // failed to write to disk, so let's try writing the header.
  15866. // If it's just run out of disk space, then if it does manage
  15867. // to write the header, we'll still have a useable file..
  15868. writeHeader();
  15869. writeFailed = true;
  15870. return false;
  15871. }
  15872. else
  15873. {
  15874. bytesWritten += bytes;
  15875. lengthInSamples += numSamples;
  15876. return true;
  15877. }
  15878. }
  15879. juce_UseDebuggingNewOperator
  15880. };
  15881. AiffAudioFormat::AiffAudioFormat()
  15882. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15883. {
  15884. }
  15885. AiffAudioFormat::~AiffAudioFormat()
  15886. {
  15887. }
  15888. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15889. {
  15890. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15891. return Array <int> (rates);
  15892. }
  15893. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15894. {
  15895. const int depths[] = { 8, 16, 24, 0 };
  15896. return Array <int> (depths);
  15897. }
  15898. bool AiffAudioFormat::canDoStereo()
  15899. {
  15900. return true;
  15901. }
  15902. bool AiffAudioFormat::canDoMono()
  15903. {
  15904. return true;
  15905. }
  15906. #if JUCE_MAC
  15907. bool AiffAudioFormat::canHandleFile (const File& f)
  15908. {
  15909. if (AudioFormat::canHandleFile (f))
  15910. return true;
  15911. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15912. return type == 'AIFF' || type == 'AIFC'
  15913. || type == 'aiff' || type == 'aifc';
  15914. }
  15915. #endif
  15916. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15917. const bool deleteStreamIfOpeningFails)
  15918. {
  15919. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15920. if (w->sampleRate != 0)
  15921. return w.release();
  15922. if (! deleteStreamIfOpeningFails)
  15923. w->input = 0;
  15924. return 0;
  15925. }
  15926. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15927. double sampleRate,
  15928. unsigned int chans,
  15929. int bitsPerSample,
  15930. const StringPairArray& /*metadataValues*/,
  15931. int /*qualityOptionIndex*/)
  15932. {
  15933. if (getPossibleBitDepths().contains (bitsPerSample))
  15934. {
  15935. return new AiffAudioFormatWriter (out,
  15936. sampleRate,
  15937. chans,
  15938. bitsPerSample);
  15939. }
  15940. return 0;
  15941. }
  15942. END_JUCE_NAMESPACE
  15943. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15944. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15945. BEGIN_JUCE_NAMESPACE
  15946. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15947. const String& formatName_)
  15948. : sampleRate (0),
  15949. bitsPerSample (0),
  15950. lengthInSamples (0),
  15951. numChannels (0),
  15952. usesFloatingPointData (false),
  15953. input (in),
  15954. formatName (formatName_)
  15955. {
  15956. }
  15957. AudioFormatReader::~AudioFormatReader()
  15958. {
  15959. delete input;
  15960. }
  15961. bool AudioFormatReader::read (int** destSamples,
  15962. int numDestChannels,
  15963. int64 startSampleInSource,
  15964. int numSamplesToRead,
  15965. const bool fillLeftoverChannelsWithCopies)
  15966. {
  15967. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15968. int startOffsetInDestBuffer = 0;
  15969. if (startSampleInSource < 0)
  15970. {
  15971. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15972. for (int i = numDestChannels; --i >= 0;)
  15973. if (destSamples[i] != 0)
  15974. zeromem (destSamples[i], sizeof (int) * silence);
  15975. startOffsetInDestBuffer += silence;
  15976. numSamplesToRead -= silence;
  15977. startSampleInSource = 0;
  15978. }
  15979. if (numSamplesToRead <= 0)
  15980. return true;
  15981. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  15982. startSampleInSource, numSamplesToRead))
  15983. return false;
  15984. if (numDestChannels > (int) numChannels)
  15985. {
  15986. if (fillLeftoverChannelsWithCopies)
  15987. {
  15988. int* lastFullChannel = destSamples[0];
  15989. for (int i = numDestChannels; --i > 0;)
  15990. {
  15991. if (destSamples[i] != 0)
  15992. {
  15993. lastFullChannel = destSamples[i];
  15994. break;
  15995. }
  15996. }
  15997. if (lastFullChannel != 0)
  15998. for (int i = numChannels; i < numDestChannels; ++i)
  15999. if (destSamples[i] != 0)
  16000. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16001. }
  16002. else
  16003. {
  16004. for (int i = numChannels; i < numDestChannels; ++i)
  16005. if (destSamples[i] != 0)
  16006. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16007. }
  16008. }
  16009. return true;
  16010. }
  16011. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16012. {
  16013. float mn = buffer[0];
  16014. float mx = mn;
  16015. for (int i = 1; i < num; ++i)
  16016. {
  16017. const float s = buffer[i];
  16018. if (s > mx) mx = s;
  16019. if (s < mn) mn = s;
  16020. }
  16021. maxVal = mx;
  16022. minVal = mn;
  16023. }
  16024. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16025. int64 numSamples,
  16026. float& lowestLeft, float& highestLeft,
  16027. float& lowestRight, float& highestRight)
  16028. {
  16029. if (numSamples <= 0)
  16030. {
  16031. lowestLeft = 0;
  16032. lowestRight = 0;
  16033. highestLeft = 0;
  16034. highestRight = 0;
  16035. return;
  16036. }
  16037. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16038. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16039. int* tempBuffer[3];
  16040. tempBuffer[0] = (int*) tempSpace.getData();
  16041. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16042. tempBuffer[2] = 0;
  16043. if (usesFloatingPointData)
  16044. {
  16045. float lmin = 1.0e6f;
  16046. float lmax = -lmin;
  16047. float rmin = lmin;
  16048. float rmax = lmax;
  16049. while (numSamples > 0)
  16050. {
  16051. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16052. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16053. numSamples -= numToDo;
  16054. startSampleInFile += numToDo;
  16055. float bufmin, bufmax;
  16056. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16057. lmin = jmin (lmin, bufmin);
  16058. lmax = jmax (lmax, bufmax);
  16059. if (numChannels > 1)
  16060. {
  16061. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16062. rmin = jmin (rmin, bufmin);
  16063. rmax = jmax (rmax, bufmax);
  16064. }
  16065. }
  16066. if (numChannels <= 1)
  16067. {
  16068. rmax = lmax;
  16069. rmin = lmin;
  16070. }
  16071. lowestLeft = lmin;
  16072. highestLeft = lmax;
  16073. lowestRight = rmin;
  16074. highestRight = rmax;
  16075. }
  16076. else
  16077. {
  16078. int lmax = std::numeric_limits<int>::min();
  16079. int lmin = std::numeric_limits<int>::max();
  16080. int rmax = std::numeric_limits<int>::min();
  16081. int rmin = std::numeric_limits<int>::max();
  16082. while (numSamples > 0)
  16083. {
  16084. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16085. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16086. numSamples -= numToDo;
  16087. startSampleInFile += numToDo;
  16088. for (int j = numChannels; --j >= 0;)
  16089. {
  16090. int bufMax = std::numeric_limits<int>::min();
  16091. int bufMin = std::numeric_limits<int>::max();
  16092. const int* const b = tempBuffer[j];
  16093. for (int i = 0; i < numToDo; ++i)
  16094. {
  16095. const int samp = b[i];
  16096. if (samp < bufMin)
  16097. bufMin = samp;
  16098. if (samp > bufMax)
  16099. bufMax = samp;
  16100. }
  16101. if (j == 0)
  16102. {
  16103. lmax = jmax (lmax, bufMax);
  16104. lmin = jmin (lmin, bufMin);
  16105. }
  16106. else
  16107. {
  16108. rmax = jmax (rmax, bufMax);
  16109. rmin = jmin (rmin, bufMin);
  16110. }
  16111. }
  16112. }
  16113. if (numChannels <= 1)
  16114. {
  16115. rmax = lmax;
  16116. rmin = lmin;
  16117. }
  16118. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16119. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16120. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16121. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16122. }
  16123. }
  16124. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16125. int64 numSamplesToSearch,
  16126. const double magnitudeRangeMinimum,
  16127. const double magnitudeRangeMaximum,
  16128. const int minimumConsecutiveSamples)
  16129. {
  16130. if (numSamplesToSearch == 0)
  16131. return -1;
  16132. const int bufferSize = 4096;
  16133. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16134. int* tempBuffer[3];
  16135. tempBuffer[0] = (int*) tempSpace.getData();
  16136. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16137. tempBuffer[2] = 0;
  16138. int consecutive = 0;
  16139. int64 firstMatchPos = -1;
  16140. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16141. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16142. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16143. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16144. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16145. while (numSamplesToSearch != 0)
  16146. {
  16147. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16148. int64 bufferStart = startSample;
  16149. if (numSamplesToSearch < 0)
  16150. bufferStart -= numThisTime;
  16151. if (bufferStart >= (int) lengthInSamples)
  16152. break;
  16153. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16154. int num = numThisTime;
  16155. while (--num >= 0)
  16156. {
  16157. if (numSamplesToSearch < 0)
  16158. --startSample;
  16159. bool matches = false;
  16160. const int index = (int) (startSample - bufferStart);
  16161. if (usesFloatingPointData)
  16162. {
  16163. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16164. if (sample1 >= magnitudeRangeMinimum
  16165. && sample1 <= magnitudeRangeMaximum)
  16166. {
  16167. matches = true;
  16168. }
  16169. else if (numChannels > 1)
  16170. {
  16171. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16172. matches = (sample2 >= magnitudeRangeMinimum
  16173. && sample2 <= magnitudeRangeMaximum);
  16174. }
  16175. }
  16176. else
  16177. {
  16178. const int sample1 = abs (tempBuffer[0] [index]);
  16179. if (sample1 >= intMagnitudeRangeMinimum
  16180. && sample1 <= intMagnitudeRangeMaximum)
  16181. {
  16182. matches = true;
  16183. }
  16184. else if (numChannels > 1)
  16185. {
  16186. const int sample2 = abs (tempBuffer[1][index]);
  16187. matches = (sample2 >= intMagnitudeRangeMinimum
  16188. && sample2 <= intMagnitudeRangeMaximum);
  16189. }
  16190. }
  16191. if (matches)
  16192. {
  16193. if (firstMatchPos < 0)
  16194. firstMatchPos = startSample;
  16195. if (++consecutive >= minimumConsecutiveSamples)
  16196. {
  16197. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16198. return -1;
  16199. return firstMatchPos;
  16200. }
  16201. }
  16202. else
  16203. {
  16204. consecutive = 0;
  16205. firstMatchPos = -1;
  16206. }
  16207. if (numSamplesToSearch > 0)
  16208. ++startSample;
  16209. }
  16210. if (numSamplesToSearch > 0)
  16211. numSamplesToSearch -= numThisTime;
  16212. else
  16213. numSamplesToSearch += numThisTime;
  16214. }
  16215. return -1;
  16216. }
  16217. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16218. const String& formatName_,
  16219. const double rate,
  16220. const unsigned int numChannels_,
  16221. const unsigned int bitsPerSample_)
  16222. : sampleRate (rate),
  16223. numChannels (numChannels_),
  16224. bitsPerSample (bitsPerSample_),
  16225. usesFloatingPointData (false),
  16226. output (out),
  16227. formatName (formatName_)
  16228. {
  16229. }
  16230. AudioFormatWriter::~AudioFormatWriter()
  16231. {
  16232. delete output;
  16233. }
  16234. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16235. int64 startSample,
  16236. int64 numSamplesToRead)
  16237. {
  16238. const int bufferSize = 16384;
  16239. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16240. int* buffers [128];
  16241. zerostruct (buffers);
  16242. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16243. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16244. if (numSamplesToRead < 0)
  16245. numSamplesToRead = reader.lengthInSamples;
  16246. while (numSamplesToRead > 0)
  16247. {
  16248. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16249. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16250. return false;
  16251. if (reader.usesFloatingPointData != isFloatingPoint())
  16252. {
  16253. int** bufferChan = buffers;
  16254. while (*bufferChan != 0)
  16255. {
  16256. int* b = *bufferChan++;
  16257. if (isFloatingPoint())
  16258. {
  16259. // int -> float
  16260. const double factor = 1.0 / std::numeric_limits<int>::max();
  16261. for (int i = 0; i < numToDo; ++i)
  16262. ((float*) b)[i] = (float) (factor * b[i]);
  16263. }
  16264. else
  16265. {
  16266. // float -> int
  16267. for (int i = 0; i < numToDo; ++i)
  16268. {
  16269. const double samp = *(const float*) b;
  16270. if (samp <= -1.0)
  16271. *b++ = std::numeric_limits<int>::min();
  16272. else if (samp >= 1.0)
  16273. *b++ = std::numeric_limits<int>::max();
  16274. else
  16275. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16276. }
  16277. }
  16278. }
  16279. }
  16280. if (! write ((const int**) buffers, numToDo))
  16281. return false;
  16282. numSamplesToRead -= numToDo;
  16283. startSample += numToDo;
  16284. }
  16285. return true;
  16286. }
  16287. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16288. int numSamplesToRead,
  16289. const int samplesPerBlock)
  16290. {
  16291. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16292. int* buffers [128];
  16293. zerostruct (buffers);
  16294. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16295. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16296. while (numSamplesToRead > 0)
  16297. {
  16298. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16299. AudioSourceChannelInfo info;
  16300. info.buffer = &tempBuffer;
  16301. info.startSample = 0;
  16302. info.numSamples = numToDo;
  16303. info.clearActiveBufferRegion();
  16304. source.getNextAudioBlock (info);
  16305. if (! isFloatingPoint())
  16306. {
  16307. int** bufferChan = buffers;
  16308. while (*bufferChan != 0)
  16309. {
  16310. int* b = *bufferChan++;
  16311. // float -> int
  16312. for (int j = numToDo; --j >= 0;)
  16313. {
  16314. const double samp = *(const float*) b;
  16315. if (samp <= -1.0)
  16316. *b++ = std::numeric_limits<int>::min();
  16317. else if (samp >= 1.0)
  16318. *b++ = std::numeric_limits<int>::max();
  16319. else
  16320. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16321. }
  16322. }
  16323. }
  16324. if (! write ((const int**) buffers, numToDo))
  16325. return false;
  16326. numSamplesToRead -= numToDo;
  16327. }
  16328. return true;
  16329. }
  16330. AudioFormat::AudioFormat (const String& name,
  16331. const StringArray& extensions)
  16332. : formatName (name),
  16333. fileExtensions (extensions)
  16334. {
  16335. }
  16336. AudioFormat::~AudioFormat()
  16337. {
  16338. }
  16339. const String& AudioFormat::getFormatName() const
  16340. {
  16341. return formatName;
  16342. }
  16343. const StringArray& AudioFormat::getFileExtensions() const
  16344. {
  16345. return fileExtensions;
  16346. }
  16347. bool AudioFormat::canHandleFile (const File& f)
  16348. {
  16349. for (int i = 0; i < fileExtensions.size(); ++i)
  16350. if (f.hasFileExtension (fileExtensions[i]))
  16351. return true;
  16352. return false;
  16353. }
  16354. bool AudioFormat::isCompressed()
  16355. {
  16356. return false;
  16357. }
  16358. const StringArray AudioFormat::getQualityOptions()
  16359. {
  16360. return StringArray();
  16361. }
  16362. END_JUCE_NAMESPACE
  16363. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16364. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16365. BEGIN_JUCE_NAMESPACE
  16366. AudioFormatManager::AudioFormatManager()
  16367. : defaultFormatIndex (0)
  16368. {
  16369. }
  16370. AudioFormatManager::~AudioFormatManager()
  16371. {
  16372. clearFormats();
  16373. clearSingletonInstance();
  16374. }
  16375. juce_ImplementSingleton (AudioFormatManager);
  16376. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16377. const bool makeThisTheDefaultFormat)
  16378. {
  16379. jassert (newFormat != 0);
  16380. if (newFormat != 0)
  16381. {
  16382. #if JUCE_DEBUG
  16383. for (int i = getNumKnownFormats(); --i >= 0;)
  16384. {
  16385. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16386. {
  16387. jassertfalse; // trying to add the same format twice!
  16388. }
  16389. }
  16390. #endif
  16391. if (makeThisTheDefaultFormat)
  16392. defaultFormatIndex = getNumKnownFormats();
  16393. knownFormats.add (newFormat);
  16394. }
  16395. }
  16396. void AudioFormatManager::registerBasicFormats()
  16397. {
  16398. #if JUCE_MAC
  16399. registerFormat (new AiffAudioFormat(), true);
  16400. registerFormat (new WavAudioFormat(), false);
  16401. #else
  16402. registerFormat (new WavAudioFormat(), true);
  16403. registerFormat (new AiffAudioFormat(), false);
  16404. #endif
  16405. #if JUCE_USE_FLAC
  16406. registerFormat (new FlacAudioFormat(), false);
  16407. #endif
  16408. #if JUCE_USE_OGGVORBIS
  16409. registerFormat (new OggVorbisAudioFormat(), false);
  16410. #endif
  16411. }
  16412. void AudioFormatManager::clearFormats()
  16413. {
  16414. knownFormats.clear();
  16415. defaultFormatIndex = 0;
  16416. }
  16417. int AudioFormatManager::getNumKnownFormats() const
  16418. {
  16419. return knownFormats.size();
  16420. }
  16421. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16422. {
  16423. return knownFormats [index];
  16424. }
  16425. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16426. {
  16427. return getKnownFormat (defaultFormatIndex);
  16428. }
  16429. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16430. {
  16431. String e (fileExtension);
  16432. if (! e.startsWithChar ('.'))
  16433. e = "." + e;
  16434. for (int i = 0; i < getNumKnownFormats(); ++i)
  16435. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16436. return getKnownFormat(i);
  16437. return 0;
  16438. }
  16439. const String AudioFormatManager::getWildcardForAllFormats() const
  16440. {
  16441. StringArray allExtensions;
  16442. int i;
  16443. for (i = 0; i < getNumKnownFormats(); ++i)
  16444. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16445. allExtensions.trim();
  16446. allExtensions.removeEmptyStrings();
  16447. String s;
  16448. for (i = 0; i < allExtensions.size(); ++i)
  16449. {
  16450. s << '*';
  16451. if (! allExtensions[i].startsWithChar ('.'))
  16452. s << '.';
  16453. s << allExtensions[i];
  16454. if (i < allExtensions.size() - 1)
  16455. s << ';';
  16456. }
  16457. return s;
  16458. }
  16459. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16460. {
  16461. // you need to actually register some formats before the manager can
  16462. // use them to open a file!
  16463. jassert (getNumKnownFormats() > 0);
  16464. for (int i = 0; i < getNumKnownFormats(); ++i)
  16465. {
  16466. AudioFormat* const af = getKnownFormat(i);
  16467. if (af->canHandleFile (file))
  16468. {
  16469. InputStream* const in = file.createInputStream();
  16470. if (in != 0)
  16471. {
  16472. AudioFormatReader* const r = af->createReaderFor (in, true);
  16473. if (r != 0)
  16474. return r;
  16475. }
  16476. }
  16477. }
  16478. return 0;
  16479. }
  16480. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16481. {
  16482. // you need to actually register some formats before the manager can
  16483. // use them to open a file!
  16484. jassert (getNumKnownFormats() > 0);
  16485. ScopedPointer <InputStream> in (audioFileStream);
  16486. if (in != 0)
  16487. {
  16488. const int64 originalStreamPos = in->getPosition();
  16489. for (int i = 0; i < getNumKnownFormats(); ++i)
  16490. {
  16491. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16492. if (r != 0)
  16493. {
  16494. in.release();
  16495. return r;
  16496. }
  16497. in->setPosition (originalStreamPos);
  16498. // the stream that is passed-in must be capable of being repositioned so
  16499. // that all the formats can have a go at opening it.
  16500. jassert (in->getPosition() == originalStreamPos);
  16501. }
  16502. }
  16503. return 0;
  16504. }
  16505. END_JUCE_NAMESPACE
  16506. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16507. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16508. BEGIN_JUCE_NAMESPACE
  16509. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16510. const int64 startSample_,
  16511. const int64 length_,
  16512. const bool deleteSourceWhenDeleted_)
  16513. : AudioFormatReader (0, source_->getFormatName()),
  16514. source (source_),
  16515. startSample (startSample_),
  16516. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16517. {
  16518. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16519. sampleRate = source->sampleRate;
  16520. bitsPerSample = source->bitsPerSample;
  16521. lengthInSamples = length;
  16522. numChannels = source->numChannels;
  16523. usesFloatingPointData = source->usesFloatingPointData;
  16524. }
  16525. AudioSubsectionReader::~AudioSubsectionReader()
  16526. {
  16527. if (deleteSourceWhenDeleted)
  16528. delete source;
  16529. }
  16530. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16531. int64 startSampleInFile, int numSamples)
  16532. {
  16533. if (startSampleInFile + numSamples > length)
  16534. {
  16535. for (int i = numDestChannels; --i >= 0;)
  16536. if (destSamples[i] != 0)
  16537. zeromem (destSamples[i], sizeof (int) * numSamples);
  16538. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16539. if (numSamples <= 0)
  16540. return true;
  16541. }
  16542. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16543. startSampleInFile + startSample, numSamples);
  16544. }
  16545. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16546. int64 numSamples,
  16547. float& lowestLeft,
  16548. float& highestLeft,
  16549. float& lowestRight,
  16550. float& highestRight)
  16551. {
  16552. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16553. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16554. source->readMaxLevels (startSampleInFile + startSample,
  16555. numSamples,
  16556. lowestLeft,
  16557. highestLeft,
  16558. lowestRight,
  16559. highestRight);
  16560. }
  16561. END_JUCE_NAMESPACE
  16562. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16563. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16564. BEGIN_JUCE_NAMESPACE
  16565. const int timeBeforeDeletingReader = 2000;
  16566. struct AudioThumbnailDataFormat
  16567. {
  16568. char thumbnailMagic[4];
  16569. int samplesPerThumbSample;
  16570. int64 totalSamples; // source samples
  16571. int64 numFinishedSamples; // source samples
  16572. int numThumbnailSamples;
  16573. int numChannels;
  16574. int sampleRate;
  16575. char future[16];
  16576. char data[1];
  16577. void swapEndiannessIfNeeded() throw()
  16578. {
  16579. #if JUCE_BIG_ENDIAN
  16580. flip (samplesPerThumbSample);
  16581. flip (totalSamples);
  16582. flip (numFinishedSamples);
  16583. flip (numThumbnailSamples);
  16584. flip (numChannels);
  16585. flip (sampleRate);
  16586. #endif
  16587. }
  16588. private:
  16589. #if JUCE_BIG_ENDIAN
  16590. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16591. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16592. #endif
  16593. };
  16594. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16595. AudioFormatManager& formatManagerToUse_,
  16596. AudioThumbnailCache& cacheToUse)
  16597. : formatManagerToUse (formatManagerToUse_),
  16598. cache (cacheToUse),
  16599. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16600. {
  16601. clear();
  16602. }
  16603. AudioThumbnail::~AudioThumbnail()
  16604. {
  16605. cache.removeThumbnail (this);
  16606. const ScopedLock sl (readerLock);
  16607. reader = 0;
  16608. }
  16609. void AudioThumbnail::setSource (InputSource* const newSource)
  16610. {
  16611. cache.removeThumbnail (this);
  16612. timerCallback(); // stops the timer and deletes the reader
  16613. source = newSource;
  16614. clear();
  16615. if (newSource != 0
  16616. && ! (cache.loadThumb (*this, newSource->hashCode())
  16617. && isFullyLoaded()))
  16618. {
  16619. {
  16620. const ScopedLock sl (readerLock);
  16621. reader = createReader();
  16622. }
  16623. if (reader != 0)
  16624. {
  16625. initialiseFromAudioFile (*reader);
  16626. cache.addThumbnail (this);
  16627. }
  16628. }
  16629. sendChangeMessage (this);
  16630. }
  16631. bool AudioThumbnail::useTimeSlice()
  16632. {
  16633. const ScopedLock sl (readerLock);
  16634. if (isFullyLoaded())
  16635. {
  16636. if (reader != 0)
  16637. startTimer (timeBeforeDeletingReader);
  16638. cache.removeThumbnail (this);
  16639. return false;
  16640. }
  16641. if (reader == 0)
  16642. reader = createReader();
  16643. if (reader != 0)
  16644. {
  16645. readNextBlockFromAudioFile (*reader);
  16646. stopTimer();
  16647. sendChangeMessage (this);
  16648. const bool justFinished = isFullyLoaded();
  16649. if (justFinished)
  16650. cache.storeThumb (*this, source->hashCode());
  16651. return ! justFinished;
  16652. }
  16653. return false;
  16654. }
  16655. AudioFormatReader* AudioThumbnail::createReader() const
  16656. {
  16657. if (source != 0)
  16658. {
  16659. InputStream* const audioFileStream = source->createInputStream();
  16660. if (audioFileStream != 0)
  16661. return formatManagerToUse.createReaderFor (audioFileStream);
  16662. }
  16663. return 0;
  16664. }
  16665. void AudioThumbnail::timerCallback()
  16666. {
  16667. stopTimer();
  16668. const ScopedLock sl (readerLock);
  16669. reader = 0;
  16670. }
  16671. void AudioThumbnail::clear()
  16672. {
  16673. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16674. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16675. d->thumbnailMagic[0] = 'j';
  16676. d->thumbnailMagic[1] = 'a';
  16677. d->thumbnailMagic[2] = 't';
  16678. d->thumbnailMagic[3] = 'm';
  16679. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16680. d->totalSamples = 0;
  16681. d->numFinishedSamples = 0;
  16682. d->numThumbnailSamples = 0;
  16683. d->numChannels = 0;
  16684. d->sampleRate = 0;
  16685. numSamplesCached = 0;
  16686. cacheNeedsRefilling = true;
  16687. }
  16688. void AudioThumbnail::loadFrom (InputStream& input)
  16689. {
  16690. const ScopedLock sl (readerLock);
  16691. data.setSize (0);
  16692. input.readIntoMemoryBlock (data);
  16693. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16694. d->swapEndiannessIfNeeded();
  16695. if (! (d->thumbnailMagic[0] == 'j'
  16696. && d->thumbnailMagic[1] == 'a'
  16697. && d->thumbnailMagic[2] == 't'
  16698. && d->thumbnailMagic[3] == 'm'))
  16699. {
  16700. clear();
  16701. }
  16702. numSamplesCached = 0;
  16703. cacheNeedsRefilling = true;
  16704. }
  16705. void AudioThumbnail::saveTo (OutputStream& output) const
  16706. {
  16707. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16708. d->swapEndiannessIfNeeded();
  16709. output.write (data.getData(), (int) data.getSize());
  16710. d->swapEndiannessIfNeeded();
  16711. }
  16712. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16713. {
  16714. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16715. d->totalSamples = fileReader.lengthInSamples;
  16716. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16717. d->numFinishedSamples = 0;
  16718. d->sampleRate = roundToInt (fileReader.sampleRate);
  16719. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16720. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16721. d = (AudioThumbnailDataFormat*) data.getData();
  16722. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16723. return d->totalSamples > 0;
  16724. }
  16725. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16726. {
  16727. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16728. if (d->numFinishedSamples < d->totalSamples)
  16729. {
  16730. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16731. generateSection (fileReader,
  16732. d->numFinishedSamples,
  16733. numToDo);
  16734. d->numFinishedSamples += numToDo;
  16735. }
  16736. cacheNeedsRefilling = true;
  16737. return (d->numFinishedSamples < d->totalSamples);
  16738. }
  16739. int AudioThumbnail::getNumChannels() const throw()
  16740. {
  16741. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16742. jassert (d != 0);
  16743. return d->numChannels;
  16744. }
  16745. double AudioThumbnail::getTotalLength() const throw()
  16746. {
  16747. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16748. jassert (d != 0);
  16749. if (d->sampleRate > 0)
  16750. return d->totalSamples / (double)d->sampleRate;
  16751. else
  16752. return 0.0;
  16753. }
  16754. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16755. int64 startSample,
  16756. int numSamples)
  16757. {
  16758. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16759. jassert (d != 0);
  16760. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16761. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16762. char* l = getChannelData (0);
  16763. char* r = getChannelData (1);
  16764. for (int i = firstDataPos; i < lastDataPos; ++i)
  16765. {
  16766. const int sourceStart = i * d->samplesPerThumbSample;
  16767. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16768. float lowestLeft, highestLeft, lowestRight, highestRight;
  16769. fileReader.readMaxLevels (sourceStart,
  16770. sourceEnd - sourceStart,
  16771. lowestLeft,
  16772. highestLeft,
  16773. lowestRight,
  16774. highestRight);
  16775. int n = i * 2;
  16776. if (r != 0)
  16777. {
  16778. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16779. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16780. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16781. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16782. }
  16783. else
  16784. {
  16785. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16786. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16787. }
  16788. }
  16789. }
  16790. char* AudioThumbnail::getChannelData (int channel) const
  16791. {
  16792. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16793. jassert (d != 0);
  16794. if (channel >= 0 && channel < d->numChannels)
  16795. return d->data + (channel * 2 * d->numThumbnailSamples);
  16796. return 0;
  16797. }
  16798. bool AudioThumbnail::isFullyLoaded() const throw()
  16799. {
  16800. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16801. jassert (d != 0);
  16802. return d->numFinishedSamples >= d->totalSamples;
  16803. }
  16804. void AudioThumbnail::refillCache (const int numSamples,
  16805. double startTime,
  16806. const double timePerPixel)
  16807. {
  16808. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16809. jassert (d != 0);
  16810. if (numSamples <= 0
  16811. || timePerPixel <= 0.0
  16812. || d->sampleRate <= 0)
  16813. {
  16814. numSamplesCached = 0;
  16815. cacheNeedsRefilling = true;
  16816. return;
  16817. }
  16818. if (numSamples == numSamplesCached
  16819. && numChannelsCached == d->numChannels
  16820. && startTime == cachedStart
  16821. && timePerPixel == cachedTimePerPixel
  16822. && ! cacheNeedsRefilling)
  16823. {
  16824. return;
  16825. }
  16826. numSamplesCached = numSamples;
  16827. numChannelsCached = d->numChannels;
  16828. cachedStart = startTime;
  16829. cachedTimePerPixel = timePerPixel;
  16830. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16831. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16832. const ScopedLock sl (readerLock);
  16833. cacheNeedsRefilling = false;
  16834. if (needExtraDetail && reader == 0)
  16835. reader = createReader();
  16836. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16837. {
  16838. startTimer (timeBeforeDeletingReader);
  16839. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16840. int sample = roundToInt (startTime * d->sampleRate);
  16841. for (int i = numSamples; --i >= 0;)
  16842. {
  16843. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16844. if (sample >= 0)
  16845. {
  16846. if (sample >= reader->lengthInSamples)
  16847. break;
  16848. float lmin, lmax, rmin, rmax;
  16849. reader->readMaxLevels (sample,
  16850. jmax (1, nextSample - sample),
  16851. lmin, lmax, rmin, rmax);
  16852. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16853. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16854. if (numChannelsCached > 1)
  16855. {
  16856. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16857. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16858. }
  16859. cacheData += 2 * numChannelsCached;
  16860. }
  16861. startTime += timePerPixel;
  16862. sample = nextSample;
  16863. }
  16864. }
  16865. else
  16866. {
  16867. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16868. {
  16869. char* const channelData = getChannelData (channelNum);
  16870. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16871. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16872. startTime = cachedStart;
  16873. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16874. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16875. for (int i = numSamples; --i >= 0;)
  16876. {
  16877. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16878. if (sample >= 0 && channelData != 0)
  16879. {
  16880. char mx = -128;
  16881. char mn = 127;
  16882. while (sample <= nextSample)
  16883. {
  16884. if (sample >= numFinished)
  16885. break;
  16886. const int n = sample << 1;
  16887. const char sampMin = channelData [n];
  16888. const char sampMax = channelData [n + 1];
  16889. if (sampMin < mn)
  16890. mn = sampMin;
  16891. if (sampMax > mx)
  16892. mx = sampMax;
  16893. ++sample;
  16894. }
  16895. if (mn <= mx)
  16896. {
  16897. cacheData[0] = mn;
  16898. cacheData[1] = mx;
  16899. }
  16900. else
  16901. {
  16902. cacheData[0] = 1;
  16903. cacheData[1] = 0;
  16904. }
  16905. }
  16906. else
  16907. {
  16908. cacheData[0] = 1;
  16909. cacheData[1] = 0;
  16910. }
  16911. cacheData += numChannelsCached * 2;
  16912. startTime += timePerPixel;
  16913. sample = nextSample;
  16914. }
  16915. }
  16916. }
  16917. }
  16918. void AudioThumbnail::drawChannel (Graphics& g,
  16919. int x, int y, int w, int h,
  16920. double startTime,
  16921. double endTime,
  16922. int channelNum,
  16923. const float verticalZoomFactor)
  16924. {
  16925. refillCache (w, startTime, (endTime - startTime) / w);
  16926. if (numSamplesCached >= w
  16927. && channelNum >= 0
  16928. && channelNum < numChannelsCached)
  16929. {
  16930. const float topY = (float) y;
  16931. const float bottomY = topY + h;
  16932. const float midY = topY + h * 0.5f;
  16933. const float vscale = verticalZoomFactor * h / 256.0f;
  16934. const Rectangle<int> clip (g.getClipBounds());
  16935. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16936. w -= skipLeft;
  16937. x += skipLeft;
  16938. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16939. + (channelNum << 1)
  16940. + skipLeft * (numChannelsCached << 1);
  16941. while (--w >= 0)
  16942. {
  16943. const char mn = cacheData[0];
  16944. const char mx = cacheData[1];
  16945. cacheData += numChannelsCached << 1;
  16946. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16947. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16948. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16949. ++x;
  16950. if (x >= clip.getRight())
  16951. break;
  16952. }
  16953. }
  16954. }
  16955. END_JUCE_NAMESPACE
  16956. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16957. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16958. BEGIN_JUCE_NAMESPACE
  16959. struct ThumbnailCacheEntry
  16960. {
  16961. int64 hash;
  16962. uint32 lastUsed;
  16963. MemoryBlock data;
  16964. juce_UseDebuggingNewOperator
  16965. };
  16966. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16967. : TimeSliceThread ("thumb cache"),
  16968. maxNumThumbsToStore (maxNumThumbsToStore_)
  16969. {
  16970. startThread (2);
  16971. }
  16972. AudioThumbnailCache::~AudioThumbnailCache()
  16973. {
  16974. }
  16975. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16976. {
  16977. for (int i = thumbs.size(); --i >= 0;)
  16978. {
  16979. if (thumbs[i]->hash == hashCode)
  16980. {
  16981. MemoryInputStream in (thumbs[i]->data, false);
  16982. thumb.loadFrom (in);
  16983. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16984. return true;
  16985. }
  16986. }
  16987. return false;
  16988. }
  16989. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16990. const int64 hashCode)
  16991. {
  16992. MemoryOutputStream out;
  16993. thumb.saveTo (out);
  16994. ThumbnailCacheEntry* te = 0;
  16995. for (int i = thumbs.size(); --i >= 0;)
  16996. {
  16997. if (thumbs[i]->hash == hashCode)
  16998. {
  16999. te = thumbs[i];
  17000. break;
  17001. }
  17002. }
  17003. if (te == 0)
  17004. {
  17005. te = new ThumbnailCacheEntry();
  17006. te->hash = hashCode;
  17007. if (thumbs.size() < maxNumThumbsToStore)
  17008. {
  17009. thumbs.add (te);
  17010. }
  17011. else
  17012. {
  17013. int oldest = 0;
  17014. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17015. int i;
  17016. for (i = thumbs.size(); --i >= 0;)
  17017. if (thumbs[i]->lastUsed < oldestTime)
  17018. oldest = i;
  17019. thumbs.set (i, te);
  17020. }
  17021. }
  17022. te->lastUsed = Time::getMillisecondCounter();
  17023. te->data.setSize (0);
  17024. te->data.append (out.getData(), out.getDataSize());
  17025. }
  17026. void AudioThumbnailCache::clear()
  17027. {
  17028. thumbs.clear();
  17029. }
  17030. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17031. {
  17032. addTimeSliceClient (thumb);
  17033. }
  17034. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17035. {
  17036. removeTimeSliceClient (thumb);
  17037. }
  17038. END_JUCE_NAMESPACE
  17039. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17040. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17041. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  17042. #if ! JUCE_WINDOWS
  17043. #include <QuickTime/Movies.h>
  17044. #include <QuickTime/QTML.h>
  17045. #include <QuickTime/QuickTimeComponents.h>
  17046. #include <QuickTime/MediaHandlers.h>
  17047. #include <QuickTime/ImageCodec.h>
  17048. #else
  17049. #if JUCE_MSVC
  17050. #pragma warning (push)
  17051. #pragma warning (disable : 4100)
  17052. #endif
  17053. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17054. add its header directory to your include path.
  17055. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17056. flag in juce_Config.h
  17057. */
  17058. #include <Movies.h>
  17059. #include <QTML.h>
  17060. #include <QuickTimeComponents.h>
  17061. #include <MediaHandlers.h>
  17062. #include <ImageCodec.h>
  17063. #if JUCE_MSVC
  17064. #pragma warning (pop)
  17065. #endif
  17066. #endif
  17067. BEGIN_JUCE_NAMESPACE
  17068. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17069. static const char* const quickTimeFormatName = "QuickTime file";
  17070. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17071. class QTAudioReader : public AudioFormatReader
  17072. {
  17073. public:
  17074. QTAudioReader (InputStream* const input_, const int trackNum_)
  17075. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17076. ok (false),
  17077. movie (0),
  17078. trackNum (trackNum_),
  17079. lastSampleRead (0),
  17080. lastThreadId (0),
  17081. extractor (0),
  17082. dataHandle (0)
  17083. {
  17084. bufferList.calloc (256, 1);
  17085. #if JUCE_WINDOWS
  17086. if (InitializeQTML (0) != noErr)
  17087. return;
  17088. #endif
  17089. if (EnterMovies() != noErr)
  17090. return;
  17091. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17092. if (! opened)
  17093. return;
  17094. {
  17095. const int numTracks = GetMovieTrackCount (movie);
  17096. int trackCount = 0;
  17097. for (int i = 1; i <= numTracks; ++i)
  17098. {
  17099. track = GetMovieIndTrack (movie, i);
  17100. media = GetTrackMedia (track);
  17101. OSType mediaType;
  17102. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17103. if (mediaType == SoundMediaType
  17104. && trackCount++ == trackNum_)
  17105. {
  17106. ok = true;
  17107. break;
  17108. }
  17109. }
  17110. }
  17111. if (! ok)
  17112. return;
  17113. ok = false;
  17114. lengthInSamples = GetMediaDecodeDuration (media);
  17115. usesFloatingPointData = false;
  17116. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17117. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17118. / GetMediaTimeScale (media);
  17119. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17120. unsigned long output_layout_size;
  17121. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17122. kQTPropertyClass_MovieAudioExtraction_Audio,
  17123. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17124. 0, &output_layout_size, 0);
  17125. if (err != noErr)
  17126. return;
  17127. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17128. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17129. err = MovieAudioExtractionGetProperty (extractor,
  17130. kQTPropertyClass_MovieAudioExtraction_Audio,
  17131. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17132. output_layout_size, qt_audio_channel_layout, 0);
  17133. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17134. err = MovieAudioExtractionSetProperty (extractor,
  17135. kQTPropertyClass_MovieAudioExtraction_Audio,
  17136. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17137. output_layout_size,
  17138. qt_audio_channel_layout);
  17139. err = MovieAudioExtractionGetProperty (extractor,
  17140. kQTPropertyClass_MovieAudioExtraction_Audio,
  17141. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17142. sizeof (inputStreamDesc),
  17143. &inputStreamDesc, 0);
  17144. if (err != noErr)
  17145. return;
  17146. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17147. | kAudioFormatFlagIsPacked
  17148. | kAudioFormatFlagsNativeEndian;
  17149. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17150. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17151. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17152. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17153. err = MovieAudioExtractionSetProperty (extractor,
  17154. kQTPropertyClass_MovieAudioExtraction_Audio,
  17155. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17156. sizeof (inputStreamDesc),
  17157. &inputStreamDesc);
  17158. if (err != noErr)
  17159. return;
  17160. Boolean allChannelsDiscrete = false;
  17161. err = MovieAudioExtractionSetProperty (extractor,
  17162. kQTPropertyClass_MovieAudioExtraction_Movie,
  17163. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17164. sizeof (allChannelsDiscrete),
  17165. &allChannelsDiscrete);
  17166. if (err != noErr)
  17167. return;
  17168. bufferList->mNumberBuffers = 1;
  17169. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17170. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17171. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17172. bufferList->mBuffers[0].mData = dataBuffer;
  17173. sampleRate = inputStreamDesc.mSampleRate;
  17174. bitsPerSample = 16;
  17175. numChannels = inputStreamDesc.mChannelsPerFrame;
  17176. detachThread();
  17177. ok = true;
  17178. }
  17179. ~QTAudioReader()
  17180. {
  17181. if (dataHandle != 0)
  17182. DisposeHandle (dataHandle);
  17183. if (extractor != 0)
  17184. {
  17185. MovieAudioExtractionEnd (extractor);
  17186. extractor = 0;
  17187. }
  17188. checkThreadIsAttached();
  17189. DisposeMovie (movie);
  17190. #if JUCE_MAC
  17191. ExitMoviesOnThread ();
  17192. #endif
  17193. }
  17194. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17195. int64 startSampleInFile, int numSamples)
  17196. {
  17197. checkThreadIsAttached();
  17198. while (numSamples > 0)
  17199. {
  17200. if (! loadFrame ((int) startSampleInFile))
  17201. return false;
  17202. const int numToDo = jmin (numSamples, samplesPerFrame);
  17203. for (int j = numDestChannels; --j >= 0;)
  17204. {
  17205. if (destSamples[j] != 0)
  17206. {
  17207. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17208. for (int i = 0; i < numToDo; ++i)
  17209. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17210. }
  17211. }
  17212. startOffsetInDestBuffer += numToDo;
  17213. startSampleInFile += numToDo;
  17214. numSamples -= numToDo;
  17215. }
  17216. detachThread();
  17217. return true;
  17218. }
  17219. bool loadFrame (const int sampleNum)
  17220. {
  17221. if (lastSampleRead != sampleNum)
  17222. {
  17223. TimeRecord time;
  17224. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17225. time.base = 0;
  17226. time.value.hi = 0;
  17227. time.value.lo = (UInt32) sampleNum;
  17228. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17229. kQTPropertyClass_MovieAudioExtraction_Movie,
  17230. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17231. sizeof (time), &time);
  17232. if (err != noErr)
  17233. return false;
  17234. }
  17235. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17236. UInt32 outFlags = 0;
  17237. UInt32 actualNumSamples = samplesPerFrame;
  17238. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17239. bufferList, &outFlags);
  17240. lastSampleRead = sampleNum + samplesPerFrame;
  17241. return err == noErr;
  17242. }
  17243. juce_UseDebuggingNewOperator
  17244. bool ok;
  17245. private:
  17246. Movie movie;
  17247. Media media;
  17248. Track track;
  17249. const int trackNum;
  17250. double trackUnitsPerFrame;
  17251. int samplesPerFrame;
  17252. int lastSampleRead;
  17253. Thread::ThreadID lastThreadId;
  17254. MovieAudioExtractionRef extractor;
  17255. AudioStreamBasicDescription inputStreamDesc;
  17256. HeapBlock <AudioBufferList> bufferList;
  17257. HeapBlock <char> dataBuffer;
  17258. Handle dataHandle;
  17259. void checkThreadIsAttached()
  17260. {
  17261. #if JUCE_MAC
  17262. if (Thread::getCurrentThreadId() != lastThreadId)
  17263. EnterMoviesOnThread (0);
  17264. AttachMovieToCurrentThread (movie);
  17265. #endif
  17266. }
  17267. void detachThread()
  17268. {
  17269. #if JUCE_MAC
  17270. DetachMovieFromCurrentThread (movie);
  17271. #endif
  17272. }
  17273. QTAudioReader (const QTAudioReader&);
  17274. QTAudioReader& operator= (const QTAudioReader&);
  17275. };
  17276. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17277. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17278. {
  17279. }
  17280. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17281. {
  17282. }
  17283. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17284. {
  17285. return Array<int>();
  17286. }
  17287. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17288. {
  17289. return Array<int>();
  17290. }
  17291. bool QuickTimeAudioFormat::canDoStereo()
  17292. {
  17293. return true;
  17294. }
  17295. bool QuickTimeAudioFormat::canDoMono()
  17296. {
  17297. return true;
  17298. }
  17299. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17300. const bool deleteStreamIfOpeningFails)
  17301. {
  17302. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17303. if (r->ok)
  17304. return r.release();
  17305. if (! deleteStreamIfOpeningFails)
  17306. r->input = 0;
  17307. return 0;
  17308. }
  17309. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17310. double /*sampleRateToUse*/,
  17311. unsigned int /*numberOfChannels*/,
  17312. int /*bitsPerSample*/,
  17313. const StringPairArray& /*metadataValues*/,
  17314. int /*qualityOptionIndex*/)
  17315. {
  17316. jassertfalse; // not yet implemented!
  17317. return 0;
  17318. }
  17319. END_JUCE_NAMESPACE
  17320. #endif
  17321. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17322. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17323. BEGIN_JUCE_NAMESPACE
  17324. static const char* const wavFormatName = "WAV file";
  17325. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17326. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17327. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17328. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17329. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17330. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17331. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17332. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17333. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17334. const String& originator,
  17335. const String& originatorRef,
  17336. const Time& date,
  17337. const int64 timeReferenceSamples,
  17338. const String& codingHistory)
  17339. {
  17340. StringPairArray m;
  17341. m.set (bwavDescription, description);
  17342. m.set (bwavOriginator, originator);
  17343. m.set (bwavOriginatorRef, originatorRef);
  17344. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17345. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17346. m.set (bwavTimeReference, String (timeReferenceSamples));
  17347. m.set (bwavCodingHistory, codingHistory);
  17348. return m;
  17349. }
  17350. #if JUCE_MSVC
  17351. #pragma pack (push, 1)
  17352. #define PACKED
  17353. #elif JUCE_GCC
  17354. #define PACKED __attribute__((packed))
  17355. #else
  17356. #define PACKED
  17357. #endif
  17358. struct BWAVChunk
  17359. {
  17360. char description [256];
  17361. char originator [32];
  17362. char originatorRef [32];
  17363. char originationDate [10];
  17364. char originationTime [8];
  17365. uint32 timeRefLow;
  17366. uint32 timeRefHigh;
  17367. uint16 version;
  17368. uint8 umid[64];
  17369. uint8 reserved[190];
  17370. char codingHistory[1];
  17371. void copyTo (StringPairArray& values) const
  17372. {
  17373. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17374. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17375. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17376. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17377. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17378. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17379. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17380. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17381. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17382. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17383. }
  17384. static MemoryBlock createFrom (const StringPairArray& values)
  17385. {
  17386. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17387. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17388. data.fillWith (0);
  17389. BWAVChunk* b = (BWAVChunk*) data.getData();
  17390. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17391. // as they get called in the right order..
  17392. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17393. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17394. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17395. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17396. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17397. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17398. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17399. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17400. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17401. if (b->description[0] != 0
  17402. || b->originator[0] != 0
  17403. || b->originationDate[0] != 0
  17404. || b->originationTime[0] != 0
  17405. || b->codingHistory[0] != 0
  17406. || time != 0)
  17407. {
  17408. return data;
  17409. }
  17410. return MemoryBlock();
  17411. }
  17412. } PACKED;
  17413. struct SMPLChunk
  17414. {
  17415. struct SampleLoop
  17416. {
  17417. uint32 identifier;
  17418. uint32 type;
  17419. uint32 start;
  17420. uint32 end;
  17421. uint32 fraction;
  17422. uint32 playCount;
  17423. } PACKED;
  17424. uint32 manufacturer;
  17425. uint32 product;
  17426. uint32 samplePeriod;
  17427. uint32 midiUnityNote;
  17428. uint32 midiPitchFraction;
  17429. uint32 smpteFormat;
  17430. uint32 smpteOffset;
  17431. uint32 numSampleLoops;
  17432. uint32 samplerData;
  17433. SampleLoop loops[1];
  17434. void copyTo (StringPairArray& values, const int totalSize) const
  17435. {
  17436. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17437. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17438. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17439. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17440. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17441. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17442. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17443. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17444. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17445. for (uint32 i = 0; i < numSampleLoops; ++i)
  17446. {
  17447. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17448. break;
  17449. const String prefix ("Loop" + String(i));
  17450. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17451. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17452. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17453. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17454. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17455. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17456. }
  17457. }
  17458. static MemoryBlock createFrom (const StringPairArray& values)
  17459. {
  17460. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17461. if (numLoops <= 0)
  17462. return MemoryBlock();
  17463. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17464. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17465. data.fillWith (0);
  17466. SMPLChunk* s = (SMPLChunk*) data.getData();
  17467. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17468. // as they get called in the right order..
  17469. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17470. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17471. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17472. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17473. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17474. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17475. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17476. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17477. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17478. for (int i = 0; i < numLoops; ++i)
  17479. {
  17480. const String prefix ("Loop" + String(i));
  17481. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17482. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17483. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17484. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17485. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17486. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17487. }
  17488. return data;
  17489. }
  17490. } PACKED;
  17491. struct ExtensibleWavSubFormat
  17492. {
  17493. uint32 data1;
  17494. uint16 data2;
  17495. uint16 data3;
  17496. uint8 data4[8];
  17497. } PACKED;
  17498. #if JUCE_MSVC
  17499. #pragma pack (pop)
  17500. #endif
  17501. #undef PACKED
  17502. class WavAudioFormatReader : public AudioFormatReader
  17503. {
  17504. int bytesPerFrame;
  17505. int64 dataChunkStart, dataLength;
  17506. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17507. WavAudioFormatReader (const WavAudioFormatReader&);
  17508. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17509. public:
  17510. int64 bwavChunkStart, bwavSize;
  17511. WavAudioFormatReader (InputStream* const in)
  17512. : AudioFormatReader (in, TRANS (wavFormatName)),
  17513. dataLength (0),
  17514. bwavChunkStart (0),
  17515. bwavSize (0)
  17516. {
  17517. if (input->readInt() == chunkName ("RIFF"))
  17518. {
  17519. const uint32 len = (uint32) input->readInt();
  17520. const int64 end = input->getPosition() + len;
  17521. bool hasGotType = false;
  17522. bool hasGotData = false;
  17523. if (input->readInt() == chunkName ("WAVE"))
  17524. {
  17525. while (input->getPosition() < end
  17526. && ! input->isExhausted())
  17527. {
  17528. const int chunkType = input->readInt();
  17529. uint32 length = (uint32) input->readInt();
  17530. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17531. if (chunkType == chunkName ("fmt "))
  17532. {
  17533. // read the format chunk
  17534. const unsigned short format = input->readShort();
  17535. const short numChans = input->readShort();
  17536. sampleRate = input->readInt();
  17537. const int bytesPerSec = input->readInt();
  17538. numChannels = numChans;
  17539. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17540. bitsPerSample = 8 * bytesPerFrame / numChans;
  17541. if (format == 3)
  17542. {
  17543. usesFloatingPointData = true;
  17544. }
  17545. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17546. {
  17547. if (length < 40) // too short
  17548. {
  17549. bytesPerFrame = 0;
  17550. }
  17551. else
  17552. {
  17553. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17554. ExtensibleWavSubFormat subFormat;
  17555. subFormat.data1 = input->readInt();
  17556. subFormat.data2 = input->readShort();
  17557. subFormat.data3 = input->readShort();
  17558. input->read (subFormat.data4, sizeof (subFormat.data4));
  17559. const ExtensibleWavSubFormat pcmFormat
  17560. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17561. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17562. {
  17563. const ExtensibleWavSubFormat ambisonicFormat
  17564. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17565. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17566. bytesPerFrame = 0;
  17567. }
  17568. }
  17569. }
  17570. else if (format != 1)
  17571. {
  17572. bytesPerFrame = 0;
  17573. }
  17574. hasGotType = true;
  17575. }
  17576. else if (chunkType == chunkName ("data"))
  17577. {
  17578. // get the data chunk's position
  17579. dataLength = length;
  17580. dataChunkStart = input->getPosition();
  17581. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17582. hasGotData = true;
  17583. }
  17584. else if (chunkType == chunkName ("bext"))
  17585. {
  17586. bwavChunkStart = input->getPosition();
  17587. bwavSize = length;
  17588. // Broadcast-wav extension chunk..
  17589. HeapBlock <BWAVChunk> bwav;
  17590. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17591. input->read (bwav, length);
  17592. bwav->copyTo (metadataValues);
  17593. }
  17594. else if (chunkType == chunkName ("smpl"))
  17595. {
  17596. HeapBlock <SMPLChunk> smpl;
  17597. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17598. input->read (smpl, length);
  17599. smpl->copyTo (metadataValues, length);
  17600. }
  17601. else if (chunkEnd <= input->getPosition())
  17602. {
  17603. break;
  17604. }
  17605. input->setPosition (chunkEnd);
  17606. }
  17607. }
  17608. }
  17609. }
  17610. ~WavAudioFormatReader()
  17611. {
  17612. }
  17613. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17614. int64 startSampleInFile, int numSamples)
  17615. {
  17616. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17617. if (samplesAvailable < numSamples)
  17618. {
  17619. for (int i = numDestChannels; --i >= 0;)
  17620. if (destSamples[i] != 0)
  17621. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17622. numSamples = (int) samplesAvailable;
  17623. }
  17624. if (numSamples <= 0)
  17625. return true;
  17626. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17627. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17628. char tempBuffer [tempBufSize];
  17629. while (numSamples > 0)
  17630. {
  17631. int* left = destSamples[0];
  17632. if (left != 0)
  17633. left += startOffsetInDestBuffer;
  17634. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17635. if (right != 0)
  17636. right += startOffsetInDestBuffer;
  17637. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17638. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17639. if (bytesRead < numThisTime * bytesPerFrame)
  17640. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17641. if (bitsPerSample == 16)
  17642. {
  17643. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17644. if (numChannels > 1)
  17645. {
  17646. if (left == 0)
  17647. {
  17648. for (int i = numThisTime; --i >= 0;)
  17649. {
  17650. ++src;
  17651. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17652. }
  17653. }
  17654. else if (right == 0)
  17655. {
  17656. for (int i = numThisTime; --i >= 0;)
  17657. {
  17658. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17659. ++src;
  17660. }
  17661. }
  17662. else
  17663. {
  17664. for (int i = numThisTime; --i >= 0;)
  17665. {
  17666. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17667. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17668. }
  17669. }
  17670. }
  17671. else
  17672. {
  17673. for (int i = numThisTime; --i >= 0;)
  17674. {
  17675. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17676. }
  17677. }
  17678. }
  17679. else if (bitsPerSample == 24)
  17680. {
  17681. const char* src = tempBuffer;
  17682. if (numChannels > 1)
  17683. {
  17684. if (left == 0)
  17685. {
  17686. for (int i = numThisTime; --i >= 0;)
  17687. {
  17688. src += 3;
  17689. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17690. src += 3;
  17691. }
  17692. }
  17693. else if (right == 0)
  17694. {
  17695. for (int i = numThisTime; --i >= 0;)
  17696. {
  17697. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17698. src += 6;
  17699. }
  17700. }
  17701. else
  17702. {
  17703. for (int i = 0; i < numThisTime; ++i)
  17704. {
  17705. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17706. src += 3;
  17707. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17708. src += 3;
  17709. }
  17710. }
  17711. }
  17712. else
  17713. {
  17714. for (int i = 0; i < numThisTime; ++i)
  17715. {
  17716. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17717. src += 3;
  17718. }
  17719. }
  17720. }
  17721. else if (bitsPerSample == 32)
  17722. {
  17723. const unsigned int* src = (const unsigned int*) tempBuffer;
  17724. unsigned int* l = (unsigned int*) left;
  17725. unsigned int* r = (unsigned int*) right;
  17726. if (numChannels > 1)
  17727. {
  17728. if (l == 0)
  17729. {
  17730. for (int i = numThisTime; --i >= 0;)
  17731. {
  17732. ++src;
  17733. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17734. }
  17735. }
  17736. else if (r == 0)
  17737. {
  17738. for (int i = numThisTime; --i >= 0;)
  17739. {
  17740. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17741. ++src;
  17742. }
  17743. }
  17744. else
  17745. {
  17746. for (int i = numThisTime; --i >= 0;)
  17747. {
  17748. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17749. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17750. }
  17751. }
  17752. }
  17753. else
  17754. {
  17755. for (int i = numThisTime; --i >= 0;)
  17756. {
  17757. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17758. }
  17759. }
  17760. left = (int*)l;
  17761. right = (int*)r;
  17762. }
  17763. else if (bitsPerSample == 8)
  17764. {
  17765. const unsigned char* src = (const unsigned char*) tempBuffer;
  17766. if (numChannels > 1)
  17767. {
  17768. if (left == 0)
  17769. {
  17770. for (int i = numThisTime; --i >= 0;)
  17771. {
  17772. ++src;
  17773. *right++ = ((int) *src++ - 128) << 24;
  17774. }
  17775. }
  17776. else if (right == 0)
  17777. {
  17778. for (int i = numThisTime; --i >= 0;)
  17779. {
  17780. *left++ = ((int) *src++ - 128) << 24;
  17781. ++src;
  17782. }
  17783. }
  17784. else
  17785. {
  17786. for (int i = numThisTime; --i >= 0;)
  17787. {
  17788. *left++ = ((int) *src++ - 128) << 24;
  17789. *right++ = ((int) *src++ - 128) << 24;
  17790. }
  17791. }
  17792. }
  17793. else
  17794. {
  17795. for (int i = numThisTime; --i >= 0;)
  17796. {
  17797. *left++ = ((int)*src++ - 128) << 24;
  17798. }
  17799. }
  17800. }
  17801. startOffsetInDestBuffer += numThisTime;
  17802. numSamples -= numThisTime;
  17803. }
  17804. if (numSamples > 0)
  17805. {
  17806. for (int i = numDestChannels; --i >= 0;)
  17807. if (destSamples[i] != 0)
  17808. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17809. sizeof (int) * numSamples);
  17810. }
  17811. return true;
  17812. }
  17813. juce_UseDebuggingNewOperator
  17814. };
  17815. class WavAudioFormatWriter : public AudioFormatWriter
  17816. {
  17817. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17818. uint32 lengthInSamples, bytesWritten;
  17819. int64 headerPosition;
  17820. bool writeFailed;
  17821. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17822. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17823. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17824. void writeHeader()
  17825. {
  17826. const bool seekedOk = output->setPosition (headerPosition);
  17827. (void) seekedOk;
  17828. // if this fails, you've given it an output stream that can't seek! It needs
  17829. // to be able to seek back to write the header
  17830. jassert (seekedOk);
  17831. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17832. output->writeInt (chunkName ("RIFF"));
  17833. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17834. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17835. output->writeInt (chunkName ("WAVE"));
  17836. output->writeInt (chunkName ("fmt "));
  17837. output->writeInt (16);
  17838. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17839. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17840. output->writeShort ((short) numChannels);
  17841. output->writeInt ((int) sampleRate);
  17842. output->writeInt (bytesPerFrame * (int) sampleRate);
  17843. output->writeShort ((short) bytesPerFrame);
  17844. output->writeShort ((short) bitsPerSample);
  17845. if (bwavChunk.getSize() > 0)
  17846. {
  17847. output->writeInt (chunkName ("bext"));
  17848. output->writeInt ((int) bwavChunk.getSize());
  17849. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17850. }
  17851. if (smplChunk.getSize() > 0)
  17852. {
  17853. output->writeInt (chunkName ("smpl"));
  17854. output->writeInt ((int) smplChunk.getSize());
  17855. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17856. }
  17857. output->writeInt (chunkName ("data"));
  17858. output->writeInt (lengthInSamples * bytesPerFrame);
  17859. usesFloatingPointData = (bitsPerSample == 32);
  17860. }
  17861. public:
  17862. WavAudioFormatWriter (OutputStream* const out,
  17863. const double sampleRate_,
  17864. const unsigned int numChannels_,
  17865. const int bits,
  17866. const StringPairArray& metadataValues)
  17867. : AudioFormatWriter (out,
  17868. TRANS (wavFormatName),
  17869. sampleRate_,
  17870. numChannels_,
  17871. bits),
  17872. lengthInSamples (0),
  17873. bytesWritten (0),
  17874. writeFailed (false)
  17875. {
  17876. if (metadataValues.size() > 0)
  17877. {
  17878. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17879. smplChunk = SMPLChunk::createFrom (metadataValues);
  17880. }
  17881. headerPosition = out->getPosition();
  17882. writeHeader();
  17883. }
  17884. ~WavAudioFormatWriter()
  17885. {
  17886. writeHeader();
  17887. }
  17888. bool write (const int** data, int numSamples)
  17889. {
  17890. if (writeFailed)
  17891. return false;
  17892. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17893. tempBlock.ensureSize (bytes, false);
  17894. char* buffer = static_cast <char*> (tempBlock.getData());
  17895. const int* left = data[0];
  17896. const int* right = data[1];
  17897. if (right == 0)
  17898. right = left;
  17899. if (bitsPerSample == 16)
  17900. {
  17901. short* b = (short*) buffer;
  17902. if (numChannels > 1)
  17903. {
  17904. for (int i = numSamples; --i >= 0;)
  17905. {
  17906. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17907. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17908. }
  17909. }
  17910. else
  17911. {
  17912. for (int i = numSamples; --i >= 0;)
  17913. {
  17914. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17915. }
  17916. }
  17917. }
  17918. else if (bitsPerSample == 24)
  17919. {
  17920. char* b = buffer;
  17921. if (numChannels > 1)
  17922. {
  17923. for (int i = numSamples; --i >= 0;)
  17924. {
  17925. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17926. b += 3;
  17927. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17928. b += 3;
  17929. }
  17930. }
  17931. else
  17932. {
  17933. for (int i = numSamples; --i >= 0;)
  17934. {
  17935. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17936. b += 3;
  17937. }
  17938. }
  17939. }
  17940. else if (bitsPerSample == 32)
  17941. {
  17942. unsigned int* b = (unsigned int*) buffer;
  17943. if (numChannels > 1)
  17944. {
  17945. for (int i = numSamples; --i >= 0;)
  17946. {
  17947. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17948. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17949. }
  17950. }
  17951. else
  17952. {
  17953. for (int i = numSamples; --i >= 0;)
  17954. {
  17955. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17956. }
  17957. }
  17958. }
  17959. else if (bitsPerSample == 8)
  17960. {
  17961. unsigned char* b = (unsigned char*) buffer;
  17962. if (numChannels > 1)
  17963. {
  17964. for (int i = numSamples; --i >= 0;)
  17965. {
  17966. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17967. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17968. }
  17969. }
  17970. else
  17971. {
  17972. for (int i = numSamples; --i >= 0;)
  17973. {
  17974. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17975. }
  17976. }
  17977. }
  17978. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17979. || ! output->write (buffer, bytes))
  17980. {
  17981. // failed to write to disk, so let's try writing the header.
  17982. // If it's just run out of disk space, then if it does manage
  17983. // to write the header, we'll still have a useable file..
  17984. writeHeader();
  17985. writeFailed = true;
  17986. return false;
  17987. }
  17988. else
  17989. {
  17990. bytesWritten += bytes;
  17991. lengthInSamples += numSamples;
  17992. return true;
  17993. }
  17994. }
  17995. juce_UseDebuggingNewOperator
  17996. };
  17997. WavAudioFormat::WavAudioFormat()
  17998. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  17999. {
  18000. }
  18001. WavAudioFormat::~WavAudioFormat()
  18002. {
  18003. }
  18004. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18005. {
  18006. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18007. return Array <int> (rates);
  18008. }
  18009. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18010. {
  18011. const int depths[] = { 8, 16, 24, 32, 0 };
  18012. return Array <int> (depths);
  18013. }
  18014. bool WavAudioFormat::canDoStereo()
  18015. {
  18016. return true;
  18017. }
  18018. bool WavAudioFormat::canDoMono()
  18019. {
  18020. return true;
  18021. }
  18022. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18023. const bool deleteStreamIfOpeningFails)
  18024. {
  18025. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18026. if (r->sampleRate != 0)
  18027. return r.release();
  18028. if (! deleteStreamIfOpeningFails)
  18029. r->input = 0;
  18030. return 0;
  18031. }
  18032. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18033. double sampleRate,
  18034. unsigned int numChannels,
  18035. int bitsPerSample,
  18036. const StringPairArray& metadataValues,
  18037. int /*qualityOptionIndex*/)
  18038. {
  18039. if (getPossibleBitDepths().contains (bitsPerSample))
  18040. {
  18041. return new WavAudioFormatWriter (out,
  18042. sampleRate,
  18043. numChannels,
  18044. bitsPerSample,
  18045. metadataValues);
  18046. }
  18047. return 0;
  18048. }
  18049. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18050. {
  18051. TemporaryFile tempFile (file);
  18052. WavAudioFormat wav;
  18053. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18054. if (reader != 0)
  18055. {
  18056. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18057. if (outStream != 0)
  18058. {
  18059. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18060. reader->numChannels, reader->bitsPerSample,
  18061. metadata, 0));
  18062. if (writer != 0)
  18063. {
  18064. outStream.release();
  18065. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18066. writer = 0;
  18067. reader = 0;
  18068. return ok && tempFile.overwriteTargetFileWithTemporary();
  18069. }
  18070. }
  18071. }
  18072. return false;
  18073. }
  18074. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18075. {
  18076. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18077. if (reader != 0)
  18078. {
  18079. const int64 bwavPos = reader->bwavChunkStart;
  18080. const int64 bwavSize = reader->bwavSize;
  18081. reader = 0;
  18082. if (bwavSize > 0)
  18083. {
  18084. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18085. if (chunk.getSize() <= (size_t) bwavSize)
  18086. {
  18087. // the new one will fit in the space available, so write it directly..
  18088. const int64 oldSize = wavFile.getSize();
  18089. {
  18090. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18091. out->setPosition (bwavPos);
  18092. out->write (chunk.getData(), (int) chunk.getSize());
  18093. out->setPosition (oldSize);
  18094. }
  18095. jassert (wavFile.getSize() == oldSize);
  18096. return true;
  18097. }
  18098. }
  18099. }
  18100. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18101. }
  18102. END_JUCE_NAMESPACE
  18103. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18104. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18105. BEGIN_JUCE_NAMESPACE
  18106. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18107. const bool deleteReaderWhenThisIsDeleted)
  18108. : reader (reader_),
  18109. deleteReader (deleteReaderWhenThisIsDeleted),
  18110. nextPlayPos (0),
  18111. looping (false)
  18112. {
  18113. jassert (reader != 0);
  18114. }
  18115. AudioFormatReaderSource::~AudioFormatReaderSource()
  18116. {
  18117. releaseResources();
  18118. if (deleteReader)
  18119. delete reader;
  18120. }
  18121. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18122. {
  18123. nextPlayPos = newPosition;
  18124. }
  18125. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18126. {
  18127. looping = shouldLoop;
  18128. }
  18129. int AudioFormatReaderSource::getNextReadPosition() const
  18130. {
  18131. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18132. : nextPlayPos;
  18133. }
  18134. int AudioFormatReaderSource::getTotalLength() const
  18135. {
  18136. return (int) reader->lengthInSamples;
  18137. }
  18138. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18139. double /*sampleRate*/)
  18140. {
  18141. }
  18142. void AudioFormatReaderSource::releaseResources()
  18143. {
  18144. }
  18145. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18146. {
  18147. if (info.numSamples > 0)
  18148. {
  18149. const int start = nextPlayPos;
  18150. if (looping)
  18151. {
  18152. const int newStart = start % (int) reader->lengthInSamples;
  18153. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18154. if (newEnd > newStart)
  18155. {
  18156. info.buffer->readFromAudioReader (reader,
  18157. info.startSample,
  18158. newEnd - newStart,
  18159. newStart,
  18160. true, true);
  18161. }
  18162. else
  18163. {
  18164. const int endSamps = (int) reader->lengthInSamples - newStart;
  18165. info.buffer->readFromAudioReader (reader,
  18166. info.startSample,
  18167. endSamps,
  18168. newStart,
  18169. true, true);
  18170. info.buffer->readFromAudioReader (reader,
  18171. info.startSample + endSamps,
  18172. newEnd,
  18173. 0,
  18174. true, true);
  18175. }
  18176. nextPlayPos = newEnd;
  18177. }
  18178. else
  18179. {
  18180. info.buffer->readFromAudioReader (reader,
  18181. info.startSample,
  18182. info.numSamples,
  18183. start,
  18184. true, true);
  18185. nextPlayPos += info.numSamples;
  18186. }
  18187. }
  18188. }
  18189. END_JUCE_NAMESPACE
  18190. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18191. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18192. BEGIN_JUCE_NAMESPACE
  18193. AudioSourcePlayer::AudioSourcePlayer()
  18194. : source (0),
  18195. sampleRate (0),
  18196. bufferSize (0),
  18197. tempBuffer (2, 8),
  18198. lastGain (1.0f),
  18199. gain (1.0f)
  18200. {
  18201. }
  18202. AudioSourcePlayer::~AudioSourcePlayer()
  18203. {
  18204. setSource (0);
  18205. }
  18206. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18207. {
  18208. if (source != newSource)
  18209. {
  18210. AudioSource* const oldSource = source;
  18211. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18212. newSource->prepareToPlay (bufferSize, sampleRate);
  18213. {
  18214. const ScopedLock sl (readLock);
  18215. source = newSource;
  18216. }
  18217. if (oldSource != 0)
  18218. oldSource->releaseResources();
  18219. }
  18220. }
  18221. void AudioSourcePlayer::setGain (const float newGain) throw()
  18222. {
  18223. gain = newGain;
  18224. }
  18225. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18226. int totalNumInputChannels,
  18227. float** outputChannelData,
  18228. int totalNumOutputChannels,
  18229. int numSamples)
  18230. {
  18231. // these should have been prepared by audioDeviceAboutToStart()...
  18232. jassert (sampleRate > 0 && bufferSize > 0);
  18233. const ScopedLock sl (readLock);
  18234. if (source != 0)
  18235. {
  18236. AudioSourceChannelInfo info;
  18237. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18238. // messy stuff needed to compact the channels down into an array
  18239. // of non-zero pointers..
  18240. for (i = 0; i < totalNumInputChannels; ++i)
  18241. {
  18242. if (inputChannelData[i] != 0)
  18243. {
  18244. inputChans [numInputs++] = inputChannelData[i];
  18245. if (numInputs >= numElementsInArray (inputChans))
  18246. break;
  18247. }
  18248. }
  18249. for (i = 0; i < totalNumOutputChannels; ++i)
  18250. {
  18251. if (outputChannelData[i] != 0)
  18252. {
  18253. outputChans [numOutputs++] = outputChannelData[i];
  18254. if (numOutputs >= numElementsInArray (outputChans))
  18255. break;
  18256. }
  18257. }
  18258. if (numInputs > numOutputs)
  18259. {
  18260. // if there aren't enough output channels for the number of
  18261. // inputs, we need to create some temporary extra ones (can't
  18262. // use the input data in case it gets written to)
  18263. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18264. false, false, true);
  18265. for (i = 0; i < numOutputs; ++i)
  18266. {
  18267. channels[numActiveChans] = outputChans[i];
  18268. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18269. ++numActiveChans;
  18270. }
  18271. for (i = numOutputs; i < numInputs; ++i)
  18272. {
  18273. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18274. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18275. ++numActiveChans;
  18276. }
  18277. }
  18278. else
  18279. {
  18280. for (i = 0; i < numInputs; ++i)
  18281. {
  18282. channels[numActiveChans] = outputChans[i];
  18283. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18284. ++numActiveChans;
  18285. }
  18286. for (i = numInputs; i < numOutputs; ++i)
  18287. {
  18288. channels[numActiveChans] = outputChans[i];
  18289. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18290. ++numActiveChans;
  18291. }
  18292. }
  18293. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18294. info.buffer = &buffer;
  18295. info.startSample = 0;
  18296. info.numSamples = numSamples;
  18297. source->getNextAudioBlock (info);
  18298. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18299. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18300. lastGain = gain;
  18301. }
  18302. else
  18303. {
  18304. for (int i = 0; i < totalNumOutputChannels; ++i)
  18305. if (outputChannelData[i] != 0)
  18306. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18307. }
  18308. }
  18309. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18310. {
  18311. sampleRate = device->getCurrentSampleRate();
  18312. bufferSize = device->getCurrentBufferSizeSamples();
  18313. zeromem (channels, sizeof (channels));
  18314. if (source != 0)
  18315. source->prepareToPlay (bufferSize, sampleRate);
  18316. }
  18317. void AudioSourcePlayer::audioDeviceStopped()
  18318. {
  18319. if (source != 0)
  18320. source->releaseResources();
  18321. sampleRate = 0.0;
  18322. bufferSize = 0;
  18323. tempBuffer.setSize (2, 8);
  18324. }
  18325. END_JUCE_NAMESPACE
  18326. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18327. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18328. BEGIN_JUCE_NAMESPACE
  18329. AudioTransportSource::AudioTransportSource()
  18330. : source (0),
  18331. resamplerSource (0),
  18332. bufferingSource (0),
  18333. positionableSource (0),
  18334. masterSource (0),
  18335. gain (1.0f),
  18336. lastGain (1.0f),
  18337. playing (false),
  18338. stopped (true),
  18339. sampleRate (44100.0),
  18340. sourceSampleRate (0.0),
  18341. blockSize (128),
  18342. readAheadBufferSize (0),
  18343. isPrepared (false),
  18344. inputStreamEOF (false)
  18345. {
  18346. }
  18347. AudioTransportSource::~AudioTransportSource()
  18348. {
  18349. setSource (0);
  18350. releaseResources();
  18351. }
  18352. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18353. int readAheadBufferSize_,
  18354. double sourceSampleRateToCorrectFor)
  18355. {
  18356. if (source == newSource)
  18357. {
  18358. if (source == 0)
  18359. return;
  18360. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18361. }
  18362. readAheadBufferSize = readAheadBufferSize_;
  18363. sourceSampleRate = sourceSampleRateToCorrectFor;
  18364. ResamplingAudioSource* newResamplerSource = 0;
  18365. BufferingAudioSource* newBufferingSource = 0;
  18366. PositionableAudioSource* newPositionableSource = 0;
  18367. AudioSource* newMasterSource = 0;
  18368. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18369. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18370. AudioSource* oldMasterSource = masterSource;
  18371. if (newSource != 0)
  18372. {
  18373. newPositionableSource = newSource;
  18374. if (readAheadBufferSize_ > 0)
  18375. newPositionableSource = newBufferingSource
  18376. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18377. newPositionableSource->setNextReadPosition (0);
  18378. if (sourceSampleRateToCorrectFor != 0)
  18379. newMasterSource = newResamplerSource
  18380. = new ResamplingAudioSource (newPositionableSource, false);
  18381. else
  18382. newMasterSource = newPositionableSource;
  18383. if (isPrepared)
  18384. {
  18385. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18386. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18387. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18388. }
  18389. }
  18390. {
  18391. const ScopedLock sl (callbackLock);
  18392. source = newSource;
  18393. resamplerSource = newResamplerSource;
  18394. bufferingSource = newBufferingSource;
  18395. masterSource = newMasterSource;
  18396. positionableSource = newPositionableSource;
  18397. playing = false;
  18398. }
  18399. if (oldMasterSource != 0)
  18400. oldMasterSource->releaseResources();
  18401. }
  18402. void AudioTransportSource::start()
  18403. {
  18404. if ((! playing) && masterSource != 0)
  18405. {
  18406. {
  18407. const ScopedLock sl (callbackLock);
  18408. playing = true;
  18409. stopped = false;
  18410. inputStreamEOF = false;
  18411. }
  18412. sendChangeMessage (this);
  18413. }
  18414. }
  18415. void AudioTransportSource::stop()
  18416. {
  18417. if (playing)
  18418. {
  18419. {
  18420. const ScopedLock sl (callbackLock);
  18421. playing = false;
  18422. }
  18423. int n = 500;
  18424. while (--n >= 0 && ! stopped)
  18425. Thread::sleep (2);
  18426. sendChangeMessage (this);
  18427. }
  18428. }
  18429. void AudioTransportSource::setPosition (double newPosition)
  18430. {
  18431. if (sampleRate > 0.0)
  18432. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18433. }
  18434. double AudioTransportSource::getCurrentPosition() const
  18435. {
  18436. if (sampleRate > 0.0)
  18437. return getNextReadPosition() / sampleRate;
  18438. else
  18439. return 0.0;
  18440. }
  18441. void AudioTransportSource::setNextReadPosition (int newPosition)
  18442. {
  18443. if (positionableSource != 0)
  18444. {
  18445. if (sampleRate > 0 && sourceSampleRate > 0)
  18446. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18447. positionableSource->setNextReadPosition (newPosition);
  18448. }
  18449. }
  18450. int AudioTransportSource::getNextReadPosition() const
  18451. {
  18452. if (positionableSource != 0)
  18453. {
  18454. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18455. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18456. }
  18457. return 0;
  18458. }
  18459. int AudioTransportSource::getTotalLength() const
  18460. {
  18461. const ScopedLock sl (callbackLock);
  18462. if (positionableSource != 0)
  18463. {
  18464. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18465. return roundToInt (positionableSource->getTotalLength() * ratio);
  18466. }
  18467. return 0;
  18468. }
  18469. bool AudioTransportSource::isLooping() const
  18470. {
  18471. const ScopedLock sl (callbackLock);
  18472. return positionableSource != 0
  18473. && positionableSource->isLooping();
  18474. }
  18475. void AudioTransportSource::setGain (const float newGain) throw()
  18476. {
  18477. gain = newGain;
  18478. }
  18479. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18480. double sampleRate_)
  18481. {
  18482. const ScopedLock sl (callbackLock);
  18483. sampleRate = sampleRate_;
  18484. blockSize = samplesPerBlockExpected;
  18485. if (masterSource != 0)
  18486. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18487. if (resamplerSource != 0 && sourceSampleRate != 0)
  18488. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18489. isPrepared = true;
  18490. }
  18491. void AudioTransportSource::releaseResources()
  18492. {
  18493. const ScopedLock sl (callbackLock);
  18494. if (masterSource != 0)
  18495. masterSource->releaseResources();
  18496. isPrepared = false;
  18497. }
  18498. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18499. {
  18500. const ScopedLock sl (callbackLock);
  18501. inputStreamEOF = false;
  18502. if (masterSource != 0 && ! stopped)
  18503. {
  18504. masterSource->getNextAudioBlock (info);
  18505. if (! playing)
  18506. {
  18507. // just stopped playing, so fade out the last block..
  18508. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18509. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18510. if (info.numSamples > 256)
  18511. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18512. }
  18513. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18514. && ! positionableSource->isLooping())
  18515. {
  18516. playing = false;
  18517. inputStreamEOF = true;
  18518. sendChangeMessage (this);
  18519. }
  18520. stopped = ! playing;
  18521. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18522. {
  18523. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18524. lastGain, gain);
  18525. }
  18526. }
  18527. else
  18528. {
  18529. info.clearActiveBufferRegion();
  18530. stopped = true;
  18531. }
  18532. lastGain = gain;
  18533. }
  18534. END_JUCE_NAMESPACE
  18535. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18536. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18537. BEGIN_JUCE_NAMESPACE
  18538. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18539. public Thread,
  18540. private Timer
  18541. {
  18542. public:
  18543. SharedBufferingAudioSourceThread()
  18544. : Thread ("Audio Buffer")
  18545. {
  18546. }
  18547. ~SharedBufferingAudioSourceThread()
  18548. {
  18549. stopThread (10000);
  18550. clearSingletonInstance();
  18551. }
  18552. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18553. void addSource (BufferingAudioSource* source)
  18554. {
  18555. const ScopedLock sl (lock);
  18556. if (! sources.contains (source))
  18557. {
  18558. sources.add (source);
  18559. startThread();
  18560. stopTimer();
  18561. }
  18562. notify();
  18563. }
  18564. void removeSource (BufferingAudioSource* source)
  18565. {
  18566. const ScopedLock sl (lock);
  18567. sources.removeValue (source);
  18568. if (sources.size() == 0)
  18569. startTimer (5000);
  18570. }
  18571. private:
  18572. Array <BufferingAudioSource*> sources;
  18573. CriticalSection lock;
  18574. void run()
  18575. {
  18576. while (! threadShouldExit())
  18577. {
  18578. bool busy = false;
  18579. for (int i = sources.size(); --i >= 0;)
  18580. {
  18581. if (threadShouldExit())
  18582. return;
  18583. const ScopedLock sl (lock);
  18584. BufferingAudioSource* const b = sources[i];
  18585. if (b != 0 && b->readNextBufferChunk())
  18586. busy = true;
  18587. }
  18588. if (! busy)
  18589. wait (500);
  18590. }
  18591. }
  18592. void timerCallback()
  18593. {
  18594. stopTimer();
  18595. if (sources.size() == 0)
  18596. deleteInstance();
  18597. }
  18598. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18599. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18600. };
  18601. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18602. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18603. const bool deleteSourceWhenDeleted_,
  18604. int numberOfSamplesToBuffer_)
  18605. : source (source_),
  18606. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18607. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18608. buffer (2, 0),
  18609. bufferValidStart (0),
  18610. bufferValidEnd (0),
  18611. nextPlayPos (0),
  18612. wasSourceLooping (false)
  18613. {
  18614. jassert (source_ != 0);
  18615. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18616. // not using a larger buffer..
  18617. }
  18618. BufferingAudioSource::~BufferingAudioSource()
  18619. {
  18620. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18621. if (thread != 0)
  18622. thread->removeSource (this);
  18623. if (deleteSourceWhenDeleted)
  18624. delete source;
  18625. }
  18626. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18627. {
  18628. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18629. sampleRate = sampleRate_;
  18630. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18631. buffer.clear();
  18632. bufferValidStart = 0;
  18633. bufferValidEnd = 0;
  18634. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18635. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18636. buffer.getNumSamples() / 2))
  18637. {
  18638. SharedBufferingAudioSourceThread::getInstance()->notify();
  18639. Thread::sleep (5);
  18640. }
  18641. }
  18642. void BufferingAudioSource::releaseResources()
  18643. {
  18644. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18645. if (thread != 0)
  18646. thread->removeSource (this);
  18647. buffer.setSize (2, 0);
  18648. source->releaseResources();
  18649. }
  18650. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18651. {
  18652. const ScopedLock sl (bufferStartPosLock);
  18653. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18654. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18655. if (validStart == validEnd)
  18656. {
  18657. // total cache miss
  18658. info.clearActiveBufferRegion();
  18659. }
  18660. else
  18661. {
  18662. if (validStart > 0)
  18663. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18664. if (validEnd < info.numSamples)
  18665. info.buffer->clear (info.startSample + validEnd,
  18666. info.numSamples - validEnd); // partial cache miss at end
  18667. if (validStart < validEnd)
  18668. {
  18669. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18670. {
  18671. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18672. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18673. if (startBufferIndex < endBufferIndex)
  18674. {
  18675. info.buffer->copyFrom (chan, info.startSample + validStart,
  18676. buffer,
  18677. chan, startBufferIndex,
  18678. validEnd - validStart);
  18679. }
  18680. else
  18681. {
  18682. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18683. info.buffer->copyFrom (chan, info.startSample + validStart,
  18684. buffer,
  18685. chan, startBufferIndex,
  18686. initialSize);
  18687. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18688. buffer,
  18689. chan, 0,
  18690. (validEnd - validStart) - initialSize);
  18691. }
  18692. }
  18693. }
  18694. nextPlayPos += info.numSamples;
  18695. if (source->isLooping() && nextPlayPos > 0)
  18696. nextPlayPos %= source->getTotalLength();
  18697. }
  18698. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18699. if (thread != 0)
  18700. thread->notify();
  18701. }
  18702. int BufferingAudioSource::getNextReadPosition() const
  18703. {
  18704. return (source->isLooping() && nextPlayPos > 0)
  18705. ? nextPlayPos % source->getTotalLength()
  18706. : nextPlayPos;
  18707. }
  18708. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18709. {
  18710. const ScopedLock sl (bufferStartPosLock);
  18711. nextPlayPos = newPosition;
  18712. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18713. if (thread != 0)
  18714. thread->notify();
  18715. }
  18716. bool BufferingAudioSource::readNextBufferChunk()
  18717. {
  18718. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18719. {
  18720. const ScopedLock sl (bufferStartPosLock);
  18721. if (wasSourceLooping != isLooping())
  18722. {
  18723. wasSourceLooping = isLooping();
  18724. bufferValidStart = 0;
  18725. bufferValidEnd = 0;
  18726. }
  18727. newBVS = jmax (0, nextPlayPos);
  18728. newBVE = newBVS + buffer.getNumSamples() - 4;
  18729. sectionToReadStart = 0;
  18730. sectionToReadEnd = 0;
  18731. const int maxChunkSize = 2048;
  18732. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18733. {
  18734. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18735. sectionToReadStart = newBVS;
  18736. sectionToReadEnd = newBVE;
  18737. bufferValidStart = 0;
  18738. bufferValidEnd = 0;
  18739. }
  18740. else if (abs (newBVS - bufferValidStart) > 512
  18741. || abs (newBVE - bufferValidEnd) > 512)
  18742. {
  18743. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18744. sectionToReadStart = bufferValidEnd;
  18745. sectionToReadEnd = newBVE;
  18746. bufferValidStart = newBVS;
  18747. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18748. }
  18749. }
  18750. if (sectionToReadStart != sectionToReadEnd)
  18751. {
  18752. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18753. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18754. if (bufferIndexStart < bufferIndexEnd)
  18755. {
  18756. readBufferSection (sectionToReadStart,
  18757. sectionToReadEnd - sectionToReadStart,
  18758. bufferIndexStart);
  18759. }
  18760. else
  18761. {
  18762. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18763. readBufferSection (sectionToReadStart,
  18764. initialSize,
  18765. bufferIndexStart);
  18766. readBufferSection (sectionToReadStart + initialSize,
  18767. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18768. 0);
  18769. }
  18770. const ScopedLock sl2 (bufferStartPosLock);
  18771. bufferValidStart = newBVS;
  18772. bufferValidEnd = newBVE;
  18773. return true;
  18774. }
  18775. else
  18776. {
  18777. return false;
  18778. }
  18779. }
  18780. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18781. {
  18782. if (source->getNextReadPosition() != start)
  18783. source->setNextReadPosition (start);
  18784. AudioSourceChannelInfo info;
  18785. info.buffer = &buffer;
  18786. info.startSample = bufferOffset;
  18787. info.numSamples = length;
  18788. source->getNextAudioBlock (info);
  18789. }
  18790. END_JUCE_NAMESPACE
  18791. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18792. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18793. BEGIN_JUCE_NAMESPACE
  18794. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18795. const bool deleteSourceWhenDeleted_)
  18796. : requiredNumberOfChannels (2),
  18797. source (source_),
  18798. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18799. buffer (2, 16)
  18800. {
  18801. remappedInfo.buffer = &buffer;
  18802. remappedInfo.startSample = 0;
  18803. }
  18804. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18805. {
  18806. if (deleteSourceWhenDeleted)
  18807. delete source;
  18808. }
  18809. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18810. {
  18811. const ScopedLock sl (lock);
  18812. requiredNumberOfChannels = requiredNumberOfChannels_;
  18813. }
  18814. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18815. {
  18816. const ScopedLock sl (lock);
  18817. remappedInputs.clear();
  18818. remappedOutputs.clear();
  18819. }
  18820. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18821. {
  18822. const ScopedLock sl (lock);
  18823. while (remappedInputs.size() < destIndex)
  18824. remappedInputs.add (-1);
  18825. remappedInputs.set (destIndex, sourceIndex);
  18826. }
  18827. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18828. {
  18829. const ScopedLock sl (lock);
  18830. while (remappedOutputs.size() < sourceIndex)
  18831. remappedOutputs.add (-1);
  18832. remappedOutputs.set (sourceIndex, destIndex);
  18833. }
  18834. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18835. {
  18836. const ScopedLock sl (lock);
  18837. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18838. return remappedInputs.getUnchecked (inputChannelIndex);
  18839. return -1;
  18840. }
  18841. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18842. {
  18843. const ScopedLock sl (lock);
  18844. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18845. return remappedOutputs .getUnchecked (outputChannelIndex);
  18846. return -1;
  18847. }
  18848. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18849. {
  18850. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18851. }
  18852. void ChannelRemappingAudioSource::releaseResources()
  18853. {
  18854. source->releaseResources();
  18855. }
  18856. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18857. {
  18858. const ScopedLock sl (lock);
  18859. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18860. const int numChans = bufferToFill.buffer->getNumChannels();
  18861. int i;
  18862. for (i = 0; i < buffer.getNumChannels(); ++i)
  18863. {
  18864. const int remappedChan = getRemappedInputChannel (i);
  18865. if (remappedChan >= 0 && remappedChan < numChans)
  18866. {
  18867. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18868. remappedChan,
  18869. bufferToFill.startSample,
  18870. bufferToFill.numSamples);
  18871. }
  18872. else
  18873. {
  18874. buffer.clear (i, 0, bufferToFill.numSamples);
  18875. }
  18876. }
  18877. remappedInfo.numSamples = bufferToFill.numSamples;
  18878. source->getNextAudioBlock (remappedInfo);
  18879. bufferToFill.clearActiveBufferRegion();
  18880. for (i = 0; i < requiredNumberOfChannels; ++i)
  18881. {
  18882. const int remappedChan = getRemappedOutputChannel (i);
  18883. if (remappedChan >= 0 && remappedChan < numChans)
  18884. {
  18885. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18886. buffer, i, 0, bufferToFill.numSamples);
  18887. }
  18888. }
  18889. }
  18890. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18891. {
  18892. XmlElement* e = new XmlElement ("MAPPINGS");
  18893. String ins, outs;
  18894. int i;
  18895. const ScopedLock sl (lock);
  18896. for (i = 0; i < remappedInputs.size(); ++i)
  18897. ins << remappedInputs.getUnchecked(i) << ' ';
  18898. for (i = 0; i < remappedOutputs.size(); ++i)
  18899. outs << remappedOutputs.getUnchecked(i) << ' ';
  18900. e->setAttribute ("inputs", ins.trimEnd());
  18901. e->setAttribute ("outputs", outs.trimEnd());
  18902. return e;
  18903. }
  18904. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18905. {
  18906. if (e.hasTagName ("MAPPINGS"))
  18907. {
  18908. const ScopedLock sl (lock);
  18909. clearAllMappings();
  18910. StringArray ins, outs;
  18911. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18912. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18913. int i;
  18914. for (i = 0; i < ins.size(); ++i)
  18915. remappedInputs.add (ins[i].getIntValue());
  18916. for (i = 0; i < outs.size(); ++i)
  18917. remappedOutputs.add (outs[i].getIntValue());
  18918. }
  18919. }
  18920. END_JUCE_NAMESPACE
  18921. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18922. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18923. BEGIN_JUCE_NAMESPACE
  18924. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18925. const bool deleteInputWhenDeleted_)
  18926. : input (inputSource),
  18927. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18928. {
  18929. jassert (inputSource != 0);
  18930. for (int i = 2; --i >= 0;)
  18931. iirFilters.add (new IIRFilter());
  18932. }
  18933. IIRFilterAudioSource::~IIRFilterAudioSource()
  18934. {
  18935. if (deleteInputWhenDeleted)
  18936. delete input;
  18937. }
  18938. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18939. {
  18940. for (int i = iirFilters.size(); --i >= 0;)
  18941. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18942. }
  18943. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18944. {
  18945. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18946. for (int i = iirFilters.size(); --i >= 0;)
  18947. iirFilters.getUnchecked(i)->reset();
  18948. }
  18949. void IIRFilterAudioSource::releaseResources()
  18950. {
  18951. input->releaseResources();
  18952. }
  18953. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18954. {
  18955. input->getNextAudioBlock (bufferToFill);
  18956. const int numChannels = bufferToFill.buffer->getNumChannels();
  18957. while (numChannels > iirFilters.size())
  18958. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18959. for (int i = 0; i < numChannels; ++i)
  18960. iirFilters.getUnchecked(i)
  18961. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18962. bufferToFill.numSamples);
  18963. }
  18964. END_JUCE_NAMESPACE
  18965. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18966. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18967. BEGIN_JUCE_NAMESPACE
  18968. MixerAudioSource::MixerAudioSource()
  18969. : tempBuffer (2, 0),
  18970. currentSampleRate (0.0),
  18971. bufferSizeExpected (0)
  18972. {
  18973. }
  18974. MixerAudioSource::~MixerAudioSource()
  18975. {
  18976. removeAllInputs();
  18977. }
  18978. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18979. {
  18980. if (input != 0 && ! inputs.contains (input))
  18981. {
  18982. double localRate;
  18983. int localBufferSize;
  18984. {
  18985. const ScopedLock sl (lock);
  18986. localRate = currentSampleRate;
  18987. localBufferSize = bufferSizeExpected;
  18988. }
  18989. if (localRate != 0.0)
  18990. input->prepareToPlay (localBufferSize, localRate);
  18991. const ScopedLock sl (lock);
  18992. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18993. inputs.add (input);
  18994. }
  18995. }
  18996. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18997. {
  18998. if (input != 0)
  18999. {
  19000. int index;
  19001. {
  19002. const ScopedLock sl (lock);
  19003. index = inputs.indexOf (input);
  19004. if (index >= 0)
  19005. {
  19006. inputsToDelete.shiftBits (index, 1);
  19007. inputs.remove (index);
  19008. }
  19009. }
  19010. if (index >= 0)
  19011. {
  19012. input->releaseResources();
  19013. if (deleteInput)
  19014. delete input;
  19015. }
  19016. }
  19017. }
  19018. void MixerAudioSource::removeAllInputs()
  19019. {
  19020. OwnedArray<AudioSource> toDelete;
  19021. {
  19022. const ScopedLock sl (lock);
  19023. for (int i = inputs.size(); --i >= 0;)
  19024. if (inputsToDelete[i])
  19025. toDelete.add (inputs.getUnchecked(i));
  19026. }
  19027. }
  19028. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19029. {
  19030. tempBuffer.setSize (2, samplesPerBlockExpected);
  19031. const ScopedLock sl (lock);
  19032. currentSampleRate = sampleRate;
  19033. bufferSizeExpected = samplesPerBlockExpected;
  19034. for (int i = inputs.size(); --i >= 0;)
  19035. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19036. }
  19037. void MixerAudioSource::releaseResources()
  19038. {
  19039. const ScopedLock sl (lock);
  19040. for (int i = inputs.size(); --i >= 0;)
  19041. inputs.getUnchecked(i)->releaseResources();
  19042. tempBuffer.setSize (2, 0);
  19043. currentSampleRate = 0;
  19044. bufferSizeExpected = 0;
  19045. }
  19046. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19047. {
  19048. const ScopedLock sl (lock);
  19049. if (inputs.size() > 0)
  19050. {
  19051. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19052. if (inputs.size() > 1)
  19053. {
  19054. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19055. info.buffer->getNumSamples());
  19056. AudioSourceChannelInfo info2;
  19057. info2.buffer = &tempBuffer;
  19058. info2.numSamples = info.numSamples;
  19059. info2.startSample = 0;
  19060. for (int i = 1; i < inputs.size(); ++i)
  19061. {
  19062. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19063. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19064. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19065. }
  19066. }
  19067. }
  19068. else
  19069. {
  19070. info.clearActiveBufferRegion();
  19071. }
  19072. }
  19073. END_JUCE_NAMESPACE
  19074. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19075. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19076. BEGIN_JUCE_NAMESPACE
  19077. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19078. const bool deleteInputWhenDeleted_)
  19079. : input (inputSource),
  19080. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19081. ratio (1.0),
  19082. lastRatio (1.0),
  19083. buffer (2, 0),
  19084. sampsInBuffer (0)
  19085. {
  19086. jassert (input != 0);
  19087. }
  19088. ResamplingAudioSource::~ResamplingAudioSource()
  19089. {
  19090. if (deleteInputWhenDeleted)
  19091. delete input;
  19092. }
  19093. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19094. {
  19095. jassert (samplesInPerOutputSample > 0);
  19096. const ScopedLock sl (ratioLock);
  19097. ratio = jmax (0.0, samplesInPerOutputSample);
  19098. }
  19099. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19100. double sampleRate)
  19101. {
  19102. const ScopedLock sl (ratioLock);
  19103. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19104. buffer.setSize (2, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19105. buffer.clear();
  19106. sampsInBuffer = 0;
  19107. bufferPos = 0;
  19108. subSampleOffset = 0.0;
  19109. createLowPass (ratio);
  19110. resetFilters();
  19111. }
  19112. void ResamplingAudioSource::releaseResources()
  19113. {
  19114. input->releaseResources();
  19115. buffer.setSize (2, 0);
  19116. }
  19117. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19118. {
  19119. const ScopedLock sl (ratioLock);
  19120. if (lastRatio != ratio)
  19121. {
  19122. createLowPass (ratio);
  19123. lastRatio = ratio;
  19124. }
  19125. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19126. int bufferSize = buffer.getNumSamples();
  19127. if (bufferSize < sampsNeeded + 8)
  19128. {
  19129. bufferPos %= bufferSize;
  19130. bufferSize = sampsNeeded + 32;
  19131. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19132. }
  19133. bufferPos %= bufferSize;
  19134. int endOfBufferPos = bufferPos + sampsInBuffer;
  19135. while (sampsNeeded > sampsInBuffer)
  19136. {
  19137. endOfBufferPos %= bufferSize;
  19138. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19139. bufferSize - endOfBufferPos);
  19140. AudioSourceChannelInfo readInfo;
  19141. readInfo.buffer = &buffer;
  19142. readInfo.numSamples = numToDo;
  19143. readInfo.startSample = endOfBufferPos;
  19144. input->getNextAudioBlock (readInfo);
  19145. if (ratio > 1.0001)
  19146. {
  19147. // for down-sampling, pre-apply the filter..
  19148. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19149. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19150. }
  19151. sampsInBuffer += numToDo;
  19152. endOfBufferPos += numToDo;
  19153. }
  19154. float* dl = info.buffer->getSampleData (0, info.startSample);
  19155. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  19156. const float* const bl = buffer.getSampleData (0, 0);
  19157. const float* const br = buffer.getSampleData (1, 0);
  19158. int nextPos = (bufferPos + 1) % bufferSize;
  19159. for (int m = info.numSamples; --m >= 0;)
  19160. {
  19161. const float alpha = (float) subSampleOffset;
  19162. const float invAlpha = 1.0f - alpha;
  19163. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  19164. if (dr != 0)
  19165. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  19166. subSampleOffset += ratio;
  19167. jassert (sampsInBuffer > 0);
  19168. while (subSampleOffset >= 1.0)
  19169. {
  19170. if (++bufferPos >= bufferSize)
  19171. bufferPos = 0;
  19172. --sampsInBuffer;
  19173. nextPos = (bufferPos + 1) % bufferSize;
  19174. subSampleOffset -= 1.0;
  19175. }
  19176. }
  19177. if (ratio < 0.9999)
  19178. {
  19179. // for up-sampling, apply the filter after transposing..
  19180. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19181. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19182. }
  19183. else if (ratio <= 1.0001)
  19184. {
  19185. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19186. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19187. {
  19188. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19189. FilterState& fs = filterStates[i];
  19190. if (info.numSamples > 1)
  19191. {
  19192. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19193. }
  19194. else
  19195. {
  19196. fs.y2 = fs.y1;
  19197. fs.x2 = fs.x1;
  19198. }
  19199. fs.y1 = fs.x1 = *endOfBuffer;
  19200. }
  19201. }
  19202. jassert (sampsInBuffer >= 0);
  19203. }
  19204. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19205. {
  19206. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19207. : 0.5 * frequencyRatio;
  19208. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19209. const double nSquared = n * n;
  19210. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19211. setFilterCoefficients (c1,
  19212. c1 * 2.0f,
  19213. c1,
  19214. 1.0,
  19215. c1 * 2.0 * (1.0 - nSquared),
  19216. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19217. }
  19218. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19219. {
  19220. const double a = 1.0 / c4;
  19221. c1 *= a;
  19222. c2 *= a;
  19223. c3 *= a;
  19224. c5 *= a;
  19225. c6 *= a;
  19226. coefficients[0] = c1;
  19227. coefficients[1] = c2;
  19228. coefficients[2] = c3;
  19229. coefficients[3] = c4;
  19230. coefficients[4] = c5;
  19231. coefficients[5] = c6;
  19232. }
  19233. void ResamplingAudioSource::resetFilters()
  19234. {
  19235. zeromem (filterStates, sizeof (filterStates));
  19236. }
  19237. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19238. {
  19239. while (--num >= 0)
  19240. {
  19241. const double in = *samples;
  19242. double out = coefficients[0] * in
  19243. + coefficients[1] * fs.x1
  19244. + coefficients[2] * fs.x2
  19245. - coefficients[4] * fs.y1
  19246. - coefficients[5] * fs.y2;
  19247. #if JUCE_INTEL
  19248. if (! (out < -1.0e-8 || out > 1.0e-8))
  19249. out = 0;
  19250. #endif
  19251. fs.x2 = fs.x1;
  19252. fs.x1 = in;
  19253. fs.y2 = fs.y1;
  19254. fs.y1 = out;
  19255. *samples++ = (float) out;
  19256. }
  19257. }
  19258. END_JUCE_NAMESPACE
  19259. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19260. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19261. BEGIN_JUCE_NAMESPACE
  19262. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19263. : frequency (1000.0),
  19264. sampleRate (44100.0),
  19265. currentPhase (0.0),
  19266. phasePerSample (0.0),
  19267. amplitude (0.5f)
  19268. {
  19269. }
  19270. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19271. {
  19272. }
  19273. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19274. {
  19275. amplitude = newAmplitude;
  19276. }
  19277. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19278. {
  19279. frequency = newFrequencyHz;
  19280. phasePerSample = 0.0;
  19281. }
  19282. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19283. double sampleRate_)
  19284. {
  19285. currentPhase = 0.0;
  19286. phasePerSample = 0.0;
  19287. sampleRate = sampleRate_;
  19288. }
  19289. void ToneGeneratorAudioSource::releaseResources()
  19290. {
  19291. }
  19292. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19293. {
  19294. if (phasePerSample == 0.0)
  19295. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19296. for (int i = 0; i < info.numSamples; ++i)
  19297. {
  19298. const float sample = amplitude * (float) std::sin (currentPhase);
  19299. currentPhase += phasePerSample;
  19300. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19301. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19302. }
  19303. }
  19304. END_JUCE_NAMESPACE
  19305. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19306. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19307. BEGIN_JUCE_NAMESPACE
  19308. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19309. : sampleRate (0),
  19310. bufferSize (0),
  19311. useDefaultInputChannels (true),
  19312. useDefaultOutputChannels (true)
  19313. {
  19314. }
  19315. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19316. {
  19317. return outputDeviceName == other.outputDeviceName
  19318. && inputDeviceName == other.inputDeviceName
  19319. && sampleRate == other.sampleRate
  19320. && bufferSize == other.bufferSize
  19321. && inputChannels == other.inputChannels
  19322. && useDefaultInputChannels == other.useDefaultInputChannels
  19323. && outputChannels == other.outputChannels
  19324. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19325. }
  19326. AudioDeviceManager::AudioDeviceManager()
  19327. : currentAudioDevice (0),
  19328. numInputChansNeeded (0),
  19329. numOutputChansNeeded (2),
  19330. listNeedsScanning (true),
  19331. useInputNames (false),
  19332. inputLevelMeasurementEnabledCount (0),
  19333. inputLevel (0),
  19334. tempBuffer (2, 2),
  19335. defaultMidiOutput (0),
  19336. cpuUsageMs (0),
  19337. timeToCpuScale (0)
  19338. {
  19339. callbackHandler.owner = this;
  19340. }
  19341. AudioDeviceManager::~AudioDeviceManager()
  19342. {
  19343. currentAudioDevice = 0;
  19344. defaultMidiOutput = 0;
  19345. }
  19346. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19347. {
  19348. if (availableDeviceTypes.size() == 0)
  19349. {
  19350. createAudioDeviceTypes (availableDeviceTypes);
  19351. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19352. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19353. if (availableDeviceTypes.size() > 0)
  19354. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19355. }
  19356. }
  19357. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19358. {
  19359. scanDevicesIfNeeded();
  19360. return availableDeviceTypes;
  19361. }
  19362. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19363. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19364. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19365. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19366. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19367. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19368. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19369. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19370. {
  19371. (void) list; // (to avoid 'unused param' warnings)
  19372. #if JUCE_WINDOWS
  19373. #if JUCE_WASAPI
  19374. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19375. list.add (juce_createAudioIODeviceType_WASAPI());
  19376. #endif
  19377. #if JUCE_DIRECTSOUND
  19378. list.add (juce_createAudioIODeviceType_DirectSound());
  19379. #endif
  19380. #if JUCE_ASIO
  19381. list.add (juce_createAudioIODeviceType_ASIO());
  19382. #endif
  19383. #endif
  19384. #if JUCE_MAC
  19385. list.add (juce_createAudioIODeviceType_CoreAudio());
  19386. #endif
  19387. #if JUCE_IPHONE
  19388. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19389. #endif
  19390. #if JUCE_LINUX && JUCE_ALSA
  19391. list.add (juce_createAudioIODeviceType_ALSA());
  19392. #endif
  19393. #if JUCE_LINUX && JUCE_JACK
  19394. list.add (juce_createAudioIODeviceType_JACK());
  19395. #endif
  19396. }
  19397. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19398. const int numOutputChannelsNeeded,
  19399. const XmlElement* const e,
  19400. const bool selectDefaultDeviceOnFailure,
  19401. const String& preferredDefaultDeviceName,
  19402. const AudioDeviceSetup* preferredSetupOptions)
  19403. {
  19404. scanDevicesIfNeeded();
  19405. numInputChansNeeded = numInputChannelsNeeded;
  19406. numOutputChansNeeded = numOutputChannelsNeeded;
  19407. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19408. {
  19409. lastExplicitSettings = new XmlElement (*e);
  19410. String error;
  19411. AudioDeviceSetup setup;
  19412. if (preferredSetupOptions != 0)
  19413. setup = *preferredSetupOptions;
  19414. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19415. {
  19416. setup.inputDeviceName = setup.outputDeviceName
  19417. = e->getStringAttribute ("audioDeviceName");
  19418. }
  19419. else
  19420. {
  19421. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19422. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19423. }
  19424. currentDeviceType = e->getStringAttribute ("deviceType");
  19425. if (currentDeviceType.isEmpty())
  19426. {
  19427. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19428. if (type != 0)
  19429. currentDeviceType = type->getTypeName();
  19430. else if (availableDeviceTypes.size() > 0)
  19431. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19432. }
  19433. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19434. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19435. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19436. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19437. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19438. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19439. error = setAudioDeviceSetup (setup, true);
  19440. midiInsFromXml.clear();
  19441. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19442. midiInsFromXml.add (c->getStringAttribute ("name"));
  19443. const StringArray allMidiIns (MidiInput::getDevices());
  19444. for (int i = allMidiIns.size(); --i >= 0;)
  19445. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19446. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19447. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19448. false, preferredDefaultDeviceName);
  19449. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19450. return error;
  19451. }
  19452. else
  19453. {
  19454. AudioDeviceSetup setup;
  19455. if (preferredSetupOptions != 0)
  19456. {
  19457. setup = *preferredSetupOptions;
  19458. }
  19459. else if (preferredDefaultDeviceName.isNotEmpty())
  19460. {
  19461. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19462. {
  19463. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19464. StringArray outs (type->getDeviceNames (false));
  19465. int i;
  19466. for (i = 0; i < outs.size(); ++i)
  19467. {
  19468. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19469. {
  19470. setup.outputDeviceName = outs[i];
  19471. break;
  19472. }
  19473. }
  19474. StringArray ins (type->getDeviceNames (true));
  19475. for (i = 0; i < ins.size(); ++i)
  19476. {
  19477. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19478. {
  19479. setup.inputDeviceName = ins[i];
  19480. break;
  19481. }
  19482. }
  19483. }
  19484. }
  19485. insertDefaultDeviceNames (setup);
  19486. return setAudioDeviceSetup (setup, false);
  19487. }
  19488. }
  19489. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19490. {
  19491. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19492. if (type != 0)
  19493. {
  19494. if (setup.outputDeviceName.isEmpty())
  19495. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19496. if (setup.inputDeviceName.isEmpty())
  19497. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19498. }
  19499. }
  19500. XmlElement* AudioDeviceManager::createStateXml() const
  19501. {
  19502. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19503. }
  19504. void AudioDeviceManager::scanDevicesIfNeeded()
  19505. {
  19506. if (listNeedsScanning)
  19507. {
  19508. listNeedsScanning = false;
  19509. createDeviceTypesIfNeeded();
  19510. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19511. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19512. }
  19513. }
  19514. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19515. {
  19516. scanDevicesIfNeeded();
  19517. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19518. {
  19519. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19520. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19521. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19522. {
  19523. return type;
  19524. }
  19525. }
  19526. return 0;
  19527. }
  19528. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19529. {
  19530. setup = currentSetup;
  19531. }
  19532. void AudioDeviceManager::deleteCurrentDevice()
  19533. {
  19534. currentAudioDevice = 0;
  19535. currentSetup.inputDeviceName = String::empty;
  19536. currentSetup.outputDeviceName = String::empty;
  19537. }
  19538. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19539. const bool treatAsChosenDevice)
  19540. {
  19541. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19542. {
  19543. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19544. && currentDeviceType != type)
  19545. {
  19546. currentDeviceType = type;
  19547. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19548. insertDefaultDeviceNames (s);
  19549. setAudioDeviceSetup (s, treatAsChosenDevice);
  19550. sendChangeMessage (this);
  19551. break;
  19552. }
  19553. }
  19554. }
  19555. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19556. {
  19557. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19558. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19559. return availableDeviceTypes[i];
  19560. return availableDeviceTypes[0];
  19561. }
  19562. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19563. const bool treatAsChosenDevice)
  19564. {
  19565. jassert (&newSetup != &currentSetup); // this will have no effect
  19566. if (newSetup == currentSetup && currentAudioDevice != 0)
  19567. return String::empty;
  19568. if (! (newSetup == currentSetup))
  19569. sendChangeMessage (this);
  19570. stopDevice();
  19571. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19572. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19573. String error;
  19574. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19575. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19576. {
  19577. deleteCurrentDevice();
  19578. if (treatAsChosenDevice)
  19579. updateXml();
  19580. return String::empty;
  19581. }
  19582. if (currentSetup.inputDeviceName != newInputDeviceName
  19583. || currentSetup.outputDeviceName != newOutputDeviceName
  19584. || currentAudioDevice == 0)
  19585. {
  19586. deleteCurrentDevice();
  19587. scanDevicesIfNeeded();
  19588. if (newOutputDeviceName.isNotEmpty()
  19589. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19590. {
  19591. return "No such device: " + newOutputDeviceName;
  19592. }
  19593. if (newInputDeviceName.isNotEmpty()
  19594. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19595. {
  19596. return "No such device: " + newInputDeviceName;
  19597. }
  19598. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19599. if (currentAudioDevice == 0)
  19600. error = "Can't open the audio device!\n\nThis may be because another application is currently using the same device - if so, you should close any other applications and try again!";
  19601. else
  19602. error = currentAudioDevice->getLastError();
  19603. if (error.isNotEmpty())
  19604. {
  19605. deleteCurrentDevice();
  19606. return error;
  19607. }
  19608. if (newSetup.useDefaultInputChannels)
  19609. {
  19610. inputChannels.clear();
  19611. inputChannels.setRange (0, numInputChansNeeded, true);
  19612. }
  19613. if (newSetup.useDefaultOutputChannels)
  19614. {
  19615. outputChannels.clear();
  19616. outputChannels.setRange (0, numOutputChansNeeded, true);
  19617. }
  19618. if (newInputDeviceName.isEmpty())
  19619. inputChannels.clear();
  19620. if (newOutputDeviceName.isEmpty())
  19621. outputChannels.clear();
  19622. }
  19623. if (! newSetup.useDefaultInputChannels)
  19624. inputChannels = newSetup.inputChannels;
  19625. if (! newSetup.useDefaultOutputChannels)
  19626. outputChannels = newSetup.outputChannels;
  19627. currentSetup = newSetup;
  19628. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19629. error = currentAudioDevice->open (inputChannels,
  19630. outputChannels,
  19631. currentSetup.sampleRate,
  19632. currentSetup.bufferSize);
  19633. if (error.isEmpty())
  19634. {
  19635. currentDeviceType = currentAudioDevice->getTypeName();
  19636. currentAudioDevice->start (&callbackHandler);
  19637. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19638. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19639. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19640. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19641. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19642. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19643. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19644. if (treatAsChosenDevice)
  19645. updateXml();
  19646. }
  19647. else
  19648. {
  19649. deleteCurrentDevice();
  19650. }
  19651. return error;
  19652. }
  19653. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19654. {
  19655. jassert (currentAudioDevice != 0);
  19656. if (rate > 0)
  19657. {
  19658. bool ok = false;
  19659. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19660. {
  19661. const double sr = currentAudioDevice->getSampleRate (i);
  19662. if (sr == rate)
  19663. ok = true;
  19664. }
  19665. if (! ok)
  19666. rate = 0;
  19667. }
  19668. if (rate == 0)
  19669. {
  19670. double lowestAbove44 = 0.0;
  19671. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19672. {
  19673. const double sr = currentAudioDevice->getSampleRate (i);
  19674. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19675. lowestAbove44 = sr;
  19676. }
  19677. if (lowestAbove44 == 0.0)
  19678. rate = currentAudioDevice->getSampleRate (0);
  19679. else
  19680. rate = lowestAbove44;
  19681. }
  19682. return rate;
  19683. }
  19684. void AudioDeviceManager::stopDevice()
  19685. {
  19686. if (currentAudioDevice != 0)
  19687. currentAudioDevice->stop();
  19688. testSound = 0;
  19689. }
  19690. void AudioDeviceManager::closeAudioDevice()
  19691. {
  19692. stopDevice();
  19693. currentAudioDevice = 0;
  19694. }
  19695. void AudioDeviceManager::restartLastAudioDevice()
  19696. {
  19697. if (currentAudioDevice == 0)
  19698. {
  19699. if (currentSetup.inputDeviceName.isEmpty()
  19700. && currentSetup.outputDeviceName.isEmpty())
  19701. {
  19702. // This method will only reload the last device that was running
  19703. // before closeAudioDevice() was called - you need to actually open
  19704. // one first, with setAudioDevice().
  19705. jassertfalse;
  19706. return;
  19707. }
  19708. AudioDeviceSetup s (currentSetup);
  19709. setAudioDeviceSetup (s, false);
  19710. }
  19711. }
  19712. void AudioDeviceManager::updateXml()
  19713. {
  19714. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19715. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19716. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19717. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19718. if (currentAudioDevice != 0)
  19719. {
  19720. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19721. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19722. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19723. if (! currentSetup.useDefaultInputChannels)
  19724. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19725. if (! currentSetup.useDefaultOutputChannels)
  19726. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19727. }
  19728. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19729. {
  19730. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19731. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19732. }
  19733. if (midiInsFromXml.size() > 0)
  19734. {
  19735. // Add any midi devices that have been enabled before, but which aren't currently
  19736. // open because the device has been disconnected.
  19737. const StringArray availableMidiDevices (MidiInput::getDevices());
  19738. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19739. {
  19740. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19741. {
  19742. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19743. m->setAttribute ("name", midiInsFromXml[i]);
  19744. }
  19745. }
  19746. }
  19747. if (defaultMidiOutputName.isNotEmpty())
  19748. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19749. }
  19750. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19751. {
  19752. {
  19753. const ScopedLock sl (audioCallbackLock);
  19754. if (callbacks.contains (newCallback))
  19755. return;
  19756. }
  19757. if (currentAudioDevice != 0 && newCallback != 0)
  19758. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19759. const ScopedLock sl (audioCallbackLock);
  19760. callbacks.add (newCallback);
  19761. }
  19762. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19763. {
  19764. if (callback != 0)
  19765. {
  19766. bool needsDeinitialising = currentAudioDevice != 0;
  19767. {
  19768. const ScopedLock sl (audioCallbackLock);
  19769. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19770. callbacks.removeValue (callback);
  19771. }
  19772. if (needsDeinitialising)
  19773. callback->audioDeviceStopped();
  19774. }
  19775. }
  19776. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19777. int numInputChannels,
  19778. float** outputChannelData,
  19779. int numOutputChannels,
  19780. int numSamples)
  19781. {
  19782. const ScopedLock sl (audioCallbackLock);
  19783. if (inputLevelMeasurementEnabledCount > 0)
  19784. {
  19785. for (int j = 0; j < numSamples; ++j)
  19786. {
  19787. float s = 0;
  19788. for (int i = 0; i < numInputChannels; ++i)
  19789. s += std::abs (inputChannelData[i][j]);
  19790. s /= numInputChannels;
  19791. const double decayFactor = 0.99992;
  19792. if (s > inputLevel)
  19793. inputLevel = s;
  19794. else if (inputLevel > 0.001f)
  19795. inputLevel *= decayFactor;
  19796. else
  19797. inputLevel = 0;
  19798. }
  19799. }
  19800. if (callbacks.size() > 0)
  19801. {
  19802. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19803. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19804. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19805. outputChannelData, numOutputChannels, numSamples);
  19806. float** const tempChans = tempBuffer.getArrayOfChannels();
  19807. for (int i = callbacks.size(); --i > 0;)
  19808. {
  19809. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19810. tempChans, numOutputChannels, numSamples);
  19811. for (int chan = 0; chan < numOutputChannels; ++chan)
  19812. {
  19813. const float* const src = tempChans [chan];
  19814. float* const dst = outputChannelData [chan];
  19815. if (src != 0 && dst != 0)
  19816. for (int j = 0; j < numSamples; ++j)
  19817. dst[j] += src[j];
  19818. }
  19819. }
  19820. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19821. const double filterAmount = 0.2;
  19822. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19823. }
  19824. else
  19825. {
  19826. for (int i = 0; i < numOutputChannels; ++i)
  19827. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19828. }
  19829. if (testSound != 0)
  19830. {
  19831. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19832. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19833. for (int i = 0; i < numOutputChannels; ++i)
  19834. for (int j = 0; j < numSamps; ++j)
  19835. outputChannelData [i][j] += src[j];
  19836. testSoundPosition += numSamps;
  19837. if (testSoundPosition >= testSound->getNumSamples())
  19838. testSound = 0;
  19839. }
  19840. }
  19841. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19842. {
  19843. cpuUsageMs = 0;
  19844. const double sampleRate = device->getCurrentSampleRate();
  19845. const int blockSize = device->getCurrentBufferSizeSamples();
  19846. if (sampleRate > 0.0 && blockSize > 0)
  19847. {
  19848. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19849. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19850. }
  19851. {
  19852. const ScopedLock sl (audioCallbackLock);
  19853. for (int i = callbacks.size(); --i >= 0;)
  19854. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19855. }
  19856. sendChangeMessage (this);
  19857. }
  19858. void AudioDeviceManager::audioDeviceStoppedInt()
  19859. {
  19860. cpuUsageMs = 0;
  19861. timeToCpuScale = 0;
  19862. sendChangeMessage (this);
  19863. const ScopedLock sl (audioCallbackLock);
  19864. for (int i = callbacks.size(); --i >= 0;)
  19865. callbacks.getUnchecked(i)->audioDeviceStopped();
  19866. }
  19867. double AudioDeviceManager::getCpuUsage() const
  19868. {
  19869. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19870. }
  19871. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19872. const bool enabled)
  19873. {
  19874. if (enabled != isMidiInputEnabled (name))
  19875. {
  19876. if (enabled)
  19877. {
  19878. const int index = MidiInput::getDevices().indexOf (name);
  19879. if (index >= 0)
  19880. {
  19881. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19882. if (min != 0)
  19883. {
  19884. enabledMidiInputs.add (min);
  19885. min->start();
  19886. }
  19887. }
  19888. }
  19889. else
  19890. {
  19891. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19892. if (enabledMidiInputs[i]->getName() == name)
  19893. enabledMidiInputs.remove (i);
  19894. }
  19895. updateXml();
  19896. sendChangeMessage (this);
  19897. }
  19898. }
  19899. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19900. {
  19901. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19902. if (enabledMidiInputs[i]->getName() == name)
  19903. return true;
  19904. return false;
  19905. }
  19906. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19907. MidiInputCallback* callback)
  19908. {
  19909. removeMidiInputCallback (name, callback);
  19910. if (name.isEmpty())
  19911. {
  19912. midiCallbacks.add (callback);
  19913. midiCallbackDevices.add (0);
  19914. }
  19915. else
  19916. {
  19917. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19918. {
  19919. if (enabledMidiInputs[i]->getName() == name)
  19920. {
  19921. const ScopedLock sl (midiCallbackLock);
  19922. midiCallbacks.add (callback);
  19923. midiCallbackDevices.add (enabledMidiInputs[i]);
  19924. break;
  19925. }
  19926. }
  19927. }
  19928. }
  19929. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19930. MidiInputCallback* /*callback*/)
  19931. {
  19932. const ScopedLock sl (midiCallbackLock);
  19933. for (int i = midiCallbacks.size(); --i >= 0;)
  19934. {
  19935. String devName;
  19936. if (midiCallbackDevices.getUnchecked(i) != 0)
  19937. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19938. if (devName == name)
  19939. {
  19940. midiCallbacks.remove (i);
  19941. midiCallbackDevices.remove (i);
  19942. }
  19943. }
  19944. }
  19945. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19946. const MidiMessage& message)
  19947. {
  19948. if (! message.isActiveSense())
  19949. {
  19950. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19951. const ScopedLock sl (midiCallbackLock);
  19952. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19953. {
  19954. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19955. if (md == source || (md == 0 && isDefaultSource))
  19956. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19957. }
  19958. }
  19959. }
  19960. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19961. {
  19962. if (defaultMidiOutputName != deviceName)
  19963. {
  19964. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19965. {
  19966. const ScopedLock sl (audioCallbackLock);
  19967. oldCallbacks = callbacks;
  19968. callbacks.clear();
  19969. }
  19970. if (currentAudioDevice != 0)
  19971. for (int i = oldCallbacks.size(); --i >= 0;)
  19972. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19973. defaultMidiOutput = 0;
  19974. defaultMidiOutputName = deviceName;
  19975. if (deviceName.isNotEmpty())
  19976. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19977. if (currentAudioDevice != 0)
  19978. for (int i = oldCallbacks.size(); --i >= 0;)
  19979. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19980. {
  19981. const ScopedLock sl (audioCallbackLock);
  19982. callbacks = oldCallbacks;
  19983. }
  19984. updateXml();
  19985. sendChangeMessage (this);
  19986. }
  19987. }
  19988. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19989. int numInputChannels,
  19990. float** outputChannelData,
  19991. int numOutputChannels,
  19992. int numSamples)
  19993. {
  19994. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19995. }
  19996. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19997. {
  19998. owner->audioDeviceAboutToStartInt (device);
  19999. }
  20000. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20001. {
  20002. owner->audioDeviceStoppedInt();
  20003. }
  20004. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20005. {
  20006. owner->handleIncomingMidiMessageInt (source, message);
  20007. }
  20008. void AudioDeviceManager::playTestSound()
  20009. {
  20010. { // cunningly nested to swap, unlock and delete in that order.
  20011. ScopedPointer <AudioSampleBuffer> oldSound;
  20012. {
  20013. const ScopedLock sl (audioCallbackLock);
  20014. oldSound = testSound;
  20015. }
  20016. }
  20017. testSoundPosition = 0;
  20018. if (currentAudioDevice != 0)
  20019. {
  20020. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20021. const int soundLength = (int) sampleRate;
  20022. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20023. float* samples = newSound->getSampleData (0);
  20024. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20025. const float amplitude = 0.5f;
  20026. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20027. for (int i = 0; i < soundLength; ++i)
  20028. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20029. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20030. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20031. const ScopedLock sl (audioCallbackLock);
  20032. testSound = newSound;
  20033. }
  20034. }
  20035. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20036. {
  20037. const ScopedLock sl (audioCallbackLock);
  20038. if (enableMeasurement)
  20039. ++inputLevelMeasurementEnabledCount;
  20040. else
  20041. --inputLevelMeasurementEnabledCount;
  20042. inputLevel = 0;
  20043. }
  20044. double AudioDeviceManager::getCurrentInputLevel() const
  20045. {
  20046. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20047. return inputLevel;
  20048. }
  20049. END_JUCE_NAMESPACE
  20050. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20051. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20052. BEGIN_JUCE_NAMESPACE
  20053. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20054. : name (deviceName),
  20055. typeName (typeName_)
  20056. {
  20057. }
  20058. AudioIODevice::~AudioIODevice()
  20059. {
  20060. }
  20061. bool AudioIODevice::hasControlPanel() const
  20062. {
  20063. return false;
  20064. }
  20065. bool AudioIODevice::showControlPanel()
  20066. {
  20067. jassertfalse; // this should only be called for devices which return true from
  20068. // their hasControlPanel() method.
  20069. return false;
  20070. }
  20071. END_JUCE_NAMESPACE
  20072. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20073. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20074. BEGIN_JUCE_NAMESPACE
  20075. AudioIODeviceType::AudioIODeviceType (const String& name)
  20076. : typeName (name)
  20077. {
  20078. }
  20079. AudioIODeviceType::~AudioIODeviceType()
  20080. {
  20081. }
  20082. END_JUCE_NAMESPACE
  20083. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20084. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20085. BEGIN_JUCE_NAMESPACE
  20086. MidiOutput::MidiOutput()
  20087. : Thread ("midi out"),
  20088. internal (0),
  20089. firstMessage (0)
  20090. {
  20091. }
  20092. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20093. const double sampleNumber)
  20094. : message (data, len, sampleNumber)
  20095. {
  20096. }
  20097. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20098. const double millisecondCounterToStartAt,
  20099. double samplesPerSecondForBuffer)
  20100. {
  20101. // You've got to call startBackgroundThread() for this to actually work..
  20102. jassert (isThreadRunning());
  20103. // this needs to be a value in the future - RTFM for this method!
  20104. jassert (millisecondCounterToStartAt > 0);
  20105. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20106. MidiBuffer::Iterator i (buffer);
  20107. const uint8* data;
  20108. int len, time;
  20109. while (i.getNextEvent (data, len, time))
  20110. {
  20111. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20112. PendingMessage* const m
  20113. = new PendingMessage (data, len, eventTime);
  20114. const ScopedLock sl (lock);
  20115. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20116. {
  20117. m->next = firstMessage;
  20118. firstMessage = m;
  20119. }
  20120. else
  20121. {
  20122. PendingMessage* mm = firstMessage;
  20123. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20124. mm = mm->next;
  20125. m->next = mm->next;
  20126. mm->next = m;
  20127. }
  20128. }
  20129. notify();
  20130. }
  20131. void MidiOutput::clearAllPendingMessages()
  20132. {
  20133. const ScopedLock sl (lock);
  20134. while (firstMessage != 0)
  20135. {
  20136. PendingMessage* const m = firstMessage;
  20137. firstMessage = firstMessage->next;
  20138. delete m;
  20139. }
  20140. }
  20141. void MidiOutput::startBackgroundThread()
  20142. {
  20143. startThread (9);
  20144. }
  20145. void MidiOutput::stopBackgroundThread()
  20146. {
  20147. stopThread (5000);
  20148. }
  20149. void MidiOutput::run()
  20150. {
  20151. while (! threadShouldExit())
  20152. {
  20153. uint32 now = Time::getMillisecondCounter();
  20154. uint32 eventTime = 0;
  20155. uint32 timeToWait = 500;
  20156. PendingMessage* message;
  20157. {
  20158. const ScopedLock sl (lock);
  20159. message = firstMessage;
  20160. if (message != 0)
  20161. {
  20162. eventTime = roundToInt (message->message.getTimeStamp());
  20163. if (eventTime > now + 20)
  20164. {
  20165. timeToWait = eventTime - (now + 20);
  20166. message = 0;
  20167. }
  20168. else
  20169. {
  20170. firstMessage = message->next;
  20171. }
  20172. }
  20173. }
  20174. if (message != 0)
  20175. {
  20176. if (eventTime > now)
  20177. {
  20178. Time::waitForMillisecondCounter (eventTime);
  20179. if (threadShouldExit())
  20180. break;
  20181. }
  20182. if (eventTime > now - 200)
  20183. sendMessageNow (message->message);
  20184. delete message;
  20185. }
  20186. else
  20187. {
  20188. jassert (timeToWait < 1000 * 30);
  20189. wait (timeToWait);
  20190. }
  20191. }
  20192. clearAllPendingMessages();
  20193. }
  20194. END_JUCE_NAMESPACE
  20195. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20196. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20197. BEGIN_JUCE_NAMESPACE
  20198. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20199. {
  20200. const double maxVal = (double) 0x7fff;
  20201. char* intData = static_cast <char*> (dest);
  20202. if (dest != (void*) source || destBytesPerSample <= 4)
  20203. {
  20204. for (int i = 0; i < numSamples; ++i)
  20205. {
  20206. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20207. intData += destBytesPerSample;
  20208. }
  20209. }
  20210. else
  20211. {
  20212. intData += destBytesPerSample * numSamples;
  20213. for (int i = numSamples; --i >= 0;)
  20214. {
  20215. intData -= destBytesPerSample;
  20216. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20217. }
  20218. }
  20219. }
  20220. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20221. {
  20222. const double maxVal = (double) 0x7fff;
  20223. char* intData = static_cast <char*> (dest);
  20224. if (dest != (void*) source || destBytesPerSample <= 4)
  20225. {
  20226. for (int i = 0; i < numSamples; ++i)
  20227. {
  20228. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20229. intData += destBytesPerSample;
  20230. }
  20231. }
  20232. else
  20233. {
  20234. intData += destBytesPerSample * numSamples;
  20235. for (int i = numSamples; --i >= 0;)
  20236. {
  20237. intData -= destBytesPerSample;
  20238. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20239. }
  20240. }
  20241. }
  20242. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20243. {
  20244. const double maxVal = (double) 0x7fffff;
  20245. char* intData = static_cast <char*> (dest);
  20246. if (dest != (void*) source || destBytesPerSample <= 4)
  20247. {
  20248. for (int i = 0; i < numSamples; ++i)
  20249. {
  20250. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20251. intData += destBytesPerSample;
  20252. }
  20253. }
  20254. else
  20255. {
  20256. intData += destBytesPerSample * numSamples;
  20257. for (int i = numSamples; --i >= 0;)
  20258. {
  20259. intData -= destBytesPerSample;
  20260. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20261. }
  20262. }
  20263. }
  20264. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20265. {
  20266. const double maxVal = (double) 0x7fffff;
  20267. char* intData = static_cast <char*> (dest);
  20268. if (dest != (void*) source || destBytesPerSample <= 4)
  20269. {
  20270. for (int i = 0; i < numSamples; ++i)
  20271. {
  20272. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20273. intData += destBytesPerSample;
  20274. }
  20275. }
  20276. else
  20277. {
  20278. intData += destBytesPerSample * numSamples;
  20279. for (int i = numSamples; --i >= 0;)
  20280. {
  20281. intData -= destBytesPerSample;
  20282. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20283. }
  20284. }
  20285. }
  20286. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20287. {
  20288. const double maxVal = (double) 0x7fffffff;
  20289. char* intData = static_cast <char*> (dest);
  20290. if (dest != (void*) source || destBytesPerSample <= 4)
  20291. {
  20292. for (int i = 0; i < numSamples; ++i)
  20293. {
  20294. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20295. intData += destBytesPerSample;
  20296. }
  20297. }
  20298. else
  20299. {
  20300. intData += destBytesPerSample * numSamples;
  20301. for (int i = numSamples; --i >= 0;)
  20302. {
  20303. intData -= destBytesPerSample;
  20304. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20305. }
  20306. }
  20307. }
  20308. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20309. {
  20310. const double maxVal = (double) 0x7fffffff;
  20311. char* intData = static_cast <char*> (dest);
  20312. if (dest != (void*) source || destBytesPerSample <= 4)
  20313. {
  20314. for (int i = 0; i < numSamples; ++i)
  20315. {
  20316. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20317. intData += destBytesPerSample;
  20318. }
  20319. }
  20320. else
  20321. {
  20322. intData += destBytesPerSample * numSamples;
  20323. for (int i = numSamples; --i >= 0;)
  20324. {
  20325. intData -= destBytesPerSample;
  20326. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20327. }
  20328. }
  20329. }
  20330. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20331. {
  20332. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20333. char* d = static_cast <char*> (dest);
  20334. for (int i = 0; i < numSamples; ++i)
  20335. {
  20336. *(float*) d = source[i];
  20337. #if JUCE_BIG_ENDIAN
  20338. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20339. #endif
  20340. d += destBytesPerSample;
  20341. }
  20342. }
  20343. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20344. {
  20345. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20346. char* d = static_cast <char*> (dest);
  20347. for (int i = 0; i < numSamples; ++i)
  20348. {
  20349. *(float*) d = source[i];
  20350. #if JUCE_LITTLE_ENDIAN
  20351. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20352. #endif
  20353. d += destBytesPerSample;
  20354. }
  20355. }
  20356. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20357. {
  20358. const float scale = 1.0f / 0x7fff;
  20359. const char* intData = static_cast <const char*> (source);
  20360. if (source != (void*) dest || srcBytesPerSample >= 4)
  20361. {
  20362. for (int i = 0; i < numSamples; ++i)
  20363. {
  20364. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20365. intData += srcBytesPerSample;
  20366. }
  20367. }
  20368. else
  20369. {
  20370. intData += srcBytesPerSample * numSamples;
  20371. for (int i = numSamples; --i >= 0;)
  20372. {
  20373. intData -= srcBytesPerSample;
  20374. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20375. }
  20376. }
  20377. }
  20378. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20379. {
  20380. const float scale = 1.0f / 0x7fff;
  20381. const char* intData = static_cast <const char*> (source);
  20382. if (source != (void*) dest || srcBytesPerSample >= 4)
  20383. {
  20384. for (int i = 0; i < numSamples; ++i)
  20385. {
  20386. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20387. intData += srcBytesPerSample;
  20388. }
  20389. }
  20390. else
  20391. {
  20392. intData += srcBytesPerSample * numSamples;
  20393. for (int i = numSamples; --i >= 0;)
  20394. {
  20395. intData -= srcBytesPerSample;
  20396. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20397. }
  20398. }
  20399. }
  20400. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20401. {
  20402. const float scale = 1.0f / 0x7fffff;
  20403. const char* intData = static_cast <const char*> (source);
  20404. if (source != (void*) dest || srcBytesPerSample >= 4)
  20405. {
  20406. for (int i = 0; i < numSamples; ++i)
  20407. {
  20408. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20409. intData += srcBytesPerSample;
  20410. }
  20411. }
  20412. else
  20413. {
  20414. intData += srcBytesPerSample * numSamples;
  20415. for (int i = numSamples; --i >= 0;)
  20416. {
  20417. intData -= srcBytesPerSample;
  20418. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20419. }
  20420. }
  20421. }
  20422. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20423. {
  20424. const float scale = 1.0f / 0x7fffff;
  20425. const char* intData = static_cast <const char*> (source);
  20426. if (source != (void*) dest || srcBytesPerSample >= 4)
  20427. {
  20428. for (int i = 0; i < numSamples; ++i)
  20429. {
  20430. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20431. intData += srcBytesPerSample;
  20432. }
  20433. }
  20434. else
  20435. {
  20436. intData += srcBytesPerSample * numSamples;
  20437. for (int i = numSamples; --i >= 0;)
  20438. {
  20439. intData -= srcBytesPerSample;
  20440. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20441. }
  20442. }
  20443. }
  20444. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20445. {
  20446. const float scale = 1.0f / 0x7fffffff;
  20447. const char* intData = static_cast <const char*> (source);
  20448. if (source != (void*) dest || srcBytesPerSample >= 4)
  20449. {
  20450. for (int i = 0; i < numSamples; ++i)
  20451. {
  20452. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20453. intData += srcBytesPerSample;
  20454. }
  20455. }
  20456. else
  20457. {
  20458. intData += srcBytesPerSample * numSamples;
  20459. for (int i = numSamples; --i >= 0;)
  20460. {
  20461. intData -= srcBytesPerSample;
  20462. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20463. }
  20464. }
  20465. }
  20466. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20467. {
  20468. const float scale = 1.0f / 0x7fffffff;
  20469. const char* intData = static_cast <const char*> (source);
  20470. if (source != (void*) dest || srcBytesPerSample >= 4)
  20471. {
  20472. for (int i = 0; i < numSamples; ++i)
  20473. {
  20474. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20475. intData += srcBytesPerSample;
  20476. }
  20477. }
  20478. else
  20479. {
  20480. intData += srcBytesPerSample * numSamples;
  20481. for (int i = numSamples; --i >= 0;)
  20482. {
  20483. intData -= srcBytesPerSample;
  20484. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20485. }
  20486. }
  20487. }
  20488. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20489. {
  20490. const char* s = static_cast <const char*> (source);
  20491. for (int i = 0; i < numSamples; ++i)
  20492. {
  20493. dest[i] = *(float*)s;
  20494. #if JUCE_BIG_ENDIAN
  20495. uint32* const d = (uint32*) (dest + i);
  20496. *d = ByteOrder::swap (*d);
  20497. #endif
  20498. s += srcBytesPerSample;
  20499. }
  20500. }
  20501. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20502. {
  20503. const char* s = static_cast <const char*> (source);
  20504. for (int i = 0; i < numSamples; ++i)
  20505. {
  20506. dest[i] = *(float*)s;
  20507. #if JUCE_LITTLE_ENDIAN
  20508. uint32* const d = (uint32*) (dest + i);
  20509. *d = ByteOrder::swap (*d);
  20510. #endif
  20511. s += srcBytesPerSample;
  20512. }
  20513. }
  20514. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20515. const float* const source,
  20516. void* const dest,
  20517. const int numSamples)
  20518. {
  20519. switch (destFormat)
  20520. {
  20521. case int16LE:
  20522. convertFloatToInt16LE (source, dest, numSamples);
  20523. break;
  20524. case int16BE:
  20525. convertFloatToInt16BE (source, dest, numSamples);
  20526. break;
  20527. case int24LE:
  20528. convertFloatToInt24LE (source, dest, numSamples);
  20529. break;
  20530. case int24BE:
  20531. convertFloatToInt24BE (source, dest, numSamples);
  20532. break;
  20533. case int32LE:
  20534. convertFloatToInt32LE (source, dest, numSamples);
  20535. break;
  20536. case int32BE:
  20537. convertFloatToInt32BE (source, dest, numSamples);
  20538. break;
  20539. case float32LE:
  20540. convertFloatToFloat32LE (source, dest, numSamples);
  20541. break;
  20542. case float32BE:
  20543. convertFloatToFloat32BE (source, dest, numSamples);
  20544. break;
  20545. default:
  20546. jassertfalse;
  20547. break;
  20548. }
  20549. }
  20550. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20551. const void* const source,
  20552. float* const dest,
  20553. const int numSamples)
  20554. {
  20555. switch (sourceFormat)
  20556. {
  20557. case int16LE:
  20558. convertInt16LEToFloat (source, dest, numSamples);
  20559. break;
  20560. case int16BE:
  20561. convertInt16BEToFloat (source, dest, numSamples);
  20562. break;
  20563. case int24LE:
  20564. convertInt24LEToFloat (source, dest, numSamples);
  20565. break;
  20566. case int24BE:
  20567. convertInt24BEToFloat (source, dest, numSamples);
  20568. break;
  20569. case int32LE:
  20570. convertInt32LEToFloat (source, dest, numSamples);
  20571. break;
  20572. case int32BE:
  20573. convertInt32BEToFloat (source, dest, numSamples);
  20574. break;
  20575. case float32LE:
  20576. convertFloat32LEToFloat (source, dest, numSamples);
  20577. break;
  20578. case float32BE:
  20579. convertFloat32BEToFloat (source, dest, numSamples);
  20580. break;
  20581. default:
  20582. jassertfalse;
  20583. break;
  20584. }
  20585. }
  20586. void AudioDataConverters::interleaveSamples (const float** const source,
  20587. float* const dest,
  20588. const int numSamples,
  20589. const int numChannels)
  20590. {
  20591. for (int chan = 0; chan < numChannels; ++chan)
  20592. {
  20593. int i = chan;
  20594. const float* src = source [chan];
  20595. for (int j = 0; j < numSamples; ++j)
  20596. {
  20597. dest [i] = src [j];
  20598. i += numChannels;
  20599. }
  20600. }
  20601. }
  20602. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20603. float** const dest,
  20604. const int numSamples,
  20605. const int numChannels)
  20606. {
  20607. for (int chan = 0; chan < numChannels; ++chan)
  20608. {
  20609. int i = chan;
  20610. float* dst = dest [chan];
  20611. for (int j = 0; j < numSamples; ++j)
  20612. {
  20613. dst [j] = source [i];
  20614. i += numChannels;
  20615. }
  20616. }
  20617. }
  20618. END_JUCE_NAMESPACE
  20619. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20620. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20621. BEGIN_JUCE_NAMESPACE
  20622. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20623. const int numSamples) throw()
  20624. : numChannels (numChannels_),
  20625. size (numSamples)
  20626. {
  20627. jassert (numSamples >= 0);
  20628. jassert (numChannels_ > 0);
  20629. allocateData();
  20630. }
  20631. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20632. : numChannels (other.numChannels),
  20633. size (other.size)
  20634. {
  20635. allocateData();
  20636. const size_t numBytes = size * sizeof (float);
  20637. for (int i = 0; i < numChannels; ++i)
  20638. memcpy (channels[i], other.channels[i], numBytes);
  20639. }
  20640. void AudioSampleBuffer::allocateData()
  20641. {
  20642. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20643. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20644. allocatedData.malloc (allocatedBytes);
  20645. channels = reinterpret_cast <float**> (allocatedData.getData());
  20646. float* chan = (float*) (allocatedData + channelListSize);
  20647. for (int i = 0; i < numChannels; ++i)
  20648. {
  20649. channels[i] = chan;
  20650. chan += size;
  20651. }
  20652. channels [numChannels] = 0;
  20653. }
  20654. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20655. const int numChannels_,
  20656. const int numSamples) throw()
  20657. : numChannels (numChannels_),
  20658. size (numSamples),
  20659. allocatedBytes (0)
  20660. {
  20661. jassert (numChannels_ > 0);
  20662. allocateChannels (dataToReferTo);
  20663. }
  20664. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20665. const int newNumChannels,
  20666. const int newNumSamples) throw()
  20667. {
  20668. jassert (newNumChannels > 0);
  20669. allocatedBytes = 0;
  20670. allocatedData.free();
  20671. numChannels = newNumChannels;
  20672. size = newNumSamples;
  20673. allocateChannels (dataToReferTo);
  20674. }
  20675. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20676. {
  20677. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20678. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20679. {
  20680. channels = static_cast <float**> (preallocatedChannelSpace);
  20681. }
  20682. else
  20683. {
  20684. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20685. channels = reinterpret_cast <float**> (allocatedData.getData());
  20686. }
  20687. for (int i = 0; i < numChannels; ++i)
  20688. {
  20689. // you have to pass in the same number of valid pointers as numChannels
  20690. jassert (dataToReferTo[i] != 0);
  20691. channels[i] = dataToReferTo[i];
  20692. }
  20693. channels [numChannels] = 0;
  20694. }
  20695. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20696. {
  20697. if (this != &other)
  20698. {
  20699. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20700. const size_t numBytes = size * sizeof (float);
  20701. for (int i = 0; i < numChannels; ++i)
  20702. memcpy (channels[i], other.channels[i], numBytes);
  20703. }
  20704. return *this;
  20705. }
  20706. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20707. {
  20708. }
  20709. void AudioSampleBuffer::setSize (const int newNumChannels,
  20710. const int newNumSamples,
  20711. const bool keepExistingContent,
  20712. const bool clearExtraSpace,
  20713. const bool avoidReallocating) throw()
  20714. {
  20715. jassert (newNumChannels > 0);
  20716. if (newNumSamples != size || newNumChannels != numChannels)
  20717. {
  20718. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20719. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20720. if (keepExistingContent)
  20721. {
  20722. HeapBlock <char> newData;
  20723. newData.allocate (newTotalBytes, clearExtraSpace);
  20724. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20725. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20726. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20727. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20728. for (int i = 0; i < numChansToCopy; ++i)
  20729. {
  20730. memcpy (newChan, channels[i], numBytesToCopy);
  20731. newChannels[i] = newChan;
  20732. newChan += newNumSamples;
  20733. }
  20734. allocatedData.swapWith (newData);
  20735. allocatedBytes = (int) newTotalBytes;
  20736. channels = newChannels;
  20737. }
  20738. else
  20739. {
  20740. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20741. {
  20742. if (clearExtraSpace)
  20743. zeromem (allocatedData, newTotalBytes);
  20744. }
  20745. else
  20746. {
  20747. allocatedBytes = newTotalBytes;
  20748. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20749. channels = reinterpret_cast <float**> (allocatedData.getData());
  20750. }
  20751. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20752. for (int i = 0; i < newNumChannels; ++i)
  20753. {
  20754. channels[i] = chan;
  20755. chan += newNumSamples;
  20756. }
  20757. }
  20758. channels [newNumChannels] = 0;
  20759. size = newNumSamples;
  20760. numChannels = newNumChannels;
  20761. }
  20762. }
  20763. void AudioSampleBuffer::clear() throw()
  20764. {
  20765. for (int i = 0; i < numChannels; ++i)
  20766. zeromem (channels[i], size * sizeof (float));
  20767. }
  20768. void AudioSampleBuffer::clear (const int startSample,
  20769. const int numSamples) throw()
  20770. {
  20771. jassert (startSample >= 0 && startSample + numSamples <= size);
  20772. for (int i = 0; i < numChannels; ++i)
  20773. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20774. }
  20775. void AudioSampleBuffer::clear (const int channel,
  20776. const int startSample,
  20777. const int numSamples) throw()
  20778. {
  20779. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20780. jassert (startSample >= 0 && startSample + numSamples <= size);
  20781. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20782. }
  20783. void AudioSampleBuffer::applyGain (const int channel,
  20784. const int startSample,
  20785. int numSamples,
  20786. const float gain) throw()
  20787. {
  20788. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20789. jassert (startSample >= 0 && startSample + numSamples <= size);
  20790. if (gain != 1.0f)
  20791. {
  20792. float* d = channels [channel] + startSample;
  20793. if (gain == 0.0f)
  20794. {
  20795. zeromem (d, sizeof (float) * numSamples);
  20796. }
  20797. else
  20798. {
  20799. while (--numSamples >= 0)
  20800. *d++ *= gain;
  20801. }
  20802. }
  20803. }
  20804. void AudioSampleBuffer::applyGainRamp (const int channel,
  20805. const int startSample,
  20806. int numSamples,
  20807. float startGain,
  20808. float endGain) throw()
  20809. {
  20810. if (startGain == endGain)
  20811. {
  20812. applyGain (channel, startSample, numSamples, startGain);
  20813. }
  20814. else
  20815. {
  20816. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20817. jassert (startSample >= 0 && startSample + numSamples <= size);
  20818. const float increment = (endGain - startGain) / numSamples;
  20819. float* d = channels [channel] + startSample;
  20820. while (--numSamples >= 0)
  20821. {
  20822. *d++ *= startGain;
  20823. startGain += increment;
  20824. }
  20825. }
  20826. }
  20827. void AudioSampleBuffer::applyGain (const int startSample,
  20828. const int numSamples,
  20829. const float gain) throw()
  20830. {
  20831. for (int i = 0; i < numChannels; ++i)
  20832. applyGain (i, startSample, numSamples, gain);
  20833. }
  20834. void AudioSampleBuffer::addFrom (const int destChannel,
  20835. const int destStartSample,
  20836. const AudioSampleBuffer& source,
  20837. const int sourceChannel,
  20838. const int sourceStartSample,
  20839. int numSamples,
  20840. const float gain) throw()
  20841. {
  20842. jassert (&source != this || sourceChannel != destChannel);
  20843. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20844. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20845. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20846. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20847. if (gain != 0.0f && numSamples > 0)
  20848. {
  20849. float* d = channels [destChannel] + destStartSample;
  20850. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20851. if (gain != 1.0f)
  20852. {
  20853. while (--numSamples >= 0)
  20854. *d++ += gain * *s++;
  20855. }
  20856. else
  20857. {
  20858. while (--numSamples >= 0)
  20859. *d++ += *s++;
  20860. }
  20861. }
  20862. }
  20863. void AudioSampleBuffer::addFrom (const int destChannel,
  20864. const int destStartSample,
  20865. const float* source,
  20866. int numSamples,
  20867. const float gain) throw()
  20868. {
  20869. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20870. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20871. jassert (source != 0);
  20872. if (gain != 0.0f && numSamples > 0)
  20873. {
  20874. float* d = channels [destChannel] + destStartSample;
  20875. if (gain != 1.0f)
  20876. {
  20877. while (--numSamples >= 0)
  20878. *d++ += gain * *source++;
  20879. }
  20880. else
  20881. {
  20882. while (--numSamples >= 0)
  20883. *d++ += *source++;
  20884. }
  20885. }
  20886. }
  20887. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20888. const int destStartSample,
  20889. const float* source,
  20890. int numSamples,
  20891. float startGain,
  20892. const float endGain) throw()
  20893. {
  20894. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20895. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20896. jassert (source != 0);
  20897. if (startGain == endGain)
  20898. {
  20899. addFrom (destChannel,
  20900. destStartSample,
  20901. source,
  20902. numSamples,
  20903. startGain);
  20904. }
  20905. else
  20906. {
  20907. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20908. {
  20909. const float increment = (endGain - startGain) / numSamples;
  20910. float* d = channels [destChannel] + destStartSample;
  20911. while (--numSamples >= 0)
  20912. {
  20913. *d++ += startGain * *source++;
  20914. startGain += increment;
  20915. }
  20916. }
  20917. }
  20918. }
  20919. void AudioSampleBuffer::copyFrom (const int destChannel,
  20920. const int destStartSample,
  20921. const AudioSampleBuffer& source,
  20922. const int sourceChannel,
  20923. const int sourceStartSample,
  20924. int numSamples) throw()
  20925. {
  20926. jassert (&source != this || sourceChannel != destChannel);
  20927. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20928. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20929. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20930. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20931. if (numSamples > 0)
  20932. {
  20933. memcpy (channels [destChannel] + destStartSample,
  20934. source.channels [sourceChannel] + sourceStartSample,
  20935. sizeof (float) * numSamples);
  20936. }
  20937. }
  20938. void AudioSampleBuffer::copyFrom (const int destChannel,
  20939. const int destStartSample,
  20940. const float* source,
  20941. int numSamples) throw()
  20942. {
  20943. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20944. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20945. jassert (source != 0);
  20946. if (numSamples > 0)
  20947. {
  20948. memcpy (channels [destChannel] + destStartSample,
  20949. source,
  20950. sizeof (float) * numSamples);
  20951. }
  20952. }
  20953. void AudioSampleBuffer::copyFrom (const int destChannel,
  20954. const int destStartSample,
  20955. const float* source,
  20956. int numSamples,
  20957. const float gain) throw()
  20958. {
  20959. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20960. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20961. jassert (source != 0);
  20962. if (numSamples > 0)
  20963. {
  20964. float* d = channels [destChannel] + destStartSample;
  20965. if (gain != 1.0f)
  20966. {
  20967. if (gain == 0)
  20968. {
  20969. zeromem (d, sizeof (float) * numSamples);
  20970. }
  20971. else
  20972. {
  20973. while (--numSamples >= 0)
  20974. *d++ = gain * *source++;
  20975. }
  20976. }
  20977. else
  20978. {
  20979. memcpy (d, source, sizeof (float) * numSamples);
  20980. }
  20981. }
  20982. }
  20983. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20984. const int destStartSample,
  20985. const float* source,
  20986. int numSamples,
  20987. float startGain,
  20988. float endGain) throw()
  20989. {
  20990. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20991. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20992. jassert (source != 0);
  20993. if (startGain == endGain)
  20994. {
  20995. copyFrom (destChannel,
  20996. destStartSample,
  20997. source,
  20998. numSamples,
  20999. startGain);
  21000. }
  21001. else
  21002. {
  21003. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21004. {
  21005. const float increment = (endGain - startGain) / numSamples;
  21006. float* d = channels [destChannel] + destStartSample;
  21007. while (--numSamples >= 0)
  21008. {
  21009. *d++ = startGain * *source++;
  21010. startGain += increment;
  21011. }
  21012. }
  21013. }
  21014. }
  21015. void AudioSampleBuffer::findMinMax (const int channel,
  21016. const int startSample,
  21017. int numSamples,
  21018. float& minVal,
  21019. float& maxVal) const throw()
  21020. {
  21021. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21022. jassert (startSample >= 0 && startSample + numSamples <= size);
  21023. if (numSamples <= 0)
  21024. {
  21025. minVal = 0.0f;
  21026. maxVal = 0.0f;
  21027. }
  21028. else
  21029. {
  21030. const float* d = channels [channel] + startSample;
  21031. float mn = *d++;
  21032. float mx = mn;
  21033. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21034. {
  21035. const float samp = *d++;
  21036. if (samp > mx)
  21037. mx = samp;
  21038. if (samp < mn)
  21039. mn = samp;
  21040. }
  21041. maxVal = mx;
  21042. minVal = mn;
  21043. }
  21044. }
  21045. float AudioSampleBuffer::getMagnitude (const int channel,
  21046. const int startSample,
  21047. const int numSamples) const throw()
  21048. {
  21049. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21050. jassert (startSample >= 0 && startSample + numSamples <= size);
  21051. float mn, mx;
  21052. findMinMax (channel, startSample, numSamples, mn, mx);
  21053. return jmax (mn, -mn, mx, -mx);
  21054. }
  21055. float AudioSampleBuffer::getMagnitude (const int startSample,
  21056. const int numSamples) const throw()
  21057. {
  21058. float mag = 0.0f;
  21059. for (int i = 0; i < numChannels; ++i)
  21060. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21061. return mag;
  21062. }
  21063. float AudioSampleBuffer::getRMSLevel (const int channel,
  21064. const int startSample,
  21065. const int numSamples) const throw()
  21066. {
  21067. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21068. jassert (startSample >= 0 && startSample + numSamples <= size);
  21069. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21070. return 0.0f;
  21071. const float* const data = channels [channel] + startSample;
  21072. double sum = 0.0;
  21073. for (int i = 0; i < numSamples; ++i)
  21074. {
  21075. const float sample = data [i];
  21076. sum += sample * sample;
  21077. }
  21078. return (float) std::sqrt (sum / numSamples);
  21079. }
  21080. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21081. const int startSample,
  21082. const int numSamples,
  21083. const int readerStartSample,
  21084. const bool useLeftChan,
  21085. const bool useRightChan) throw()
  21086. {
  21087. jassert (reader != 0);
  21088. jassert (startSample >= 0 && startSample + numSamples <= size);
  21089. if (numSamples > 0)
  21090. {
  21091. int* chans[3];
  21092. if (useLeftChan == useRightChan)
  21093. {
  21094. chans[0] = (int*) getSampleData (0, startSample);
  21095. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21096. }
  21097. else if (useLeftChan || (reader->numChannels == 1))
  21098. {
  21099. chans[0] = (int*) getSampleData (0, startSample);
  21100. chans[1] = 0;
  21101. }
  21102. else if (useRightChan)
  21103. {
  21104. chans[0] = 0;
  21105. chans[1] = (int*) getSampleData (0, startSample);
  21106. }
  21107. chans[2] = 0;
  21108. reader->read (chans, 2, readerStartSample, numSamples, true);
  21109. if (! reader->usesFloatingPointData)
  21110. {
  21111. for (int j = 0; j < 2; ++j)
  21112. {
  21113. float* const d = reinterpret_cast <float*> (chans[j]);
  21114. if (d != 0)
  21115. {
  21116. const float multiplier = 1.0f / 0x7fffffff;
  21117. for (int i = 0; i < numSamples; ++i)
  21118. d[i] = *(int*)(d + i) * multiplier;
  21119. }
  21120. }
  21121. }
  21122. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21123. {
  21124. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21125. memcpy (getSampleData (1, startSample),
  21126. getSampleData (0, startSample),
  21127. sizeof (float) * numSamples);
  21128. }
  21129. }
  21130. }
  21131. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21132. const int startSample,
  21133. const int numSamples) const throw()
  21134. {
  21135. jassert (startSample >= 0 && startSample + numSamples <= size);
  21136. if (numSamples > 0)
  21137. {
  21138. int* chans [3];
  21139. if (writer->isFloatingPoint())
  21140. {
  21141. chans[0] = (int*) getSampleData (0, startSample);
  21142. if (numChannels > 1)
  21143. chans[1] = (int*) getSampleData (1, startSample);
  21144. else
  21145. chans[1] = 0;
  21146. chans[2] = 0;
  21147. writer->write ((const int**) chans, numSamples);
  21148. }
  21149. else
  21150. {
  21151. HeapBlock <int> tempBuffer (numSamples * 2);
  21152. chans[0] = tempBuffer;
  21153. if (numChannels > 1)
  21154. chans[1] = chans[0] + numSamples;
  21155. else
  21156. chans[1] = 0;
  21157. chans[2] = 0;
  21158. for (int j = 0; j < 2; ++j)
  21159. {
  21160. int* const dest = chans[j];
  21161. if (dest != 0)
  21162. {
  21163. const float* const src = channels [j] + startSample;
  21164. for (int i = 0; i < numSamples; ++i)
  21165. {
  21166. const double samp = src[i];
  21167. if (samp <= -1.0)
  21168. dest[i] = std::numeric_limits<int>::min();
  21169. else if (samp >= 1.0)
  21170. dest[i] = std::numeric_limits<int>::max();
  21171. else
  21172. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21173. }
  21174. }
  21175. }
  21176. writer->write ((const int**) chans, numSamples);
  21177. }
  21178. }
  21179. }
  21180. END_JUCE_NAMESPACE
  21181. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21182. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21183. BEGIN_JUCE_NAMESPACE
  21184. IIRFilter::IIRFilter()
  21185. : active (false)
  21186. {
  21187. reset();
  21188. }
  21189. IIRFilter::IIRFilter (const IIRFilter& other)
  21190. : active (other.active)
  21191. {
  21192. const ScopedLock sl (other.processLock);
  21193. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21194. reset();
  21195. }
  21196. IIRFilter::~IIRFilter()
  21197. {
  21198. }
  21199. void IIRFilter::reset() throw()
  21200. {
  21201. const ScopedLock sl (processLock);
  21202. x1 = 0;
  21203. x2 = 0;
  21204. y1 = 0;
  21205. y2 = 0;
  21206. }
  21207. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21208. {
  21209. float out = coefficients[0] * in
  21210. + coefficients[1] * x1
  21211. + coefficients[2] * x2
  21212. - coefficients[4] * y1
  21213. - coefficients[5] * y2;
  21214. #if JUCE_INTEL
  21215. if (! (out < -1.0e-8 || out > 1.0e-8))
  21216. out = 0;
  21217. #endif
  21218. x2 = x1;
  21219. x1 = in;
  21220. y2 = y1;
  21221. y1 = out;
  21222. return out;
  21223. }
  21224. void IIRFilter::processSamples (float* const samples,
  21225. const int numSamples) throw()
  21226. {
  21227. const ScopedLock sl (processLock);
  21228. if (active)
  21229. {
  21230. for (int i = 0; i < numSamples; ++i)
  21231. {
  21232. const float in = samples[i];
  21233. float out = coefficients[0] * in
  21234. + coefficients[1] * x1
  21235. + coefficients[2] * x2
  21236. - coefficients[4] * y1
  21237. - coefficients[5] * y2;
  21238. #if JUCE_INTEL
  21239. if (! (out < -1.0e-8 || out > 1.0e-8))
  21240. out = 0;
  21241. #endif
  21242. x2 = x1;
  21243. x1 = in;
  21244. y2 = y1;
  21245. y1 = out;
  21246. samples[i] = out;
  21247. }
  21248. }
  21249. }
  21250. void IIRFilter::makeLowPass (const double sampleRate,
  21251. const double frequency) throw()
  21252. {
  21253. jassert (sampleRate > 0);
  21254. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21255. const double nSquared = n * n;
  21256. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21257. setCoefficients (c1,
  21258. c1 * 2.0f,
  21259. c1,
  21260. 1.0,
  21261. c1 * 2.0 * (1.0 - nSquared),
  21262. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21263. }
  21264. void IIRFilter::makeHighPass (const double sampleRate,
  21265. const double frequency) throw()
  21266. {
  21267. const double n = tan (double_Pi * frequency / sampleRate);
  21268. const double nSquared = n * n;
  21269. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21270. setCoefficients (c1,
  21271. c1 * -2.0f,
  21272. c1,
  21273. 1.0,
  21274. c1 * 2.0 * (nSquared - 1.0),
  21275. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21276. }
  21277. void IIRFilter::makeLowShelf (const double sampleRate,
  21278. const double cutOffFrequency,
  21279. const double Q,
  21280. const float gainFactor) throw()
  21281. {
  21282. jassert (sampleRate > 0);
  21283. jassert (Q > 0);
  21284. const double A = jmax (0.0f, gainFactor);
  21285. const double aminus1 = A - 1.0;
  21286. const double aplus1 = A + 1.0;
  21287. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21288. const double coso = std::cos (omega);
  21289. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21290. const double aminus1TimesCoso = aminus1 * coso;
  21291. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21292. A * 2.0 * (aminus1 - aplus1 * coso),
  21293. A * (aplus1 - aminus1TimesCoso - beta),
  21294. aplus1 + aminus1TimesCoso + beta,
  21295. -2.0 * (aminus1 + aplus1 * coso),
  21296. aplus1 + aminus1TimesCoso - beta);
  21297. }
  21298. void IIRFilter::makeHighShelf (const double sampleRate,
  21299. const double cutOffFrequency,
  21300. const double Q,
  21301. const float gainFactor) throw()
  21302. {
  21303. jassert (sampleRate > 0);
  21304. jassert (Q > 0);
  21305. const double A = jmax (0.0f, gainFactor);
  21306. const double aminus1 = A - 1.0;
  21307. const double aplus1 = A + 1.0;
  21308. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21309. const double coso = std::cos (omega);
  21310. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21311. const double aminus1TimesCoso = aminus1 * coso;
  21312. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21313. A * -2.0 * (aminus1 + aplus1 * coso),
  21314. A * (aplus1 + aminus1TimesCoso - beta),
  21315. aplus1 - aminus1TimesCoso + beta,
  21316. 2.0 * (aminus1 - aplus1 * coso),
  21317. aplus1 - aminus1TimesCoso - beta);
  21318. }
  21319. void IIRFilter::makeBandPass (const double sampleRate,
  21320. const double centreFrequency,
  21321. const double Q,
  21322. const float gainFactor) throw()
  21323. {
  21324. jassert (sampleRate > 0);
  21325. jassert (Q > 0);
  21326. const double A = jmax (0.0f, gainFactor);
  21327. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21328. const double alpha = 0.5 * std::sin (omega) / Q;
  21329. const double c2 = -2.0 * std::cos (omega);
  21330. const double alphaTimesA = alpha * A;
  21331. const double alphaOverA = alpha / A;
  21332. setCoefficients (1.0 + alphaTimesA,
  21333. c2,
  21334. 1.0 - alphaTimesA,
  21335. 1.0 + alphaOverA,
  21336. c2,
  21337. 1.0 - alphaOverA);
  21338. }
  21339. void IIRFilter::makeInactive() throw()
  21340. {
  21341. const ScopedLock sl (processLock);
  21342. active = false;
  21343. }
  21344. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21345. {
  21346. const ScopedLock sl (processLock);
  21347. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21348. active = other.active;
  21349. }
  21350. void IIRFilter::setCoefficients (double c1,
  21351. double c2,
  21352. double c3,
  21353. double c4,
  21354. double c5,
  21355. double c6) throw()
  21356. {
  21357. const double a = 1.0 / c4;
  21358. c1 *= a;
  21359. c2 *= a;
  21360. c3 *= a;
  21361. c5 *= a;
  21362. c6 *= a;
  21363. const ScopedLock sl (processLock);
  21364. coefficients[0] = (float) c1;
  21365. coefficients[1] = (float) c2;
  21366. coefficients[2] = (float) c3;
  21367. coefficients[3] = (float) c4;
  21368. coefficients[4] = (float) c5;
  21369. coefficients[5] = (float) c6;
  21370. active = true;
  21371. }
  21372. END_JUCE_NAMESPACE
  21373. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21374. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21375. BEGIN_JUCE_NAMESPACE
  21376. MidiBuffer::MidiBuffer() throw()
  21377. : bytesUsed (0)
  21378. {
  21379. }
  21380. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21381. : bytesUsed (0)
  21382. {
  21383. addEvent (message, 0);
  21384. }
  21385. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21386. : data (other.data),
  21387. bytesUsed (other.bytesUsed)
  21388. {
  21389. }
  21390. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21391. {
  21392. bytesUsed = other.bytesUsed;
  21393. data = other.data;
  21394. return *this;
  21395. }
  21396. void MidiBuffer::swapWith (MidiBuffer& other)
  21397. {
  21398. data.swapWith (other.data);
  21399. swapVariables <int> (bytesUsed, other.bytesUsed);
  21400. }
  21401. MidiBuffer::~MidiBuffer() throw()
  21402. {
  21403. }
  21404. inline uint8* MidiBuffer::getData() const throw()
  21405. {
  21406. return static_cast <uint8*> (data.getData());
  21407. }
  21408. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21409. {
  21410. return *static_cast <const int*> (d);
  21411. }
  21412. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21413. {
  21414. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21415. }
  21416. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21417. {
  21418. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21419. }
  21420. void MidiBuffer::clear() throw()
  21421. {
  21422. bytesUsed = 0;
  21423. }
  21424. void MidiBuffer::clear (const int startSample,
  21425. const int numSamples) throw()
  21426. {
  21427. uint8* const start = findEventAfter (getData(), startSample - 1);
  21428. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21429. if (end > start)
  21430. {
  21431. const int bytesToMove = bytesUsed - (int) (end - getData());
  21432. if (bytesToMove > 0)
  21433. memmove (start, end, bytesToMove);
  21434. bytesUsed -= (int) (end - start);
  21435. }
  21436. }
  21437. void MidiBuffer::addEvent (const MidiMessage& m,
  21438. const int sampleNumber) throw()
  21439. {
  21440. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21441. }
  21442. static int findActualEventLength (const uint8* const data,
  21443. const int maxBytes) throw()
  21444. {
  21445. unsigned int byte = (unsigned int) *data;
  21446. int size = 0;
  21447. if (byte == 0xf0 || byte == 0xf7)
  21448. {
  21449. const uint8* d = data + 1;
  21450. while (d < data + maxBytes)
  21451. if (*d++ == 0xf7)
  21452. break;
  21453. size = (int) (d - data);
  21454. }
  21455. else if (byte == 0xff)
  21456. {
  21457. int n;
  21458. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21459. size = jmin (maxBytes, n + 2 + bytesLeft);
  21460. }
  21461. else if (byte >= 0x80)
  21462. {
  21463. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21464. }
  21465. return size;
  21466. }
  21467. void MidiBuffer::addEvent (const uint8* const newData,
  21468. const int maxBytes,
  21469. const int sampleNumber) throw()
  21470. {
  21471. const int numBytes = findActualEventLength (newData, maxBytes);
  21472. if (numBytes > 0)
  21473. {
  21474. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21475. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21476. uint8* d = findEventAfter (getData(), sampleNumber);
  21477. const int bytesToMove = bytesUsed - (int) (d - getData());
  21478. if (bytesToMove > 0)
  21479. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21480. *reinterpret_cast <int*> (d) = sampleNumber;
  21481. d += sizeof (int);
  21482. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21483. d += sizeof (uint16);
  21484. memcpy (d, newData, numBytes);
  21485. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21486. }
  21487. }
  21488. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21489. const int startSample,
  21490. const int numSamples,
  21491. const int sampleDeltaToAdd) throw()
  21492. {
  21493. Iterator i (otherBuffer);
  21494. i.setNextSamplePosition (startSample);
  21495. const uint8* eventData;
  21496. int eventSize, position;
  21497. while (i.getNextEvent (eventData, eventSize, position)
  21498. && (position < startSample + numSamples || numSamples < 0))
  21499. {
  21500. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21501. }
  21502. }
  21503. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21504. {
  21505. data.ensureSize (minimumNumBytes);
  21506. }
  21507. bool MidiBuffer::isEmpty() const throw()
  21508. {
  21509. return bytesUsed == 0;
  21510. }
  21511. int MidiBuffer::getNumEvents() const throw()
  21512. {
  21513. int n = 0;
  21514. const uint8* d = getData();
  21515. const uint8* const end = d + bytesUsed;
  21516. while (d < end)
  21517. {
  21518. d += getEventTotalSize (d);
  21519. ++n;
  21520. }
  21521. return n;
  21522. }
  21523. int MidiBuffer::getFirstEventTime() const throw()
  21524. {
  21525. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21526. }
  21527. int MidiBuffer::getLastEventTime() const throw()
  21528. {
  21529. if (bytesUsed == 0)
  21530. return 0;
  21531. const uint8* d = getData();
  21532. const uint8* const endData = d + bytesUsed;
  21533. for (;;)
  21534. {
  21535. const uint8* const nextOne = d + getEventTotalSize (d);
  21536. if (nextOne >= endData)
  21537. return getEventTime (d);
  21538. d = nextOne;
  21539. }
  21540. }
  21541. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21542. {
  21543. const uint8* const endData = getData() + bytesUsed;
  21544. while (d < endData && getEventTime (d) <= samplePosition)
  21545. d += getEventTotalSize (d);
  21546. return d;
  21547. }
  21548. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21549. : buffer (buffer_),
  21550. data (buffer_.getData())
  21551. {
  21552. }
  21553. MidiBuffer::Iterator::~Iterator() throw()
  21554. {
  21555. }
  21556. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21557. {
  21558. data = buffer.getData();
  21559. const uint8* dataEnd = data + buffer.bytesUsed;
  21560. while (data < dataEnd && getEventTime (data) < samplePosition)
  21561. data += getEventTotalSize (data);
  21562. }
  21563. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21564. {
  21565. if (data >= buffer.getData() + buffer.bytesUsed)
  21566. return false;
  21567. samplePosition = getEventTime (data);
  21568. numBytes = getEventDataSize (data);
  21569. data += sizeof (int) + sizeof (uint16);
  21570. midiData = data;
  21571. data += numBytes;
  21572. return true;
  21573. }
  21574. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21575. {
  21576. if (data >= buffer.getData() + buffer.bytesUsed)
  21577. return false;
  21578. samplePosition = getEventTime (data);
  21579. const int numBytes = getEventDataSize (data);
  21580. data += sizeof (int) + sizeof (uint16);
  21581. result = MidiMessage (data, numBytes, samplePosition);
  21582. data += numBytes;
  21583. return true;
  21584. }
  21585. END_JUCE_NAMESPACE
  21586. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21587. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21588. BEGIN_JUCE_NAMESPACE
  21589. namespace MidiFileHelpers
  21590. {
  21591. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21592. {
  21593. unsigned int buffer = v & 0x7F;
  21594. while ((v >>= 7) != 0)
  21595. {
  21596. buffer <<= 8;
  21597. buffer |= ((v & 0x7F) | 0x80);
  21598. }
  21599. for (;;)
  21600. {
  21601. out.writeByte ((char) buffer);
  21602. if (buffer & 0x80)
  21603. buffer >>= 8;
  21604. else
  21605. break;
  21606. }
  21607. }
  21608. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21609. {
  21610. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21611. data += 4;
  21612. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21613. {
  21614. bool ok = false;
  21615. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21616. {
  21617. for (int i = 0; i < 8; ++i)
  21618. {
  21619. ch = ByteOrder::bigEndianInt (data);
  21620. data += 4;
  21621. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21622. {
  21623. ok = true;
  21624. break;
  21625. }
  21626. }
  21627. }
  21628. if (! ok)
  21629. return false;
  21630. }
  21631. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21632. data += 4;
  21633. fileType = (short) ByteOrder::bigEndianShort (data);
  21634. data += 2;
  21635. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21636. data += 2;
  21637. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21638. data += 2;
  21639. bytesRemaining -= 6;
  21640. data += bytesRemaining;
  21641. return true;
  21642. }
  21643. static double convertTicksToSeconds (const double time,
  21644. const MidiMessageSequence& tempoEvents,
  21645. const int timeFormat)
  21646. {
  21647. if (timeFormat > 0)
  21648. {
  21649. int numer = 4, denom = 4;
  21650. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21651. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21652. double secsPerTick = 0.5 * tickLen;
  21653. const int numEvents = tempoEvents.getNumEvents();
  21654. for (int i = 0; i < numEvents; ++i)
  21655. {
  21656. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21657. if (time <= m.getTimeStamp())
  21658. break;
  21659. if (timeFormat > 0)
  21660. {
  21661. correctedTempoTime = correctedTempoTime
  21662. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21663. }
  21664. else
  21665. {
  21666. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21667. }
  21668. tempoTime = m.getTimeStamp();
  21669. if (m.isTempoMetaEvent())
  21670. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21671. else if (m.isTimeSignatureMetaEvent())
  21672. m.getTimeSignatureInfo (numer, denom);
  21673. while (i + 1 < numEvents)
  21674. {
  21675. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21676. if (m2.getTimeStamp() == tempoTime)
  21677. {
  21678. ++i;
  21679. if (m2.isTempoMetaEvent())
  21680. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21681. else if (m2.isTimeSignatureMetaEvent())
  21682. m2.getTimeSignatureInfo (numer, denom);
  21683. }
  21684. else
  21685. {
  21686. break;
  21687. }
  21688. }
  21689. }
  21690. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21691. }
  21692. else
  21693. {
  21694. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21695. }
  21696. }
  21697. }
  21698. MidiFile::MidiFile()
  21699. : timeFormat ((short) (unsigned short) 0xe728)
  21700. {
  21701. }
  21702. MidiFile::~MidiFile()
  21703. {
  21704. clear();
  21705. }
  21706. void MidiFile::clear()
  21707. {
  21708. tracks.clear();
  21709. }
  21710. int MidiFile::getNumTracks() const throw()
  21711. {
  21712. return tracks.size();
  21713. }
  21714. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21715. {
  21716. return tracks [index];
  21717. }
  21718. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21719. {
  21720. tracks.add (new MidiMessageSequence (trackSequence));
  21721. }
  21722. short MidiFile::getTimeFormat() const throw()
  21723. {
  21724. return timeFormat;
  21725. }
  21726. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21727. {
  21728. timeFormat = (short) ticks;
  21729. }
  21730. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21731. const int subframeResolution) throw()
  21732. {
  21733. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21734. }
  21735. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21736. {
  21737. for (int i = tracks.size(); --i >= 0;)
  21738. {
  21739. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21740. for (int j = 0; j < numEvents; ++j)
  21741. {
  21742. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21743. if (m.isTempoMetaEvent())
  21744. tempoChangeEvents.addEvent (m);
  21745. }
  21746. }
  21747. }
  21748. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21749. {
  21750. for (int i = tracks.size(); --i >= 0;)
  21751. {
  21752. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21753. for (int j = 0; j < numEvents; ++j)
  21754. {
  21755. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21756. if (m.isTimeSignatureMetaEvent())
  21757. timeSigEvents.addEvent (m);
  21758. }
  21759. }
  21760. }
  21761. double MidiFile::getLastTimestamp() const
  21762. {
  21763. double t = 0.0;
  21764. for (int i = tracks.size(); --i >= 0;)
  21765. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21766. return t;
  21767. }
  21768. bool MidiFile::readFrom (InputStream& sourceStream)
  21769. {
  21770. clear();
  21771. MemoryBlock data;
  21772. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21773. // (put a sanity-check on the file size, as midi files are generally small)
  21774. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21775. {
  21776. size_t size = data.getSize();
  21777. const uint8* d = static_cast <const uint8*> (data.getData());
  21778. short fileType, expectedTracks;
  21779. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21780. {
  21781. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21782. int track = 0;
  21783. while (size > 0 && track < expectedTracks)
  21784. {
  21785. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21786. d += 4;
  21787. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21788. d += 4;
  21789. if (chunkSize <= 0)
  21790. break;
  21791. if (size < 0)
  21792. return false;
  21793. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21794. {
  21795. readNextTrack (d, chunkSize);
  21796. }
  21797. size -= chunkSize + 8;
  21798. d += chunkSize;
  21799. ++track;
  21800. }
  21801. return true;
  21802. }
  21803. }
  21804. return false;
  21805. }
  21806. // a comparator that puts all the note-offs before note-ons that have the same time
  21807. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21808. const MidiMessageSequence::MidiEventHolder* const second)
  21809. {
  21810. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21811. if (diff == 0)
  21812. {
  21813. if (first->message.isNoteOff() && second->message.isNoteOn())
  21814. return -1;
  21815. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21816. return 1;
  21817. else
  21818. return 0;
  21819. }
  21820. else
  21821. {
  21822. return (diff > 0) ? 1 : -1;
  21823. }
  21824. }
  21825. void MidiFile::readNextTrack (const uint8* data, int size)
  21826. {
  21827. double time = 0;
  21828. char lastStatusByte = 0;
  21829. MidiMessageSequence result;
  21830. while (size > 0)
  21831. {
  21832. int bytesUsed;
  21833. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21834. data += bytesUsed;
  21835. size -= bytesUsed;
  21836. time += delay;
  21837. int messSize = 0;
  21838. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21839. if (messSize <= 0)
  21840. break;
  21841. size -= messSize;
  21842. data += messSize;
  21843. result.addEvent (mm);
  21844. const char firstByte = *(mm.getRawData());
  21845. if ((firstByte & 0xf0) != 0xf0)
  21846. lastStatusByte = firstByte;
  21847. }
  21848. // use a sort that puts all the note-offs before note-ons that have the same time
  21849. result.list.sort (*this, true);
  21850. result.updateMatchedPairs();
  21851. addTrack (result);
  21852. }
  21853. void MidiFile::convertTimestampTicksToSeconds()
  21854. {
  21855. MidiMessageSequence tempoEvents;
  21856. findAllTempoEvents (tempoEvents);
  21857. findAllTimeSigEvents (tempoEvents);
  21858. for (int i = 0; i < tracks.size(); ++i)
  21859. {
  21860. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21861. for (int j = ms.getNumEvents(); --j >= 0;)
  21862. {
  21863. MidiMessage& m = ms.getEventPointer(j)->message;
  21864. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21865. tempoEvents,
  21866. timeFormat));
  21867. }
  21868. }
  21869. }
  21870. bool MidiFile::writeTo (OutputStream& out)
  21871. {
  21872. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21873. out.writeIntBigEndian (6);
  21874. out.writeShortBigEndian (1); // type
  21875. out.writeShortBigEndian ((short) tracks.size());
  21876. out.writeShortBigEndian (timeFormat);
  21877. for (int i = 0; i < tracks.size(); ++i)
  21878. writeTrack (out, i);
  21879. out.flush();
  21880. return true;
  21881. }
  21882. void MidiFile::writeTrack (OutputStream& mainOut,
  21883. const int trackNum)
  21884. {
  21885. MemoryOutputStream out;
  21886. const MidiMessageSequence& ms = *tracks[trackNum];
  21887. int lastTick = 0;
  21888. char lastStatusByte = 0;
  21889. for (int i = 0; i < ms.getNumEvents(); ++i)
  21890. {
  21891. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21892. const int tick = roundToInt (mm.getTimeStamp());
  21893. const int delta = jmax (0, tick - lastTick);
  21894. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21895. lastTick = tick;
  21896. const char statusByte = *(mm.getRawData());
  21897. if ((statusByte == lastStatusByte)
  21898. && ((statusByte & 0xf0) != 0xf0)
  21899. && i > 0
  21900. && mm.getRawDataSize() > 1)
  21901. {
  21902. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21903. }
  21904. else
  21905. {
  21906. out.write (mm.getRawData(), mm.getRawDataSize());
  21907. }
  21908. lastStatusByte = statusByte;
  21909. }
  21910. out.writeByte (0);
  21911. const MidiMessage m (MidiMessage::endOfTrack());
  21912. out.write (m.getRawData(),
  21913. m.getRawDataSize());
  21914. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21915. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21916. mainOut.write (out.getData(), (int) out.getDataSize());
  21917. }
  21918. END_JUCE_NAMESPACE
  21919. /*** End of inlined file: juce_MidiFile.cpp ***/
  21920. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21921. BEGIN_JUCE_NAMESPACE
  21922. MidiKeyboardState::MidiKeyboardState()
  21923. {
  21924. zerostruct (noteStates);
  21925. }
  21926. MidiKeyboardState::~MidiKeyboardState()
  21927. {
  21928. }
  21929. void MidiKeyboardState::reset()
  21930. {
  21931. const ScopedLock sl (lock);
  21932. zerostruct (noteStates);
  21933. eventsToAdd.clear();
  21934. }
  21935. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21936. {
  21937. jassert (midiChannel >= 0 && midiChannel <= 16);
  21938. return ((unsigned int) n) < 128
  21939. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21940. }
  21941. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21942. {
  21943. return ((unsigned int) n) < 128
  21944. && (noteStates[n] & midiChannelMask) != 0;
  21945. }
  21946. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21947. {
  21948. jassert (midiChannel >= 0 && midiChannel <= 16);
  21949. jassert (((unsigned int) midiNoteNumber) < 128);
  21950. const ScopedLock sl (lock);
  21951. if (((unsigned int) midiNoteNumber) < 128)
  21952. {
  21953. const int timeNow = (int) Time::getMillisecondCounter();
  21954. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21955. eventsToAdd.clear (0, timeNow - 500);
  21956. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21957. }
  21958. }
  21959. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21960. {
  21961. if (((unsigned int) midiNoteNumber) < 128)
  21962. {
  21963. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21964. for (int i = listeners.size(); --i >= 0;)
  21965. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21966. }
  21967. }
  21968. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21969. {
  21970. const ScopedLock sl (lock);
  21971. if (isNoteOn (midiChannel, midiNoteNumber))
  21972. {
  21973. const int timeNow = (int) Time::getMillisecondCounter();
  21974. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21975. eventsToAdd.clear (0, timeNow - 500);
  21976. noteOffInternal (midiChannel, midiNoteNumber);
  21977. }
  21978. }
  21979. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21980. {
  21981. if (isNoteOn (midiChannel, midiNoteNumber))
  21982. {
  21983. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21984. for (int i = listeners.size(); --i >= 0;)
  21985. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  21986. }
  21987. }
  21988. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21989. {
  21990. const ScopedLock sl (lock);
  21991. if (midiChannel <= 0)
  21992. {
  21993. for (int i = 1; i <= 16; ++i)
  21994. allNotesOff (i);
  21995. }
  21996. else
  21997. {
  21998. for (int i = 0; i < 128; ++i)
  21999. noteOff (midiChannel, i);
  22000. }
  22001. }
  22002. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22003. {
  22004. if (message.isNoteOn())
  22005. {
  22006. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22007. }
  22008. else if (message.isNoteOff())
  22009. {
  22010. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22011. }
  22012. else if (message.isAllNotesOff())
  22013. {
  22014. for (int i = 0; i < 128; ++i)
  22015. noteOffInternal (message.getChannel(), i);
  22016. }
  22017. }
  22018. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22019. const int startSample,
  22020. const int numSamples,
  22021. const bool injectIndirectEvents)
  22022. {
  22023. MidiBuffer::Iterator i (buffer);
  22024. MidiMessage message (0xf4, 0.0);
  22025. int time;
  22026. const ScopedLock sl (lock);
  22027. while (i.getNextEvent (message, time))
  22028. processNextMidiEvent (message);
  22029. if (injectIndirectEvents)
  22030. {
  22031. MidiBuffer::Iterator i2 (eventsToAdd);
  22032. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22033. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22034. while (i2.getNextEvent (message, time))
  22035. {
  22036. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22037. buffer.addEvent (message, startSample + pos);
  22038. }
  22039. }
  22040. eventsToAdd.clear();
  22041. }
  22042. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22043. {
  22044. const ScopedLock sl (lock);
  22045. listeners.addIfNotAlreadyThere (listener);
  22046. }
  22047. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22048. {
  22049. const ScopedLock sl (lock);
  22050. listeners.removeValue (listener);
  22051. }
  22052. END_JUCE_NAMESPACE
  22053. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22054. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22055. BEGIN_JUCE_NAMESPACE
  22056. int MidiMessage::readVariableLengthVal (const uint8* data,
  22057. int& numBytesUsed) throw()
  22058. {
  22059. numBytesUsed = 0;
  22060. int v = 0;
  22061. int i;
  22062. do
  22063. {
  22064. i = (int) *data++;
  22065. if (++numBytesUsed > 6)
  22066. break;
  22067. v = (v << 7) + (i & 0x7f);
  22068. } while (i & 0x80);
  22069. return v;
  22070. }
  22071. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22072. {
  22073. // this method only works for valid starting bytes of a short midi message
  22074. jassert (firstByte >= 0x80
  22075. && firstByte != 0xf0
  22076. && firstByte != 0xf7);
  22077. static const char messageLengths[] =
  22078. {
  22079. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22080. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22081. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22082. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22083. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22084. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22085. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22086. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22087. };
  22088. return messageLengths [firstByte & 0x7f];
  22089. }
  22090. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22091. : timeStamp (t),
  22092. size (dataSize)
  22093. {
  22094. jassert (dataSize > 0);
  22095. if (dataSize <= 4)
  22096. data = static_cast<uint8*> (preallocatedData.asBytes);
  22097. else
  22098. data = new uint8 [dataSize];
  22099. memcpy (data, d, dataSize);
  22100. // check that the length matches the data..
  22101. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22102. }
  22103. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22104. : timeStamp (t),
  22105. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22106. size (1)
  22107. {
  22108. data[0] = (uint8) byte1;
  22109. // check that the length matches the data..
  22110. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22111. }
  22112. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22113. : timeStamp (t),
  22114. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22115. size (2)
  22116. {
  22117. data[0] = (uint8) byte1;
  22118. data[1] = (uint8) byte2;
  22119. // check that the length matches the data..
  22120. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22121. }
  22122. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22123. : timeStamp (t),
  22124. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22125. size (3)
  22126. {
  22127. data[0] = (uint8) byte1;
  22128. data[1] = (uint8) byte2;
  22129. data[2] = (uint8) byte3;
  22130. // check that the length matches the data..
  22131. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22132. }
  22133. MidiMessage::MidiMessage (const MidiMessage& other)
  22134. : timeStamp (other.timeStamp),
  22135. size (other.size)
  22136. {
  22137. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22138. {
  22139. data = new uint8 [size];
  22140. memcpy (data, other.data, size);
  22141. }
  22142. else
  22143. {
  22144. data = static_cast<uint8*> (preallocatedData.asBytes);
  22145. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22146. }
  22147. }
  22148. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22149. : timeStamp (newTimeStamp),
  22150. size (other.size)
  22151. {
  22152. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22153. {
  22154. data = new uint8 [size];
  22155. memcpy (data, other.data, size);
  22156. }
  22157. else
  22158. {
  22159. data = static_cast<uint8*> (preallocatedData.asBytes);
  22160. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22161. }
  22162. }
  22163. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22164. : timeStamp (t),
  22165. data (static_cast<uint8*> (preallocatedData.asBytes))
  22166. {
  22167. const uint8* src = static_cast <const uint8*> (src_);
  22168. unsigned int byte = (unsigned int) *src;
  22169. if (byte < 0x80)
  22170. {
  22171. byte = (unsigned int) (uint8) lastStatusByte;
  22172. numBytesUsed = -1;
  22173. }
  22174. else
  22175. {
  22176. numBytesUsed = 0;
  22177. --sz;
  22178. ++src;
  22179. }
  22180. if (byte >= 0x80)
  22181. {
  22182. if (byte == 0xf0)
  22183. {
  22184. const uint8* d = src;
  22185. while (d < src + sz)
  22186. {
  22187. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22188. {
  22189. if (*d == 0xf7) // include an 0xf7 if we hit one
  22190. ++d;
  22191. break;
  22192. }
  22193. ++d;
  22194. }
  22195. size = 1 + (int) (d - src);
  22196. data = new uint8 [size];
  22197. *data = (uint8) byte;
  22198. memcpy (data + 1, src, size - 1);
  22199. }
  22200. else if (byte == 0xff)
  22201. {
  22202. int n;
  22203. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22204. size = jmin (sz + 1, n + 2 + bytesLeft);
  22205. data = new uint8 [size];
  22206. *data = (uint8) byte;
  22207. memcpy (data + 1, src, size - 1);
  22208. }
  22209. else
  22210. {
  22211. preallocatedData.asInt32 = 0;
  22212. size = getMessageLengthFromFirstByte ((uint8) byte);
  22213. data[0] = (uint8) byte;
  22214. if (size > 1)
  22215. {
  22216. data[1] = src[0];
  22217. if (size > 2)
  22218. data[2] = src[1];
  22219. }
  22220. }
  22221. numBytesUsed += size;
  22222. }
  22223. else
  22224. {
  22225. preallocatedData.asInt32 = 0;
  22226. size = 0;
  22227. }
  22228. }
  22229. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22230. {
  22231. if (this != &other)
  22232. {
  22233. timeStamp = other.timeStamp;
  22234. size = other.size;
  22235. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22236. delete[] data;
  22237. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22238. {
  22239. data = new uint8 [size];
  22240. memcpy (data, other.data, size);
  22241. }
  22242. else
  22243. {
  22244. data = static_cast<uint8*> (preallocatedData.asBytes);
  22245. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22246. }
  22247. }
  22248. return *this;
  22249. }
  22250. MidiMessage::~MidiMessage()
  22251. {
  22252. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22253. delete[] data;
  22254. }
  22255. int MidiMessage::getChannel() const throw()
  22256. {
  22257. if ((data[0] & 0xf0) != 0xf0)
  22258. return (data[0] & 0xf) + 1;
  22259. else
  22260. return 0;
  22261. }
  22262. bool MidiMessage::isForChannel (const int channel) const throw()
  22263. {
  22264. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22265. return ((data[0] & 0xf) == channel - 1)
  22266. && ((data[0] & 0xf0) != 0xf0);
  22267. }
  22268. void MidiMessage::setChannel (const int channel) throw()
  22269. {
  22270. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22271. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22272. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22273. | (uint8)(channel - 1));
  22274. }
  22275. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22276. {
  22277. return ((data[0] & 0xf0) == 0x90)
  22278. && (returnTrueForVelocity0 || data[2] != 0);
  22279. }
  22280. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22281. {
  22282. return ((data[0] & 0xf0) == 0x80)
  22283. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22284. }
  22285. bool MidiMessage::isNoteOnOrOff() const throw()
  22286. {
  22287. const int d = data[0] & 0xf0;
  22288. return (d == 0x90) || (d == 0x80);
  22289. }
  22290. int MidiMessage::getNoteNumber() const throw()
  22291. {
  22292. return data[1];
  22293. }
  22294. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22295. {
  22296. if (isNoteOnOrOff())
  22297. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22298. }
  22299. uint8 MidiMessage::getVelocity() const throw()
  22300. {
  22301. if (isNoteOnOrOff())
  22302. return data[2];
  22303. else
  22304. return 0;
  22305. }
  22306. float MidiMessage::getFloatVelocity() const throw()
  22307. {
  22308. return getVelocity() * (1.0f / 127.0f);
  22309. }
  22310. void MidiMessage::setVelocity (const float newVelocity) throw()
  22311. {
  22312. if (isNoteOnOrOff())
  22313. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22314. }
  22315. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22316. {
  22317. if (isNoteOnOrOff())
  22318. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22319. }
  22320. bool MidiMessage::isAftertouch() const throw()
  22321. {
  22322. return (data[0] & 0xf0) == 0xa0;
  22323. }
  22324. int MidiMessage::getAfterTouchValue() const throw()
  22325. {
  22326. return data[2];
  22327. }
  22328. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22329. const int noteNum,
  22330. const int aftertouchValue) throw()
  22331. {
  22332. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22333. jassert (((unsigned int) noteNum) <= 127);
  22334. jassert (((unsigned int) aftertouchValue) <= 127);
  22335. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22336. noteNum & 0x7f,
  22337. aftertouchValue & 0x7f);
  22338. }
  22339. bool MidiMessage::isChannelPressure() const throw()
  22340. {
  22341. return (data[0] & 0xf0) == 0xd0;
  22342. }
  22343. int MidiMessage::getChannelPressureValue() const throw()
  22344. {
  22345. jassert (isChannelPressure());
  22346. return data[1];
  22347. }
  22348. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22349. const int pressure) throw()
  22350. {
  22351. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22352. jassert (((unsigned int) pressure) <= 127);
  22353. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22354. pressure & 0x7f);
  22355. }
  22356. bool MidiMessage::isProgramChange() const throw()
  22357. {
  22358. return (data[0] & 0xf0) == 0xc0;
  22359. }
  22360. int MidiMessage::getProgramChangeNumber() const throw()
  22361. {
  22362. return data[1];
  22363. }
  22364. const MidiMessage MidiMessage::programChange (const int channel,
  22365. const int programNumber) throw()
  22366. {
  22367. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22368. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22369. programNumber & 0x7f);
  22370. }
  22371. bool MidiMessage::isPitchWheel() const throw()
  22372. {
  22373. return (data[0] & 0xf0) == 0xe0;
  22374. }
  22375. int MidiMessage::getPitchWheelValue() const throw()
  22376. {
  22377. return data[1] | (data[2] << 7);
  22378. }
  22379. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22380. const int position) throw()
  22381. {
  22382. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22383. jassert (((unsigned int) position) <= 0x3fff);
  22384. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22385. position & 127,
  22386. (position >> 7) & 127);
  22387. }
  22388. bool MidiMessage::isController() const throw()
  22389. {
  22390. return (data[0] & 0xf0) == 0xb0;
  22391. }
  22392. int MidiMessage::getControllerNumber() const throw()
  22393. {
  22394. jassert (isController());
  22395. return data[1];
  22396. }
  22397. int MidiMessage::getControllerValue() const throw()
  22398. {
  22399. jassert (isController());
  22400. return data[2];
  22401. }
  22402. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22403. const int controllerType,
  22404. const int value) throw()
  22405. {
  22406. // the channel must be between 1 and 16 inclusive
  22407. jassert (channel > 0 && channel <= 16);
  22408. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22409. controllerType & 127,
  22410. value & 127);
  22411. }
  22412. const MidiMessage MidiMessage::noteOn (const int channel,
  22413. const int noteNumber,
  22414. const float velocity) throw()
  22415. {
  22416. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22417. }
  22418. const MidiMessage MidiMessage::noteOn (const int channel,
  22419. const int noteNumber,
  22420. const uint8 velocity) throw()
  22421. {
  22422. jassert (channel > 0 && channel <= 16);
  22423. jassert (((unsigned int) noteNumber) <= 127);
  22424. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22425. noteNumber & 127,
  22426. jlimit (0, 127, roundToInt (velocity)));
  22427. }
  22428. const MidiMessage MidiMessage::noteOff (const int channel,
  22429. const int noteNumber) throw()
  22430. {
  22431. jassert (channel > 0 && channel <= 16);
  22432. jassert (((unsigned int) noteNumber) <= 127);
  22433. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22434. }
  22435. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22436. {
  22437. jassert (channel > 0 && channel <= 16);
  22438. return controllerEvent (channel, 123, 0);
  22439. }
  22440. bool MidiMessage::isAllNotesOff() const throw()
  22441. {
  22442. return (data[0] & 0xf0) == 0xb0
  22443. && data[1] == 123;
  22444. }
  22445. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22446. {
  22447. return controllerEvent (channel, 120, 0);
  22448. }
  22449. bool MidiMessage::isAllSoundOff() const throw()
  22450. {
  22451. return (data[0] & 0xf0) == 0xb0
  22452. && data[1] == 120;
  22453. }
  22454. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22455. {
  22456. return controllerEvent (channel, 121, 0);
  22457. }
  22458. const MidiMessage MidiMessage::masterVolume (const float volume)
  22459. {
  22460. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22461. uint8 buf[8];
  22462. buf[0] = 0xf0;
  22463. buf[1] = 0x7f;
  22464. buf[2] = 0x7f;
  22465. buf[3] = 0x04;
  22466. buf[4] = 0x01;
  22467. buf[5] = (uint8) (vol & 0x7f);
  22468. buf[6] = (uint8) (vol >> 7);
  22469. buf[7] = 0xf7;
  22470. return MidiMessage (buf, 8);
  22471. }
  22472. bool MidiMessage::isSysEx() const throw()
  22473. {
  22474. return *data == 0xf0;
  22475. }
  22476. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22477. {
  22478. MemoryBlock mm (dataSize + 2);
  22479. uint8* const m = static_cast <uint8*> (mm.getData());
  22480. m[0] = 0xf0;
  22481. memcpy (m + 1, sysexData, dataSize);
  22482. m[dataSize + 1] = 0xf7;
  22483. return MidiMessage (m, dataSize + 2);
  22484. }
  22485. const uint8* MidiMessage::getSysExData() const throw()
  22486. {
  22487. return (isSysEx()) ? getRawData() + 1 : 0;
  22488. }
  22489. int MidiMessage::getSysExDataSize() const throw()
  22490. {
  22491. return (isSysEx()) ? size - 2 : 0;
  22492. }
  22493. bool MidiMessage::isMetaEvent() const throw()
  22494. {
  22495. return *data == 0xff;
  22496. }
  22497. bool MidiMessage::isActiveSense() const throw()
  22498. {
  22499. return *data == 0xfe;
  22500. }
  22501. int MidiMessage::getMetaEventType() const throw()
  22502. {
  22503. if (*data != 0xff)
  22504. return -1;
  22505. else
  22506. return data[1];
  22507. }
  22508. int MidiMessage::getMetaEventLength() const throw()
  22509. {
  22510. if (*data == 0xff)
  22511. {
  22512. int n;
  22513. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22514. }
  22515. return 0;
  22516. }
  22517. const uint8* MidiMessage::getMetaEventData() const throw()
  22518. {
  22519. int n;
  22520. const uint8* d = data + 2;
  22521. readVariableLengthVal (d, n);
  22522. return d + n;
  22523. }
  22524. bool MidiMessage::isTrackMetaEvent() const throw()
  22525. {
  22526. return getMetaEventType() == 0;
  22527. }
  22528. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22529. {
  22530. return getMetaEventType() == 47;
  22531. }
  22532. bool MidiMessage::isTextMetaEvent() const throw()
  22533. {
  22534. const int t = getMetaEventType();
  22535. return t > 0 && t < 16;
  22536. }
  22537. const String MidiMessage::getTextFromTextMetaEvent() const
  22538. {
  22539. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22540. }
  22541. bool MidiMessage::isTrackNameEvent() const throw()
  22542. {
  22543. return (data[1] == 3)
  22544. && (*data == 0xff);
  22545. }
  22546. bool MidiMessage::isTempoMetaEvent() const throw()
  22547. {
  22548. return (data[1] == 81)
  22549. && (*data == 0xff);
  22550. }
  22551. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22552. {
  22553. return (data[1] == 0x20)
  22554. && (*data == 0xff)
  22555. && (data[2] == 1);
  22556. }
  22557. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22558. {
  22559. return data[3] + 1;
  22560. }
  22561. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22562. {
  22563. if (! isTempoMetaEvent())
  22564. return 0.0;
  22565. const uint8* const d = getMetaEventData();
  22566. return (((unsigned int) d[0] << 16)
  22567. | ((unsigned int) d[1] << 8)
  22568. | d[2])
  22569. / 1000000.0;
  22570. }
  22571. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22572. {
  22573. if (timeFormat > 0)
  22574. {
  22575. if (! isTempoMetaEvent())
  22576. return 0.5 / timeFormat;
  22577. return getTempoSecondsPerQuarterNote() / timeFormat;
  22578. }
  22579. else
  22580. {
  22581. const int frameCode = (-timeFormat) >> 8;
  22582. double framesPerSecond;
  22583. switch (frameCode)
  22584. {
  22585. case 24: framesPerSecond = 24.0; break;
  22586. case 25: framesPerSecond = 25.0; break;
  22587. case 29: framesPerSecond = 29.97; break;
  22588. case 30: framesPerSecond = 30.0; break;
  22589. default: framesPerSecond = 30.0; break;
  22590. }
  22591. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22592. }
  22593. }
  22594. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22595. {
  22596. uint8 d[8];
  22597. d[0] = 0xff;
  22598. d[1] = 81;
  22599. d[2] = 3;
  22600. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22601. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22602. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22603. return MidiMessage (d, 6, 0.0);
  22604. }
  22605. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22606. {
  22607. return (data[1] == 0x58)
  22608. && (*data == (uint8) 0xff);
  22609. }
  22610. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22611. {
  22612. if (isTimeSignatureMetaEvent())
  22613. {
  22614. const uint8* const d = getMetaEventData();
  22615. numerator = d[0];
  22616. denominator = 1 << d[1];
  22617. }
  22618. else
  22619. {
  22620. numerator = 4;
  22621. denominator = 4;
  22622. }
  22623. }
  22624. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22625. {
  22626. uint8 d[8];
  22627. d[0] = 0xff;
  22628. d[1] = 0x58;
  22629. d[2] = 0x04;
  22630. d[3] = (uint8) numerator;
  22631. int n = 1;
  22632. int powerOfTwo = 0;
  22633. while (n < denominator)
  22634. {
  22635. n <<= 1;
  22636. ++powerOfTwo;
  22637. }
  22638. d[4] = (uint8) powerOfTwo;
  22639. d[5] = 0x01;
  22640. d[6] = 96;
  22641. return MidiMessage (d, 7, 0.0);
  22642. }
  22643. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22644. {
  22645. uint8 d[8];
  22646. d[0] = 0xff;
  22647. d[1] = 0x20;
  22648. d[2] = 0x01;
  22649. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22650. return MidiMessage (d, 4, 0.0);
  22651. }
  22652. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22653. {
  22654. return getMetaEventType() == 89;
  22655. }
  22656. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22657. {
  22658. return (int) *getMetaEventData();
  22659. }
  22660. const MidiMessage MidiMessage::endOfTrack() throw()
  22661. {
  22662. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22663. }
  22664. bool MidiMessage::isSongPositionPointer() const throw()
  22665. {
  22666. return *data == 0xf2;
  22667. }
  22668. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22669. {
  22670. return data[1] | (data[2] << 7);
  22671. }
  22672. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22673. {
  22674. return MidiMessage (0xf2,
  22675. positionInMidiBeats & 127,
  22676. (positionInMidiBeats >> 7) & 127);
  22677. }
  22678. bool MidiMessage::isMidiStart() const throw()
  22679. {
  22680. return *data == 0xfa;
  22681. }
  22682. const MidiMessage MidiMessage::midiStart() throw()
  22683. {
  22684. return MidiMessage (0xfa);
  22685. }
  22686. bool MidiMessage::isMidiContinue() const throw()
  22687. {
  22688. return *data == 0xfb;
  22689. }
  22690. const MidiMessage MidiMessage::midiContinue() throw()
  22691. {
  22692. return MidiMessage (0xfb);
  22693. }
  22694. bool MidiMessage::isMidiStop() const throw()
  22695. {
  22696. return *data == 0xfc;
  22697. }
  22698. const MidiMessage MidiMessage::midiStop() throw()
  22699. {
  22700. return MidiMessage (0xfc);
  22701. }
  22702. bool MidiMessage::isMidiClock() const throw()
  22703. {
  22704. return *data == 0xf8;
  22705. }
  22706. const MidiMessage MidiMessage::midiClock() throw()
  22707. {
  22708. return MidiMessage (0xf8);
  22709. }
  22710. bool MidiMessage::isQuarterFrame() const throw()
  22711. {
  22712. return *data == 0xf1;
  22713. }
  22714. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22715. {
  22716. return ((int) data[1]) >> 4;
  22717. }
  22718. int MidiMessage::getQuarterFrameValue() const throw()
  22719. {
  22720. return ((int) data[1]) & 0x0f;
  22721. }
  22722. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22723. const int value) throw()
  22724. {
  22725. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22726. }
  22727. bool MidiMessage::isFullFrame() const throw()
  22728. {
  22729. return data[0] == 0xf0
  22730. && data[1] == 0x7f
  22731. && size >= 10
  22732. && data[3] == 0x01
  22733. && data[4] == 0x01;
  22734. }
  22735. void MidiMessage::getFullFrameParameters (int& hours,
  22736. int& minutes,
  22737. int& seconds,
  22738. int& frames,
  22739. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22740. {
  22741. jassert (isFullFrame());
  22742. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22743. hours = data[5] & 0x1f;
  22744. minutes = data[6];
  22745. seconds = data[7];
  22746. frames = data[8];
  22747. }
  22748. const MidiMessage MidiMessage::fullFrame (const int hours,
  22749. const int minutes,
  22750. const int seconds,
  22751. const int frames,
  22752. MidiMessage::SmpteTimecodeType timecodeType)
  22753. {
  22754. uint8 d[10];
  22755. d[0] = 0xf0;
  22756. d[1] = 0x7f;
  22757. d[2] = 0x7f;
  22758. d[3] = 0x01;
  22759. d[4] = 0x01;
  22760. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22761. d[6] = (uint8) minutes;
  22762. d[7] = (uint8) seconds;
  22763. d[8] = (uint8) frames;
  22764. d[9] = 0xf7;
  22765. return MidiMessage (d, 10, 0.0);
  22766. }
  22767. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22768. {
  22769. return data[0] == 0xf0
  22770. && data[1] == 0x7f
  22771. && data[3] == 0x06
  22772. && size > 5;
  22773. }
  22774. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22775. {
  22776. jassert (isMidiMachineControlMessage());
  22777. return (MidiMachineControlCommand) data[4];
  22778. }
  22779. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22780. {
  22781. uint8 d[6];
  22782. d[0] = 0xf0;
  22783. d[1] = 0x7f;
  22784. d[2] = 0x00;
  22785. d[3] = 0x06;
  22786. d[4] = (uint8) command;
  22787. d[5] = 0xf7;
  22788. return MidiMessage (d, 6, 0.0);
  22789. }
  22790. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22791. int& minutes,
  22792. int& seconds,
  22793. int& frames) const throw()
  22794. {
  22795. if (size >= 12
  22796. && data[0] == 0xf0
  22797. && data[1] == 0x7f
  22798. && data[3] == 0x06
  22799. && data[4] == 0x44
  22800. && data[5] == 0x06
  22801. && data[6] == 0x01)
  22802. {
  22803. hours = data[7] % 24; // (that some machines send out hours > 24)
  22804. minutes = data[8];
  22805. seconds = data[9];
  22806. frames = data[10];
  22807. return true;
  22808. }
  22809. return false;
  22810. }
  22811. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22812. int minutes,
  22813. int seconds,
  22814. int frames)
  22815. {
  22816. uint8 d[12];
  22817. d[0] = 0xf0;
  22818. d[1] = 0x7f;
  22819. d[2] = 0x00;
  22820. d[3] = 0x06;
  22821. d[4] = 0x44;
  22822. d[5] = 0x06;
  22823. d[6] = 0x01;
  22824. d[7] = (uint8) hours;
  22825. d[8] = (uint8) minutes;
  22826. d[9] = (uint8) seconds;
  22827. d[10] = (uint8) frames;
  22828. d[11] = 0xf7;
  22829. return MidiMessage (d, 12, 0.0);
  22830. }
  22831. const String MidiMessage::getMidiNoteName (int note,
  22832. bool useSharps,
  22833. bool includeOctaveNumber,
  22834. int octaveNumForMiddleC) throw()
  22835. {
  22836. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22837. "F", "F#", "G", "G#", "A",
  22838. "A#", "B" };
  22839. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22840. "F", "Gb", "G", "Ab", "A",
  22841. "Bb", "B" };
  22842. if (((unsigned int) note) < 128)
  22843. {
  22844. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22845. : flatNoteNames [note % 12]);
  22846. if (includeOctaveNumber)
  22847. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22848. else
  22849. return s;
  22850. }
  22851. return String::empty;
  22852. }
  22853. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22854. {
  22855. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22856. return 440.0 * pow (2.0, noteNumber / 12.0);
  22857. }
  22858. const String MidiMessage::getGMInstrumentName (int n) throw()
  22859. {
  22860. const char *names[] =
  22861. {
  22862. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22863. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22864. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22865. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22866. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22867. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22868. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22869. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22870. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22871. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22872. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22873. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22874. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22875. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22876. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22877. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22878. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22879. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22880. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22881. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22882. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22883. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22884. "Applause", "Gunshot"
  22885. };
  22886. return (((unsigned int) n) < 128) ? names[n]
  22887. : (const char*)0;
  22888. }
  22889. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22890. {
  22891. const char* names[] =
  22892. {
  22893. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22894. "Bass", "Strings", "Ensemble", "Brass",
  22895. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22896. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22897. };
  22898. return (((unsigned int) n) <= 15) ? names[n]
  22899. : (const char*)0;
  22900. }
  22901. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22902. {
  22903. const char* names[] =
  22904. {
  22905. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22906. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22907. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22908. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22909. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22910. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22911. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22912. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22913. "Mute Triangle", "Open Triangle"
  22914. };
  22915. return (n >= 35 && n <= 81) ? names [n - 35]
  22916. : (const char*)0;
  22917. }
  22918. const String MidiMessage::getControllerName (int n) throw()
  22919. {
  22920. const char* names[] =
  22921. {
  22922. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22923. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22924. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22925. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22926. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22927. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22928. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22929. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22930. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22931. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22932. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22933. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22934. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22935. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22936. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22937. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22938. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22939. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22940. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22942. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22943. "Poly Operation"
  22944. };
  22945. return (((unsigned int) n) < 128) ? names[n]
  22946. : (const char*)0;
  22947. }
  22948. END_JUCE_NAMESPACE
  22949. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22950. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22951. BEGIN_JUCE_NAMESPACE
  22952. MidiMessageCollector::MidiMessageCollector()
  22953. : lastCallbackTime (0),
  22954. sampleRate (44100.0001)
  22955. {
  22956. }
  22957. MidiMessageCollector::~MidiMessageCollector()
  22958. {
  22959. }
  22960. void MidiMessageCollector::reset (const double sampleRate_)
  22961. {
  22962. jassert (sampleRate_ > 0);
  22963. const ScopedLock sl (midiCallbackLock);
  22964. sampleRate = sampleRate_;
  22965. incomingMessages.clear();
  22966. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22967. }
  22968. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22969. {
  22970. // you need to call reset() to set the correct sample rate before using this object
  22971. jassert (sampleRate != 44100.0001);
  22972. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22973. // for details of what the number should be.
  22974. jassert (message.getTimeStamp() != 0);
  22975. const ScopedLock sl (midiCallbackLock);
  22976. const int sampleNumber
  22977. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22978. incomingMessages.addEvent (message, sampleNumber);
  22979. // if the messages don't get used for over a second, we'd better
  22980. // get rid of any old ones to avoid the queue getting too big
  22981. if (sampleNumber > sampleRate)
  22982. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22983. }
  22984. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22985. const int numSamples)
  22986. {
  22987. // you need to call reset() to set the correct sample rate before using this object
  22988. jassert (sampleRate != 44100.0001);
  22989. const double timeNow = Time::getMillisecondCounterHiRes();
  22990. const double msElapsed = timeNow - lastCallbackTime;
  22991. const ScopedLock sl (midiCallbackLock);
  22992. lastCallbackTime = timeNow;
  22993. if (! incomingMessages.isEmpty())
  22994. {
  22995. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  22996. int startSample = 0;
  22997. int scale = 1 << 16;
  22998. const uint8* midiData;
  22999. int numBytes, samplePosition;
  23000. MidiBuffer::Iterator iter (incomingMessages);
  23001. if (numSourceSamples > numSamples)
  23002. {
  23003. // if our list of events is longer than the buffer we're being
  23004. // asked for, scale them down to squeeze them all in..
  23005. const int maxBlockLengthToUse = numSamples << 5;
  23006. if (numSourceSamples > maxBlockLengthToUse)
  23007. {
  23008. startSample = numSourceSamples - maxBlockLengthToUse;
  23009. numSourceSamples = maxBlockLengthToUse;
  23010. iter.setNextSamplePosition (startSample);
  23011. }
  23012. scale = (numSamples << 10) / numSourceSamples;
  23013. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23014. {
  23015. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23016. destBuffer.addEvent (midiData, numBytes,
  23017. jlimit (0, numSamples - 1, samplePosition));
  23018. }
  23019. }
  23020. else
  23021. {
  23022. // if our event list is shorter than the number we need, put them
  23023. // towards the end of the buffer
  23024. startSample = numSamples - numSourceSamples;
  23025. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23026. {
  23027. destBuffer.addEvent (midiData, numBytes,
  23028. jlimit (0, numSamples - 1, samplePosition + startSample));
  23029. }
  23030. }
  23031. incomingMessages.clear();
  23032. }
  23033. }
  23034. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23035. {
  23036. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23037. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23038. addMessageToQueue (m);
  23039. }
  23040. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23041. {
  23042. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23043. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23044. addMessageToQueue (m);
  23045. }
  23046. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23047. {
  23048. addMessageToQueue (message);
  23049. }
  23050. END_JUCE_NAMESPACE
  23051. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23052. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23053. BEGIN_JUCE_NAMESPACE
  23054. MidiMessageSequence::MidiMessageSequence()
  23055. {
  23056. }
  23057. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23058. {
  23059. list.ensureStorageAllocated (other.list.size());
  23060. for (int i = 0; i < other.list.size(); ++i)
  23061. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23062. }
  23063. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23064. {
  23065. MidiMessageSequence otherCopy (other);
  23066. swapWith (otherCopy);
  23067. return *this;
  23068. }
  23069. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23070. {
  23071. list.swapWithArray (other.list);
  23072. }
  23073. MidiMessageSequence::~MidiMessageSequence()
  23074. {
  23075. }
  23076. void MidiMessageSequence::clear()
  23077. {
  23078. list.clear();
  23079. }
  23080. int MidiMessageSequence::getNumEvents() const
  23081. {
  23082. return list.size();
  23083. }
  23084. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23085. {
  23086. return list [index];
  23087. }
  23088. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23089. {
  23090. const MidiEventHolder* const meh = list [index];
  23091. if (meh != 0 && meh->noteOffObject != 0)
  23092. return meh->noteOffObject->message.getTimeStamp();
  23093. else
  23094. return 0.0;
  23095. }
  23096. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23097. {
  23098. const MidiEventHolder* const meh = list [index];
  23099. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23100. }
  23101. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23102. {
  23103. return list.indexOf (event);
  23104. }
  23105. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23106. {
  23107. const int numEvents = list.size();
  23108. int i;
  23109. for (i = 0; i < numEvents; ++i)
  23110. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23111. break;
  23112. return i;
  23113. }
  23114. double MidiMessageSequence::getStartTime() const
  23115. {
  23116. if (list.size() > 0)
  23117. return list.getUnchecked(0)->message.getTimeStamp();
  23118. else
  23119. return 0;
  23120. }
  23121. double MidiMessageSequence::getEndTime() const
  23122. {
  23123. if (list.size() > 0)
  23124. return list.getLast()->message.getTimeStamp();
  23125. else
  23126. return 0;
  23127. }
  23128. double MidiMessageSequence::getEventTime (const int index) const
  23129. {
  23130. if (((unsigned int) index) < (unsigned int) list.size())
  23131. return list.getUnchecked (index)->message.getTimeStamp();
  23132. return 0.0;
  23133. }
  23134. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23135. double timeAdjustment)
  23136. {
  23137. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23138. timeAdjustment += newMessage.getTimeStamp();
  23139. newOne->message.setTimeStamp (timeAdjustment);
  23140. int i;
  23141. for (i = list.size(); --i >= 0;)
  23142. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23143. break;
  23144. list.insert (i + 1, newOne);
  23145. }
  23146. void MidiMessageSequence::deleteEvent (const int index,
  23147. const bool deleteMatchingNoteUp)
  23148. {
  23149. if (((unsigned int) index) < (unsigned int) list.size())
  23150. {
  23151. if (deleteMatchingNoteUp)
  23152. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23153. list.remove (index);
  23154. }
  23155. }
  23156. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23157. double timeAdjustment,
  23158. double firstAllowableTime,
  23159. double endOfAllowableDestTimes)
  23160. {
  23161. firstAllowableTime -= timeAdjustment;
  23162. endOfAllowableDestTimes -= timeAdjustment;
  23163. for (int i = 0; i < other.list.size(); ++i)
  23164. {
  23165. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23166. const double t = m.getTimeStamp();
  23167. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23168. {
  23169. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23170. newOne->message.setTimeStamp (timeAdjustment + t);
  23171. list.add (newOne);
  23172. }
  23173. }
  23174. sort();
  23175. }
  23176. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23177. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23178. {
  23179. const double diff = first->message.getTimeStamp()
  23180. - second->message.getTimeStamp();
  23181. return (diff > 0) - (diff < 0);
  23182. }
  23183. void MidiMessageSequence::sort()
  23184. {
  23185. list.sort (*this, true);
  23186. }
  23187. void MidiMessageSequence::updateMatchedPairs()
  23188. {
  23189. for (int i = 0; i < list.size(); ++i)
  23190. {
  23191. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23192. if (m1.isNoteOn())
  23193. {
  23194. list.getUnchecked(i)->noteOffObject = 0;
  23195. const int note = m1.getNoteNumber();
  23196. const int chan = m1.getChannel();
  23197. const int len = list.size();
  23198. for (int j = i + 1; j < len; ++j)
  23199. {
  23200. const MidiMessage& m = list.getUnchecked(j)->message;
  23201. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23202. {
  23203. if (m.isNoteOff())
  23204. {
  23205. list.getUnchecked(i)->noteOffObject = list[j];
  23206. break;
  23207. }
  23208. else if (m.isNoteOn())
  23209. {
  23210. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23211. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23212. list.getUnchecked(i)->noteOffObject = list[j];
  23213. break;
  23214. }
  23215. }
  23216. }
  23217. }
  23218. }
  23219. }
  23220. void MidiMessageSequence::addTimeToMessages (const double delta)
  23221. {
  23222. for (int i = list.size(); --i >= 0;)
  23223. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23224. + delta);
  23225. }
  23226. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23227. MidiMessageSequence& destSequence,
  23228. const bool alsoIncludeMetaEvents) const
  23229. {
  23230. for (int i = 0; i < list.size(); ++i)
  23231. {
  23232. const MidiMessage& mm = list.getUnchecked(i)->message;
  23233. if (mm.isForChannel (channelNumberToExtract)
  23234. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23235. {
  23236. destSequence.addEvent (mm);
  23237. }
  23238. }
  23239. }
  23240. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23241. {
  23242. for (int i = 0; i < list.size(); ++i)
  23243. {
  23244. const MidiMessage& mm = list.getUnchecked(i)->message;
  23245. if (mm.isSysEx())
  23246. destSequence.addEvent (mm);
  23247. }
  23248. }
  23249. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23250. {
  23251. for (int i = list.size(); --i >= 0;)
  23252. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23253. list.remove(i);
  23254. }
  23255. void MidiMessageSequence::deleteSysExMessages()
  23256. {
  23257. for (int i = list.size(); --i >= 0;)
  23258. if (list.getUnchecked(i)->message.isSysEx())
  23259. list.remove(i);
  23260. }
  23261. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23262. const double time,
  23263. OwnedArray<MidiMessage>& dest)
  23264. {
  23265. bool doneProg = false;
  23266. bool donePitchWheel = false;
  23267. Array <int> doneControllers;
  23268. doneControllers.ensureStorageAllocated (32);
  23269. for (int i = list.size(); --i >= 0;)
  23270. {
  23271. const MidiMessage& mm = list.getUnchecked(i)->message;
  23272. if (mm.isForChannel (channelNumber)
  23273. && mm.getTimeStamp() <= time)
  23274. {
  23275. if (mm.isProgramChange())
  23276. {
  23277. if (! doneProg)
  23278. {
  23279. dest.add (new MidiMessage (mm, 0.0));
  23280. doneProg = true;
  23281. }
  23282. }
  23283. else if (mm.isController())
  23284. {
  23285. if (! doneControllers.contains (mm.getControllerNumber()))
  23286. {
  23287. dest.add (new MidiMessage (mm, 0.0));
  23288. doneControllers.add (mm.getControllerNumber());
  23289. }
  23290. }
  23291. else if (mm.isPitchWheel())
  23292. {
  23293. if (! donePitchWheel)
  23294. {
  23295. dest.add (new MidiMessage (mm, 0.0));
  23296. donePitchWheel = true;
  23297. }
  23298. }
  23299. }
  23300. }
  23301. }
  23302. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23303. : message (message_),
  23304. noteOffObject (0)
  23305. {
  23306. }
  23307. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23308. {
  23309. }
  23310. END_JUCE_NAMESPACE
  23311. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23312. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23313. BEGIN_JUCE_NAMESPACE
  23314. AudioPluginFormat::AudioPluginFormat() throw()
  23315. {
  23316. }
  23317. AudioPluginFormat::~AudioPluginFormat()
  23318. {
  23319. }
  23320. END_JUCE_NAMESPACE
  23321. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23322. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23323. BEGIN_JUCE_NAMESPACE
  23324. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23325. {
  23326. }
  23327. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23328. {
  23329. clearSingletonInstance();
  23330. }
  23331. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23332. void AudioPluginFormatManager::addDefaultFormats()
  23333. {
  23334. #if JUCE_DEBUG
  23335. // you should only call this method once!
  23336. for (int i = formats.size(); --i >= 0;)
  23337. {
  23338. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23339. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23340. #endif
  23341. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23342. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23343. #endif
  23344. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23345. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23346. #endif
  23347. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23348. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23349. #endif
  23350. }
  23351. #endif
  23352. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23353. formats.add (new AudioUnitPluginFormat());
  23354. #endif
  23355. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23356. formats.add (new VSTPluginFormat());
  23357. #endif
  23358. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23359. formats.add (new DirectXPluginFormat());
  23360. #endif
  23361. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23362. formats.add (new LADSPAPluginFormat());
  23363. #endif
  23364. }
  23365. int AudioPluginFormatManager::getNumFormats() throw()
  23366. {
  23367. return formats.size();
  23368. }
  23369. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23370. {
  23371. return formats [index];
  23372. }
  23373. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23374. {
  23375. formats.add (format);
  23376. }
  23377. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23378. String& errorMessage) const
  23379. {
  23380. AudioPluginInstance* result = 0;
  23381. for (int i = 0; i < formats.size(); ++i)
  23382. {
  23383. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23384. if (result != 0)
  23385. break;
  23386. }
  23387. if (result == 0)
  23388. {
  23389. if (! doesPluginStillExist (description))
  23390. errorMessage = TRANS ("This plug-in file no longer exists");
  23391. else
  23392. errorMessage = TRANS ("This plug-in failed to load correctly");
  23393. }
  23394. return result;
  23395. }
  23396. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23397. {
  23398. for (int i = 0; i < formats.size(); ++i)
  23399. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23400. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23401. return false;
  23402. }
  23403. END_JUCE_NAMESPACE
  23404. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23405. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23406. #define JUCE_PLUGIN_HOST 1
  23407. BEGIN_JUCE_NAMESPACE
  23408. AudioPluginInstance::AudioPluginInstance()
  23409. {
  23410. }
  23411. AudioPluginInstance::~AudioPluginInstance()
  23412. {
  23413. }
  23414. END_JUCE_NAMESPACE
  23415. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23416. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23417. BEGIN_JUCE_NAMESPACE
  23418. KnownPluginList::KnownPluginList()
  23419. {
  23420. }
  23421. KnownPluginList::~KnownPluginList()
  23422. {
  23423. }
  23424. void KnownPluginList::clear()
  23425. {
  23426. if (types.size() > 0)
  23427. {
  23428. types.clear();
  23429. sendChangeMessage (this);
  23430. }
  23431. }
  23432. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23433. {
  23434. for (int i = 0; i < types.size(); ++i)
  23435. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23436. return types.getUnchecked(i);
  23437. return 0;
  23438. }
  23439. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23440. {
  23441. for (int i = 0; i < types.size(); ++i)
  23442. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23443. return types.getUnchecked(i);
  23444. return 0;
  23445. }
  23446. bool KnownPluginList::addType (const PluginDescription& type)
  23447. {
  23448. for (int i = types.size(); --i >= 0;)
  23449. {
  23450. if (types.getUnchecked(i)->isDuplicateOf (type))
  23451. {
  23452. // strange - found a duplicate plugin with different info..
  23453. jassert (types.getUnchecked(i)->name == type.name);
  23454. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23455. *types.getUnchecked(i) = type;
  23456. return false;
  23457. }
  23458. }
  23459. types.add (new PluginDescription (type));
  23460. sendChangeMessage (this);
  23461. return true;
  23462. }
  23463. void KnownPluginList::removeType (const int index) throw()
  23464. {
  23465. types.remove (index);
  23466. sendChangeMessage (this);
  23467. }
  23468. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23469. {
  23470. if (fileOrIdentifier.startsWithChar ('/')
  23471. || fileOrIdentifier[1] == ':')
  23472. {
  23473. return File (fileOrIdentifier).getLastModificationTime();
  23474. }
  23475. return Time (0);
  23476. }
  23477. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23478. {
  23479. return t1 != t2 || t1 == Time (0);
  23480. }
  23481. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23482. {
  23483. if (getTypeForFile (fileOrIdentifier) == 0)
  23484. return false;
  23485. for (int i = types.size(); --i >= 0;)
  23486. {
  23487. const PluginDescription* const d = types.getUnchecked(i);
  23488. if (d->fileOrIdentifier == fileOrIdentifier
  23489. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23490. {
  23491. return false;
  23492. }
  23493. }
  23494. return true;
  23495. }
  23496. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23497. const bool dontRescanIfAlreadyInList,
  23498. OwnedArray <PluginDescription>& typesFound,
  23499. AudioPluginFormat& format)
  23500. {
  23501. bool addedOne = false;
  23502. if (dontRescanIfAlreadyInList
  23503. && getTypeForFile (fileOrIdentifier) != 0)
  23504. {
  23505. bool needsRescanning = false;
  23506. for (int i = types.size(); --i >= 0;)
  23507. {
  23508. const PluginDescription* const d = types.getUnchecked(i);
  23509. if (d->fileOrIdentifier == fileOrIdentifier)
  23510. {
  23511. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23512. needsRescanning = true;
  23513. else
  23514. typesFound.add (new PluginDescription (*d));
  23515. }
  23516. }
  23517. if (! needsRescanning)
  23518. return false;
  23519. }
  23520. OwnedArray <PluginDescription> found;
  23521. format.findAllTypesForFile (found, fileOrIdentifier);
  23522. for (int i = 0; i < found.size(); ++i)
  23523. {
  23524. PluginDescription* const desc = found.getUnchecked(i);
  23525. jassert (desc != 0);
  23526. if (addType (*desc))
  23527. addedOne = true;
  23528. typesFound.add (new PluginDescription (*desc));
  23529. }
  23530. return addedOne;
  23531. }
  23532. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23533. OwnedArray <PluginDescription>& typesFound)
  23534. {
  23535. for (int i = 0; i < files.size(); ++i)
  23536. {
  23537. bool loaded = false;
  23538. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23539. {
  23540. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23541. if (scanAndAddFile (files[i], true, typesFound, *format))
  23542. loaded = true;
  23543. }
  23544. if (! loaded)
  23545. {
  23546. const File f (files[i]);
  23547. if (f.isDirectory())
  23548. {
  23549. StringArray s;
  23550. {
  23551. Array<File> subFiles;
  23552. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23553. for (int j = 0; j < subFiles.size(); ++j)
  23554. s.add (subFiles.getReference(j).getFullPathName());
  23555. }
  23556. scanAndAddDragAndDroppedFiles (s, typesFound);
  23557. }
  23558. }
  23559. }
  23560. }
  23561. class PluginSorter
  23562. {
  23563. public:
  23564. KnownPluginList::SortMethod method;
  23565. PluginSorter() throw() {}
  23566. int compareElements (const PluginDescription* const first,
  23567. const PluginDescription* const second) const throw()
  23568. {
  23569. int diff = 0;
  23570. if (method == KnownPluginList::sortByCategory)
  23571. diff = first->category.compareLexicographically (second->category);
  23572. else if (method == KnownPluginList::sortByManufacturer)
  23573. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23574. else if (method == KnownPluginList::sortByFileSystemLocation)
  23575. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23576. .upToLastOccurrenceOf ("/", false, false)
  23577. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23578. .upToLastOccurrenceOf ("/", false, false));
  23579. if (diff == 0)
  23580. diff = first->name.compareLexicographically (second->name);
  23581. return diff;
  23582. }
  23583. };
  23584. void KnownPluginList::sort (const SortMethod method)
  23585. {
  23586. if (method != defaultOrder)
  23587. {
  23588. PluginSorter sorter;
  23589. sorter.method = method;
  23590. types.sort (sorter, true);
  23591. sendChangeMessage (this);
  23592. }
  23593. }
  23594. XmlElement* KnownPluginList::createXml() const
  23595. {
  23596. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23597. for (int i = 0; i < types.size(); ++i)
  23598. e->addChildElement (types.getUnchecked(i)->createXml());
  23599. return e;
  23600. }
  23601. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23602. {
  23603. clear();
  23604. if (xml.hasTagName ("KNOWNPLUGINS"))
  23605. {
  23606. forEachXmlChildElement (xml, e)
  23607. {
  23608. PluginDescription info;
  23609. if (info.loadFromXml (*e))
  23610. addType (info);
  23611. }
  23612. }
  23613. }
  23614. const int menuIdBase = 0x324503f4;
  23615. // This is used to turn a bunch of paths into a nested menu structure.
  23616. struct PluginFilesystemTree
  23617. {
  23618. private:
  23619. String folder;
  23620. OwnedArray <PluginFilesystemTree> subFolders;
  23621. Array <PluginDescription*> plugins;
  23622. void addPlugin (PluginDescription* const pd, const String& path)
  23623. {
  23624. if (path.isEmpty())
  23625. {
  23626. plugins.add (pd);
  23627. }
  23628. else
  23629. {
  23630. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23631. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23632. for (int i = subFolders.size(); --i >= 0;)
  23633. {
  23634. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23635. {
  23636. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23637. return;
  23638. }
  23639. }
  23640. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23641. newFolder->folder = firstSubFolder;
  23642. subFolders.add (newFolder);
  23643. newFolder->addPlugin (pd, remainingPath);
  23644. }
  23645. }
  23646. // removes any deeply nested folders that don't contain any actual plugins
  23647. void optimise()
  23648. {
  23649. for (int i = subFolders.size(); --i >= 0;)
  23650. {
  23651. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23652. sub->optimise();
  23653. if (sub->plugins.size() == 0)
  23654. {
  23655. for (int j = 0; j < sub->subFolders.size(); ++j)
  23656. subFolders.add (sub->subFolders.getUnchecked(j));
  23657. sub->subFolders.clear (false);
  23658. subFolders.remove (i);
  23659. }
  23660. }
  23661. }
  23662. public:
  23663. void buildTree (const Array <PluginDescription*>& allPlugins)
  23664. {
  23665. for (int i = 0; i < allPlugins.size(); ++i)
  23666. {
  23667. String path (allPlugins.getUnchecked(i)
  23668. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23669. .upToLastOccurrenceOf ("/", false, false));
  23670. if (path.substring (1, 2) == ":")
  23671. path = path.substring (2);
  23672. addPlugin (allPlugins.getUnchecked(i), path);
  23673. }
  23674. optimise();
  23675. }
  23676. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23677. {
  23678. int i;
  23679. for (i = 0; i < subFolders.size(); ++i)
  23680. {
  23681. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23682. PopupMenu subMenu;
  23683. sub->addToMenu (subMenu, allPlugins);
  23684. #if JUCE_MAC
  23685. // avoid the special AU formatting nonsense on Mac..
  23686. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23687. #else
  23688. m.addSubMenu (sub->folder, subMenu);
  23689. #endif
  23690. }
  23691. for (i = 0; i < plugins.size(); ++i)
  23692. {
  23693. PluginDescription* const plugin = plugins.getUnchecked(i);
  23694. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23695. plugin->name, true, false);
  23696. }
  23697. }
  23698. };
  23699. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23700. {
  23701. Array <PluginDescription*> sorted;
  23702. {
  23703. PluginSorter sorter;
  23704. sorter.method = sortMethod;
  23705. for (int i = 0; i < types.size(); ++i)
  23706. sorted.addSorted (sorter, types.getUnchecked(i));
  23707. }
  23708. if (sortMethod == sortByCategory
  23709. || sortMethod == sortByManufacturer)
  23710. {
  23711. String lastSubMenuName;
  23712. PopupMenu sub;
  23713. for (int i = 0; i < sorted.size(); ++i)
  23714. {
  23715. const PluginDescription* const pd = sorted.getUnchecked(i);
  23716. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23717. : pd->manufacturerName);
  23718. if (! thisSubMenuName.containsNonWhitespaceChars())
  23719. thisSubMenuName = "Other";
  23720. if (thisSubMenuName != lastSubMenuName)
  23721. {
  23722. if (sub.getNumItems() > 0)
  23723. {
  23724. menu.addSubMenu (lastSubMenuName, sub);
  23725. sub.clear();
  23726. }
  23727. lastSubMenuName = thisSubMenuName;
  23728. }
  23729. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23730. }
  23731. if (sub.getNumItems() > 0)
  23732. menu.addSubMenu (lastSubMenuName, sub);
  23733. }
  23734. else if (sortMethod == sortByFileSystemLocation)
  23735. {
  23736. PluginFilesystemTree root;
  23737. root.buildTree (sorted);
  23738. root.addToMenu (menu, types);
  23739. }
  23740. else
  23741. {
  23742. for (int i = 0; i < sorted.size(); ++i)
  23743. {
  23744. const PluginDescription* const pd = sorted.getUnchecked(i);
  23745. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23746. }
  23747. }
  23748. }
  23749. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23750. {
  23751. const int i = menuResultCode - menuIdBase;
  23752. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23753. }
  23754. END_JUCE_NAMESPACE
  23755. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23756. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23757. BEGIN_JUCE_NAMESPACE
  23758. PluginDescription::PluginDescription() throw()
  23759. : uid (0),
  23760. isInstrument (false),
  23761. numInputChannels (0),
  23762. numOutputChannels (0)
  23763. {
  23764. }
  23765. PluginDescription::~PluginDescription() throw()
  23766. {
  23767. }
  23768. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23769. : name (other.name),
  23770. pluginFormatName (other.pluginFormatName),
  23771. category (other.category),
  23772. manufacturerName (other.manufacturerName),
  23773. version (other.version),
  23774. fileOrIdentifier (other.fileOrIdentifier),
  23775. lastFileModTime (other.lastFileModTime),
  23776. uid (other.uid),
  23777. isInstrument (other.isInstrument),
  23778. numInputChannels (other.numInputChannels),
  23779. numOutputChannels (other.numOutputChannels)
  23780. {
  23781. }
  23782. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23783. {
  23784. name = other.name;
  23785. pluginFormatName = other.pluginFormatName;
  23786. category = other.category;
  23787. manufacturerName = other.manufacturerName;
  23788. version = other.version;
  23789. fileOrIdentifier = other.fileOrIdentifier;
  23790. uid = other.uid;
  23791. isInstrument = other.isInstrument;
  23792. lastFileModTime = other.lastFileModTime;
  23793. numInputChannels = other.numInputChannels;
  23794. numOutputChannels = other.numOutputChannels;
  23795. return *this;
  23796. }
  23797. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23798. {
  23799. return fileOrIdentifier == other.fileOrIdentifier
  23800. && uid == other.uid;
  23801. }
  23802. const String PluginDescription::createIdentifierString() const throw()
  23803. {
  23804. return pluginFormatName
  23805. + "-" + name
  23806. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23807. + "-" + String::toHexString (uid);
  23808. }
  23809. XmlElement* PluginDescription::createXml() const
  23810. {
  23811. XmlElement* const e = new XmlElement ("PLUGIN");
  23812. e->setAttribute ("name", name);
  23813. e->setAttribute ("format", pluginFormatName);
  23814. e->setAttribute ("category", category);
  23815. e->setAttribute ("manufacturer", manufacturerName);
  23816. e->setAttribute ("version", version);
  23817. e->setAttribute ("file", fileOrIdentifier);
  23818. e->setAttribute ("uid", String::toHexString (uid));
  23819. e->setAttribute ("isInstrument", isInstrument);
  23820. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23821. e->setAttribute ("numInputs", numInputChannels);
  23822. e->setAttribute ("numOutputs", numOutputChannels);
  23823. return e;
  23824. }
  23825. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23826. {
  23827. if (xml.hasTagName ("PLUGIN"))
  23828. {
  23829. name = xml.getStringAttribute ("name");
  23830. pluginFormatName = xml.getStringAttribute ("format");
  23831. category = xml.getStringAttribute ("category");
  23832. manufacturerName = xml.getStringAttribute ("manufacturer");
  23833. version = xml.getStringAttribute ("version");
  23834. fileOrIdentifier = xml.getStringAttribute ("file");
  23835. uid = xml.getStringAttribute ("uid").getHexValue32();
  23836. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23837. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23838. numInputChannels = xml.getIntAttribute ("numInputs");
  23839. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23840. return true;
  23841. }
  23842. return false;
  23843. }
  23844. END_JUCE_NAMESPACE
  23845. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23846. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23847. BEGIN_JUCE_NAMESPACE
  23848. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23849. AudioPluginFormat& formatToLookFor,
  23850. FileSearchPath directoriesToSearch,
  23851. const bool recursive,
  23852. const File& deadMansPedalFile_)
  23853. : list (listToAddTo),
  23854. format (formatToLookFor),
  23855. deadMansPedalFile (deadMansPedalFile_),
  23856. nextIndex (0),
  23857. progress (0)
  23858. {
  23859. directoriesToSearch.removeRedundantPaths();
  23860. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23861. // If any plugins have crashed recently when being loaded, move them to the
  23862. // end of the list to give the others a chance to load correctly..
  23863. const StringArray crashedPlugins (getDeadMansPedalFile());
  23864. for (int i = 0; i < crashedPlugins.size(); ++i)
  23865. {
  23866. const String f = crashedPlugins[i];
  23867. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23868. if (f == filesOrIdentifiersToScan[j])
  23869. filesOrIdentifiersToScan.move (j, -1);
  23870. }
  23871. }
  23872. PluginDirectoryScanner::~PluginDirectoryScanner()
  23873. {
  23874. }
  23875. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23876. {
  23877. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23878. }
  23879. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23880. {
  23881. String file (filesOrIdentifiersToScan [nextIndex]);
  23882. if (file.isNotEmpty())
  23883. {
  23884. if (! list.isListingUpToDate (file))
  23885. {
  23886. OwnedArray <PluginDescription> typesFound;
  23887. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23888. StringArray crashedPlugins (getDeadMansPedalFile());
  23889. crashedPlugins.removeString (file);
  23890. crashedPlugins.add (file);
  23891. setDeadMansPedalFile (crashedPlugins);
  23892. list.scanAndAddFile (file,
  23893. dontRescanIfAlreadyInList,
  23894. typesFound,
  23895. format);
  23896. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23897. crashedPlugins.removeString (file);
  23898. setDeadMansPedalFile (crashedPlugins);
  23899. if (typesFound.size() == 0)
  23900. failedFiles.add (file);
  23901. }
  23902. ++nextIndex;
  23903. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23904. }
  23905. return nextIndex < filesOrIdentifiersToScan.size();
  23906. }
  23907. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23908. {
  23909. StringArray lines;
  23910. if (deadMansPedalFile != File::nonexistent)
  23911. {
  23912. lines.addLines (deadMansPedalFile.loadFileAsString());
  23913. lines.removeEmptyStrings();
  23914. }
  23915. return lines;
  23916. }
  23917. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23918. {
  23919. if (deadMansPedalFile != File::nonexistent)
  23920. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23921. }
  23922. END_JUCE_NAMESPACE
  23923. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23924. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23925. BEGIN_JUCE_NAMESPACE
  23926. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23927. const File& deadMansPedalFile_,
  23928. PropertiesFile* const propertiesToUse_)
  23929. : list (listToEdit),
  23930. deadMansPedalFile (deadMansPedalFile_),
  23931. propertiesToUse (propertiesToUse_)
  23932. {
  23933. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23934. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23935. optionsButton->addButtonListener (this);
  23936. optionsButton->setTriggeredOnMouseDown (true);
  23937. setSize (400, 600);
  23938. list.addChangeListener (this);
  23939. }
  23940. PluginListComponent::~PluginListComponent()
  23941. {
  23942. list.removeChangeListener (this);
  23943. deleteAllChildren();
  23944. }
  23945. void PluginListComponent::resized()
  23946. {
  23947. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23948. optionsButton->changeWidthToFitText (24);
  23949. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23950. }
  23951. void PluginListComponent::changeListenerCallback (void*)
  23952. {
  23953. listBox->updateContent();
  23954. listBox->repaint();
  23955. }
  23956. int PluginListComponent::getNumRows()
  23957. {
  23958. return list.getNumTypes();
  23959. }
  23960. void PluginListComponent::paintListBoxItem (int row,
  23961. Graphics& g,
  23962. int width, int height,
  23963. bool rowIsSelected)
  23964. {
  23965. if (rowIsSelected)
  23966. g.fillAll (findColour (TextEditor::highlightColourId));
  23967. const PluginDescription* const pd = list.getType (row);
  23968. if (pd != 0)
  23969. {
  23970. GlyphArrangement ga;
  23971. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23972. g.setColour (Colours::black);
  23973. ga.draw (g);
  23974. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  23975. String desc;
  23976. desc << pd->pluginFormatName
  23977. << (pd->isInstrument ? " instrument" : " effect")
  23978. << " - "
  23979. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23980. << " / "
  23981. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23982. if (pd->manufacturerName.isNotEmpty())
  23983. desc << " - " << pd->manufacturerName;
  23984. if (pd->version.isNotEmpty())
  23985. desc << " - " << pd->version;
  23986. if (pd->category.isNotEmpty())
  23987. desc << " - category: '" << pd->category << '\'';
  23988. g.setColour (Colours::grey);
  23989. ga.clear();
  23990. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  23991. ga.draw (g);
  23992. }
  23993. }
  23994. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23995. {
  23996. list.removeType (lastRowSelected);
  23997. }
  23998. void PluginListComponent::buttonClicked (Button* b)
  23999. {
  24000. if (optionsButton == b)
  24001. {
  24002. PopupMenu menu;
  24003. menu.addItem (1, TRANS("Clear list"));
  24004. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24005. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24006. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24007. menu.addSeparator();
  24008. menu.addItem (2, TRANS("Sort alphabetically"));
  24009. menu.addItem (3, TRANS("Sort by category"));
  24010. menu.addItem (4, TRANS("Sort by manufacturer"));
  24011. menu.addSeparator();
  24012. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24013. {
  24014. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24015. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24016. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24017. }
  24018. const int r = menu.showAt (optionsButton);
  24019. if (r == 1)
  24020. {
  24021. list.clear();
  24022. }
  24023. else if (r == 2)
  24024. {
  24025. list.sort (KnownPluginList::sortAlphabetically);
  24026. }
  24027. else if (r == 3)
  24028. {
  24029. list.sort (KnownPluginList::sortByCategory);
  24030. }
  24031. else if (r == 4)
  24032. {
  24033. list.sort (KnownPluginList::sortByManufacturer);
  24034. }
  24035. else if (r == 5)
  24036. {
  24037. const SparseSet <int> selected (listBox->getSelectedRows());
  24038. for (int i = list.getNumTypes(); --i >= 0;)
  24039. if (selected.contains (i))
  24040. list.removeType (i);
  24041. }
  24042. else if (r == 6)
  24043. {
  24044. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24045. if (desc != 0)
  24046. {
  24047. if (File (desc->fileOrIdentifier).existsAsFile())
  24048. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24049. }
  24050. }
  24051. else if (r == 7)
  24052. {
  24053. for (int i = list.getNumTypes(); --i >= 0;)
  24054. {
  24055. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24056. {
  24057. list.removeType (i);
  24058. }
  24059. }
  24060. }
  24061. else if (r != 0)
  24062. {
  24063. typeToScan = r - 10;
  24064. startTimer (1);
  24065. }
  24066. }
  24067. }
  24068. void PluginListComponent::timerCallback()
  24069. {
  24070. stopTimer();
  24071. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24072. }
  24073. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24074. {
  24075. return true;
  24076. }
  24077. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24078. {
  24079. OwnedArray <PluginDescription> typesFound;
  24080. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24081. }
  24082. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24083. {
  24084. if (format == 0)
  24085. return;
  24086. FileSearchPath path (format->getDefaultLocationsToSearch());
  24087. if (propertiesToUse != 0)
  24088. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24089. {
  24090. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24091. FileSearchPathListComponent pathList;
  24092. pathList.setSize (500, 300);
  24093. pathList.setPath (path);
  24094. aw.addCustomComponent (&pathList);
  24095. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24096. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24097. if (aw.runModalLoop() == 0)
  24098. return;
  24099. path = pathList.getPath();
  24100. }
  24101. if (propertiesToUse != 0)
  24102. {
  24103. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24104. propertiesToUse->saveIfNeeded();
  24105. }
  24106. double progress = 0.0;
  24107. AlertWindow aw (TRANS("Scanning for plugins..."),
  24108. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24109. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24110. aw.addProgressBarComponent (progress);
  24111. aw.enterModalState();
  24112. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24113. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24114. for (;;)
  24115. {
  24116. aw.setMessage (TRANS("Testing:\n\n")
  24117. + scanner.getNextPluginFileThatWillBeScanned());
  24118. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24119. if (! scanner.scanNextFile (true))
  24120. break;
  24121. if (! aw.isCurrentlyModal())
  24122. break;
  24123. progress = scanner.getProgress();
  24124. }
  24125. if (scanner.getFailedFiles().size() > 0)
  24126. {
  24127. StringArray shortNames;
  24128. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24129. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24130. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24131. TRANS("Scan complete"),
  24132. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24133. + shortNames.joinIntoString (", "));
  24134. }
  24135. }
  24136. END_JUCE_NAMESPACE
  24137. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24138. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24139. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24140. #include <AudioUnit/AudioUnit.h>
  24141. #include <AudioUnit/AUCocoaUIView.h>
  24142. #include <CoreAudioKit/AUGenericView.h>
  24143. #if JUCE_SUPPORT_CARBON
  24144. #include <AudioToolbox/AudioUnitUtilities.h>
  24145. #include <AudioUnit/AudioUnitCarbonView.h>
  24146. #endif
  24147. BEGIN_JUCE_NAMESPACE
  24148. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24149. #endif
  24150. #if JUCE_MAC
  24151. // Change this to disable logging of various activities
  24152. #ifndef AU_LOGGING
  24153. #define AU_LOGGING 1
  24154. #endif
  24155. #if AU_LOGGING
  24156. #define log(a) Logger::writeToLog(a);
  24157. #else
  24158. #define log(a)
  24159. #endif
  24160. static int insideCallback = 0;
  24161. static const String osTypeToString (OSType type)
  24162. {
  24163. char s[4];
  24164. s[0] = (char) (((uint32) type) >> 24);
  24165. s[1] = (char) (((uint32) type) >> 16);
  24166. s[2] = (char) (((uint32) type) >> 8);
  24167. s[3] = (char) ((uint32) type);
  24168. return String (s, 4);
  24169. }
  24170. static OSType stringToOSType (const String& s1)
  24171. {
  24172. const String s (s1 + " ");
  24173. return (((OSType) (unsigned char) s[0]) << 24)
  24174. | (((OSType) (unsigned char) s[1]) << 16)
  24175. | (((OSType) (unsigned char) s[2]) << 8)
  24176. | ((OSType) (unsigned char) s[3]);
  24177. }
  24178. static const char* auIdentifierPrefix = "AudioUnit:";
  24179. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24180. {
  24181. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24182. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24183. String s (auIdentifierPrefix);
  24184. if (desc.componentType == kAudioUnitType_MusicDevice)
  24185. s << "Synths/";
  24186. else if (desc.componentType == kAudioUnitType_MusicEffect
  24187. || desc.componentType == kAudioUnitType_Effect)
  24188. s << "Effects/";
  24189. else if (desc.componentType == kAudioUnitType_Generator)
  24190. s << "Generators/";
  24191. else if (desc.componentType == kAudioUnitType_Panner)
  24192. s << "Panners/";
  24193. s << osTypeToString (desc.componentType) << ","
  24194. << osTypeToString (desc.componentSubType) << ","
  24195. << osTypeToString (desc.componentManufacturer);
  24196. return s;
  24197. }
  24198. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24199. {
  24200. Handle componentNameHandle = NewHandle (sizeof (void*));
  24201. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24202. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24203. {
  24204. ComponentDescription desc;
  24205. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24206. {
  24207. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24208. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24209. if (nameString != 0 && nameString[0] != 0)
  24210. {
  24211. const String all ((const char*) nameString + 1, nameString[0]);
  24212. DBG ("name: "+ all);
  24213. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24214. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24215. }
  24216. if (infoString != 0 && infoString[0] != 0)
  24217. {
  24218. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24219. }
  24220. if (name.isEmpty())
  24221. name = "<Unknown>";
  24222. }
  24223. DisposeHandle (componentNameHandle);
  24224. DisposeHandle (componentInfoHandle);
  24225. }
  24226. }
  24227. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24228. String& name, String& version, String& manufacturer)
  24229. {
  24230. zerostruct (desc);
  24231. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24232. {
  24233. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24234. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24235. StringArray tokens;
  24236. tokens.addTokens (s, ",", String::empty);
  24237. tokens.trim();
  24238. tokens.removeEmptyStrings();
  24239. if (tokens.size() == 3)
  24240. {
  24241. desc.componentType = stringToOSType (tokens[0]);
  24242. desc.componentSubType = stringToOSType (tokens[1]);
  24243. desc.componentManufacturer = stringToOSType (tokens[2]);
  24244. ComponentRecord* comp = FindNextComponent (0, &desc);
  24245. if (comp != 0)
  24246. {
  24247. getAUDetails (comp, name, manufacturer);
  24248. return true;
  24249. }
  24250. }
  24251. }
  24252. return false;
  24253. }
  24254. class AudioUnitPluginWindowCarbon;
  24255. class AudioUnitPluginWindowCocoa;
  24256. class AudioUnitPluginInstance : public AudioPluginInstance
  24257. {
  24258. public:
  24259. ~AudioUnitPluginInstance();
  24260. // AudioPluginInstance methods:
  24261. void fillInPluginDescription (PluginDescription& desc) const
  24262. {
  24263. desc.name = pluginName;
  24264. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  24265. desc.uid = ((int) componentDesc.componentType)
  24266. ^ ((int) componentDesc.componentSubType)
  24267. ^ ((int) componentDesc.componentManufacturer);
  24268. desc.lastFileModTime = 0;
  24269. desc.pluginFormatName = "AudioUnit";
  24270. desc.category = getCategory();
  24271. desc.manufacturerName = manufacturer;
  24272. desc.version = version;
  24273. desc.numInputChannels = getNumInputChannels();
  24274. desc.numOutputChannels = getNumOutputChannels();
  24275. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24276. }
  24277. const String getName() const { return pluginName; }
  24278. bool acceptsMidi() const { return wantsMidiMessages; }
  24279. bool producesMidi() const { return false; }
  24280. // AudioProcessor methods:
  24281. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24282. void releaseResources();
  24283. void processBlock (AudioSampleBuffer& buffer,
  24284. MidiBuffer& midiMessages);
  24285. AudioProcessorEditor* createEditor();
  24286. const String getInputChannelName (const int index) const;
  24287. bool isInputChannelStereoPair (int index) const;
  24288. const String getOutputChannelName (const int index) const;
  24289. bool isOutputChannelStereoPair (int index) const;
  24290. int getNumParameters();
  24291. float getParameter (int index);
  24292. void setParameter (int index, float newValue);
  24293. const String getParameterName (int index);
  24294. const String getParameterText (int index);
  24295. bool isParameterAutomatable (int index) const;
  24296. int getNumPrograms();
  24297. int getCurrentProgram();
  24298. void setCurrentProgram (int index);
  24299. const String getProgramName (int index);
  24300. void changeProgramName (int index, const String& newName);
  24301. void getStateInformation (MemoryBlock& destData);
  24302. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24303. void setStateInformation (const void* data, int sizeInBytes);
  24304. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24305. juce_UseDebuggingNewOperator
  24306. private:
  24307. friend class AudioUnitPluginWindowCarbon;
  24308. friend class AudioUnitPluginWindowCocoa;
  24309. friend class AudioUnitPluginFormat;
  24310. ComponentDescription componentDesc;
  24311. String pluginName, manufacturer, version;
  24312. String fileOrIdentifier;
  24313. CriticalSection lock;
  24314. bool initialised, wantsMidiMessages, wasPlaying;
  24315. HeapBlock <AudioBufferList> outputBufferList;
  24316. AudioTimeStamp timeStamp;
  24317. AudioSampleBuffer* currentBuffer;
  24318. AudioUnit audioUnit;
  24319. Array <int> parameterIds;
  24320. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24321. void initialise();
  24322. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24323. const AudioTimeStamp* inTimeStamp,
  24324. UInt32 inBusNumber,
  24325. UInt32 inNumberFrames,
  24326. AudioBufferList* ioData) const;
  24327. static OSStatus renderGetInputCallback (void* inRefCon,
  24328. AudioUnitRenderActionFlags* ioActionFlags,
  24329. const AudioTimeStamp* inTimeStamp,
  24330. UInt32 inBusNumber,
  24331. UInt32 inNumberFrames,
  24332. AudioBufferList* ioData)
  24333. {
  24334. return ((AudioUnitPluginInstance*) inRefCon)
  24335. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24336. }
  24337. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24338. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24339. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24340. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24341. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24342. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24343. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24344. {
  24345. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24346. }
  24347. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24348. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24349. Float64* outCurrentMeasureDownBeat)
  24350. {
  24351. return ((AudioUnitPluginInstance*) inHostUserData)
  24352. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24353. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24354. }
  24355. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24356. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24357. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24358. {
  24359. return ((AudioUnitPluginInstance*) inHostUserData)
  24360. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24361. outCurrentSampleInTimeLine, outIsCycling,
  24362. outCycleStartBeat, outCycleEndBeat);
  24363. }
  24364. void getNumChannels (int& numIns, int& numOuts)
  24365. {
  24366. numIns = 0;
  24367. numOuts = 0;
  24368. AUChannelInfo supportedChannels [128];
  24369. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24370. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24371. 0, supportedChannels, &supportedChannelsSize) == noErr
  24372. && supportedChannelsSize > 0)
  24373. {
  24374. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24375. {
  24376. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24377. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24378. }
  24379. }
  24380. else
  24381. {
  24382. // (this really means the plugin will take any number of ins/outs as long
  24383. // as they are the same)
  24384. numIns = numOuts = 2;
  24385. }
  24386. }
  24387. const String getCategory() const;
  24388. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24389. };
  24390. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24391. : fileOrIdentifier (fileOrIdentifier),
  24392. initialised (false),
  24393. wantsMidiMessages (false),
  24394. audioUnit (0),
  24395. currentBuffer (0)
  24396. {
  24397. try
  24398. {
  24399. ++insideCallback;
  24400. log ("Opening AU: " + fileOrIdentifier);
  24401. if (getComponentDescFromFile (fileOrIdentifier))
  24402. {
  24403. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24404. if (comp != 0)
  24405. {
  24406. audioUnit = (AudioUnit) OpenComponent (comp);
  24407. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24408. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24409. }
  24410. }
  24411. --insideCallback;
  24412. }
  24413. catch (...)
  24414. {
  24415. --insideCallback;
  24416. }
  24417. }
  24418. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24419. {
  24420. const ScopedLock sl (lock);
  24421. jassert (insideCallback == 0);
  24422. if (audioUnit != 0)
  24423. {
  24424. AudioUnitUninitialize (audioUnit);
  24425. CloseComponent (audioUnit);
  24426. audioUnit = 0;
  24427. }
  24428. }
  24429. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24430. {
  24431. zerostruct (componentDesc);
  24432. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24433. return true;
  24434. const File file (fileOrIdentifier);
  24435. if (! file.hasFileExtension (".component"))
  24436. return false;
  24437. const char* const utf8 = fileOrIdentifier.toUTF8();
  24438. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24439. strlen (utf8), file.isDirectory());
  24440. if (url != 0)
  24441. {
  24442. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24443. CFRelease (url);
  24444. if (bundleRef != 0)
  24445. {
  24446. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24447. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24448. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24449. if (pluginName.isEmpty())
  24450. pluginName = file.getFileNameWithoutExtension();
  24451. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24452. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24453. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24454. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24455. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24456. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24457. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24458. UseResFile (resFileId);
  24459. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24460. {
  24461. Handle h = Get1IndResource ('thng', i);
  24462. if (h != 0)
  24463. {
  24464. HLock (h);
  24465. const uint32* const types = (const uint32*) *h;
  24466. if (types[0] == kAudioUnitType_MusicDevice
  24467. || types[0] == kAudioUnitType_MusicEffect
  24468. || types[0] == kAudioUnitType_Effect
  24469. || types[0] == kAudioUnitType_Generator
  24470. || types[0] == kAudioUnitType_Panner)
  24471. {
  24472. componentDesc.componentType = types[0];
  24473. componentDesc.componentSubType = types[1];
  24474. componentDesc.componentManufacturer = types[2];
  24475. break;
  24476. }
  24477. HUnlock (h);
  24478. ReleaseResource (h);
  24479. }
  24480. }
  24481. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24482. CFRelease (bundleRef);
  24483. }
  24484. }
  24485. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24486. }
  24487. void AudioUnitPluginInstance::initialise()
  24488. {
  24489. if (initialised || audioUnit == 0)
  24490. return;
  24491. log ("Initialising AU: " + pluginName);
  24492. parameterIds.clear();
  24493. {
  24494. UInt32 paramListSize = 0;
  24495. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24496. 0, 0, &paramListSize);
  24497. if (paramListSize > 0)
  24498. {
  24499. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24500. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24501. 0, &parameterIds.getReference(0), &paramListSize);
  24502. }
  24503. }
  24504. {
  24505. AURenderCallbackStruct info;
  24506. zerostruct (info);
  24507. info.inputProcRefCon = this;
  24508. info.inputProc = renderGetInputCallback;
  24509. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24510. 0, &info, sizeof (info));
  24511. }
  24512. {
  24513. HostCallbackInfo info;
  24514. zerostruct (info);
  24515. info.hostUserData = this;
  24516. info.beatAndTempoProc = getBeatAndTempoCallback;
  24517. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24518. info.transportStateProc = getTransportStateCallback;
  24519. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24520. 0, &info, sizeof (info));
  24521. }
  24522. int numIns, numOuts;
  24523. getNumChannels (numIns, numOuts);
  24524. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24525. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24526. setLatencySamples (0);
  24527. }
  24528. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24529. int samplesPerBlockExpected)
  24530. {
  24531. if (audioUnit != 0)
  24532. {
  24533. Float64 sampleRateIn = 0, sampleRateOut = 0;
  24534. UInt32 sampleRateSize = sizeof (sampleRateIn);
  24535. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  24536. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  24537. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  24538. {
  24539. if (initialised)
  24540. {
  24541. AudioUnitUninitialize (audioUnit);
  24542. initialised = false;
  24543. }
  24544. Float64 sr = sampleRate_;
  24545. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  24546. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  24547. }
  24548. }
  24549. initialise();
  24550. if (initialised)
  24551. {
  24552. int numIns, numOuts;
  24553. getNumChannels (numIns, numOuts);
  24554. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24555. Float64 latencySecs = 0.0;
  24556. UInt32 latencySize = sizeof (latencySecs);
  24557. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24558. 0, &latencySecs, &latencySize);
  24559. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24560. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24561. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24562. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24563. AudioStreamBasicDescription stream;
  24564. zerostruct (stream);
  24565. stream.mSampleRate = sampleRate_;
  24566. stream.mFormatID = kAudioFormatLinearPCM;
  24567. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24568. stream.mFramesPerPacket = 1;
  24569. stream.mBytesPerPacket = 4;
  24570. stream.mBytesPerFrame = 4;
  24571. stream.mBitsPerChannel = 32;
  24572. stream.mChannelsPerFrame = numIns;
  24573. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  24574. 0, &stream, sizeof (stream));
  24575. stream.mChannelsPerFrame = numOuts;
  24576. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  24577. 0, &stream, sizeof (stream));
  24578. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24579. outputBufferList->mNumberBuffers = numOuts;
  24580. for (int i = numOuts; --i >= 0;)
  24581. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24582. zerostruct (timeStamp);
  24583. timeStamp.mSampleTime = 0;
  24584. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24585. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24586. currentBuffer = 0;
  24587. wasPlaying = false;
  24588. }
  24589. }
  24590. void AudioUnitPluginInstance::releaseResources()
  24591. {
  24592. if (initialised)
  24593. {
  24594. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24595. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24596. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24597. outputBufferList.free();
  24598. currentBuffer = 0;
  24599. }
  24600. }
  24601. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24602. const AudioTimeStamp* inTimeStamp,
  24603. UInt32 inBusNumber,
  24604. UInt32 inNumberFrames,
  24605. AudioBufferList* ioData) const
  24606. {
  24607. if (inBusNumber == 0
  24608. && currentBuffer != 0)
  24609. {
  24610. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24611. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24612. {
  24613. if (i < currentBuffer->getNumChannels())
  24614. {
  24615. memcpy (ioData->mBuffers[i].mData,
  24616. currentBuffer->getSampleData (i, 0),
  24617. sizeof (float) * inNumberFrames);
  24618. }
  24619. else
  24620. {
  24621. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24622. }
  24623. }
  24624. }
  24625. return noErr;
  24626. }
  24627. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24628. MidiBuffer& midiMessages)
  24629. {
  24630. const int numSamples = buffer.getNumSamples();
  24631. if (initialised)
  24632. {
  24633. AudioUnitRenderActionFlags flags = 0;
  24634. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24635. for (int i = getNumOutputChannels(); --i >= 0;)
  24636. {
  24637. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24638. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24639. }
  24640. currentBuffer = &buffer;
  24641. if (wantsMidiMessages)
  24642. {
  24643. const uint8* midiEventData;
  24644. int midiEventSize, midiEventPosition;
  24645. MidiBuffer::Iterator i (midiMessages);
  24646. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24647. {
  24648. if (midiEventSize <= 3)
  24649. MusicDeviceMIDIEvent (audioUnit,
  24650. midiEventData[0], midiEventData[1], midiEventData[2],
  24651. midiEventPosition);
  24652. else
  24653. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24654. }
  24655. midiMessages.clear();
  24656. }
  24657. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24658. 0, numSamples, outputBufferList);
  24659. timeStamp.mSampleTime += numSamples;
  24660. }
  24661. else
  24662. {
  24663. // Not initialised, so just bypass..
  24664. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24665. buffer.clear (i, 0, buffer.getNumSamples());
  24666. }
  24667. }
  24668. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24669. {
  24670. AudioPlayHead* const ph = getPlayHead();
  24671. AudioPlayHead::CurrentPositionInfo result;
  24672. if (ph != 0 && ph->getCurrentPosition (result))
  24673. {
  24674. if (outCurrentBeat != 0)
  24675. *outCurrentBeat = result.ppqPosition;
  24676. if (outCurrentTempo != 0)
  24677. *outCurrentTempo = result.bpm;
  24678. }
  24679. else
  24680. {
  24681. if (outCurrentBeat != 0)
  24682. *outCurrentBeat = 0;
  24683. if (outCurrentTempo != 0)
  24684. *outCurrentTempo = 120.0;
  24685. }
  24686. return noErr;
  24687. }
  24688. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24689. Float32* outTimeSig_Numerator,
  24690. UInt32* outTimeSig_Denominator,
  24691. Float64* outCurrentMeasureDownBeat) const
  24692. {
  24693. AudioPlayHead* const ph = getPlayHead();
  24694. AudioPlayHead::CurrentPositionInfo result;
  24695. if (ph != 0 && ph->getCurrentPosition (result))
  24696. {
  24697. if (outTimeSig_Numerator != 0)
  24698. *outTimeSig_Numerator = result.timeSigNumerator;
  24699. if (outTimeSig_Denominator != 0)
  24700. *outTimeSig_Denominator = result.timeSigDenominator;
  24701. if (outDeltaSampleOffsetToNextBeat != 0)
  24702. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24703. if (outCurrentMeasureDownBeat != 0)
  24704. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24705. }
  24706. else
  24707. {
  24708. if (outDeltaSampleOffsetToNextBeat != 0)
  24709. *outDeltaSampleOffsetToNextBeat = 0;
  24710. if (outTimeSig_Numerator != 0)
  24711. *outTimeSig_Numerator = 4;
  24712. if (outTimeSig_Denominator != 0)
  24713. *outTimeSig_Denominator = 4;
  24714. if (outCurrentMeasureDownBeat != 0)
  24715. *outCurrentMeasureDownBeat = 0;
  24716. }
  24717. return noErr;
  24718. }
  24719. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24720. Boolean* outTransportStateChanged,
  24721. Float64* outCurrentSampleInTimeLine,
  24722. Boolean* outIsCycling,
  24723. Float64* outCycleStartBeat,
  24724. Float64* outCycleEndBeat)
  24725. {
  24726. AudioPlayHead* const ph = getPlayHead();
  24727. AudioPlayHead::CurrentPositionInfo result;
  24728. if (ph != 0 && ph->getCurrentPosition (result))
  24729. {
  24730. if (outIsPlaying != 0)
  24731. *outIsPlaying = result.isPlaying;
  24732. if (outTransportStateChanged != 0)
  24733. {
  24734. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24735. wasPlaying = result.isPlaying;
  24736. }
  24737. if (outCurrentSampleInTimeLine != 0)
  24738. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24739. if (outIsCycling != 0)
  24740. *outIsCycling = false;
  24741. if (outCycleStartBeat != 0)
  24742. *outCycleStartBeat = 0;
  24743. if (outCycleEndBeat != 0)
  24744. *outCycleEndBeat = 0;
  24745. }
  24746. else
  24747. {
  24748. if (outIsPlaying != 0)
  24749. *outIsPlaying = false;
  24750. if (outTransportStateChanged != 0)
  24751. *outTransportStateChanged = false;
  24752. if (outCurrentSampleInTimeLine != 0)
  24753. *outCurrentSampleInTimeLine = 0;
  24754. if (outIsCycling != 0)
  24755. *outIsCycling = false;
  24756. if (outCycleStartBeat != 0)
  24757. *outCycleStartBeat = 0;
  24758. if (outCycleEndBeat != 0)
  24759. *outCycleEndBeat = 0;
  24760. }
  24761. return noErr;
  24762. }
  24763. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24764. {
  24765. public:
  24766. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24767. : AudioProcessorEditor (&plugin_),
  24768. plugin (plugin_),
  24769. wrapper (0)
  24770. {
  24771. addAndMakeVisible (wrapper = new NSViewComponent());
  24772. setOpaque (true);
  24773. setVisible (true);
  24774. setSize (100, 100);
  24775. createView (createGenericViewIfNeeded);
  24776. }
  24777. ~AudioUnitPluginWindowCocoa()
  24778. {
  24779. const bool wasValid = isValid();
  24780. wrapper->setView (0);
  24781. if (wasValid)
  24782. plugin.editorBeingDeleted (this);
  24783. delete wrapper;
  24784. }
  24785. bool isValid() const { return wrapper->getView() != 0; }
  24786. void paint (Graphics& g)
  24787. {
  24788. g.fillAll (Colours::white);
  24789. }
  24790. void resized()
  24791. {
  24792. wrapper->setSize (getWidth(), getHeight());
  24793. }
  24794. private:
  24795. AudioUnitPluginInstance& plugin;
  24796. NSViewComponent* wrapper;
  24797. bool createView (const bool createGenericViewIfNeeded)
  24798. {
  24799. NSView* pluginView = 0;
  24800. UInt32 dataSize = 0;
  24801. Boolean isWritable = false;
  24802. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24803. 0, &dataSize, &isWritable) == noErr
  24804. && dataSize != 0
  24805. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24806. 0, &dataSize, &isWritable) == noErr)
  24807. {
  24808. HeapBlock <AudioUnitCocoaViewInfo> info;
  24809. info.calloc (dataSize, 1);
  24810. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24811. 0, info, &dataSize) == noErr)
  24812. {
  24813. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24814. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24815. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24816. Class viewClass = [viewBundle classNamed: viewClassName];
  24817. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24818. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24819. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24820. {
  24821. id factory = [[[viewClass alloc] init] autorelease];
  24822. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24823. withSize: NSMakeSize (getWidth(), getHeight())];
  24824. }
  24825. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24826. {
  24827. CFRelease (info->mCocoaAUViewClass[i]);
  24828. CFRelease (info->mCocoaAUViewBundleLocation);
  24829. }
  24830. }
  24831. }
  24832. if (createGenericViewIfNeeded && (pluginView == 0))
  24833. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24834. wrapper->setView (pluginView);
  24835. if (pluginView != 0)
  24836. setSize ([pluginView frame].size.width,
  24837. [pluginView frame].size.height);
  24838. return pluginView != 0;
  24839. }
  24840. };
  24841. #if JUCE_SUPPORT_CARBON
  24842. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24843. {
  24844. public:
  24845. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24846. : AudioProcessorEditor (&plugin_),
  24847. plugin (plugin_),
  24848. viewComponent (0)
  24849. {
  24850. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24851. setOpaque (true);
  24852. setVisible (true);
  24853. setSize (400, 300);
  24854. ComponentDescription viewList [16];
  24855. UInt32 viewListSize = sizeof (viewList);
  24856. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24857. 0, &viewList, &viewListSize);
  24858. componentRecord = FindNextComponent (0, &viewList[0]);
  24859. }
  24860. ~AudioUnitPluginWindowCarbon()
  24861. {
  24862. innerWrapper = 0;
  24863. if (isValid())
  24864. plugin.editorBeingDeleted (this);
  24865. }
  24866. bool isValid() const throw() { return componentRecord != 0; }
  24867. void paint (Graphics& g)
  24868. {
  24869. g.fillAll (Colours::black);
  24870. }
  24871. void resized()
  24872. {
  24873. innerWrapper->setSize (getWidth(), getHeight());
  24874. }
  24875. bool keyStateChanged (bool)
  24876. {
  24877. return false;
  24878. }
  24879. bool keyPressed (const KeyPress&)
  24880. {
  24881. return false;
  24882. }
  24883. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24884. AudioUnitCarbonView getViewComponent()
  24885. {
  24886. if (viewComponent == 0 && componentRecord != 0)
  24887. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24888. return viewComponent;
  24889. }
  24890. void closeViewComponent()
  24891. {
  24892. if (viewComponent != 0)
  24893. {
  24894. CloseComponent (viewComponent);
  24895. viewComponent = 0;
  24896. }
  24897. }
  24898. juce_UseDebuggingNewOperator
  24899. private:
  24900. AudioUnitPluginInstance& plugin;
  24901. ComponentRecord* componentRecord;
  24902. AudioUnitCarbonView viewComponent;
  24903. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24904. {
  24905. public:
  24906. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24907. : owner (owner_)
  24908. {
  24909. }
  24910. ~InnerWrapperComponent()
  24911. {
  24912. deleteWindow();
  24913. }
  24914. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24915. {
  24916. log ("Opening AU GUI: " + owner->plugin.getName());
  24917. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24918. if (viewComponent == 0)
  24919. return 0;
  24920. Float32Point pos = { 0, 0 };
  24921. Float32Point size = { 250, 200 };
  24922. HIViewRef pluginView = 0;
  24923. AudioUnitCarbonViewCreate (viewComponent,
  24924. owner->getAudioUnit(),
  24925. windowRef,
  24926. rootView,
  24927. &pos,
  24928. &size,
  24929. (ControlRef*) &pluginView);
  24930. return pluginView;
  24931. }
  24932. void removeView (HIViewRef)
  24933. {
  24934. log ("Closing AU GUI: " + owner->plugin.getName());
  24935. owner->closeViewComponent();
  24936. }
  24937. private:
  24938. AudioUnitPluginWindowCarbon* const owner;
  24939. };
  24940. friend class InnerWrapperComponent;
  24941. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24942. };
  24943. #endif
  24944. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24945. {
  24946. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24947. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24948. w = 0;
  24949. #if JUCE_SUPPORT_CARBON
  24950. if (w == 0)
  24951. {
  24952. w = new AudioUnitPluginWindowCarbon (*this);
  24953. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24954. w = 0;
  24955. }
  24956. #endif
  24957. if (w == 0)
  24958. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24959. return w.release();
  24960. }
  24961. const String AudioUnitPluginInstance::getCategory() const
  24962. {
  24963. const char* result = 0;
  24964. switch (componentDesc.componentType)
  24965. {
  24966. case kAudioUnitType_Effect:
  24967. case kAudioUnitType_MusicEffect:
  24968. result = "Effect";
  24969. break;
  24970. case kAudioUnitType_MusicDevice:
  24971. result = "Synth";
  24972. break;
  24973. case kAudioUnitType_Generator:
  24974. result = "Generator";
  24975. break;
  24976. case kAudioUnitType_Panner:
  24977. result = "Panner";
  24978. break;
  24979. default:
  24980. break;
  24981. }
  24982. return result;
  24983. }
  24984. int AudioUnitPluginInstance::getNumParameters()
  24985. {
  24986. return parameterIds.size();
  24987. }
  24988. float AudioUnitPluginInstance::getParameter (int index)
  24989. {
  24990. const ScopedLock sl (lock);
  24991. Float32 value = 0.0f;
  24992. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24993. {
  24994. AudioUnitGetParameter (audioUnit,
  24995. (UInt32) parameterIds.getUnchecked (index),
  24996. kAudioUnitScope_Global, 0,
  24997. &value);
  24998. }
  24999. return value;
  25000. }
  25001. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25002. {
  25003. const ScopedLock sl (lock);
  25004. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25005. {
  25006. AudioUnitSetParameter (audioUnit,
  25007. (UInt32) parameterIds.getUnchecked (index),
  25008. kAudioUnitScope_Global, 0,
  25009. newValue, 0);
  25010. }
  25011. }
  25012. const String AudioUnitPluginInstance::getParameterName (int index)
  25013. {
  25014. AudioUnitParameterInfo info;
  25015. zerostruct (info);
  25016. UInt32 sz = sizeof (info);
  25017. String name;
  25018. if (AudioUnitGetProperty (audioUnit,
  25019. kAudioUnitProperty_ParameterInfo,
  25020. kAudioUnitScope_Global,
  25021. parameterIds [index], &info, &sz) == noErr)
  25022. {
  25023. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25024. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25025. else
  25026. name = String (info.name, sizeof (info.name));
  25027. }
  25028. return name;
  25029. }
  25030. const String AudioUnitPluginInstance::getParameterText (int index)
  25031. {
  25032. return String (getParameter (index));
  25033. }
  25034. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25035. {
  25036. AudioUnitParameterInfo info;
  25037. UInt32 sz = sizeof (info);
  25038. if (AudioUnitGetProperty (audioUnit,
  25039. kAudioUnitProperty_ParameterInfo,
  25040. kAudioUnitScope_Global,
  25041. parameterIds [index], &info, &sz) == noErr)
  25042. {
  25043. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25044. }
  25045. return true;
  25046. }
  25047. int AudioUnitPluginInstance::getNumPrograms()
  25048. {
  25049. CFArrayRef presets;
  25050. UInt32 sz = sizeof (CFArrayRef);
  25051. int num = 0;
  25052. if (AudioUnitGetProperty (audioUnit,
  25053. kAudioUnitProperty_FactoryPresets,
  25054. kAudioUnitScope_Global,
  25055. 0, &presets, &sz) == noErr)
  25056. {
  25057. num = (int) CFArrayGetCount (presets);
  25058. CFRelease (presets);
  25059. }
  25060. return num;
  25061. }
  25062. int AudioUnitPluginInstance::getCurrentProgram()
  25063. {
  25064. AUPreset current;
  25065. current.presetNumber = 0;
  25066. UInt32 sz = sizeof (AUPreset);
  25067. AudioUnitGetProperty (audioUnit,
  25068. kAudioUnitProperty_FactoryPresets,
  25069. kAudioUnitScope_Global,
  25070. 0, &current, &sz);
  25071. return current.presetNumber;
  25072. }
  25073. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25074. {
  25075. AUPreset current;
  25076. current.presetNumber = newIndex;
  25077. current.presetName = 0;
  25078. AudioUnitSetProperty (audioUnit,
  25079. kAudioUnitProperty_FactoryPresets,
  25080. kAudioUnitScope_Global,
  25081. 0, &current, sizeof (AUPreset));
  25082. }
  25083. const String AudioUnitPluginInstance::getProgramName (int index)
  25084. {
  25085. String s;
  25086. CFArrayRef presets;
  25087. UInt32 sz = sizeof (CFArrayRef);
  25088. if (AudioUnitGetProperty (audioUnit,
  25089. kAudioUnitProperty_FactoryPresets,
  25090. kAudioUnitScope_Global,
  25091. 0, &presets, &sz) == noErr)
  25092. {
  25093. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25094. {
  25095. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25096. if (p != 0 && p->presetNumber == index)
  25097. {
  25098. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25099. break;
  25100. }
  25101. }
  25102. CFRelease (presets);
  25103. }
  25104. return s;
  25105. }
  25106. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25107. {
  25108. jassertfalse; // xxx not implemented!
  25109. }
  25110. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25111. {
  25112. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25113. return "Input " + String (index + 1);
  25114. return String::empty;
  25115. }
  25116. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25117. {
  25118. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25119. return false;
  25120. return true;
  25121. }
  25122. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25123. {
  25124. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25125. return "Output " + String (index + 1);
  25126. return String::empty;
  25127. }
  25128. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25129. {
  25130. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25131. return false;
  25132. return true;
  25133. }
  25134. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25135. {
  25136. getCurrentProgramStateInformation (destData);
  25137. }
  25138. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25139. {
  25140. CFPropertyListRef propertyList = 0;
  25141. UInt32 sz = sizeof (CFPropertyListRef);
  25142. if (AudioUnitGetProperty (audioUnit,
  25143. kAudioUnitProperty_ClassInfo,
  25144. kAudioUnitScope_Global,
  25145. 0, &propertyList, &sz) == noErr)
  25146. {
  25147. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25148. CFWriteStreamOpen (stream);
  25149. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25150. CFWriteStreamClose (stream);
  25151. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25152. destData.setSize (bytesWritten);
  25153. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25154. CFRelease (data);
  25155. CFRelease (stream);
  25156. CFRelease (propertyList);
  25157. }
  25158. }
  25159. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25160. {
  25161. setCurrentProgramStateInformation (data, sizeInBytes);
  25162. }
  25163. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25164. {
  25165. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25166. (const UInt8*) data,
  25167. sizeInBytes,
  25168. kCFAllocatorNull);
  25169. CFReadStreamOpen (stream);
  25170. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25171. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25172. stream,
  25173. 0,
  25174. kCFPropertyListImmutable,
  25175. &format,
  25176. 0);
  25177. CFRelease (stream);
  25178. if (propertyList != 0)
  25179. AudioUnitSetProperty (audioUnit,
  25180. kAudioUnitProperty_ClassInfo,
  25181. kAudioUnitScope_Global,
  25182. 0, &propertyList, sizeof (propertyList));
  25183. }
  25184. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25185. {
  25186. }
  25187. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25188. {
  25189. }
  25190. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25191. const String& fileOrIdentifier)
  25192. {
  25193. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25194. return;
  25195. PluginDescription desc;
  25196. desc.fileOrIdentifier = fileOrIdentifier;
  25197. desc.uid = 0;
  25198. try
  25199. {
  25200. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25201. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25202. if (auInstance != 0)
  25203. {
  25204. auInstance->fillInPluginDescription (desc);
  25205. results.add (new PluginDescription (desc));
  25206. }
  25207. }
  25208. catch (...)
  25209. {
  25210. // crashed while loading...
  25211. }
  25212. }
  25213. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25214. {
  25215. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25216. {
  25217. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25218. if (result->audioUnit != 0)
  25219. {
  25220. result->initialise();
  25221. return result.release();
  25222. }
  25223. }
  25224. return 0;
  25225. }
  25226. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25227. const bool /*recursive*/)
  25228. {
  25229. StringArray result;
  25230. ComponentRecord* comp = 0;
  25231. ComponentDescription desc;
  25232. zerostruct (desc);
  25233. for (;;)
  25234. {
  25235. zerostruct (desc);
  25236. comp = FindNextComponent (comp, &desc);
  25237. if (comp == 0)
  25238. break;
  25239. GetComponentInfo (comp, &desc, 0, 0, 0);
  25240. if (desc.componentType == kAudioUnitType_MusicDevice
  25241. || desc.componentType == kAudioUnitType_MusicEffect
  25242. || desc.componentType == kAudioUnitType_Effect
  25243. || desc.componentType == kAudioUnitType_Generator
  25244. || desc.componentType == kAudioUnitType_Panner)
  25245. {
  25246. const String s (createAUPluginIdentifier (desc));
  25247. DBG (s);
  25248. result.add (s);
  25249. }
  25250. }
  25251. return result;
  25252. }
  25253. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25254. {
  25255. ComponentDescription desc;
  25256. String name, version, manufacturer;
  25257. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25258. return FindNextComponent (0, &desc) != 0;
  25259. const File f (fileOrIdentifier);
  25260. return f.hasFileExtension (".component")
  25261. && f.isDirectory();
  25262. }
  25263. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25264. {
  25265. ComponentDescription desc;
  25266. String name, version, manufacturer;
  25267. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25268. if (name.isEmpty())
  25269. name = fileOrIdentifier;
  25270. return name;
  25271. }
  25272. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25273. {
  25274. if (desc.fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25275. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25276. else
  25277. return File (desc.fileOrIdentifier).exists();
  25278. }
  25279. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25280. {
  25281. return FileSearchPath ("/(Default AudioUnit locations)");
  25282. }
  25283. #endif
  25284. END_JUCE_NAMESPACE
  25285. #undef log
  25286. #endif
  25287. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25288. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25289. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25290. #define JUCE_MAC_VST_INCLUDED 1
  25291. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25292. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  25293. #if JUCE_WINDOWS
  25294. #undef _WIN32_WINNT
  25295. #define _WIN32_WINNT 0x500
  25296. #undef STRICT
  25297. #define STRICT
  25298. #include <windows.h>
  25299. #include <float.h>
  25300. #pragma warning (disable : 4312 4355)
  25301. #elif JUCE_LINUX
  25302. #include <float.h>
  25303. #include <sys/time.h>
  25304. #include <X11/Xlib.h>
  25305. #include <X11/Xutil.h>
  25306. #include <X11/Xatom.h>
  25307. #undef Font
  25308. #undef KeyPress
  25309. #undef Drawable
  25310. #undef Time
  25311. #else
  25312. #include <Cocoa/Cocoa.h>
  25313. #include <Carbon/Carbon.h>
  25314. #endif
  25315. #if ! (JUCE_MAC && JUCE_64BIT)
  25316. BEGIN_JUCE_NAMESPACE
  25317. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25318. #endif
  25319. #undef PRAGMA_ALIGN_SUPPORTED
  25320. #define VST_FORCE_DEPRECATED 0
  25321. #if JUCE_MSVC
  25322. #pragma warning (push)
  25323. #pragma warning (disable: 4996)
  25324. #endif
  25325. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25326. your include path if you want to add VST support.
  25327. If you're not interested in VSTs, you can disable them by changing the
  25328. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25329. */
  25330. #include "pluginterfaces/vst2.x/aeffectx.h"
  25331. #if JUCE_MSVC
  25332. #pragma warning (pop)
  25333. #endif
  25334. #if JUCE_LINUX
  25335. #define Font JUCE_NAMESPACE::Font
  25336. #define KeyPress JUCE_NAMESPACE::KeyPress
  25337. #define Drawable JUCE_NAMESPACE::Drawable
  25338. #define Time JUCE_NAMESPACE::Time
  25339. #endif
  25340. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25341. #ifdef __aeffect__
  25342. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25343. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25344. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25345. events to the list.
  25346. This is used by both the VST hosting code and the plugin wrapper.
  25347. */
  25348. class VSTMidiEventList
  25349. {
  25350. public:
  25351. VSTMidiEventList()
  25352. : numEventsUsed (0), numEventsAllocated (0)
  25353. {
  25354. }
  25355. ~VSTMidiEventList()
  25356. {
  25357. freeEvents();
  25358. }
  25359. void clear()
  25360. {
  25361. numEventsUsed = 0;
  25362. if (events != 0)
  25363. events->numEvents = 0;
  25364. }
  25365. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25366. {
  25367. ensureSize (numEventsUsed + 1);
  25368. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25369. events->numEvents = ++numEventsUsed;
  25370. if (numBytes <= 4)
  25371. {
  25372. if (e->type == kVstSysExType)
  25373. {
  25374. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25375. e->type = kVstMidiType;
  25376. e->byteSize = sizeof (VstMidiEvent);
  25377. e->noteLength = 0;
  25378. e->noteOffset = 0;
  25379. e->detune = 0;
  25380. e->noteOffVelocity = 0;
  25381. }
  25382. e->deltaFrames = frameOffset;
  25383. memcpy (e->midiData, midiData, numBytes);
  25384. }
  25385. else
  25386. {
  25387. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25388. if (se->type == kVstSysExType)
  25389. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25390. else
  25391. se->sysexDump = (char*) juce_malloc (numBytes);
  25392. memcpy (se->sysexDump, midiData, numBytes);
  25393. se->type = kVstSysExType;
  25394. se->byteSize = sizeof (VstMidiSysexEvent);
  25395. se->deltaFrames = frameOffset;
  25396. se->flags = 0;
  25397. se->dumpBytes = numBytes;
  25398. se->resvd1 = 0;
  25399. se->resvd2 = 0;
  25400. }
  25401. }
  25402. // Handy method to pull the events out of an event buffer supplied by the host
  25403. // or plugin.
  25404. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25405. {
  25406. for (int i = 0; i < events->numEvents; ++i)
  25407. {
  25408. const VstEvent* const e = events->events[i];
  25409. if (e != 0)
  25410. {
  25411. if (e->type == kVstMidiType)
  25412. {
  25413. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25414. 4, e->deltaFrames);
  25415. }
  25416. else if (e->type == kVstSysExType)
  25417. {
  25418. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25419. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25420. e->deltaFrames);
  25421. }
  25422. }
  25423. }
  25424. }
  25425. void ensureSize (int numEventsNeeded)
  25426. {
  25427. if (numEventsNeeded > numEventsAllocated)
  25428. {
  25429. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25430. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25431. if (events == 0)
  25432. events.calloc (size, 1);
  25433. else
  25434. events.realloc (size, 1);
  25435. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25436. {
  25437. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25438. (int) sizeof (VstMidiSysexEvent)));
  25439. e->type = kVstMidiType;
  25440. e->byteSize = sizeof (VstMidiEvent);
  25441. events->events[i] = (VstEvent*) e;
  25442. }
  25443. numEventsAllocated = numEventsNeeded;
  25444. }
  25445. }
  25446. void freeEvents()
  25447. {
  25448. if (events != 0)
  25449. {
  25450. for (int i = numEventsAllocated; --i >= 0;)
  25451. {
  25452. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25453. if (e->type == kVstSysExType)
  25454. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25455. juce_free (e);
  25456. }
  25457. events.free();
  25458. numEventsUsed = 0;
  25459. numEventsAllocated = 0;
  25460. }
  25461. }
  25462. HeapBlock <VstEvents> events;
  25463. private:
  25464. int numEventsUsed, numEventsAllocated;
  25465. };
  25466. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25467. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25468. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25469. #if ! JUCE_WINDOWS
  25470. static void _fpreset() {}
  25471. static void _clearfp() {}
  25472. #endif
  25473. extern void juce_callAnyTimersSynchronously();
  25474. const int fxbVersionNum = 1;
  25475. struct fxProgram
  25476. {
  25477. long chunkMagic; // 'CcnK'
  25478. long byteSize; // of this chunk, excl. magic + byteSize
  25479. long fxMagic; // 'FxCk'
  25480. long version;
  25481. long fxID; // fx unique id
  25482. long fxVersion;
  25483. long numParams;
  25484. char prgName[28];
  25485. float params[1]; // variable no. of parameters
  25486. };
  25487. struct fxSet
  25488. {
  25489. long chunkMagic; // 'CcnK'
  25490. long byteSize; // of this chunk, excl. magic + byteSize
  25491. long fxMagic; // 'FxBk'
  25492. long version;
  25493. long fxID; // fx unique id
  25494. long fxVersion;
  25495. long numPrograms;
  25496. char future[128];
  25497. fxProgram programs[1]; // variable no. of programs
  25498. };
  25499. struct fxChunkSet
  25500. {
  25501. long chunkMagic; // 'CcnK'
  25502. long byteSize; // of this chunk, excl. magic + byteSize
  25503. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25504. long version;
  25505. long fxID; // fx unique id
  25506. long fxVersion;
  25507. long numPrograms;
  25508. char future[128];
  25509. long chunkSize;
  25510. char chunk[8]; // variable
  25511. };
  25512. struct fxProgramSet
  25513. {
  25514. long chunkMagic; // 'CcnK'
  25515. long byteSize; // of this chunk, excl. magic + byteSize
  25516. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25517. long version;
  25518. long fxID; // fx unique id
  25519. long fxVersion;
  25520. long numPrograms;
  25521. char name[28];
  25522. long chunkSize;
  25523. char chunk[8]; // variable
  25524. };
  25525. static long vst_swap (const long x) throw()
  25526. {
  25527. #ifdef JUCE_LITTLE_ENDIAN
  25528. return (long) ByteOrder::swap ((uint32) x);
  25529. #else
  25530. return x;
  25531. #endif
  25532. }
  25533. static float vst_swapFloat (const float x) throw()
  25534. {
  25535. #ifdef JUCE_LITTLE_ENDIAN
  25536. union { uint32 asInt; float asFloat; } n;
  25537. n.asFloat = x;
  25538. n.asInt = ByteOrder::swap (n.asInt);
  25539. return n.asFloat;
  25540. #else
  25541. return x;
  25542. #endif
  25543. }
  25544. typedef AEffect* (*MainCall) (audioMasterCallback);
  25545. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25546. static int shellUIDToCreate = 0;
  25547. static int insideVSTCallback = 0;
  25548. class VSTPluginWindow;
  25549. // Change this to disable logging of various VST activities
  25550. #ifndef VST_LOGGING
  25551. #define VST_LOGGING 1
  25552. #endif
  25553. #if VST_LOGGING
  25554. #define log(a) Logger::writeToLog(a);
  25555. #else
  25556. #define log(a)
  25557. #endif
  25558. #if JUCE_MAC && JUCE_PPC
  25559. static void* NewCFMFromMachO (void* const machofp) throw()
  25560. {
  25561. void* result = juce_malloc (8);
  25562. ((void**) result)[0] = machofp;
  25563. ((void**) result)[1] = result;
  25564. return result;
  25565. }
  25566. #endif
  25567. #if JUCE_LINUX
  25568. extern Display* display;
  25569. extern XContext windowHandleXContext;
  25570. typedef void (*EventProcPtr) (XEvent* ev);
  25571. static bool xErrorTriggered;
  25572. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25573. {
  25574. xErrorTriggered = true;
  25575. return 0;
  25576. }
  25577. static int getPropertyFromXWindow (Window handle, Atom atom)
  25578. {
  25579. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25580. xErrorTriggered = false;
  25581. int userSize;
  25582. unsigned long bytes, userCount;
  25583. unsigned char* data;
  25584. Atom userType;
  25585. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25586. &userType, &userSize, &userCount, &bytes, &data);
  25587. XSetErrorHandler (oldErrorHandler);
  25588. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25589. : 0;
  25590. }
  25591. static Window getChildWindow (Window windowToCheck)
  25592. {
  25593. Window rootWindow, parentWindow;
  25594. Window* childWindows;
  25595. unsigned int numChildren;
  25596. XQueryTree (display,
  25597. windowToCheck,
  25598. &rootWindow,
  25599. &parentWindow,
  25600. &childWindows,
  25601. &numChildren);
  25602. if (numChildren > 0)
  25603. return childWindows [0];
  25604. return 0;
  25605. }
  25606. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25607. {
  25608. if (e.mods.isLeftButtonDown())
  25609. {
  25610. ev.xbutton.button = Button1;
  25611. ev.xbutton.state |= Button1Mask;
  25612. }
  25613. else if (e.mods.isRightButtonDown())
  25614. {
  25615. ev.xbutton.button = Button3;
  25616. ev.xbutton.state |= Button3Mask;
  25617. }
  25618. else if (e.mods.isMiddleButtonDown())
  25619. {
  25620. ev.xbutton.button = Button2;
  25621. ev.xbutton.state |= Button2Mask;
  25622. }
  25623. }
  25624. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25625. {
  25626. if (e.mods.isLeftButtonDown())
  25627. ev.xmotion.state |= Button1Mask;
  25628. else if (e.mods.isRightButtonDown())
  25629. ev.xmotion.state |= Button3Mask;
  25630. else if (e.mods.isMiddleButtonDown())
  25631. ev.xmotion.state |= Button2Mask;
  25632. }
  25633. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25634. {
  25635. if (e.mods.isLeftButtonDown())
  25636. ev.xcrossing.state |= Button1Mask;
  25637. else if (e.mods.isRightButtonDown())
  25638. ev.xcrossing.state |= Button3Mask;
  25639. else if (e.mods.isMiddleButtonDown())
  25640. ev.xcrossing.state |= Button2Mask;
  25641. }
  25642. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25643. {
  25644. if (increment < 0)
  25645. {
  25646. ev.xbutton.button = Button5;
  25647. ev.xbutton.state |= Button5Mask;
  25648. }
  25649. else if (increment > 0)
  25650. {
  25651. ev.xbutton.button = Button4;
  25652. ev.xbutton.state |= Button4Mask;
  25653. }
  25654. }
  25655. #endif
  25656. class ModuleHandle : public ReferenceCountedObject
  25657. {
  25658. public:
  25659. File file;
  25660. MainCall moduleMain;
  25661. String pluginName;
  25662. static Array <ModuleHandle*>& getActiveModules()
  25663. {
  25664. static Array <ModuleHandle*> activeModules;
  25665. return activeModules;
  25666. }
  25667. static ModuleHandle* findOrCreateModule (const File& file)
  25668. {
  25669. for (int i = getActiveModules().size(); --i >= 0;)
  25670. {
  25671. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  25672. if (module->file == file)
  25673. return module;
  25674. }
  25675. _fpreset(); // (doesn't do any harm)
  25676. ++insideVSTCallback;
  25677. shellUIDToCreate = 0;
  25678. log ("Attempting to load VST: " + file.getFullPathName());
  25679. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25680. if (! m->open())
  25681. m = 0;
  25682. --insideVSTCallback;
  25683. _fpreset(); // (doesn't do any harm)
  25684. return m.release();
  25685. }
  25686. ModuleHandle (const File& file_)
  25687. : file (file_),
  25688. moduleMain (0),
  25689. #if JUCE_WINDOWS || JUCE_LINUX
  25690. hModule (0)
  25691. #elif JUCE_MAC
  25692. fragId (0),
  25693. resHandle (0),
  25694. bundleRef (0),
  25695. resFileId (0)
  25696. #endif
  25697. {
  25698. getActiveModules().add (this);
  25699. #if JUCE_WINDOWS || JUCE_LINUX
  25700. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25701. #elif JUCE_MAC
  25702. FSRef ref;
  25703. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25704. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25705. #endif
  25706. }
  25707. ~ModuleHandle()
  25708. {
  25709. getActiveModules().removeValue (this);
  25710. close();
  25711. }
  25712. juce_UseDebuggingNewOperator
  25713. #if JUCE_WINDOWS || JUCE_LINUX
  25714. void* hModule;
  25715. String fullParentDirectoryPathName;
  25716. bool open()
  25717. {
  25718. #if JUCE_WINDOWS
  25719. static bool timePeriodSet = false;
  25720. if (! timePeriodSet)
  25721. {
  25722. timePeriodSet = true;
  25723. timeBeginPeriod (2);
  25724. }
  25725. #endif
  25726. pluginName = file.getFileNameWithoutExtension();
  25727. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25728. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25729. if (moduleMain == 0)
  25730. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25731. return moduleMain != 0;
  25732. }
  25733. void close()
  25734. {
  25735. _fpreset(); // (doesn't do any harm)
  25736. PlatformUtilities::freeDynamicLibrary (hModule);
  25737. }
  25738. void closeEffect (AEffect* eff)
  25739. {
  25740. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25741. }
  25742. #else
  25743. CFragConnectionID fragId;
  25744. Handle resHandle;
  25745. CFBundleRef bundleRef;
  25746. FSSpec parentDirFSSpec;
  25747. short resFileId;
  25748. bool open()
  25749. {
  25750. bool ok = false;
  25751. const String filename (file.getFullPathName());
  25752. if (file.hasFileExtension (".vst"))
  25753. {
  25754. const char* const utf8 = filename.toUTF8();
  25755. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25756. strlen (utf8), file.isDirectory());
  25757. if (url != 0)
  25758. {
  25759. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25760. CFRelease (url);
  25761. if (bundleRef != 0)
  25762. {
  25763. if (CFBundleLoadExecutable (bundleRef))
  25764. {
  25765. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25766. if (moduleMain == 0)
  25767. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25768. if (moduleMain != 0)
  25769. {
  25770. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25771. if (name != 0)
  25772. {
  25773. if (CFGetTypeID (name) == CFStringGetTypeID())
  25774. {
  25775. char buffer[1024];
  25776. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25777. pluginName = buffer;
  25778. }
  25779. }
  25780. if (pluginName.isEmpty())
  25781. pluginName = file.getFileNameWithoutExtension();
  25782. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25783. ok = true;
  25784. }
  25785. }
  25786. if (! ok)
  25787. {
  25788. CFBundleUnloadExecutable (bundleRef);
  25789. CFRelease (bundleRef);
  25790. bundleRef = 0;
  25791. }
  25792. }
  25793. }
  25794. }
  25795. #if JUCE_PPC
  25796. else
  25797. {
  25798. FSRef fn;
  25799. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25800. {
  25801. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25802. if (resFileId != -1)
  25803. {
  25804. const int numEffs = Count1Resources ('aEff');
  25805. for (int i = 0; i < numEffs; ++i)
  25806. {
  25807. resHandle = Get1IndResource ('aEff', i + 1);
  25808. if (resHandle != 0)
  25809. {
  25810. OSType type;
  25811. Str255 name;
  25812. SInt16 id;
  25813. GetResInfo (resHandle, &id, &type, name);
  25814. pluginName = String ((const char*) name + 1, name[0]);
  25815. DetachResource (resHandle);
  25816. HLock (resHandle);
  25817. Ptr ptr;
  25818. Str255 errorText;
  25819. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25820. name, kPrivateCFragCopy,
  25821. &fragId, &ptr, errorText);
  25822. if (err == noErr)
  25823. {
  25824. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25825. ok = true;
  25826. }
  25827. else
  25828. {
  25829. HUnlock (resHandle);
  25830. }
  25831. break;
  25832. }
  25833. }
  25834. if (! ok)
  25835. CloseResFile (resFileId);
  25836. }
  25837. }
  25838. }
  25839. #endif
  25840. return ok;
  25841. }
  25842. void close()
  25843. {
  25844. #if JUCE_PPC
  25845. if (fragId != 0)
  25846. {
  25847. if (moduleMain != 0)
  25848. disposeMachOFromCFM ((void*) moduleMain);
  25849. CloseConnection (&fragId);
  25850. HUnlock (resHandle);
  25851. if (resFileId != 0)
  25852. CloseResFile (resFileId);
  25853. }
  25854. else
  25855. #endif
  25856. if (bundleRef != 0)
  25857. {
  25858. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25859. if (CFGetRetainCount (bundleRef) == 1)
  25860. CFBundleUnloadExecutable (bundleRef);
  25861. if (CFGetRetainCount (bundleRef) > 0)
  25862. CFRelease (bundleRef);
  25863. }
  25864. }
  25865. void closeEffect (AEffect* eff)
  25866. {
  25867. #if JUCE_PPC
  25868. if (fragId != 0)
  25869. {
  25870. Array<void*> thingsToDelete;
  25871. thingsToDelete.add ((void*) eff->dispatcher);
  25872. thingsToDelete.add ((void*) eff->process);
  25873. thingsToDelete.add ((void*) eff->setParameter);
  25874. thingsToDelete.add ((void*) eff->getParameter);
  25875. thingsToDelete.add ((void*) eff->processReplacing);
  25876. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25877. for (int i = thingsToDelete.size(); --i >= 0;)
  25878. disposeMachOFromCFM (thingsToDelete[i]);
  25879. }
  25880. else
  25881. #endif
  25882. {
  25883. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25884. }
  25885. }
  25886. #if JUCE_PPC
  25887. static void* newMachOFromCFM (void* cfmfp)
  25888. {
  25889. if (cfmfp == 0)
  25890. return 0;
  25891. UInt32* const mfp = new UInt32[6];
  25892. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25893. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25894. mfp[2] = 0x800c0000;
  25895. mfp[3] = 0x804c0004;
  25896. mfp[4] = 0x7c0903a6;
  25897. mfp[5] = 0x4e800420;
  25898. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25899. return mfp;
  25900. }
  25901. static void disposeMachOFromCFM (void* ptr)
  25902. {
  25903. delete[] static_cast <UInt32*> (ptr);
  25904. }
  25905. void coerceAEffectFunctionCalls (AEffect* eff)
  25906. {
  25907. if (fragId != 0)
  25908. {
  25909. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25910. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25911. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25912. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25913. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25914. }
  25915. }
  25916. #endif
  25917. #endif
  25918. };
  25919. /**
  25920. An instance of a plugin, created by a VSTPluginFormat.
  25921. */
  25922. class VSTPluginInstance : public AudioPluginInstance,
  25923. private Timer,
  25924. private AsyncUpdater
  25925. {
  25926. public:
  25927. ~VSTPluginInstance();
  25928. // AudioPluginInstance methods:
  25929. void fillInPluginDescription (PluginDescription& desc) const
  25930. {
  25931. desc.name = name;
  25932. desc.fileOrIdentifier = module->file.getFullPathName();
  25933. desc.uid = getUID();
  25934. desc.lastFileModTime = module->file.getLastModificationTime();
  25935. desc.pluginFormatName = "VST";
  25936. desc.category = getCategory();
  25937. {
  25938. char buffer [kVstMaxVendorStrLen + 8];
  25939. zerostruct (buffer);
  25940. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25941. desc.manufacturerName = buffer;
  25942. }
  25943. desc.version = getVersion();
  25944. desc.numInputChannels = getNumInputChannels();
  25945. desc.numOutputChannels = getNumOutputChannels();
  25946. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25947. }
  25948. const String getName() const { return name; }
  25949. int getUID() const throw();
  25950. bool acceptsMidi() const { return wantsMidiMessages; }
  25951. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25952. // AudioProcessor methods:
  25953. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25954. void releaseResources();
  25955. void processBlock (AudioSampleBuffer& buffer,
  25956. MidiBuffer& midiMessages);
  25957. AudioProcessorEditor* createEditor();
  25958. const String getInputChannelName (const int index) const;
  25959. bool isInputChannelStereoPair (int index) const;
  25960. const String getOutputChannelName (const int index) const;
  25961. bool isOutputChannelStereoPair (int index) const;
  25962. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25963. float getParameter (int index);
  25964. void setParameter (int index, float newValue);
  25965. const String getParameterName (int index);
  25966. const String getParameterText (int index);
  25967. bool isParameterAutomatable (int index) const;
  25968. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25969. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25970. void setCurrentProgram (int index);
  25971. const String getProgramName (int index);
  25972. void changeProgramName (int index, const String& newName);
  25973. void getStateInformation (MemoryBlock& destData);
  25974. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25975. void setStateInformation (const void* data, int sizeInBytes);
  25976. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25977. void timerCallback();
  25978. void handleAsyncUpdate();
  25979. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25980. juce_UseDebuggingNewOperator
  25981. private:
  25982. friend class VSTPluginWindow;
  25983. friend class VSTPluginFormat;
  25984. AEffect* effect;
  25985. String name;
  25986. CriticalSection lock;
  25987. bool wantsMidiMessages, initialised, isPowerOn;
  25988. mutable StringArray programNames;
  25989. AudioSampleBuffer tempBuffer;
  25990. CriticalSection midiInLock;
  25991. MidiBuffer incomingMidi;
  25992. VSTMidiEventList midiEventsToSend;
  25993. VstTimeInfo vstHostTime;
  25994. HeapBlock <float*> channels;
  25995. ReferenceCountedObjectPtr <ModuleHandle> module;
  25996. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25997. bool restoreProgramSettings (const fxProgram* const prog);
  25998. const String getCurrentProgramName();
  25999. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26000. void updateStoredProgramNames();
  26001. void initialise();
  26002. void handleMidiFromPlugin (const VstEvents* const events);
  26003. void createTempParameterStore (MemoryBlock& dest);
  26004. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26005. const String getParameterLabel (int index) const;
  26006. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26007. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26008. void setChunkData (const char* data, int size, bool isPreset);
  26009. bool loadFromFXBFile (const void* data, int numBytes);
  26010. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26011. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26012. const String getVersion() const throw();
  26013. const String getCategory() const throw();
  26014. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26015. void setPower (const bool on);
  26016. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26017. };
  26018. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26019. : effect (0),
  26020. wantsMidiMessages (false),
  26021. initialised (false),
  26022. isPowerOn (false),
  26023. tempBuffer (1, 1),
  26024. module (module_)
  26025. {
  26026. try
  26027. {
  26028. _fpreset();
  26029. ++insideVSTCallback;
  26030. name = module->pluginName;
  26031. log ("Creating VST instance: " + name);
  26032. #if JUCE_MAC
  26033. if (module->resFileId != 0)
  26034. UseResFile (module->resFileId);
  26035. #if JUCE_PPC
  26036. if (module->fragId != 0)
  26037. {
  26038. static void* audioMasterCoerced = 0;
  26039. if (audioMasterCoerced == 0)
  26040. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26041. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26042. }
  26043. else
  26044. #endif
  26045. #endif
  26046. {
  26047. effect = module->moduleMain (&audioMaster);
  26048. }
  26049. --insideVSTCallback;
  26050. if (effect != 0 && effect->magic == kEffectMagic)
  26051. {
  26052. #if JUCE_PPC
  26053. module->coerceAEffectFunctionCalls (effect);
  26054. #endif
  26055. jassert (effect->resvd2 == 0);
  26056. jassert (effect->object != 0);
  26057. _fpreset(); // some dodgy plugs fuck around with this
  26058. }
  26059. else
  26060. {
  26061. effect = 0;
  26062. }
  26063. }
  26064. catch (...)
  26065. {
  26066. --insideVSTCallback;
  26067. }
  26068. }
  26069. VSTPluginInstance::~VSTPluginInstance()
  26070. {
  26071. {
  26072. const ScopedLock sl (lock);
  26073. jassert (insideVSTCallback == 0);
  26074. if (effect != 0 && effect->magic == kEffectMagic)
  26075. {
  26076. try
  26077. {
  26078. #if JUCE_MAC
  26079. if (module->resFileId != 0)
  26080. UseResFile (module->resFileId);
  26081. #endif
  26082. // Must delete any editors before deleting the plugin instance!
  26083. jassert (getActiveEditor() == 0);
  26084. _fpreset(); // some dodgy plugs fuck around with this
  26085. module->closeEffect (effect);
  26086. }
  26087. catch (...)
  26088. {}
  26089. }
  26090. module = 0;
  26091. effect = 0;
  26092. }
  26093. }
  26094. void VSTPluginInstance::initialise()
  26095. {
  26096. if (initialised || effect == 0)
  26097. return;
  26098. log ("Initialising VST: " + module->pluginName);
  26099. initialised = true;
  26100. dispatch (effIdentify, 0, 0, 0, 0);
  26101. // this code would ask the plugin for its name, but so few plugins
  26102. // actually bother implementing this correctly, that it's better to
  26103. // just ignore it and use the file name instead.
  26104. /* {
  26105. char buffer [256];
  26106. zerostruct (buffer);
  26107. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26108. name = String (buffer).trim();
  26109. if (name.isEmpty())
  26110. name = module->pluginName;
  26111. }
  26112. */
  26113. if (getSampleRate() > 0)
  26114. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26115. if (getBlockSize() > 0)
  26116. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26117. dispatch (effOpen, 0, 0, 0, 0);
  26118. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26119. getSampleRate(), getBlockSize());
  26120. if (getNumPrograms() > 1)
  26121. setCurrentProgram (0);
  26122. else
  26123. dispatch (effSetProgram, 0, 0, 0, 0);
  26124. int i;
  26125. for (i = effect->numInputs; --i >= 0;)
  26126. dispatch (effConnectInput, i, 1, 0, 0);
  26127. for (i = effect->numOutputs; --i >= 0;)
  26128. dispatch (effConnectOutput, i, 1, 0, 0);
  26129. updateStoredProgramNames();
  26130. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26131. setLatencySamples (effect->initialDelay);
  26132. }
  26133. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26134. int samplesPerBlockExpected)
  26135. {
  26136. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26137. sampleRate_, samplesPerBlockExpected);
  26138. setLatencySamples (effect->initialDelay);
  26139. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26140. vstHostTime.tempo = 120.0;
  26141. vstHostTime.timeSigNumerator = 4;
  26142. vstHostTime.timeSigDenominator = 4;
  26143. vstHostTime.sampleRate = sampleRate_;
  26144. vstHostTime.samplePos = 0;
  26145. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26146. initialise();
  26147. if (initialised)
  26148. {
  26149. wantsMidiMessages = wantsMidiMessages
  26150. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26151. if (wantsMidiMessages)
  26152. midiEventsToSend.ensureSize (256);
  26153. else
  26154. midiEventsToSend.freeEvents();
  26155. incomingMidi.clear();
  26156. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26157. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26158. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26159. if (! isPowerOn)
  26160. setPower (true);
  26161. // dodgy hack to force some plugins to initialise the sample rate..
  26162. if ((! hasEditor()) && getNumParameters() > 0)
  26163. {
  26164. const float old = getParameter (0);
  26165. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26166. setParameter (0, old);
  26167. }
  26168. dispatch (effStartProcess, 0, 0, 0, 0);
  26169. }
  26170. }
  26171. void VSTPluginInstance::releaseResources()
  26172. {
  26173. if (initialised)
  26174. {
  26175. dispatch (effStopProcess, 0, 0, 0, 0);
  26176. setPower (false);
  26177. }
  26178. tempBuffer.setSize (1, 1);
  26179. incomingMidi.clear();
  26180. midiEventsToSend.freeEvents();
  26181. channels.free();
  26182. }
  26183. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26184. MidiBuffer& midiMessages)
  26185. {
  26186. const int numSamples = buffer.getNumSamples();
  26187. if (initialised)
  26188. {
  26189. AudioPlayHead* playHead = getPlayHead();
  26190. if (playHead != 0)
  26191. {
  26192. AudioPlayHead::CurrentPositionInfo position;
  26193. playHead->getCurrentPosition (position);
  26194. vstHostTime.tempo = position.bpm;
  26195. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26196. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26197. vstHostTime.ppqPos = position.ppqPosition;
  26198. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26199. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26200. if (position.isPlaying)
  26201. vstHostTime.flags |= kVstTransportPlaying;
  26202. else
  26203. vstHostTime.flags &= ~kVstTransportPlaying;
  26204. }
  26205. #if JUCE_WINDOWS
  26206. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26207. #elif JUCE_LINUX
  26208. timeval micro;
  26209. gettimeofday (&micro, 0);
  26210. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26211. #elif JUCE_MAC
  26212. UnsignedWide micro;
  26213. Microseconds (&micro);
  26214. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26215. #endif
  26216. if (wantsMidiMessages)
  26217. {
  26218. midiEventsToSend.clear();
  26219. midiEventsToSend.ensureSize (1);
  26220. MidiBuffer::Iterator iter (midiMessages);
  26221. const uint8* midiData;
  26222. int numBytesOfMidiData, samplePosition;
  26223. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26224. {
  26225. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26226. jlimit (0, numSamples - 1, samplePosition));
  26227. }
  26228. try
  26229. {
  26230. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26231. }
  26232. catch (...)
  26233. {}
  26234. }
  26235. int i;
  26236. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26237. for (i = 0; i < maxChans; ++i)
  26238. channels[i] = buffer.getSampleData (i);
  26239. channels [maxChans] = 0;
  26240. _clearfp();
  26241. if ((effect->flags & effFlagsCanReplacing) != 0)
  26242. {
  26243. try
  26244. {
  26245. effect->processReplacing (effect, channels, channels, numSamples);
  26246. }
  26247. catch (...)
  26248. {}
  26249. }
  26250. else
  26251. {
  26252. tempBuffer.setSize (effect->numOutputs, numSamples);
  26253. tempBuffer.clear();
  26254. float* outs [64];
  26255. for (i = effect->numOutputs; --i >= 0;)
  26256. outs[i] = tempBuffer.getSampleData (i);
  26257. outs [effect->numOutputs] = 0;
  26258. try
  26259. {
  26260. effect->process (effect, channels, outs, numSamples);
  26261. }
  26262. catch (...)
  26263. {}
  26264. for (i = effect->numOutputs; --i >= 0;)
  26265. buffer.copyFrom (i, 0, outs[i], numSamples);
  26266. }
  26267. }
  26268. else
  26269. {
  26270. // Not initialised, so just bypass..
  26271. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26272. buffer.clear (i, 0, buffer.getNumSamples());
  26273. }
  26274. {
  26275. // copy any incoming midi..
  26276. const ScopedLock sl (midiInLock);
  26277. midiMessages.swapWith (incomingMidi);
  26278. incomingMidi.clear();
  26279. }
  26280. }
  26281. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26282. {
  26283. if (events != 0)
  26284. {
  26285. const ScopedLock sl (midiInLock);
  26286. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26287. }
  26288. }
  26289. static Array <VSTPluginWindow*> activeVSTWindows;
  26290. class VSTPluginWindow : public AudioProcessorEditor,
  26291. #if ! JUCE_MAC
  26292. public ComponentMovementWatcher,
  26293. #endif
  26294. public Timer
  26295. {
  26296. public:
  26297. VSTPluginWindow (VSTPluginInstance& plugin_)
  26298. : AudioProcessorEditor (&plugin_),
  26299. #if ! JUCE_MAC
  26300. ComponentMovementWatcher (this),
  26301. #endif
  26302. plugin (plugin_),
  26303. isOpen (false),
  26304. wasShowing (false),
  26305. pluginRefusesToResize (false),
  26306. pluginWantsKeys (false),
  26307. alreadyInside (false),
  26308. recursiveResize (false)
  26309. {
  26310. #if JUCE_WINDOWS
  26311. sizeCheckCount = 0;
  26312. pluginHWND = 0;
  26313. #elif JUCE_LINUX
  26314. pluginWindow = None;
  26315. pluginProc = None;
  26316. #else
  26317. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26318. #endif
  26319. activeVSTWindows.add (this);
  26320. setSize (1, 1);
  26321. setOpaque (true);
  26322. setVisible (true);
  26323. }
  26324. ~VSTPluginWindow()
  26325. {
  26326. #if JUCE_MAC
  26327. innerWrapper = 0;
  26328. #else
  26329. closePluginWindow();
  26330. #endif
  26331. activeVSTWindows.removeValue (this);
  26332. plugin.editorBeingDeleted (this);
  26333. }
  26334. #if ! JUCE_MAC
  26335. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26336. {
  26337. if (recursiveResize)
  26338. return;
  26339. Component* const topComp = getTopLevelComponent();
  26340. if (topComp->getPeer() != 0)
  26341. {
  26342. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26343. recursiveResize = true;
  26344. #if JUCE_WINDOWS
  26345. if (pluginHWND != 0)
  26346. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26347. #elif JUCE_LINUX
  26348. if (pluginWindow != 0)
  26349. {
  26350. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26351. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26352. XMapRaised (display, pluginWindow);
  26353. }
  26354. #endif
  26355. recursiveResize = false;
  26356. }
  26357. }
  26358. void componentVisibilityChanged (Component&)
  26359. {
  26360. const bool isShowingNow = isShowing();
  26361. if (wasShowing != isShowingNow)
  26362. {
  26363. wasShowing = isShowingNow;
  26364. if (isShowingNow)
  26365. openPluginWindow();
  26366. else
  26367. closePluginWindow();
  26368. }
  26369. componentMovedOrResized (true, true);
  26370. }
  26371. void componentPeerChanged()
  26372. {
  26373. closePluginWindow();
  26374. openPluginWindow();
  26375. }
  26376. #endif
  26377. bool keyStateChanged (bool)
  26378. {
  26379. return pluginWantsKeys;
  26380. }
  26381. bool keyPressed (const KeyPress&)
  26382. {
  26383. return pluginWantsKeys;
  26384. }
  26385. #if JUCE_MAC
  26386. void paint (Graphics& g)
  26387. {
  26388. g.fillAll (Colours::black);
  26389. }
  26390. #else
  26391. void paint (Graphics& g)
  26392. {
  26393. if (isOpen)
  26394. {
  26395. ComponentPeer* const peer = getPeer();
  26396. if (peer != 0)
  26397. {
  26398. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26399. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26400. #if JUCE_LINUX
  26401. if (pluginWindow != 0)
  26402. {
  26403. const Rectangle<int> clip (g.getClipBounds());
  26404. XEvent ev;
  26405. zerostruct (ev);
  26406. ev.xexpose.type = Expose;
  26407. ev.xexpose.display = display;
  26408. ev.xexpose.window = pluginWindow;
  26409. ev.xexpose.x = clip.getX();
  26410. ev.xexpose.y = clip.getY();
  26411. ev.xexpose.width = clip.getWidth();
  26412. ev.xexpose.height = clip.getHeight();
  26413. sendEventToChild (&ev);
  26414. }
  26415. #endif
  26416. }
  26417. }
  26418. else
  26419. {
  26420. g.fillAll (Colours::black);
  26421. }
  26422. }
  26423. #endif
  26424. void timerCallback()
  26425. {
  26426. #if JUCE_WINDOWS
  26427. if (--sizeCheckCount <= 0)
  26428. {
  26429. sizeCheckCount = 10;
  26430. checkPluginWindowSize();
  26431. }
  26432. #endif
  26433. try
  26434. {
  26435. static bool reentrant = false;
  26436. if (! reentrant)
  26437. {
  26438. reentrant = true;
  26439. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26440. reentrant = false;
  26441. }
  26442. }
  26443. catch (...)
  26444. {}
  26445. }
  26446. void mouseDown (const MouseEvent& e)
  26447. {
  26448. #if JUCE_LINUX
  26449. if (pluginWindow == 0)
  26450. return;
  26451. toFront (true);
  26452. XEvent ev;
  26453. zerostruct (ev);
  26454. ev.xbutton.display = display;
  26455. ev.xbutton.type = ButtonPress;
  26456. ev.xbutton.window = pluginWindow;
  26457. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26458. ev.xbutton.time = CurrentTime;
  26459. ev.xbutton.x = e.x;
  26460. ev.xbutton.y = e.y;
  26461. ev.xbutton.x_root = e.getScreenX();
  26462. ev.xbutton.y_root = e.getScreenY();
  26463. translateJuceToXButtonModifiers (e, ev);
  26464. sendEventToChild (&ev);
  26465. #elif JUCE_WINDOWS
  26466. (void) e;
  26467. toFront (true);
  26468. #endif
  26469. }
  26470. void broughtToFront()
  26471. {
  26472. activeVSTWindows.removeValue (this);
  26473. activeVSTWindows.add (this);
  26474. #if JUCE_MAC
  26475. dispatch (effEditTop, 0, 0, 0, 0);
  26476. #endif
  26477. }
  26478. juce_UseDebuggingNewOperator
  26479. private:
  26480. VSTPluginInstance& plugin;
  26481. bool isOpen, wasShowing, recursiveResize;
  26482. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26483. #if JUCE_WINDOWS
  26484. HWND pluginHWND;
  26485. void* originalWndProc;
  26486. int sizeCheckCount;
  26487. #elif JUCE_LINUX
  26488. Window pluginWindow;
  26489. EventProcPtr pluginProc;
  26490. #endif
  26491. #if JUCE_MAC
  26492. void openPluginWindow (WindowRef parentWindow)
  26493. {
  26494. if (isOpen || parentWindow == 0)
  26495. return;
  26496. isOpen = true;
  26497. ERect* rect = 0;
  26498. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26499. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26500. // do this before and after like in the steinberg example
  26501. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26502. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26503. // Install keyboard hooks
  26504. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26505. // double-check it's not too tiny
  26506. int w = 250, h = 150;
  26507. if (rect != 0)
  26508. {
  26509. w = rect->right - rect->left;
  26510. h = rect->bottom - rect->top;
  26511. if (w == 0 || h == 0)
  26512. {
  26513. w = 250;
  26514. h = 150;
  26515. }
  26516. }
  26517. w = jmax (w, 32);
  26518. h = jmax (h, 32);
  26519. setSize (w, h);
  26520. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26521. repaint();
  26522. }
  26523. #else
  26524. void openPluginWindow()
  26525. {
  26526. if (isOpen || getWindowHandle() == 0)
  26527. return;
  26528. log ("Opening VST UI: " + plugin.name);
  26529. isOpen = true;
  26530. ERect* rect = 0;
  26531. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26532. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26533. // do this before and after like in the steinberg example
  26534. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26535. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26536. // Install keyboard hooks
  26537. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26538. #if JUCE_WINDOWS
  26539. originalWndProc = 0;
  26540. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26541. if (pluginHWND == 0)
  26542. {
  26543. isOpen = false;
  26544. setSize (300, 150);
  26545. return;
  26546. }
  26547. #pragma warning (push)
  26548. #pragma warning (disable: 4244)
  26549. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26550. if (! pluginWantsKeys)
  26551. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26552. #pragma warning (pop)
  26553. int w, h;
  26554. RECT r;
  26555. GetWindowRect (pluginHWND, &r);
  26556. w = r.right - r.left;
  26557. h = r.bottom - r.top;
  26558. if (rect != 0)
  26559. {
  26560. const int rw = rect->right - rect->left;
  26561. const int rh = rect->bottom - rect->top;
  26562. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26563. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26564. {
  26565. // very dodgy logic to decide which size is right.
  26566. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26567. {
  26568. SetWindowPos (pluginHWND, 0,
  26569. 0, 0, rw, rh,
  26570. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26571. GetWindowRect (pluginHWND, &r);
  26572. w = r.right - r.left;
  26573. h = r.bottom - r.top;
  26574. pluginRefusesToResize = (w != rw) || (h != rh);
  26575. w = rw;
  26576. h = rh;
  26577. }
  26578. }
  26579. }
  26580. #elif JUCE_LINUX
  26581. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26582. if (pluginWindow != 0)
  26583. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26584. XInternAtom (display, "_XEventProc", False));
  26585. int w = 250, h = 150;
  26586. if (rect != 0)
  26587. {
  26588. w = rect->right - rect->left;
  26589. h = rect->bottom - rect->top;
  26590. if (w == 0 || h == 0)
  26591. {
  26592. w = 250;
  26593. h = 150;
  26594. }
  26595. }
  26596. if (pluginWindow != 0)
  26597. XMapRaised (display, pluginWindow);
  26598. #endif
  26599. // double-check it's not too tiny
  26600. w = jmax (w, 32);
  26601. h = jmax (h, 32);
  26602. setSize (w, h);
  26603. #if JUCE_WINDOWS
  26604. checkPluginWindowSize();
  26605. #endif
  26606. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26607. repaint();
  26608. }
  26609. #endif
  26610. #if ! JUCE_MAC
  26611. void closePluginWindow()
  26612. {
  26613. if (isOpen)
  26614. {
  26615. log ("Closing VST UI: " + plugin.getName());
  26616. isOpen = false;
  26617. dispatch (effEditClose, 0, 0, 0, 0);
  26618. #if JUCE_WINDOWS
  26619. #pragma warning (push)
  26620. #pragma warning (disable: 4244)
  26621. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26622. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26623. #pragma warning (pop)
  26624. stopTimer();
  26625. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26626. DestroyWindow (pluginHWND);
  26627. pluginHWND = 0;
  26628. #elif JUCE_LINUX
  26629. stopTimer();
  26630. pluginWindow = 0;
  26631. pluginProc = 0;
  26632. #endif
  26633. }
  26634. }
  26635. #endif
  26636. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26637. {
  26638. return plugin.dispatch (opcode, index, value, ptr, opt);
  26639. }
  26640. #if JUCE_WINDOWS
  26641. void checkPluginWindowSize() throw()
  26642. {
  26643. RECT r;
  26644. GetWindowRect (pluginHWND, &r);
  26645. const int w = r.right - r.left;
  26646. const int h = r.bottom - r.top;
  26647. if (isShowing() && w > 0 && h > 0
  26648. && (w != getWidth() || h != getHeight())
  26649. && ! pluginRefusesToResize)
  26650. {
  26651. setSize (w, h);
  26652. sizeCheckCount = 0;
  26653. }
  26654. }
  26655. // hooks to get keyboard events from VST windows..
  26656. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26657. {
  26658. for (int i = activeVSTWindows.size(); --i >= 0;)
  26659. {
  26660. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26661. if (w->pluginHWND == hW)
  26662. {
  26663. if (message == WM_CHAR
  26664. || message == WM_KEYDOWN
  26665. || message == WM_SYSKEYDOWN
  26666. || message == WM_KEYUP
  26667. || message == WM_SYSKEYUP
  26668. || message == WM_APPCOMMAND)
  26669. {
  26670. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26671. message, wParam, lParam);
  26672. }
  26673. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26674. (HWND) w->pluginHWND,
  26675. message,
  26676. wParam,
  26677. lParam);
  26678. }
  26679. }
  26680. return DefWindowProc (hW, message, wParam, lParam);
  26681. }
  26682. #endif
  26683. #if JUCE_LINUX
  26684. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26685. void sendEventToChild (XEvent* event)
  26686. {
  26687. if (pluginProc != 0)
  26688. {
  26689. // if the plugin publishes an event procedure, pass the event directly..
  26690. pluginProc (event);
  26691. }
  26692. else if (pluginWindow != 0)
  26693. {
  26694. // if the plugin has a window, then send the event to the window so that
  26695. // its message thread will pick it up..
  26696. XSendEvent (display, pluginWindow, False, 0L, event);
  26697. XFlush (display);
  26698. }
  26699. }
  26700. void mouseEnter (const MouseEvent& e)
  26701. {
  26702. if (pluginWindow != 0)
  26703. {
  26704. XEvent ev;
  26705. zerostruct (ev);
  26706. ev.xcrossing.display = display;
  26707. ev.xcrossing.type = EnterNotify;
  26708. ev.xcrossing.window = pluginWindow;
  26709. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26710. ev.xcrossing.time = CurrentTime;
  26711. ev.xcrossing.x = e.x;
  26712. ev.xcrossing.y = e.y;
  26713. ev.xcrossing.x_root = e.getScreenX();
  26714. ev.xcrossing.y_root = e.getScreenY();
  26715. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26716. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26717. translateJuceToXCrossingModifiers (e, ev);
  26718. sendEventToChild (&ev);
  26719. }
  26720. }
  26721. void mouseExit (const MouseEvent& e)
  26722. {
  26723. if (pluginWindow != 0)
  26724. {
  26725. XEvent ev;
  26726. zerostruct (ev);
  26727. ev.xcrossing.display = display;
  26728. ev.xcrossing.type = LeaveNotify;
  26729. ev.xcrossing.window = pluginWindow;
  26730. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26731. ev.xcrossing.time = CurrentTime;
  26732. ev.xcrossing.x = e.x;
  26733. ev.xcrossing.y = e.y;
  26734. ev.xcrossing.x_root = e.getScreenX();
  26735. ev.xcrossing.y_root = e.getScreenY();
  26736. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26737. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26738. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26739. translateJuceToXCrossingModifiers (e, ev);
  26740. sendEventToChild (&ev);
  26741. }
  26742. }
  26743. void mouseMove (const MouseEvent& e)
  26744. {
  26745. if (pluginWindow != 0)
  26746. {
  26747. XEvent ev;
  26748. zerostruct (ev);
  26749. ev.xmotion.display = display;
  26750. ev.xmotion.type = MotionNotify;
  26751. ev.xmotion.window = pluginWindow;
  26752. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26753. ev.xmotion.time = CurrentTime;
  26754. ev.xmotion.is_hint = NotifyNormal;
  26755. ev.xmotion.x = e.x;
  26756. ev.xmotion.y = e.y;
  26757. ev.xmotion.x_root = e.getScreenX();
  26758. ev.xmotion.y_root = e.getScreenY();
  26759. sendEventToChild (&ev);
  26760. }
  26761. }
  26762. void mouseDrag (const MouseEvent& e)
  26763. {
  26764. if (pluginWindow != 0)
  26765. {
  26766. XEvent ev;
  26767. zerostruct (ev);
  26768. ev.xmotion.display = display;
  26769. ev.xmotion.type = MotionNotify;
  26770. ev.xmotion.window = pluginWindow;
  26771. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26772. ev.xmotion.time = CurrentTime;
  26773. ev.xmotion.x = e.x ;
  26774. ev.xmotion.y = e.y;
  26775. ev.xmotion.x_root = e.getScreenX();
  26776. ev.xmotion.y_root = e.getScreenY();
  26777. ev.xmotion.is_hint = NotifyNormal;
  26778. translateJuceToXMotionModifiers (e, ev);
  26779. sendEventToChild (&ev);
  26780. }
  26781. }
  26782. void mouseUp (const MouseEvent& e)
  26783. {
  26784. if (pluginWindow != 0)
  26785. {
  26786. XEvent ev;
  26787. zerostruct (ev);
  26788. ev.xbutton.display = display;
  26789. ev.xbutton.type = ButtonRelease;
  26790. ev.xbutton.window = pluginWindow;
  26791. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26792. ev.xbutton.time = CurrentTime;
  26793. ev.xbutton.x = e.x;
  26794. ev.xbutton.y = e.y;
  26795. ev.xbutton.x_root = e.getScreenX();
  26796. ev.xbutton.y_root = e.getScreenY();
  26797. translateJuceToXButtonModifiers (e, ev);
  26798. sendEventToChild (&ev);
  26799. }
  26800. }
  26801. void mouseWheelMove (const MouseEvent& e,
  26802. float incrementX,
  26803. float incrementY)
  26804. {
  26805. if (pluginWindow != 0)
  26806. {
  26807. XEvent ev;
  26808. zerostruct (ev);
  26809. ev.xbutton.display = display;
  26810. ev.xbutton.type = ButtonPress;
  26811. ev.xbutton.window = pluginWindow;
  26812. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26813. ev.xbutton.time = CurrentTime;
  26814. ev.xbutton.x = e.x;
  26815. ev.xbutton.y = e.y;
  26816. ev.xbutton.x_root = e.getScreenX();
  26817. ev.xbutton.y_root = e.getScreenY();
  26818. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26819. sendEventToChild (&ev);
  26820. // TODO - put a usleep here ?
  26821. ev.xbutton.type = ButtonRelease;
  26822. sendEventToChild (&ev);
  26823. }
  26824. }
  26825. #endif
  26826. #if JUCE_MAC
  26827. #if ! JUCE_SUPPORT_CARBON
  26828. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26829. #endif
  26830. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26831. {
  26832. public:
  26833. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26834. : owner (owner_),
  26835. alreadyInside (false)
  26836. {
  26837. }
  26838. ~InnerWrapperComponent()
  26839. {
  26840. deleteWindow();
  26841. }
  26842. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26843. {
  26844. owner->openPluginWindow (windowRef);
  26845. return 0;
  26846. }
  26847. void removeView (HIViewRef)
  26848. {
  26849. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26850. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26851. }
  26852. bool getEmbeddedViewSize (int& w, int& h)
  26853. {
  26854. ERect* rect = 0;
  26855. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26856. w = rect->right - rect->left;
  26857. h = rect->bottom - rect->top;
  26858. return true;
  26859. }
  26860. void mouseDown (int x, int y)
  26861. {
  26862. if (! alreadyInside)
  26863. {
  26864. alreadyInside = true;
  26865. getTopLevelComponent()->toFront (true);
  26866. owner->dispatch (effEditMouse, x, y, 0, 0);
  26867. alreadyInside = false;
  26868. }
  26869. else
  26870. {
  26871. PostEvent (::mouseDown, 0);
  26872. }
  26873. }
  26874. void paint()
  26875. {
  26876. ComponentPeer* const peer = getPeer();
  26877. if (peer != 0)
  26878. {
  26879. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26880. ERect r;
  26881. r.left = pos.getX();
  26882. r.right = r.left + getWidth();
  26883. r.top = pos.getY();
  26884. r.bottom = r.top + getHeight();
  26885. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26886. }
  26887. }
  26888. private:
  26889. VSTPluginWindow* const owner;
  26890. bool alreadyInside;
  26891. };
  26892. friend class InnerWrapperComponent;
  26893. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26894. void resized()
  26895. {
  26896. innerWrapper->setSize (getWidth(), getHeight());
  26897. }
  26898. #endif
  26899. };
  26900. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26901. {
  26902. if (hasEditor())
  26903. return new VSTPluginWindow (*this);
  26904. return 0;
  26905. }
  26906. void VSTPluginInstance::handleAsyncUpdate()
  26907. {
  26908. // indicates that something about the plugin has changed..
  26909. updateHostDisplay();
  26910. }
  26911. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26912. {
  26913. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26914. {
  26915. changeProgramName (getCurrentProgram(), prog->prgName);
  26916. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26917. setParameter (i, vst_swapFloat (prog->params[i]));
  26918. return true;
  26919. }
  26920. return false;
  26921. }
  26922. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26923. const int dataSize)
  26924. {
  26925. if (dataSize < 28)
  26926. return false;
  26927. const fxSet* const set = (const fxSet*) data;
  26928. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26929. || vst_swap (set->version) > fxbVersionNum)
  26930. return false;
  26931. if (vst_swap (set->fxMagic) == 'FxBk')
  26932. {
  26933. // bank of programs
  26934. if (vst_swap (set->numPrograms) >= 0)
  26935. {
  26936. const int oldProg = getCurrentProgram();
  26937. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26938. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26939. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26940. {
  26941. if (i != oldProg)
  26942. {
  26943. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26944. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26945. return false;
  26946. if (vst_swap (set->numPrograms) > 0)
  26947. setCurrentProgram (i);
  26948. if (! restoreProgramSettings (prog))
  26949. return false;
  26950. }
  26951. }
  26952. if (vst_swap (set->numPrograms) > 0)
  26953. setCurrentProgram (oldProg);
  26954. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26955. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26956. return false;
  26957. if (! restoreProgramSettings (prog))
  26958. return false;
  26959. }
  26960. }
  26961. else if (vst_swap (set->fxMagic) == 'FxCk')
  26962. {
  26963. // single program
  26964. const fxProgram* const prog = (const fxProgram*) data;
  26965. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26966. return false;
  26967. changeProgramName (getCurrentProgram(), prog->prgName);
  26968. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26969. setParameter (i, vst_swapFloat (prog->params[i]));
  26970. }
  26971. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26972. {
  26973. // non-preset chunk
  26974. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26975. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26976. return false;
  26977. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26978. }
  26979. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26980. {
  26981. // preset chunk
  26982. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26983. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26984. return false;
  26985. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26986. changeProgramName (getCurrentProgram(), cset->name);
  26987. }
  26988. else
  26989. {
  26990. return false;
  26991. }
  26992. return true;
  26993. }
  26994. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26995. {
  26996. const int numParams = getNumParameters();
  26997. prog->chunkMagic = vst_swap ('CcnK');
  26998. prog->byteSize = 0;
  26999. prog->fxMagic = vst_swap ('FxCk');
  27000. prog->version = vst_swap (fxbVersionNum);
  27001. prog->fxID = vst_swap (getUID());
  27002. prog->fxVersion = vst_swap (getVersionNumber());
  27003. prog->numParams = vst_swap (numParams);
  27004. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27005. for (int i = 0; i < numParams; ++i)
  27006. prog->params[i] = vst_swapFloat (getParameter (i));
  27007. }
  27008. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27009. {
  27010. const int numPrograms = getNumPrograms();
  27011. const int numParams = getNumParameters();
  27012. if (usesChunks())
  27013. {
  27014. if (isFXB)
  27015. {
  27016. MemoryBlock chunk;
  27017. getChunkData (chunk, false, maxSizeMB);
  27018. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27019. dest.setSize (totalLen, true);
  27020. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27021. set->chunkMagic = vst_swap ('CcnK');
  27022. set->byteSize = 0;
  27023. set->fxMagic = vst_swap ('FBCh');
  27024. set->version = vst_swap (fxbVersionNum);
  27025. set->fxID = vst_swap (getUID());
  27026. set->fxVersion = vst_swap (getVersionNumber());
  27027. set->numPrograms = vst_swap (numPrograms);
  27028. set->chunkSize = vst_swap ((long) chunk.getSize());
  27029. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27030. }
  27031. else
  27032. {
  27033. MemoryBlock chunk;
  27034. getChunkData (chunk, true, maxSizeMB);
  27035. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27036. dest.setSize (totalLen, true);
  27037. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27038. set->chunkMagic = vst_swap ('CcnK');
  27039. set->byteSize = 0;
  27040. set->fxMagic = vst_swap ('FPCh');
  27041. set->version = vst_swap (fxbVersionNum);
  27042. set->fxID = vst_swap (getUID());
  27043. set->fxVersion = vst_swap (getVersionNumber());
  27044. set->numPrograms = vst_swap (numPrograms);
  27045. set->chunkSize = vst_swap ((long) chunk.getSize());
  27046. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27047. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27048. }
  27049. }
  27050. else
  27051. {
  27052. if (isFXB)
  27053. {
  27054. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27055. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27056. dest.setSize (len, true);
  27057. fxSet* const set = (fxSet*) dest.getData();
  27058. set->chunkMagic = vst_swap ('CcnK');
  27059. set->byteSize = 0;
  27060. set->fxMagic = vst_swap ('FxBk');
  27061. set->version = vst_swap (fxbVersionNum);
  27062. set->fxID = vst_swap (getUID());
  27063. set->fxVersion = vst_swap (getVersionNumber());
  27064. set->numPrograms = vst_swap (numPrograms);
  27065. const int oldProgram = getCurrentProgram();
  27066. MemoryBlock oldSettings;
  27067. createTempParameterStore (oldSettings);
  27068. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27069. for (int i = 0; i < numPrograms; ++i)
  27070. {
  27071. if (i != oldProgram)
  27072. {
  27073. setCurrentProgram (i);
  27074. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27075. }
  27076. }
  27077. setCurrentProgram (oldProgram);
  27078. restoreFromTempParameterStore (oldSettings);
  27079. }
  27080. else
  27081. {
  27082. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27083. dest.setSize (totalLen, true);
  27084. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27085. }
  27086. }
  27087. return true;
  27088. }
  27089. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27090. {
  27091. if (usesChunks())
  27092. {
  27093. void* data = 0;
  27094. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27095. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27096. {
  27097. mb.setSize (bytes);
  27098. mb.copyFrom (data, 0, bytes);
  27099. }
  27100. }
  27101. }
  27102. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27103. {
  27104. if (size > 0 && usesChunks())
  27105. {
  27106. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27107. if (! isPreset)
  27108. updateStoredProgramNames();
  27109. }
  27110. }
  27111. void VSTPluginInstance::timerCallback()
  27112. {
  27113. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27114. stopTimer();
  27115. }
  27116. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27117. {
  27118. const ScopedLock sl (lock);
  27119. ++insideVSTCallback;
  27120. int result = 0;
  27121. try
  27122. {
  27123. if (effect != 0)
  27124. {
  27125. #if JUCE_MAC
  27126. if (module->resFileId != 0)
  27127. UseResFile (module->resFileId);
  27128. CGrafPtr oldPort;
  27129. if (getActiveEditor() != 0)
  27130. {
  27131. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27132. GetPort (&oldPort);
  27133. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27134. SetOrigin (-pos.getX(), -pos.getY());
  27135. }
  27136. #endif
  27137. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27138. #if JUCE_MAC
  27139. if (getActiveEditor() != 0)
  27140. SetPort (oldPort);
  27141. module->resFileId = CurResFile();
  27142. #endif
  27143. --insideVSTCallback;
  27144. return result;
  27145. }
  27146. }
  27147. catch (...)
  27148. {
  27149. }
  27150. --insideVSTCallback;
  27151. return result;
  27152. }
  27153. // handles non plugin-specific callbacks..
  27154. static const int defaultVSTSampleRateValue = 16384;
  27155. static const int defaultVSTBlockSizeValue = 512;
  27156. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27157. {
  27158. (void) index;
  27159. (void) value;
  27160. (void) opt;
  27161. switch (opcode)
  27162. {
  27163. case audioMasterCanDo:
  27164. {
  27165. static const char* canDos[] = { "supplyIdle",
  27166. "sendVstEvents",
  27167. "sendVstMidiEvent",
  27168. "sendVstTimeInfo",
  27169. "receiveVstEvents",
  27170. "receiveVstMidiEvent",
  27171. "supportShell",
  27172. "shellCategory" };
  27173. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27174. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27175. return 1;
  27176. return 0;
  27177. }
  27178. case audioMasterVersion:
  27179. return 0x2400;
  27180. case audioMasterCurrentId:
  27181. return shellUIDToCreate;
  27182. case audioMasterGetNumAutomatableParameters:
  27183. return 0;
  27184. case audioMasterGetAutomationState:
  27185. return 1;
  27186. case audioMasterGetVendorVersion:
  27187. return 0x0101;
  27188. case audioMasterGetVendorString:
  27189. case audioMasterGetProductString:
  27190. {
  27191. String hostName ("Juce VST Host");
  27192. if (JUCEApplication::getInstance() != 0)
  27193. hostName = JUCEApplication::getInstance()->getApplicationName();
  27194. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27195. }
  27196. break;
  27197. case audioMasterGetSampleRate:
  27198. return (VstIntPtr) defaultVSTSampleRateValue;
  27199. case audioMasterGetBlockSize:
  27200. return (VstIntPtr) defaultVSTBlockSizeValue;
  27201. case audioMasterSetOutputSampleRate:
  27202. return 0;
  27203. default:
  27204. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27205. break;
  27206. }
  27207. return 0;
  27208. }
  27209. // handles callbacks for a specific plugin
  27210. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27211. {
  27212. switch (opcode)
  27213. {
  27214. case audioMasterAutomate:
  27215. sendParamChangeMessageToListeners (index, opt);
  27216. break;
  27217. case audioMasterProcessEvents:
  27218. handleMidiFromPlugin ((const VstEvents*) ptr);
  27219. break;
  27220. case audioMasterGetTime:
  27221. #if JUCE_MSVC
  27222. #pragma warning (push)
  27223. #pragma warning (disable: 4311)
  27224. #endif
  27225. return (VstIntPtr) &vstHostTime;
  27226. #if JUCE_MSVC
  27227. #pragma warning (pop)
  27228. #endif
  27229. break;
  27230. case audioMasterIdle:
  27231. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27232. {
  27233. ++insideVSTCallback;
  27234. #if JUCE_MAC
  27235. if (getActiveEditor() != 0)
  27236. dispatch (effEditIdle, 0, 0, 0, 0);
  27237. #endif
  27238. juce_callAnyTimersSynchronously();
  27239. handleUpdateNowIfNeeded();
  27240. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27241. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27242. --insideVSTCallback;
  27243. }
  27244. break;
  27245. case audioMasterUpdateDisplay:
  27246. triggerAsyncUpdate();
  27247. break;
  27248. case audioMasterTempoAt:
  27249. // returns (10000 * bpm)
  27250. break;
  27251. case audioMasterNeedIdle:
  27252. startTimer (50);
  27253. break;
  27254. case audioMasterSizeWindow:
  27255. if (getActiveEditor() != 0)
  27256. getActiveEditor()->setSize (index, value);
  27257. return 1;
  27258. case audioMasterGetSampleRate:
  27259. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27260. case audioMasterGetBlockSize:
  27261. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27262. case audioMasterWantMidi:
  27263. wantsMidiMessages = true;
  27264. break;
  27265. case audioMasterGetDirectory:
  27266. #if JUCE_MAC
  27267. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27268. #else
  27269. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27270. #endif
  27271. case audioMasterGetAutomationState:
  27272. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27273. break;
  27274. // none of these are handled (yet)..
  27275. case audioMasterBeginEdit:
  27276. case audioMasterEndEdit:
  27277. case audioMasterSetTime:
  27278. case audioMasterPinConnected:
  27279. case audioMasterGetParameterQuantization:
  27280. case audioMasterIOChanged:
  27281. case audioMasterGetInputLatency:
  27282. case audioMasterGetOutputLatency:
  27283. case audioMasterGetPreviousPlug:
  27284. case audioMasterGetNextPlug:
  27285. case audioMasterWillReplaceOrAccumulate:
  27286. case audioMasterGetCurrentProcessLevel:
  27287. case audioMasterOfflineStart:
  27288. case audioMasterOfflineRead:
  27289. case audioMasterOfflineWrite:
  27290. case audioMasterOfflineGetCurrentPass:
  27291. case audioMasterOfflineGetCurrentMetaPass:
  27292. case audioMasterVendorSpecific:
  27293. case audioMasterSetIcon:
  27294. case audioMasterGetLanguage:
  27295. case audioMasterOpenWindow:
  27296. case audioMasterCloseWindow:
  27297. break;
  27298. default:
  27299. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27300. }
  27301. return 0;
  27302. }
  27303. // entry point for all callbacks from the plugin
  27304. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27305. {
  27306. try
  27307. {
  27308. if (effect != 0 && effect->resvd2 != 0)
  27309. {
  27310. return ((VSTPluginInstance*)(effect->resvd2))
  27311. ->handleCallback (opcode, index, value, ptr, opt);
  27312. }
  27313. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27314. }
  27315. catch (...)
  27316. {
  27317. return 0;
  27318. }
  27319. }
  27320. const String VSTPluginInstance::getVersion() const throw()
  27321. {
  27322. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27323. String s;
  27324. if (v == 0 || v == -1)
  27325. v = getVersionNumber();
  27326. if (v != 0)
  27327. {
  27328. int versionBits[4];
  27329. int n = 0;
  27330. while (v != 0)
  27331. {
  27332. versionBits [n++] = (v & 0xff);
  27333. v >>= 8;
  27334. }
  27335. s << 'V';
  27336. while (n > 0)
  27337. {
  27338. s << versionBits [--n];
  27339. if (n > 0)
  27340. s << '.';
  27341. }
  27342. }
  27343. return s;
  27344. }
  27345. int VSTPluginInstance::getUID() const throw()
  27346. {
  27347. int uid = effect != 0 ? effect->uniqueID : 0;
  27348. if (uid == 0)
  27349. uid = module->file.hashCode();
  27350. return uid;
  27351. }
  27352. const String VSTPluginInstance::getCategory() const throw()
  27353. {
  27354. const char* result = 0;
  27355. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27356. {
  27357. case kPlugCategEffect:
  27358. result = "Effect";
  27359. break;
  27360. case kPlugCategSynth:
  27361. result = "Synth";
  27362. break;
  27363. case kPlugCategAnalysis:
  27364. result = "Anaylsis";
  27365. break;
  27366. case kPlugCategMastering:
  27367. result = "Mastering";
  27368. break;
  27369. case kPlugCategSpacializer:
  27370. result = "Spacial";
  27371. break;
  27372. case kPlugCategRoomFx:
  27373. result = "Reverb";
  27374. break;
  27375. case kPlugSurroundFx:
  27376. result = "Surround";
  27377. break;
  27378. case kPlugCategRestoration:
  27379. result = "Restoration";
  27380. break;
  27381. case kPlugCategGenerator:
  27382. result = "Tone generation";
  27383. break;
  27384. default:
  27385. break;
  27386. }
  27387. return result;
  27388. }
  27389. float VSTPluginInstance::getParameter (int index)
  27390. {
  27391. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27392. {
  27393. try
  27394. {
  27395. const ScopedLock sl (lock);
  27396. return effect->getParameter (effect, index);
  27397. }
  27398. catch (...)
  27399. {
  27400. }
  27401. }
  27402. return 0.0f;
  27403. }
  27404. void VSTPluginInstance::setParameter (int index, float newValue)
  27405. {
  27406. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27407. {
  27408. try
  27409. {
  27410. const ScopedLock sl (lock);
  27411. if (effect->getParameter (effect, index) != newValue)
  27412. effect->setParameter (effect, index, newValue);
  27413. }
  27414. catch (...)
  27415. {
  27416. }
  27417. }
  27418. }
  27419. const String VSTPluginInstance::getParameterName (int index)
  27420. {
  27421. if (effect != 0)
  27422. {
  27423. jassert (index >= 0 && index < effect->numParams);
  27424. char nm [256];
  27425. zerostruct (nm);
  27426. dispatch (effGetParamName, index, 0, nm, 0);
  27427. return String (nm).trim();
  27428. }
  27429. return String::empty;
  27430. }
  27431. const String VSTPluginInstance::getParameterLabel (int index) const
  27432. {
  27433. if (effect != 0)
  27434. {
  27435. jassert (index >= 0 && index < effect->numParams);
  27436. char nm [256];
  27437. zerostruct (nm);
  27438. dispatch (effGetParamLabel, index, 0, nm, 0);
  27439. return String (nm).trim();
  27440. }
  27441. return String::empty;
  27442. }
  27443. const String VSTPluginInstance::getParameterText (int index)
  27444. {
  27445. if (effect != 0)
  27446. {
  27447. jassert (index >= 0 && index < effect->numParams);
  27448. char nm [256];
  27449. zerostruct (nm);
  27450. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27451. return String (nm).trim();
  27452. }
  27453. return String::empty;
  27454. }
  27455. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27456. {
  27457. if (effect != 0)
  27458. {
  27459. jassert (index >= 0 && index < effect->numParams);
  27460. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27461. }
  27462. return false;
  27463. }
  27464. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27465. {
  27466. dest.setSize (64 + 4 * getNumParameters());
  27467. dest.fillWith (0);
  27468. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27469. float* const p = (float*) (((char*) dest.getData()) + 64);
  27470. for (int i = 0; i < getNumParameters(); ++i)
  27471. p[i] = getParameter(i);
  27472. }
  27473. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27474. {
  27475. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27476. float* p = (float*) (((char*) m.getData()) + 64);
  27477. for (int i = 0; i < getNumParameters(); ++i)
  27478. setParameter (i, p[i]);
  27479. }
  27480. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27481. {
  27482. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27483. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27484. }
  27485. const String VSTPluginInstance::getProgramName (int index)
  27486. {
  27487. if (index == getCurrentProgram())
  27488. {
  27489. return getCurrentProgramName();
  27490. }
  27491. else if (effect != 0)
  27492. {
  27493. char nm [256];
  27494. zerostruct (nm);
  27495. if (dispatch (effGetProgramNameIndexed,
  27496. jlimit (0, getNumPrograms(), index),
  27497. -1, nm, 0) != 0)
  27498. {
  27499. return String (nm).trim();
  27500. }
  27501. }
  27502. return programNames [index];
  27503. }
  27504. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27505. {
  27506. if (index == getCurrentProgram())
  27507. {
  27508. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27509. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27510. }
  27511. else
  27512. {
  27513. jassertfalse; // xxx not implemented!
  27514. }
  27515. }
  27516. void VSTPluginInstance::updateStoredProgramNames()
  27517. {
  27518. if (effect != 0 && getNumPrograms() > 0)
  27519. {
  27520. char nm [256];
  27521. zerostruct (nm);
  27522. // only do this if the plugin can't use indexed names..
  27523. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27524. {
  27525. const int oldProgram = getCurrentProgram();
  27526. MemoryBlock oldSettings;
  27527. createTempParameterStore (oldSettings);
  27528. for (int i = 0; i < getNumPrograms(); ++i)
  27529. {
  27530. setCurrentProgram (i);
  27531. getCurrentProgramName(); // (this updates the list)
  27532. }
  27533. setCurrentProgram (oldProgram);
  27534. restoreFromTempParameterStore (oldSettings);
  27535. }
  27536. }
  27537. }
  27538. const String VSTPluginInstance::getCurrentProgramName()
  27539. {
  27540. if (effect != 0)
  27541. {
  27542. char nm [256];
  27543. zerostruct (nm);
  27544. dispatch (effGetProgramName, 0, 0, nm, 0);
  27545. const int index = getCurrentProgram();
  27546. if (programNames[index].isEmpty())
  27547. {
  27548. while (programNames.size() < index)
  27549. programNames.add (String::empty);
  27550. programNames.set (index, String (nm).trim());
  27551. }
  27552. return String (nm).trim();
  27553. }
  27554. return String::empty;
  27555. }
  27556. const String VSTPluginInstance::getInputChannelName (const int index) const
  27557. {
  27558. if (index >= 0 && index < getNumInputChannels())
  27559. {
  27560. VstPinProperties pinProps;
  27561. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27562. return String (pinProps.label, sizeof (pinProps.label));
  27563. }
  27564. return String::empty;
  27565. }
  27566. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27567. {
  27568. if (index < 0 || index >= getNumInputChannels())
  27569. return false;
  27570. VstPinProperties pinProps;
  27571. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27572. return (pinProps.flags & kVstPinIsStereo) != 0;
  27573. return true;
  27574. }
  27575. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27576. {
  27577. if (index >= 0 && index < getNumOutputChannels())
  27578. {
  27579. VstPinProperties pinProps;
  27580. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27581. return String (pinProps.label, sizeof (pinProps.label));
  27582. }
  27583. return String::empty;
  27584. }
  27585. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27586. {
  27587. if (index < 0 || index >= getNumOutputChannels())
  27588. return false;
  27589. VstPinProperties pinProps;
  27590. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27591. return (pinProps.flags & kVstPinIsStereo) != 0;
  27592. return true;
  27593. }
  27594. void VSTPluginInstance::setPower (const bool on)
  27595. {
  27596. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27597. isPowerOn = on;
  27598. }
  27599. const int defaultMaxSizeMB = 64;
  27600. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27601. {
  27602. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27603. }
  27604. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27605. {
  27606. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27607. }
  27608. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27609. {
  27610. loadFromFXBFile (data, sizeInBytes);
  27611. }
  27612. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27613. {
  27614. loadFromFXBFile (data, sizeInBytes);
  27615. }
  27616. VSTPluginFormat::VSTPluginFormat()
  27617. {
  27618. }
  27619. VSTPluginFormat::~VSTPluginFormat()
  27620. {
  27621. }
  27622. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27623. const String& fileOrIdentifier)
  27624. {
  27625. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27626. return;
  27627. PluginDescription desc;
  27628. desc.fileOrIdentifier = fileOrIdentifier;
  27629. desc.uid = 0;
  27630. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27631. if (instance == 0)
  27632. return;
  27633. try
  27634. {
  27635. #if JUCE_MAC
  27636. if (instance->module->resFileId != 0)
  27637. UseResFile (instance->module->resFileId);
  27638. #endif
  27639. instance->fillInPluginDescription (desc);
  27640. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27641. if (category != kPlugCategShell)
  27642. {
  27643. // Normal plugin...
  27644. results.add (new PluginDescription (desc));
  27645. ++insideVSTCallback;
  27646. instance->dispatch (effOpen, 0, 0, 0, 0);
  27647. --insideVSTCallback;
  27648. }
  27649. else
  27650. {
  27651. // It's a shell plugin, so iterate all the subtypes...
  27652. char shellEffectName [64];
  27653. for (;;)
  27654. {
  27655. zerostruct (shellEffectName);
  27656. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27657. if (uid == 0)
  27658. {
  27659. break;
  27660. }
  27661. else
  27662. {
  27663. desc.uid = uid;
  27664. desc.name = shellEffectName;
  27665. bool alreadyThere = false;
  27666. for (int i = results.size(); --i >= 0;)
  27667. {
  27668. PluginDescription* const d = results.getUnchecked(i);
  27669. if (d->isDuplicateOf (desc))
  27670. {
  27671. alreadyThere = true;
  27672. break;
  27673. }
  27674. }
  27675. if (! alreadyThere)
  27676. results.add (new PluginDescription (desc));
  27677. }
  27678. }
  27679. }
  27680. }
  27681. catch (...)
  27682. {
  27683. // crashed while loading...
  27684. }
  27685. }
  27686. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27687. {
  27688. ScopedPointer <VSTPluginInstance> result;
  27689. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27690. {
  27691. File file (desc.fileOrIdentifier);
  27692. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27693. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27694. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27695. if (module != 0)
  27696. {
  27697. shellUIDToCreate = desc.uid;
  27698. result = new VSTPluginInstance (module);
  27699. if (result->effect != 0)
  27700. {
  27701. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27702. result->initialise();
  27703. }
  27704. else
  27705. {
  27706. result = 0;
  27707. }
  27708. }
  27709. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27710. }
  27711. return result.release();
  27712. }
  27713. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27714. {
  27715. const File f (fileOrIdentifier);
  27716. #if JUCE_MAC
  27717. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27718. return true;
  27719. #if JUCE_PPC
  27720. FSRef fileRef;
  27721. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27722. {
  27723. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27724. if (resFileId != -1)
  27725. {
  27726. const int numEffects = Count1Resources ('aEff');
  27727. CloseResFile (resFileId);
  27728. if (numEffects > 0)
  27729. return true;
  27730. }
  27731. }
  27732. #endif
  27733. return false;
  27734. #elif JUCE_WINDOWS
  27735. return f.existsAsFile()
  27736. && f.hasFileExtension (".dll");
  27737. #elif JUCE_LINUX
  27738. return f.existsAsFile()
  27739. && f.hasFileExtension (".so");
  27740. #endif
  27741. }
  27742. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27743. {
  27744. return fileOrIdentifier;
  27745. }
  27746. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27747. {
  27748. return File (desc.fileOrIdentifier).exists();
  27749. }
  27750. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27751. {
  27752. StringArray results;
  27753. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27754. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27755. return results;
  27756. }
  27757. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27758. {
  27759. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27760. // .component or .vst directories.
  27761. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27762. while (iter.next())
  27763. {
  27764. const File f (iter.getFile());
  27765. bool isPlugin = false;
  27766. if (fileMightContainThisPluginType (f.getFullPathName()))
  27767. {
  27768. isPlugin = true;
  27769. results.add (f.getFullPathName());
  27770. }
  27771. if (recursive && (! isPlugin) && f.isDirectory())
  27772. recursiveFileSearch (results, f, true);
  27773. }
  27774. }
  27775. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27776. {
  27777. #if JUCE_MAC
  27778. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27779. #elif JUCE_WINDOWS
  27780. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27781. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27782. #elif JUCE_LINUX
  27783. return FileSearchPath ("/usr/lib/vst");
  27784. #endif
  27785. }
  27786. END_JUCE_NAMESPACE
  27787. #endif
  27788. #undef log
  27789. #endif
  27790. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27791. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27792. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27793. BEGIN_JUCE_NAMESPACE
  27794. AudioProcessor::AudioProcessor()
  27795. : playHead (0),
  27796. activeEditor (0),
  27797. sampleRate (0),
  27798. blockSize (0),
  27799. numInputChannels (0),
  27800. numOutputChannels (0),
  27801. latencySamples (0),
  27802. suspended (false),
  27803. nonRealtime (false)
  27804. {
  27805. }
  27806. AudioProcessor::~AudioProcessor()
  27807. {
  27808. // ooh, nasty - the editor should have been deleted before the filter
  27809. // that it refers to is deleted..
  27810. jassert (activeEditor == 0);
  27811. #if JUCE_DEBUG
  27812. // This will fail if you've called beginParameterChangeGesture() for one
  27813. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27814. jassert (changingParams.countNumberOfSetBits() == 0);
  27815. #endif
  27816. }
  27817. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27818. {
  27819. playHead = newPlayHead;
  27820. }
  27821. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27822. {
  27823. const ScopedLock sl (listenerLock);
  27824. listeners.addIfNotAlreadyThere (newListener);
  27825. }
  27826. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27827. {
  27828. const ScopedLock sl (listenerLock);
  27829. listeners.removeValue (listenerToRemove);
  27830. }
  27831. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27832. const int numOuts,
  27833. const double sampleRate_,
  27834. const int blockSize_) throw()
  27835. {
  27836. numInputChannels = numIns;
  27837. numOutputChannels = numOuts;
  27838. sampleRate = sampleRate_;
  27839. blockSize = blockSize_;
  27840. }
  27841. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27842. {
  27843. nonRealtime = nonRealtime_;
  27844. }
  27845. void AudioProcessor::setLatencySamples (const int newLatency)
  27846. {
  27847. if (latencySamples != newLatency)
  27848. {
  27849. latencySamples = newLatency;
  27850. updateHostDisplay();
  27851. }
  27852. }
  27853. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27854. const float newValue)
  27855. {
  27856. setParameter (parameterIndex, newValue);
  27857. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27858. }
  27859. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27860. {
  27861. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27862. for (int i = listeners.size(); --i >= 0;)
  27863. {
  27864. AudioProcessorListener* l;
  27865. {
  27866. const ScopedLock sl (listenerLock);
  27867. l = listeners [i];
  27868. }
  27869. if (l != 0)
  27870. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27871. }
  27872. }
  27873. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27874. {
  27875. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27876. #if JUCE_DEBUG
  27877. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27878. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27879. jassert (! changingParams [parameterIndex]);
  27880. changingParams.setBit (parameterIndex);
  27881. #endif
  27882. for (int i = listeners.size(); --i >= 0;)
  27883. {
  27884. AudioProcessorListener* l;
  27885. {
  27886. const ScopedLock sl (listenerLock);
  27887. l = listeners [i];
  27888. }
  27889. if (l != 0)
  27890. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27891. }
  27892. }
  27893. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27894. {
  27895. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27896. #if JUCE_DEBUG
  27897. // This means you've called endParameterChangeGesture without having previously called
  27898. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27899. // calls matched correctly.
  27900. jassert (changingParams [parameterIndex]);
  27901. changingParams.clearBit (parameterIndex);
  27902. #endif
  27903. for (int i = listeners.size(); --i >= 0;)
  27904. {
  27905. AudioProcessorListener* l;
  27906. {
  27907. const ScopedLock sl (listenerLock);
  27908. l = listeners [i];
  27909. }
  27910. if (l != 0)
  27911. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27912. }
  27913. }
  27914. void AudioProcessor::updateHostDisplay()
  27915. {
  27916. for (int i = listeners.size(); --i >= 0;)
  27917. {
  27918. AudioProcessorListener* l;
  27919. {
  27920. const ScopedLock sl (listenerLock);
  27921. l = listeners [i];
  27922. }
  27923. if (l != 0)
  27924. l->audioProcessorChanged (this);
  27925. }
  27926. }
  27927. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27928. {
  27929. return true;
  27930. }
  27931. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27932. {
  27933. return false;
  27934. }
  27935. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27936. {
  27937. const ScopedLock sl (callbackLock);
  27938. suspended = shouldBeSuspended;
  27939. }
  27940. void AudioProcessor::reset()
  27941. {
  27942. }
  27943. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27944. {
  27945. const ScopedLock sl (callbackLock);
  27946. jassert (activeEditor == editor);
  27947. if (activeEditor == editor)
  27948. activeEditor = 0;
  27949. }
  27950. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27951. {
  27952. if (activeEditor != 0)
  27953. return activeEditor;
  27954. AudioProcessorEditor* const ed = createEditor();
  27955. if (ed != 0)
  27956. {
  27957. // you must give your editor comp a size before returning it..
  27958. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27959. const ScopedLock sl (callbackLock);
  27960. activeEditor = ed;
  27961. }
  27962. return ed;
  27963. }
  27964. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27965. {
  27966. getStateInformation (destData);
  27967. }
  27968. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27969. {
  27970. setStateInformation (data, sizeInBytes);
  27971. }
  27972. // magic number to identify memory blocks that we've stored as XML
  27973. const uint32 magicXmlNumber = 0x21324356;
  27974. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27975. JUCE_NAMESPACE::MemoryBlock& destData)
  27976. {
  27977. const String xmlString (xml.createDocument (String::empty, true, false));
  27978. const int stringLength = xmlString.getNumBytesAsUTF8();
  27979. destData.setSize (stringLength + 10);
  27980. char* const d = (char*) destData.getData();
  27981. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  27982. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  27983. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  27984. }
  27985. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27986. const int sizeInBytes)
  27987. {
  27988. if (sizeInBytes > 8
  27989. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  27990. {
  27991. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  27992. if (stringLength > 0)
  27993. {
  27994. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  27995. jmin ((sizeInBytes - 8), stringLength)));
  27996. return doc.getDocumentElement();
  27997. }
  27998. }
  27999. return 0;
  28000. }
  28001. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28002. {
  28003. }
  28004. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28005. {
  28006. }
  28007. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28008. {
  28009. return timeInSeconds == other.timeInSeconds
  28010. && ppqPosition == other.ppqPosition
  28011. && editOriginTime == other.editOriginTime
  28012. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28013. && frameRate == other.frameRate
  28014. && isPlaying == other.isPlaying
  28015. && isRecording == other.isRecording
  28016. && bpm == other.bpm
  28017. && timeSigNumerator == other.timeSigNumerator
  28018. && timeSigDenominator == other.timeSigDenominator;
  28019. }
  28020. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28021. {
  28022. return ! operator== (other);
  28023. }
  28024. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28025. {
  28026. zerostruct (*this);
  28027. timeSigNumerator = 4;
  28028. timeSigDenominator = 4;
  28029. bpm = 120;
  28030. }
  28031. END_JUCE_NAMESPACE
  28032. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28033. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28034. BEGIN_JUCE_NAMESPACE
  28035. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28036. : owner (owner_)
  28037. {
  28038. // the filter must be valid..
  28039. jassert (owner != 0);
  28040. }
  28041. AudioProcessorEditor::~AudioProcessorEditor()
  28042. {
  28043. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28044. // filter for some reason..
  28045. jassert (owner->getActiveEditor() != this);
  28046. }
  28047. END_JUCE_NAMESPACE
  28048. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28049. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28050. BEGIN_JUCE_NAMESPACE
  28051. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28052. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28053. : id (id_),
  28054. processor (processor_),
  28055. isPrepared (false)
  28056. {
  28057. jassert (processor_ != 0);
  28058. }
  28059. AudioProcessorGraph::Node::~Node()
  28060. {
  28061. delete processor;
  28062. }
  28063. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28064. AudioProcessorGraph* const graph)
  28065. {
  28066. if (! isPrepared)
  28067. {
  28068. isPrepared = true;
  28069. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28070. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28071. if (ioProc != 0)
  28072. ioProc->setParentGraph (graph);
  28073. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28074. processor->getNumOutputChannels(),
  28075. sampleRate, blockSize);
  28076. processor->prepareToPlay (sampleRate, blockSize);
  28077. }
  28078. }
  28079. void AudioProcessorGraph::Node::unprepare()
  28080. {
  28081. if (isPrepared)
  28082. {
  28083. isPrepared = false;
  28084. processor->releaseResources();
  28085. }
  28086. }
  28087. AudioProcessorGraph::AudioProcessorGraph()
  28088. : lastNodeId (0),
  28089. renderingBuffers (1, 1),
  28090. currentAudioOutputBuffer (1, 1)
  28091. {
  28092. }
  28093. AudioProcessorGraph::~AudioProcessorGraph()
  28094. {
  28095. clearRenderingSequence();
  28096. clear();
  28097. }
  28098. const String AudioProcessorGraph::getName() const
  28099. {
  28100. return "Audio Graph";
  28101. }
  28102. void AudioProcessorGraph::clear()
  28103. {
  28104. nodes.clear();
  28105. connections.clear();
  28106. triggerAsyncUpdate();
  28107. }
  28108. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28109. {
  28110. for (int i = nodes.size(); --i >= 0;)
  28111. if (nodes.getUnchecked(i)->id == nodeId)
  28112. return nodes.getUnchecked(i);
  28113. return 0;
  28114. }
  28115. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28116. uint32 nodeId)
  28117. {
  28118. if (newProcessor == 0)
  28119. {
  28120. jassertfalse;
  28121. return 0;
  28122. }
  28123. if (nodeId == 0)
  28124. {
  28125. nodeId = ++lastNodeId;
  28126. }
  28127. else
  28128. {
  28129. // you can't add a node with an id that already exists in the graph..
  28130. jassert (getNodeForId (nodeId) == 0);
  28131. removeNode (nodeId);
  28132. }
  28133. lastNodeId = nodeId;
  28134. Node* const n = new Node (nodeId, newProcessor);
  28135. nodes.add (n);
  28136. triggerAsyncUpdate();
  28137. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28138. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28139. if (ioProc != 0)
  28140. ioProc->setParentGraph (this);
  28141. return n;
  28142. }
  28143. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28144. {
  28145. disconnectNode (nodeId);
  28146. for (int i = nodes.size(); --i >= 0;)
  28147. {
  28148. if (nodes.getUnchecked(i)->id == nodeId)
  28149. {
  28150. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28151. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28152. if (ioProc != 0)
  28153. ioProc->setParentGraph (0);
  28154. nodes.remove (i);
  28155. triggerAsyncUpdate();
  28156. return true;
  28157. }
  28158. }
  28159. return false;
  28160. }
  28161. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28162. const int sourceChannelIndex,
  28163. const uint32 destNodeId,
  28164. const int destChannelIndex) const
  28165. {
  28166. for (int i = connections.size(); --i >= 0;)
  28167. {
  28168. const Connection* const c = connections.getUnchecked(i);
  28169. if (c->sourceNodeId == sourceNodeId
  28170. && c->destNodeId == destNodeId
  28171. && c->sourceChannelIndex == sourceChannelIndex
  28172. && c->destChannelIndex == destChannelIndex)
  28173. {
  28174. return c;
  28175. }
  28176. }
  28177. return 0;
  28178. }
  28179. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28180. const uint32 possibleDestNodeId) const
  28181. {
  28182. for (int i = connections.size(); --i >= 0;)
  28183. {
  28184. const Connection* const c = connections.getUnchecked(i);
  28185. if (c->sourceNodeId == possibleSourceNodeId
  28186. && c->destNodeId == possibleDestNodeId)
  28187. {
  28188. return true;
  28189. }
  28190. }
  28191. return false;
  28192. }
  28193. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28194. const int sourceChannelIndex,
  28195. const uint32 destNodeId,
  28196. const int destChannelIndex) const
  28197. {
  28198. if (sourceChannelIndex < 0
  28199. || destChannelIndex < 0
  28200. || sourceNodeId == destNodeId
  28201. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28202. return false;
  28203. const Node* const source = getNodeForId (sourceNodeId);
  28204. if (source == 0
  28205. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28206. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28207. return false;
  28208. const Node* const dest = getNodeForId (destNodeId);
  28209. if (dest == 0
  28210. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28211. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28212. return false;
  28213. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28214. destNodeId, destChannelIndex) == 0;
  28215. }
  28216. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28217. const int sourceChannelIndex,
  28218. const uint32 destNodeId,
  28219. const int destChannelIndex)
  28220. {
  28221. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28222. return false;
  28223. Connection* const c = new Connection();
  28224. c->sourceNodeId = sourceNodeId;
  28225. c->sourceChannelIndex = sourceChannelIndex;
  28226. c->destNodeId = destNodeId;
  28227. c->destChannelIndex = destChannelIndex;
  28228. connections.add (c);
  28229. triggerAsyncUpdate();
  28230. return true;
  28231. }
  28232. void AudioProcessorGraph::removeConnection (const int index)
  28233. {
  28234. connections.remove (index);
  28235. triggerAsyncUpdate();
  28236. }
  28237. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28238. const uint32 destNodeId, const int destChannelIndex)
  28239. {
  28240. bool doneAnything = false;
  28241. for (int i = connections.size(); --i >= 0;)
  28242. {
  28243. const Connection* const c = connections.getUnchecked(i);
  28244. if (c->sourceNodeId == sourceNodeId
  28245. && c->destNodeId == destNodeId
  28246. && c->sourceChannelIndex == sourceChannelIndex
  28247. && c->destChannelIndex == destChannelIndex)
  28248. {
  28249. removeConnection (i);
  28250. doneAnything = true;
  28251. triggerAsyncUpdate();
  28252. }
  28253. }
  28254. return doneAnything;
  28255. }
  28256. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28257. {
  28258. bool doneAnything = false;
  28259. for (int i = connections.size(); --i >= 0;)
  28260. {
  28261. const Connection* const c = connections.getUnchecked(i);
  28262. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28263. {
  28264. removeConnection (i);
  28265. doneAnything = true;
  28266. triggerAsyncUpdate();
  28267. }
  28268. }
  28269. return doneAnything;
  28270. }
  28271. bool AudioProcessorGraph::removeIllegalConnections()
  28272. {
  28273. bool doneAnything = false;
  28274. for (int i = connections.size(); --i >= 0;)
  28275. {
  28276. const Connection* const c = connections.getUnchecked(i);
  28277. const Node* const source = getNodeForId (c->sourceNodeId);
  28278. const Node* const dest = getNodeForId (c->destNodeId);
  28279. if (source == 0 || dest == 0
  28280. || (c->sourceChannelIndex != midiChannelIndex
  28281. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28282. || (c->sourceChannelIndex == midiChannelIndex
  28283. && ! source->processor->producesMidi())
  28284. || (c->destChannelIndex != midiChannelIndex
  28285. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28286. || (c->destChannelIndex == midiChannelIndex
  28287. && ! dest->processor->acceptsMidi()))
  28288. {
  28289. removeConnection (i);
  28290. doneAnything = true;
  28291. triggerAsyncUpdate();
  28292. }
  28293. }
  28294. return doneAnything;
  28295. }
  28296. namespace GraphRenderingOps
  28297. {
  28298. class AudioGraphRenderingOp
  28299. {
  28300. public:
  28301. AudioGraphRenderingOp() {}
  28302. virtual ~AudioGraphRenderingOp() {}
  28303. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28304. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28305. const int numSamples) = 0;
  28306. juce_UseDebuggingNewOperator
  28307. };
  28308. class ClearChannelOp : public AudioGraphRenderingOp
  28309. {
  28310. public:
  28311. ClearChannelOp (const int channelNum_)
  28312. : channelNum (channelNum_)
  28313. {}
  28314. ~ClearChannelOp() {}
  28315. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28316. {
  28317. sharedBufferChans.clear (channelNum, 0, numSamples);
  28318. }
  28319. private:
  28320. const int channelNum;
  28321. ClearChannelOp (const ClearChannelOp&);
  28322. ClearChannelOp& operator= (const ClearChannelOp&);
  28323. };
  28324. class CopyChannelOp : public AudioGraphRenderingOp
  28325. {
  28326. public:
  28327. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28328. : srcChannelNum (srcChannelNum_),
  28329. dstChannelNum (dstChannelNum_)
  28330. {}
  28331. ~CopyChannelOp() {}
  28332. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28333. {
  28334. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28335. }
  28336. private:
  28337. const int srcChannelNum, dstChannelNum;
  28338. CopyChannelOp (const CopyChannelOp&);
  28339. CopyChannelOp& operator= (const CopyChannelOp&);
  28340. };
  28341. class AddChannelOp : public AudioGraphRenderingOp
  28342. {
  28343. public:
  28344. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28345. : srcChannelNum (srcChannelNum_),
  28346. dstChannelNum (dstChannelNum_)
  28347. {}
  28348. ~AddChannelOp() {}
  28349. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28350. {
  28351. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28352. }
  28353. private:
  28354. const int srcChannelNum, dstChannelNum;
  28355. AddChannelOp (const AddChannelOp&);
  28356. AddChannelOp& operator= (const AddChannelOp&);
  28357. };
  28358. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28359. {
  28360. public:
  28361. ClearMidiBufferOp (const int bufferNum_)
  28362. : bufferNum (bufferNum_)
  28363. {}
  28364. ~ClearMidiBufferOp() {}
  28365. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28366. {
  28367. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28368. }
  28369. private:
  28370. const int bufferNum;
  28371. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28372. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28373. };
  28374. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28375. {
  28376. public:
  28377. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28378. : srcBufferNum (srcBufferNum_),
  28379. dstBufferNum (dstBufferNum_)
  28380. {}
  28381. ~CopyMidiBufferOp() {}
  28382. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28383. {
  28384. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28385. }
  28386. private:
  28387. const int srcBufferNum, dstBufferNum;
  28388. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28389. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28390. };
  28391. class AddMidiBufferOp : public AudioGraphRenderingOp
  28392. {
  28393. public:
  28394. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28395. : srcBufferNum (srcBufferNum_),
  28396. dstBufferNum (dstBufferNum_)
  28397. {}
  28398. ~AddMidiBufferOp() {}
  28399. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28400. {
  28401. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28402. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28403. }
  28404. private:
  28405. const int srcBufferNum, dstBufferNum;
  28406. AddMidiBufferOp (const AddMidiBufferOp&);
  28407. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28408. };
  28409. class ProcessBufferOp : public AudioGraphRenderingOp
  28410. {
  28411. public:
  28412. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28413. const Array <int>& audioChannelsToUse_,
  28414. const int totalChans_,
  28415. const int midiBufferToUse_)
  28416. : node (node_),
  28417. processor (node_->processor),
  28418. audioChannelsToUse (audioChannelsToUse_),
  28419. totalChans (jmax (1, totalChans_)),
  28420. midiBufferToUse (midiBufferToUse_)
  28421. {
  28422. channels.calloc (totalChans);
  28423. while (audioChannelsToUse.size() < totalChans)
  28424. audioChannelsToUse.add (0);
  28425. }
  28426. ~ProcessBufferOp()
  28427. {
  28428. }
  28429. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28430. {
  28431. for (int i = totalChans; --i >= 0;)
  28432. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28433. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28434. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28435. }
  28436. const AudioProcessorGraph::Node::Ptr node;
  28437. AudioProcessor* const processor;
  28438. private:
  28439. Array <int> audioChannelsToUse;
  28440. HeapBlock <float*> channels;
  28441. int totalChans;
  28442. int midiBufferToUse;
  28443. ProcessBufferOp (const ProcessBufferOp&);
  28444. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28445. };
  28446. /** Used to calculate the correct sequence of rendering ops needed, based on
  28447. the best re-use of shared buffers at each stage.
  28448. */
  28449. class RenderingOpSequenceCalculator
  28450. {
  28451. public:
  28452. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28453. const Array<void*>& orderedNodes_,
  28454. Array<void*>& renderingOps)
  28455. : graph (graph_),
  28456. orderedNodes (orderedNodes_)
  28457. {
  28458. nodeIds.add (-2); // first buffer is read-only zeros
  28459. channels.add (0);
  28460. midiNodeIds.add (-2);
  28461. for (int i = 0; i < orderedNodes.size(); ++i)
  28462. {
  28463. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28464. renderingOps, i);
  28465. markAnyUnusedBuffersAsFree (i);
  28466. }
  28467. }
  28468. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28469. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28470. juce_UseDebuggingNewOperator
  28471. private:
  28472. AudioProcessorGraph& graph;
  28473. const Array<void*>& orderedNodes;
  28474. Array <int> nodeIds, channels, midiNodeIds;
  28475. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28476. Array<void*>& renderingOps,
  28477. const int ourRenderingIndex)
  28478. {
  28479. const int numIns = node->processor->getNumInputChannels();
  28480. const int numOuts = node->processor->getNumOutputChannels();
  28481. const int totalChans = jmax (numIns, numOuts);
  28482. Array <int> audioChannelsToUse;
  28483. int midiBufferToUse = -1;
  28484. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28485. {
  28486. // get a list of all the inputs to this node
  28487. Array <int> sourceNodes, sourceOutputChans;
  28488. for (int i = graph.getNumConnections(); --i >= 0;)
  28489. {
  28490. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28491. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28492. {
  28493. sourceNodes.add (c->sourceNodeId);
  28494. sourceOutputChans.add (c->sourceChannelIndex);
  28495. }
  28496. }
  28497. int bufIndex = -1;
  28498. if (sourceNodes.size() == 0)
  28499. {
  28500. // unconnected input channel
  28501. if (inputChan >= numOuts)
  28502. {
  28503. bufIndex = getReadOnlyEmptyBuffer();
  28504. jassert (bufIndex >= 0);
  28505. }
  28506. else
  28507. {
  28508. bufIndex = getFreeBuffer (false);
  28509. renderingOps.add (new ClearChannelOp (bufIndex));
  28510. }
  28511. }
  28512. else if (sourceNodes.size() == 1)
  28513. {
  28514. // channel with a straightforward single input..
  28515. const int srcNode = sourceNodes.getUnchecked(0);
  28516. const int srcChan = sourceOutputChans.getUnchecked(0);
  28517. bufIndex = getBufferContaining (srcNode, srcChan);
  28518. if (bufIndex < 0)
  28519. {
  28520. // if not found, this is probably a feedback loop
  28521. bufIndex = getReadOnlyEmptyBuffer();
  28522. jassert (bufIndex >= 0);
  28523. }
  28524. if (inputChan < numOuts
  28525. && isBufferNeededLater (ourRenderingIndex,
  28526. inputChan,
  28527. srcNode, srcChan))
  28528. {
  28529. // can't mess up this channel because it's needed later by another node, so we
  28530. // need to use a copy of it..
  28531. const int newFreeBuffer = getFreeBuffer (false);
  28532. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28533. bufIndex = newFreeBuffer;
  28534. }
  28535. }
  28536. else
  28537. {
  28538. // channel with a mix of several inputs..
  28539. // try to find a re-usable channel from our inputs..
  28540. int reusableInputIndex = -1;
  28541. for (int i = 0; i < sourceNodes.size(); ++i)
  28542. {
  28543. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28544. sourceOutputChans.getUnchecked(i));
  28545. if (sourceBufIndex >= 0
  28546. && ! isBufferNeededLater (ourRenderingIndex,
  28547. inputChan,
  28548. sourceNodes.getUnchecked(i),
  28549. sourceOutputChans.getUnchecked(i)))
  28550. {
  28551. // we've found one of our input chans that can be re-used..
  28552. reusableInputIndex = i;
  28553. bufIndex = sourceBufIndex;
  28554. break;
  28555. }
  28556. }
  28557. if (reusableInputIndex < 0)
  28558. {
  28559. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28560. bufIndex = getFreeBuffer (false);
  28561. jassert (bufIndex != 0);
  28562. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28563. sourceOutputChans.getUnchecked (0));
  28564. if (srcIndex < 0)
  28565. {
  28566. // if not found, this is probably a feedback loop
  28567. renderingOps.add (new ClearChannelOp (bufIndex));
  28568. }
  28569. else
  28570. {
  28571. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28572. }
  28573. reusableInputIndex = 0;
  28574. }
  28575. for (int j = 0; j < sourceNodes.size(); ++j)
  28576. {
  28577. if (j != reusableInputIndex)
  28578. {
  28579. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28580. sourceOutputChans.getUnchecked(j));
  28581. if (srcIndex >= 0)
  28582. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28583. }
  28584. }
  28585. }
  28586. jassert (bufIndex >= 0);
  28587. audioChannelsToUse.add (bufIndex);
  28588. if (inputChan < numOuts)
  28589. markBufferAsContaining (bufIndex, node->id, inputChan);
  28590. }
  28591. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28592. {
  28593. const int bufIndex = getFreeBuffer (false);
  28594. jassert (bufIndex != 0);
  28595. audioChannelsToUse.add (bufIndex);
  28596. markBufferAsContaining (bufIndex, node->id, outputChan);
  28597. }
  28598. // Now the same thing for midi..
  28599. Array <int> midiSourceNodes;
  28600. for (int i = graph.getNumConnections(); --i >= 0;)
  28601. {
  28602. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28603. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28604. midiSourceNodes.add (c->sourceNodeId);
  28605. }
  28606. if (midiSourceNodes.size() == 0)
  28607. {
  28608. // No midi inputs..
  28609. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28610. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28611. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28612. }
  28613. else if (midiSourceNodes.size() == 1)
  28614. {
  28615. // One midi input..
  28616. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28617. AudioProcessorGraph::midiChannelIndex);
  28618. if (midiBufferToUse >= 0)
  28619. {
  28620. if (isBufferNeededLater (ourRenderingIndex,
  28621. AudioProcessorGraph::midiChannelIndex,
  28622. midiSourceNodes.getUnchecked(0),
  28623. AudioProcessorGraph::midiChannelIndex))
  28624. {
  28625. // can't mess up this channel because it's needed later by another node, so we
  28626. // need to use a copy of it..
  28627. const int newFreeBuffer = getFreeBuffer (true);
  28628. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28629. midiBufferToUse = newFreeBuffer;
  28630. }
  28631. }
  28632. else
  28633. {
  28634. // probably a feedback loop, so just use an empty one..
  28635. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28636. }
  28637. }
  28638. else
  28639. {
  28640. // More than one midi input being mixed..
  28641. int reusableInputIndex = -1;
  28642. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28643. {
  28644. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28645. AudioProcessorGraph::midiChannelIndex);
  28646. if (sourceBufIndex >= 0
  28647. && ! isBufferNeededLater (ourRenderingIndex,
  28648. AudioProcessorGraph::midiChannelIndex,
  28649. midiSourceNodes.getUnchecked(i),
  28650. AudioProcessorGraph::midiChannelIndex))
  28651. {
  28652. // we've found one of our input buffers that can be re-used..
  28653. reusableInputIndex = i;
  28654. midiBufferToUse = sourceBufIndex;
  28655. break;
  28656. }
  28657. }
  28658. if (reusableInputIndex < 0)
  28659. {
  28660. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28661. midiBufferToUse = getFreeBuffer (true);
  28662. jassert (midiBufferToUse >= 0);
  28663. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28664. AudioProcessorGraph::midiChannelIndex);
  28665. if (srcIndex >= 0)
  28666. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28667. else
  28668. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28669. reusableInputIndex = 0;
  28670. }
  28671. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28672. {
  28673. if (j != reusableInputIndex)
  28674. {
  28675. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28676. AudioProcessorGraph::midiChannelIndex);
  28677. if (srcIndex >= 0)
  28678. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28679. }
  28680. }
  28681. }
  28682. if (node->processor->producesMidi())
  28683. markBufferAsContaining (midiBufferToUse, node->id,
  28684. AudioProcessorGraph::midiChannelIndex);
  28685. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28686. totalChans, midiBufferToUse));
  28687. }
  28688. int getFreeBuffer (const bool forMidi)
  28689. {
  28690. if (forMidi)
  28691. {
  28692. for (int i = 1; i < midiNodeIds.size(); ++i)
  28693. if (midiNodeIds.getUnchecked(i) < 0)
  28694. return i;
  28695. midiNodeIds.add (-1);
  28696. return midiNodeIds.size() - 1;
  28697. }
  28698. else
  28699. {
  28700. for (int i = 1; i < nodeIds.size(); ++i)
  28701. if (nodeIds.getUnchecked(i) < 0)
  28702. return i;
  28703. nodeIds.add (-1);
  28704. channels.add (0);
  28705. return nodeIds.size() - 1;
  28706. }
  28707. }
  28708. int getReadOnlyEmptyBuffer() const
  28709. {
  28710. return 0;
  28711. }
  28712. int getBufferContaining (const int nodeId, const int outputChannel) const
  28713. {
  28714. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28715. {
  28716. for (int i = midiNodeIds.size(); --i >= 0;)
  28717. if (midiNodeIds.getUnchecked(i) == nodeId)
  28718. return i;
  28719. }
  28720. else
  28721. {
  28722. for (int i = nodeIds.size(); --i >= 0;)
  28723. if (nodeIds.getUnchecked(i) == nodeId
  28724. && channels.getUnchecked(i) == outputChannel)
  28725. return i;
  28726. }
  28727. return -1;
  28728. }
  28729. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28730. {
  28731. int i;
  28732. for (i = 0; i < nodeIds.size(); ++i)
  28733. {
  28734. if (nodeIds.getUnchecked(i) >= 0
  28735. && ! isBufferNeededLater (stepIndex, -1,
  28736. nodeIds.getUnchecked(i),
  28737. channels.getUnchecked(i)))
  28738. {
  28739. nodeIds.set (i, -1);
  28740. }
  28741. }
  28742. for (i = 0; i < midiNodeIds.size(); ++i)
  28743. {
  28744. if (midiNodeIds.getUnchecked(i) >= 0
  28745. && ! isBufferNeededLater (stepIndex, -1,
  28746. midiNodeIds.getUnchecked(i),
  28747. AudioProcessorGraph::midiChannelIndex))
  28748. {
  28749. midiNodeIds.set (i, -1);
  28750. }
  28751. }
  28752. }
  28753. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28754. int inputChannelOfIndexToIgnore,
  28755. const int nodeId,
  28756. const int outputChanIndex) const
  28757. {
  28758. while (stepIndexToSearchFrom < orderedNodes.size())
  28759. {
  28760. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28761. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28762. {
  28763. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28764. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28765. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28766. return true;
  28767. }
  28768. else
  28769. {
  28770. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28771. if (i != inputChannelOfIndexToIgnore
  28772. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28773. node->id, i) != 0)
  28774. return true;
  28775. }
  28776. inputChannelOfIndexToIgnore = -1;
  28777. ++stepIndexToSearchFrom;
  28778. }
  28779. return false;
  28780. }
  28781. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28782. {
  28783. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28784. {
  28785. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28786. midiNodeIds.set (bufferNum, nodeId);
  28787. }
  28788. else
  28789. {
  28790. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28791. nodeIds.set (bufferNum, nodeId);
  28792. channels.set (bufferNum, outputIndex);
  28793. }
  28794. }
  28795. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28796. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28797. };
  28798. }
  28799. void AudioProcessorGraph::clearRenderingSequence()
  28800. {
  28801. const ScopedLock sl (renderLock);
  28802. for (int i = renderingOps.size(); --i >= 0;)
  28803. {
  28804. GraphRenderingOps::AudioGraphRenderingOp* const r
  28805. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28806. renderingOps.remove (i);
  28807. delete r;
  28808. }
  28809. }
  28810. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28811. const uint32 possibleDestinationId,
  28812. const int recursionCheck) const
  28813. {
  28814. if (recursionCheck > 0)
  28815. {
  28816. for (int i = connections.size(); --i >= 0;)
  28817. {
  28818. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28819. if (c->destNodeId == possibleDestinationId
  28820. && (c->sourceNodeId == possibleInputId
  28821. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28822. return true;
  28823. }
  28824. }
  28825. return false;
  28826. }
  28827. void AudioProcessorGraph::buildRenderingSequence()
  28828. {
  28829. Array<void*> newRenderingOps;
  28830. int numRenderingBuffersNeeded = 2;
  28831. int numMidiBuffersNeeded = 1;
  28832. {
  28833. MessageManagerLock mml;
  28834. Array<void*> orderedNodes;
  28835. int i;
  28836. for (i = 0; i < nodes.size(); ++i)
  28837. {
  28838. Node* const node = nodes.getUnchecked(i);
  28839. node->prepare (getSampleRate(), getBlockSize(), this);
  28840. int j = 0;
  28841. for (; j < orderedNodes.size(); ++j)
  28842. if (isAnInputTo (node->id,
  28843. ((Node*) orderedNodes.getUnchecked (j))->id,
  28844. nodes.size() + 1))
  28845. break;
  28846. orderedNodes.insert (j, node);
  28847. }
  28848. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28849. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28850. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28851. }
  28852. Array<void*> oldRenderingOps (renderingOps);
  28853. {
  28854. // swap over to the new rendering sequence..
  28855. const ScopedLock sl (renderLock);
  28856. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28857. renderingBuffers.clear();
  28858. for (int i = midiBuffers.size(); --i >= 0;)
  28859. midiBuffers.getUnchecked(i)->clear();
  28860. while (midiBuffers.size() < numMidiBuffersNeeded)
  28861. midiBuffers.add (new MidiBuffer());
  28862. renderingOps = newRenderingOps;
  28863. }
  28864. for (int i = oldRenderingOps.size(); --i >= 0;)
  28865. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28866. }
  28867. void AudioProcessorGraph::handleAsyncUpdate()
  28868. {
  28869. buildRenderingSequence();
  28870. }
  28871. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28872. {
  28873. currentAudioInputBuffer = 0;
  28874. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28875. currentMidiInputBuffer = 0;
  28876. currentMidiOutputBuffer.clear();
  28877. clearRenderingSequence();
  28878. buildRenderingSequence();
  28879. }
  28880. void AudioProcessorGraph::releaseResources()
  28881. {
  28882. for (int i = 0; i < nodes.size(); ++i)
  28883. nodes.getUnchecked(i)->unprepare();
  28884. renderingBuffers.setSize (1, 1);
  28885. midiBuffers.clear();
  28886. currentAudioInputBuffer = 0;
  28887. currentAudioOutputBuffer.setSize (1, 1);
  28888. currentMidiInputBuffer = 0;
  28889. currentMidiOutputBuffer.clear();
  28890. }
  28891. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28892. {
  28893. const int numSamples = buffer.getNumSamples();
  28894. const ScopedLock sl (renderLock);
  28895. currentAudioInputBuffer = &buffer;
  28896. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28897. currentAudioOutputBuffer.clear();
  28898. currentMidiInputBuffer = &midiMessages;
  28899. currentMidiOutputBuffer.clear();
  28900. int i;
  28901. for (i = 0; i < renderingOps.size(); ++i)
  28902. {
  28903. GraphRenderingOps::AudioGraphRenderingOp* const op
  28904. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28905. op->perform (renderingBuffers, midiBuffers, numSamples);
  28906. }
  28907. for (i = 0; i < buffer.getNumChannels(); ++i)
  28908. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28909. midiMessages.clear();
  28910. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28911. }
  28912. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28913. {
  28914. return "Input " + String (channelIndex + 1);
  28915. }
  28916. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28917. {
  28918. return "Output " + String (channelIndex + 1);
  28919. }
  28920. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28921. {
  28922. return true;
  28923. }
  28924. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28925. {
  28926. return true;
  28927. }
  28928. bool AudioProcessorGraph::acceptsMidi() const
  28929. {
  28930. return true;
  28931. }
  28932. bool AudioProcessorGraph::producesMidi() const
  28933. {
  28934. return true;
  28935. }
  28936. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28937. {
  28938. }
  28939. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28940. {
  28941. }
  28942. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28943. : type (type_),
  28944. graph (0)
  28945. {
  28946. }
  28947. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28948. {
  28949. }
  28950. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28951. {
  28952. switch (type)
  28953. {
  28954. case audioOutputNode:
  28955. return "Audio Output";
  28956. case audioInputNode:
  28957. return "Audio Input";
  28958. case midiOutputNode:
  28959. return "Midi Output";
  28960. case midiInputNode:
  28961. return "Midi Input";
  28962. default:
  28963. break;
  28964. }
  28965. return String::empty;
  28966. }
  28967. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28968. {
  28969. d.name = getName();
  28970. d.uid = d.name.hashCode();
  28971. d.category = "I/O devices";
  28972. d.pluginFormatName = "Internal";
  28973. d.manufacturerName = "Raw Material Software";
  28974. d.version = "1.0";
  28975. d.isInstrument = false;
  28976. d.numInputChannels = getNumInputChannels();
  28977. if (type == audioOutputNode && graph != 0)
  28978. d.numInputChannels = graph->getNumInputChannels();
  28979. d.numOutputChannels = getNumOutputChannels();
  28980. if (type == audioInputNode && graph != 0)
  28981. d.numOutputChannels = graph->getNumOutputChannels();
  28982. }
  28983. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28984. {
  28985. jassert (graph != 0);
  28986. }
  28987. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28988. {
  28989. }
  28990. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28991. MidiBuffer& midiMessages)
  28992. {
  28993. jassert (graph != 0);
  28994. switch (type)
  28995. {
  28996. case audioOutputNode:
  28997. {
  28998. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  28999. buffer.getNumChannels()); --i >= 0;)
  29000. {
  29001. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29002. }
  29003. break;
  29004. }
  29005. case audioInputNode:
  29006. {
  29007. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29008. buffer.getNumChannels()); --i >= 0;)
  29009. {
  29010. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29011. }
  29012. break;
  29013. }
  29014. case midiOutputNode:
  29015. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29016. break;
  29017. case midiInputNode:
  29018. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29019. break;
  29020. default:
  29021. break;
  29022. }
  29023. }
  29024. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29025. {
  29026. return type == midiOutputNode;
  29027. }
  29028. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29029. {
  29030. return type == midiInputNode;
  29031. }
  29032. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29033. {
  29034. switch (type)
  29035. {
  29036. case audioOutputNode:
  29037. return "Output " + String (channelIndex + 1);
  29038. case midiOutputNode:
  29039. return "Midi Output";
  29040. default:
  29041. break;
  29042. }
  29043. return String::empty;
  29044. }
  29045. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29046. {
  29047. switch (type)
  29048. {
  29049. case audioInputNode:
  29050. return "Input " + String (channelIndex + 1);
  29051. case midiInputNode:
  29052. return "Midi Input";
  29053. default:
  29054. break;
  29055. }
  29056. return String::empty;
  29057. }
  29058. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29059. {
  29060. return type == audioInputNode || type == audioOutputNode;
  29061. }
  29062. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29063. {
  29064. return isInputChannelStereoPair (index);
  29065. }
  29066. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29067. {
  29068. return type == audioInputNode || type == midiInputNode;
  29069. }
  29070. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29071. {
  29072. return type == audioOutputNode || type == midiOutputNode;
  29073. }
  29074. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29075. {
  29076. return 0;
  29077. }
  29078. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29079. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29080. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29081. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29082. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29083. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29084. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29085. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29086. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29087. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29088. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29089. {
  29090. }
  29091. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29092. {
  29093. }
  29094. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29095. {
  29096. graph = newGraph;
  29097. if (graph != 0)
  29098. {
  29099. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29100. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29101. getSampleRate(),
  29102. getBlockSize());
  29103. updateHostDisplay();
  29104. }
  29105. }
  29106. END_JUCE_NAMESPACE
  29107. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29108. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29109. BEGIN_JUCE_NAMESPACE
  29110. AudioProcessorPlayer::AudioProcessorPlayer()
  29111. : processor (0),
  29112. sampleRate (0),
  29113. blockSize (0),
  29114. isPrepared (false),
  29115. numInputChans (0),
  29116. numOutputChans (0),
  29117. tempBuffer (1, 1)
  29118. {
  29119. }
  29120. AudioProcessorPlayer::~AudioProcessorPlayer()
  29121. {
  29122. setProcessor (0);
  29123. }
  29124. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29125. {
  29126. if (processor != processorToPlay)
  29127. {
  29128. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29129. {
  29130. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29131. sampleRate, blockSize);
  29132. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29133. }
  29134. AudioProcessor* oldOne;
  29135. {
  29136. const ScopedLock sl (lock);
  29137. oldOne = isPrepared ? processor : 0;
  29138. processor = processorToPlay;
  29139. isPrepared = true;
  29140. }
  29141. if (oldOne != 0)
  29142. oldOne->releaseResources();
  29143. }
  29144. }
  29145. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  29146. int numInputChannels,
  29147. float** outputChannelData,
  29148. int numOutputChannels,
  29149. int numSamples)
  29150. {
  29151. // these should have been prepared by audioDeviceAboutToStart()...
  29152. jassert (sampleRate > 0 && blockSize > 0);
  29153. incomingMidi.clear();
  29154. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29155. int i, totalNumChans = 0;
  29156. if (numInputChannels > numOutputChannels)
  29157. {
  29158. // if there aren't enough output channels for the number of
  29159. // inputs, we need to create some temporary extra ones (can't
  29160. // use the input data in case it gets written to)
  29161. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29162. false, false, true);
  29163. for (i = 0; i < numOutputChannels; ++i)
  29164. {
  29165. channels[totalNumChans] = outputChannelData[i];
  29166. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29167. ++totalNumChans;
  29168. }
  29169. for (i = numOutputChannels; i < numInputChannels; ++i)
  29170. {
  29171. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29172. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29173. ++totalNumChans;
  29174. }
  29175. }
  29176. else
  29177. {
  29178. for (i = 0; i < numInputChannels; ++i)
  29179. {
  29180. channels[totalNumChans] = outputChannelData[i];
  29181. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29182. ++totalNumChans;
  29183. }
  29184. for (i = numInputChannels; i < numOutputChannels; ++i)
  29185. {
  29186. channels[totalNumChans] = outputChannelData[i];
  29187. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29188. ++totalNumChans;
  29189. }
  29190. }
  29191. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29192. const ScopedLock sl (lock);
  29193. if (processor != 0)
  29194. {
  29195. const ScopedLock sl (processor->getCallbackLock());
  29196. if (! processor->isSuspended())
  29197. processor->processBlock (buffer, incomingMidi);
  29198. }
  29199. }
  29200. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29201. {
  29202. const ScopedLock sl (lock);
  29203. sampleRate = device->getCurrentSampleRate();
  29204. blockSize = device->getCurrentBufferSizeSamples();
  29205. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29206. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29207. messageCollector.reset (sampleRate);
  29208. zeromem (channels, sizeof (channels));
  29209. if (processor != 0)
  29210. {
  29211. if (isPrepared)
  29212. processor->releaseResources();
  29213. AudioProcessor* const oldProcessor = processor;
  29214. setProcessor (0);
  29215. setProcessor (oldProcessor);
  29216. }
  29217. }
  29218. void AudioProcessorPlayer::audioDeviceStopped()
  29219. {
  29220. const ScopedLock sl (lock);
  29221. if (processor != 0 && isPrepared)
  29222. processor->releaseResources();
  29223. sampleRate = 0.0;
  29224. blockSize = 0;
  29225. isPrepared = false;
  29226. tempBuffer.setSize (1, 1);
  29227. }
  29228. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29229. {
  29230. messageCollector.addMessageToQueue (message);
  29231. }
  29232. END_JUCE_NAMESPACE
  29233. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29234. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29235. BEGIN_JUCE_NAMESPACE
  29236. class ProcessorParameterPropertyComp : public PropertyComponent,
  29237. public AudioProcessorListener,
  29238. public AsyncUpdater
  29239. {
  29240. public:
  29241. ProcessorParameterPropertyComp (const String& name,
  29242. AudioProcessor* const owner_,
  29243. const int index_)
  29244. : PropertyComponent (name),
  29245. owner (owner_),
  29246. index (index_)
  29247. {
  29248. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29249. owner_->addListener (this);
  29250. }
  29251. ~ProcessorParameterPropertyComp()
  29252. {
  29253. owner->removeListener (this);
  29254. deleteAllChildren();
  29255. }
  29256. void refresh()
  29257. {
  29258. slider->setValue (owner->getParameter (index), false);
  29259. }
  29260. void audioProcessorChanged (AudioProcessor*) {}
  29261. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29262. {
  29263. if (parameterIndex == index)
  29264. triggerAsyncUpdate();
  29265. }
  29266. void handleAsyncUpdate()
  29267. {
  29268. refresh();
  29269. }
  29270. juce_UseDebuggingNewOperator
  29271. private:
  29272. AudioProcessor* const owner;
  29273. const int index;
  29274. Slider* slider;
  29275. class ParamSlider : public Slider
  29276. {
  29277. public:
  29278. ParamSlider (AudioProcessor* const owner_, const int index_)
  29279. : Slider (String::empty),
  29280. owner (owner_),
  29281. index (index_)
  29282. {
  29283. setRange (0.0, 1.0, 0.0);
  29284. setSliderStyle (Slider::LinearBar);
  29285. setTextBoxIsEditable (false);
  29286. setScrollWheelEnabled (false);
  29287. }
  29288. ~ParamSlider()
  29289. {
  29290. }
  29291. void valueChanged()
  29292. {
  29293. const float newVal = (float) getValue();
  29294. if (owner->getParameter (index) != newVal)
  29295. owner->setParameter (index, newVal);
  29296. }
  29297. const String getTextFromValue (double /*value*/)
  29298. {
  29299. return owner->getParameterText (index);
  29300. }
  29301. juce_UseDebuggingNewOperator
  29302. private:
  29303. AudioProcessor* const owner;
  29304. const int index;
  29305. ParamSlider (const ParamSlider&);
  29306. ParamSlider& operator= (const ParamSlider&);
  29307. };
  29308. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29309. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29310. };
  29311. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29312. : AudioProcessorEditor (owner_)
  29313. {
  29314. setOpaque (true);
  29315. addAndMakeVisible (panel = new PropertyPanel());
  29316. Array <PropertyComponent*> params;
  29317. const int numParams = owner_->getNumParameters();
  29318. int totalHeight = 0;
  29319. for (int i = 0; i < numParams; ++i)
  29320. {
  29321. String name (owner_->getParameterName (i));
  29322. if (name.trim().isEmpty())
  29323. name = "Unnamed";
  29324. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29325. params.add (pc);
  29326. totalHeight += pc->getPreferredHeight();
  29327. }
  29328. panel->addProperties (params);
  29329. setSize (400, jlimit (25, 400, totalHeight));
  29330. }
  29331. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29332. {
  29333. deleteAllChildren();
  29334. }
  29335. void GenericAudioProcessorEditor::paint (Graphics& g)
  29336. {
  29337. g.fillAll (Colours::white);
  29338. }
  29339. void GenericAudioProcessorEditor::resized()
  29340. {
  29341. panel->setSize (getWidth(), getHeight());
  29342. }
  29343. END_JUCE_NAMESPACE
  29344. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29345. /*** Start of inlined file: juce_Sampler.cpp ***/
  29346. BEGIN_JUCE_NAMESPACE
  29347. SamplerSound::SamplerSound (const String& name_,
  29348. AudioFormatReader& source,
  29349. const BigInteger& midiNotes_,
  29350. const int midiNoteForNormalPitch,
  29351. const double attackTimeSecs,
  29352. const double releaseTimeSecs,
  29353. const double maxSampleLengthSeconds)
  29354. : name (name_),
  29355. midiNotes (midiNotes_),
  29356. midiRootNote (midiNoteForNormalPitch)
  29357. {
  29358. sourceSampleRate = source.sampleRate;
  29359. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29360. {
  29361. length = 0;
  29362. attackSamples = 0;
  29363. releaseSamples = 0;
  29364. }
  29365. else
  29366. {
  29367. length = jmin ((int) source.lengthInSamples,
  29368. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29369. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29370. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29371. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29372. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29373. }
  29374. }
  29375. SamplerSound::~SamplerSound()
  29376. {
  29377. }
  29378. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29379. {
  29380. return midiNotes [midiNoteNumber];
  29381. }
  29382. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29383. {
  29384. return true;
  29385. }
  29386. SamplerVoice::SamplerVoice()
  29387. : pitchRatio (0.0),
  29388. sourceSamplePosition (0.0),
  29389. lgain (0.0f),
  29390. rgain (0.0f),
  29391. isInAttack (false),
  29392. isInRelease (false)
  29393. {
  29394. }
  29395. SamplerVoice::~SamplerVoice()
  29396. {
  29397. }
  29398. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29399. {
  29400. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29401. }
  29402. void SamplerVoice::startNote (const int midiNoteNumber,
  29403. const float velocity,
  29404. SynthesiserSound* s,
  29405. const int /*currentPitchWheelPosition*/)
  29406. {
  29407. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29408. jassert (sound != 0); // this object can only play SamplerSounds!
  29409. if (sound != 0)
  29410. {
  29411. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29412. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29413. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29414. sourceSamplePosition = 0.0;
  29415. lgain = velocity;
  29416. rgain = velocity;
  29417. isInAttack = (sound->attackSamples > 0);
  29418. isInRelease = false;
  29419. if (isInAttack)
  29420. {
  29421. attackReleaseLevel = 0.0f;
  29422. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29423. }
  29424. else
  29425. {
  29426. attackReleaseLevel = 1.0f;
  29427. attackDelta = 0.0f;
  29428. }
  29429. if (sound->releaseSamples > 0)
  29430. {
  29431. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29432. }
  29433. else
  29434. {
  29435. releaseDelta = 0.0f;
  29436. }
  29437. }
  29438. }
  29439. void SamplerVoice::stopNote (const bool allowTailOff)
  29440. {
  29441. if (allowTailOff)
  29442. {
  29443. isInAttack = false;
  29444. isInRelease = true;
  29445. }
  29446. else
  29447. {
  29448. clearCurrentNote();
  29449. }
  29450. }
  29451. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29452. {
  29453. }
  29454. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29455. const int /*newValue*/)
  29456. {
  29457. }
  29458. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29459. {
  29460. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29461. if (playingSound != 0)
  29462. {
  29463. const float* const inL = playingSound->data->getSampleData (0, 0);
  29464. const float* const inR = playingSound->data->getNumChannels() > 1
  29465. ? playingSound->data->getSampleData (1, 0) : 0;
  29466. float* outL = outputBuffer.getSampleData (0, startSample);
  29467. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29468. while (--numSamples >= 0)
  29469. {
  29470. const int pos = (int) sourceSamplePosition;
  29471. const float alpha = (float) (sourceSamplePosition - pos);
  29472. const float invAlpha = 1.0f - alpha;
  29473. // just using a very simple linear interpolation here..
  29474. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29475. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29476. : l;
  29477. l *= lgain;
  29478. r *= rgain;
  29479. if (isInAttack)
  29480. {
  29481. l *= attackReleaseLevel;
  29482. r *= attackReleaseLevel;
  29483. attackReleaseLevel += attackDelta;
  29484. if (attackReleaseLevel >= 1.0f)
  29485. {
  29486. attackReleaseLevel = 1.0f;
  29487. isInAttack = false;
  29488. }
  29489. }
  29490. else if (isInRelease)
  29491. {
  29492. l *= attackReleaseLevel;
  29493. r *= attackReleaseLevel;
  29494. attackReleaseLevel += releaseDelta;
  29495. if (attackReleaseLevel <= 0.0f)
  29496. {
  29497. stopNote (false);
  29498. break;
  29499. }
  29500. }
  29501. if (outR != 0)
  29502. {
  29503. *outL++ += l;
  29504. *outR++ += r;
  29505. }
  29506. else
  29507. {
  29508. *outL++ += (l + r) * 0.5f;
  29509. }
  29510. sourceSamplePosition += pitchRatio;
  29511. if (sourceSamplePosition > playingSound->length)
  29512. {
  29513. stopNote (false);
  29514. break;
  29515. }
  29516. }
  29517. }
  29518. }
  29519. END_JUCE_NAMESPACE
  29520. /*** End of inlined file: juce_Sampler.cpp ***/
  29521. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29522. BEGIN_JUCE_NAMESPACE
  29523. SynthesiserSound::SynthesiserSound()
  29524. {
  29525. }
  29526. SynthesiserSound::~SynthesiserSound()
  29527. {
  29528. }
  29529. SynthesiserVoice::SynthesiserVoice()
  29530. : currentSampleRate (44100.0),
  29531. currentlyPlayingNote (-1),
  29532. noteOnTime (0),
  29533. currentlyPlayingSound (0)
  29534. {
  29535. }
  29536. SynthesiserVoice::~SynthesiserVoice()
  29537. {
  29538. }
  29539. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29540. {
  29541. return currentlyPlayingSound != 0
  29542. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29543. }
  29544. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29545. {
  29546. currentSampleRate = newRate;
  29547. }
  29548. void SynthesiserVoice::clearCurrentNote()
  29549. {
  29550. currentlyPlayingNote = -1;
  29551. currentlyPlayingSound = 0;
  29552. }
  29553. Synthesiser::Synthesiser()
  29554. : sampleRate (0),
  29555. lastNoteOnCounter (0),
  29556. shouldStealNotes (true)
  29557. {
  29558. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29559. lastPitchWheelValues[i] = 0x2000;
  29560. }
  29561. Synthesiser::~Synthesiser()
  29562. {
  29563. }
  29564. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29565. {
  29566. const ScopedLock sl (lock);
  29567. return voices [index];
  29568. }
  29569. void Synthesiser::clearVoices()
  29570. {
  29571. const ScopedLock sl (lock);
  29572. voices.clear();
  29573. }
  29574. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29575. {
  29576. const ScopedLock sl (lock);
  29577. voices.add (newVoice);
  29578. }
  29579. void Synthesiser::removeVoice (const int index)
  29580. {
  29581. const ScopedLock sl (lock);
  29582. voices.remove (index);
  29583. }
  29584. void Synthesiser::clearSounds()
  29585. {
  29586. const ScopedLock sl (lock);
  29587. sounds.clear();
  29588. }
  29589. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29590. {
  29591. const ScopedLock sl (lock);
  29592. sounds.add (newSound);
  29593. }
  29594. void Synthesiser::removeSound (const int index)
  29595. {
  29596. const ScopedLock sl (lock);
  29597. sounds.remove (index);
  29598. }
  29599. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29600. {
  29601. shouldStealNotes = shouldStealNotes_;
  29602. }
  29603. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29604. {
  29605. if (sampleRate != newRate)
  29606. {
  29607. const ScopedLock sl (lock);
  29608. allNotesOff (0, false);
  29609. sampleRate = newRate;
  29610. for (int i = voices.size(); --i >= 0;)
  29611. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29612. }
  29613. }
  29614. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29615. const MidiBuffer& midiData,
  29616. int startSample,
  29617. int numSamples)
  29618. {
  29619. // must set the sample rate before using this!
  29620. jassert (sampleRate != 0);
  29621. const ScopedLock sl (lock);
  29622. MidiBuffer::Iterator midiIterator (midiData);
  29623. midiIterator.setNextSamplePosition (startSample);
  29624. MidiMessage m (0xf4, 0.0);
  29625. while (numSamples > 0)
  29626. {
  29627. int midiEventPos;
  29628. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29629. && midiEventPos < startSample + numSamples;
  29630. const int numThisTime = useEvent ? midiEventPos - startSample
  29631. : numSamples;
  29632. if (numThisTime > 0)
  29633. {
  29634. for (int i = voices.size(); --i >= 0;)
  29635. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29636. }
  29637. if (useEvent)
  29638. {
  29639. if (m.isNoteOn())
  29640. {
  29641. const int channel = m.getChannel();
  29642. noteOn (channel,
  29643. m.getNoteNumber(),
  29644. m.getFloatVelocity());
  29645. }
  29646. else if (m.isNoteOff())
  29647. {
  29648. noteOff (m.getChannel(),
  29649. m.getNoteNumber(),
  29650. true);
  29651. }
  29652. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29653. {
  29654. allNotesOff (m.getChannel(), true);
  29655. }
  29656. else if (m.isPitchWheel())
  29657. {
  29658. const int channel = m.getChannel();
  29659. const int wheelPos = m.getPitchWheelValue();
  29660. lastPitchWheelValues [channel - 1] = wheelPos;
  29661. handlePitchWheel (channel, wheelPos);
  29662. }
  29663. else if (m.isController())
  29664. {
  29665. handleController (m.getChannel(),
  29666. m.getControllerNumber(),
  29667. m.getControllerValue());
  29668. }
  29669. }
  29670. startSample += numThisTime;
  29671. numSamples -= numThisTime;
  29672. }
  29673. }
  29674. void Synthesiser::noteOn (const int midiChannel,
  29675. const int midiNoteNumber,
  29676. const float velocity)
  29677. {
  29678. const ScopedLock sl (lock);
  29679. for (int i = sounds.size(); --i >= 0;)
  29680. {
  29681. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29682. if (sound->appliesToNote (midiNoteNumber)
  29683. && sound->appliesToChannel (midiChannel))
  29684. {
  29685. startVoice (findFreeVoice (sound, shouldStealNotes),
  29686. sound, midiChannel, midiNoteNumber, velocity);
  29687. }
  29688. }
  29689. }
  29690. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29691. SynthesiserSound* const sound,
  29692. const int midiChannel,
  29693. const int midiNoteNumber,
  29694. const float velocity)
  29695. {
  29696. if (voice != 0 && sound != 0)
  29697. {
  29698. if (voice->currentlyPlayingSound != 0)
  29699. voice->stopNote (false);
  29700. voice->startNote (midiNoteNumber,
  29701. velocity,
  29702. sound,
  29703. lastPitchWheelValues [midiChannel - 1]);
  29704. voice->currentlyPlayingNote = midiNoteNumber;
  29705. voice->noteOnTime = ++lastNoteOnCounter;
  29706. voice->currentlyPlayingSound = sound;
  29707. }
  29708. }
  29709. void Synthesiser::noteOff (const int midiChannel,
  29710. const int midiNoteNumber,
  29711. const bool allowTailOff)
  29712. {
  29713. const ScopedLock sl (lock);
  29714. for (int i = voices.size(); --i >= 0;)
  29715. {
  29716. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29717. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29718. {
  29719. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29720. if (sound != 0
  29721. && sound->appliesToNote (midiNoteNumber)
  29722. && sound->appliesToChannel (midiChannel))
  29723. {
  29724. voice->stopNote (allowTailOff);
  29725. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29726. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29727. }
  29728. }
  29729. }
  29730. }
  29731. void Synthesiser::allNotesOff (const int midiChannel,
  29732. const bool allowTailOff)
  29733. {
  29734. const ScopedLock sl (lock);
  29735. for (int i = voices.size(); --i >= 0;)
  29736. {
  29737. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29738. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29739. voice->stopNote (allowTailOff);
  29740. }
  29741. }
  29742. void Synthesiser::handlePitchWheel (const int midiChannel,
  29743. const int wheelValue)
  29744. {
  29745. const ScopedLock sl (lock);
  29746. for (int i = voices.size(); --i >= 0;)
  29747. {
  29748. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29749. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29750. {
  29751. voice->pitchWheelMoved (wheelValue);
  29752. }
  29753. }
  29754. }
  29755. void Synthesiser::handleController (const int midiChannel,
  29756. const int controllerNumber,
  29757. const int controllerValue)
  29758. {
  29759. const ScopedLock sl (lock);
  29760. for (int i = voices.size(); --i >= 0;)
  29761. {
  29762. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29763. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29764. voice->controllerMoved (controllerNumber, controllerValue);
  29765. }
  29766. }
  29767. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29768. const bool stealIfNoneAvailable) const
  29769. {
  29770. const ScopedLock sl (lock);
  29771. for (int i = voices.size(); --i >= 0;)
  29772. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29773. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29774. return voices.getUnchecked (i);
  29775. if (stealIfNoneAvailable)
  29776. {
  29777. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29778. SynthesiserVoice* oldest = 0;
  29779. for (int i = voices.size(); --i >= 0;)
  29780. {
  29781. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29782. if (voice->canPlaySound (soundToPlay)
  29783. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29784. oldest = voice;
  29785. }
  29786. jassert (oldest != 0);
  29787. return oldest;
  29788. }
  29789. return 0;
  29790. }
  29791. END_JUCE_NAMESPACE
  29792. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29793. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29794. BEGIN_JUCE_NAMESPACE
  29795. ActionBroadcaster::ActionBroadcaster() throw()
  29796. {
  29797. // are you trying to create this object before or after juce has been intialised??
  29798. jassert (MessageManager::instance != 0);
  29799. }
  29800. ActionBroadcaster::~ActionBroadcaster()
  29801. {
  29802. // all event-based objects must be deleted BEFORE juce is shut down!
  29803. jassert (MessageManager::instance != 0);
  29804. }
  29805. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29806. {
  29807. actionListenerList.addActionListener (listener);
  29808. }
  29809. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29810. {
  29811. jassert (actionListenerList.isValidMessageListener());
  29812. if (actionListenerList.isValidMessageListener())
  29813. actionListenerList.removeActionListener (listener);
  29814. }
  29815. void ActionBroadcaster::removeAllActionListeners()
  29816. {
  29817. actionListenerList.removeAllActionListeners();
  29818. }
  29819. void ActionBroadcaster::sendActionMessage (const String& message) const
  29820. {
  29821. actionListenerList.sendActionMessage (message);
  29822. }
  29823. END_JUCE_NAMESPACE
  29824. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29825. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29826. BEGIN_JUCE_NAMESPACE
  29827. // special message of our own with a string in it
  29828. class ActionMessage : public Message
  29829. {
  29830. public:
  29831. const String message;
  29832. ActionMessage (const String& messageText,
  29833. void* const listener_) throw()
  29834. : message (messageText)
  29835. {
  29836. pointerParameter = listener_;
  29837. }
  29838. ~ActionMessage() throw()
  29839. {
  29840. }
  29841. private:
  29842. ActionMessage (const ActionMessage&);
  29843. ActionMessage& operator= (const ActionMessage&);
  29844. };
  29845. ActionListenerList::ActionListenerList() throw()
  29846. {
  29847. }
  29848. ActionListenerList::~ActionListenerList() throw()
  29849. {
  29850. }
  29851. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29852. {
  29853. const ScopedLock sl (actionListenerLock_);
  29854. jassert (listener != 0);
  29855. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29856. if (listener != 0)
  29857. actionListeners_.add (listener);
  29858. }
  29859. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29860. {
  29861. const ScopedLock sl (actionListenerLock_);
  29862. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29863. actionListeners_.removeValue (listener);
  29864. }
  29865. void ActionListenerList::removeAllActionListeners() throw()
  29866. {
  29867. const ScopedLock sl (actionListenerLock_);
  29868. actionListeners_.clear();
  29869. }
  29870. void ActionListenerList::sendActionMessage (const String& message) const
  29871. {
  29872. const ScopedLock sl (actionListenerLock_);
  29873. for (int i = actionListeners_.size(); --i >= 0;)
  29874. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29875. }
  29876. void ActionListenerList::handleMessage (const Message& message)
  29877. {
  29878. const ActionMessage& am = (const ActionMessage&) message;
  29879. if (actionListeners_.contains (am.pointerParameter))
  29880. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29881. }
  29882. END_JUCE_NAMESPACE
  29883. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29884. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29885. BEGIN_JUCE_NAMESPACE
  29886. AsyncUpdater::AsyncUpdater() throw()
  29887. : asyncMessagePending (false)
  29888. {
  29889. internalAsyncHandler.owner = this;
  29890. }
  29891. AsyncUpdater::~AsyncUpdater()
  29892. {
  29893. }
  29894. void AsyncUpdater::triggerAsyncUpdate() throw()
  29895. {
  29896. if (! asyncMessagePending)
  29897. {
  29898. asyncMessagePending = true;
  29899. internalAsyncHandler.postMessage (new Message());
  29900. }
  29901. }
  29902. void AsyncUpdater::cancelPendingUpdate() throw()
  29903. {
  29904. asyncMessagePending = false;
  29905. }
  29906. void AsyncUpdater::handleUpdateNowIfNeeded()
  29907. {
  29908. if (asyncMessagePending)
  29909. {
  29910. asyncMessagePending = false;
  29911. handleAsyncUpdate();
  29912. }
  29913. }
  29914. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29915. {
  29916. owner->handleUpdateNowIfNeeded();
  29917. }
  29918. END_JUCE_NAMESPACE
  29919. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29920. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29921. BEGIN_JUCE_NAMESPACE
  29922. ChangeBroadcaster::ChangeBroadcaster() throw()
  29923. {
  29924. // are you trying to create this object before or after juce has been intialised??
  29925. jassert (MessageManager::instance != 0);
  29926. }
  29927. ChangeBroadcaster::~ChangeBroadcaster()
  29928. {
  29929. // all event-based objects must be deleted BEFORE juce is shut down!
  29930. jassert (MessageManager::instance != 0);
  29931. }
  29932. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29933. {
  29934. changeListenerList.addChangeListener (listener);
  29935. }
  29936. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29937. {
  29938. jassert (changeListenerList.isValidMessageListener());
  29939. if (changeListenerList.isValidMessageListener())
  29940. changeListenerList.removeChangeListener (listener);
  29941. }
  29942. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29943. {
  29944. changeListenerList.removeAllChangeListeners();
  29945. }
  29946. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29947. {
  29948. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29949. }
  29950. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29951. {
  29952. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29953. }
  29954. void ChangeBroadcaster::dispatchPendingMessages()
  29955. {
  29956. changeListenerList.dispatchPendingMessages();
  29957. }
  29958. END_JUCE_NAMESPACE
  29959. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  29960. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  29961. BEGIN_JUCE_NAMESPACE
  29962. ChangeListenerList::ChangeListenerList() throw()
  29963. : lastChangedObject (0),
  29964. messagePending (false)
  29965. {
  29966. }
  29967. ChangeListenerList::~ChangeListenerList() throw()
  29968. {
  29969. }
  29970. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29971. {
  29972. const ScopedLock sl (lock);
  29973. jassert (listener != 0);
  29974. if (listener != 0)
  29975. listeners.add (listener);
  29976. }
  29977. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29978. {
  29979. const ScopedLock sl (lock);
  29980. listeners.removeValue (listener);
  29981. }
  29982. void ChangeListenerList::removeAllChangeListeners() throw()
  29983. {
  29984. const ScopedLock sl (lock);
  29985. listeners.clear();
  29986. }
  29987. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29988. {
  29989. const ScopedLock sl (lock);
  29990. if ((! messagePending) && (listeners.size() > 0))
  29991. {
  29992. lastChangedObject = objectThatHasChanged;
  29993. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29994. messagePending = true;
  29995. }
  29996. }
  29997. void ChangeListenerList::handleMessage (const Message& message)
  29998. {
  29999. sendSynchronousChangeMessage (message.pointerParameter);
  30000. }
  30001. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30002. {
  30003. const ScopedLock sl (lock);
  30004. messagePending = false;
  30005. for (int i = listeners.size(); --i >= 0;)
  30006. {
  30007. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30008. {
  30009. const ScopedUnlock tempUnlocker (lock);
  30010. l->changeListenerCallback (objectThatHasChanged);
  30011. }
  30012. i = jmin (i, listeners.size());
  30013. }
  30014. }
  30015. void ChangeListenerList::dispatchPendingMessages()
  30016. {
  30017. if (messagePending)
  30018. sendSynchronousChangeMessage (lastChangedObject);
  30019. }
  30020. END_JUCE_NAMESPACE
  30021. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30022. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30023. BEGIN_JUCE_NAMESPACE
  30024. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30025. const uint32 magicMessageHeaderNumber)
  30026. : Thread ("Juce IPC connection"),
  30027. callbackConnectionState (false),
  30028. useMessageThread (callbacksOnMessageThread),
  30029. magicMessageHeader (magicMessageHeaderNumber),
  30030. pipeReceiveMessageTimeout (-1)
  30031. {
  30032. }
  30033. InterprocessConnection::~InterprocessConnection()
  30034. {
  30035. callbackConnectionState = false;
  30036. disconnect();
  30037. }
  30038. bool InterprocessConnection::connectToSocket (const String& hostName,
  30039. const int portNumber,
  30040. const int timeOutMillisecs)
  30041. {
  30042. disconnect();
  30043. const ScopedLock sl (pipeAndSocketLock);
  30044. socket = new StreamingSocket();
  30045. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30046. {
  30047. connectionMadeInt();
  30048. startThread();
  30049. return true;
  30050. }
  30051. else
  30052. {
  30053. socket = 0;
  30054. return false;
  30055. }
  30056. }
  30057. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30058. const int pipeReceiveMessageTimeoutMs)
  30059. {
  30060. disconnect();
  30061. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30062. if (newPipe->openExisting (pipeName))
  30063. {
  30064. const ScopedLock sl (pipeAndSocketLock);
  30065. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30066. initialiseWithPipe (newPipe.release());
  30067. return true;
  30068. }
  30069. return false;
  30070. }
  30071. bool InterprocessConnection::createPipe (const String& pipeName,
  30072. const int pipeReceiveMessageTimeoutMs)
  30073. {
  30074. disconnect();
  30075. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30076. if (newPipe->createNewPipe (pipeName))
  30077. {
  30078. const ScopedLock sl (pipeAndSocketLock);
  30079. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30080. initialiseWithPipe (newPipe.release());
  30081. return true;
  30082. }
  30083. return false;
  30084. }
  30085. void InterprocessConnection::disconnect()
  30086. {
  30087. if (socket != 0)
  30088. socket->close();
  30089. if (pipe != 0)
  30090. {
  30091. pipe->cancelPendingReads();
  30092. pipe->close();
  30093. }
  30094. stopThread (4000);
  30095. {
  30096. const ScopedLock sl (pipeAndSocketLock);
  30097. socket = 0;
  30098. pipe = 0;
  30099. }
  30100. connectionLostInt();
  30101. }
  30102. bool InterprocessConnection::isConnected() const
  30103. {
  30104. const ScopedLock sl (pipeAndSocketLock);
  30105. return ((socket != 0 && socket->isConnected())
  30106. || (pipe != 0 && pipe->isOpen()))
  30107. && isThreadRunning();
  30108. }
  30109. const String InterprocessConnection::getConnectedHostName() const
  30110. {
  30111. if (pipe != 0)
  30112. {
  30113. return "localhost";
  30114. }
  30115. else if (socket != 0)
  30116. {
  30117. if (! socket->isLocal())
  30118. return socket->getHostName();
  30119. return "localhost";
  30120. }
  30121. return String::empty;
  30122. }
  30123. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30124. {
  30125. uint32 messageHeader[2];
  30126. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30127. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30128. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30129. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30130. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30131. size_t bytesWritten = 0;
  30132. const ScopedLock sl (pipeAndSocketLock);
  30133. if (socket != 0)
  30134. {
  30135. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30136. }
  30137. else if (pipe != 0)
  30138. {
  30139. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30140. }
  30141. if (bytesWritten < 0)
  30142. {
  30143. // error..
  30144. return false;
  30145. }
  30146. return (bytesWritten == messageData.getSize());
  30147. }
  30148. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30149. {
  30150. jassert (socket == 0);
  30151. socket = socket_;
  30152. connectionMadeInt();
  30153. startThread();
  30154. }
  30155. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30156. {
  30157. jassert (pipe == 0);
  30158. pipe = pipe_;
  30159. connectionMadeInt();
  30160. startThread();
  30161. }
  30162. const int messageMagicNumber = 0xb734128b;
  30163. void InterprocessConnection::handleMessage (const Message& message)
  30164. {
  30165. if (message.intParameter1 == messageMagicNumber)
  30166. {
  30167. switch (message.intParameter2)
  30168. {
  30169. case 0:
  30170. {
  30171. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30172. messageReceived (*data);
  30173. break;
  30174. }
  30175. case 1:
  30176. connectionMade();
  30177. break;
  30178. case 2:
  30179. connectionLost();
  30180. break;
  30181. }
  30182. }
  30183. }
  30184. void InterprocessConnection::connectionMadeInt()
  30185. {
  30186. if (! callbackConnectionState)
  30187. {
  30188. callbackConnectionState = true;
  30189. if (useMessageThread)
  30190. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30191. else
  30192. connectionMade();
  30193. }
  30194. }
  30195. void InterprocessConnection::connectionLostInt()
  30196. {
  30197. if (callbackConnectionState)
  30198. {
  30199. callbackConnectionState = false;
  30200. if (useMessageThread)
  30201. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30202. else
  30203. connectionLost();
  30204. }
  30205. }
  30206. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30207. {
  30208. jassert (callbackConnectionState);
  30209. if (useMessageThread)
  30210. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30211. else
  30212. messageReceived (data);
  30213. }
  30214. bool InterprocessConnection::readNextMessageInt()
  30215. {
  30216. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30217. uint32 messageHeader[2];
  30218. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30219. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30220. if (bytes == sizeof (messageHeader)
  30221. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30222. {
  30223. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30224. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30225. {
  30226. MemoryBlock messageData (bytesInMessage, true);
  30227. int bytesRead = 0;
  30228. while (bytesInMessage > 0)
  30229. {
  30230. if (threadShouldExit())
  30231. return false;
  30232. const int numThisTime = jmin (bytesInMessage, 65536);
  30233. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30234. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30235. if (bytesIn <= 0)
  30236. break;
  30237. bytesRead += bytesIn;
  30238. bytesInMessage -= bytesIn;
  30239. }
  30240. if (bytesRead >= 0)
  30241. deliverDataInt (messageData);
  30242. }
  30243. }
  30244. else if (bytes < 0)
  30245. {
  30246. {
  30247. const ScopedLock sl (pipeAndSocketLock);
  30248. socket = 0;
  30249. }
  30250. connectionLostInt();
  30251. return false;
  30252. }
  30253. return true;
  30254. }
  30255. void InterprocessConnection::run()
  30256. {
  30257. while (! threadShouldExit())
  30258. {
  30259. if (socket != 0)
  30260. {
  30261. const int ready = socket->waitUntilReady (true, 0);
  30262. if (ready < 0)
  30263. {
  30264. {
  30265. const ScopedLock sl (pipeAndSocketLock);
  30266. socket = 0;
  30267. }
  30268. connectionLostInt();
  30269. break;
  30270. }
  30271. else if (ready > 0)
  30272. {
  30273. if (! readNextMessageInt())
  30274. break;
  30275. }
  30276. else
  30277. {
  30278. Thread::sleep (2);
  30279. }
  30280. }
  30281. else if (pipe != 0)
  30282. {
  30283. if (! pipe->isOpen())
  30284. {
  30285. {
  30286. const ScopedLock sl (pipeAndSocketLock);
  30287. pipe = 0;
  30288. }
  30289. connectionLostInt();
  30290. break;
  30291. }
  30292. else
  30293. {
  30294. if (! readNextMessageInt())
  30295. break;
  30296. }
  30297. }
  30298. else
  30299. {
  30300. break;
  30301. }
  30302. }
  30303. }
  30304. END_JUCE_NAMESPACE
  30305. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30306. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30307. BEGIN_JUCE_NAMESPACE
  30308. InterprocessConnectionServer::InterprocessConnectionServer()
  30309. : Thread ("Juce IPC server")
  30310. {
  30311. }
  30312. InterprocessConnectionServer::~InterprocessConnectionServer()
  30313. {
  30314. stop();
  30315. }
  30316. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30317. {
  30318. stop();
  30319. socket = new StreamingSocket();
  30320. if (socket->createListener (portNumber))
  30321. {
  30322. startThread();
  30323. return true;
  30324. }
  30325. socket = 0;
  30326. return false;
  30327. }
  30328. void InterprocessConnectionServer::stop()
  30329. {
  30330. signalThreadShouldExit();
  30331. if (socket != 0)
  30332. socket->close();
  30333. stopThread (4000);
  30334. socket = 0;
  30335. }
  30336. void InterprocessConnectionServer::run()
  30337. {
  30338. while ((! threadShouldExit()) && socket != 0)
  30339. {
  30340. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30341. if (clientSocket != 0)
  30342. {
  30343. InterprocessConnection* newConnection = createConnectionObject();
  30344. if (newConnection != 0)
  30345. newConnection->initialiseWithSocket (clientSocket.release());
  30346. }
  30347. }
  30348. }
  30349. END_JUCE_NAMESPACE
  30350. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30351. /*** Start of inlined file: juce_Message.cpp ***/
  30352. BEGIN_JUCE_NAMESPACE
  30353. Message::Message() throw()
  30354. : intParameter1 (0),
  30355. intParameter2 (0),
  30356. intParameter3 (0),
  30357. pointerParameter (0)
  30358. {
  30359. }
  30360. Message::Message (const int intParameter1_,
  30361. const int intParameter2_,
  30362. const int intParameter3_,
  30363. void* const pointerParameter_) throw()
  30364. : intParameter1 (intParameter1_),
  30365. intParameter2 (intParameter2_),
  30366. intParameter3 (intParameter3_),
  30367. pointerParameter (pointerParameter_)
  30368. {
  30369. }
  30370. Message::~Message() throw()
  30371. {
  30372. }
  30373. END_JUCE_NAMESPACE
  30374. /*** End of inlined file: juce_Message.cpp ***/
  30375. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30376. BEGIN_JUCE_NAMESPACE
  30377. MessageListener::MessageListener() throw()
  30378. {
  30379. // are you trying to create a messagelistener before or after juce has been intialised??
  30380. jassert (MessageManager::instance != 0);
  30381. if (MessageManager::instance != 0)
  30382. MessageManager::instance->messageListeners.add (this);
  30383. }
  30384. MessageListener::~MessageListener()
  30385. {
  30386. if (MessageManager::instance != 0)
  30387. MessageManager::instance->messageListeners.removeValue (this);
  30388. }
  30389. void MessageListener::postMessage (Message* const message) const throw()
  30390. {
  30391. message->messageRecipient = const_cast <MessageListener*> (this);
  30392. if (MessageManager::instance == 0)
  30393. MessageManager::getInstance();
  30394. MessageManager::instance->postMessageToQueue (message);
  30395. }
  30396. bool MessageListener::isValidMessageListener() const throw()
  30397. {
  30398. return (MessageManager::instance != 0)
  30399. && MessageManager::instance->messageListeners.contains (this);
  30400. }
  30401. END_JUCE_NAMESPACE
  30402. /*** End of inlined file: juce_MessageListener.cpp ***/
  30403. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30404. BEGIN_JUCE_NAMESPACE
  30405. // platform-specific functions..
  30406. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30407. bool juce_postMessageToSystemQueue (void* message);
  30408. MessageManager* MessageManager::instance = 0;
  30409. static const int quitMessageId = 0xfffff321;
  30410. MessageManager::MessageManager() throw()
  30411. : quitMessagePosted (false),
  30412. quitMessageReceived (false),
  30413. threadWithLock (0)
  30414. {
  30415. messageThreadId = Thread::getCurrentThreadId();
  30416. }
  30417. MessageManager::~MessageManager() throw()
  30418. {
  30419. broadcastListeners = 0;
  30420. doPlatformSpecificShutdown();
  30421. jassert (instance == this);
  30422. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30423. }
  30424. MessageManager* MessageManager::getInstance() throw()
  30425. {
  30426. if (instance == 0)
  30427. {
  30428. instance = new MessageManager();
  30429. doPlatformSpecificInitialisation();
  30430. }
  30431. return instance;
  30432. }
  30433. void MessageManager::postMessageToQueue (Message* const message)
  30434. {
  30435. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30436. delete message;
  30437. }
  30438. CallbackMessage::CallbackMessage() throw() {}
  30439. CallbackMessage::~CallbackMessage() throw() {}
  30440. void CallbackMessage::post()
  30441. {
  30442. if (MessageManager::instance != 0)
  30443. MessageManager::instance->postCallbackMessage (this);
  30444. }
  30445. void MessageManager::postCallbackMessage (Message* const message)
  30446. {
  30447. message->messageRecipient = 0;
  30448. postMessageToQueue (message);
  30449. }
  30450. // not for public use..
  30451. void MessageManager::deliverMessage (void* const message)
  30452. {
  30453. const ScopedPointer <Message> m (static_cast <Message*> (message));
  30454. MessageListener* const recipient = m->messageRecipient;
  30455. JUCE_TRY
  30456. {
  30457. if (messageListeners.contains (recipient))
  30458. {
  30459. recipient->handleMessage (*m);
  30460. }
  30461. else if (recipient == 0)
  30462. {
  30463. if (m->intParameter1 == quitMessageId)
  30464. {
  30465. quitMessageReceived = true;
  30466. }
  30467. else
  30468. {
  30469. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (static_cast <Message*> (m));
  30470. if (cm != 0)
  30471. cm->messageCallback();
  30472. }
  30473. }
  30474. }
  30475. JUCE_CATCH_EXCEPTION
  30476. }
  30477. #if ! (JUCE_MAC || JUCE_IPHONE)
  30478. void MessageManager::runDispatchLoop()
  30479. {
  30480. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30481. runDispatchLoopUntil (-1);
  30482. }
  30483. void MessageManager::stopDispatchLoop()
  30484. {
  30485. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30486. m->messageRecipient = 0;
  30487. postMessageToQueue (m);
  30488. quitMessagePosted = true;
  30489. }
  30490. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30491. {
  30492. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30493. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30494. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30495. && ! quitMessageReceived)
  30496. {
  30497. JUCE_TRY
  30498. {
  30499. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30500. {
  30501. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30502. if (msToWait > 0)
  30503. Thread::sleep (jmin (5, msToWait));
  30504. }
  30505. }
  30506. JUCE_CATCH_EXCEPTION
  30507. }
  30508. return ! quitMessageReceived;
  30509. }
  30510. #endif
  30511. void MessageManager::deliverBroadcastMessage (const String& value)
  30512. {
  30513. if (broadcastListeners != 0)
  30514. broadcastListeners->sendActionMessage (value);
  30515. }
  30516. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30517. {
  30518. if (broadcastListeners == 0)
  30519. broadcastListeners = new ActionListenerList();
  30520. broadcastListeners->addActionListener (listener);
  30521. }
  30522. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30523. {
  30524. if (broadcastListeners != 0)
  30525. broadcastListeners->removeActionListener (listener);
  30526. }
  30527. bool MessageManager::isThisTheMessageThread() const throw()
  30528. {
  30529. return Thread::getCurrentThreadId() == messageThreadId;
  30530. }
  30531. void MessageManager::setCurrentThreadAsMessageThread()
  30532. {
  30533. if (messageThreadId != Thread::getCurrentThreadId())
  30534. {
  30535. messageThreadId = Thread::getCurrentThreadId();
  30536. // This is needed on windows to make sure the message window is created by this thread
  30537. doPlatformSpecificShutdown();
  30538. doPlatformSpecificInitialisation();
  30539. }
  30540. }
  30541. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30542. {
  30543. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30544. return thisThread == messageThreadId || thisThread == threadWithLock;
  30545. }
  30546. /* The only safe way to lock the message thread while another thread does
  30547. some work is by posting a special message, whose purpose is to tie up the event
  30548. loop until the other thread has finished its business.
  30549. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30550. get locked before making an event callback, because if the same OS lock gets indirectly
  30551. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30552. in Cocoa).
  30553. */
  30554. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30555. {
  30556. public:
  30557. SharedEvents() {}
  30558. ~SharedEvents() {}
  30559. /* This class just holds a couple of events to communicate between the BlockingMessage
  30560. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30561. this shared data must be kept in a separate, ref-counted container. */
  30562. WaitableEvent lockedEvent, releaseEvent;
  30563. private:
  30564. SharedEvents (const SharedEvents&);
  30565. SharedEvents& operator= (const SharedEvents&);
  30566. };
  30567. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30568. {
  30569. public:
  30570. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30571. ~BlockingMessage() throw() {}
  30572. void messageCallback()
  30573. {
  30574. events->lockedEvent.signal();
  30575. events->releaseEvent.wait();
  30576. }
  30577. juce_UseDebuggingNewOperator
  30578. private:
  30579. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30580. BlockingMessage (const BlockingMessage&);
  30581. BlockingMessage& operator= (const BlockingMessage&);
  30582. };
  30583. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30584. : sharedEvents (0),
  30585. locked (false)
  30586. {
  30587. init (threadToCheck, 0);
  30588. }
  30589. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30590. : sharedEvents (0),
  30591. locked (false)
  30592. {
  30593. init (0, jobToCheckForExitSignal);
  30594. }
  30595. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30596. {
  30597. if (MessageManager::instance != 0)
  30598. {
  30599. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30600. {
  30601. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30602. }
  30603. else
  30604. {
  30605. if (threadToCheck == 0 && job == 0)
  30606. {
  30607. MessageManager::instance->lockingLock.enter();
  30608. }
  30609. else
  30610. {
  30611. while (! MessageManager::instance->lockingLock.tryEnter())
  30612. {
  30613. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30614. || (job != 0 && job->shouldExit()))
  30615. return;
  30616. Thread::sleep (1);
  30617. }
  30618. }
  30619. sharedEvents = new SharedEvents();
  30620. sharedEvents->incReferenceCount();
  30621. (new BlockingMessage (sharedEvents))->post();
  30622. while (! sharedEvents->lockedEvent.wait (50))
  30623. {
  30624. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30625. || (job != 0 && job->shouldExit()))
  30626. {
  30627. sharedEvents->releaseEvent.signal();
  30628. sharedEvents->decReferenceCount();
  30629. sharedEvents = 0;
  30630. MessageManager::instance->lockingLock.exit();
  30631. return;
  30632. }
  30633. }
  30634. jassert (MessageManager::instance->threadWithLock == 0);
  30635. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30636. locked = true;
  30637. }
  30638. }
  30639. }
  30640. MessageManagerLock::~MessageManagerLock() throw()
  30641. {
  30642. if (sharedEvents != 0)
  30643. {
  30644. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30645. sharedEvents->releaseEvent.signal();
  30646. sharedEvents->decReferenceCount();
  30647. if (MessageManager::instance != 0)
  30648. {
  30649. MessageManager::instance->threadWithLock = 0;
  30650. MessageManager::instance->lockingLock.exit();
  30651. }
  30652. }
  30653. }
  30654. END_JUCE_NAMESPACE
  30655. /*** End of inlined file: juce_MessageManager.cpp ***/
  30656. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30657. BEGIN_JUCE_NAMESPACE
  30658. class MultiTimer::MultiTimerCallback : public Timer
  30659. {
  30660. public:
  30661. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30662. : timerId (timerId_),
  30663. owner (owner_)
  30664. {
  30665. }
  30666. ~MultiTimerCallback()
  30667. {
  30668. }
  30669. void timerCallback()
  30670. {
  30671. owner.timerCallback (timerId);
  30672. }
  30673. const int timerId;
  30674. private:
  30675. MultiTimer& owner;
  30676. };
  30677. MultiTimer::MultiTimer() throw()
  30678. {
  30679. }
  30680. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30681. {
  30682. }
  30683. MultiTimer::~MultiTimer()
  30684. {
  30685. const ScopedLock sl (timerListLock);
  30686. timers.clear();
  30687. }
  30688. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30689. {
  30690. const ScopedLock sl (timerListLock);
  30691. for (int i = timers.size(); --i >= 0;)
  30692. {
  30693. MultiTimerCallback* const t = timers.getUnchecked(i);
  30694. if (t->timerId == timerId)
  30695. {
  30696. t->startTimer (intervalInMilliseconds);
  30697. return;
  30698. }
  30699. }
  30700. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30701. timers.add (newTimer);
  30702. newTimer->startTimer (intervalInMilliseconds);
  30703. }
  30704. void MultiTimer::stopTimer (const int timerId) throw()
  30705. {
  30706. const ScopedLock sl (timerListLock);
  30707. for (int i = timers.size(); --i >= 0;)
  30708. {
  30709. MultiTimerCallback* const t = timers.getUnchecked(i);
  30710. if (t->timerId == timerId)
  30711. t->stopTimer();
  30712. }
  30713. }
  30714. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30715. {
  30716. const ScopedLock sl (timerListLock);
  30717. for (int i = timers.size(); --i >= 0;)
  30718. {
  30719. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30720. if (t->timerId == timerId)
  30721. return t->isTimerRunning();
  30722. }
  30723. return false;
  30724. }
  30725. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30726. {
  30727. const ScopedLock sl (timerListLock);
  30728. for (int i = timers.size(); --i >= 0;)
  30729. {
  30730. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30731. if (t->timerId == timerId)
  30732. return t->getTimerInterval();
  30733. }
  30734. return 0;
  30735. }
  30736. END_JUCE_NAMESPACE
  30737. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30738. /*** Start of inlined file: juce_Timer.cpp ***/
  30739. BEGIN_JUCE_NAMESPACE
  30740. class InternalTimerThread : private Thread,
  30741. private MessageListener,
  30742. private DeletedAtShutdown,
  30743. private AsyncUpdater
  30744. {
  30745. public:
  30746. InternalTimerThread()
  30747. : Thread ("Juce Timer"),
  30748. firstTimer (0),
  30749. callbackNeeded (0)
  30750. {
  30751. triggerAsyncUpdate();
  30752. }
  30753. ~InternalTimerThread() throw()
  30754. {
  30755. stopThread (4000);
  30756. jassert (instance == this || instance == 0);
  30757. if (instance == this)
  30758. instance = 0;
  30759. }
  30760. void run()
  30761. {
  30762. uint32 lastTime = Time::getMillisecondCounter();
  30763. while (! threadShouldExit())
  30764. {
  30765. const uint32 now = Time::getMillisecondCounter();
  30766. if (now <= lastTime)
  30767. {
  30768. wait (2);
  30769. continue;
  30770. }
  30771. const int elapsed = now - lastTime;
  30772. lastTime = now;
  30773. int timeUntilFirstTimer = 1000;
  30774. {
  30775. const ScopedLock sl (lock);
  30776. decrementAllCounters (elapsed);
  30777. if (firstTimer != 0)
  30778. timeUntilFirstTimer = firstTimer->countdownMs;
  30779. }
  30780. if (timeUntilFirstTimer <= 0)
  30781. {
  30782. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30783. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30784. but if it fails it means the message-thread changed the value from under us so at least
  30785. some processing is happenening and we can just loop around and try again
  30786. */
  30787. if (callbackNeeded.compareAndSetBool (1, 0))
  30788. {
  30789. postMessage (new Message());
  30790. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30791. when the app has a modal loop), so this is how long to wait before assuming the
  30792. message has been lost and trying again.
  30793. */
  30794. const uint32 messageDeliveryTimeout = now + 2000;
  30795. while (callbackNeeded.get() != 0)
  30796. {
  30797. wait (4);
  30798. if (threadShouldExit())
  30799. return;
  30800. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30801. break;
  30802. }
  30803. }
  30804. }
  30805. else
  30806. {
  30807. // don't wait for too long because running this loop also helps keep the
  30808. // Time::getApproximateMillisecondTimer value stay up-to-date
  30809. wait (jlimit (1, 50, timeUntilFirstTimer));
  30810. }
  30811. }
  30812. }
  30813. void callTimers()
  30814. {
  30815. const ScopedLock sl (lock);
  30816. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30817. {
  30818. Timer* const t = firstTimer;
  30819. t->countdownMs = t->periodMs;
  30820. removeTimer (t);
  30821. addTimer (t);
  30822. const ScopedUnlock ul (lock);
  30823. JUCE_TRY
  30824. {
  30825. t->timerCallback();
  30826. }
  30827. JUCE_CATCH_EXCEPTION
  30828. }
  30829. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30830. before the boolean is set. This set should never fail since if it was false in the first place,
  30831. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30832. get a message then the value is true and the other thread can only set it to true again and
  30833. we will get another callback to set it to false.
  30834. */
  30835. callbackNeeded.set (0);
  30836. }
  30837. void handleMessage (const Message&)
  30838. {
  30839. callTimers();
  30840. }
  30841. void callTimersSynchronously()
  30842. {
  30843. if (! isThreadRunning())
  30844. {
  30845. // (This is relied on by some plugins in cases where the MM has
  30846. // had to restart and the async callback never started)
  30847. cancelPendingUpdate();
  30848. triggerAsyncUpdate();
  30849. }
  30850. callTimers();
  30851. }
  30852. static void callAnyTimersSynchronously()
  30853. {
  30854. if (InternalTimerThread::instance != 0)
  30855. InternalTimerThread::instance->callTimersSynchronously();
  30856. }
  30857. static inline void add (Timer* const tim) throw()
  30858. {
  30859. if (instance == 0)
  30860. instance = new InternalTimerThread();
  30861. const ScopedLock sl (instance->lock);
  30862. instance->addTimer (tim);
  30863. }
  30864. static inline void remove (Timer* const tim) throw()
  30865. {
  30866. if (instance != 0)
  30867. {
  30868. const ScopedLock sl (instance->lock);
  30869. instance->removeTimer (tim);
  30870. }
  30871. }
  30872. static inline void resetCounter (Timer* const tim,
  30873. const int newCounter) throw()
  30874. {
  30875. if (instance != 0)
  30876. {
  30877. tim->countdownMs = newCounter;
  30878. tim->periodMs = newCounter;
  30879. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30880. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30881. {
  30882. const ScopedLock sl (instance->lock);
  30883. instance->removeTimer (tim);
  30884. instance->addTimer (tim);
  30885. }
  30886. }
  30887. }
  30888. private:
  30889. friend class Timer;
  30890. static InternalTimerThread* instance;
  30891. static CriticalSection lock;
  30892. Timer* volatile firstTimer;
  30893. Atomic <int> callbackNeeded;
  30894. void addTimer (Timer* const t) throw()
  30895. {
  30896. #if JUCE_DEBUG
  30897. Timer* tt = firstTimer;
  30898. while (tt != 0)
  30899. {
  30900. // trying to add a timer that's already here - shouldn't get to this point,
  30901. // so if you get this assertion, let me know!
  30902. jassert (tt != t);
  30903. tt = tt->next;
  30904. }
  30905. jassert (t->previous == 0 && t->next == 0);
  30906. #endif
  30907. Timer* i = firstTimer;
  30908. if (i == 0 || i->countdownMs > t->countdownMs)
  30909. {
  30910. t->next = firstTimer;
  30911. firstTimer = t;
  30912. }
  30913. else
  30914. {
  30915. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30916. i = i->next;
  30917. jassert (i != 0);
  30918. t->next = i->next;
  30919. t->previous = i;
  30920. i->next = t;
  30921. }
  30922. if (t->next != 0)
  30923. t->next->previous = t;
  30924. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30925. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30926. notify();
  30927. }
  30928. void removeTimer (Timer* const t) throw()
  30929. {
  30930. #if JUCE_DEBUG
  30931. Timer* tt = firstTimer;
  30932. bool found = false;
  30933. while (tt != 0)
  30934. {
  30935. if (tt == t)
  30936. {
  30937. found = true;
  30938. break;
  30939. }
  30940. tt = tt->next;
  30941. }
  30942. // trying to remove a timer that's not here - shouldn't get to this point,
  30943. // so if you get this assertion, let me know!
  30944. jassert (found);
  30945. #endif
  30946. if (t->previous != 0)
  30947. {
  30948. jassert (firstTimer != t);
  30949. t->previous->next = t->next;
  30950. }
  30951. else
  30952. {
  30953. jassert (firstTimer == t);
  30954. firstTimer = t->next;
  30955. }
  30956. if (t->next != 0)
  30957. t->next->previous = t->previous;
  30958. t->next = 0;
  30959. t->previous = 0;
  30960. }
  30961. void decrementAllCounters (const int numMillisecs) const
  30962. {
  30963. Timer* t = firstTimer;
  30964. while (t != 0)
  30965. {
  30966. t->countdownMs -= numMillisecs;
  30967. t = t->next;
  30968. }
  30969. }
  30970. void handleAsyncUpdate()
  30971. {
  30972. startThread (7);
  30973. }
  30974. InternalTimerThread (const InternalTimerThread&);
  30975. InternalTimerThread& operator= (const InternalTimerThread&);
  30976. };
  30977. InternalTimerThread* InternalTimerThread::instance = 0;
  30978. CriticalSection InternalTimerThread::lock;
  30979. void juce_callAnyTimersSynchronously()
  30980. {
  30981. InternalTimerThread::callAnyTimersSynchronously();
  30982. }
  30983. #if JUCE_DEBUG
  30984. static SortedSet <Timer*> activeTimers;
  30985. #endif
  30986. Timer::Timer() throw()
  30987. : countdownMs (0),
  30988. periodMs (0),
  30989. previous (0),
  30990. next (0)
  30991. {
  30992. #if JUCE_DEBUG
  30993. activeTimers.add (this);
  30994. #endif
  30995. }
  30996. Timer::Timer (const Timer&) throw()
  30997. : countdownMs (0),
  30998. periodMs (0),
  30999. previous (0),
  31000. next (0)
  31001. {
  31002. #if JUCE_DEBUG
  31003. activeTimers.add (this);
  31004. #endif
  31005. }
  31006. Timer::~Timer()
  31007. {
  31008. stopTimer();
  31009. #if JUCE_DEBUG
  31010. activeTimers.removeValue (this);
  31011. #endif
  31012. }
  31013. void Timer::startTimer (const int interval) throw()
  31014. {
  31015. const ScopedLock sl (InternalTimerThread::lock);
  31016. #if JUCE_DEBUG
  31017. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31018. jassert (activeTimers.contains (this));
  31019. #endif
  31020. if (periodMs == 0)
  31021. {
  31022. countdownMs = interval;
  31023. periodMs = jmax (1, interval);
  31024. InternalTimerThread::add (this);
  31025. }
  31026. else
  31027. {
  31028. InternalTimerThread::resetCounter (this, interval);
  31029. }
  31030. }
  31031. void Timer::stopTimer() throw()
  31032. {
  31033. const ScopedLock sl (InternalTimerThread::lock);
  31034. #if JUCE_DEBUG
  31035. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31036. jassert (activeTimers.contains (this));
  31037. #endif
  31038. if (periodMs > 0)
  31039. {
  31040. InternalTimerThread::remove (this);
  31041. periodMs = 0;
  31042. }
  31043. }
  31044. END_JUCE_NAMESPACE
  31045. /*** End of inlined file: juce_Timer.cpp ***/
  31046. #endif
  31047. #if JUCE_BUILD_GUI
  31048. /*** Start of inlined file: juce_Component.cpp ***/
  31049. BEGIN_JUCE_NAMESPACE
  31050. Component* Component::currentlyFocusedComponent = 0;
  31051. static Array <Component*> modalComponentStack, modalComponentReturnValueKeys;
  31052. static Array <int> modalReturnValues;
  31053. enum ComponentMessageNumbers
  31054. {
  31055. customCommandMessage = 0x7fff0001,
  31056. exitModalStateMessage = 0x7fff0002
  31057. };
  31058. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31059. static uint32 nextComponentUID = 0;
  31060. Component::Component()
  31061. : parentComponent_ (0),
  31062. componentUID (++nextComponentUID),
  31063. numDeepMouseListeners (0),
  31064. lookAndFeel_ (0),
  31065. effect_ (0),
  31066. bufferedImage_ (0),
  31067. mouseListeners_ (0),
  31068. keyListeners_ (0),
  31069. componentFlags_ (0)
  31070. {
  31071. }
  31072. Component::Component (const String& name)
  31073. : componentName_ (name),
  31074. parentComponent_ (0),
  31075. componentUID (++nextComponentUID),
  31076. numDeepMouseListeners (0),
  31077. lookAndFeel_ (0),
  31078. effect_ (0),
  31079. bufferedImage_ (0),
  31080. mouseListeners_ (0),
  31081. keyListeners_ (0),
  31082. componentFlags_ (0)
  31083. {
  31084. }
  31085. Component::~Component()
  31086. {
  31087. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31088. if (parentComponent_ != 0)
  31089. {
  31090. parentComponent_->removeChildComponent (this);
  31091. }
  31092. else if ((currentlyFocusedComponent == this)
  31093. || isParentOf (currentlyFocusedComponent))
  31094. {
  31095. giveAwayFocus();
  31096. }
  31097. if (flags.hasHeavyweightPeerFlag)
  31098. removeFromDesktop();
  31099. modalComponentStack.removeValue (this);
  31100. for (int i = childComponentList_.size(); --i >= 0;)
  31101. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31102. delete mouseListeners_;
  31103. delete keyListeners_;
  31104. }
  31105. void Component::setName (const String& name)
  31106. {
  31107. // if component methods are being called from threads other than the message
  31108. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31109. checkMessageManagerIsLocked
  31110. if (componentName_ != name)
  31111. {
  31112. componentName_ = name;
  31113. if (flags.hasHeavyweightPeerFlag)
  31114. {
  31115. ComponentPeer* const peer = getPeer();
  31116. jassert (peer != 0);
  31117. if (peer != 0)
  31118. peer->setTitle (name);
  31119. }
  31120. BailOutChecker checker (this);
  31121. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31122. }
  31123. }
  31124. void Component::setVisible (bool shouldBeVisible)
  31125. {
  31126. if (flags.visibleFlag != shouldBeVisible)
  31127. {
  31128. // if component methods are being called from threads other than the message
  31129. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31130. checkMessageManagerIsLocked
  31131. SafePointer<Component> safePointer (this);
  31132. flags.visibleFlag = shouldBeVisible;
  31133. internalRepaint (0, 0, getWidth(), getHeight());
  31134. sendFakeMouseMove();
  31135. if (! shouldBeVisible)
  31136. {
  31137. if (currentlyFocusedComponent == this
  31138. || isParentOf (currentlyFocusedComponent))
  31139. {
  31140. if (parentComponent_ != 0)
  31141. parentComponent_->grabKeyboardFocus();
  31142. else
  31143. giveAwayFocus();
  31144. }
  31145. }
  31146. if (safePointer != 0)
  31147. {
  31148. sendVisibilityChangeMessage();
  31149. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31150. {
  31151. ComponentPeer* const peer = getPeer();
  31152. jassert (peer != 0);
  31153. if (peer != 0)
  31154. {
  31155. peer->setVisible (shouldBeVisible);
  31156. internalHierarchyChanged();
  31157. }
  31158. }
  31159. }
  31160. }
  31161. }
  31162. void Component::visibilityChanged()
  31163. {
  31164. }
  31165. void Component::sendVisibilityChangeMessage()
  31166. {
  31167. BailOutChecker checker (this);
  31168. visibilityChanged();
  31169. if (! checker.shouldBailOut())
  31170. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31171. }
  31172. bool Component::isShowing() const
  31173. {
  31174. if (flags.visibleFlag)
  31175. {
  31176. if (parentComponent_ != 0)
  31177. {
  31178. return parentComponent_->isShowing();
  31179. }
  31180. else
  31181. {
  31182. const ComponentPeer* const peer = getPeer();
  31183. return peer != 0 && ! peer->isMinimised();
  31184. }
  31185. }
  31186. return false;
  31187. }
  31188. class FadeOutProxyComponent : public Component,
  31189. public Timer
  31190. {
  31191. public:
  31192. FadeOutProxyComponent (Component* comp,
  31193. const int fadeLengthMs,
  31194. const int deltaXToMove,
  31195. const int deltaYToMove,
  31196. const float scaleFactorAtEnd)
  31197. : lastTime (0),
  31198. alpha (1.0f),
  31199. scale (1.0f)
  31200. {
  31201. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31202. setBounds (comp->getBounds());
  31203. comp->getParentComponent()->addAndMakeVisible (this);
  31204. toBehind (comp);
  31205. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31206. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31207. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31208. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31209. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31210. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31211. setInterceptsMouseClicks (false, false);
  31212. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31213. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31214. }
  31215. ~FadeOutProxyComponent()
  31216. {
  31217. }
  31218. void paint (Graphics& g)
  31219. {
  31220. g.setOpacity (alpha);
  31221. g.drawImage (image,
  31222. 0, 0, getWidth(), getHeight(),
  31223. 0, 0, image.getWidth(), image.getHeight());
  31224. }
  31225. void timerCallback()
  31226. {
  31227. const uint32 now = Time::getMillisecondCounter();
  31228. if (lastTime == 0)
  31229. lastTime = now;
  31230. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31231. lastTime = now;
  31232. alpha += alphaChangePerMs * msPassed;
  31233. if (alpha > 0)
  31234. {
  31235. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31236. {
  31237. centreX += xChangePerMs * msPassed;
  31238. centreY += yChangePerMs * msPassed;
  31239. scale += scaleChangePerMs * msPassed;
  31240. const int w = roundToInt (image.getWidth() * scale);
  31241. const int h = roundToInt (image.getHeight() * scale);
  31242. setBounds (roundToInt (centreX) - w / 2,
  31243. roundToInt (centreY) - h / 2,
  31244. w, h);
  31245. }
  31246. repaint();
  31247. }
  31248. else
  31249. {
  31250. delete this;
  31251. }
  31252. }
  31253. juce_UseDebuggingNewOperator
  31254. private:
  31255. Image image;
  31256. uint32 lastTime;
  31257. float alpha, alphaChangePerMs;
  31258. float centreX, xChangePerMs;
  31259. float centreY, yChangePerMs;
  31260. float scale, scaleChangePerMs;
  31261. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31262. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31263. };
  31264. void Component::fadeOutComponent (const int millisecondsToFade,
  31265. const int deltaXToMove,
  31266. const int deltaYToMove,
  31267. const float scaleFactorAtEnd)
  31268. {
  31269. //xxx won't work for comps without parents
  31270. if (isShowing() && millisecondsToFade > 0)
  31271. new FadeOutProxyComponent (this, millisecondsToFade,
  31272. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31273. setVisible (false);
  31274. }
  31275. bool Component::isValidComponent() const
  31276. {
  31277. return (this != 0) && isValidMessageListener();
  31278. }
  31279. void* Component::getWindowHandle() const
  31280. {
  31281. const ComponentPeer* const peer = getPeer();
  31282. if (peer != 0)
  31283. return peer->getNativeHandle();
  31284. return 0;
  31285. }
  31286. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31287. {
  31288. // if component methods are being called from threads other than the message
  31289. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31290. checkMessageManagerIsLocked
  31291. if (isOpaque())
  31292. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31293. else
  31294. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31295. int currentStyleFlags = 0;
  31296. // don't use getPeer(), so that we only get the peer that's specifically
  31297. // for this comp, and not for one of its parents.
  31298. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31299. if (peer != 0)
  31300. currentStyleFlags = peer->getStyleFlags();
  31301. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31302. {
  31303. SafePointer<Component> safePointer (this);
  31304. #if JUCE_LINUX
  31305. // it's wise to give the component a non-zero size before
  31306. // putting it on the desktop, as X windows get confused by this, and
  31307. // a (1, 1) minimum size is enforced here.
  31308. setSize (jmax (1, getWidth()),
  31309. jmax (1, getHeight()));
  31310. #endif
  31311. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31312. bool wasFullscreen = false;
  31313. bool wasMinimised = false;
  31314. ComponentBoundsConstrainer* currentConstainer = 0;
  31315. Rectangle<int> oldNonFullScreenBounds;
  31316. if (peer != 0)
  31317. {
  31318. wasFullscreen = peer->isFullScreen();
  31319. wasMinimised = peer->isMinimised();
  31320. currentConstainer = peer->getConstrainer();
  31321. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31322. removeFromDesktop();
  31323. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31324. }
  31325. if (parentComponent_ != 0)
  31326. parentComponent_->removeChildComponent (this);
  31327. if (safePointer != 0)
  31328. {
  31329. flags.hasHeavyweightPeerFlag = true;
  31330. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31331. Desktop::getInstance().addDesktopComponent (this);
  31332. bounds_.setPosition (topLeft);
  31333. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31334. peer->setVisible (isVisible());
  31335. if (wasFullscreen)
  31336. {
  31337. peer->setFullScreen (true);
  31338. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31339. }
  31340. if (wasMinimised)
  31341. peer->setMinimised (true);
  31342. if (isAlwaysOnTop())
  31343. peer->setAlwaysOnTop (true);
  31344. peer->setConstrainer (currentConstainer);
  31345. repaint();
  31346. }
  31347. internalHierarchyChanged();
  31348. }
  31349. }
  31350. void Component::removeFromDesktop()
  31351. {
  31352. // if component methods are being called from threads other than the message
  31353. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31354. checkMessageManagerIsLocked
  31355. if (flags.hasHeavyweightPeerFlag)
  31356. {
  31357. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31358. flags.hasHeavyweightPeerFlag = false;
  31359. jassert (peer != 0);
  31360. delete peer;
  31361. Desktop::getInstance().removeDesktopComponent (this);
  31362. }
  31363. }
  31364. bool Component::isOnDesktop() const throw()
  31365. {
  31366. return flags.hasHeavyweightPeerFlag;
  31367. }
  31368. void Component::userTriedToCloseWindow()
  31369. {
  31370. /* This means that the user's trying to get rid of your window with the 'close window' system
  31371. menu option (on windows) or possibly the task manager - you should really handle this
  31372. and delete or hide your component in an appropriate way.
  31373. If you want to ignore the event and don't want to trigger this assertion, just override
  31374. this method and do nothing.
  31375. */
  31376. jassertfalse;
  31377. }
  31378. void Component::minimisationStateChanged (bool)
  31379. {
  31380. }
  31381. void Component::setOpaque (const bool shouldBeOpaque)
  31382. {
  31383. if (shouldBeOpaque != flags.opaqueFlag)
  31384. {
  31385. flags.opaqueFlag = shouldBeOpaque;
  31386. if (flags.hasHeavyweightPeerFlag)
  31387. {
  31388. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31389. if (peer != 0)
  31390. {
  31391. // to make it recreate the heavyweight window
  31392. addToDesktop (peer->getStyleFlags());
  31393. }
  31394. }
  31395. repaint();
  31396. }
  31397. }
  31398. bool Component::isOpaque() const throw()
  31399. {
  31400. return flags.opaqueFlag;
  31401. }
  31402. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31403. {
  31404. if (shouldBeBuffered != flags.bufferToImageFlag)
  31405. {
  31406. bufferedImage_ = Image();
  31407. flags.bufferToImageFlag = shouldBeBuffered;
  31408. }
  31409. }
  31410. void Component::toFront (const bool setAsForeground)
  31411. {
  31412. // if component methods are being called from threads other than the message
  31413. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31414. checkMessageManagerIsLocked
  31415. if (flags.hasHeavyweightPeerFlag)
  31416. {
  31417. ComponentPeer* const peer = getPeer();
  31418. if (peer != 0)
  31419. {
  31420. peer->toFront (setAsForeground);
  31421. if (setAsForeground && ! hasKeyboardFocus (true))
  31422. grabKeyboardFocus();
  31423. }
  31424. }
  31425. else if (parentComponent_ != 0)
  31426. {
  31427. Array<Component*>& childList = parentComponent_->childComponentList_;
  31428. if (childList.getLast() != this)
  31429. {
  31430. const int index = childList.indexOf (this);
  31431. if (index >= 0)
  31432. {
  31433. int insertIndex = -1;
  31434. if (! flags.alwaysOnTopFlag)
  31435. {
  31436. insertIndex = childList.size() - 1;
  31437. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31438. --insertIndex;
  31439. }
  31440. if (index != insertIndex)
  31441. {
  31442. childList.move (index, insertIndex);
  31443. sendFakeMouseMove();
  31444. repaintParent();
  31445. }
  31446. }
  31447. }
  31448. if (setAsForeground)
  31449. {
  31450. internalBroughtToFront();
  31451. grabKeyboardFocus();
  31452. }
  31453. }
  31454. }
  31455. void Component::toBehind (Component* const other)
  31456. {
  31457. if (other != 0 && other != this)
  31458. {
  31459. // the two components must belong to the same parent..
  31460. jassert (parentComponent_ == other->parentComponent_);
  31461. if (parentComponent_ != 0)
  31462. {
  31463. Array<Component*>& childList = parentComponent_->childComponentList_;
  31464. const int index = childList.indexOf (this);
  31465. if (index >= 0 && childList [index + 1] != other)
  31466. {
  31467. int otherIndex = childList.indexOf (other);
  31468. if (otherIndex >= 0)
  31469. {
  31470. if (index < otherIndex)
  31471. --otherIndex;
  31472. childList.move (index, otherIndex);
  31473. sendFakeMouseMove();
  31474. repaintParent();
  31475. }
  31476. }
  31477. }
  31478. else if (isOnDesktop())
  31479. {
  31480. jassert (other->isOnDesktop());
  31481. if (other->isOnDesktop())
  31482. {
  31483. ComponentPeer* const us = getPeer();
  31484. ComponentPeer* const them = other->getPeer();
  31485. jassert (us != 0 && them != 0);
  31486. if (us != 0 && them != 0)
  31487. us->toBehind (them);
  31488. }
  31489. }
  31490. }
  31491. }
  31492. void Component::toBack()
  31493. {
  31494. Array<Component*>& childList = parentComponent_->childComponentList_;
  31495. if (isOnDesktop())
  31496. {
  31497. jassertfalse; //xxx need to add this to native window
  31498. }
  31499. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31500. {
  31501. const int index = childList.indexOf (this);
  31502. if (index > 0)
  31503. {
  31504. int insertIndex = 0;
  31505. if (flags.alwaysOnTopFlag)
  31506. {
  31507. while (insertIndex < childList.size()
  31508. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31509. {
  31510. ++insertIndex;
  31511. }
  31512. }
  31513. if (index != insertIndex)
  31514. {
  31515. childList.move (index, insertIndex);
  31516. sendFakeMouseMove();
  31517. repaintParent();
  31518. }
  31519. }
  31520. }
  31521. }
  31522. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31523. {
  31524. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31525. {
  31526. flags.alwaysOnTopFlag = shouldStayOnTop;
  31527. if (isOnDesktop())
  31528. {
  31529. ComponentPeer* const peer = getPeer();
  31530. jassert (peer != 0);
  31531. if (peer != 0)
  31532. {
  31533. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31534. {
  31535. // some kinds of peer can't change their always-on-top status, so
  31536. // for these, we'll need to create a new window
  31537. const int oldFlags = peer->getStyleFlags();
  31538. removeFromDesktop();
  31539. addToDesktop (oldFlags);
  31540. }
  31541. }
  31542. }
  31543. if (shouldStayOnTop)
  31544. toFront (false);
  31545. internalHierarchyChanged();
  31546. }
  31547. }
  31548. bool Component::isAlwaysOnTop() const throw()
  31549. {
  31550. return flags.alwaysOnTopFlag;
  31551. }
  31552. int Component::proportionOfWidth (const float proportion) const throw()
  31553. {
  31554. return roundToInt (proportion * bounds_.getWidth());
  31555. }
  31556. int Component::proportionOfHeight (const float proportion) const throw()
  31557. {
  31558. return roundToInt (proportion * bounds_.getHeight());
  31559. }
  31560. int Component::getParentWidth() const throw()
  31561. {
  31562. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31563. : getParentMonitorArea().getWidth();
  31564. }
  31565. int Component::getParentHeight() const throw()
  31566. {
  31567. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31568. : getParentMonitorArea().getHeight();
  31569. }
  31570. int Component::getScreenX() const
  31571. {
  31572. return getScreenPosition().getX();
  31573. }
  31574. int Component::getScreenY() const
  31575. {
  31576. return getScreenPosition().getY();
  31577. }
  31578. const Point<int> Component::getScreenPosition() const
  31579. {
  31580. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31581. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31582. : getPosition());
  31583. }
  31584. const Rectangle<int> Component::getScreenBounds() const
  31585. {
  31586. return bounds_.withPosition (getScreenPosition());
  31587. }
  31588. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31589. {
  31590. const Component* c = this;
  31591. Point<int> p (relativePosition);
  31592. do
  31593. {
  31594. if (c->flags.hasHeavyweightPeerFlag)
  31595. return c->getPeer()->relativePositionToGlobal (p);
  31596. p += c->getPosition();
  31597. c = c->parentComponent_;
  31598. }
  31599. while (c != 0);
  31600. return p;
  31601. }
  31602. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31603. {
  31604. if (flags.hasHeavyweightPeerFlag)
  31605. {
  31606. return getPeer()->globalPositionToRelative (screenPosition);
  31607. }
  31608. else
  31609. {
  31610. if (parentComponent_ != 0)
  31611. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31612. return screenPosition - getPosition();
  31613. }
  31614. }
  31615. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31616. {
  31617. Point<int> p (positionRelativeToThis);
  31618. if (targetComponent != 0)
  31619. {
  31620. const Component* c = this;
  31621. do
  31622. {
  31623. if (c == targetComponent)
  31624. return p;
  31625. if (c->flags.hasHeavyweightPeerFlag)
  31626. {
  31627. p = c->getPeer()->relativePositionToGlobal (p);
  31628. break;
  31629. }
  31630. p += c->getPosition();
  31631. c = c->parentComponent_;
  31632. }
  31633. while (c != 0);
  31634. p = targetComponent->globalPositionToRelative (p);
  31635. }
  31636. return p;
  31637. }
  31638. void Component::setBounds (int x, int y, int w, int h)
  31639. {
  31640. // if component methods are being called from threads other than the message
  31641. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31642. checkMessageManagerIsLocked
  31643. if (w < 0) w = 0;
  31644. if (h < 0) h = 0;
  31645. const bool wasResized = (getWidth() != w || getHeight() != h);
  31646. const bool wasMoved = (getX() != x || getY() != y);
  31647. #if JUCE_DEBUG
  31648. // It's a very bad idea to try to resize a window during its paint() method!
  31649. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31650. #endif
  31651. if (wasMoved || wasResized)
  31652. {
  31653. if (flags.visibleFlag)
  31654. {
  31655. // send a fake mouse move to trigger enter/exit messages if needed..
  31656. sendFakeMouseMove();
  31657. if (! flags.hasHeavyweightPeerFlag)
  31658. repaintParent();
  31659. }
  31660. bounds_.setBounds (x, y, w, h);
  31661. if (wasResized)
  31662. repaint();
  31663. else if (! flags.hasHeavyweightPeerFlag)
  31664. repaintParent();
  31665. if (flags.hasHeavyweightPeerFlag)
  31666. {
  31667. ComponentPeer* const peer = getPeer();
  31668. if (peer != 0)
  31669. {
  31670. if (wasMoved && wasResized)
  31671. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31672. else if (wasMoved)
  31673. peer->setPosition (getX(), getY());
  31674. else if (wasResized)
  31675. peer->setSize (getWidth(), getHeight());
  31676. }
  31677. }
  31678. sendMovedResizedMessages (wasMoved, wasResized);
  31679. }
  31680. }
  31681. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31682. {
  31683. JUCE_TRY
  31684. {
  31685. if (wasMoved)
  31686. moved();
  31687. if (wasResized)
  31688. {
  31689. resized();
  31690. for (int i = childComponentList_.size(); --i >= 0;)
  31691. {
  31692. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31693. i = jmin (i, childComponentList_.size());
  31694. }
  31695. }
  31696. BailOutChecker checker (this);
  31697. if (parentComponent_ != 0)
  31698. parentComponent_->childBoundsChanged (this);
  31699. if (! checker.shouldBailOut())
  31700. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31701. *this, wasMoved, wasResized);
  31702. }
  31703. JUCE_CATCH_EXCEPTION
  31704. }
  31705. void Component::setSize (const int w, const int h)
  31706. {
  31707. setBounds (getX(), getY(), w, h);
  31708. }
  31709. void Component::setTopLeftPosition (const int x, const int y)
  31710. {
  31711. setBounds (x, y, getWidth(), getHeight());
  31712. }
  31713. void Component::setTopRightPosition (const int x, const int y)
  31714. {
  31715. setTopLeftPosition (x - getWidth(), y);
  31716. }
  31717. void Component::setBounds (const Rectangle<int>& r)
  31718. {
  31719. setBounds (r.getX(),
  31720. r.getY(),
  31721. r.getWidth(),
  31722. r.getHeight());
  31723. }
  31724. void Component::setBoundsRelative (const float x, const float y,
  31725. const float w, const float h)
  31726. {
  31727. const int pw = getParentWidth();
  31728. const int ph = getParentHeight();
  31729. setBounds (roundToInt (x * pw),
  31730. roundToInt (y * ph),
  31731. roundToInt (w * pw),
  31732. roundToInt (h * ph));
  31733. }
  31734. void Component::setCentrePosition (const int x, const int y)
  31735. {
  31736. setTopLeftPosition (x - getWidth() / 2,
  31737. y - getHeight() / 2);
  31738. }
  31739. void Component::setCentreRelative (const float x, const float y)
  31740. {
  31741. setCentrePosition (roundToInt (getParentWidth() * x),
  31742. roundToInt (getParentHeight() * y));
  31743. }
  31744. void Component::centreWithSize (const int width, const int height)
  31745. {
  31746. setBounds ((getParentWidth() - width) / 2,
  31747. (getParentHeight() - height) / 2,
  31748. width,
  31749. height);
  31750. }
  31751. void Component::setBoundsInset (const BorderSize& borders)
  31752. {
  31753. setBounds (borders.getLeft(),
  31754. borders.getTop(),
  31755. getParentWidth() - (borders.getLeftAndRight()),
  31756. getParentHeight() - (borders.getTopAndBottom()));
  31757. }
  31758. void Component::setBoundsToFit (int x, int y, int width, int height,
  31759. const Justification& justification,
  31760. const bool onlyReduceInSize)
  31761. {
  31762. // it's no good calling this method unless both the component and
  31763. // target rectangle have a finite size.
  31764. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31765. if (getWidth() > 0 && getHeight() > 0
  31766. && width > 0 && height > 0)
  31767. {
  31768. int newW, newH;
  31769. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31770. {
  31771. newW = getWidth();
  31772. newH = getHeight();
  31773. }
  31774. else
  31775. {
  31776. const double imageRatio = getHeight() / (double) getWidth();
  31777. const double targetRatio = height / (double) width;
  31778. if (imageRatio <= targetRatio)
  31779. {
  31780. newW = width;
  31781. newH = jmin (height, roundToInt (newW * imageRatio));
  31782. }
  31783. else
  31784. {
  31785. newH = height;
  31786. newW = jmin (width, roundToInt (newH / imageRatio));
  31787. }
  31788. }
  31789. if (newW > 0 && newH > 0)
  31790. {
  31791. int newX, newY;
  31792. justification.applyToRectangle (newX, newY, newW, newH,
  31793. x, y, width, height);
  31794. setBounds (newX, newY, newW, newH);
  31795. }
  31796. }
  31797. }
  31798. bool Component::hitTest (int x, int y)
  31799. {
  31800. if (! flags.ignoresMouseClicksFlag)
  31801. return true;
  31802. if (flags.allowChildMouseClicksFlag)
  31803. {
  31804. for (int i = getNumChildComponents(); --i >= 0;)
  31805. {
  31806. Component* const c = getChildComponent (i);
  31807. if (c->isVisible()
  31808. && c->bounds_.contains (x, y)
  31809. && c->hitTest (x - c->getX(),
  31810. y - c->getY()))
  31811. {
  31812. return true;
  31813. }
  31814. }
  31815. }
  31816. return false;
  31817. }
  31818. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31819. const bool allowClicksOnChildComponents) throw()
  31820. {
  31821. flags.ignoresMouseClicksFlag = ! allowClicks;
  31822. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31823. }
  31824. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31825. bool& allowsClicksOnChildComponents) const throw()
  31826. {
  31827. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31828. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31829. }
  31830. bool Component::contains (const int x, const int y)
  31831. {
  31832. if (((unsigned int) x) < (unsigned int) getWidth()
  31833. && ((unsigned int) y) < (unsigned int) getHeight()
  31834. && hitTest (x, y))
  31835. {
  31836. if (parentComponent_ != 0)
  31837. {
  31838. return parentComponent_->contains (x + getX(),
  31839. y + getY());
  31840. }
  31841. else if (flags.hasHeavyweightPeerFlag)
  31842. {
  31843. const ComponentPeer* const peer = getPeer();
  31844. if (peer != 0)
  31845. return peer->contains (Point<int> (x, y), true);
  31846. }
  31847. }
  31848. return false;
  31849. }
  31850. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31851. {
  31852. if (! contains (x, y))
  31853. return false;
  31854. Component* p = this;
  31855. while (p->parentComponent_ != 0)
  31856. {
  31857. x += p->getX();
  31858. y += p->getY();
  31859. p = p->parentComponent_;
  31860. }
  31861. const Component* const c = p->getComponentAt (x, y);
  31862. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31863. }
  31864. Component* Component::getComponentAt (const Point<int>& position)
  31865. {
  31866. return getComponentAt (position.getX(), position.getY());
  31867. }
  31868. Component* Component::getComponentAt (const int x, const int y)
  31869. {
  31870. if (flags.visibleFlag
  31871. && ((unsigned int) x) < (unsigned int) getWidth()
  31872. && ((unsigned int) y) < (unsigned int) getHeight()
  31873. && hitTest (x, y))
  31874. {
  31875. for (int i = childComponentList_.size(); --i >= 0;)
  31876. {
  31877. Component* const child = childComponentList_.getUnchecked(i);
  31878. Component* const c = child->getComponentAt (x - child->getX(),
  31879. y - child->getY());
  31880. if (c != 0)
  31881. return c;
  31882. }
  31883. return this;
  31884. }
  31885. return 0;
  31886. }
  31887. void Component::addChildComponent (Component* const child, int zOrder)
  31888. {
  31889. // if component methods are being called from threads other than the message
  31890. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31891. checkMessageManagerIsLocked
  31892. if (child != 0 && child->parentComponent_ != this)
  31893. {
  31894. if (child->parentComponent_ != 0)
  31895. child->parentComponent_->removeChildComponent (child);
  31896. else
  31897. child->removeFromDesktop();
  31898. child->parentComponent_ = this;
  31899. if (child->isVisible())
  31900. child->repaintParent();
  31901. if (! child->isAlwaysOnTop())
  31902. {
  31903. if (zOrder < 0 || zOrder > childComponentList_.size())
  31904. zOrder = childComponentList_.size();
  31905. while (zOrder > 0)
  31906. {
  31907. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31908. break;
  31909. --zOrder;
  31910. }
  31911. }
  31912. childComponentList_.insert (zOrder, child);
  31913. child->internalHierarchyChanged();
  31914. internalChildrenChanged();
  31915. }
  31916. }
  31917. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31918. {
  31919. if (child != 0)
  31920. {
  31921. child->setVisible (true);
  31922. addChildComponent (child, zOrder);
  31923. }
  31924. }
  31925. void Component::removeChildComponent (Component* const child)
  31926. {
  31927. removeChildComponent (childComponentList_.indexOf (child));
  31928. }
  31929. Component* Component::removeChildComponent (const int index)
  31930. {
  31931. // if component methods are being called from threads other than the message
  31932. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31933. checkMessageManagerIsLocked
  31934. Component* const child = childComponentList_ [index];
  31935. if (child != 0)
  31936. {
  31937. sendFakeMouseMove();
  31938. child->repaintParent();
  31939. childComponentList_.remove (index);
  31940. child->parentComponent_ = 0;
  31941. JUCE_TRY
  31942. {
  31943. if ((currentlyFocusedComponent == child)
  31944. || child->isParentOf (currentlyFocusedComponent))
  31945. {
  31946. // get rid first to force the grabKeyboardFocus to change to us.
  31947. giveAwayFocus();
  31948. grabKeyboardFocus();
  31949. }
  31950. }
  31951. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31952. catch (const std::exception& e)
  31953. {
  31954. currentlyFocusedComponent = 0;
  31955. Desktop::getInstance().triggerFocusCallback();
  31956. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31957. }
  31958. catch (...)
  31959. {
  31960. currentlyFocusedComponent = 0;
  31961. Desktop::getInstance().triggerFocusCallback();
  31962. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31963. }
  31964. #endif
  31965. child->internalHierarchyChanged();
  31966. internalChildrenChanged();
  31967. }
  31968. return child;
  31969. }
  31970. void Component::removeAllChildren()
  31971. {
  31972. while (childComponentList_.size() > 0)
  31973. removeChildComponent (childComponentList_.size() - 1);
  31974. }
  31975. void Component::deleteAllChildren()
  31976. {
  31977. while (childComponentList_.size() > 0)
  31978. delete (removeChildComponent (childComponentList_.size() - 1));
  31979. }
  31980. int Component::getNumChildComponents() const throw()
  31981. {
  31982. return childComponentList_.size();
  31983. }
  31984. Component* Component::getChildComponent (const int index) const throw()
  31985. {
  31986. return childComponentList_ [index];
  31987. }
  31988. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31989. {
  31990. return childComponentList_.indexOf (const_cast <Component*> (child));
  31991. }
  31992. Component* Component::getTopLevelComponent() const throw()
  31993. {
  31994. const Component* comp = this;
  31995. while (comp->parentComponent_ != 0)
  31996. comp = comp->parentComponent_;
  31997. return const_cast <Component*> (comp);
  31998. }
  31999. bool Component::isParentOf (const Component* possibleChild) const throw()
  32000. {
  32001. if (! possibleChild->isValidComponent())
  32002. {
  32003. jassert (possibleChild == 0);
  32004. return false;
  32005. }
  32006. while (possibleChild != 0)
  32007. {
  32008. possibleChild = possibleChild->parentComponent_;
  32009. if (possibleChild == this)
  32010. return true;
  32011. }
  32012. return false;
  32013. }
  32014. void Component::parentHierarchyChanged()
  32015. {
  32016. }
  32017. void Component::childrenChanged()
  32018. {
  32019. }
  32020. void Component::internalChildrenChanged()
  32021. {
  32022. if (componentListeners.isEmpty())
  32023. {
  32024. childrenChanged();
  32025. }
  32026. else
  32027. {
  32028. BailOutChecker checker (this);
  32029. childrenChanged();
  32030. if (! checker.shouldBailOut())
  32031. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32032. }
  32033. }
  32034. void Component::internalHierarchyChanged()
  32035. {
  32036. BailOutChecker checker (this);
  32037. parentHierarchyChanged();
  32038. if (checker.shouldBailOut())
  32039. return;
  32040. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32041. if (checker.shouldBailOut())
  32042. return;
  32043. for (int i = childComponentList_.size(); --i >= 0;)
  32044. {
  32045. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32046. if (checker.shouldBailOut())
  32047. {
  32048. // you really shouldn't delete the parent component during a callback telling you
  32049. // that it's changed..
  32050. jassertfalse;
  32051. return;
  32052. }
  32053. i = jmin (i, childComponentList_.size());
  32054. }
  32055. }
  32056. void* Component::runModalLoopCallback (void* userData)
  32057. {
  32058. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32059. }
  32060. int Component::runModalLoop()
  32061. {
  32062. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32063. {
  32064. // use a callback so this can be called from non-gui threads
  32065. return (int) (pointer_sized_int)
  32066. MessageManager::getInstance()
  32067. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32068. }
  32069. SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  32070. if (! isCurrentlyModal())
  32071. enterModalState();
  32072. JUCE_TRY
  32073. {
  32074. while (flags.currentlyModalFlag && flags.visibleFlag)
  32075. {
  32076. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  32077. break;
  32078. // check whether this component was deleted during the last message
  32079. if (! isValidMessageListener())
  32080. break;
  32081. }
  32082. }
  32083. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32084. catch (const std::exception& e)
  32085. {
  32086. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32087. return 0;
  32088. }
  32089. catch (...)
  32090. {
  32091. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32092. return 0;
  32093. }
  32094. #endif
  32095. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32096. int returnValue = 0;
  32097. if (modalIndex >= 0)
  32098. {
  32099. modalComponentReturnValueKeys.remove (modalIndex);
  32100. returnValue = modalReturnValues.remove (modalIndex);
  32101. }
  32102. modalComponentStack.removeValue (this);
  32103. if (prevFocused != 0)
  32104. prevFocused->grabKeyboardFocus();
  32105. return returnValue;
  32106. }
  32107. void Component::enterModalState (const bool takeKeyboardFocus_)
  32108. {
  32109. // if component methods are being called from threads other than the message
  32110. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32111. checkMessageManagerIsLocked
  32112. // Check for an attempt to make a component modal when it already is!
  32113. // This can cause nasty problems..
  32114. jassert (! flags.currentlyModalFlag);
  32115. if (! isCurrentlyModal())
  32116. {
  32117. modalComponentStack.add (this);
  32118. modalComponentReturnValueKeys.add (this);
  32119. modalReturnValues.add (0);
  32120. flags.currentlyModalFlag = true;
  32121. setVisible (true);
  32122. if (takeKeyboardFocus_)
  32123. grabKeyboardFocus();
  32124. }
  32125. }
  32126. void Component::exitModalState (const int returnValue)
  32127. {
  32128. if (isCurrentlyModal())
  32129. {
  32130. if (MessageManager::getInstance()->isThisTheMessageThread())
  32131. {
  32132. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32133. if (modalIndex >= 0)
  32134. {
  32135. modalReturnValues.set (modalIndex, returnValue);
  32136. }
  32137. else
  32138. {
  32139. modalComponentReturnValueKeys.add (this);
  32140. modalReturnValues.add (returnValue);
  32141. }
  32142. modalComponentStack.removeValue (this);
  32143. flags.currentlyModalFlag = false;
  32144. bringModalComponentToFront();
  32145. }
  32146. else
  32147. {
  32148. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32149. }
  32150. }
  32151. }
  32152. bool Component::isCurrentlyModal() const throw()
  32153. {
  32154. return flags.currentlyModalFlag
  32155. && getCurrentlyModalComponent() == this;
  32156. }
  32157. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32158. {
  32159. Component* const mc = getCurrentlyModalComponent();
  32160. return mc != 0
  32161. && mc != this
  32162. && (! mc->isParentOf (this))
  32163. && ! mc->canModalEventBeSentToComponent (this);
  32164. }
  32165. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32166. {
  32167. return modalComponentStack.size();
  32168. }
  32169. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32170. {
  32171. Component* const c = static_cast <Component*> (modalComponentStack [modalComponentStack.size() - index - 1]);
  32172. return c->isValidComponent() ? c : 0;
  32173. }
  32174. void Component::bringModalComponentToFront()
  32175. {
  32176. ComponentPeer* lastOne = 0;
  32177. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32178. {
  32179. Component* const c = getCurrentlyModalComponent (i);
  32180. if (c == 0)
  32181. break;
  32182. ComponentPeer* peer = c->getPeer();
  32183. if (peer != 0 && peer != lastOne)
  32184. {
  32185. if (lastOne == 0)
  32186. {
  32187. peer->toFront (true);
  32188. peer->grabFocus();
  32189. }
  32190. else
  32191. peer->toBehind (lastOne);
  32192. lastOne = peer;
  32193. }
  32194. }
  32195. }
  32196. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32197. {
  32198. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32199. }
  32200. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32201. {
  32202. return flags.bringToFrontOnClickFlag;
  32203. }
  32204. void Component::setMouseCursor (const MouseCursor& cursor)
  32205. {
  32206. if (cursor_ != cursor)
  32207. {
  32208. cursor_ = cursor;
  32209. if (flags.visibleFlag)
  32210. updateMouseCursor();
  32211. }
  32212. }
  32213. const MouseCursor Component::getMouseCursor()
  32214. {
  32215. return cursor_;
  32216. }
  32217. void Component::updateMouseCursor() const
  32218. {
  32219. sendFakeMouseMove();
  32220. }
  32221. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32222. {
  32223. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32224. }
  32225. void Component::repaintParent()
  32226. {
  32227. if (flags.visibleFlag)
  32228. internalRepaint (0, 0, getWidth(), getHeight());
  32229. }
  32230. void Component::repaint()
  32231. {
  32232. repaint (0, 0, getWidth(), getHeight());
  32233. }
  32234. void Component::repaint (const int x, const int y,
  32235. const int w, const int h)
  32236. {
  32237. bufferedImage_ = Image();
  32238. if (flags.visibleFlag)
  32239. internalRepaint (x, y, w, h);
  32240. }
  32241. void Component::repaint (const Rectangle<int>& area)
  32242. {
  32243. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32244. }
  32245. void Component::internalRepaint (int x, int y, int w, int h)
  32246. {
  32247. // if component methods are being called from threads other than the message
  32248. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32249. checkMessageManagerIsLocked
  32250. if (x < 0)
  32251. {
  32252. w += x;
  32253. x = 0;
  32254. }
  32255. if (x + w > getWidth())
  32256. w = getWidth() - x;
  32257. if (w > 0)
  32258. {
  32259. if (y < 0)
  32260. {
  32261. h += y;
  32262. y = 0;
  32263. }
  32264. if (y + h > getHeight())
  32265. h = getHeight() - y;
  32266. if (h > 0)
  32267. {
  32268. if (parentComponent_ != 0)
  32269. {
  32270. x += getX();
  32271. y += getY();
  32272. if (parentComponent_->flags.visibleFlag)
  32273. parentComponent_->internalRepaint (x, y, w, h);
  32274. }
  32275. else if (flags.hasHeavyweightPeerFlag)
  32276. {
  32277. ComponentPeer* const peer = getPeer();
  32278. if (peer != 0)
  32279. peer->repaint (Rectangle<int> (x, y, w, h));
  32280. }
  32281. }
  32282. }
  32283. }
  32284. void Component::renderComponent (Graphics& g)
  32285. {
  32286. const Rectangle<int> clipBounds (g.getClipBounds());
  32287. g.saveState();
  32288. clipObscuredRegions (g, clipBounds, 0, 0);
  32289. if (! g.isClipEmpty())
  32290. {
  32291. if (flags.bufferToImageFlag)
  32292. {
  32293. if (bufferedImage_.isNull())
  32294. {
  32295. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32296. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  32297. Graphics imG (bufferedImage_);
  32298. paint (imG);
  32299. }
  32300. g.setColour (Colours::black);
  32301. g.drawImageAt (bufferedImage_, 0, 0);
  32302. }
  32303. else
  32304. {
  32305. paint (g);
  32306. }
  32307. }
  32308. g.restoreState();
  32309. for (int i = 0; i < childComponentList_.size(); ++i)
  32310. {
  32311. Component* const child = childComponentList_.getUnchecked (i);
  32312. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32313. {
  32314. g.saveState();
  32315. if (g.reduceClipRegion (child->getX(), child->getY(),
  32316. child->getWidth(), child->getHeight()))
  32317. {
  32318. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32319. {
  32320. const Component* const sibling = childComponentList_.getUnchecked (j);
  32321. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32322. g.excludeClipRegion (sibling->getBounds());
  32323. }
  32324. if (! g.isClipEmpty())
  32325. {
  32326. g.setOrigin (child->getX(), child->getY());
  32327. child->paintEntireComponent (g);
  32328. }
  32329. }
  32330. g.restoreState();
  32331. }
  32332. }
  32333. g.saveState();
  32334. paintOverChildren (g);
  32335. g.restoreState();
  32336. }
  32337. void Component::paintEntireComponent (Graphics& g)
  32338. {
  32339. jassert (! g.isClipEmpty());
  32340. #if JUCE_DEBUG
  32341. flags.isInsidePaintCall = true;
  32342. #endif
  32343. if (effect_ != 0)
  32344. {
  32345. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32346. getWidth(), getHeight(),
  32347. ! flags.opaqueFlag, Image::NativeImage);
  32348. {
  32349. Graphics g2 (effectImage);
  32350. renderComponent (g2);
  32351. }
  32352. effect_->applyEffect (effectImage, g);
  32353. }
  32354. else
  32355. {
  32356. renderComponent (g);
  32357. }
  32358. #if JUCE_DEBUG
  32359. flags.isInsidePaintCall = false;
  32360. #endif
  32361. }
  32362. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32363. const bool clipImageToComponentBounds)
  32364. {
  32365. Rectangle<int> r (areaToGrab);
  32366. if (clipImageToComponentBounds)
  32367. r = r.getIntersection (getLocalBounds());
  32368. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32369. jmax (1, r.getWidth()),
  32370. jmax (1, r.getHeight()),
  32371. true);
  32372. Graphics imageContext (componentImage);
  32373. imageContext.setOrigin (-r.getX(), -r.getY());
  32374. paintEntireComponent (imageContext);
  32375. return componentImage;
  32376. }
  32377. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32378. {
  32379. if (effect_ != effect)
  32380. {
  32381. effect_ = effect;
  32382. repaint();
  32383. }
  32384. }
  32385. LookAndFeel& Component::getLookAndFeel() const throw()
  32386. {
  32387. const Component* c = this;
  32388. do
  32389. {
  32390. if (c->lookAndFeel_ != 0)
  32391. return *(c->lookAndFeel_);
  32392. c = c->parentComponent_;
  32393. }
  32394. while (c != 0);
  32395. return LookAndFeel::getDefaultLookAndFeel();
  32396. }
  32397. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32398. {
  32399. if (lookAndFeel_ != newLookAndFeel)
  32400. {
  32401. lookAndFeel_ = newLookAndFeel;
  32402. sendLookAndFeelChange();
  32403. }
  32404. }
  32405. void Component::lookAndFeelChanged()
  32406. {
  32407. }
  32408. void Component::sendLookAndFeelChange()
  32409. {
  32410. repaint();
  32411. lookAndFeelChanged();
  32412. // (it's not a great idea to do anything that would delete this component
  32413. // during the lookAndFeelChanged() callback)
  32414. jassert (isValidComponent());
  32415. SafePointer<Component> safePointer (this);
  32416. for (int i = childComponentList_.size(); --i >= 0;)
  32417. {
  32418. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32419. if (safePointer == 0)
  32420. return;
  32421. i = jmin (i, childComponentList_.size());
  32422. }
  32423. }
  32424. static const Identifier getColourPropertyId (const int colourId)
  32425. {
  32426. String s;
  32427. s.preallocateStorage (18);
  32428. s << "jcclr_" << String::toHexString (colourId);
  32429. return s;
  32430. }
  32431. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32432. {
  32433. var* v = properties.getItem (getColourPropertyId (colourId));
  32434. if (v != 0)
  32435. return Colour ((int) *v);
  32436. if (inheritFromParent && parentComponent_ != 0)
  32437. return parentComponent_->findColour (colourId, true);
  32438. return getLookAndFeel().findColour (colourId);
  32439. }
  32440. bool Component::isColourSpecified (const int colourId) const
  32441. {
  32442. return properties.contains (getColourPropertyId (colourId));
  32443. }
  32444. void Component::removeColour (const int colourId)
  32445. {
  32446. if (properties.remove (getColourPropertyId (colourId)))
  32447. colourChanged();
  32448. }
  32449. void Component::setColour (const int colourId, const Colour& colour)
  32450. {
  32451. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32452. colourChanged();
  32453. }
  32454. void Component::copyAllExplicitColoursTo (Component& target) const
  32455. {
  32456. bool changed = false;
  32457. for (int i = properties.size(); --i >= 0;)
  32458. {
  32459. const Identifier name (properties.getName(i));
  32460. if (name.toString().startsWith ("jcclr_"))
  32461. if (target.properties.set (name, properties [name]))
  32462. changed = true;
  32463. }
  32464. if (changed)
  32465. target.colourChanged();
  32466. }
  32467. void Component::colourChanged()
  32468. {
  32469. }
  32470. const Rectangle<int> Component::getLocalBounds() const throw()
  32471. {
  32472. return Rectangle<int> (0, 0, getWidth(), getHeight());
  32473. }
  32474. const Rectangle<int> Component::getUnclippedArea() const
  32475. {
  32476. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32477. Component* p = parentComponent_;
  32478. int px = getX();
  32479. int py = getY();
  32480. while (p != 0)
  32481. {
  32482. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32483. return Rectangle<int>();
  32484. px += p->getX();
  32485. py += p->getY();
  32486. p = p->parentComponent_;
  32487. }
  32488. return Rectangle<int> (x, y, w, h);
  32489. }
  32490. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32491. const int deltaX, const int deltaY) const
  32492. {
  32493. for (int i = childComponentList_.size(); --i >= 0;)
  32494. {
  32495. const Component* const c = childComponentList_.getUnchecked(i);
  32496. if (c->isVisible())
  32497. {
  32498. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32499. if (! newClip.isEmpty())
  32500. {
  32501. if (c->isOpaque())
  32502. {
  32503. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32504. }
  32505. else
  32506. {
  32507. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32508. c->getX() + deltaX,
  32509. c->getY() + deltaY);
  32510. }
  32511. }
  32512. }
  32513. }
  32514. }
  32515. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32516. {
  32517. result.clear();
  32518. const Rectangle<int> unclipped (getUnclippedArea());
  32519. if (! unclipped.isEmpty())
  32520. {
  32521. result.add (unclipped);
  32522. if (includeSiblings)
  32523. {
  32524. const Component* const c = getTopLevelComponent();
  32525. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32526. c->getLocalBounds(), this);
  32527. }
  32528. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32529. result.consolidate();
  32530. }
  32531. }
  32532. void Component::subtractObscuredRegions (RectangleList& result,
  32533. const Point<int>& delta,
  32534. const Rectangle<int>& clipRect,
  32535. const Component* const compToAvoid) const
  32536. {
  32537. for (int i = childComponentList_.size(); --i >= 0;)
  32538. {
  32539. const Component* const c = childComponentList_.getUnchecked(i);
  32540. if (c != compToAvoid && c->isVisible())
  32541. {
  32542. if (c->isOpaque())
  32543. {
  32544. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32545. childBounds.translate (delta.getX(), delta.getY());
  32546. result.subtract (childBounds);
  32547. }
  32548. else
  32549. {
  32550. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32551. newClip.translate (-c->getX(), -c->getY());
  32552. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32553. newClip, compToAvoid);
  32554. }
  32555. }
  32556. }
  32557. }
  32558. void Component::mouseEnter (const MouseEvent&)
  32559. {
  32560. // base class does nothing
  32561. }
  32562. void Component::mouseExit (const MouseEvent&)
  32563. {
  32564. // base class does nothing
  32565. }
  32566. void Component::mouseDown (const MouseEvent&)
  32567. {
  32568. // base class does nothing
  32569. }
  32570. void Component::mouseUp (const MouseEvent&)
  32571. {
  32572. // base class does nothing
  32573. }
  32574. void Component::mouseDrag (const MouseEvent&)
  32575. {
  32576. // base class does nothing
  32577. }
  32578. void Component::mouseMove (const MouseEvent&)
  32579. {
  32580. // base class does nothing
  32581. }
  32582. void Component::mouseDoubleClick (const MouseEvent&)
  32583. {
  32584. // base class does nothing
  32585. }
  32586. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32587. {
  32588. // the base class just passes this event up to its parent..
  32589. if (parentComponent_ != 0)
  32590. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32591. wheelIncrementX, wheelIncrementY);
  32592. }
  32593. void Component::resized()
  32594. {
  32595. // base class does nothing
  32596. }
  32597. void Component::moved()
  32598. {
  32599. // base class does nothing
  32600. }
  32601. void Component::childBoundsChanged (Component*)
  32602. {
  32603. // base class does nothing
  32604. }
  32605. void Component::parentSizeChanged()
  32606. {
  32607. // base class does nothing
  32608. }
  32609. void Component::addComponentListener (ComponentListener* const newListener)
  32610. {
  32611. jassert (isValidComponent());
  32612. componentListeners.add (newListener);
  32613. }
  32614. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32615. {
  32616. jassert (isValidComponent());
  32617. componentListeners.remove (listenerToRemove);
  32618. }
  32619. void Component::inputAttemptWhenModal()
  32620. {
  32621. bringModalComponentToFront();
  32622. getLookAndFeel().playAlertSound();
  32623. }
  32624. bool Component::canModalEventBeSentToComponent (const Component*)
  32625. {
  32626. return false;
  32627. }
  32628. void Component::internalModalInputAttempt()
  32629. {
  32630. Component* const current = getCurrentlyModalComponent();
  32631. if (current != 0)
  32632. current->inputAttemptWhenModal();
  32633. }
  32634. void Component::paint (Graphics&)
  32635. {
  32636. // all painting is done in the subclasses
  32637. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32638. }
  32639. void Component::paintOverChildren (Graphics&)
  32640. {
  32641. // all painting is done in the subclasses
  32642. }
  32643. void Component::handleMessage (const Message& message)
  32644. {
  32645. if (message.intParameter1 == exitModalStateMessage)
  32646. {
  32647. exitModalState (message.intParameter2);
  32648. }
  32649. else if (message.intParameter1 == customCommandMessage)
  32650. {
  32651. handleCommandMessage (message.intParameter2);
  32652. }
  32653. }
  32654. void Component::postCommandMessage (const int commandId)
  32655. {
  32656. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32657. }
  32658. void Component::handleCommandMessage (int)
  32659. {
  32660. // used by subclasses
  32661. }
  32662. void Component::addMouseListener (MouseListener* const newListener,
  32663. const bool wantsEventsForAllNestedChildComponents)
  32664. {
  32665. // if component methods are being called from threads other than the message
  32666. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32667. checkMessageManagerIsLocked
  32668. if (mouseListeners_ == 0)
  32669. mouseListeners_ = new Array<MouseListener*>();
  32670. if (! mouseListeners_->contains (newListener))
  32671. {
  32672. if (wantsEventsForAllNestedChildComponents)
  32673. {
  32674. mouseListeners_->insert (0, newListener);
  32675. ++numDeepMouseListeners;
  32676. }
  32677. else
  32678. {
  32679. mouseListeners_->add (newListener);
  32680. }
  32681. }
  32682. }
  32683. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32684. {
  32685. // if component methods are being called from threads other than the message
  32686. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32687. checkMessageManagerIsLocked
  32688. if (mouseListeners_ != 0)
  32689. {
  32690. const int index = mouseListeners_->indexOf (listenerToRemove);
  32691. if (index >= 0)
  32692. {
  32693. if (index < numDeepMouseListeners)
  32694. --numDeepMouseListeners;
  32695. mouseListeners_->remove (index);
  32696. }
  32697. }
  32698. }
  32699. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32700. {
  32701. if (isCurrentlyBlockedByAnotherModalComponent())
  32702. {
  32703. // if something else is modal, always just show a normal mouse cursor
  32704. source.showMouseCursor (MouseCursor::NormalCursor);
  32705. return;
  32706. }
  32707. if (! flags.mouseInsideFlag)
  32708. {
  32709. flags.mouseInsideFlag = true;
  32710. flags.mouseOverFlag = true;
  32711. flags.draggingFlag = false;
  32712. BailOutChecker checker (this);
  32713. if (flags.repaintOnMouseActivityFlag)
  32714. repaint();
  32715. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32716. this, this, time, relativePos,
  32717. time, 0, false);
  32718. mouseEnter (me);
  32719. if (checker.shouldBailOut())
  32720. return;
  32721. Desktop::getInstance().resetTimer();
  32722. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32723. if (checker.shouldBailOut())
  32724. return;
  32725. if (mouseListeners_ != 0)
  32726. {
  32727. for (int i = mouseListeners_->size(); --i >= 0;)
  32728. {
  32729. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32730. if (checker.shouldBailOut())
  32731. return;
  32732. i = jmin (i, mouseListeners_->size());
  32733. }
  32734. }
  32735. Component* p = parentComponent_;
  32736. while (p != 0)
  32737. {
  32738. if (p->numDeepMouseListeners > 0)
  32739. {
  32740. BailOutChecker checker2 (this, p);
  32741. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32742. {
  32743. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32744. if (checker2.shouldBailOut())
  32745. return;
  32746. i = jmin (i, p->numDeepMouseListeners);
  32747. }
  32748. }
  32749. p = p->parentComponent_;
  32750. }
  32751. }
  32752. }
  32753. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32754. {
  32755. BailOutChecker checker (this);
  32756. if (flags.draggingFlag)
  32757. {
  32758. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32759. if (checker.shouldBailOut())
  32760. return;
  32761. }
  32762. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32763. {
  32764. flags.mouseInsideFlag = false;
  32765. flags.mouseOverFlag = false;
  32766. flags.draggingFlag = false;
  32767. if (flags.repaintOnMouseActivityFlag)
  32768. repaint();
  32769. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32770. this, this, time, relativePos,
  32771. time, 0, false);
  32772. mouseExit (me);
  32773. if (checker.shouldBailOut())
  32774. return;
  32775. Desktop::getInstance().resetTimer();
  32776. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32777. if (checker.shouldBailOut())
  32778. return;
  32779. if (mouseListeners_ != 0)
  32780. {
  32781. for (int i = mouseListeners_->size(); --i >= 0;)
  32782. {
  32783. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32784. if (checker.shouldBailOut())
  32785. return;
  32786. i = jmin (i, mouseListeners_->size());
  32787. }
  32788. }
  32789. Component* p = parentComponent_;
  32790. while (p != 0)
  32791. {
  32792. if (p->numDeepMouseListeners > 0)
  32793. {
  32794. BailOutChecker checker2 (this, p);
  32795. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32796. {
  32797. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32798. if (checker2.shouldBailOut())
  32799. return;
  32800. i = jmin (i, p->numDeepMouseListeners);
  32801. }
  32802. }
  32803. p = p->parentComponent_;
  32804. }
  32805. }
  32806. }
  32807. class InternalDragRepeater : public Timer
  32808. {
  32809. public:
  32810. InternalDragRepeater()
  32811. {}
  32812. ~InternalDragRepeater()
  32813. {
  32814. clearSingletonInstance();
  32815. }
  32816. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32817. void timerCallback()
  32818. {
  32819. Desktop& desktop = Desktop::getInstance();
  32820. int numMiceDown = 0;
  32821. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32822. {
  32823. MouseInputSource* const source = desktop.getMouseSource(i);
  32824. if (source->isDragging())
  32825. {
  32826. source->triggerFakeMove();
  32827. ++numMiceDown;
  32828. }
  32829. }
  32830. if (numMiceDown == 0)
  32831. deleteInstance();
  32832. }
  32833. juce_UseDebuggingNewOperator
  32834. private:
  32835. InternalDragRepeater (const InternalDragRepeater&);
  32836. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32837. };
  32838. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32839. void Component::beginDragAutoRepeat (const int interval)
  32840. {
  32841. if (interval > 0)
  32842. {
  32843. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32844. InternalDragRepeater::getInstance()->startTimer (interval);
  32845. }
  32846. else
  32847. {
  32848. InternalDragRepeater::deleteInstance();
  32849. }
  32850. }
  32851. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32852. {
  32853. Desktop& desktop = Desktop::getInstance();
  32854. BailOutChecker checker (this);
  32855. if (isCurrentlyBlockedByAnotherModalComponent())
  32856. {
  32857. internalModalInputAttempt();
  32858. if (checker.shouldBailOut())
  32859. return;
  32860. // If processing the input attempt has exited the modal loop, we'll allow the event
  32861. // to be delivered..
  32862. if (isCurrentlyBlockedByAnotherModalComponent())
  32863. {
  32864. // allow blocked mouse-events to go to global listeners..
  32865. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32866. this, this, time, relativePos, time,
  32867. source.getNumberOfMultipleClicks(), false);
  32868. desktop.resetTimer();
  32869. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32870. return;
  32871. }
  32872. }
  32873. {
  32874. Component* c = this;
  32875. while (c != 0)
  32876. {
  32877. if (c->isBroughtToFrontOnMouseClick())
  32878. {
  32879. c->toFront (true);
  32880. if (checker.shouldBailOut())
  32881. return;
  32882. }
  32883. c = c->parentComponent_;
  32884. }
  32885. }
  32886. if (! flags.dontFocusOnMouseClickFlag)
  32887. {
  32888. grabFocusInternal (focusChangedByMouseClick);
  32889. if (checker.shouldBailOut())
  32890. return;
  32891. }
  32892. flags.draggingFlag = true;
  32893. flags.mouseOverFlag = true;
  32894. if (flags.repaintOnMouseActivityFlag)
  32895. repaint();
  32896. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32897. this, this, time, relativePos, time,
  32898. source.getNumberOfMultipleClicks(), false);
  32899. mouseDown (me);
  32900. if (checker.shouldBailOut())
  32901. return;
  32902. desktop.resetTimer();
  32903. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32904. if (checker.shouldBailOut())
  32905. return;
  32906. if (mouseListeners_ != 0)
  32907. {
  32908. for (int i = mouseListeners_->size(); --i >= 0;)
  32909. {
  32910. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32911. if (checker.shouldBailOut())
  32912. return;
  32913. i = jmin (i, mouseListeners_->size());
  32914. }
  32915. }
  32916. Component* p = parentComponent_;
  32917. while (p != 0)
  32918. {
  32919. if (p->numDeepMouseListeners > 0)
  32920. {
  32921. BailOutChecker checker2 (this, p);
  32922. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32923. {
  32924. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32925. if (checker2.shouldBailOut())
  32926. return;
  32927. i = jmin (i, p->numDeepMouseListeners);
  32928. }
  32929. }
  32930. p = p->parentComponent_;
  32931. }
  32932. }
  32933. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32934. {
  32935. if (flags.draggingFlag)
  32936. {
  32937. Desktop& desktop = Desktop::getInstance();
  32938. flags.draggingFlag = false;
  32939. BailOutChecker checker (this);
  32940. if (flags.repaintOnMouseActivityFlag)
  32941. repaint();
  32942. const MouseEvent me (source, relativePos,
  32943. oldModifiers, this, this, time,
  32944. globalPositionToRelative (source.getLastMouseDownPosition()),
  32945. source.getLastMouseDownTime(),
  32946. source.getNumberOfMultipleClicks(),
  32947. source.hasMouseMovedSignificantlySincePressed());
  32948. mouseUp (me);
  32949. if (checker.shouldBailOut())
  32950. return;
  32951. desktop.resetTimer();
  32952. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32953. if (checker.shouldBailOut())
  32954. return;
  32955. if (mouseListeners_ != 0)
  32956. {
  32957. for (int i = mouseListeners_->size(); --i >= 0;)
  32958. {
  32959. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32960. if (checker.shouldBailOut())
  32961. return;
  32962. i = jmin (i, mouseListeners_->size());
  32963. }
  32964. }
  32965. {
  32966. Component* p = parentComponent_;
  32967. while (p != 0)
  32968. {
  32969. if (p->numDeepMouseListeners > 0)
  32970. {
  32971. BailOutChecker checker2 (this, p);
  32972. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32973. {
  32974. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32975. if (checker2.shouldBailOut())
  32976. return;
  32977. i = jmin (i, p->numDeepMouseListeners);
  32978. }
  32979. }
  32980. p = p->parentComponent_;
  32981. }
  32982. }
  32983. // check for double-click
  32984. if (me.getNumberOfClicks() >= 2)
  32985. {
  32986. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32987. mouseDoubleClick (me);
  32988. if (checker.shouldBailOut())
  32989. return;
  32990. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  32991. if (checker.shouldBailOut())
  32992. return;
  32993. for (int i = numListeners; --i >= 0;)
  32994. {
  32995. if (checker.shouldBailOut())
  32996. return;
  32997. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32998. if (ml != 0)
  32999. ml->mouseDoubleClick (me);
  33000. }
  33001. if (checker.shouldBailOut())
  33002. return;
  33003. Component* p = parentComponent_;
  33004. while (p != 0)
  33005. {
  33006. if (p->numDeepMouseListeners > 0)
  33007. {
  33008. BailOutChecker checker2 (this, p);
  33009. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33010. {
  33011. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33012. if (checker2.shouldBailOut())
  33013. return;
  33014. i = jmin (i, p->numDeepMouseListeners);
  33015. }
  33016. }
  33017. p = p->parentComponent_;
  33018. }
  33019. }
  33020. }
  33021. }
  33022. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33023. {
  33024. if (flags.draggingFlag)
  33025. {
  33026. Desktop& desktop = Desktop::getInstance();
  33027. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33028. BailOutChecker checker (this);
  33029. const MouseEvent me (source, relativePos,
  33030. source.getCurrentModifiers(), this, this, time,
  33031. globalPositionToRelative (source.getLastMouseDownPosition()),
  33032. source.getLastMouseDownTime(),
  33033. source.getNumberOfMultipleClicks(),
  33034. source.hasMouseMovedSignificantlySincePressed());
  33035. mouseDrag (me);
  33036. if (checker.shouldBailOut())
  33037. return;
  33038. desktop.resetTimer();
  33039. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33040. if (checker.shouldBailOut())
  33041. return;
  33042. if (mouseListeners_ != 0)
  33043. {
  33044. for (int i = mouseListeners_->size(); --i >= 0;)
  33045. {
  33046. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33047. if (checker.shouldBailOut())
  33048. return;
  33049. i = jmin (i, mouseListeners_->size());
  33050. }
  33051. }
  33052. Component* p = parentComponent_;
  33053. while (p != 0)
  33054. {
  33055. if (p->numDeepMouseListeners > 0)
  33056. {
  33057. BailOutChecker checker2 (this, p);
  33058. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33059. {
  33060. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33061. if (checker2.shouldBailOut())
  33062. return;
  33063. i = jmin (i, p->numDeepMouseListeners);
  33064. }
  33065. }
  33066. p = p->parentComponent_;
  33067. }
  33068. }
  33069. }
  33070. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33071. {
  33072. Desktop& desktop = Desktop::getInstance();
  33073. BailOutChecker checker (this);
  33074. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33075. this, this, time, relativePos,
  33076. time, 0, false);
  33077. if (isCurrentlyBlockedByAnotherModalComponent())
  33078. {
  33079. // allow blocked mouse-events to go to global listeners..
  33080. desktop.sendMouseMove();
  33081. }
  33082. else
  33083. {
  33084. flags.mouseOverFlag = true;
  33085. mouseMove (me);
  33086. if (checker.shouldBailOut())
  33087. return;
  33088. desktop.resetTimer();
  33089. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33090. if (checker.shouldBailOut())
  33091. return;
  33092. if (mouseListeners_ != 0)
  33093. {
  33094. for (int i = mouseListeners_->size(); --i >= 0;)
  33095. {
  33096. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33097. if (checker.shouldBailOut())
  33098. return;
  33099. i = jmin (i, mouseListeners_->size());
  33100. }
  33101. }
  33102. Component* p = parentComponent_;
  33103. while (p != 0)
  33104. {
  33105. if (p->numDeepMouseListeners > 0)
  33106. {
  33107. BailOutChecker checker2 (this, p);
  33108. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33109. {
  33110. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33111. if (checker2.shouldBailOut())
  33112. return;
  33113. i = jmin (i, p->numDeepMouseListeners);
  33114. }
  33115. }
  33116. p = p->parentComponent_;
  33117. }
  33118. }
  33119. }
  33120. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33121. const Time& time, const float amountX, const float amountY)
  33122. {
  33123. Desktop& desktop = Desktop::getInstance();
  33124. BailOutChecker checker (this);
  33125. const float wheelIncrementX = amountX * (1.0f / 256.0f);
  33126. const float wheelIncrementY = amountY * (1.0f / 256.0f);
  33127. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33128. this, this, time, relativePos, time, 0, false);
  33129. if (isCurrentlyBlockedByAnotherModalComponent())
  33130. {
  33131. // allow blocked mouse-events to go to global listeners..
  33132. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33133. }
  33134. else
  33135. {
  33136. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33137. if (checker.shouldBailOut())
  33138. return;
  33139. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33140. if (checker.shouldBailOut())
  33141. return;
  33142. if (mouseListeners_ != 0)
  33143. {
  33144. for (int i = mouseListeners_->size(); --i >= 0;)
  33145. {
  33146. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33147. if (checker.shouldBailOut())
  33148. return;
  33149. i = jmin (i, mouseListeners_->size());
  33150. }
  33151. }
  33152. Component* p = parentComponent_;
  33153. while (p != 0)
  33154. {
  33155. if (p->numDeepMouseListeners > 0)
  33156. {
  33157. BailOutChecker checker2 (this, p);
  33158. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33159. {
  33160. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33161. if (checker2.shouldBailOut())
  33162. return;
  33163. i = jmin (i, p->numDeepMouseListeners);
  33164. }
  33165. }
  33166. p = p->parentComponent_;
  33167. }
  33168. }
  33169. }
  33170. void Component::sendFakeMouseMove() const
  33171. {
  33172. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33173. }
  33174. void Component::broughtToFront()
  33175. {
  33176. }
  33177. void Component::internalBroughtToFront()
  33178. {
  33179. if (! isValidComponent())
  33180. return;
  33181. if (flags.hasHeavyweightPeerFlag)
  33182. Desktop::getInstance().componentBroughtToFront (this);
  33183. BailOutChecker checker (this);
  33184. broughtToFront();
  33185. if (checker.shouldBailOut())
  33186. return;
  33187. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33188. if (checker.shouldBailOut())
  33189. return;
  33190. // When brought to the front and there's a modal component blocking this one,
  33191. // we need to bring the modal one to the front instead..
  33192. Component* const cm = getCurrentlyModalComponent();
  33193. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33194. bringModalComponentToFront();
  33195. }
  33196. void Component::focusGained (FocusChangeType)
  33197. {
  33198. // base class does nothing
  33199. }
  33200. void Component::internalFocusGain (const FocusChangeType cause)
  33201. {
  33202. SafePointer<Component> safePointer (this);
  33203. focusGained (cause);
  33204. if (safePointer != 0)
  33205. internalChildFocusChange (cause);
  33206. }
  33207. void Component::focusLost (FocusChangeType)
  33208. {
  33209. // base class does nothing
  33210. }
  33211. void Component::internalFocusLoss (const FocusChangeType cause)
  33212. {
  33213. SafePointer<Component> safePointer (this);
  33214. focusLost (focusChangedDirectly);
  33215. if (safePointer != 0)
  33216. internalChildFocusChange (cause);
  33217. }
  33218. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33219. {
  33220. // base class does nothing
  33221. }
  33222. void Component::internalChildFocusChange (FocusChangeType cause)
  33223. {
  33224. const bool childIsNowFocused = hasKeyboardFocus (true);
  33225. if (flags.childCompFocusedFlag != childIsNowFocused)
  33226. {
  33227. flags.childCompFocusedFlag = childIsNowFocused;
  33228. SafePointer<Component> safePointer (this);
  33229. focusOfChildComponentChanged (cause);
  33230. if (safePointer == 0)
  33231. return;
  33232. }
  33233. if (parentComponent_ != 0)
  33234. parentComponent_->internalChildFocusChange (cause);
  33235. }
  33236. bool Component::isEnabled() const throw()
  33237. {
  33238. return (! flags.isDisabledFlag)
  33239. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33240. }
  33241. void Component::setEnabled (const bool shouldBeEnabled)
  33242. {
  33243. if (flags.isDisabledFlag == shouldBeEnabled)
  33244. {
  33245. flags.isDisabledFlag = ! shouldBeEnabled;
  33246. // if any parent components are disabled, setting our flag won't make a difference,
  33247. // so no need to send a change message
  33248. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33249. sendEnablementChangeMessage();
  33250. }
  33251. }
  33252. void Component::sendEnablementChangeMessage()
  33253. {
  33254. SafePointer<Component> safePointer (this);
  33255. enablementChanged();
  33256. if (safePointer == 0)
  33257. return;
  33258. for (int i = getNumChildComponents(); --i >= 0;)
  33259. {
  33260. Component* const c = getChildComponent (i);
  33261. if (c != 0)
  33262. {
  33263. c->sendEnablementChangeMessage();
  33264. if (safePointer == 0)
  33265. return;
  33266. }
  33267. }
  33268. }
  33269. void Component::enablementChanged()
  33270. {
  33271. }
  33272. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33273. {
  33274. flags.wantsFocusFlag = wantsFocus;
  33275. }
  33276. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33277. {
  33278. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33279. }
  33280. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33281. {
  33282. return ! flags.dontFocusOnMouseClickFlag;
  33283. }
  33284. bool Component::getWantsKeyboardFocus() const throw()
  33285. {
  33286. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33287. }
  33288. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33289. {
  33290. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33291. }
  33292. bool Component::isFocusContainer() const throw()
  33293. {
  33294. return flags.isFocusContainerFlag;
  33295. }
  33296. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33297. int Component::getExplicitFocusOrder() const
  33298. {
  33299. return properties [juce_explicitFocusOrderId];
  33300. }
  33301. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33302. {
  33303. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33304. }
  33305. KeyboardFocusTraverser* Component::createFocusTraverser()
  33306. {
  33307. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33308. return new KeyboardFocusTraverser();
  33309. return parentComponent_->createFocusTraverser();
  33310. }
  33311. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33312. {
  33313. // give the focus to this component
  33314. if (currentlyFocusedComponent != this)
  33315. {
  33316. JUCE_TRY
  33317. {
  33318. // get the focus onto our desktop window
  33319. ComponentPeer* const peer = getPeer();
  33320. if (peer != 0)
  33321. {
  33322. SafePointer<Component> safePointer (this);
  33323. peer->grabFocus();
  33324. if (peer->isFocused() && currentlyFocusedComponent != this)
  33325. {
  33326. Component* const componentLosingFocus = currentlyFocusedComponent;
  33327. currentlyFocusedComponent = this;
  33328. Desktop::getInstance().triggerFocusCallback();
  33329. // call this after setting currentlyFocusedComponent so that the one that's
  33330. // losing it has a chance to see where focus is going
  33331. if (componentLosingFocus->isValidComponent())
  33332. componentLosingFocus->internalFocusLoss (cause);
  33333. if (currentlyFocusedComponent == this)
  33334. {
  33335. focusGained (cause);
  33336. if (safePointer != 0)
  33337. internalChildFocusChange (cause);
  33338. }
  33339. }
  33340. }
  33341. }
  33342. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33343. catch (const std::exception& e)
  33344. {
  33345. currentlyFocusedComponent = 0;
  33346. Desktop::getInstance().triggerFocusCallback();
  33347. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33348. }
  33349. catch (...)
  33350. {
  33351. currentlyFocusedComponent = 0;
  33352. Desktop::getInstance().triggerFocusCallback();
  33353. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33354. }
  33355. #endif
  33356. }
  33357. }
  33358. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33359. {
  33360. if (isShowing())
  33361. {
  33362. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33363. {
  33364. takeKeyboardFocus (cause);
  33365. }
  33366. else
  33367. {
  33368. if (isParentOf (currentlyFocusedComponent)
  33369. && currentlyFocusedComponent->isShowing())
  33370. {
  33371. // do nothing if the focused component is actually a child of ours..
  33372. }
  33373. else
  33374. {
  33375. // find the default child component..
  33376. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33377. if (traverser != 0)
  33378. {
  33379. Component* const defaultComp = traverser->getDefaultComponent (this);
  33380. traverser = 0;
  33381. if (defaultComp != 0)
  33382. {
  33383. defaultComp->grabFocusInternal (cause, false);
  33384. return;
  33385. }
  33386. }
  33387. if (canTryParent && parentComponent_ != 0)
  33388. {
  33389. // if no children want it and we're allowed to try our parent comp,
  33390. // then pass up to parent, which will try our siblings.
  33391. parentComponent_->grabFocusInternal (cause, true);
  33392. }
  33393. }
  33394. }
  33395. }
  33396. }
  33397. void Component::grabKeyboardFocus()
  33398. {
  33399. // if component methods are being called from threads other than the message
  33400. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33401. checkMessageManagerIsLocked
  33402. grabFocusInternal (focusChangedDirectly);
  33403. }
  33404. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33405. {
  33406. // if component methods are being called from threads other than the message
  33407. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33408. checkMessageManagerIsLocked
  33409. if (parentComponent_ != 0)
  33410. {
  33411. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33412. if (traverser != 0)
  33413. {
  33414. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33415. : traverser->getPreviousComponent (this);
  33416. traverser = 0;
  33417. if (nextComp != 0)
  33418. {
  33419. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33420. {
  33421. SafePointer<Component> nextCompPointer (nextComp);
  33422. internalModalInputAttempt();
  33423. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33424. return;
  33425. }
  33426. nextComp->grabFocusInternal (focusChangedByTabKey);
  33427. return;
  33428. }
  33429. }
  33430. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33431. }
  33432. }
  33433. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33434. {
  33435. return (currentlyFocusedComponent == this)
  33436. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33437. }
  33438. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33439. {
  33440. return currentlyFocusedComponent;
  33441. }
  33442. void Component::giveAwayFocus()
  33443. {
  33444. // use a copy so we can clear the value before the call
  33445. Component* const componentLosingFocus = currentlyFocusedComponent;
  33446. currentlyFocusedComponent = 0;
  33447. Desktop::getInstance().triggerFocusCallback();
  33448. if (componentLosingFocus->isValidComponent())
  33449. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33450. }
  33451. bool Component::isMouseOver() const throw()
  33452. {
  33453. return flags.mouseOverFlag;
  33454. }
  33455. bool Component::isMouseButtonDown() const throw()
  33456. {
  33457. return flags.draggingFlag;
  33458. }
  33459. bool Component::isMouseOverOrDragging() const throw()
  33460. {
  33461. return flags.mouseOverFlag || flags.draggingFlag;
  33462. }
  33463. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33464. {
  33465. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33466. }
  33467. const Point<int> Component::getMouseXYRelative() const
  33468. {
  33469. return globalPositionToRelative (Desktop::getMousePosition());
  33470. }
  33471. const Rectangle<int> Component::getParentMonitorArea() const
  33472. {
  33473. return Desktop::getInstance()
  33474. .getMonitorAreaContaining (relativePositionToGlobal (Point<int> (getWidth() / 2,
  33475. getHeight() / 2)));
  33476. }
  33477. void Component::addKeyListener (KeyListener* const newListener)
  33478. {
  33479. if (keyListeners_ == 0)
  33480. keyListeners_ = new Array <KeyListener*>();
  33481. keyListeners_->addIfNotAlreadyThere (newListener);
  33482. }
  33483. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33484. {
  33485. if (keyListeners_ != 0)
  33486. keyListeners_->removeValue (listenerToRemove);
  33487. }
  33488. bool Component::keyPressed (const KeyPress&)
  33489. {
  33490. return false;
  33491. }
  33492. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33493. {
  33494. return false;
  33495. }
  33496. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33497. {
  33498. if (parentComponent_ != 0)
  33499. parentComponent_->modifierKeysChanged (modifiers);
  33500. }
  33501. void Component::internalModifierKeysChanged()
  33502. {
  33503. sendFakeMouseMove();
  33504. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33505. }
  33506. ComponentPeer* Component::getPeer() const
  33507. {
  33508. if (flags.hasHeavyweightPeerFlag)
  33509. return ComponentPeer::getPeerFor (this);
  33510. else if (parentComponent_ != 0)
  33511. return parentComponent_->getPeer();
  33512. else
  33513. return 0;
  33514. }
  33515. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33516. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33517. {
  33518. jassert (component1 != 0);
  33519. }
  33520. bool Component::BailOutChecker::shouldBailOut() const throw()
  33521. {
  33522. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33523. }
  33524. END_JUCE_NAMESPACE
  33525. /*** End of inlined file: juce_Component.cpp ***/
  33526. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33527. BEGIN_JUCE_NAMESPACE
  33528. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33529. void ComponentListener::componentBroughtToFront (Component&) {}
  33530. void ComponentListener::componentVisibilityChanged (Component&) {}
  33531. void ComponentListener::componentChildrenChanged (Component&) {}
  33532. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33533. void ComponentListener::componentNameChanged (Component&) {}
  33534. void ComponentListener::componentBeingDeleted (Component&) {}
  33535. END_JUCE_NAMESPACE
  33536. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33537. /*** Start of inlined file: juce_Desktop.cpp ***/
  33538. BEGIN_JUCE_NAMESPACE
  33539. Desktop::Desktop()
  33540. : mouseClickCounter (0),
  33541. kioskModeComponent (0)
  33542. {
  33543. createMouseInputSources();
  33544. refreshMonitorSizes();
  33545. }
  33546. Desktop::~Desktop()
  33547. {
  33548. jassert (instance == this);
  33549. instance = 0;
  33550. // doh! If you don't delete all your windows before exiting, you're going to
  33551. // be leaking memory!
  33552. jassert (desktopComponents.size() == 0);
  33553. }
  33554. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33555. {
  33556. if (instance == 0)
  33557. instance = new Desktop();
  33558. return *instance;
  33559. }
  33560. Desktop* Desktop::instance = 0;
  33561. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33562. const bool clipToWorkArea);
  33563. void Desktop::refreshMonitorSizes()
  33564. {
  33565. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33566. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33567. monitorCoordsClipped.clear();
  33568. monitorCoordsUnclipped.clear();
  33569. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33570. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33571. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33572. if (oldClipped != monitorCoordsClipped
  33573. || oldUnclipped != monitorCoordsUnclipped)
  33574. {
  33575. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33576. {
  33577. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33578. if (p != 0)
  33579. p->handleScreenSizeChange();
  33580. }
  33581. }
  33582. }
  33583. int Desktop::getNumDisplayMonitors() const throw()
  33584. {
  33585. return monitorCoordsClipped.size();
  33586. }
  33587. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33588. {
  33589. return clippedToWorkArea ? monitorCoordsClipped [index]
  33590. : monitorCoordsUnclipped [index];
  33591. }
  33592. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33593. {
  33594. RectangleList rl;
  33595. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33596. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33597. return rl;
  33598. }
  33599. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33600. {
  33601. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33602. }
  33603. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33604. {
  33605. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33606. double bestDistance = 1.0e10;
  33607. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33608. {
  33609. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33610. if (rect.contains (position))
  33611. return rect;
  33612. const double distance = rect.getCentre().getDistanceFrom (position);
  33613. if (distance < bestDistance)
  33614. {
  33615. bestDistance = distance;
  33616. best = rect;
  33617. }
  33618. }
  33619. return best;
  33620. }
  33621. int Desktop::getNumComponents() const throw()
  33622. {
  33623. return desktopComponents.size();
  33624. }
  33625. Component* Desktop::getComponent (const int index) const throw()
  33626. {
  33627. return desktopComponents [index];
  33628. }
  33629. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33630. {
  33631. for (int i = desktopComponents.size(); --i >= 0;)
  33632. {
  33633. Component* const c = desktopComponents.getUnchecked(i);
  33634. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33635. if (c->contains (relative.getX(), relative.getY()))
  33636. return c->getComponentAt (relative.getX(), relative.getY());
  33637. }
  33638. return 0;
  33639. }
  33640. void Desktop::addDesktopComponent (Component* const c)
  33641. {
  33642. jassert (c != 0);
  33643. jassert (! desktopComponents.contains (c));
  33644. desktopComponents.addIfNotAlreadyThere (c);
  33645. }
  33646. void Desktop::removeDesktopComponent (Component* const c)
  33647. {
  33648. desktopComponents.removeValue (c);
  33649. }
  33650. void Desktop::componentBroughtToFront (Component* const c)
  33651. {
  33652. const int index = desktopComponents.indexOf (c);
  33653. jassert (index >= 0);
  33654. if (index >= 0)
  33655. {
  33656. int newIndex = -1;
  33657. if (! c->isAlwaysOnTop())
  33658. {
  33659. newIndex = desktopComponents.size();
  33660. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33661. --newIndex;
  33662. --newIndex;
  33663. }
  33664. desktopComponents.move (index, newIndex);
  33665. }
  33666. }
  33667. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33668. {
  33669. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33670. }
  33671. int Desktop::getMouseButtonClickCounter() throw()
  33672. {
  33673. return getInstance().mouseClickCounter;
  33674. }
  33675. void Desktop::incrementMouseClickCounter() throw()
  33676. {
  33677. ++mouseClickCounter;
  33678. }
  33679. int Desktop::getNumDraggingMouseSources() const throw()
  33680. {
  33681. int num = 0;
  33682. for (int i = mouseSources.size(); --i >= 0;)
  33683. if (mouseSources.getUnchecked(i)->isDragging())
  33684. ++num;
  33685. return num;
  33686. }
  33687. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33688. {
  33689. int num = 0;
  33690. for (int i = mouseSources.size(); --i >= 0;)
  33691. {
  33692. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33693. if (mi->isDragging())
  33694. {
  33695. if (index == num)
  33696. return mi;
  33697. ++num;
  33698. }
  33699. }
  33700. return 0;
  33701. }
  33702. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33703. {
  33704. focusListeners.add (listener);
  33705. }
  33706. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33707. {
  33708. focusListeners.remove (listener);
  33709. }
  33710. void Desktop::triggerFocusCallback()
  33711. {
  33712. triggerAsyncUpdate();
  33713. }
  33714. void Desktop::handleAsyncUpdate()
  33715. {
  33716. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33717. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33718. }
  33719. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33720. {
  33721. mouseListeners.add (listener);
  33722. resetTimer();
  33723. }
  33724. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33725. {
  33726. mouseListeners.remove (listener);
  33727. resetTimer();
  33728. }
  33729. void Desktop::timerCallback()
  33730. {
  33731. if (lastFakeMouseMove != getMousePosition())
  33732. sendMouseMove();
  33733. }
  33734. void Desktop::sendMouseMove()
  33735. {
  33736. if (! mouseListeners.isEmpty())
  33737. {
  33738. startTimer (20);
  33739. lastFakeMouseMove = getMousePosition();
  33740. Component* const target = findComponentAt (lastFakeMouseMove);
  33741. if (target != 0)
  33742. {
  33743. Component::BailOutChecker checker (target);
  33744. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33745. const Time now (Time::getCurrentTime());
  33746. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33747. target, target, now, pos, now, 0, false);
  33748. if (me.mods.isAnyMouseButtonDown())
  33749. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33750. else
  33751. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33752. }
  33753. }
  33754. }
  33755. void Desktop::resetTimer()
  33756. {
  33757. if (mouseListeners.size() == 0)
  33758. stopTimer();
  33759. else
  33760. startTimer (100);
  33761. lastFakeMouseMove = getMousePosition();
  33762. }
  33763. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33764. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33765. {
  33766. if (kioskModeComponent != componentToUse)
  33767. {
  33768. // agh! Don't delete a component without first stopping it being the kiosk comp
  33769. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33770. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33771. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33772. if (kioskModeComponent->isValidComponent())
  33773. {
  33774. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33775. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33776. }
  33777. kioskModeComponent = componentToUse;
  33778. if (kioskModeComponent != 0)
  33779. {
  33780. jassert (kioskModeComponent->isValidComponent());
  33781. // Only components that are already on the desktop can be put into kiosk mode!
  33782. jassert (kioskModeComponent->isOnDesktop());
  33783. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33784. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33785. }
  33786. }
  33787. }
  33788. END_JUCE_NAMESPACE
  33789. /*** End of inlined file: juce_Desktop.cpp ***/
  33790. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33791. BEGIN_JUCE_NAMESPACE
  33792. ArrowButton::ArrowButton (const String& name,
  33793. float arrowDirectionInRadians,
  33794. const Colour& arrowColour)
  33795. : Button (name),
  33796. colour (arrowColour)
  33797. {
  33798. path.lineTo (0.0f, 1.0f);
  33799. path.lineTo (1.0f, 0.5f);
  33800. path.closeSubPath();
  33801. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33802. 0.5f, 0.5f));
  33803. setComponentEffect (&shadow);
  33804. buttonStateChanged();
  33805. }
  33806. ArrowButton::~ArrowButton()
  33807. {
  33808. }
  33809. void ArrowButton::paintButton (Graphics& g,
  33810. bool /*isMouseOverButton*/,
  33811. bool /*isButtonDown*/)
  33812. {
  33813. g.setColour (colour);
  33814. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33815. (float) offset,
  33816. (float) (getWidth() - 3),
  33817. (float) (getHeight() - 3),
  33818. false));
  33819. }
  33820. void ArrowButton::buttonStateChanged()
  33821. {
  33822. offset = (isDown()) ? 1 : 0;
  33823. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33824. 0.3f, -1, 0);
  33825. }
  33826. END_JUCE_NAMESPACE
  33827. /*** End of inlined file: juce_ArrowButton.cpp ***/
  33828. /*** Start of inlined file: juce_Button.cpp ***/
  33829. BEGIN_JUCE_NAMESPACE
  33830. class Button::RepeatTimer : public Timer
  33831. {
  33832. public:
  33833. RepeatTimer (Button& owner_) : owner (owner_) {}
  33834. void timerCallback() { owner.repeatTimerCallback(); }
  33835. juce_UseDebuggingNewOperator
  33836. private:
  33837. Button& owner;
  33838. RepeatTimer (const RepeatTimer&);
  33839. RepeatTimer& operator= (const RepeatTimer&);
  33840. };
  33841. Button::Button (const String& name)
  33842. : Component (name),
  33843. text (name),
  33844. buttonPressTime (0),
  33845. lastTimeCallbackTime (0),
  33846. commandManagerToUse (0),
  33847. autoRepeatDelay (-1),
  33848. autoRepeatSpeed (0),
  33849. autoRepeatMinimumDelay (-1),
  33850. radioGroupId (0),
  33851. commandID (0),
  33852. connectedEdgeFlags (0),
  33853. buttonState (buttonNormal),
  33854. lastToggleState (false),
  33855. clickTogglesState (false),
  33856. needsToRelease (false),
  33857. needsRepainting (false),
  33858. isKeyDown (false),
  33859. triggerOnMouseDown (false),
  33860. generateTooltip (false)
  33861. {
  33862. setWantsKeyboardFocus (true);
  33863. isOn.addListener (this);
  33864. }
  33865. Button::~Button()
  33866. {
  33867. isOn.removeListener (this);
  33868. if (commandManagerToUse != 0)
  33869. commandManagerToUse->removeListener (this);
  33870. repeatTimer = 0;
  33871. clearShortcuts();
  33872. }
  33873. void Button::setButtonText (const String& newText)
  33874. {
  33875. if (text != newText)
  33876. {
  33877. text = newText;
  33878. repaint();
  33879. }
  33880. }
  33881. void Button::setTooltip (const String& newTooltip)
  33882. {
  33883. SettableTooltipClient::setTooltip (newTooltip);
  33884. generateTooltip = false;
  33885. }
  33886. const String Button::getTooltip()
  33887. {
  33888. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33889. {
  33890. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33891. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33892. for (int i = 0; i < keyPresses.size(); ++i)
  33893. {
  33894. const String key (keyPresses.getReference(i).getTextDescription());
  33895. tt << " [";
  33896. if (key.length() == 1)
  33897. tt << TRANS("shortcut") << ": '" << key << "']";
  33898. else
  33899. tt << key << ']';
  33900. }
  33901. return tt;
  33902. }
  33903. return SettableTooltipClient::getTooltip();
  33904. }
  33905. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  33906. {
  33907. if (connectedEdgeFlags != connectedEdgeFlags_)
  33908. {
  33909. connectedEdgeFlags = connectedEdgeFlags_;
  33910. repaint();
  33911. }
  33912. }
  33913. void Button::setToggleState (const bool shouldBeOn,
  33914. const bool sendChangeNotification)
  33915. {
  33916. if (shouldBeOn != lastToggleState)
  33917. {
  33918. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  33919. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  33920. lastToggleState = shouldBeOn;
  33921. repaint();
  33922. if (sendChangeNotification)
  33923. {
  33924. Component::SafePointer<Component> deletionWatcher (this);
  33925. sendClickMessage (ModifierKeys());
  33926. if (deletionWatcher == 0)
  33927. return;
  33928. }
  33929. if (lastToggleState)
  33930. turnOffOtherButtonsInGroup (sendChangeNotification);
  33931. }
  33932. }
  33933. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33934. {
  33935. clickTogglesState = shouldToggle;
  33936. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33937. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33938. // it is that this button represents, and the button will update its state to reflect this
  33939. // in the applicationCommandListChanged() method.
  33940. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33941. }
  33942. bool Button::getClickingTogglesState() const throw()
  33943. {
  33944. return clickTogglesState;
  33945. }
  33946. void Button::valueChanged (Value& value)
  33947. {
  33948. if (value.refersToSameSourceAs (isOn))
  33949. setToggleState (isOn.getValue(), true);
  33950. }
  33951. void Button::setRadioGroupId (const int newGroupId)
  33952. {
  33953. if (radioGroupId != newGroupId)
  33954. {
  33955. radioGroupId = newGroupId;
  33956. if (lastToggleState)
  33957. turnOffOtherButtonsInGroup (true);
  33958. }
  33959. }
  33960. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33961. {
  33962. Component* const p = getParentComponent();
  33963. if (p != 0 && radioGroupId != 0)
  33964. {
  33965. Component::SafePointer<Component> deletionWatcher (this);
  33966. for (int i = p->getNumChildComponents(); --i >= 0;)
  33967. {
  33968. Component* const c = p->getChildComponent (i);
  33969. if (c != this)
  33970. {
  33971. Button* const b = dynamic_cast <Button*> (c);
  33972. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33973. {
  33974. b->setToggleState (false, sendChangeNotification);
  33975. if (deletionWatcher == 0)
  33976. return;
  33977. }
  33978. }
  33979. }
  33980. }
  33981. }
  33982. void Button::enablementChanged()
  33983. {
  33984. updateState (0);
  33985. repaint();
  33986. }
  33987. Button::ButtonState Button::updateState (const MouseEvent* const e)
  33988. {
  33989. ButtonState state = buttonNormal;
  33990. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33991. {
  33992. Point<int> mousePos;
  33993. if (e == 0)
  33994. mousePos = getMouseXYRelative();
  33995. else
  33996. mousePos = e->getEventRelativeTo (this).getPosition();
  33997. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  33998. const bool down = isMouseButtonDown();
  33999. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34000. state = buttonDown;
  34001. else if (over)
  34002. state = buttonOver;
  34003. }
  34004. setState (state);
  34005. return state;
  34006. }
  34007. void Button::setState (const ButtonState newState)
  34008. {
  34009. if (buttonState != newState)
  34010. {
  34011. buttonState = newState;
  34012. repaint();
  34013. if (buttonState == buttonDown)
  34014. {
  34015. buttonPressTime = Time::getApproximateMillisecondCounter();
  34016. lastTimeCallbackTime = buttonPressTime;
  34017. }
  34018. sendStateMessage();
  34019. }
  34020. }
  34021. bool Button::isDown() const throw()
  34022. {
  34023. return buttonState == buttonDown;
  34024. }
  34025. bool Button::isOver() const throw()
  34026. {
  34027. return buttonState != buttonNormal;
  34028. }
  34029. void Button::buttonStateChanged()
  34030. {
  34031. }
  34032. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34033. {
  34034. const uint32 now = Time::getApproximateMillisecondCounter();
  34035. return now > buttonPressTime ? now - buttonPressTime : 0;
  34036. }
  34037. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34038. {
  34039. triggerOnMouseDown = isTriggeredOnMouseDown;
  34040. }
  34041. void Button::clicked()
  34042. {
  34043. }
  34044. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34045. {
  34046. clicked();
  34047. }
  34048. static const int clickMessageId = 0x2f3f4f99;
  34049. void Button::triggerClick()
  34050. {
  34051. postCommandMessage (clickMessageId);
  34052. }
  34053. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34054. {
  34055. if (clickTogglesState)
  34056. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34057. sendClickMessage (modifiers);
  34058. }
  34059. void Button::flashButtonState()
  34060. {
  34061. if (isEnabled())
  34062. {
  34063. needsToRelease = true;
  34064. setState (buttonDown);
  34065. getRepeatTimer().startTimer (100);
  34066. }
  34067. }
  34068. void Button::handleCommandMessage (int commandId)
  34069. {
  34070. if (commandId == clickMessageId)
  34071. {
  34072. if (isEnabled())
  34073. {
  34074. flashButtonState();
  34075. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34076. }
  34077. }
  34078. else
  34079. {
  34080. Component::handleCommandMessage (commandId);
  34081. }
  34082. }
  34083. void Button::addButtonListener (ButtonListener* const newListener)
  34084. {
  34085. buttonListeners.add (newListener);
  34086. }
  34087. void Button::removeButtonListener (ButtonListener* const listener)
  34088. {
  34089. buttonListeners.remove (listener);
  34090. }
  34091. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34092. {
  34093. Component::BailOutChecker checker (this);
  34094. if (commandManagerToUse != 0 && commandID != 0)
  34095. {
  34096. ApplicationCommandTarget::InvocationInfo info (commandID);
  34097. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34098. info.originatingComponent = this;
  34099. commandManagerToUse->invoke (info, true);
  34100. }
  34101. clicked (modifiers);
  34102. if (! checker.shouldBailOut())
  34103. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this);
  34104. }
  34105. void Button::sendStateMessage()
  34106. {
  34107. Component::BailOutChecker checker (this);
  34108. buttonStateChanged();
  34109. if (! checker.shouldBailOut())
  34110. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34111. }
  34112. void Button::paint (Graphics& g)
  34113. {
  34114. if (needsToRelease && isEnabled())
  34115. {
  34116. needsToRelease = false;
  34117. needsRepainting = true;
  34118. }
  34119. paintButton (g, isOver(), isDown());
  34120. }
  34121. void Button::mouseEnter (const MouseEvent& e)
  34122. {
  34123. updateState (&e);
  34124. }
  34125. void Button::mouseExit (const MouseEvent& e)
  34126. {
  34127. updateState (&e);
  34128. }
  34129. void Button::mouseDown (const MouseEvent& e)
  34130. {
  34131. updateState (&e);
  34132. if (isDown())
  34133. {
  34134. if (autoRepeatDelay >= 0)
  34135. getRepeatTimer().startTimer (autoRepeatDelay);
  34136. if (triggerOnMouseDown)
  34137. internalClickCallback (e.mods);
  34138. }
  34139. }
  34140. void Button::mouseUp (const MouseEvent& e)
  34141. {
  34142. const bool wasDown = isDown();
  34143. updateState (&e);
  34144. if (wasDown && isOver() && ! triggerOnMouseDown)
  34145. internalClickCallback (e.mods);
  34146. }
  34147. void Button::mouseDrag (const MouseEvent& e)
  34148. {
  34149. const ButtonState oldState = buttonState;
  34150. updateState (&e);
  34151. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34152. getRepeatTimer().startTimer (autoRepeatSpeed);
  34153. }
  34154. void Button::focusGained (FocusChangeType)
  34155. {
  34156. updateState (0);
  34157. repaint();
  34158. }
  34159. void Button::focusLost (FocusChangeType)
  34160. {
  34161. updateState (0);
  34162. repaint();
  34163. }
  34164. void Button::setVisible (bool shouldBeVisible)
  34165. {
  34166. if (shouldBeVisible != isVisible())
  34167. {
  34168. Component::setVisible (shouldBeVisible);
  34169. if (! shouldBeVisible)
  34170. needsToRelease = false;
  34171. updateState (0);
  34172. }
  34173. else
  34174. {
  34175. Component::setVisible (shouldBeVisible);
  34176. }
  34177. }
  34178. void Button::parentHierarchyChanged()
  34179. {
  34180. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34181. if (newKeySource != keySource.getComponent())
  34182. {
  34183. if (keySource != 0)
  34184. keySource->removeKeyListener (this);
  34185. keySource = newKeySource;
  34186. if (keySource != 0)
  34187. keySource->addKeyListener (this);
  34188. }
  34189. }
  34190. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34191. const int commandID_,
  34192. const bool generateTooltip_)
  34193. {
  34194. commandID = commandID_;
  34195. generateTooltip = generateTooltip_;
  34196. if (commandManagerToUse != commandManagerToUse_)
  34197. {
  34198. if (commandManagerToUse != 0)
  34199. commandManagerToUse->removeListener (this);
  34200. commandManagerToUse = commandManagerToUse_;
  34201. if (commandManagerToUse != 0)
  34202. commandManagerToUse->addListener (this);
  34203. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34204. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34205. // it is that this button represents, and the button will update its state to reflect this
  34206. // in the applicationCommandListChanged() method.
  34207. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34208. }
  34209. if (commandManagerToUse != 0)
  34210. applicationCommandListChanged();
  34211. else
  34212. setEnabled (true);
  34213. }
  34214. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34215. {
  34216. if (info.commandID == commandID
  34217. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34218. {
  34219. flashButtonState();
  34220. }
  34221. }
  34222. void Button::applicationCommandListChanged()
  34223. {
  34224. if (commandManagerToUse != 0)
  34225. {
  34226. ApplicationCommandInfo info (0);
  34227. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34228. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34229. if (target != 0)
  34230. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34231. }
  34232. }
  34233. void Button::addShortcut (const KeyPress& key)
  34234. {
  34235. if (key.isValid())
  34236. {
  34237. jassert (! isRegisteredForShortcut (key)); // already registered!
  34238. shortcuts.add (key);
  34239. parentHierarchyChanged();
  34240. }
  34241. }
  34242. void Button::clearShortcuts()
  34243. {
  34244. shortcuts.clear();
  34245. parentHierarchyChanged();
  34246. }
  34247. bool Button::isShortcutPressed() const
  34248. {
  34249. if (! isCurrentlyBlockedByAnotherModalComponent())
  34250. {
  34251. for (int i = shortcuts.size(); --i >= 0;)
  34252. if (shortcuts.getReference(i).isCurrentlyDown())
  34253. return true;
  34254. }
  34255. return false;
  34256. }
  34257. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34258. {
  34259. for (int i = shortcuts.size(); --i >= 0;)
  34260. if (key == shortcuts.getReference(i))
  34261. return true;
  34262. return false;
  34263. }
  34264. bool Button::keyStateChanged (const bool, Component*)
  34265. {
  34266. if (! isEnabled())
  34267. return false;
  34268. const bool wasDown = isKeyDown;
  34269. isKeyDown = isShortcutPressed();
  34270. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34271. getRepeatTimer().startTimer (autoRepeatDelay);
  34272. updateState (0);
  34273. if (isEnabled() && wasDown && ! isKeyDown)
  34274. {
  34275. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34276. // (return immediately - this button may now have been deleted)
  34277. return true;
  34278. }
  34279. return wasDown || isKeyDown;
  34280. }
  34281. bool Button::keyPressed (const KeyPress&, Component*)
  34282. {
  34283. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34284. return isShortcutPressed();
  34285. }
  34286. bool Button::keyPressed (const KeyPress& key)
  34287. {
  34288. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34289. {
  34290. triggerClick();
  34291. return true;
  34292. }
  34293. return false;
  34294. }
  34295. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34296. const int repeatMillisecs,
  34297. const int minimumDelayInMillisecs) throw()
  34298. {
  34299. autoRepeatDelay = initialDelayMillisecs;
  34300. autoRepeatSpeed = repeatMillisecs;
  34301. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34302. }
  34303. void Button::repeatTimerCallback()
  34304. {
  34305. if (needsRepainting)
  34306. {
  34307. getRepeatTimer().stopTimer();
  34308. updateState (0);
  34309. needsRepainting = false;
  34310. }
  34311. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34312. {
  34313. int repeatSpeed = autoRepeatSpeed;
  34314. if (autoRepeatMinimumDelay >= 0)
  34315. {
  34316. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34317. timeHeldDown *= timeHeldDown;
  34318. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34319. }
  34320. repeatSpeed = jmax (1, repeatSpeed);
  34321. getRepeatTimer().startTimer (repeatSpeed);
  34322. const uint32 now = Time::getApproximateMillisecondCounter();
  34323. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34324. lastTimeCallbackTime = now;
  34325. Component::SafePointer<Component> deletionWatcher (this);
  34326. for (int i = numTimesToCallback; --i >= 0;)
  34327. {
  34328. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34329. if (deletionWatcher == 0 || ! isDown())
  34330. return;
  34331. }
  34332. }
  34333. else if (! needsToRelease)
  34334. {
  34335. getRepeatTimer().stopTimer();
  34336. }
  34337. }
  34338. Button::RepeatTimer& Button::getRepeatTimer()
  34339. {
  34340. if (repeatTimer == 0)
  34341. repeatTimer = new RepeatTimer (*this);
  34342. return *repeatTimer;
  34343. }
  34344. END_JUCE_NAMESPACE
  34345. /*** End of inlined file: juce_Button.cpp ***/
  34346. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34347. BEGIN_JUCE_NAMESPACE
  34348. DrawableButton::DrawableButton (const String& name,
  34349. const DrawableButton::ButtonStyle buttonStyle)
  34350. : Button (name),
  34351. style (buttonStyle),
  34352. edgeIndent (3)
  34353. {
  34354. if (buttonStyle == ImageOnButtonBackground)
  34355. {
  34356. backgroundOff = Colour (0xffbbbbff);
  34357. backgroundOn = Colour (0xff3333ff);
  34358. }
  34359. else
  34360. {
  34361. backgroundOff = Colours::transparentBlack;
  34362. backgroundOn = Colour (0xaabbbbff);
  34363. }
  34364. }
  34365. DrawableButton::~DrawableButton()
  34366. {
  34367. deleteImages();
  34368. }
  34369. void DrawableButton::deleteImages()
  34370. {
  34371. }
  34372. void DrawableButton::setImages (const Drawable* normal,
  34373. const Drawable* over,
  34374. const Drawable* down,
  34375. const Drawable* disabled,
  34376. const Drawable* normalOn,
  34377. const Drawable* overOn,
  34378. const Drawable* downOn,
  34379. const Drawable* disabledOn)
  34380. {
  34381. deleteImages();
  34382. jassert (normal != 0); // you really need to give it at least a normal image..
  34383. if (normal != 0)
  34384. normalImage = normal->createCopy();
  34385. if (over != 0)
  34386. overImage = over->createCopy();
  34387. if (down != 0)
  34388. downImage = down->createCopy();
  34389. if (disabled != 0)
  34390. disabledImage = disabled->createCopy();
  34391. if (normalOn != 0)
  34392. normalImageOn = normalOn->createCopy();
  34393. if (overOn != 0)
  34394. overImageOn = overOn->createCopy();
  34395. if (downOn != 0)
  34396. downImageOn = downOn->createCopy();
  34397. if (disabledOn != 0)
  34398. disabledImageOn = disabledOn->createCopy();
  34399. repaint();
  34400. }
  34401. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34402. {
  34403. if (style != newStyle)
  34404. {
  34405. style = newStyle;
  34406. repaint();
  34407. }
  34408. }
  34409. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34410. const Colour& toggledOnColour)
  34411. {
  34412. if (backgroundOff != toggledOffColour
  34413. || backgroundOn != toggledOnColour)
  34414. {
  34415. backgroundOff = toggledOffColour;
  34416. backgroundOn = toggledOnColour;
  34417. repaint();
  34418. }
  34419. }
  34420. const Colour& DrawableButton::getBackgroundColour() const throw()
  34421. {
  34422. return getToggleState() ? backgroundOn
  34423. : backgroundOff;
  34424. }
  34425. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34426. {
  34427. edgeIndent = numPixelsIndent;
  34428. repaint();
  34429. }
  34430. void DrawableButton::paintButton (Graphics& g,
  34431. bool isMouseOverButton,
  34432. bool isButtonDown)
  34433. {
  34434. Rectangle<int> imageSpace;
  34435. if (style == ImageOnButtonBackground)
  34436. {
  34437. const int insetX = getWidth() / 4;
  34438. const int insetY = getHeight() / 4;
  34439. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34440. getLookAndFeel().drawButtonBackground (g, *this,
  34441. getBackgroundColour(),
  34442. isMouseOverButton,
  34443. isButtonDown);
  34444. }
  34445. else
  34446. {
  34447. g.fillAll (getBackgroundColour());
  34448. const int textH = (style == ImageAboveTextLabel)
  34449. ? jmin (16, proportionOfHeight (0.25f))
  34450. : 0;
  34451. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34452. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34453. imageSpace.setBounds (indentX, indentY,
  34454. getWidth() - indentX * 2,
  34455. getHeight() - indentY * 2 - textH);
  34456. if (textH > 0)
  34457. {
  34458. g.setFont ((float) textH);
  34459. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34460. g.drawFittedText (getButtonText(),
  34461. 2, getHeight() - textH - 1,
  34462. getWidth() - 4, textH,
  34463. Justification::centred, 1);
  34464. }
  34465. }
  34466. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34467. g.setOpacity (1.0f);
  34468. const Drawable* imageToDraw = 0;
  34469. if (isEnabled())
  34470. {
  34471. imageToDraw = getCurrentImage();
  34472. }
  34473. else
  34474. {
  34475. imageToDraw = getToggleState() ? disabledImageOn
  34476. : disabledImage;
  34477. if (imageToDraw == 0)
  34478. {
  34479. g.setOpacity (0.4f);
  34480. imageToDraw = getNormalImage();
  34481. }
  34482. }
  34483. if (imageToDraw != 0)
  34484. {
  34485. if (style == ImageRaw)
  34486. {
  34487. imageToDraw->draw (g, 1.0f);
  34488. }
  34489. else
  34490. {
  34491. imageToDraw->drawWithin (g,
  34492. imageSpace.getX(),
  34493. imageSpace.getY(),
  34494. imageSpace.getWidth(),
  34495. imageSpace.getHeight(),
  34496. RectanglePlacement::centred,
  34497. 1.0f);
  34498. }
  34499. }
  34500. }
  34501. const Drawable* DrawableButton::getCurrentImage() const throw()
  34502. {
  34503. if (isDown())
  34504. return getDownImage();
  34505. if (isOver())
  34506. return getOverImage();
  34507. return getNormalImage();
  34508. }
  34509. const Drawable* DrawableButton::getNormalImage() const throw()
  34510. {
  34511. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34512. : normalImage;
  34513. }
  34514. const Drawable* DrawableButton::getOverImage() const throw()
  34515. {
  34516. const Drawable* d = normalImage;
  34517. if (getToggleState())
  34518. {
  34519. if (overImageOn != 0)
  34520. d = overImageOn;
  34521. else if (normalImageOn != 0)
  34522. d = normalImageOn;
  34523. else if (overImage != 0)
  34524. d = overImage;
  34525. }
  34526. else
  34527. {
  34528. if (overImage != 0)
  34529. d = overImage;
  34530. }
  34531. return d;
  34532. }
  34533. const Drawable* DrawableButton::getDownImage() const throw()
  34534. {
  34535. const Drawable* d = normalImage;
  34536. if (getToggleState())
  34537. {
  34538. if (downImageOn != 0)
  34539. d = downImageOn;
  34540. else if (overImageOn != 0)
  34541. d = overImageOn;
  34542. else if (normalImageOn != 0)
  34543. d = normalImageOn;
  34544. else if (downImage != 0)
  34545. d = downImage;
  34546. else
  34547. d = getOverImage();
  34548. }
  34549. else
  34550. {
  34551. if (downImage != 0)
  34552. d = downImage;
  34553. else
  34554. d = getOverImage();
  34555. }
  34556. return d;
  34557. }
  34558. END_JUCE_NAMESPACE
  34559. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34560. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34561. BEGIN_JUCE_NAMESPACE
  34562. HyperlinkButton::HyperlinkButton (const String& linkText,
  34563. const URL& linkURL)
  34564. : Button (linkText),
  34565. url (linkURL),
  34566. font (14.0f, Font::underlined),
  34567. resizeFont (true),
  34568. justification (Justification::centred)
  34569. {
  34570. setMouseCursor (MouseCursor::PointingHandCursor);
  34571. setTooltip (linkURL.toString (false));
  34572. }
  34573. HyperlinkButton::~HyperlinkButton()
  34574. {
  34575. }
  34576. void HyperlinkButton::setFont (const Font& newFont,
  34577. const bool resizeToMatchComponentHeight,
  34578. const Justification& justificationType)
  34579. {
  34580. font = newFont;
  34581. resizeFont = resizeToMatchComponentHeight;
  34582. justification = justificationType;
  34583. repaint();
  34584. }
  34585. void HyperlinkButton::setURL (const URL& newURL) throw()
  34586. {
  34587. url = newURL;
  34588. setTooltip (newURL.toString (false));
  34589. }
  34590. const Font HyperlinkButton::getFontToUse() const
  34591. {
  34592. Font f (font);
  34593. if (resizeFont)
  34594. f.setHeight (getHeight() * 0.7f);
  34595. return f;
  34596. }
  34597. void HyperlinkButton::changeWidthToFitText()
  34598. {
  34599. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34600. }
  34601. void HyperlinkButton::colourChanged()
  34602. {
  34603. repaint();
  34604. }
  34605. void HyperlinkButton::clicked()
  34606. {
  34607. if (url.isWellFormed())
  34608. url.launchInDefaultBrowser();
  34609. }
  34610. void HyperlinkButton::paintButton (Graphics& g,
  34611. bool isMouseOverButton,
  34612. bool isButtonDown)
  34613. {
  34614. const Colour textColour (findColour (textColourId));
  34615. if (isEnabled())
  34616. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34617. : textColour);
  34618. else
  34619. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34620. g.setFont (getFontToUse());
  34621. g.drawText (getButtonText(),
  34622. 2, 0, getWidth() - 2, getHeight(),
  34623. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34624. true);
  34625. }
  34626. END_JUCE_NAMESPACE
  34627. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34628. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34629. BEGIN_JUCE_NAMESPACE
  34630. ImageButton::ImageButton (const String& text_)
  34631. : Button (text_),
  34632. scaleImageToFit (true),
  34633. preserveProportions (true),
  34634. alphaThreshold (0),
  34635. imageX (0),
  34636. imageY (0),
  34637. imageW (0),
  34638. imageH (0),
  34639. normalImage (0),
  34640. overImage (0),
  34641. downImage (0)
  34642. {
  34643. }
  34644. ImageButton::~ImageButton()
  34645. {
  34646. }
  34647. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34648. const bool rescaleImagesWhenButtonSizeChanges,
  34649. const bool preserveImageProportions,
  34650. const Image& normalImage_,
  34651. const float imageOpacityWhenNormal,
  34652. const Colour& overlayColourWhenNormal,
  34653. const Image& overImage_,
  34654. const float imageOpacityWhenOver,
  34655. const Colour& overlayColourWhenOver,
  34656. const Image& downImage_,
  34657. const float imageOpacityWhenDown,
  34658. const Colour& overlayColourWhenDown,
  34659. const float hitTestAlphaThreshold)
  34660. {
  34661. normalImage = normalImage_;
  34662. overImage = overImage_;
  34663. downImage = downImage_;
  34664. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  34665. {
  34666. imageW = normalImage.getWidth();
  34667. imageH = normalImage.getHeight();
  34668. setSize (imageW, imageH);
  34669. }
  34670. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34671. preserveProportions = preserveImageProportions;
  34672. normalOpacity = imageOpacityWhenNormal;
  34673. normalOverlay = overlayColourWhenNormal;
  34674. overOpacity = imageOpacityWhenOver;
  34675. overOverlay = overlayColourWhenOver;
  34676. downOpacity = imageOpacityWhenDown;
  34677. downOverlay = overlayColourWhenDown;
  34678. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34679. repaint();
  34680. }
  34681. const Image ImageButton::getCurrentImage() const
  34682. {
  34683. if (isDown() || getToggleState())
  34684. return getDownImage();
  34685. if (isOver())
  34686. return getOverImage();
  34687. return getNormalImage();
  34688. }
  34689. const Image ImageButton::getNormalImage() const
  34690. {
  34691. return normalImage;
  34692. }
  34693. const Image ImageButton::getOverImage() const
  34694. {
  34695. return overImage.isValid() ? overImage
  34696. : normalImage;
  34697. }
  34698. const Image ImageButton::getDownImage() const
  34699. {
  34700. return downImage.isValid() ? downImage
  34701. : getOverImage();
  34702. }
  34703. void ImageButton::paintButton (Graphics& g,
  34704. bool isMouseOverButton,
  34705. bool isButtonDown)
  34706. {
  34707. if (! isEnabled())
  34708. {
  34709. isMouseOverButton = false;
  34710. isButtonDown = false;
  34711. }
  34712. Image im (getCurrentImage());
  34713. if (im.isValid())
  34714. {
  34715. const int iw = im.getWidth();
  34716. const int ih = im.getHeight();
  34717. imageW = getWidth();
  34718. imageH = getHeight();
  34719. imageX = (imageW - iw) >> 1;
  34720. imageY = (imageH - ih) >> 1;
  34721. if (scaleImageToFit)
  34722. {
  34723. if (preserveProportions)
  34724. {
  34725. int newW, newH;
  34726. const float imRatio = ih / (float)iw;
  34727. const float destRatio = imageH / (float)imageW;
  34728. if (imRatio > destRatio)
  34729. {
  34730. newW = roundToInt (imageH / imRatio);
  34731. newH = imageH;
  34732. }
  34733. else
  34734. {
  34735. newW = imageW;
  34736. newH = roundToInt (imageW * imRatio);
  34737. }
  34738. imageX = (imageW - newW) / 2;
  34739. imageY = (imageH - newH) / 2;
  34740. imageW = newW;
  34741. imageH = newH;
  34742. }
  34743. else
  34744. {
  34745. imageX = 0;
  34746. imageY = 0;
  34747. }
  34748. }
  34749. if (! scaleImageToFit)
  34750. {
  34751. imageW = iw;
  34752. imageH = ih;
  34753. }
  34754. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  34755. isButtonDown ? downOverlay
  34756. : (isMouseOverButton ? overOverlay
  34757. : normalOverlay),
  34758. isButtonDown ? downOpacity
  34759. : (isMouseOverButton ? overOpacity
  34760. : normalOpacity),
  34761. *this);
  34762. }
  34763. }
  34764. bool ImageButton::hitTest (int x, int y)
  34765. {
  34766. if (alphaThreshold == 0)
  34767. return true;
  34768. Image im (getCurrentImage());
  34769. return im.isNull() || (imageW > 0 && imageH > 0
  34770. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  34771. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  34772. }
  34773. END_JUCE_NAMESPACE
  34774. /*** End of inlined file: juce_ImageButton.cpp ***/
  34775. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34776. BEGIN_JUCE_NAMESPACE
  34777. ShapeButton::ShapeButton (const String& text_,
  34778. const Colour& normalColour_,
  34779. const Colour& overColour_,
  34780. const Colour& downColour_)
  34781. : Button (text_),
  34782. normalColour (normalColour_),
  34783. overColour (overColour_),
  34784. downColour (downColour_),
  34785. maintainShapeProportions (false),
  34786. outlineWidth (0.0f)
  34787. {
  34788. }
  34789. ShapeButton::~ShapeButton()
  34790. {
  34791. }
  34792. void ShapeButton::setColours (const Colour& newNormalColour,
  34793. const Colour& newOverColour,
  34794. const Colour& newDownColour)
  34795. {
  34796. normalColour = newNormalColour;
  34797. overColour = newOverColour;
  34798. downColour = newDownColour;
  34799. }
  34800. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34801. const float newOutlineWidth)
  34802. {
  34803. outlineColour = newOutlineColour;
  34804. outlineWidth = newOutlineWidth;
  34805. }
  34806. void ShapeButton::setShape (const Path& newShape,
  34807. const bool resizeNowToFitThisShape,
  34808. const bool maintainShapeProportions_,
  34809. const bool hasShadow)
  34810. {
  34811. shape = newShape;
  34812. maintainShapeProportions = maintainShapeProportions_;
  34813. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34814. setComponentEffect ((hasShadow) ? &shadow : 0);
  34815. if (resizeNowToFitThisShape)
  34816. {
  34817. Rectangle<float> bounds (shape.getBounds());
  34818. if (hasShadow)
  34819. bounds.expand (4.0f, 4.0f);
  34820. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  34821. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  34822. 1 + (int) (bounds.getHeight() + outlineWidth));
  34823. }
  34824. }
  34825. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34826. {
  34827. if (! isEnabled())
  34828. {
  34829. isMouseOverButton = false;
  34830. isButtonDown = false;
  34831. }
  34832. g.setColour ((isButtonDown) ? downColour
  34833. : (isMouseOverButton) ? overColour
  34834. : normalColour);
  34835. int w = getWidth();
  34836. int h = getHeight();
  34837. if (getComponentEffect() != 0)
  34838. {
  34839. w -= 4;
  34840. h -= 4;
  34841. }
  34842. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34843. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34844. w - offset - outlineWidth,
  34845. h - offset - outlineWidth,
  34846. maintainShapeProportions));
  34847. g.fillPath (shape, trans);
  34848. if (outlineWidth > 0.0f)
  34849. {
  34850. g.setColour (outlineColour);
  34851. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34852. }
  34853. }
  34854. END_JUCE_NAMESPACE
  34855. /*** End of inlined file: juce_ShapeButton.cpp ***/
  34856. /*** Start of inlined file: juce_TextButton.cpp ***/
  34857. BEGIN_JUCE_NAMESPACE
  34858. TextButton::TextButton (const String& name,
  34859. const String& toolTip)
  34860. : Button (name)
  34861. {
  34862. setTooltip (toolTip);
  34863. }
  34864. TextButton::~TextButton()
  34865. {
  34866. }
  34867. void TextButton::paintButton (Graphics& g,
  34868. bool isMouseOverButton,
  34869. bool isButtonDown)
  34870. {
  34871. getLookAndFeel().drawButtonBackground (g, *this,
  34872. findColour (getToggleState() ? buttonOnColourId
  34873. : buttonColourId),
  34874. isMouseOverButton,
  34875. isButtonDown);
  34876. getLookAndFeel().drawButtonText (g, *this,
  34877. isMouseOverButton,
  34878. isButtonDown);
  34879. }
  34880. void TextButton::colourChanged()
  34881. {
  34882. repaint();
  34883. }
  34884. const Font TextButton::getFont()
  34885. {
  34886. return Font (jmin (15.0f, getHeight() * 0.6f));
  34887. }
  34888. void TextButton::changeWidthToFitText (const int newHeight)
  34889. {
  34890. if (newHeight >= 0)
  34891. setSize (jmax (1, getWidth()), newHeight);
  34892. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34893. getHeight());
  34894. }
  34895. END_JUCE_NAMESPACE
  34896. /*** End of inlined file: juce_TextButton.cpp ***/
  34897. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  34898. BEGIN_JUCE_NAMESPACE
  34899. ToggleButton::ToggleButton (const String& buttonText)
  34900. : Button (buttonText)
  34901. {
  34902. setClickingTogglesState (true);
  34903. }
  34904. ToggleButton::~ToggleButton()
  34905. {
  34906. }
  34907. void ToggleButton::paintButton (Graphics& g,
  34908. bool isMouseOverButton,
  34909. bool isButtonDown)
  34910. {
  34911. getLookAndFeel().drawToggleButton (g, *this,
  34912. isMouseOverButton,
  34913. isButtonDown);
  34914. }
  34915. void ToggleButton::changeWidthToFitText()
  34916. {
  34917. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34918. }
  34919. void ToggleButton::colourChanged()
  34920. {
  34921. repaint();
  34922. }
  34923. END_JUCE_NAMESPACE
  34924. /*** End of inlined file: juce_ToggleButton.cpp ***/
  34925. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  34926. BEGIN_JUCE_NAMESPACE
  34927. ToolbarButton::ToolbarButton (const int itemId_,
  34928. const String& buttonText,
  34929. Drawable* const normalImage_,
  34930. Drawable* const toggledOnImage_)
  34931. : ToolbarItemComponent (itemId_, buttonText, true),
  34932. normalImage (normalImage_),
  34933. toggledOnImage (toggledOnImage_)
  34934. {
  34935. jassert (normalImage_ != 0);
  34936. }
  34937. ToolbarButton::~ToolbarButton()
  34938. {
  34939. }
  34940. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34941. bool /*isToolbarVertical*/,
  34942. int& preferredSize,
  34943. int& minSize, int& maxSize)
  34944. {
  34945. preferredSize = minSize = maxSize = toolbarDepth;
  34946. return true;
  34947. }
  34948. void ToolbarButton::paintButtonArea (Graphics& g,
  34949. int width, int height,
  34950. bool /*isMouseOver*/,
  34951. bool /*isMouseDown*/)
  34952. {
  34953. Drawable* d = normalImage;
  34954. if (getToggleState() && toggledOnImage != 0)
  34955. d = toggledOnImage;
  34956. if (! isEnabled())
  34957. {
  34958. Image im (Image::ARGB, width, height, true);
  34959. {
  34960. Graphics g2 (im);
  34961. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34962. }
  34963. im.desaturate();
  34964. g.drawImageAt (im, 0, 0);
  34965. }
  34966. else
  34967. {
  34968. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34969. }
  34970. }
  34971. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  34972. {
  34973. }
  34974. END_JUCE_NAMESPACE
  34975. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  34976. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  34977. BEGIN_JUCE_NAMESPACE
  34978. class CodeDocumentLine
  34979. {
  34980. public:
  34981. CodeDocumentLine (const juce_wchar* const line_,
  34982. const int lineLength_,
  34983. const int numNewLineChars,
  34984. const int lineStartInFile_)
  34985. : line (line_, lineLength_),
  34986. lineStartInFile (lineStartInFile_),
  34987. lineLength (lineLength_),
  34988. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  34989. {
  34990. }
  34991. ~CodeDocumentLine()
  34992. {
  34993. }
  34994. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  34995. {
  34996. const juce_wchar* const t = text;
  34997. int pos = 0;
  34998. while (t [pos] != 0)
  34999. {
  35000. const int startOfLine = pos;
  35001. int numNewLineChars = 0;
  35002. while (t[pos] != 0)
  35003. {
  35004. if (t[pos] == '\r')
  35005. {
  35006. ++numNewLineChars;
  35007. ++pos;
  35008. if (t[pos] == '\n')
  35009. {
  35010. ++numNewLineChars;
  35011. ++pos;
  35012. }
  35013. break;
  35014. }
  35015. if (t[pos] == '\n')
  35016. {
  35017. ++numNewLineChars;
  35018. ++pos;
  35019. break;
  35020. }
  35021. ++pos;
  35022. }
  35023. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35024. numNewLineChars, startOfLine));
  35025. }
  35026. jassert (pos == text.length());
  35027. }
  35028. bool endsWithLineBreak() const throw()
  35029. {
  35030. return lineLengthWithoutNewLines != lineLength;
  35031. }
  35032. void updateLength() throw()
  35033. {
  35034. lineLengthWithoutNewLines = lineLength = line.length();
  35035. while (lineLengthWithoutNewLines > 0
  35036. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35037. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35038. {
  35039. --lineLengthWithoutNewLines;
  35040. }
  35041. }
  35042. String line;
  35043. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35044. };
  35045. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35046. : document (document_),
  35047. currentLine (document_->lines[0]),
  35048. line (0),
  35049. position (0)
  35050. {
  35051. }
  35052. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35053. : document (other.document),
  35054. currentLine (other.currentLine),
  35055. line (other.line),
  35056. position (other.position)
  35057. {
  35058. }
  35059. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35060. {
  35061. document = other.document;
  35062. currentLine = other.currentLine;
  35063. line = other.line;
  35064. position = other.position;
  35065. return *this;
  35066. }
  35067. CodeDocument::Iterator::~Iterator() throw()
  35068. {
  35069. }
  35070. juce_wchar CodeDocument::Iterator::nextChar()
  35071. {
  35072. if (currentLine == 0)
  35073. return 0;
  35074. jassert (currentLine == document->lines.getUnchecked (line));
  35075. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35076. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35077. {
  35078. ++line;
  35079. currentLine = document->lines [line];
  35080. }
  35081. return result;
  35082. }
  35083. void CodeDocument::Iterator::skip()
  35084. {
  35085. if (currentLine != 0)
  35086. {
  35087. jassert (currentLine == document->lines.getUnchecked (line));
  35088. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35089. {
  35090. ++line;
  35091. currentLine = document->lines [line];
  35092. }
  35093. }
  35094. }
  35095. void CodeDocument::Iterator::skipToEndOfLine()
  35096. {
  35097. if (currentLine != 0)
  35098. {
  35099. jassert (currentLine == document->lines.getUnchecked (line));
  35100. ++line;
  35101. currentLine = document->lines [line];
  35102. if (currentLine != 0)
  35103. position = currentLine->lineStartInFile;
  35104. else
  35105. position = document->getNumCharacters();
  35106. }
  35107. }
  35108. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35109. {
  35110. if (currentLine == 0)
  35111. return 0;
  35112. jassert (currentLine == document->lines.getUnchecked (line));
  35113. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35114. }
  35115. void CodeDocument::Iterator::skipWhitespace()
  35116. {
  35117. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35118. skip();
  35119. }
  35120. bool CodeDocument::Iterator::isEOF() const throw()
  35121. {
  35122. return currentLine == 0;
  35123. }
  35124. CodeDocument::Position::Position() throw()
  35125. : owner (0), characterPos (0), line (0),
  35126. indexInLine (0), positionMaintained (false)
  35127. {
  35128. }
  35129. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35130. const int line_, const int indexInLine_) throw()
  35131. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35132. characterPos (0), line (line_),
  35133. indexInLine (indexInLine_), positionMaintained (false)
  35134. {
  35135. setLineAndIndex (line_, indexInLine_);
  35136. }
  35137. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35138. const int characterPos_) throw()
  35139. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35140. positionMaintained (false)
  35141. {
  35142. setPosition (characterPos_);
  35143. }
  35144. CodeDocument::Position::Position (const Position& other) throw()
  35145. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35146. indexInLine (other.indexInLine), positionMaintained (false)
  35147. {
  35148. jassert (*this == other);
  35149. }
  35150. CodeDocument::Position::~Position() throw()
  35151. {
  35152. setPositionMaintained (false);
  35153. }
  35154. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35155. {
  35156. if (this != &other)
  35157. {
  35158. const bool wasPositionMaintained = positionMaintained;
  35159. if (owner != other.owner)
  35160. setPositionMaintained (false);
  35161. owner = other.owner;
  35162. line = other.line;
  35163. indexInLine = other.indexInLine;
  35164. characterPos = other.characterPos;
  35165. setPositionMaintained (wasPositionMaintained);
  35166. jassert (*this == other);
  35167. }
  35168. return *this;
  35169. }
  35170. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35171. {
  35172. jassert ((characterPos == other.characterPos)
  35173. == (line == other.line && indexInLine == other.indexInLine));
  35174. return characterPos == other.characterPos
  35175. && line == other.line
  35176. && indexInLine == other.indexInLine
  35177. && owner == other.owner;
  35178. }
  35179. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35180. {
  35181. return ! operator== (other);
  35182. }
  35183. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35184. {
  35185. jassert (owner != 0);
  35186. if (owner->lines.size() == 0)
  35187. {
  35188. line = 0;
  35189. indexInLine = 0;
  35190. characterPos = 0;
  35191. }
  35192. else
  35193. {
  35194. if (newLine >= owner->lines.size())
  35195. {
  35196. line = owner->lines.size() - 1;
  35197. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35198. jassert (l != 0);
  35199. indexInLine = l->lineLengthWithoutNewLines;
  35200. characterPos = l->lineStartInFile + indexInLine;
  35201. }
  35202. else
  35203. {
  35204. line = jmax (0, newLine);
  35205. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35206. jassert (l != 0);
  35207. if (l->lineLengthWithoutNewLines > 0)
  35208. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35209. else
  35210. indexInLine = 0;
  35211. characterPos = l->lineStartInFile + indexInLine;
  35212. }
  35213. }
  35214. }
  35215. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35216. {
  35217. jassert (owner != 0);
  35218. line = 0;
  35219. indexInLine = 0;
  35220. characterPos = 0;
  35221. if (newPosition > 0)
  35222. {
  35223. int lineStart = 0;
  35224. int lineEnd = owner->lines.size();
  35225. for (;;)
  35226. {
  35227. if (lineEnd - lineStart < 4)
  35228. {
  35229. for (int i = lineStart; i < lineEnd; ++i)
  35230. {
  35231. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35232. int index = newPosition - l->lineStartInFile;
  35233. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35234. {
  35235. line = i;
  35236. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35237. characterPos = l->lineStartInFile + indexInLine;
  35238. }
  35239. }
  35240. break;
  35241. }
  35242. else
  35243. {
  35244. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35245. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35246. if (newPosition >= mid->lineStartInFile)
  35247. lineStart = midIndex;
  35248. else
  35249. lineEnd = midIndex;
  35250. }
  35251. }
  35252. }
  35253. }
  35254. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35255. {
  35256. jassert (owner != 0);
  35257. if (characterDelta == 1)
  35258. {
  35259. setPosition (getPosition());
  35260. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35261. if (line < owner->lines.size())
  35262. {
  35263. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35264. if (indexInLine + characterDelta < l->lineLength
  35265. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35266. ++characterDelta;
  35267. }
  35268. }
  35269. setPosition (characterPos + characterDelta);
  35270. }
  35271. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35272. {
  35273. CodeDocument::Position p (*this);
  35274. p.moveBy (characterDelta);
  35275. return p;
  35276. }
  35277. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35278. {
  35279. CodeDocument::Position p (*this);
  35280. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35281. return p;
  35282. }
  35283. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35284. {
  35285. const CodeDocumentLine* const l = owner->lines [line];
  35286. return l == 0 ? 0 : l->line [getIndexInLine()];
  35287. }
  35288. const String CodeDocument::Position::getLineText() const throw()
  35289. {
  35290. const CodeDocumentLine* const l = owner->lines [line];
  35291. return l == 0 ? String::empty : l->line;
  35292. }
  35293. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35294. {
  35295. if (isMaintained != positionMaintained)
  35296. {
  35297. positionMaintained = isMaintained;
  35298. if (owner != 0)
  35299. {
  35300. if (isMaintained)
  35301. {
  35302. jassert (! owner->positionsToMaintain.contains (this));
  35303. owner->positionsToMaintain.add (this);
  35304. }
  35305. else
  35306. {
  35307. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35308. jassert (owner->positionsToMaintain.contains (this));
  35309. owner->positionsToMaintain.removeValue (this);
  35310. }
  35311. }
  35312. }
  35313. }
  35314. CodeDocument::CodeDocument()
  35315. : undoManager (std::numeric_limits<int>::max(), 10000),
  35316. currentActionIndex (0),
  35317. indexOfSavedState (-1),
  35318. maximumLineLength (-1),
  35319. newLineChars ("\r\n")
  35320. {
  35321. }
  35322. CodeDocument::~CodeDocument()
  35323. {
  35324. }
  35325. const String CodeDocument::getAllContent() const throw()
  35326. {
  35327. return getTextBetween (Position (this, 0),
  35328. Position (this, lines.size(), 0));
  35329. }
  35330. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35331. {
  35332. if (end.getPosition() <= start.getPosition())
  35333. return String::empty;
  35334. const int startLine = start.getLineNumber();
  35335. const int endLine = end.getLineNumber();
  35336. if (startLine == endLine)
  35337. {
  35338. CodeDocumentLine* const line = lines [startLine];
  35339. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35340. }
  35341. String result;
  35342. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35343. String::Concatenator concatenator (result);
  35344. const int maxLine = jmin (lines.size() - 1, endLine);
  35345. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35346. {
  35347. const CodeDocumentLine* line = lines.getUnchecked(i);
  35348. int len = line->lineLength;
  35349. if (i == startLine)
  35350. {
  35351. const int index = start.getIndexInLine();
  35352. concatenator.append (line->line.substring (index, len));
  35353. }
  35354. else if (i == endLine)
  35355. {
  35356. len = end.getIndexInLine();
  35357. concatenator.append (line->line.substring (0, len));
  35358. }
  35359. else
  35360. {
  35361. concatenator.append (line->line);
  35362. }
  35363. }
  35364. return result;
  35365. }
  35366. int CodeDocument::getNumCharacters() const throw()
  35367. {
  35368. const CodeDocumentLine* const lastLine = lines.getLast();
  35369. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35370. }
  35371. const String CodeDocument::getLine (const int lineIndex) const throw()
  35372. {
  35373. const CodeDocumentLine* const line = lines [lineIndex];
  35374. return (line == 0) ? String::empty : line->line;
  35375. }
  35376. int CodeDocument::getMaximumLineLength() throw()
  35377. {
  35378. if (maximumLineLength < 0)
  35379. {
  35380. maximumLineLength = 0;
  35381. for (int i = lines.size(); --i >= 0;)
  35382. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35383. }
  35384. return maximumLineLength;
  35385. }
  35386. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35387. {
  35388. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35389. }
  35390. void CodeDocument::insertText (const Position& position, const String& text)
  35391. {
  35392. insert (text, position.getPosition(), true);
  35393. }
  35394. void CodeDocument::replaceAllContent (const String& newContent)
  35395. {
  35396. remove (0, getNumCharacters(), true);
  35397. insert (newContent, 0, true);
  35398. }
  35399. bool CodeDocument::loadFromStream (InputStream& stream)
  35400. {
  35401. replaceAllContent (stream.readEntireStreamAsString());
  35402. setSavePoint();
  35403. clearUndoHistory();
  35404. return true;
  35405. }
  35406. bool CodeDocument::writeToStream (OutputStream& stream)
  35407. {
  35408. for (int i = 0; i < lines.size(); ++i)
  35409. {
  35410. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35411. const char* utf8 = temp.toUTF8();
  35412. if (! stream.write (utf8, (int) strlen (utf8)))
  35413. return false;
  35414. }
  35415. return true;
  35416. }
  35417. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35418. {
  35419. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35420. newLineChars = newLine;
  35421. }
  35422. void CodeDocument::newTransaction()
  35423. {
  35424. undoManager.beginNewTransaction (String::empty);
  35425. }
  35426. void CodeDocument::undo()
  35427. {
  35428. newTransaction();
  35429. undoManager.undo();
  35430. }
  35431. void CodeDocument::redo()
  35432. {
  35433. undoManager.redo();
  35434. }
  35435. void CodeDocument::clearUndoHistory()
  35436. {
  35437. undoManager.clearUndoHistory();
  35438. }
  35439. void CodeDocument::setSavePoint() throw()
  35440. {
  35441. indexOfSavedState = currentActionIndex;
  35442. }
  35443. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35444. {
  35445. return currentActionIndex != indexOfSavedState;
  35446. }
  35447. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35448. {
  35449. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35450. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35451. }
  35452. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35453. {
  35454. Position p (position);
  35455. const int maxDistance = 256;
  35456. int i = 0;
  35457. while (i < maxDistance
  35458. && CharacterFunctions::isWhitespace (p.getCharacter())
  35459. && (i == 0 || (p.getCharacter() != '\n'
  35460. && p.getCharacter() != '\r')))
  35461. {
  35462. ++i;
  35463. p.moveBy (1);
  35464. }
  35465. if (i == 0)
  35466. {
  35467. const int type = getCodeCharacterCategory (p.getCharacter());
  35468. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35469. {
  35470. ++i;
  35471. p.moveBy (1);
  35472. }
  35473. while (i < maxDistance
  35474. && CharacterFunctions::isWhitespace (p.getCharacter())
  35475. && (i == 0 || (p.getCharacter() != '\n'
  35476. && p.getCharacter() != '\r')))
  35477. {
  35478. ++i;
  35479. p.moveBy (1);
  35480. }
  35481. }
  35482. return p;
  35483. }
  35484. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35485. {
  35486. Position p (position);
  35487. const int maxDistance = 256;
  35488. int i = 0;
  35489. bool stoppedAtLineStart = false;
  35490. while (i < maxDistance)
  35491. {
  35492. const juce_wchar c = p.movedBy (-1).getCharacter();
  35493. if (c == '\r' || c == '\n')
  35494. {
  35495. stoppedAtLineStart = true;
  35496. if (i > 0)
  35497. break;
  35498. }
  35499. if (! CharacterFunctions::isWhitespace (c))
  35500. break;
  35501. p.moveBy (-1);
  35502. ++i;
  35503. }
  35504. if (i < maxDistance && ! stoppedAtLineStart)
  35505. {
  35506. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35507. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35508. {
  35509. p.moveBy (-1);
  35510. ++i;
  35511. }
  35512. }
  35513. return p;
  35514. }
  35515. void CodeDocument::checkLastLineStatus()
  35516. {
  35517. while (lines.size() > 0
  35518. && lines.getLast()->lineLength == 0
  35519. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35520. {
  35521. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35522. lines.removeLast();
  35523. }
  35524. const CodeDocumentLine* const lastLine = lines.getLast();
  35525. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35526. {
  35527. // check that there's an empty line at the end if the preceding one ends in a newline..
  35528. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35529. }
  35530. }
  35531. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35532. {
  35533. listeners.add (listener);
  35534. }
  35535. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35536. {
  35537. listeners.remove (listener);
  35538. }
  35539. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35540. {
  35541. Position startPos (this, startLine, 0);
  35542. Position endPos (this, endLine, 0);
  35543. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35544. }
  35545. class CodeDocumentInsertAction : public UndoableAction
  35546. {
  35547. CodeDocument& owner;
  35548. const String text;
  35549. int insertPos;
  35550. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35551. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35552. public:
  35553. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35554. : owner (owner_),
  35555. text (text_),
  35556. insertPos (insertPos_)
  35557. {
  35558. }
  35559. ~CodeDocumentInsertAction() {}
  35560. bool perform()
  35561. {
  35562. owner.currentActionIndex++;
  35563. owner.insert (text, insertPos, false);
  35564. return true;
  35565. }
  35566. bool undo()
  35567. {
  35568. owner.currentActionIndex--;
  35569. owner.remove (insertPos, insertPos + text.length(), false);
  35570. return true;
  35571. }
  35572. int getSizeInUnits() { return text.length() + 32; }
  35573. };
  35574. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35575. {
  35576. if (text.isEmpty())
  35577. return;
  35578. if (undoable)
  35579. {
  35580. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35581. }
  35582. else
  35583. {
  35584. Position pos (this, insertPos);
  35585. const int firstAffectedLine = pos.getLineNumber();
  35586. int lastAffectedLine = firstAffectedLine + 1;
  35587. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35588. String textInsideOriginalLine (text);
  35589. if (firstLine != 0)
  35590. {
  35591. const int index = pos.getIndexInLine();
  35592. textInsideOriginalLine = firstLine->line.substring (0, index)
  35593. + textInsideOriginalLine
  35594. + firstLine->line.substring (index);
  35595. }
  35596. maximumLineLength = -1;
  35597. Array <CodeDocumentLine*> newLines;
  35598. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35599. jassert (newLines.size() > 0);
  35600. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35601. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35602. lines.set (firstAffectedLine, newFirstLine);
  35603. if (newLines.size() > 1)
  35604. {
  35605. for (int i = 1; i < newLines.size(); ++i)
  35606. {
  35607. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35608. lines.insert (firstAffectedLine + i, l);
  35609. }
  35610. lastAffectedLine = lines.size();
  35611. }
  35612. int i, lineStart = newFirstLine->lineStartInFile;
  35613. for (i = firstAffectedLine; i < lines.size(); ++i)
  35614. {
  35615. CodeDocumentLine* const l = lines.getUnchecked (i);
  35616. l->lineStartInFile = lineStart;
  35617. lineStart += l->lineLength;
  35618. }
  35619. checkLastLineStatus();
  35620. const int newTextLength = text.length();
  35621. for (i = 0; i < positionsToMaintain.size(); ++i)
  35622. {
  35623. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35624. if (p->getPosition() >= insertPos)
  35625. p->setPosition (p->getPosition() + newTextLength);
  35626. }
  35627. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35628. }
  35629. }
  35630. class CodeDocumentDeleteAction : public UndoableAction
  35631. {
  35632. CodeDocument& owner;
  35633. int startPos, endPos;
  35634. String removedText;
  35635. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35636. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35637. public:
  35638. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35639. : owner (owner_),
  35640. startPos (startPos_),
  35641. endPos (endPos_)
  35642. {
  35643. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35644. CodeDocument::Position (&owner, endPos));
  35645. }
  35646. ~CodeDocumentDeleteAction() {}
  35647. bool perform()
  35648. {
  35649. owner.currentActionIndex++;
  35650. owner.remove (startPos, endPos, false);
  35651. return true;
  35652. }
  35653. bool undo()
  35654. {
  35655. owner.currentActionIndex--;
  35656. owner.insert (removedText, startPos, false);
  35657. return true;
  35658. }
  35659. int getSizeInUnits() { return removedText.length() + 32; }
  35660. };
  35661. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35662. {
  35663. if (endPos <= startPos)
  35664. return;
  35665. if (undoable)
  35666. {
  35667. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35668. }
  35669. else
  35670. {
  35671. Position startPosition (this, startPos);
  35672. Position endPosition (this, endPos);
  35673. maximumLineLength = -1;
  35674. const int firstAffectedLine = startPosition.getLineNumber();
  35675. const int endLine = endPosition.getLineNumber();
  35676. int lastAffectedLine = firstAffectedLine + 1;
  35677. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35678. if (firstAffectedLine == endLine)
  35679. {
  35680. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35681. + firstLine->line.substring (endPosition.getIndexInLine());
  35682. firstLine->updateLength();
  35683. }
  35684. else
  35685. {
  35686. lastAffectedLine = lines.size();
  35687. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35688. jassert (lastLine != 0);
  35689. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35690. + lastLine->line.substring (endPosition.getIndexInLine());
  35691. firstLine->updateLength();
  35692. int numLinesToRemove = endLine - firstAffectedLine;
  35693. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35694. }
  35695. int i;
  35696. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35697. {
  35698. CodeDocumentLine* const l = lines.getUnchecked (i);
  35699. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35700. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35701. }
  35702. checkLastLineStatus();
  35703. const int totalChars = getNumCharacters();
  35704. for (i = 0; i < positionsToMaintain.size(); ++i)
  35705. {
  35706. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35707. if (p->getPosition() > startPosition.getPosition())
  35708. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35709. if (p->getPosition() > totalChars)
  35710. p->setPosition (totalChars);
  35711. }
  35712. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35713. }
  35714. }
  35715. END_JUCE_NAMESPACE
  35716. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35717. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35718. BEGIN_JUCE_NAMESPACE
  35719. class CodeEditorComponent::CaretComponent : public Component,
  35720. public Timer
  35721. {
  35722. public:
  35723. CaretComponent (CodeEditorComponent& owner_)
  35724. : owner (owner_)
  35725. {
  35726. setAlwaysOnTop (true);
  35727. setInterceptsMouseClicks (false, false);
  35728. }
  35729. ~CaretComponent()
  35730. {
  35731. }
  35732. void paint (Graphics& g)
  35733. {
  35734. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35735. }
  35736. void timerCallback()
  35737. {
  35738. setVisible (shouldBeShown() && ! isVisible());
  35739. }
  35740. void updatePosition()
  35741. {
  35742. startTimer (400);
  35743. setVisible (shouldBeShown());
  35744. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35745. }
  35746. private:
  35747. CodeEditorComponent& owner;
  35748. CaretComponent (const CaretComponent&);
  35749. CaretComponent& operator= (const CaretComponent&);
  35750. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35751. };
  35752. class CodeEditorComponent::CodeEditorLine
  35753. {
  35754. public:
  35755. CodeEditorLine() throw()
  35756. : highlightColumnStart (0), highlightColumnEnd (0)
  35757. {
  35758. }
  35759. ~CodeEditorLine() throw()
  35760. {
  35761. }
  35762. bool update (CodeDocument& document, int lineNum,
  35763. CodeDocument::Iterator& source,
  35764. CodeTokeniser* analyser, const int spacesPerTab,
  35765. const CodeDocument::Position& selectionStart,
  35766. const CodeDocument::Position& selectionEnd)
  35767. {
  35768. Array <SyntaxToken> newTokens;
  35769. newTokens.ensureStorageAllocated (8);
  35770. if (analyser == 0)
  35771. {
  35772. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35773. }
  35774. else if (lineNum < document.getNumLines())
  35775. {
  35776. const CodeDocument::Position pos (&document, lineNum, 0);
  35777. createTokens (pos.getPosition(), pos.getLineText(),
  35778. source, analyser, newTokens);
  35779. }
  35780. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35781. int newHighlightStart = 0;
  35782. int newHighlightEnd = 0;
  35783. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35784. {
  35785. const String line (document.getLine (lineNum));
  35786. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35787. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35788. line, spacesPerTab);
  35789. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35790. line, spacesPerTab);
  35791. }
  35792. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35793. {
  35794. highlightColumnStart = newHighlightStart;
  35795. highlightColumnEnd = newHighlightEnd;
  35796. }
  35797. else
  35798. {
  35799. if (tokens.size() == newTokens.size())
  35800. {
  35801. bool allTheSame = true;
  35802. for (int i = newTokens.size(); --i >= 0;)
  35803. {
  35804. if (tokens.getReference(i) != newTokens.getReference(i))
  35805. {
  35806. allTheSame = false;
  35807. break;
  35808. }
  35809. }
  35810. if (allTheSame)
  35811. return false;
  35812. }
  35813. }
  35814. tokens.swapWithArray (newTokens);
  35815. return true;
  35816. }
  35817. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35818. float x, const int y, const int baselineOffset, const int lineHeight,
  35819. const Colour& highlightColour) const throw()
  35820. {
  35821. if (highlightColumnStart < highlightColumnEnd)
  35822. {
  35823. g.setColour (highlightColour);
  35824. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  35825. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  35826. }
  35827. int lastType = std::numeric_limits<int>::min();
  35828. for (int i = 0; i < tokens.size(); ++i)
  35829. {
  35830. SyntaxToken& token = tokens.getReference(i);
  35831. if (lastType != token.tokenType)
  35832. {
  35833. lastType = token.tokenType;
  35834. g.setColour (owner.getColourForTokenType (lastType));
  35835. }
  35836. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  35837. if (i < tokens.size() - 1)
  35838. {
  35839. if (token.width < 0)
  35840. token.width = font.getStringWidthFloat (token.text);
  35841. x += token.width;
  35842. }
  35843. }
  35844. }
  35845. private:
  35846. struct SyntaxToken
  35847. {
  35848. String text;
  35849. int tokenType;
  35850. float width;
  35851. SyntaxToken (const String& text_, const int type) throw()
  35852. : text (text_), tokenType (type), width (-1.0f)
  35853. {
  35854. }
  35855. bool operator!= (const SyntaxToken& other) const throw()
  35856. {
  35857. return text != other.text || tokenType != other.tokenType;
  35858. }
  35859. };
  35860. Array <SyntaxToken> tokens;
  35861. int highlightColumnStart, highlightColumnEnd;
  35862. static void createTokens (int startPosition, const String& lineText,
  35863. CodeDocument::Iterator& source,
  35864. CodeTokeniser* analyser,
  35865. Array <SyntaxToken>& newTokens)
  35866. {
  35867. CodeDocument::Iterator lastIterator (source);
  35868. const int lineLength = lineText.length();
  35869. for (;;)
  35870. {
  35871. int tokenType = analyser->readNextToken (source);
  35872. int tokenStart = lastIterator.getPosition();
  35873. int tokenEnd = source.getPosition();
  35874. if (tokenEnd <= tokenStart)
  35875. break;
  35876. tokenEnd -= startPosition;
  35877. if (tokenEnd > 0)
  35878. {
  35879. tokenStart -= startPosition;
  35880. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  35881. tokenType));
  35882. if (tokenEnd >= lineLength)
  35883. break;
  35884. }
  35885. lastIterator = source;
  35886. }
  35887. source = lastIterator;
  35888. }
  35889. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  35890. {
  35891. int x = 0;
  35892. for (int i = 0; i < tokens.size(); ++i)
  35893. {
  35894. SyntaxToken& t = tokens.getReference(i);
  35895. for (;;)
  35896. {
  35897. int tabPos = t.text.indexOfChar ('\t');
  35898. if (tabPos < 0)
  35899. break;
  35900. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  35901. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  35902. }
  35903. x += t.text.length();
  35904. }
  35905. }
  35906. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  35907. {
  35908. jassert (index <= line.length());
  35909. int col = 0;
  35910. for (int i = 0; i < index; ++i)
  35911. {
  35912. if (line[i] != '\t')
  35913. ++col;
  35914. else
  35915. col += spacesPerTab - (col % spacesPerTab);
  35916. }
  35917. return col;
  35918. }
  35919. };
  35920. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  35921. CodeTokeniser* const codeTokeniser_)
  35922. : document (document_),
  35923. firstLineOnScreen (0),
  35924. gutter (5),
  35925. spacesPerTab (4),
  35926. lineHeight (0),
  35927. linesOnScreen (0),
  35928. columnsOnScreen (0),
  35929. scrollbarThickness (16),
  35930. columnToTryToMaintain (-1),
  35931. useSpacesForTabs (false),
  35932. xOffset (0),
  35933. codeTokeniser (codeTokeniser_)
  35934. {
  35935. caretPos = CodeDocument::Position (&document_, 0, 0);
  35936. caretPos.setPositionMaintained (true);
  35937. selectionStart = CodeDocument::Position (&document_, 0, 0);
  35938. selectionStart.setPositionMaintained (true);
  35939. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  35940. selectionEnd.setPositionMaintained (true);
  35941. setOpaque (true);
  35942. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  35943. setWantsKeyboardFocus (true);
  35944. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  35945. verticalScrollBar->setSingleStepSize (1.0);
  35946. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  35947. horizontalScrollBar->setSingleStepSize (1.0);
  35948. addAndMakeVisible (caret = new CaretComponent (*this));
  35949. Font f (12.0f);
  35950. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  35951. setFont (f);
  35952. resetToDefaultColours();
  35953. verticalScrollBar->addListener (this);
  35954. horizontalScrollBar->addListener (this);
  35955. document.addListener (this);
  35956. }
  35957. CodeEditorComponent::~CodeEditorComponent()
  35958. {
  35959. document.removeListener (this);
  35960. deleteAllChildren();
  35961. }
  35962. void CodeEditorComponent::loadContent (const String& newContent)
  35963. {
  35964. clearCachedIterators (0);
  35965. document.replaceAllContent (newContent);
  35966. document.clearUndoHistory();
  35967. document.setSavePoint();
  35968. caretPos.setPosition (0);
  35969. selectionStart.setPosition (0);
  35970. selectionEnd.setPosition (0);
  35971. scrollToLine (0);
  35972. }
  35973. bool CodeEditorComponent::isTextInputActive() const
  35974. {
  35975. return true;
  35976. }
  35977. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  35978. const CodeDocument::Position& affectedTextEnd)
  35979. {
  35980. clearCachedIterators (affectedTextStart.getLineNumber());
  35981. triggerAsyncUpdate();
  35982. caret->updatePosition();
  35983. columnToTryToMaintain = -1;
  35984. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  35985. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  35986. deselectAll();
  35987. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  35988. || caretPos.getPosition() < affectedTextStart.getPosition())
  35989. moveCaretTo (affectedTextStart, false);
  35990. updateScrollBars();
  35991. }
  35992. void CodeEditorComponent::resized()
  35993. {
  35994. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  35995. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  35996. lines.clear();
  35997. rebuildLineTokens();
  35998. caret->updatePosition();
  35999. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36000. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36001. updateScrollBars();
  36002. }
  36003. void CodeEditorComponent::paint (Graphics& g)
  36004. {
  36005. handleUpdateNowIfNeeded();
  36006. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36007. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36008. g.setFont (font);
  36009. const int baselineOffset = (int) font.getAscent();
  36010. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36011. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36012. const Rectangle<int> clip (g.getClipBounds());
  36013. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36014. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36015. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36016. {
  36017. lines.getUnchecked(j)->draw (*this, g, font,
  36018. (float) (gutter - xOffset * charWidth),
  36019. lineHeight * j, baselineOffset, lineHeight,
  36020. highlightColour);
  36021. }
  36022. }
  36023. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36024. {
  36025. if (scrollbarThickness != thickness)
  36026. {
  36027. scrollbarThickness = thickness;
  36028. resized();
  36029. }
  36030. }
  36031. void CodeEditorComponent::handleAsyncUpdate()
  36032. {
  36033. rebuildLineTokens();
  36034. }
  36035. void CodeEditorComponent::rebuildLineTokens()
  36036. {
  36037. cancelPendingUpdate();
  36038. const int numNeeded = linesOnScreen + 1;
  36039. int minLineToRepaint = numNeeded;
  36040. int maxLineToRepaint = 0;
  36041. if (numNeeded != lines.size())
  36042. {
  36043. lines.clear();
  36044. for (int i = numNeeded; --i >= 0;)
  36045. lines.add (new CodeEditorLine());
  36046. minLineToRepaint = 0;
  36047. maxLineToRepaint = numNeeded;
  36048. }
  36049. jassert (numNeeded == lines.size());
  36050. CodeDocument::Iterator source (&document);
  36051. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36052. for (int i = 0; i < numNeeded; ++i)
  36053. {
  36054. CodeEditorLine* const line = lines.getUnchecked(i);
  36055. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36056. selectionStart, selectionEnd))
  36057. {
  36058. minLineToRepaint = jmin (minLineToRepaint, i);
  36059. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36060. }
  36061. }
  36062. if (minLineToRepaint <= maxLineToRepaint)
  36063. {
  36064. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36065. verticalScrollBar->getX() - gutter,
  36066. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36067. }
  36068. }
  36069. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36070. {
  36071. caretPos = newPos;
  36072. columnToTryToMaintain = -1;
  36073. if (highlighting)
  36074. {
  36075. if (dragType == notDragging)
  36076. {
  36077. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36078. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36079. dragType = draggingSelectionStart;
  36080. else
  36081. dragType = draggingSelectionEnd;
  36082. }
  36083. if (dragType == draggingSelectionStart)
  36084. {
  36085. selectionStart = caretPos;
  36086. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36087. {
  36088. const CodeDocument::Position temp (selectionStart);
  36089. selectionStart = selectionEnd;
  36090. selectionEnd = temp;
  36091. dragType = draggingSelectionEnd;
  36092. }
  36093. }
  36094. else
  36095. {
  36096. selectionEnd = caretPos;
  36097. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36098. {
  36099. const CodeDocument::Position temp (selectionStart);
  36100. selectionStart = selectionEnd;
  36101. selectionEnd = temp;
  36102. dragType = draggingSelectionStart;
  36103. }
  36104. }
  36105. triggerAsyncUpdate();
  36106. }
  36107. else
  36108. {
  36109. deselectAll();
  36110. }
  36111. caret->updatePosition();
  36112. scrollToKeepCaretOnScreen();
  36113. updateScrollBars();
  36114. }
  36115. void CodeEditorComponent::deselectAll()
  36116. {
  36117. if (selectionStart != selectionEnd)
  36118. triggerAsyncUpdate();
  36119. selectionStart = caretPos;
  36120. selectionEnd = caretPos;
  36121. }
  36122. void CodeEditorComponent::updateScrollBars()
  36123. {
  36124. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36125. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36126. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36127. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36128. }
  36129. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36130. {
  36131. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36132. newFirstLineOnScreen);
  36133. if (newFirstLineOnScreen != firstLineOnScreen)
  36134. {
  36135. firstLineOnScreen = newFirstLineOnScreen;
  36136. caret->updatePosition();
  36137. updateCachedIterators (firstLineOnScreen);
  36138. triggerAsyncUpdate();
  36139. }
  36140. }
  36141. void CodeEditorComponent::scrollToColumnInternal (double column)
  36142. {
  36143. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36144. if (xOffset != newOffset)
  36145. {
  36146. xOffset = newOffset;
  36147. caret->updatePosition();
  36148. repaint();
  36149. }
  36150. }
  36151. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36152. {
  36153. scrollToLineInternal (newFirstLineOnScreen);
  36154. updateScrollBars();
  36155. }
  36156. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36157. {
  36158. scrollToColumnInternal (newFirstColumnOnScreen);
  36159. updateScrollBars();
  36160. }
  36161. void CodeEditorComponent::scrollBy (int deltaLines)
  36162. {
  36163. scrollToLine (firstLineOnScreen + deltaLines);
  36164. }
  36165. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36166. {
  36167. if (caretPos.getLineNumber() < firstLineOnScreen)
  36168. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36169. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36170. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36171. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36172. if (column >= xOffset + columnsOnScreen - 1)
  36173. scrollToColumn (column + 1 - columnsOnScreen);
  36174. else if (column < xOffset)
  36175. scrollToColumn (column);
  36176. }
  36177. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36178. {
  36179. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36180. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36181. roundToInt (charWidth),
  36182. lineHeight);
  36183. }
  36184. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36185. {
  36186. const int line = y / lineHeight + firstLineOnScreen;
  36187. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36188. const int index = columnToIndex (line, column);
  36189. return CodeDocument::Position (&document, line, index);
  36190. }
  36191. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36192. {
  36193. document.deleteSection (selectionStart, selectionEnd);
  36194. if (newText.isNotEmpty())
  36195. document.insertText (caretPos, newText);
  36196. scrollToKeepCaretOnScreen();
  36197. }
  36198. void CodeEditorComponent::insertTabAtCaret()
  36199. {
  36200. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36201. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36202. {
  36203. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36204. }
  36205. if (useSpacesForTabs)
  36206. {
  36207. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36208. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36209. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36210. }
  36211. else
  36212. {
  36213. insertTextAtCaret ("\t");
  36214. }
  36215. }
  36216. void CodeEditorComponent::cut()
  36217. {
  36218. insertTextAtCaret (String::empty);
  36219. }
  36220. void CodeEditorComponent::copy()
  36221. {
  36222. newTransaction();
  36223. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36224. if (selection.isNotEmpty())
  36225. SystemClipboard::copyTextToClipboard (selection);
  36226. }
  36227. void CodeEditorComponent::copyThenCut()
  36228. {
  36229. copy();
  36230. cut();
  36231. newTransaction();
  36232. }
  36233. void CodeEditorComponent::paste()
  36234. {
  36235. newTransaction();
  36236. const String clip (SystemClipboard::getTextFromClipboard());
  36237. if (clip.isNotEmpty())
  36238. insertTextAtCaret (clip);
  36239. newTransaction();
  36240. }
  36241. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36242. {
  36243. newTransaction();
  36244. if (moveInWholeWordSteps)
  36245. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36246. else
  36247. moveCaretTo (caretPos.movedBy (-1), selecting);
  36248. }
  36249. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36250. {
  36251. newTransaction();
  36252. if (moveInWholeWordSteps)
  36253. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36254. else
  36255. moveCaretTo (caretPos.movedBy (1), selecting);
  36256. }
  36257. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36258. {
  36259. CodeDocument::Position pos (caretPos);
  36260. const int newLineNum = pos.getLineNumber() + delta;
  36261. if (columnToTryToMaintain < 0)
  36262. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36263. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36264. const int colToMaintain = columnToTryToMaintain;
  36265. moveCaretTo (pos, selecting);
  36266. columnToTryToMaintain = colToMaintain;
  36267. }
  36268. void CodeEditorComponent::cursorDown (const bool selecting)
  36269. {
  36270. newTransaction();
  36271. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36272. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36273. else
  36274. moveLineDelta (1, selecting);
  36275. }
  36276. void CodeEditorComponent::cursorUp (const bool selecting)
  36277. {
  36278. newTransaction();
  36279. if (caretPos.getLineNumber() == 0)
  36280. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36281. else
  36282. moveLineDelta (-1, selecting);
  36283. }
  36284. void CodeEditorComponent::pageDown (const bool selecting)
  36285. {
  36286. newTransaction();
  36287. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36288. moveLineDelta (linesOnScreen, selecting);
  36289. }
  36290. void CodeEditorComponent::pageUp (const bool selecting)
  36291. {
  36292. newTransaction();
  36293. scrollBy (-linesOnScreen);
  36294. moveLineDelta (-linesOnScreen, selecting);
  36295. }
  36296. void CodeEditorComponent::scrollUp()
  36297. {
  36298. newTransaction();
  36299. scrollBy (1);
  36300. if (caretPos.getLineNumber() < firstLineOnScreen)
  36301. moveLineDelta (1, false);
  36302. }
  36303. void CodeEditorComponent::scrollDown()
  36304. {
  36305. newTransaction();
  36306. scrollBy (-1);
  36307. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36308. moveLineDelta (-1, false);
  36309. }
  36310. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36311. {
  36312. newTransaction();
  36313. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36314. }
  36315. static int findFirstNonWhitespaceChar (const String& line) throw()
  36316. {
  36317. const int len = line.length();
  36318. for (int i = 0; i < len; ++i)
  36319. if (! CharacterFunctions::isWhitespace (line [i]))
  36320. return i;
  36321. return 0;
  36322. }
  36323. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36324. {
  36325. newTransaction();
  36326. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36327. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36328. index = 0;
  36329. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36330. }
  36331. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36332. {
  36333. newTransaction();
  36334. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36335. }
  36336. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36337. {
  36338. newTransaction();
  36339. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36340. }
  36341. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36342. {
  36343. if (moveInWholeWordSteps)
  36344. {
  36345. cut(); // in case something is already highlighted
  36346. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36347. }
  36348. else
  36349. {
  36350. if (selectionStart == selectionEnd)
  36351. selectionStart.moveBy (-1);
  36352. }
  36353. cut();
  36354. }
  36355. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36356. {
  36357. if (moveInWholeWordSteps)
  36358. {
  36359. cut(); // in case something is already highlighted
  36360. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36361. }
  36362. else
  36363. {
  36364. if (selectionStart == selectionEnd)
  36365. selectionEnd.moveBy (1);
  36366. else
  36367. newTransaction();
  36368. }
  36369. cut();
  36370. }
  36371. void CodeEditorComponent::selectAll()
  36372. {
  36373. newTransaction();
  36374. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36375. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36376. }
  36377. void CodeEditorComponent::undo()
  36378. {
  36379. document.undo();
  36380. scrollToKeepCaretOnScreen();
  36381. }
  36382. void CodeEditorComponent::redo()
  36383. {
  36384. document.redo();
  36385. scrollToKeepCaretOnScreen();
  36386. }
  36387. void CodeEditorComponent::newTransaction()
  36388. {
  36389. document.newTransaction();
  36390. startTimer (600);
  36391. }
  36392. void CodeEditorComponent::timerCallback()
  36393. {
  36394. newTransaction();
  36395. }
  36396. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36397. {
  36398. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36399. }
  36400. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36401. {
  36402. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36403. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36404. }
  36405. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36406. {
  36407. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36408. CodeDocument::Position (&document, range.getEnd()));
  36409. }
  36410. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36411. {
  36412. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36413. const bool shiftDown = key.getModifiers().isShiftDown();
  36414. if (key.isKeyCode (KeyPress::leftKey))
  36415. {
  36416. cursorLeft (moveInWholeWordSteps, shiftDown);
  36417. }
  36418. else if (key.isKeyCode (KeyPress::rightKey))
  36419. {
  36420. cursorRight (moveInWholeWordSteps, shiftDown);
  36421. }
  36422. else if (key.isKeyCode (KeyPress::upKey))
  36423. {
  36424. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36425. scrollDown();
  36426. #if JUCE_MAC
  36427. else if (key.getModifiers().isCommandDown())
  36428. goToStartOfDocument (shiftDown);
  36429. #endif
  36430. else
  36431. cursorUp (shiftDown);
  36432. }
  36433. else if (key.isKeyCode (KeyPress::downKey))
  36434. {
  36435. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36436. scrollUp();
  36437. #if JUCE_MAC
  36438. else if (key.getModifiers().isCommandDown())
  36439. goToEndOfDocument (shiftDown);
  36440. #endif
  36441. else
  36442. cursorDown (shiftDown);
  36443. }
  36444. else if (key.isKeyCode (KeyPress::pageDownKey))
  36445. {
  36446. pageDown (shiftDown);
  36447. }
  36448. else if (key.isKeyCode (KeyPress::pageUpKey))
  36449. {
  36450. pageUp (shiftDown);
  36451. }
  36452. else if (key.isKeyCode (KeyPress::homeKey))
  36453. {
  36454. if (moveInWholeWordSteps)
  36455. goToStartOfDocument (shiftDown);
  36456. else
  36457. goToStartOfLine (shiftDown);
  36458. }
  36459. else if (key.isKeyCode (KeyPress::endKey))
  36460. {
  36461. if (moveInWholeWordSteps)
  36462. goToEndOfDocument (shiftDown);
  36463. else
  36464. goToEndOfLine (shiftDown);
  36465. }
  36466. else if (key.isKeyCode (KeyPress::backspaceKey))
  36467. {
  36468. backspace (moveInWholeWordSteps);
  36469. }
  36470. else if (key.isKeyCode (KeyPress::deleteKey))
  36471. {
  36472. deleteForward (moveInWholeWordSteps);
  36473. }
  36474. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36475. {
  36476. copy();
  36477. }
  36478. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36479. {
  36480. copyThenCut();
  36481. }
  36482. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36483. {
  36484. paste();
  36485. }
  36486. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36487. {
  36488. undo();
  36489. }
  36490. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36491. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36492. {
  36493. redo();
  36494. }
  36495. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36496. {
  36497. selectAll();
  36498. }
  36499. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36500. {
  36501. insertTabAtCaret();
  36502. }
  36503. else if (key == KeyPress::returnKey)
  36504. {
  36505. newTransaction();
  36506. insertTextAtCaret (document.getNewLineCharacters());
  36507. }
  36508. else if (key.isKeyCode (KeyPress::escapeKey))
  36509. {
  36510. newTransaction();
  36511. }
  36512. else if (key.getTextCharacter() >= ' ')
  36513. {
  36514. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36515. }
  36516. else
  36517. {
  36518. return false;
  36519. }
  36520. return true;
  36521. }
  36522. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36523. {
  36524. newTransaction();
  36525. dragType = notDragging;
  36526. if (! e.mods.isPopupMenu())
  36527. {
  36528. beginDragAutoRepeat (100);
  36529. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36530. }
  36531. else
  36532. {
  36533. /*PopupMenu m;
  36534. addPopupMenuItems (m, &e);
  36535. const int result = m.show();
  36536. if (result != 0)
  36537. performPopupMenuAction (result);
  36538. */
  36539. }
  36540. }
  36541. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36542. {
  36543. if (! e.mods.isPopupMenu())
  36544. moveCaretTo (getPositionAt (e.x, e.y), true);
  36545. }
  36546. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36547. {
  36548. newTransaction();
  36549. beginDragAutoRepeat (0);
  36550. dragType = notDragging;
  36551. }
  36552. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36553. {
  36554. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36555. CodeDocument::Position tokenEnd (tokenStart);
  36556. if (e.getNumberOfClicks() > 2)
  36557. {
  36558. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36559. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36560. }
  36561. else
  36562. {
  36563. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36564. tokenEnd.moveBy (1);
  36565. tokenStart = tokenEnd;
  36566. while (tokenStart.getIndexInLine() > 0
  36567. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36568. tokenStart.moveBy (-1);
  36569. }
  36570. moveCaretTo (tokenEnd, false);
  36571. moveCaretTo (tokenStart, true);
  36572. }
  36573. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36574. {
  36575. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36576. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36577. {
  36578. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36579. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36580. }
  36581. else
  36582. {
  36583. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36584. }
  36585. }
  36586. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36587. {
  36588. if (scrollBarThatHasMoved == verticalScrollBar)
  36589. scrollToLineInternal ((int) newRangeStart);
  36590. else
  36591. scrollToColumnInternal (newRangeStart);
  36592. }
  36593. void CodeEditorComponent::focusGained (FocusChangeType)
  36594. {
  36595. caret->updatePosition();
  36596. }
  36597. void CodeEditorComponent::focusLost (FocusChangeType)
  36598. {
  36599. caret->updatePosition();
  36600. }
  36601. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36602. {
  36603. useSpacesForTabs = insertSpaces;
  36604. if (spacesPerTab != numSpaces)
  36605. {
  36606. spacesPerTab = numSpaces;
  36607. triggerAsyncUpdate();
  36608. }
  36609. }
  36610. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36611. {
  36612. const String line (document.getLine (lineNum));
  36613. jassert (index <= line.length());
  36614. int col = 0;
  36615. for (int i = 0; i < index; ++i)
  36616. {
  36617. if (line[i] != '\t')
  36618. ++col;
  36619. else
  36620. col += getTabSize() - (col % getTabSize());
  36621. }
  36622. return col;
  36623. }
  36624. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36625. {
  36626. const String line (document.getLine (lineNum));
  36627. const int lineLength = line.length();
  36628. int i, col = 0;
  36629. for (i = 0; i < lineLength; ++i)
  36630. {
  36631. if (line[i] != '\t')
  36632. ++col;
  36633. else
  36634. col += getTabSize() - (col % getTabSize());
  36635. if (col > column)
  36636. break;
  36637. }
  36638. return i;
  36639. }
  36640. void CodeEditorComponent::setFont (const Font& newFont)
  36641. {
  36642. font = newFont;
  36643. charWidth = font.getStringWidthFloat ("0");
  36644. lineHeight = roundToInt (font.getHeight());
  36645. resized();
  36646. }
  36647. void CodeEditorComponent::resetToDefaultColours()
  36648. {
  36649. coloursForTokenCategories.clear();
  36650. if (codeTokeniser != 0)
  36651. {
  36652. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36653. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36654. }
  36655. }
  36656. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36657. {
  36658. jassert (tokenType < 256);
  36659. while (coloursForTokenCategories.size() < tokenType)
  36660. coloursForTokenCategories.add (Colours::black);
  36661. coloursForTokenCategories.set (tokenType, colour);
  36662. repaint();
  36663. }
  36664. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36665. {
  36666. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36667. return findColour (CodeEditorComponent::defaultTextColourId);
  36668. return coloursForTokenCategories.getReference (tokenType);
  36669. }
  36670. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36671. {
  36672. int i;
  36673. for (i = cachedIterators.size(); --i >= 0;)
  36674. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36675. break;
  36676. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36677. }
  36678. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36679. {
  36680. const int maxNumCachedPositions = 5000;
  36681. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36682. if (cachedIterators.size() == 0)
  36683. cachedIterators.add (new CodeDocument::Iterator (&document));
  36684. if (codeTokeniser == 0)
  36685. return;
  36686. for (;;)
  36687. {
  36688. CodeDocument::Iterator* last = cachedIterators.getLast();
  36689. if (last->getLine() >= maxLineNum)
  36690. break;
  36691. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36692. cachedIterators.add (t);
  36693. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36694. for (;;)
  36695. {
  36696. codeTokeniser->readNextToken (*t);
  36697. if (t->getLine() >= targetLine)
  36698. break;
  36699. if (t->isEOF())
  36700. return;
  36701. }
  36702. }
  36703. }
  36704. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36705. {
  36706. if (codeTokeniser == 0)
  36707. return;
  36708. for (int i = cachedIterators.size(); --i >= 0;)
  36709. {
  36710. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36711. if (t->getPosition() <= position)
  36712. {
  36713. source = *t;
  36714. break;
  36715. }
  36716. }
  36717. while (source.getPosition() < position)
  36718. {
  36719. const CodeDocument::Iterator original (source);
  36720. codeTokeniser->readNextToken (source);
  36721. if (source.getPosition() > position || source.isEOF())
  36722. {
  36723. source = original;
  36724. break;
  36725. }
  36726. }
  36727. }
  36728. END_JUCE_NAMESPACE
  36729. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36730. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36731. BEGIN_JUCE_NAMESPACE
  36732. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36733. {
  36734. }
  36735. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36736. {
  36737. }
  36738. namespace CppTokeniser
  36739. {
  36740. static bool isIdentifierStart (const juce_wchar c) throw()
  36741. {
  36742. return CharacterFunctions::isLetter (c)
  36743. || c == '_' || c == '@';
  36744. }
  36745. static bool isIdentifierBody (const juce_wchar c) throw()
  36746. {
  36747. return CharacterFunctions::isLetterOrDigit (c)
  36748. || c == '_' || c == '@';
  36749. }
  36750. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  36751. {
  36752. static const juce_wchar* const keywords2Char[] =
  36753. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  36754. static const juce_wchar* const keywords3Char[] =
  36755. { JUCE_T("for"), JUCE_T("int"), JUCE_T("new"), JUCE_T("try"), JUCE_T("xor"), JUCE_T("and"), JUCE_T("asm"), JUCE_T("not"), 0 };
  36756. static const juce_wchar* const keywords4Char[] =
  36757. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  36758. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  36759. static const juce_wchar* const keywords5Char[] =
  36760. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  36761. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  36762. static const juce_wchar* const keywords6Char[] =
  36763. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  36764. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  36765. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  36766. static const juce_wchar* const keywordsOther[] =
  36767. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  36768. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  36769. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  36770. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  36771. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  36772. const juce_wchar* const* k;
  36773. switch (tokenLength)
  36774. {
  36775. case 2: k = keywords2Char; break;
  36776. case 3: k = keywords3Char; break;
  36777. case 4: k = keywords4Char; break;
  36778. case 5: k = keywords5Char; break;
  36779. case 6: k = keywords6Char; break;
  36780. default:
  36781. if (tokenLength < 2 || tokenLength > 16)
  36782. return false;
  36783. k = keywordsOther;
  36784. break;
  36785. }
  36786. int i = 0;
  36787. while (k[i] != 0)
  36788. {
  36789. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  36790. return true;
  36791. ++i;
  36792. }
  36793. return false;
  36794. }
  36795. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36796. {
  36797. int tokenLength = 0;
  36798. juce_wchar possibleIdentifier [19];
  36799. while (isIdentifierBody (source.peekNextChar()))
  36800. {
  36801. const juce_wchar c = source.nextChar();
  36802. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36803. possibleIdentifier [tokenLength] = c;
  36804. ++tokenLength;
  36805. }
  36806. if (tokenLength > 1 && tokenLength <= 16)
  36807. {
  36808. possibleIdentifier [tokenLength] = 0;
  36809. if (isReservedKeyword (possibleIdentifier, tokenLength))
  36810. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36811. }
  36812. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36813. }
  36814. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36815. {
  36816. const juce_wchar c = source.peekNextChar();
  36817. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36818. source.skip();
  36819. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36820. return false;
  36821. return true;
  36822. }
  36823. static bool isHexDigit (const juce_wchar c) throw()
  36824. {
  36825. return (c >= '0' && c <= '9')
  36826. || (c >= 'a' && c <= 'f')
  36827. || (c >= 'A' && c <= 'F');
  36828. }
  36829. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  36830. {
  36831. if (source.nextChar() != '0')
  36832. return false;
  36833. juce_wchar c = source.nextChar();
  36834. if (c != 'x' && c != 'X')
  36835. return false;
  36836. int numDigits = 0;
  36837. while (isHexDigit (source.peekNextChar()))
  36838. {
  36839. ++numDigits;
  36840. source.skip();
  36841. }
  36842. if (numDigits == 0)
  36843. return false;
  36844. return skipNumberSuffix (source);
  36845. }
  36846. static bool isOctalDigit (const juce_wchar c) throw()
  36847. {
  36848. return c >= '0' && c <= '7';
  36849. }
  36850. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  36851. {
  36852. if (source.nextChar() != '0')
  36853. return false;
  36854. if (! isOctalDigit (source.nextChar()))
  36855. return false;
  36856. while (isOctalDigit (source.peekNextChar()))
  36857. source.skip();
  36858. return skipNumberSuffix (source);
  36859. }
  36860. static bool isDecimalDigit (const juce_wchar c) throw()
  36861. {
  36862. return c >= '0' && c <= '9';
  36863. }
  36864. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  36865. {
  36866. int numChars = 0;
  36867. while (isDecimalDigit (source.peekNextChar()))
  36868. {
  36869. ++numChars;
  36870. source.skip();
  36871. }
  36872. if (numChars == 0)
  36873. return false;
  36874. return skipNumberSuffix (source);
  36875. }
  36876. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  36877. {
  36878. int numDigits = 0;
  36879. while (isDecimalDigit (source.peekNextChar()))
  36880. {
  36881. source.skip();
  36882. ++numDigits;
  36883. }
  36884. const bool hasPoint = (source.peekNextChar() == '.');
  36885. if (hasPoint)
  36886. {
  36887. source.skip();
  36888. while (isDecimalDigit (source.peekNextChar()))
  36889. {
  36890. source.skip();
  36891. ++numDigits;
  36892. }
  36893. }
  36894. if (numDigits == 0)
  36895. return false;
  36896. juce_wchar c = source.peekNextChar();
  36897. const bool hasExponent = (c == 'e' || c == 'E');
  36898. if (hasExponent)
  36899. {
  36900. source.skip();
  36901. c = source.peekNextChar();
  36902. if (c == '+' || c == '-')
  36903. source.skip();
  36904. int numExpDigits = 0;
  36905. while (isDecimalDigit (source.peekNextChar()))
  36906. {
  36907. source.skip();
  36908. ++numExpDigits;
  36909. }
  36910. if (numExpDigits == 0)
  36911. return false;
  36912. }
  36913. c = source.peekNextChar();
  36914. if (c == 'f' || c == 'F')
  36915. source.skip();
  36916. else if (! (hasExponent || hasPoint))
  36917. return false;
  36918. return true;
  36919. }
  36920. static int parseNumber (CodeDocument::Iterator& source)
  36921. {
  36922. const CodeDocument::Iterator original (source);
  36923. if (parseFloatLiteral (source))
  36924. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  36925. source = original;
  36926. if (parseHexLiteral (source))
  36927. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36928. source = original;
  36929. if (parseOctalLiteral (source))
  36930. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36931. source = original;
  36932. if (parseDecimalLiteral (source))
  36933. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36934. source = original;
  36935. source.skip();
  36936. return CPlusPlusCodeTokeniser::tokenType_error;
  36937. }
  36938. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  36939. {
  36940. const juce_wchar quote = source.nextChar();
  36941. for (;;)
  36942. {
  36943. const juce_wchar c = source.nextChar();
  36944. if (c == quote || c == 0)
  36945. break;
  36946. if (c == '\\')
  36947. source.skip();
  36948. }
  36949. }
  36950. static void skipComment (CodeDocument::Iterator& source) throw()
  36951. {
  36952. bool lastWasStar = false;
  36953. for (;;)
  36954. {
  36955. const juce_wchar c = source.nextChar();
  36956. if (c == 0 || (c == '/' && lastWasStar))
  36957. break;
  36958. lastWasStar = (c == '*');
  36959. }
  36960. }
  36961. }
  36962. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  36963. {
  36964. int result = tokenType_error;
  36965. source.skipWhitespace();
  36966. juce_wchar firstChar = source.peekNextChar();
  36967. switch (firstChar)
  36968. {
  36969. case 0:
  36970. source.skip();
  36971. break;
  36972. case '0':
  36973. case '1':
  36974. case '2':
  36975. case '3':
  36976. case '4':
  36977. case '5':
  36978. case '6':
  36979. case '7':
  36980. case '8':
  36981. case '9':
  36982. result = CppTokeniser::parseNumber (source);
  36983. break;
  36984. case '.':
  36985. result = CppTokeniser::parseNumber (source);
  36986. if (result == tokenType_error)
  36987. result = tokenType_punctuation;
  36988. break;
  36989. case ',':
  36990. case ';':
  36991. case ':':
  36992. source.skip();
  36993. result = tokenType_punctuation;
  36994. break;
  36995. case '(':
  36996. case ')':
  36997. case '{':
  36998. case '}':
  36999. case '[':
  37000. case ']':
  37001. source.skip();
  37002. result = tokenType_bracket;
  37003. break;
  37004. case '"':
  37005. case '\'':
  37006. CppTokeniser::skipQuotedString (source);
  37007. result = tokenType_stringLiteral;
  37008. break;
  37009. case '+':
  37010. result = tokenType_operator;
  37011. source.skip();
  37012. if (source.peekNextChar() == '+')
  37013. source.skip();
  37014. else if (source.peekNextChar() == '=')
  37015. source.skip();
  37016. break;
  37017. case '-':
  37018. source.skip();
  37019. result = CppTokeniser::parseNumber (source);
  37020. if (result == tokenType_error)
  37021. {
  37022. result = tokenType_operator;
  37023. if (source.peekNextChar() == '-')
  37024. source.skip();
  37025. else if (source.peekNextChar() == '=')
  37026. source.skip();
  37027. }
  37028. break;
  37029. case '*':
  37030. case '%':
  37031. case '=':
  37032. case '!':
  37033. result = tokenType_operator;
  37034. source.skip();
  37035. if (source.peekNextChar() == '=')
  37036. source.skip();
  37037. break;
  37038. case '/':
  37039. result = tokenType_operator;
  37040. source.skip();
  37041. if (source.peekNextChar() == '=')
  37042. {
  37043. source.skip();
  37044. }
  37045. else if (source.peekNextChar() == '/')
  37046. {
  37047. result = tokenType_comment;
  37048. source.skipToEndOfLine();
  37049. }
  37050. else if (source.peekNextChar() == '*')
  37051. {
  37052. source.skip();
  37053. result = tokenType_comment;
  37054. CppTokeniser::skipComment (source);
  37055. }
  37056. break;
  37057. case '?':
  37058. case '~':
  37059. source.skip();
  37060. result = tokenType_operator;
  37061. break;
  37062. case '<':
  37063. source.skip();
  37064. result = tokenType_operator;
  37065. if (source.peekNextChar() == '=')
  37066. {
  37067. source.skip();
  37068. }
  37069. else if (source.peekNextChar() == '<')
  37070. {
  37071. source.skip();
  37072. if (source.peekNextChar() == '=')
  37073. source.skip();
  37074. }
  37075. break;
  37076. case '>':
  37077. source.skip();
  37078. result = tokenType_operator;
  37079. if (source.peekNextChar() == '=')
  37080. {
  37081. source.skip();
  37082. }
  37083. else if (source.peekNextChar() == '<')
  37084. {
  37085. source.skip();
  37086. if (source.peekNextChar() == '=')
  37087. source.skip();
  37088. }
  37089. break;
  37090. case '|':
  37091. source.skip();
  37092. result = tokenType_operator;
  37093. if (source.peekNextChar() == '=')
  37094. {
  37095. source.skip();
  37096. }
  37097. else if (source.peekNextChar() == '|')
  37098. {
  37099. source.skip();
  37100. if (source.peekNextChar() == '=')
  37101. source.skip();
  37102. }
  37103. break;
  37104. case '&':
  37105. source.skip();
  37106. result = tokenType_operator;
  37107. if (source.peekNextChar() == '=')
  37108. {
  37109. source.skip();
  37110. }
  37111. else if (source.peekNextChar() == '&')
  37112. {
  37113. source.skip();
  37114. if (source.peekNextChar() == '=')
  37115. source.skip();
  37116. }
  37117. break;
  37118. case '^':
  37119. source.skip();
  37120. result = tokenType_operator;
  37121. if (source.peekNextChar() == '=')
  37122. {
  37123. source.skip();
  37124. }
  37125. else if (source.peekNextChar() == '^')
  37126. {
  37127. source.skip();
  37128. if (source.peekNextChar() == '=')
  37129. source.skip();
  37130. }
  37131. break;
  37132. case '#':
  37133. result = tokenType_preprocessor;
  37134. source.skipToEndOfLine();
  37135. break;
  37136. default:
  37137. if (CppTokeniser::isIdentifierStart (firstChar))
  37138. result = CppTokeniser::parseIdentifier (source);
  37139. else
  37140. source.skip();
  37141. break;
  37142. }
  37143. return result;
  37144. }
  37145. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37146. {
  37147. const char* const types[] =
  37148. {
  37149. "Error",
  37150. "Comment",
  37151. "C++ keyword",
  37152. "Identifier",
  37153. "Integer literal",
  37154. "Float literal",
  37155. "String literal",
  37156. "Operator",
  37157. "Bracket",
  37158. "Punctuation",
  37159. "Preprocessor line",
  37160. 0
  37161. };
  37162. return StringArray (types);
  37163. }
  37164. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37165. {
  37166. const uint32 colours[] =
  37167. {
  37168. 0xffcc0000, // error
  37169. 0xff00aa00, // comment
  37170. 0xff0000cc, // keyword
  37171. 0xff000000, // identifier
  37172. 0xff880000, // int literal
  37173. 0xff885500, // float literal
  37174. 0xff990099, // string literal
  37175. 0xff225500, // operator
  37176. 0xff000055, // bracket
  37177. 0xff004400, // punctuation
  37178. 0xff660000 // preprocessor
  37179. };
  37180. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37181. return Colour (colours [tokenType]);
  37182. return Colours::black;
  37183. }
  37184. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37185. {
  37186. return CppTokeniser::isReservedKeyword (token, token.length());
  37187. }
  37188. END_JUCE_NAMESPACE
  37189. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37190. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37191. BEGIN_JUCE_NAMESPACE
  37192. ComboBox::ComboBox (const String& name)
  37193. : Component (name),
  37194. lastCurrentId (0),
  37195. isButtonDown (false),
  37196. separatorPending (false),
  37197. menuActive (false),
  37198. label (0)
  37199. {
  37200. noChoicesMessage = TRANS("(no choices)");
  37201. setRepaintsOnMouseActivity (true);
  37202. lookAndFeelChanged();
  37203. currentId.addListener (this);
  37204. }
  37205. ComboBox::~ComboBox()
  37206. {
  37207. currentId.removeListener (this);
  37208. if (menuActive)
  37209. PopupMenu::dismissAllActiveMenus();
  37210. label = 0;
  37211. deleteAllChildren();
  37212. }
  37213. void ComboBox::setEditableText (const bool isEditable)
  37214. {
  37215. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37216. {
  37217. label->setEditable (isEditable, isEditable, false);
  37218. setWantsKeyboardFocus (! isEditable);
  37219. resized();
  37220. }
  37221. }
  37222. bool ComboBox::isTextEditable() const throw()
  37223. {
  37224. return label->isEditable();
  37225. }
  37226. void ComboBox::setJustificationType (const Justification& justification) throw()
  37227. {
  37228. label->setJustificationType (justification);
  37229. }
  37230. const Justification ComboBox::getJustificationType() const throw()
  37231. {
  37232. return label->getJustificationType();
  37233. }
  37234. void ComboBox::setTooltip (const String& newTooltip)
  37235. {
  37236. SettableTooltipClient::setTooltip (newTooltip);
  37237. label->setTooltip (newTooltip);
  37238. }
  37239. void ComboBox::addItem (const String& newItemText,
  37240. const int newItemId) throw()
  37241. {
  37242. // you can't add empty strings to the list..
  37243. jassert (newItemText.isNotEmpty());
  37244. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37245. jassert (newItemId != 0);
  37246. // you shouldn't use duplicate item IDs!
  37247. jassert (getItemForId (newItemId) == 0);
  37248. if (newItemText.isNotEmpty() && newItemId != 0)
  37249. {
  37250. if (separatorPending)
  37251. {
  37252. separatorPending = false;
  37253. ItemInfo* const item = new ItemInfo();
  37254. item->itemId = 0;
  37255. item->isEnabled = false;
  37256. item->isHeading = false;
  37257. items.add (item);
  37258. }
  37259. ItemInfo* const item = new ItemInfo();
  37260. item->name = newItemText;
  37261. item->itemId = newItemId;
  37262. item->isEnabled = true;
  37263. item->isHeading = false;
  37264. items.add (item);
  37265. }
  37266. }
  37267. void ComboBox::addSeparator() throw()
  37268. {
  37269. separatorPending = (items.size() > 0);
  37270. }
  37271. void ComboBox::addSectionHeading (const String& headingName) throw()
  37272. {
  37273. // you can't add empty strings to the list..
  37274. jassert (headingName.isNotEmpty());
  37275. if (headingName.isNotEmpty())
  37276. {
  37277. if (separatorPending)
  37278. {
  37279. separatorPending = false;
  37280. ItemInfo* const item = new ItemInfo();
  37281. item->itemId = 0;
  37282. item->isEnabled = false;
  37283. item->isHeading = false;
  37284. items.add (item);
  37285. }
  37286. ItemInfo* const item = new ItemInfo();
  37287. item->name = headingName;
  37288. item->itemId = 0;
  37289. item->isEnabled = true;
  37290. item->isHeading = true;
  37291. items.add (item);
  37292. }
  37293. }
  37294. void ComboBox::setItemEnabled (const int itemId,
  37295. const bool shouldBeEnabled) throw()
  37296. {
  37297. ItemInfo* const item = getItemForId (itemId);
  37298. if (item != 0)
  37299. item->isEnabled = shouldBeEnabled;
  37300. }
  37301. void ComboBox::changeItemText (const int itemId,
  37302. const String& newText) throw()
  37303. {
  37304. ItemInfo* const item = getItemForId (itemId);
  37305. jassert (item != 0);
  37306. if (item != 0)
  37307. item->name = newText;
  37308. }
  37309. void ComboBox::clear (const bool dontSendChangeMessage)
  37310. {
  37311. items.clear();
  37312. separatorPending = false;
  37313. if (! label->isEditable())
  37314. setSelectedItemIndex (-1, dontSendChangeMessage);
  37315. }
  37316. bool ComboBox::ItemInfo::isSeparator() const throw()
  37317. {
  37318. return name.isEmpty();
  37319. }
  37320. bool ComboBox::ItemInfo::isRealItem() const throw()
  37321. {
  37322. return ! (isHeading || name.isEmpty());
  37323. }
  37324. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37325. {
  37326. if (itemId != 0)
  37327. {
  37328. for (int i = items.size(); --i >= 0;)
  37329. if (items.getUnchecked(i)->itemId == itemId)
  37330. return items.getUnchecked(i);
  37331. }
  37332. return 0;
  37333. }
  37334. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37335. {
  37336. int n = 0;
  37337. for (int i = 0; i < items.size(); ++i)
  37338. {
  37339. ItemInfo* const item = items.getUnchecked(i);
  37340. if (item->isRealItem())
  37341. if (n++ == index)
  37342. return item;
  37343. }
  37344. return 0;
  37345. }
  37346. int ComboBox::getNumItems() const throw()
  37347. {
  37348. int n = 0;
  37349. for (int i = items.size(); --i >= 0;)
  37350. if (items.getUnchecked(i)->isRealItem())
  37351. ++n;
  37352. return n;
  37353. }
  37354. const String ComboBox::getItemText (const int index) const throw()
  37355. {
  37356. const ItemInfo* const item = getItemForIndex (index);
  37357. if (item != 0)
  37358. return item->name;
  37359. return String::empty;
  37360. }
  37361. int ComboBox::getItemId (const int index) const throw()
  37362. {
  37363. const ItemInfo* const item = getItemForIndex (index);
  37364. return (item != 0) ? item->itemId : 0;
  37365. }
  37366. int ComboBox::indexOfItemId (const int itemId) const throw()
  37367. {
  37368. int n = 0;
  37369. for (int i = 0; i < items.size(); ++i)
  37370. {
  37371. const ItemInfo* const item = items.getUnchecked(i);
  37372. if (item->isRealItem())
  37373. {
  37374. if (item->itemId == itemId)
  37375. return n;
  37376. ++n;
  37377. }
  37378. }
  37379. return -1;
  37380. }
  37381. int ComboBox::getSelectedItemIndex() const throw()
  37382. {
  37383. int index = indexOfItemId (currentId.getValue());
  37384. if (getText() != getItemText (index))
  37385. index = -1;
  37386. return index;
  37387. }
  37388. void ComboBox::setSelectedItemIndex (const int index,
  37389. const bool dontSendChangeMessage) throw()
  37390. {
  37391. setSelectedId (getItemId (index), dontSendChangeMessage);
  37392. }
  37393. int ComboBox::getSelectedId() const throw()
  37394. {
  37395. const ItemInfo* const item = getItemForId (currentId.getValue());
  37396. return (item != 0 && getText() == item->name)
  37397. ? item->itemId
  37398. : 0;
  37399. }
  37400. void ComboBox::setSelectedId (const int newItemId,
  37401. const bool dontSendChangeMessage) throw()
  37402. {
  37403. const ItemInfo* const item = getItemForId (newItemId);
  37404. const String newItemText (item != 0 ? item->name : String::empty);
  37405. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37406. {
  37407. if (! dontSendChangeMessage)
  37408. triggerAsyncUpdate();
  37409. label->setText (newItemText, false);
  37410. lastCurrentId = newItemId;
  37411. currentId = newItemId;
  37412. repaint(); // for the benefit of the 'none selected' text
  37413. }
  37414. }
  37415. void ComboBox::valueChanged (Value&)
  37416. {
  37417. if (lastCurrentId != (int) currentId.getValue())
  37418. setSelectedId (currentId.getValue(), false);
  37419. }
  37420. const String ComboBox::getText() const throw()
  37421. {
  37422. return label->getText();
  37423. }
  37424. void ComboBox::setText (const String& newText,
  37425. const bool dontSendChangeMessage) throw()
  37426. {
  37427. for (int i = items.size(); --i >= 0;)
  37428. {
  37429. const ItemInfo* const item = items.getUnchecked(i);
  37430. if (item->isRealItem()
  37431. && item->name == newText)
  37432. {
  37433. setSelectedId (item->itemId, dontSendChangeMessage);
  37434. return;
  37435. }
  37436. }
  37437. lastCurrentId = 0;
  37438. currentId = 0;
  37439. if (label->getText() != newText)
  37440. {
  37441. label->setText (newText, false);
  37442. if (! dontSendChangeMessage)
  37443. triggerAsyncUpdate();
  37444. }
  37445. repaint();
  37446. }
  37447. void ComboBox::showEditor()
  37448. {
  37449. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37450. label->showEditor();
  37451. }
  37452. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37453. {
  37454. if (textWhenNothingSelected != newMessage)
  37455. {
  37456. textWhenNothingSelected = newMessage;
  37457. repaint();
  37458. }
  37459. }
  37460. const String ComboBox::getTextWhenNothingSelected() const throw()
  37461. {
  37462. return textWhenNothingSelected;
  37463. }
  37464. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37465. {
  37466. noChoicesMessage = newMessage;
  37467. }
  37468. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37469. {
  37470. return noChoicesMessage;
  37471. }
  37472. void ComboBox::paint (Graphics& g)
  37473. {
  37474. getLookAndFeel().drawComboBox (g,
  37475. getWidth(),
  37476. getHeight(),
  37477. isButtonDown,
  37478. label->getRight(),
  37479. 0,
  37480. getWidth() - label->getRight(),
  37481. getHeight(),
  37482. *this);
  37483. if (textWhenNothingSelected.isNotEmpty()
  37484. && label->getText().isEmpty()
  37485. && ! label->isBeingEdited())
  37486. {
  37487. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37488. g.setFont (label->getFont());
  37489. g.drawFittedText (textWhenNothingSelected,
  37490. label->getX() + 2, label->getY() + 1,
  37491. label->getWidth() - 4, label->getHeight() - 2,
  37492. label->getJustificationType(),
  37493. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37494. }
  37495. }
  37496. void ComboBox::resized()
  37497. {
  37498. if (getHeight() > 0 && getWidth() > 0)
  37499. getLookAndFeel().positionComboBoxText (*this, *label);
  37500. }
  37501. void ComboBox::enablementChanged()
  37502. {
  37503. repaint();
  37504. }
  37505. void ComboBox::lookAndFeelChanged()
  37506. {
  37507. repaint();
  37508. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37509. if (label != 0)
  37510. {
  37511. newLabel->setEditable (label->isEditable());
  37512. newLabel->setJustificationType (label->getJustificationType());
  37513. newLabel->setTooltip (label->getTooltip());
  37514. newLabel->setText (label->getText(), false);
  37515. }
  37516. label = newLabel;
  37517. addAndMakeVisible (newLabel);
  37518. newLabel->addListener (this);
  37519. newLabel->addMouseListener (this, false);
  37520. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37521. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37522. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37523. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37524. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37525. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37526. resized();
  37527. }
  37528. void ComboBox::colourChanged()
  37529. {
  37530. lookAndFeelChanged();
  37531. }
  37532. bool ComboBox::keyPressed (const KeyPress& key)
  37533. {
  37534. bool used = false;
  37535. if (key.isKeyCode (KeyPress::upKey)
  37536. || key.isKeyCode (KeyPress::leftKey))
  37537. {
  37538. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37539. used = true;
  37540. }
  37541. else if (key.isKeyCode (KeyPress::downKey)
  37542. || key.isKeyCode (KeyPress::rightKey))
  37543. {
  37544. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37545. used = true;
  37546. }
  37547. else if (key.isKeyCode (KeyPress::returnKey))
  37548. {
  37549. showPopup();
  37550. used = true;
  37551. }
  37552. return used;
  37553. }
  37554. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37555. {
  37556. // only forward key events that aren't used by this component
  37557. return isKeyDown
  37558. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37559. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37560. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37561. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37562. }
  37563. void ComboBox::focusGained (FocusChangeType)
  37564. {
  37565. repaint();
  37566. }
  37567. void ComboBox::focusLost (FocusChangeType)
  37568. {
  37569. repaint();
  37570. }
  37571. void ComboBox::labelTextChanged (Label*)
  37572. {
  37573. triggerAsyncUpdate();
  37574. }
  37575. void ComboBox::showPopup()
  37576. {
  37577. if (! menuActive)
  37578. {
  37579. const int selectedId = getSelectedId();
  37580. Component::SafePointer<Component> deletionWatcher (this);
  37581. PopupMenu menu;
  37582. menu.setLookAndFeel (&getLookAndFeel());
  37583. for (int i = 0; i < items.size(); ++i)
  37584. {
  37585. const ItemInfo* const item = items.getUnchecked(i);
  37586. if (item->isSeparator())
  37587. menu.addSeparator();
  37588. else if (item->isHeading)
  37589. menu.addSectionHeader (item->name);
  37590. else
  37591. menu.addItem (item->itemId, item->name,
  37592. item->isEnabled, item->itemId == selectedId);
  37593. }
  37594. if (items.size() == 0)
  37595. menu.addItem (1, noChoicesMessage, false);
  37596. const int itemHeight = jlimit (12, 24, getHeight());
  37597. menuActive = true;
  37598. const int resultId = menu.showAt (this, selectedId,
  37599. getWidth(), 1, itemHeight);
  37600. if (deletionWatcher == 0)
  37601. return;
  37602. menuActive = false;
  37603. if (resultId != 0)
  37604. setSelectedId (resultId);
  37605. }
  37606. }
  37607. void ComboBox::mouseDown (const MouseEvent& e)
  37608. {
  37609. beginDragAutoRepeat (300);
  37610. isButtonDown = isEnabled();
  37611. if (isButtonDown
  37612. && (e.eventComponent == this || ! label->isEditable()))
  37613. {
  37614. showPopup();
  37615. }
  37616. }
  37617. void ComboBox::mouseDrag (const MouseEvent& e)
  37618. {
  37619. beginDragAutoRepeat (50);
  37620. if (isButtonDown && ! e.mouseWasClicked())
  37621. showPopup();
  37622. }
  37623. void ComboBox::mouseUp (const MouseEvent& e2)
  37624. {
  37625. if (isButtonDown)
  37626. {
  37627. isButtonDown = false;
  37628. repaint();
  37629. const MouseEvent e (e2.getEventRelativeTo (this));
  37630. if (reallyContains (e.x, e.y, true)
  37631. && (e2.eventComponent == this || ! label->isEditable()))
  37632. {
  37633. showPopup();
  37634. }
  37635. }
  37636. }
  37637. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  37638. {
  37639. listeners.add (listener);
  37640. }
  37641. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  37642. {
  37643. listeners.remove (listener);
  37644. }
  37645. void ComboBox::handleAsyncUpdate()
  37646. {
  37647. Component::BailOutChecker checker (this);
  37648. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this);
  37649. }
  37650. END_JUCE_NAMESPACE
  37651. /*** End of inlined file: juce_ComboBox.cpp ***/
  37652. /*** Start of inlined file: juce_Label.cpp ***/
  37653. BEGIN_JUCE_NAMESPACE
  37654. Label::Label (const String& componentName,
  37655. const String& labelText)
  37656. : Component (componentName),
  37657. textValue (labelText),
  37658. lastTextValue (labelText),
  37659. font (15.0f),
  37660. justification (Justification::centredLeft),
  37661. ownerComponent (0),
  37662. horizontalBorderSize (5),
  37663. verticalBorderSize (1),
  37664. minimumHorizontalScale (0.7f),
  37665. editSingleClick (false),
  37666. editDoubleClick (false),
  37667. lossOfFocusDiscardsChanges (false)
  37668. {
  37669. setColour (TextEditor::textColourId, Colours::black);
  37670. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37671. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37672. textValue.addListener (this);
  37673. }
  37674. Label::~Label()
  37675. {
  37676. textValue.removeListener (this);
  37677. if (ownerComponent != 0)
  37678. ownerComponent->removeComponentListener (this);
  37679. editor = 0;
  37680. }
  37681. void Label::setText (const String& newText,
  37682. const bool broadcastChangeMessage)
  37683. {
  37684. hideEditor (true);
  37685. if (lastTextValue != newText)
  37686. {
  37687. lastTextValue = newText;
  37688. textValue = newText;
  37689. repaint();
  37690. textWasChanged();
  37691. if (ownerComponent != 0)
  37692. componentMovedOrResized (*ownerComponent, true, true);
  37693. if (broadcastChangeMessage)
  37694. callChangeListeners();
  37695. }
  37696. }
  37697. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37698. {
  37699. return (returnActiveEditorContents && isBeingEdited())
  37700. ? editor->getText()
  37701. : textValue.toString();
  37702. }
  37703. void Label::valueChanged (Value&)
  37704. {
  37705. if (lastTextValue != textValue.toString())
  37706. setText (textValue.toString(), true);
  37707. }
  37708. void Label::setFont (const Font& newFont) throw()
  37709. {
  37710. if (font != newFont)
  37711. {
  37712. font = newFont;
  37713. repaint();
  37714. }
  37715. }
  37716. const Font& Label::getFont() const throw()
  37717. {
  37718. return font;
  37719. }
  37720. void Label::setEditable (const bool editOnSingleClick,
  37721. const bool editOnDoubleClick,
  37722. const bool lossOfFocusDiscardsChanges_) throw()
  37723. {
  37724. editSingleClick = editOnSingleClick;
  37725. editDoubleClick = editOnDoubleClick;
  37726. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37727. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37728. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37729. }
  37730. void Label::setJustificationType (const Justification& newJustification) throw()
  37731. {
  37732. if (justification != newJustification)
  37733. {
  37734. justification = newJustification;
  37735. repaint();
  37736. }
  37737. }
  37738. void Label::setBorderSize (int h, int v)
  37739. {
  37740. if (horizontalBorderSize != h || verticalBorderSize != v)
  37741. {
  37742. horizontalBorderSize = h;
  37743. verticalBorderSize = v;
  37744. repaint();
  37745. }
  37746. }
  37747. Component* Label::getAttachedComponent() const
  37748. {
  37749. return static_cast<Component*> (ownerComponent);
  37750. }
  37751. void Label::attachToComponent (Component* owner,
  37752. const bool onLeft)
  37753. {
  37754. if (ownerComponent != 0)
  37755. ownerComponent->removeComponentListener (this);
  37756. ownerComponent = owner;
  37757. leftOfOwnerComp = onLeft;
  37758. if (ownerComponent != 0)
  37759. {
  37760. setVisible (owner->isVisible());
  37761. ownerComponent->addComponentListener (this);
  37762. componentParentHierarchyChanged (*ownerComponent);
  37763. componentMovedOrResized (*ownerComponent, true, true);
  37764. }
  37765. }
  37766. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  37767. {
  37768. if (leftOfOwnerComp)
  37769. {
  37770. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37771. component.getHeight());
  37772. setTopRightPosition (component.getX(), component.getY());
  37773. }
  37774. else
  37775. {
  37776. setSize (component.getWidth(),
  37777. 8 + roundToInt (getFont().getHeight()));
  37778. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37779. }
  37780. }
  37781. void Label::componentParentHierarchyChanged (Component& component)
  37782. {
  37783. if (component.getParentComponent() != 0)
  37784. component.getParentComponent()->addChildComponent (this);
  37785. }
  37786. void Label::componentVisibilityChanged (Component& component)
  37787. {
  37788. setVisible (component.isVisible());
  37789. }
  37790. void Label::textWasEdited()
  37791. {
  37792. }
  37793. void Label::textWasChanged()
  37794. {
  37795. }
  37796. void Label::showEditor()
  37797. {
  37798. if (editor == 0)
  37799. {
  37800. addAndMakeVisible (editor = createEditorComponent());
  37801. editor->setText (getText(), false);
  37802. editor->addListener (this);
  37803. editor->grabKeyboardFocus();
  37804. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37805. editor->addListener (this);
  37806. resized();
  37807. repaint();
  37808. editorShown (editor);
  37809. enterModalState (false);
  37810. editor->grabKeyboardFocus();
  37811. }
  37812. }
  37813. void Label::editorShown (TextEditor* /*editorComponent*/)
  37814. {
  37815. }
  37816. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  37817. {
  37818. }
  37819. bool Label::updateFromTextEditorContents()
  37820. {
  37821. jassert (editor != 0);
  37822. const String newText (editor->getText());
  37823. if (textValue.toString() != newText)
  37824. {
  37825. lastTextValue = newText;
  37826. textValue = newText;
  37827. repaint();
  37828. textWasChanged();
  37829. if (ownerComponent != 0)
  37830. componentMovedOrResized (*ownerComponent, true, true);
  37831. return true;
  37832. }
  37833. return false;
  37834. }
  37835. void Label::hideEditor (const bool discardCurrentEditorContents)
  37836. {
  37837. if (editor != 0)
  37838. {
  37839. Component::SafePointer<Component> deletionChecker (this);
  37840. editorAboutToBeHidden (editor);
  37841. const bool changed = (! discardCurrentEditorContents)
  37842. && updateFromTextEditorContents();
  37843. editor = 0;
  37844. repaint();
  37845. if (changed)
  37846. textWasEdited();
  37847. if (deletionChecker != 0)
  37848. exitModalState (0);
  37849. if (changed && deletionChecker != 0)
  37850. callChangeListeners();
  37851. }
  37852. }
  37853. void Label::inputAttemptWhenModal()
  37854. {
  37855. if (editor != 0)
  37856. {
  37857. if (lossOfFocusDiscardsChanges)
  37858. textEditorEscapeKeyPressed (*editor);
  37859. else
  37860. textEditorReturnKeyPressed (*editor);
  37861. }
  37862. }
  37863. bool Label::isBeingEdited() const throw()
  37864. {
  37865. return editor != 0;
  37866. }
  37867. TextEditor* Label::createEditorComponent()
  37868. {
  37869. TextEditor* const ed = new TextEditor (getName());
  37870. ed->setFont (font);
  37871. // copy these colours from our own settings..
  37872. const int cols[] = { TextEditor::backgroundColourId,
  37873. TextEditor::textColourId,
  37874. TextEditor::highlightColourId,
  37875. TextEditor::highlightedTextColourId,
  37876. TextEditor::caretColourId,
  37877. TextEditor::outlineColourId,
  37878. TextEditor::focusedOutlineColourId,
  37879. TextEditor::shadowColourId };
  37880. for (int i = 0; i < numElementsInArray (cols); ++i)
  37881. ed->setColour (cols[i], findColour (cols[i]));
  37882. return ed;
  37883. }
  37884. void Label::paint (Graphics& g)
  37885. {
  37886. getLookAndFeel().drawLabel (g, *this);
  37887. }
  37888. void Label::mouseUp (const MouseEvent& e)
  37889. {
  37890. if (editSingleClick
  37891. && e.mouseWasClicked()
  37892. && contains (e.x, e.y)
  37893. && ! e.mods.isPopupMenu())
  37894. {
  37895. showEditor();
  37896. }
  37897. }
  37898. void Label::mouseDoubleClick (const MouseEvent& e)
  37899. {
  37900. if (editDoubleClick && ! e.mods.isPopupMenu())
  37901. showEditor();
  37902. }
  37903. void Label::resized()
  37904. {
  37905. if (editor != 0)
  37906. editor->setBoundsInset (BorderSize (0));
  37907. }
  37908. void Label::focusGained (FocusChangeType cause)
  37909. {
  37910. if (editSingleClick && cause == focusChangedByTabKey)
  37911. showEditor();
  37912. }
  37913. void Label::enablementChanged()
  37914. {
  37915. repaint();
  37916. }
  37917. void Label::colourChanged()
  37918. {
  37919. repaint();
  37920. }
  37921. void Label::setMinimumHorizontalScale (const float newScale)
  37922. {
  37923. if (minimumHorizontalScale != newScale)
  37924. {
  37925. minimumHorizontalScale = newScale;
  37926. repaint();
  37927. }
  37928. }
  37929. // We'll use a custom focus traverser here to make sure focus goes from the
  37930. // text editor to another component rather than back to the label itself.
  37931. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  37932. {
  37933. public:
  37934. LabelKeyboardFocusTraverser() {}
  37935. Component* getNextComponent (Component* current)
  37936. {
  37937. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  37938. ? current->getParentComponent() : current);
  37939. }
  37940. Component* getPreviousComponent (Component* current)
  37941. {
  37942. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  37943. ? current->getParentComponent() : current);
  37944. }
  37945. };
  37946. KeyboardFocusTraverser* Label::createFocusTraverser()
  37947. {
  37948. return new LabelKeyboardFocusTraverser();
  37949. }
  37950. void Label::addListener (LabelListener* const listener) throw()
  37951. {
  37952. listeners.add (listener);
  37953. }
  37954. void Label::removeListener (LabelListener* const listener) throw()
  37955. {
  37956. listeners.remove (listener);
  37957. }
  37958. void Label::callChangeListeners()
  37959. {
  37960. Component::BailOutChecker checker (this);
  37961. listeners.callChecked (checker, &LabelListener::labelTextChanged, this);
  37962. }
  37963. void Label::textEditorTextChanged (TextEditor& ed)
  37964. {
  37965. if (editor != 0)
  37966. {
  37967. jassert (&ed == editor);
  37968. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  37969. {
  37970. if (lossOfFocusDiscardsChanges)
  37971. textEditorEscapeKeyPressed (ed);
  37972. else
  37973. textEditorReturnKeyPressed (ed);
  37974. }
  37975. }
  37976. }
  37977. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  37978. {
  37979. if (editor != 0)
  37980. {
  37981. jassert (&ed == editor);
  37982. (void) ed;
  37983. const bool changed = updateFromTextEditorContents();
  37984. hideEditor (true);
  37985. if (changed)
  37986. {
  37987. Component::SafePointer<Component> deletionChecker (this);
  37988. textWasEdited();
  37989. if (deletionChecker != 0)
  37990. callChangeListeners();
  37991. }
  37992. }
  37993. }
  37994. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  37995. {
  37996. if (editor != 0)
  37997. {
  37998. jassert (&ed == editor);
  37999. (void) ed;
  38000. editor->setText (textValue.toString(), false);
  38001. hideEditor (true);
  38002. }
  38003. }
  38004. void Label::textEditorFocusLost (TextEditor& ed)
  38005. {
  38006. textEditorTextChanged (ed);
  38007. }
  38008. END_JUCE_NAMESPACE
  38009. /*** End of inlined file: juce_Label.cpp ***/
  38010. /*** Start of inlined file: juce_ListBox.cpp ***/
  38011. BEGIN_JUCE_NAMESPACE
  38012. class ListBoxRowComponent : public Component,
  38013. public TooltipClient
  38014. {
  38015. public:
  38016. ListBoxRowComponent (ListBox& owner_)
  38017. : owner (owner_),
  38018. row (-1),
  38019. selected (false),
  38020. isDragging (false)
  38021. {
  38022. }
  38023. ~ListBoxRowComponent()
  38024. {
  38025. deleteAllChildren();
  38026. }
  38027. void paint (Graphics& g)
  38028. {
  38029. if (owner.getModel() != 0)
  38030. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38031. }
  38032. void update (const int row_, const bool selected_)
  38033. {
  38034. if (row != row_ || selected != selected_)
  38035. {
  38036. repaint();
  38037. row = row_;
  38038. selected = selected_;
  38039. }
  38040. if (owner.getModel() != 0)
  38041. {
  38042. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38043. if (customComp != 0)
  38044. {
  38045. addAndMakeVisible (customComp);
  38046. customComp->setBounds (0, 0, getWidth(), getHeight());
  38047. for (int i = getNumChildComponents(); --i >= 0;)
  38048. if (getChildComponent (i) != customComp)
  38049. delete getChildComponent (i);
  38050. }
  38051. else
  38052. {
  38053. deleteAllChildren();
  38054. }
  38055. }
  38056. }
  38057. void mouseDown (const MouseEvent& e)
  38058. {
  38059. isDragging = false;
  38060. selectRowOnMouseUp = false;
  38061. if (isEnabled())
  38062. {
  38063. if (! selected)
  38064. {
  38065. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38066. if (owner.getModel() != 0)
  38067. owner.getModel()->listBoxItemClicked (row, e);
  38068. }
  38069. else
  38070. {
  38071. selectRowOnMouseUp = true;
  38072. }
  38073. }
  38074. }
  38075. void mouseUp (const MouseEvent& e)
  38076. {
  38077. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38078. {
  38079. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38080. if (owner.getModel() != 0)
  38081. owner.getModel()->listBoxItemClicked (row, e);
  38082. }
  38083. }
  38084. void mouseDoubleClick (const MouseEvent& e)
  38085. {
  38086. if (owner.getModel() != 0 && isEnabled())
  38087. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38088. }
  38089. void mouseDrag (const MouseEvent& e)
  38090. {
  38091. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38092. {
  38093. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38094. if (selectedRows.size() > 0)
  38095. {
  38096. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38097. if (dragDescription.isNotEmpty())
  38098. {
  38099. isDragging = true;
  38100. owner.startDragAndDrop (e, dragDescription);
  38101. }
  38102. }
  38103. }
  38104. }
  38105. void resized()
  38106. {
  38107. if (getNumChildComponents() > 0)
  38108. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  38109. }
  38110. const String getTooltip()
  38111. {
  38112. if (owner.getModel() != 0)
  38113. return owner.getModel()->getTooltipForRow (row);
  38114. return String::empty;
  38115. }
  38116. juce_UseDebuggingNewOperator
  38117. bool neededFlag;
  38118. private:
  38119. ListBox& owner;
  38120. int row;
  38121. bool selected, isDragging, selectRowOnMouseUp;
  38122. ListBoxRowComponent (const ListBoxRowComponent&);
  38123. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38124. };
  38125. class ListViewport : public Viewport
  38126. {
  38127. public:
  38128. int firstIndex, firstWholeIndex, lastWholeIndex;
  38129. bool hasUpdated;
  38130. ListViewport (ListBox& owner_)
  38131. : owner (owner_)
  38132. {
  38133. setWantsKeyboardFocus (false);
  38134. setViewedComponent (new Component());
  38135. getViewedComponent()->addMouseListener (this, false);
  38136. getViewedComponent()->setWantsKeyboardFocus (false);
  38137. }
  38138. ~ListViewport()
  38139. {
  38140. getViewedComponent()->removeMouseListener (this);
  38141. getViewedComponent()->deleteAllChildren();
  38142. }
  38143. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38144. {
  38145. return static_cast <ListBoxRowComponent*>
  38146. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38147. }
  38148. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38149. {
  38150. const int index = getIndexOfChildComponent (rowComponent);
  38151. const int num = getViewedComponent()->getNumChildComponents();
  38152. for (int i = num; --i >= 0;)
  38153. if (((firstIndex + i) % jmax (1, num)) == index)
  38154. return firstIndex + i;
  38155. return -1;
  38156. }
  38157. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38158. {
  38159. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38160. ? getComponentForRow (row) : 0;
  38161. }
  38162. void visibleAreaChanged (int, int, int, int)
  38163. {
  38164. updateVisibleArea (true);
  38165. if (owner.getModel() != 0)
  38166. owner.getModel()->listWasScrolled();
  38167. }
  38168. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38169. {
  38170. hasUpdated = false;
  38171. const int newX = getViewedComponent()->getX();
  38172. int newY = getViewedComponent()->getY();
  38173. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38174. const int newH = owner.totalItems * owner.getRowHeight();
  38175. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38176. newY = getMaximumVisibleHeight() - newH;
  38177. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38178. if (makeSureItUpdatesContent && ! hasUpdated)
  38179. updateContents();
  38180. }
  38181. void updateContents()
  38182. {
  38183. hasUpdated = true;
  38184. const int rowHeight = owner.getRowHeight();
  38185. if (rowHeight > 0)
  38186. {
  38187. const int y = getViewPositionY();
  38188. const int w = getViewedComponent()->getWidth();
  38189. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38190. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38191. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38192. jassert (numNeeded >= 0);
  38193. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38194. {
  38195. Component* const rowToRemove
  38196. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38197. delete rowToRemove;
  38198. }
  38199. firstIndex = y / rowHeight;
  38200. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38201. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38202. for (int i = 0; i < numNeeded; ++i)
  38203. {
  38204. const int row = i + firstIndex;
  38205. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38206. if (rowComp != 0)
  38207. {
  38208. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38209. rowComp->update (row, owner.isRowSelected (row));
  38210. }
  38211. }
  38212. }
  38213. if (owner.headerComponent != 0)
  38214. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38215. owner.outlineThickness,
  38216. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38217. getViewedComponent()->getWidth()),
  38218. owner.headerComponent->getHeight());
  38219. }
  38220. void paint (Graphics& g)
  38221. {
  38222. if (isOpaque())
  38223. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38224. }
  38225. bool keyPressed (const KeyPress& key)
  38226. {
  38227. if (key.isKeyCode (KeyPress::upKey)
  38228. || key.isKeyCode (KeyPress::downKey)
  38229. || key.isKeyCode (KeyPress::pageUpKey)
  38230. || key.isKeyCode (KeyPress::pageDownKey)
  38231. || key.isKeyCode (KeyPress::homeKey)
  38232. || key.isKeyCode (KeyPress::endKey))
  38233. {
  38234. // we want to avoid these keypresses going to the viewport, and instead allow
  38235. // them to pass up to our listbox..
  38236. return false;
  38237. }
  38238. return Viewport::keyPressed (key);
  38239. }
  38240. juce_UseDebuggingNewOperator
  38241. private:
  38242. ListBox& owner;
  38243. ListViewport (const ListViewport&);
  38244. ListViewport& operator= (const ListViewport&);
  38245. };
  38246. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38247. : Component (name),
  38248. model (model_),
  38249. headerComponent (0),
  38250. totalItems (0),
  38251. rowHeight (22),
  38252. minimumRowWidth (0),
  38253. outlineThickness (0),
  38254. lastRowSelected (-1),
  38255. mouseMoveSelects (false),
  38256. multipleSelection (false),
  38257. hasDoneInitialUpdate (false)
  38258. {
  38259. addAndMakeVisible (viewport = new ListViewport (*this));
  38260. setWantsKeyboardFocus (true);
  38261. colourChanged();
  38262. }
  38263. ListBox::~ListBox()
  38264. {
  38265. deleteAllChildren();
  38266. }
  38267. void ListBox::setModel (ListBoxModel* const newModel)
  38268. {
  38269. if (model != newModel)
  38270. {
  38271. model = newModel;
  38272. updateContent();
  38273. }
  38274. }
  38275. void ListBox::setMultipleSelectionEnabled (bool b)
  38276. {
  38277. multipleSelection = b;
  38278. }
  38279. void ListBox::setMouseMoveSelectsRows (bool b)
  38280. {
  38281. mouseMoveSelects = b;
  38282. if (b)
  38283. addMouseListener (this, true);
  38284. }
  38285. void ListBox::paint (Graphics& g)
  38286. {
  38287. if (! hasDoneInitialUpdate)
  38288. updateContent();
  38289. g.fillAll (findColour (backgroundColourId));
  38290. }
  38291. void ListBox::paintOverChildren (Graphics& g)
  38292. {
  38293. if (outlineThickness > 0)
  38294. {
  38295. g.setColour (findColour (outlineColourId));
  38296. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38297. }
  38298. }
  38299. void ListBox::resized()
  38300. {
  38301. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38302. outlineThickness,
  38303. outlineThickness,
  38304. outlineThickness));
  38305. viewport->setSingleStepSizes (20, getRowHeight());
  38306. viewport->updateVisibleArea (false);
  38307. }
  38308. void ListBox::visibilityChanged()
  38309. {
  38310. viewport->updateVisibleArea (true);
  38311. }
  38312. Viewport* ListBox::getViewport() const throw()
  38313. {
  38314. return viewport;
  38315. }
  38316. void ListBox::updateContent()
  38317. {
  38318. hasDoneInitialUpdate = true;
  38319. totalItems = (model != 0) ? model->getNumRows() : 0;
  38320. bool selectionChanged = false;
  38321. if (selected [selected.size() - 1] >= totalItems)
  38322. {
  38323. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38324. lastRowSelected = getSelectedRow (0);
  38325. selectionChanged = true;
  38326. }
  38327. viewport->updateVisibleArea (isVisible());
  38328. viewport->resized();
  38329. if (selectionChanged && model != 0)
  38330. model->selectedRowsChanged (lastRowSelected);
  38331. }
  38332. void ListBox::selectRow (const int row,
  38333. bool dontScroll,
  38334. bool deselectOthersFirst)
  38335. {
  38336. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38337. }
  38338. void ListBox::selectRowInternal (const int row,
  38339. bool dontScroll,
  38340. bool deselectOthersFirst,
  38341. bool isMouseClick)
  38342. {
  38343. if (! multipleSelection)
  38344. deselectOthersFirst = true;
  38345. if ((! isRowSelected (row))
  38346. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38347. {
  38348. if (((unsigned int) row) < (unsigned int) totalItems)
  38349. {
  38350. if (deselectOthersFirst)
  38351. selected.clear();
  38352. selected.addRange (Range<int> (row, row + 1));
  38353. if (getHeight() == 0 || getWidth() == 0)
  38354. dontScroll = true;
  38355. viewport->hasUpdated = false;
  38356. if (row < viewport->firstWholeIndex && ! dontScroll)
  38357. {
  38358. viewport->setViewPosition (viewport->getViewPositionX(),
  38359. row * getRowHeight());
  38360. }
  38361. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38362. {
  38363. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38364. if (row >= lastRowSelected + rowsOnScreen
  38365. && rowsOnScreen < totalItems - 1
  38366. && ! isMouseClick)
  38367. {
  38368. viewport->setViewPosition (viewport->getViewPositionX(),
  38369. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38370. * getRowHeight());
  38371. }
  38372. else
  38373. {
  38374. viewport->setViewPosition (viewport->getViewPositionX(),
  38375. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38376. }
  38377. }
  38378. if (! viewport->hasUpdated)
  38379. viewport->updateContents();
  38380. lastRowSelected = row;
  38381. model->selectedRowsChanged (row);
  38382. }
  38383. else
  38384. {
  38385. if (deselectOthersFirst)
  38386. deselectAllRows();
  38387. }
  38388. }
  38389. }
  38390. void ListBox::deselectRow (const int row)
  38391. {
  38392. if (selected.contains (row))
  38393. {
  38394. selected.removeRange (Range <int> (row, row + 1));
  38395. if (row == lastRowSelected)
  38396. lastRowSelected = getSelectedRow (0);
  38397. viewport->updateContents();
  38398. model->selectedRowsChanged (lastRowSelected);
  38399. }
  38400. }
  38401. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38402. const bool sendNotificationEventToModel)
  38403. {
  38404. selected = setOfRowsToBeSelected;
  38405. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38406. if (! isRowSelected (lastRowSelected))
  38407. lastRowSelected = getSelectedRow (0);
  38408. viewport->updateContents();
  38409. if ((model != 0) && sendNotificationEventToModel)
  38410. model->selectedRowsChanged (lastRowSelected);
  38411. }
  38412. const SparseSet<int> ListBox::getSelectedRows() const
  38413. {
  38414. return selected;
  38415. }
  38416. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38417. {
  38418. if (multipleSelection && (firstRow != lastRow))
  38419. {
  38420. const int numRows = totalItems - 1;
  38421. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38422. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38423. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38424. jmax (firstRow, lastRow) + 1));
  38425. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38426. }
  38427. selectRowInternal (lastRow, false, false, true);
  38428. }
  38429. void ListBox::flipRowSelection (const int row)
  38430. {
  38431. if (isRowSelected (row))
  38432. deselectRow (row);
  38433. else
  38434. selectRowInternal (row, false, false, true);
  38435. }
  38436. void ListBox::deselectAllRows()
  38437. {
  38438. if (! selected.isEmpty())
  38439. {
  38440. selected.clear();
  38441. lastRowSelected = -1;
  38442. viewport->updateContents();
  38443. if (model != 0)
  38444. model->selectedRowsChanged (lastRowSelected);
  38445. }
  38446. }
  38447. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38448. const ModifierKeys& mods)
  38449. {
  38450. if (multipleSelection && mods.isCommandDown())
  38451. {
  38452. flipRowSelection (row);
  38453. }
  38454. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38455. {
  38456. selectRangeOfRows (lastRowSelected, row);
  38457. }
  38458. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38459. {
  38460. selectRowInternal (row, false, true, true);
  38461. }
  38462. }
  38463. int ListBox::getNumSelectedRows() const
  38464. {
  38465. return selected.size();
  38466. }
  38467. int ListBox::getSelectedRow (const int index) const
  38468. {
  38469. return (((unsigned int) index) < (unsigned int) selected.size())
  38470. ? selected [index] : -1;
  38471. }
  38472. bool ListBox::isRowSelected (const int row) const
  38473. {
  38474. return selected.contains (row);
  38475. }
  38476. int ListBox::getLastRowSelected() const
  38477. {
  38478. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38479. }
  38480. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38481. {
  38482. if (((unsigned int) x) < (unsigned int) getWidth())
  38483. {
  38484. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38485. if (((unsigned int) row) < (unsigned int) totalItems)
  38486. return row;
  38487. }
  38488. return -1;
  38489. }
  38490. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38491. {
  38492. if (((unsigned int) x) < (unsigned int) getWidth())
  38493. {
  38494. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38495. return jlimit (0, totalItems, row);
  38496. }
  38497. return -1;
  38498. }
  38499. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38500. {
  38501. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38502. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38503. }
  38504. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38505. {
  38506. return viewport->getRowNumberOfComponent (rowComponent);
  38507. }
  38508. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38509. const bool relativeToComponentTopLeft) const throw()
  38510. {
  38511. int y = viewport->getY() + rowHeight * rowNumber;
  38512. if (relativeToComponentTopLeft)
  38513. y -= viewport->getViewPositionY();
  38514. return Rectangle<int> (viewport->getX(), y,
  38515. viewport->getViewedComponent()->getWidth(), rowHeight);
  38516. }
  38517. void ListBox::setVerticalPosition (const double proportion)
  38518. {
  38519. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38520. viewport->setViewPosition (viewport->getViewPositionX(),
  38521. jmax (0, roundToInt (proportion * offscreen)));
  38522. }
  38523. double ListBox::getVerticalPosition() const
  38524. {
  38525. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38526. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38527. : 0;
  38528. }
  38529. int ListBox::getVisibleRowWidth() const throw()
  38530. {
  38531. return viewport->getViewWidth();
  38532. }
  38533. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38534. {
  38535. if (row < viewport->firstWholeIndex)
  38536. {
  38537. viewport->setViewPosition (viewport->getViewPositionX(),
  38538. row * getRowHeight());
  38539. }
  38540. else if (row >= viewport->lastWholeIndex)
  38541. {
  38542. viewport->setViewPosition (viewport->getViewPositionX(),
  38543. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38544. }
  38545. }
  38546. bool ListBox::keyPressed (const KeyPress& key)
  38547. {
  38548. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38549. const bool multiple = multipleSelection
  38550. && (lastRowSelected >= 0)
  38551. && (key.getModifiers().isShiftDown()
  38552. || key.getModifiers().isCtrlDown()
  38553. || key.getModifiers().isCommandDown());
  38554. if (key.isKeyCode (KeyPress::upKey))
  38555. {
  38556. if (multiple)
  38557. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38558. else
  38559. selectRow (jmax (0, lastRowSelected - 1));
  38560. }
  38561. else if (key.isKeyCode (KeyPress::returnKey)
  38562. && isRowSelected (lastRowSelected))
  38563. {
  38564. if (model != 0)
  38565. model->returnKeyPressed (lastRowSelected);
  38566. }
  38567. else if (key.isKeyCode (KeyPress::pageUpKey))
  38568. {
  38569. if (multiple)
  38570. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38571. else
  38572. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38573. }
  38574. else if (key.isKeyCode (KeyPress::pageDownKey))
  38575. {
  38576. if (multiple)
  38577. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38578. else
  38579. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38580. }
  38581. else if (key.isKeyCode (KeyPress::homeKey))
  38582. {
  38583. if (multiple && key.getModifiers().isShiftDown())
  38584. selectRangeOfRows (lastRowSelected, 0);
  38585. else
  38586. selectRow (0);
  38587. }
  38588. else if (key.isKeyCode (KeyPress::endKey))
  38589. {
  38590. if (multiple && key.getModifiers().isShiftDown())
  38591. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38592. else
  38593. selectRow (totalItems - 1);
  38594. }
  38595. else if (key.isKeyCode (KeyPress::downKey))
  38596. {
  38597. if (multiple)
  38598. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38599. else
  38600. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38601. }
  38602. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38603. && isRowSelected (lastRowSelected))
  38604. {
  38605. if (model != 0)
  38606. model->deleteKeyPressed (lastRowSelected);
  38607. }
  38608. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38609. {
  38610. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38611. }
  38612. else
  38613. {
  38614. return false;
  38615. }
  38616. return true;
  38617. }
  38618. bool ListBox::keyStateChanged (const bool isKeyDown)
  38619. {
  38620. return isKeyDown
  38621. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38622. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38623. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38624. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38625. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38626. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38627. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38628. }
  38629. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38630. {
  38631. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38632. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38633. }
  38634. void ListBox::mouseMove (const MouseEvent& e)
  38635. {
  38636. if (mouseMoveSelects)
  38637. {
  38638. const MouseEvent e2 (e.getEventRelativeTo (this));
  38639. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38640. }
  38641. }
  38642. void ListBox::mouseExit (const MouseEvent& e)
  38643. {
  38644. mouseMove (e);
  38645. }
  38646. void ListBox::mouseUp (const MouseEvent& e)
  38647. {
  38648. if (e.mouseWasClicked() && model != 0)
  38649. model->backgroundClicked();
  38650. }
  38651. void ListBox::setRowHeight (const int newHeight)
  38652. {
  38653. rowHeight = jmax (1, newHeight);
  38654. viewport->setSingleStepSizes (20, rowHeight);
  38655. updateContent();
  38656. }
  38657. int ListBox::getNumRowsOnScreen() const throw()
  38658. {
  38659. return viewport->getMaximumVisibleHeight() / rowHeight;
  38660. }
  38661. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38662. {
  38663. minimumRowWidth = newMinimumWidth;
  38664. updateContent();
  38665. }
  38666. int ListBox::getVisibleContentWidth() const throw()
  38667. {
  38668. return viewport->getMaximumVisibleWidth();
  38669. }
  38670. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38671. {
  38672. return viewport->getVerticalScrollBar();
  38673. }
  38674. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38675. {
  38676. return viewport->getHorizontalScrollBar();
  38677. }
  38678. void ListBox::colourChanged()
  38679. {
  38680. setOpaque (findColour (backgroundColourId).isOpaque());
  38681. viewport->setOpaque (isOpaque());
  38682. repaint();
  38683. }
  38684. void ListBox::setOutlineThickness (const int outlineThickness_)
  38685. {
  38686. outlineThickness = outlineThickness_;
  38687. resized();
  38688. }
  38689. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38690. {
  38691. if (headerComponent != newHeaderComponent)
  38692. {
  38693. delete headerComponent;
  38694. headerComponent = newHeaderComponent;
  38695. addAndMakeVisible (newHeaderComponent);
  38696. ListBox::resized();
  38697. }
  38698. }
  38699. void ListBox::repaintRow (const int rowNumber) throw()
  38700. {
  38701. repaint (getRowPosition (rowNumber, true));
  38702. }
  38703. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38704. {
  38705. Rectangle<int> imageArea;
  38706. const int firstRow = getRowContainingPosition (0, 0);
  38707. int i;
  38708. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38709. {
  38710. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38711. if (rowComp != 0 && isRowSelected (firstRow + i))
  38712. {
  38713. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38714. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38715. imageArea = imageArea.getUnion (rowRect);
  38716. }
  38717. }
  38718. imageArea = imageArea.getIntersection (getLocalBounds());
  38719. imageX = imageArea.getX();
  38720. imageY = imageArea.getY();
  38721. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  38722. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38723. {
  38724. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38725. if (rowComp != 0 && isRowSelected (firstRow + i))
  38726. {
  38727. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38728. Graphics g (snapshot);
  38729. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38730. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38731. rowComp->paintEntireComponent (g);
  38732. }
  38733. }
  38734. return snapshot;
  38735. }
  38736. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38737. {
  38738. DragAndDropContainer* const dragContainer
  38739. = DragAndDropContainer::findParentDragContainerFor (this);
  38740. if (dragContainer != 0)
  38741. {
  38742. int x, y;
  38743. Image dragImage (createSnapshotOfSelectedRows (x, y));
  38744. dragImage.multiplyAllAlphas (0.6f);
  38745. MouseEvent e2 (e.getEventRelativeTo (this));
  38746. const Point<int> p (x - e2.x, y - e2.y);
  38747. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38748. }
  38749. else
  38750. {
  38751. // to be able to do a drag-and-drop operation, the listbox needs to
  38752. // be inside a component which is also a DragAndDropContainer.
  38753. jassertfalse;
  38754. }
  38755. }
  38756. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38757. {
  38758. (void) existingComponentToUpdate;
  38759. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38760. return 0;
  38761. }
  38762. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38763. {
  38764. }
  38765. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38766. {
  38767. }
  38768. void ListBoxModel::backgroundClicked()
  38769. {
  38770. }
  38771. void ListBoxModel::selectedRowsChanged (int)
  38772. {
  38773. }
  38774. void ListBoxModel::deleteKeyPressed (int)
  38775. {
  38776. }
  38777. void ListBoxModel::returnKeyPressed (int)
  38778. {
  38779. }
  38780. void ListBoxModel::listWasScrolled()
  38781. {
  38782. }
  38783. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38784. {
  38785. return String::empty;
  38786. }
  38787. const String ListBoxModel::getTooltipForRow (int)
  38788. {
  38789. return String::empty;
  38790. }
  38791. END_JUCE_NAMESPACE
  38792. /*** End of inlined file: juce_ListBox.cpp ***/
  38793. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38794. BEGIN_JUCE_NAMESPACE
  38795. ProgressBar::ProgressBar (double& progress_)
  38796. : progress (progress_),
  38797. displayPercentage (true),
  38798. lastCallbackTime (0)
  38799. {
  38800. currentValue = jlimit (0.0, 1.0, progress);
  38801. }
  38802. ProgressBar::~ProgressBar()
  38803. {
  38804. }
  38805. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38806. {
  38807. displayPercentage = shouldDisplayPercentage;
  38808. repaint();
  38809. }
  38810. void ProgressBar::setTextToDisplay (const String& text)
  38811. {
  38812. displayPercentage = false;
  38813. displayedMessage = text;
  38814. }
  38815. void ProgressBar::lookAndFeelChanged()
  38816. {
  38817. setOpaque (findColour (backgroundColourId).isOpaque());
  38818. }
  38819. void ProgressBar::colourChanged()
  38820. {
  38821. lookAndFeelChanged();
  38822. }
  38823. void ProgressBar::paint (Graphics& g)
  38824. {
  38825. String text;
  38826. if (displayPercentage)
  38827. {
  38828. if (currentValue >= 0 && currentValue <= 1.0)
  38829. text << roundToInt (currentValue * 100.0) << '%';
  38830. }
  38831. else
  38832. {
  38833. text = displayedMessage;
  38834. }
  38835. getLookAndFeel().drawProgressBar (g, *this,
  38836. getWidth(), getHeight(),
  38837. currentValue, text);
  38838. }
  38839. void ProgressBar::visibilityChanged()
  38840. {
  38841. if (isVisible())
  38842. startTimer (30);
  38843. else
  38844. stopTimer();
  38845. }
  38846. void ProgressBar::timerCallback()
  38847. {
  38848. double newProgress = progress;
  38849. const uint32 now = Time::getMillisecondCounter();
  38850. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  38851. lastCallbackTime = now;
  38852. if (currentValue != newProgress
  38853. || newProgress < 0 || newProgress >= 1.0
  38854. || currentMessage != displayedMessage)
  38855. {
  38856. if (currentValue < newProgress
  38857. && newProgress >= 0 && newProgress < 1.0
  38858. && currentValue >= 0 && currentValue < 1.0)
  38859. {
  38860. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  38861. newProgress);
  38862. }
  38863. currentValue = newProgress;
  38864. currentMessage = displayedMessage;
  38865. repaint();
  38866. }
  38867. }
  38868. END_JUCE_NAMESPACE
  38869. /*** End of inlined file: juce_ProgressBar.cpp ***/
  38870. /*** Start of inlined file: juce_Slider.cpp ***/
  38871. BEGIN_JUCE_NAMESPACE
  38872. class SliderPopupDisplayComponent : public BubbleComponent
  38873. {
  38874. public:
  38875. SliderPopupDisplayComponent (Slider* const owner_)
  38876. : owner (owner_),
  38877. font (15.0f, Font::bold)
  38878. {
  38879. setAlwaysOnTop (true);
  38880. }
  38881. ~SliderPopupDisplayComponent()
  38882. {
  38883. }
  38884. void paintContent (Graphics& g, int w, int h)
  38885. {
  38886. g.setFont (font);
  38887. g.setColour (Colours::black);
  38888. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  38889. }
  38890. void getContentSize (int& w, int& h)
  38891. {
  38892. w = font.getStringWidth (text) + 18;
  38893. h = (int) (font.getHeight() * 1.6f);
  38894. }
  38895. void updatePosition (const String& newText)
  38896. {
  38897. if (text != newText)
  38898. {
  38899. text = newText;
  38900. repaint();
  38901. }
  38902. BubbleComponent::setPosition (owner);
  38903. }
  38904. juce_UseDebuggingNewOperator
  38905. private:
  38906. Slider* owner;
  38907. Font font;
  38908. String text;
  38909. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  38910. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  38911. };
  38912. Slider::Slider (const String& name)
  38913. : Component (name),
  38914. lastCurrentValue (0),
  38915. lastValueMin (0),
  38916. lastValueMax (0),
  38917. minimum (0),
  38918. maximum (10),
  38919. interval (0),
  38920. skewFactor (1.0),
  38921. velocityModeSensitivity (1.0),
  38922. velocityModeOffset (0.0),
  38923. velocityModeThreshold (1),
  38924. rotaryStart (float_Pi * 1.2f),
  38925. rotaryEnd (float_Pi * 2.8f),
  38926. numDecimalPlaces (7),
  38927. sliderRegionStart (0),
  38928. sliderRegionSize (1),
  38929. sliderBeingDragged (-1),
  38930. pixelsForFullDragExtent (250),
  38931. style (LinearHorizontal),
  38932. textBoxPos (TextBoxLeft),
  38933. textBoxWidth (80),
  38934. textBoxHeight (20),
  38935. incDecButtonMode (incDecButtonsNotDraggable),
  38936. editableText (true),
  38937. doubleClickToValue (false),
  38938. isVelocityBased (false),
  38939. userKeyOverridesVelocity (true),
  38940. rotaryStop (true),
  38941. incDecButtonsSideBySide (false),
  38942. sendChangeOnlyOnRelease (false),
  38943. popupDisplayEnabled (false),
  38944. menuEnabled (false),
  38945. menuShown (false),
  38946. scrollWheelEnabled (true),
  38947. snapsToMousePos (true),
  38948. valueBox (0),
  38949. incButton (0),
  38950. decButton (0),
  38951. popupDisplay (0),
  38952. parentForPopupDisplay (0)
  38953. {
  38954. setWantsKeyboardFocus (false);
  38955. setRepaintsOnMouseActivity (true);
  38956. lookAndFeelChanged();
  38957. updateText();
  38958. currentValue.addListener (this);
  38959. valueMin.addListener (this);
  38960. valueMax.addListener (this);
  38961. }
  38962. Slider::~Slider()
  38963. {
  38964. currentValue.removeListener (this);
  38965. valueMin.removeListener (this);
  38966. valueMax.removeListener (this);
  38967. popupDisplay = 0;
  38968. deleteAllChildren();
  38969. }
  38970. void Slider::handleAsyncUpdate()
  38971. {
  38972. cancelPendingUpdate();
  38973. Component::BailOutChecker checker (this);
  38974. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this);
  38975. }
  38976. void Slider::sendDragStart()
  38977. {
  38978. startedDragging();
  38979. Component::BailOutChecker checker (this);
  38980. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  38981. }
  38982. void Slider::sendDragEnd()
  38983. {
  38984. stoppedDragging();
  38985. sliderBeingDragged = -1;
  38986. Component::BailOutChecker checker (this);
  38987. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  38988. }
  38989. void Slider::addListener (SliderListener* const listener)
  38990. {
  38991. listeners.add (listener);
  38992. }
  38993. void Slider::removeListener (SliderListener* const listener)
  38994. {
  38995. listeners.remove (listener);
  38996. }
  38997. void Slider::setSliderStyle (const SliderStyle newStyle)
  38998. {
  38999. if (style != newStyle)
  39000. {
  39001. style = newStyle;
  39002. repaint();
  39003. lookAndFeelChanged();
  39004. }
  39005. }
  39006. void Slider::setRotaryParameters (const float startAngleRadians,
  39007. const float endAngleRadians,
  39008. const bool stopAtEnd)
  39009. {
  39010. // make sure the values are sensible..
  39011. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39012. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39013. jassert (rotaryStart < rotaryEnd);
  39014. rotaryStart = startAngleRadians;
  39015. rotaryEnd = endAngleRadians;
  39016. rotaryStop = stopAtEnd;
  39017. }
  39018. void Slider::setVelocityBasedMode (const bool velBased)
  39019. {
  39020. isVelocityBased = velBased;
  39021. }
  39022. void Slider::setVelocityModeParameters (const double sensitivity,
  39023. const int threshold,
  39024. const double offset,
  39025. const bool userCanPressKeyToSwapMode)
  39026. {
  39027. jassert (threshold >= 0);
  39028. jassert (sensitivity > 0);
  39029. jassert (offset >= 0);
  39030. velocityModeSensitivity = sensitivity;
  39031. velocityModeOffset = offset;
  39032. velocityModeThreshold = threshold;
  39033. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39034. }
  39035. void Slider::setSkewFactor (const double factor)
  39036. {
  39037. skewFactor = factor;
  39038. }
  39039. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39040. {
  39041. if (maximum > minimum)
  39042. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39043. / (maximum - minimum));
  39044. }
  39045. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39046. {
  39047. jassert (distanceForFullScaleDrag > 0);
  39048. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39049. }
  39050. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39051. {
  39052. if (incDecButtonMode != mode)
  39053. {
  39054. incDecButtonMode = mode;
  39055. lookAndFeelChanged();
  39056. }
  39057. }
  39058. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39059. const bool isReadOnly,
  39060. const int textEntryBoxWidth,
  39061. const int textEntryBoxHeight)
  39062. {
  39063. if (textBoxPos != newPosition
  39064. || editableText != (! isReadOnly)
  39065. || textBoxWidth != textEntryBoxWidth
  39066. || textBoxHeight != textEntryBoxHeight)
  39067. {
  39068. textBoxPos = newPosition;
  39069. editableText = ! isReadOnly;
  39070. textBoxWidth = textEntryBoxWidth;
  39071. textBoxHeight = textEntryBoxHeight;
  39072. repaint();
  39073. lookAndFeelChanged();
  39074. }
  39075. }
  39076. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39077. {
  39078. editableText = shouldBeEditable;
  39079. if (valueBox != 0)
  39080. valueBox->setEditable (shouldBeEditable && isEnabled());
  39081. }
  39082. void Slider::showTextBox()
  39083. {
  39084. jassert (editableText); // this should probably be avoided in read-only sliders.
  39085. if (valueBox != 0)
  39086. valueBox->showEditor();
  39087. }
  39088. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39089. {
  39090. if (valueBox != 0)
  39091. {
  39092. valueBox->hideEditor (discardCurrentEditorContents);
  39093. if (discardCurrentEditorContents)
  39094. updateText();
  39095. }
  39096. }
  39097. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39098. {
  39099. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39100. }
  39101. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39102. {
  39103. snapsToMousePos = shouldSnapToMouse;
  39104. }
  39105. void Slider::setPopupDisplayEnabled (const bool enabled,
  39106. Component* const parentComponentToUse)
  39107. {
  39108. popupDisplayEnabled = enabled;
  39109. parentForPopupDisplay = parentComponentToUse;
  39110. }
  39111. void Slider::colourChanged()
  39112. {
  39113. lookAndFeelChanged();
  39114. }
  39115. void Slider::lookAndFeelChanged()
  39116. {
  39117. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39118. : getTextFromValue (currentValue.getValue()));
  39119. deleteAllChildren();
  39120. valueBox = 0;
  39121. LookAndFeel& lf = getLookAndFeel();
  39122. if (textBoxPos != NoTextBox)
  39123. {
  39124. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39125. valueBox->setWantsKeyboardFocus (false);
  39126. valueBox->setText (previousTextBoxContent, false);
  39127. valueBox->setEditable (editableText && isEnabled());
  39128. valueBox->addListener (this);
  39129. if (style == LinearBar)
  39130. valueBox->addMouseListener (this, false);
  39131. valueBox->setTooltip (getTooltip());
  39132. }
  39133. if (style == IncDecButtons)
  39134. {
  39135. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39136. incButton->addButtonListener (this);
  39137. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39138. decButton->addButtonListener (this);
  39139. if (incDecButtonMode != incDecButtonsNotDraggable)
  39140. {
  39141. incButton->addMouseListener (this, false);
  39142. decButton->addMouseListener (this, false);
  39143. }
  39144. else
  39145. {
  39146. incButton->setRepeatSpeed (300, 100, 20);
  39147. incButton->addMouseListener (decButton, false);
  39148. decButton->setRepeatSpeed (300, 100, 20);
  39149. decButton->addMouseListener (incButton, false);
  39150. }
  39151. incButton->setTooltip (getTooltip());
  39152. decButton->setTooltip (getTooltip());
  39153. }
  39154. setComponentEffect (lf.getSliderEffect());
  39155. resized();
  39156. repaint();
  39157. }
  39158. void Slider::setRange (const double newMin,
  39159. const double newMax,
  39160. const double newInt)
  39161. {
  39162. if (minimum != newMin
  39163. || maximum != newMax
  39164. || interval != newInt)
  39165. {
  39166. minimum = newMin;
  39167. maximum = newMax;
  39168. interval = newInt;
  39169. // figure out the number of DPs needed to display all values at this
  39170. // interval setting.
  39171. numDecimalPlaces = 7;
  39172. if (newInt != 0)
  39173. {
  39174. int v = abs ((int) (newInt * 10000000));
  39175. while ((v % 10) == 0)
  39176. {
  39177. --numDecimalPlaces;
  39178. v /= 10;
  39179. }
  39180. }
  39181. // keep the current values inside the new range..
  39182. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39183. {
  39184. setValue (getValue(), false, false);
  39185. }
  39186. else
  39187. {
  39188. setMinValue (getMinValue(), false, false);
  39189. setMaxValue (getMaxValue(), false, false);
  39190. }
  39191. updateText();
  39192. }
  39193. }
  39194. void Slider::triggerChangeMessage (const bool synchronous)
  39195. {
  39196. if (synchronous)
  39197. handleAsyncUpdate();
  39198. else
  39199. triggerAsyncUpdate();
  39200. valueChanged();
  39201. }
  39202. void Slider::valueChanged (Value& value)
  39203. {
  39204. if (value.refersToSameSourceAs (currentValue))
  39205. {
  39206. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39207. setValue (currentValue.getValue(), false, false);
  39208. }
  39209. else if (value.refersToSameSourceAs (valueMin))
  39210. setMinValue (valueMin.getValue(), false, false, true);
  39211. else if (value.refersToSameSourceAs (valueMax))
  39212. setMaxValue (valueMax.getValue(), false, false, true);
  39213. }
  39214. double Slider::getValue() const
  39215. {
  39216. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39217. // methods to get the two values.
  39218. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39219. return currentValue.getValue();
  39220. }
  39221. void Slider::setValue (double newValue,
  39222. const bool sendUpdateMessage,
  39223. const bool sendMessageSynchronously)
  39224. {
  39225. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39226. // methods to set the two values.
  39227. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39228. newValue = constrainedValue (newValue);
  39229. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39230. {
  39231. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39232. newValue = jlimit ((double) valueMin.getValue(),
  39233. (double) valueMax.getValue(),
  39234. newValue);
  39235. }
  39236. if (newValue != lastCurrentValue)
  39237. {
  39238. if (valueBox != 0)
  39239. valueBox->hideEditor (true);
  39240. lastCurrentValue = newValue;
  39241. currentValue = newValue;
  39242. updateText();
  39243. repaint();
  39244. if (popupDisplay != 0)
  39245. {
  39246. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39247. ->updatePosition (getTextFromValue (newValue));
  39248. popupDisplay->repaint();
  39249. }
  39250. if (sendUpdateMessage)
  39251. triggerChangeMessage (sendMessageSynchronously);
  39252. }
  39253. }
  39254. double Slider::getMinValue() const
  39255. {
  39256. // The minimum value only applies to sliders that are in two- or three-value mode.
  39257. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39258. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39259. return valueMin.getValue();
  39260. }
  39261. double Slider::getMaxValue() const
  39262. {
  39263. // The maximum value only applies to sliders that are in two- or three-value mode.
  39264. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39265. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39266. return valueMax.getValue();
  39267. }
  39268. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39269. {
  39270. // The minimum value only applies to sliders that are in two- or three-value mode.
  39271. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39272. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39273. newValue = constrainedValue (newValue);
  39274. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39275. {
  39276. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39277. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39278. newValue = jmin ((double) valueMax.getValue(), newValue);
  39279. }
  39280. else
  39281. {
  39282. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39283. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39284. newValue = jmin (lastCurrentValue, newValue);
  39285. }
  39286. if (lastValueMin != newValue)
  39287. {
  39288. lastValueMin = newValue;
  39289. valueMin = newValue;
  39290. repaint();
  39291. if (popupDisplay != 0)
  39292. {
  39293. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39294. ->updatePosition (getTextFromValue (newValue));
  39295. popupDisplay->repaint();
  39296. }
  39297. if (sendUpdateMessage)
  39298. triggerChangeMessage (sendMessageSynchronously);
  39299. }
  39300. }
  39301. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39302. {
  39303. // The maximum value only applies to sliders that are in two- or three-value mode.
  39304. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39305. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39306. newValue = constrainedValue (newValue);
  39307. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39308. {
  39309. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39310. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39311. newValue = jmax ((double) valueMin.getValue(), newValue);
  39312. }
  39313. else
  39314. {
  39315. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39316. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39317. newValue = jmax (lastCurrentValue, newValue);
  39318. }
  39319. if (lastValueMax != newValue)
  39320. {
  39321. lastValueMax = newValue;
  39322. valueMax = newValue;
  39323. repaint();
  39324. if (popupDisplay != 0)
  39325. {
  39326. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39327. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39328. popupDisplay->repaint();
  39329. }
  39330. if (sendUpdateMessage)
  39331. triggerChangeMessage (sendMessageSynchronously);
  39332. }
  39333. }
  39334. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39335. const double valueToSetOnDoubleClick)
  39336. {
  39337. doubleClickToValue = isDoubleClickEnabled;
  39338. doubleClickReturnValue = valueToSetOnDoubleClick;
  39339. }
  39340. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39341. {
  39342. isEnabled_ = doubleClickToValue;
  39343. return doubleClickReturnValue;
  39344. }
  39345. void Slider::updateText()
  39346. {
  39347. if (valueBox != 0)
  39348. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39349. }
  39350. void Slider::setTextValueSuffix (const String& suffix)
  39351. {
  39352. if (textSuffix != suffix)
  39353. {
  39354. textSuffix = suffix;
  39355. updateText();
  39356. }
  39357. }
  39358. const String Slider::getTextValueSuffix() const
  39359. {
  39360. return textSuffix;
  39361. }
  39362. const String Slider::getTextFromValue (double v)
  39363. {
  39364. if (getNumDecimalPlacesToDisplay() > 0)
  39365. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39366. else
  39367. return String (roundToInt (v)) + getTextValueSuffix();
  39368. }
  39369. double Slider::getValueFromText (const String& text)
  39370. {
  39371. String t (text.trimStart());
  39372. if (t.endsWith (textSuffix))
  39373. t = t.substring (0, t.length() - textSuffix.length());
  39374. while (t.startsWithChar ('+'))
  39375. t = t.substring (1).trimStart();
  39376. return t.initialSectionContainingOnly ("0123456789.,-")
  39377. .getDoubleValue();
  39378. }
  39379. double Slider::proportionOfLengthToValue (double proportion)
  39380. {
  39381. if (skewFactor != 1.0 && proportion > 0.0)
  39382. proportion = exp (log (proportion) / skewFactor);
  39383. return minimum + (maximum - minimum) * proportion;
  39384. }
  39385. double Slider::valueToProportionOfLength (double value)
  39386. {
  39387. const double n = (value - minimum) / (maximum - minimum);
  39388. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39389. }
  39390. double Slider::snapValue (double attemptedValue, const bool)
  39391. {
  39392. return attemptedValue;
  39393. }
  39394. void Slider::startedDragging()
  39395. {
  39396. }
  39397. void Slider::stoppedDragging()
  39398. {
  39399. }
  39400. void Slider::valueChanged()
  39401. {
  39402. }
  39403. void Slider::enablementChanged()
  39404. {
  39405. repaint();
  39406. }
  39407. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39408. {
  39409. menuEnabled = menuEnabled_;
  39410. }
  39411. void Slider::setScrollWheelEnabled (const bool enabled)
  39412. {
  39413. scrollWheelEnabled = enabled;
  39414. }
  39415. void Slider::labelTextChanged (Label* label)
  39416. {
  39417. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39418. if (newValue != (double) currentValue.getValue())
  39419. {
  39420. sendDragStart();
  39421. setValue (newValue, true, true);
  39422. sendDragEnd();
  39423. }
  39424. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39425. }
  39426. void Slider::buttonClicked (Button* button)
  39427. {
  39428. if (style == IncDecButtons)
  39429. {
  39430. sendDragStart();
  39431. if (button == incButton)
  39432. setValue (snapValue (getValue() + interval, false), true, true);
  39433. else if (button == decButton)
  39434. setValue (snapValue (getValue() - interval, false), true, true);
  39435. sendDragEnd();
  39436. }
  39437. }
  39438. double Slider::constrainedValue (double value) const
  39439. {
  39440. if (interval > 0)
  39441. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  39442. if (value <= minimum || maximum <= minimum)
  39443. value = minimum;
  39444. else if (value >= maximum)
  39445. value = maximum;
  39446. return value;
  39447. }
  39448. float Slider::getLinearSliderPos (const double value)
  39449. {
  39450. double sliderPosProportional;
  39451. if (maximum > minimum)
  39452. {
  39453. if (value < minimum)
  39454. {
  39455. sliderPosProportional = 0.0;
  39456. }
  39457. else if (value > maximum)
  39458. {
  39459. sliderPosProportional = 1.0;
  39460. }
  39461. else
  39462. {
  39463. sliderPosProportional = valueToProportionOfLength (value);
  39464. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39465. }
  39466. }
  39467. else
  39468. {
  39469. sliderPosProportional = 0.5;
  39470. }
  39471. if (isVertical() || style == IncDecButtons)
  39472. sliderPosProportional = 1.0 - sliderPosProportional;
  39473. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39474. }
  39475. bool Slider::isHorizontal() const
  39476. {
  39477. return style == LinearHorizontal
  39478. || style == LinearBar
  39479. || style == TwoValueHorizontal
  39480. || style == ThreeValueHorizontal;
  39481. }
  39482. bool Slider::isVertical() const
  39483. {
  39484. return style == LinearVertical
  39485. || style == TwoValueVertical
  39486. || style == ThreeValueVertical;
  39487. }
  39488. bool Slider::incDecDragDirectionIsHorizontal() const
  39489. {
  39490. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39491. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39492. }
  39493. float Slider::getPositionOfValue (const double value)
  39494. {
  39495. if (isHorizontal() || isVertical())
  39496. {
  39497. return getLinearSliderPos (value);
  39498. }
  39499. else
  39500. {
  39501. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  39502. return 0.0f;
  39503. }
  39504. }
  39505. void Slider::paint (Graphics& g)
  39506. {
  39507. if (style != IncDecButtons)
  39508. {
  39509. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39510. {
  39511. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39512. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39513. getLookAndFeel().drawRotarySlider (g,
  39514. sliderRect.getX(),
  39515. sliderRect.getY(),
  39516. sliderRect.getWidth(),
  39517. sliderRect.getHeight(),
  39518. sliderPos,
  39519. rotaryStart, rotaryEnd,
  39520. *this);
  39521. }
  39522. else
  39523. {
  39524. getLookAndFeel().drawLinearSlider (g,
  39525. sliderRect.getX(),
  39526. sliderRect.getY(),
  39527. sliderRect.getWidth(),
  39528. sliderRect.getHeight(),
  39529. getLinearSliderPos (lastCurrentValue),
  39530. getLinearSliderPos (lastValueMin),
  39531. getLinearSliderPos (lastValueMax),
  39532. style,
  39533. *this);
  39534. }
  39535. if (style == LinearBar && valueBox == 0)
  39536. {
  39537. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39538. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39539. }
  39540. }
  39541. }
  39542. void Slider::resized()
  39543. {
  39544. int minXSpace = 0;
  39545. int minYSpace = 0;
  39546. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39547. minXSpace = 30;
  39548. else
  39549. minYSpace = 15;
  39550. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39551. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39552. if (style == LinearBar)
  39553. {
  39554. if (valueBox != 0)
  39555. valueBox->setBounds (0, 0, getWidth(), getHeight());
  39556. }
  39557. else
  39558. {
  39559. if (textBoxPos == NoTextBox)
  39560. {
  39561. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  39562. }
  39563. else if (textBoxPos == TextBoxLeft)
  39564. {
  39565. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39566. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39567. }
  39568. else if (textBoxPos == TextBoxRight)
  39569. {
  39570. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39571. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39572. }
  39573. else if (textBoxPos == TextBoxAbove)
  39574. {
  39575. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39576. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39577. }
  39578. else if (textBoxPos == TextBoxBelow)
  39579. {
  39580. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39581. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39582. }
  39583. }
  39584. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39585. if (style == LinearBar)
  39586. {
  39587. const int barIndent = 1;
  39588. sliderRegionStart = barIndent;
  39589. sliderRegionSize = getWidth() - barIndent * 2;
  39590. sliderRect.setBounds (sliderRegionStart, barIndent,
  39591. sliderRegionSize, getHeight() - barIndent * 2);
  39592. }
  39593. else if (isHorizontal())
  39594. {
  39595. sliderRegionStart = sliderRect.getX() + indent;
  39596. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39597. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39598. sliderRegionSize, sliderRect.getHeight());
  39599. }
  39600. else if (isVertical())
  39601. {
  39602. sliderRegionStart = sliderRect.getY() + indent;
  39603. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39604. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39605. sliderRect.getWidth(), sliderRegionSize);
  39606. }
  39607. else
  39608. {
  39609. sliderRegionStart = 0;
  39610. sliderRegionSize = 100;
  39611. }
  39612. if (style == IncDecButtons)
  39613. {
  39614. Rectangle<int> buttonRect (sliderRect);
  39615. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39616. buttonRect.expand (-2, 0);
  39617. else
  39618. buttonRect.expand (0, -2);
  39619. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39620. if (incDecButtonsSideBySide)
  39621. {
  39622. decButton->setBounds (buttonRect.getX(),
  39623. buttonRect.getY(),
  39624. buttonRect.getWidth() / 2,
  39625. buttonRect.getHeight());
  39626. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39627. incButton->setBounds (buttonRect.getCentreX(),
  39628. buttonRect.getY(),
  39629. buttonRect.getWidth() / 2,
  39630. buttonRect.getHeight());
  39631. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39632. }
  39633. else
  39634. {
  39635. incButton->setBounds (buttonRect.getX(),
  39636. buttonRect.getY(),
  39637. buttonRect.getWidth(),
  39638. buttonRect.getHeight() / 2);
  39639. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39640. decButton->setBounds (buttonRect.getX(),
  39641. buttonRect.getCentreY(),
  39642. buttonRect.getWidth(),
  39643. buttonRect.getHeight() / 2);
  39644. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39645. }
  39646. }
  39647. }
  39648. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39649. {
  39650. repaint();
  39651. }
  39652. void Slider::mouseDown (const MouseEvent& e)
  39653. {
  39654. mouseWasHidden = false;
  39655. incDecDragged = false;
  39656. mouseXWhenLastDragged = e.x;
  39657. mouseYWhenLastDragged = e.y;
  39658. mouseDragStartX = e.getMouseDownX();
  39659. mouseDragStartY = e.getMouseDownY();
  39660. if (isEnabled())
  39661. {
  39662. if (e.mods.isPopupMenu() && menuEnabled)
  39663. {
  39664. menuShown = true;
  39665. PopupMenu m;
  39666. m.setLookAndFeel (&getLookAndFeel());
  39667. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39668. m.addSeparator();
  39669. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39670. {
  39671. PopupMenu rotaryMenu;
  39672. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39673. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39674. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39675. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39676. }
  39677. const int r = m.show();
  39678. if (r == 1)
  39679. {
  39680. setVelocityBasedMode (! isVelocityBased);
  39681. }
  39682. else if (r == 2)
  39683. {
  39684. setSliderStyle (Rotary);
  39685. }
  39686. else if (r == 3)
  39687. {
  39688. setSliderStyle (RotaryHorizontalDrag);
  39689. }
  39690. else if (r == 4)
  39691. {
  39692. setSliderStyle (RotaryVerticalDrag);
  39693. }
  39694. }
  39695. else if (maximum > minimum)
  39696. {
  39697. menuShown = false;
  39698. if (valueBox != 0)
  39699. valueBox->hideEditor (true);
  39700. sliderBeingDragged = 0;
  39701. if (style == TwoValueHorizontal
  39702. || style == TwoValueVertical
  39703. || style == ThreeValueHorizontal
  39704. || style == ThreeValueVertical)
  39705. {
  39706. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39707. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39708. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39709. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39710. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39711. {
  39712. if (maxPosDistance <= minPosDistance)
  39713. sliderBeingDragged = 2;
  39714. else
  39715. sliderBeingDragged = 1;
  39716. }
  39717. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39718. {
  39719. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39720. sliderBeingDragged = 1;
  39721. else if (normalPosDistance >= maxPosDistance)
  39722. sliderBeingDragged = 2;
  39723. }
  39724. }
  39725. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39726. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39727. * valueToProportionOfLength (currentValue.getValue());
  39728. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39729. : ((sliderBeingDragged == 1) ? valueMin
  39730. : currentValue)).getValue();
  39731. valueOnMouseDown = valueWhenLastDragged;
  39732. if (popupDisplayEnabled)
  39733. {
  39734. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39735. popupDisplay = popup;
  39736. if (parentForPopupDisplay != 0)
  39737. {
  39738. parentForPopupDisplay->addChildComponent (popup);
  39739. }
  39740. else
  39741. {
  39742. popup->addToDesktop (0);
  39743. }
  39744. popup->setVisible (true);
  39745. }
  39746. sendDragStart();
  39747. mouseDrag (e);
  39748. }
  39749. }
  39750. }
  39751. void Slider::mouseUp (const MouseEvent&)
  39752. {
  39753. if (isEnabled()
  39754. && (! menuShown)
  39755. && (maximum > minimum)
  39756. && (style != IncDecButtons || incDecDragged))
  39757. {
  39758. restoreMouseIfHidden();
  39759. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39760. triggerChangeMessage (false);
  39761. sendDragEnd();
  39762. popupDisplay = 0;
  39763. if (style == IncDecButtons)
  39764. {
  39765. incButton->setState (Button::buttonNormal);
  39766. decButton->setState (Button::buttonNormal);
  39767. }
  39768. }
  39769. }
  39770. void Slider::restoreMouseIfHidden()
  39771. {
  39772. if (mouseWasHidden)
  39773. {
  39774. mouseWasHidden = false;
  39775. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39776. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39777. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39778. : ((sliderBeingDragged == 1) ? getMinValue()
  39779. : (double) currentValue.getValue());
  39780. Point<int> mousePos;
  39781. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39782. {
  39783. mousePos = Desktop::getLastMouseDownPosition();
  39784. if (style == RotaryHorizontalDrag)
  39785. {
  39786. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39787. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39788. }
  39789. else
  39790. {
  39791. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39792. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39793. }
  39794. }
  39795. else
  39796. {
  39797. const int pixelPos = (int) getLinearSliderPos (pos);
  39798. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39799. isVertical() ? pixelPos : (getHeight() / 2)));
  39800. }
  39801. Desktop::setMousePosition (mousePos);
  39802. }
  39803. }
  39804. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39805. {
  39806. if (isEnabled()
  39807. && style != IncDecButtons
  39808. && style != Rotary
  39809. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  39810. {
  39811. restoreMouseIfHidden();
  39812. }
  39813. }
  39814. static double smallestAngleBetween (double a1, double a2)
  39815. {
  39816. return jmin (std::abs (a1 - a2),
  39817. std::abs (a1 + double_Pi * 2.0 - a2),
  39818. std::abs (a2 + double_Pi * 2.0 - a1));
  39819. }
  39820. void Slider::mouseDrag (const MouseEvent& e)
  39821. {
  39822. if (isEnabled()
  39823. && (! menuShown)
  39824. && (maximum > minimum))
  39825. {
  39826. if (style == Rotary)
  39827. {
  39828. int dx = e.x - sliderRect.getCentreX();
  39829. int dy = e.y - sliderRect.getCentreY();
  39830. if (dx * dx + dy * dy > 25)
  39831. {
  39832. double angle = std::atan2 ((double) dx, (double) -dy);
  39833. while (angle < 0.0)
  39834. angle += double_Pi * 2.0;
  39835. if (rotaryStop && ! e.mouseWasClicked())
  39836. {
  39837. if (std::abs (angle - lastAngle) > double_Pi)
  39838. {
  39839. if (angle >= lastAngle)
  39840. angle -= double_Pi * 2.0;
  39841. else
  39842. angle += double_Pi * 2.0;
  39843. }
  39844. if (angle >= lastAngle)
  39845. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  39846. else
  39847. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  39848. }
  39849. else
  39850. {
  39851. while (angle < rotaryStart)
  39852. angle += double_Pi * 2.0;
  39853. if (angle > rotaryEnd)
  39854. {
  39855. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  39856. angle = rotaryStart;
  39857. else
  39858. angle = rotaryEnd;
  39859. }
  39860. }
  39861. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  39862. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  39863. lastAngle = angle;
  39864. }
  39865. }
  39866. else
  39867. {
  39868. if (style == LinearBar && e.mouseWasClicked()
  39869. && valueBox != 0 && valueBox->isEditable())
  39870. return;
  39871. if (style == IncDecButtons && ! incDecDragged)
  39872. {
  39873. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  39874. return;
  39875. incDecDragged = true;
  39876. mouseDragStartX = e.x;
  39877. mouseDragStartY = e.y;
  39878. }
  39879. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  39880. : false))
  39881. || ((maximum - minimum) / sliderRegionSize < interval))
  39882. {
  39883. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  39884. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  39885. if (style == RotaryHorizontalDrag
  39886. || style == RotaryVerticalDrag
  39887. || style == IncDecButtons
  39888. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  39889. && ! snapsToMousePos))
  39890. {
  39891. const int mouseDiff = (style == RotaryHorizontalDrag
  39892. || style == LinearHorizontal
  39893. || style == LinearBar
  39894. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39895. ? e.x - mouseDragStartX
  39896. : mouseDragStartY - e.y;
  39897. double newPos = valueToProportionOfLength (valueOnMouseDown)
  39898. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  39899. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  39900. if (style == IncDecButtons)
  39901. {
  39902. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  39903. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  39904. }
  39905. }
  39906. else
  39907. {
  39908. if (isVertical())
  39909. scaledMousePos = 1.0 - scaledMousePos;
  39910. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  39911. }
  39912. }
  39913. else
  39914. {
  39915. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  39916. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39917. ? e.x - mouseXWhenLastDragged
  39918. : e.y - mouseYWhenLastDragged;
  39919. const double maxSpeed = jmax (200, sliderRegionSize);
  39920. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  39921. if (speed != 0)
  39922. {
  39923. speed = 0.2 * velocityModeSensitivity
  39924. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  39925. + jmax (0.0, (double) (speed - velocityModeThreshold))
  39926. / maxSpeed))));
  39927. if (mouseDiff < 0)
  39928. speed = -speed;
  39929. if (isVertical() || style == RotaryVerticalDrag
  39930. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  39931. speed = -speed;
  39932. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  39933. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  39934. e.source.enableUnboundedMouseMovement (true, false);
  39935. mouseWasHidden = true;
  39936. }
  39937. }
  39938. }
  39939. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  39940. if (sliderBeingDragged == 0)
  39941. {
  39942. setValue (snapValue (valueWhenLastDragged, true),
  39943. ! sendChangeOnlyOnRelease, true);
  39944. }
  39945. else if (sliderBeingDragged == 1)
  39946. {
  39947. setMinValue (snapValue (valueWhenLastDragged, true),
  39948. ! sendChangeOnlyOnRelease, false, true);
  39949. if (e.mods.isShiftDown())
  39950. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  39951. else
  39952. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39953. }
  39954. else
  39955. {
  39956. jassert (sliderBeingDragged == 2);
  39957. setMaxValue (snapValue (valueWhenLastDragged, true),
  39958. ! sendChangeOnlyOnRelease, false, true);
  39959. if (e.mods.isShiftDown())
  39960. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  39961. else
  39962. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39963. }
  39964. mouseXWhenLastDragged = e.x;
  39965. mouseYWhenLastDragged = e.y;
  39966. }
  39967. }
  39968. void Slider::mouseDoubleClick (const MouseEvent&)
  39969. {
  39970. if (doubleClickToValue
  39971. && isEnabled()
  39972. && style != IncDecButtons
  39973. && minimum <= doubleClickReturnValue
  39974. && maximum >= doubleClickReturnValue)
  39975. {
  39976. sendDragStart();
  39977. setValue (doubleClickReturnValue, true, true);
  39978. sendDragEnd();
  39979. }
  39980. }
  39981. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39982. {
  39983. if (scrollWheelEnabled && isEnabled()
  39984. && style != TwoValueHorizontal
  39985. && style != TwoValueVertical)
  39986. {
  39987. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  39988. {
  39989. if (valueBox != 0)
  39990. valueBox->hideEditor (false);
  39991. const double value = (double) currentValue.getValue();
  39992. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  39993. const double currentPos = valueToProportionOfLength (value);
  39994. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  39995. double delta = (newValue != value)
  39996. ? jmax (std::abs (newValue - value), interval) : 0;
  39997. if (value > newValue)
  39998. delta = -delta;
  39999. sendDragStart();
  40000. setValue (snapValue (value + delta, false), true, true);
  40001. sendDragEnd();
  40002. }
  40003. }
  40004. else
  40005. {
  40006. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40007. }
  40008. }
  40009. void SliderListener::sliderDragStarted (Slider*)
  40010. {
  40011. }
  40012. void SliderListener::sliderDragEnded (Slider*)
  40013. {
  40014. }
  40015. END_JUCE_NAMESPACE
  40016. /*** End of inlined file: juce_Slider.cpp ***/
  40017. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40018. BEGIN_JUCE_NAMESPACE
  40019. class DragOverlayComp : public Component
  40020. {
  40021. public:
  40022. DragOverlayComp (const Image& image_)
  40023. : image (image_)
  40024. {
  40025. image.duplicateIfShared();
  40026. image.multiplyAllAlphas (0.8f);
  40027. setAlwaysOnTop (true);
  40028. }
  40029. ~DragOverlayComp()
  40030. {
  40031. }
  40032. void paint (Graphics& g)
  40033. {
  40034. g.drawImageAt (image, 0, 0);
  40035. }
  40036. private:
  40037. Image image;
  40038. DragOverlayComp (const DragOverlayComp&);
  40039. DragOverlayComp& operator= (const DragOverlayComp&);
  40040. };
  40041. TableHeaderComponent::TableHeaderComponent()
  40042. : columnsChanged (false),
  40043. columnsResized (false),
  40044. sortChanged (false),
  40045. menuActive (true),
  40046. stretchToFit (false),
  40047. columnIdBeingResized (0),
  40048. columnIdBeingDragged (0),
  40049. columnIdUnderMouse (0),
  40050. lastDeliberateWidth (0)
  40051. {
  40052. }
  40053. TableHeaderComponent::~TableHeaderComponent()
  40054. {
  40055. dragOverlayComp = 0;
  40056. }
  40057. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40058. {
  40059. menuActive = hasMenu;
  40060. }
  40061. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40062. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40063. {
  40064. if (onlyCountVisibleColumns)
  40065. {
  40066. int num = 0;
  40067. for (int i = columns.size(); --i >= 0;)
  40068. if (columns.getUnchecked(i)->isVisible())
  40069. ++num;
  40070. return num;
  40071. }
  40072. else
  40073. {
  40074. return columns.size();
  40075. }
  40076. }
  40077. const String TableHeaderComponent::getColumnName (const int columnId) const
  40078. {
  40079. const ColumnInfo* const ci = getInfoForId (columnId);
  40080. return ci != 0 ? ci->name : String::empty;
  40081. }
  40082. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40083. {
  40084. ColumnInfo* const ci = getInfoForId (columnId);
  40085. if (ci != 0 && ci->name != newName)
  40086. {
  40087. ci->name = newName;
  40088. sendColumnsChanged();
  40089. }
  40090. }
  40091. void TableHeaderComponent::addColumn (const String& columnName,
  40092. const int columnId,
  40093. const int width,
  40094. const int minimumWidth,
  40095. const int maximumWidth,
  40096. const int propertyFlags,
  40097. const int insertIndex)
  40098. {
  40099. // can't have a duplicate or null ID!
  40100. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40101. jassert (width > 0);
  40102. ColumnInfo* const ci = new ColumnInfo();
  40103. ci->name = columnName;
  40104. ci->id = columnId;
  40105. ci->width = width;
  40106. ci->lastDeliberateWidth = width;
  40107. ci->minimumWidth = minimumWidth;
  40108. ci->maximumWidth = maximumWidth;
  40109. if (ci->maximumWidth < 0)
  40110. ci->maximumWidth = std::numeric_limits<int>::max();
  40111. jassert (ci->maximumWidth >= ci->minimumWidth);
  40112. ci->propertyFlags = propertyFlags;
  40113. columns.insert (insertIndex, ci);
  40114. sendColumnsChanged();
  40115. }
  40116. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40117. {
  40118. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40119. if (index >= 0)
  40120. {
  40121. columns.remove (index);
  40122. sortChanged = true;
  40123. sendColumnsChanged();
  40124. }
  40125. }
  40126. void TableHeaderComponent::removeAllColumns()
  40127. {
  40128. if (columns.size() > 0)
  40129. {
  40130. columns.clear();
  40131. sendColumnsChanged();
  40132. }
  40133. }
  40134. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40135. {
  40136. const int currentIndex = getIndexOfColumnId (columnId, false);
  40137. newIndex = visibleIndexToTotalIndex (newIndex);
  40138. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40139. {
  40140. columns.move (currentIndex, newIndex);
  40141. sendColumnsChanged();
  40142. }
  40143. }
  40144. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40145. {
  40146. const ColumnInfo* const ci = getInfoForId (columnId);
  40147. return ci != 0 ? ci->width : 0;
  40148. }
  40149. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40150. {
  40151. ColumnInfo* const ci = getInfoForId (columnId);
  40152. if (ci != 0 && ci->width != newWidth)
  40153. {
  40154. const int numColumns = getNumColumns (true);
  40155. ci->lastDeliberateWidth = ci->width
  40156. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40157. if (stretchToFit)
  40158. {
  40159. const int index = getIndexOfColumnId (columnId, true) + 1;
  40160. if (((unsigned int) index) < (unsigned int) numColumns)
  40161. {
  40162. const int x = getColumnPosition (index).getX();
  40163. if (lastDeliberateWidth == 0)
  40164. lastDeliberateWidth = getTotalWidth();
  40165. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40166. }
  40167. }
  40168. repaint();
  40169. columnsResized = true;
  40170. triggerAsyncUpdate();
  40171. }
  40172. }
  40173. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40174. {
  40175. int n = 0;
  40176. for (int i = 0; i < columns.size(); ++i)
  40177. {
  40178. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40179. {
  40180. if (columns.getUnchecked(i)->id == columnId)
  40181. return n;
  40182. ++n;
  40183. }
  40184. }
  40185. return -1;
  40186. }
  40187. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40188. {
  40189. if (onlyCountVisibleColumns)
  40190. index = visibleIndexToTotalIndex (index);
  40191. const ColumnInfo* const ci = columns [index];
  40192. return (ci != 0) ? ci->id : 0;
  40193. }
  40194. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40195. {
  40196. int x = 0, width = 0, n = 0;
  40197. for (int i = 0; i < columns.size(); ++i)
  40198. {
  40199. x += width;
  40200. if (columns.getUnchecked(i)->isVisible())
  40201. {
  40202. width = columns.getUnchecked(i)->width;
  40203. if (n++ == index)
  40204. break;
  40205. }
  40206. else
  40207. {
  40208. width = 0;
  40209. }
  40210. }
  40211. return Rectangle<int> (x, 0, width, getHeight());
  40212. }
  40213. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40214. {
  40215. if (xToFind >= 0)
  40216. {
  40217. int x = 0;
  40218. for (int i = 0; i < columns.size(); ++i)
  40219. {
  40220. const ColumnInfo* const ci = columns.getUnchecked(i);
  40221. if (ci->isVisible())
  40222. {
  40223. x += ci->width;
  40224. if (xToFind < x)
  40225. return ci->id;
  40226. }
  40227. }
  40228. }
  40229. return 0;
  40230. }
  40231. int TableHeaderComponent::getTotalWidth() const
  40232. {
  40233. int w = 0;
  40234. for (int i = columns.size(); --i >= 0;)
  40235. if (columns.getUnchecked(i)->isVisible())
  40236. w += columns.getUnchecked(i)->width;
  40237. return w;
  40238. }
  40239. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40240. {
  40241. stretchToFit = shouldStretchToFit;
  40242. lastDeliberateWidth = getTotalWidth();
  40243. resized();
  40244. }
  40245. bool TableHeaderComponent::isStretchToFitActive() const
  40246. {
  40247. return stretchToFit;
  40248. }
  40249. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40250. {
  40251. if (stretchToFit && getWidth() > 0
  40252. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40253. {
  40254. lastDeliberateWidth = targetTotalWidth;
  40255. resizeColumnsToFit (0, targetTotalWidth);
  40256. }
  40257. }
  40258. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40259. {
  40260. targetTotalWidth = jmax (targetTotalWidth, 0);
  40261. StretchableObjectResizer sor;
  40262. int i;
  40263. for (i = firstColumnIndex; i < columns.size(); ++i)
  40264. {
  40265. ColumnInfo* const ci = columns.getUnchecked(i);
  40266. if (ci->isVisible())
  40267. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40268. }
  40269. sor.resizeToFit (targetTotalWidth);
  40270. int visIndex = 0;
  40271. for (i = firstColumnIndex; i < columns.size(); ++i)
  40272. {
  40273. ColumnInfo* const ci = columns.getUnchecked(i);
  40274. if (ci->isVisible())
  40275. {
  40276. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40277. (int) std::floor (sor.getItemSize (visIndex++)));
  40278. if (newWidth != ci->width)
  40279. {
  40280. ci->width = newWidth;
  40281. repaint();
  40282. columnsResized = true;
  40283. triggerAsyncUpdate();
  40284. }
  40285. }
  40286. }
  40287. }
  40288. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40289. {
  40290. ColumnInfo* const ci = getInfoForId (columnId);
  40291. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40292. {
  40293. if (shouldBeVisible)
  40294. ci->propertyFlags |= visible;
  40295. else
  40296. ci->propertyFlags &= ~visible;
  40297. sendColumnsChanged();
  40298. resized();
  40299. }
  40300. }
  40301. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40302. {
  40303. const ColumnInfo* const ci = getInfoForId (columnId);
  40304. return ci != 0 && ci->isVisible();
  40305. }
  40306. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40307. {
  40308. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40309. {
  40310. for (int i = columns.size(); --i >= 0;)
  40311. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40312. ColumnInfo* const ci = getInfoForId (columnId);
  40313. if (ci != 0)
  40314. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40315. reSortTable();
  40316. }
  40317. }
  40318. int TableHeaderComponent::getSortColumnId() const
  40319. {
  40320. for (int i = columns.size(); --i >= 0;)
  40321. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40322. return columns.getUnchecked(i)->id;
  40323. return 0;
  40324. }
  40325. bool TableHeaderComponent::isSortedForwards() const
  40326. {
  40327. for (int i = columns.size(); --i >= 0;)
  40328. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40329. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40330. return true;
  40331. }
  40332. void TableHeaderComponent::reSortTable()
  40333. {
  40334. sortChanged = true;
  40335. repaint();
  40336. triggerAsyncUpdate();
  40337. }
  40338. const String TableHeaderComponent::toString() const
  40339. {
  40340. String s;
  40341. XmlElement doc ("TABLELAYOUT");
  40342. doc.setAttribute ("sortedCol", getSortColumnId());
  40343. doc.setAttribute ("sortForwards", isSortedForwards());
  40344. for (int i = 0; i < columns.size(); ++i)
  40345. {
  40346. const ColumnInfo* const ci = columns.getUnchecked (i);
  40347. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40348. e->setAttribute ("id", ci->id);
  40349. e->setAttribute ("visible", ci->isVisible());
  40350. e->setAttribute ("width", ci->width);
  40351. }
  40352. return doc.createDocument (String::empty, true, false);
  40353. }
  40354. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40355. {
  40356. XmlDocument doc (storedVersion);
  40357. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40358. int index = 0;
  40359. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40360. {
  40361. forEachXmlChildElement (*storedXml, col)
  40362. {
  40363. const int tabId = col->getIntAttribute ("id");
  40364. ColumnInfo* const ci = getInfoForId (tabId);
  40365. if (ci != 0)
  40366. {
  40367. columns.move (columns.indexOf (ci), index);
  40368. ci->width = col->getIntAttribute ("width");
  40369. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40370. }
  40371. ++index;
  40372. }
  40373. columnsResized = true;
  40374. sendColumnsChanged();
  40375. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40376. storedXml->getBoolAttribute ("sortForwards", true));
  40377. }
  40378. }
  40379. void TableHeaderComponent::addListener (TableHeaderListener* const newListener)
  40380. {
  40381. listeners.addIfNotAlreadyThere (newListener);
  40382. }
  40383. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove)
  40384. {
  40385. listeners.removeValue (listenerToRemove);
  40386. }
  40387. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40388. {
  40389. const ColumnInfo* const ci = getInfoForId (columnId);
  40390. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40391. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40392. }
  40393. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40394. {
  40395. for (int i = 0; i < columns.size(); ++i)
  40396. {
  40397. const ColumnInfo* const ci = columns.getUnchecked(i);
  40398. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40399. menu.addItem (ci->id, ci->name,
  40400. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40401. isColumnVisible (ci->id));
  40402. }
  40403. }
  40404. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40405. {
  40406. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40407. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40408. }
  40409. void TableHeaderComponent::paint (Graphics& g)
  40410. {
  40411. LookAndFeel& lf = getLookAndFeel();
  40412. lf.drawTableHeaderBackground (g, *this);
  40413. const Rectangle<int> clip (g.getClipBounds());
  40414. int x = 0;
  40415. for (int i = 0; i < columns.size(); ++i)
  40416. {
  40417. const ColumnInfo* const ci = columns.getUnchecked(i);
  40418. if (ci->isVisible())
  40419. {
  40420. if (x + ci->width > clip.getX()
  40421. && (ci->id != columnIdBeingDragged
  40422. || dragOverlayComp == 0
  40423. || ! dragOverlayComp->isVisible()))
  40424. {
  40425. g.saveState();
  40426. g.setOrigin (x, 0);
  40427. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40428. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40429. ci->id == columnIdUnderMouse,
  40430. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40431. ci->propertyFlags);
  40432. g.restoreState();
  40433. }
  40434. x += ci->width;
  40435. if (x >= clip.getRight())
  40436. break;
  40437. }
  40438. }
  40439. }
  40440. void TableHeaderComponent::resized()
  40441. {
  40442. }
  40443. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40444. {
  40445. updateColumnUnderMouse (e.x, e.y);
  40446. }
  40447. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40448. {
  40449. updateColumnUnderMouse (e.x, e.y);
  40450. }
  40451. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40452. {
  40453. updateColumnUnderMouse (e.x, e.y);
  40454. }
  40455. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40456. {
  40457. repaint();
  40458. columnIdBeingResized = 0;
  40459. columnIdBeingDragged = 0;
  40460. if (columnIdUnderMouse != 0)
  40461. {
  40462. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40463. if (e.mods.isPopupMenu())
  40464. columnClicked (columnIdUnderMouse, e.mods);
  40465. }
  40466. if (menuActive && e.mods.isPopupMenu())
  40467. showColumnChooserMenu (columnIdUnderMouse);
  40468. }
  40469. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40470. {
  40471. if (columnIdBeingResized == 0
  40472. && columnIdBeingDragged == 0
  40473. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40474. {
  40475. dragOverlayComp = 0;
  40476. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40477. if (columnIdBeingResized != 0)
  40478. {
  40479. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40480. initialColumnWidth = ci->width;
  40481. }
  40482. else
  40483. {
  40484. beginDrag (e);
  40485. }
  40486. }
  40487. if (columnIdBeingResized != 0)
  40488. {
  40489. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40490. if (ci != 0)
  40491. {
  40492. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40493. initialColumnWidth + e.getDistanceFromDragStartX());
  40494. if (stretchToFit)
  40495. {
  40496. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40497. int minWidthOnRight = 0;
  40498. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40499. if (columns.getUnchecked (i)->isVisible())
  40500. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40501. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40502. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40503. }
  40504. setColumnWidth (columnIdBeingResized, w);
  40505. }
  40506. }
  40507. else if (columnIdBeingDragged != 0)
  40508. {
  40509. if (e.y >= -50 && e.y < getHeight() + 50)
  40510. {
  40511. if (dragOverlayComp != 0)
  40512. {
  40513. dragOverlayComp->setVisible (true);
  40514. dragOverlayComp->setBounds (jlimit (0,
  40515. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40516. e.x - draggingColumnOffset),
  40517. 0,
  40518. dragOverlayComp->getWidth(),
  40519. getHeight());
  40520. for (int i = columns.size(); --i >= 0;)
  40521. {
  40522. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40523. int newIndex = currentIndex;
  40524. if (newIndex > 0)
  40525. {
  40526. // if the previous column isn't draggable, we can't move our column
  40527. // past it, because that'd change the undraggable column's position..
  40528. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40529. if ((previous->propertyFlags & draggable) != 0)
  40530. {
  40531. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40532. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40533. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40534. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40535. {
  40536. --newIndex;
  40537. }
  40538. }
  40539. }
  40540. if (newIndex < columns.size() - 1)
  40541. {
  40542. // if the next column isn't draggable, we can't move our column
  40543. // past it, because that'd change the undraggable column's position..
  40544. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40545. if ((nextCol->propertyFlags & draggable) != 0)
  40546. {
  40547. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40548. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40549. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40550. > abs (dragOverlayComp->getRight() - rightOfNext))
  40551. {
  40552. ++newIndex;
  40553. }
  40554. }
  40555. }
  40556. if (newIndex != currentIndex)
  40557. moveColumn (columnIdBeingDragged, newIndex);
  40558. else
  40559. break;
  40560. }
  40561. }
  40562. }
  40563. else
  40564. {
  40565. endDrag (draggingColumnOriginalIndex);
  40566. }
  40567. }
  40568. }
  40569. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40570. {
  40571. if (columnIdBeingDragged == 0)
  40572. {
  40573. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40574. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40575. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40576. {
  40577. columnIdBeingDragged = 0;
  40578. }
  40579. else
  40580. {
  40581. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40582. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40583. const int temp = columnIdBeingDragged;
  40584. columnIdBeingDragged = 0;
  40585. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40586. columnIdBeingDragged = temp;
  40587. dragOverlayComp->setBounds (columnRect);
  40588. for (int i = listeners.size(); --i >= 0;)
  40589. {
  40590. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40591. i = jmin (i, listeners.size() - 1);
  40592. }
  40593. }
  40594. }
  40595. }
  40596. void TableHeaderComponent::endDrag (const int finalIndex)
  40597. {
  40598. if (columnIdBeingDragged != 0)
  40599. {
  40600. moveColumn (columnIdBeingDragged, finalIndex);
  40601. columnIdBeingDragged = 0;
  40602. repaint();
  40603. for (int i = listeners.size(); --i >= 0;)
  40604. {
  40605. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40606. i = jmin (i, listeners.size() - 1);
  40607. }
  40608. }
  40609. }
  40610. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40611. {
  40612. mouseDrag (e);
  40613. for (int i = columns.size(); --i >= 0;)
  40614. if (columns.getUnchecked (i)->isVisible())
  40615. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40616. columnIdBeingResized = 0;
  40617. repaint();
  40618. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40619. updateColumnUnderMouse (e.x, e.y);
  40620. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40621. columnClicked (columnIdUnderMouse, e.mods);
  40622. dragOverlayComp = 0;
  40623. }
  40624. const MouseCursor TableHeaderComponent::getMouseCursor()
  40625. {
  40626. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40627. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40628. return Component::getMouseCursor();
  40629. }
  40630. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40631. {
  40632. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40633. }
  40634. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40635. {
  40636. for (int i = columns.size(); --i >= 0;)
  40637. if (columns.getUnchecked(i)->id == id)
  40638. return columns.getUnchecked(i);
  40639. return 0;
  40640. }
  40641. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40642. {
  40643. int n = 0;
  40644. for (int i = 0; i < columns.size(); ++i)
  40645. {
  40646. if (columns.getUnchecked(i)->isVisible())
  40647. {
  40648. if (n == visibleIndex)
  40649. return i;
  40650. ++n;
  40651. }
  40652. }
  40653. return -1;
  40654. }
  40655. void TableHeaderComponent::sendColumnsChanged()
  40656. {
  40657. if (stretchToFit && lastDeliberateWidth > 0)
  40658. resizeAllColumnsToFit (lastDeliberateWidth);
  40659. repaint();
  40660. columnsChanged = true;
  40661. triggerAsyncUpdate();
  40662. }
  40663. void TableHeaderComponent::handleAsyncUpdate()
  40664. {
  40665. const bool changed = columnsChanged || sortChanged;
  40666. const bool sized = columnsResized || changed;
  40667. const bool sorted = sortChanged;
  40668. columnsChanged = false;
  40669. columnsResized = false;
  40670. sortChanged = false;
  40671. if (sorted)
  40672. {
  40673. for (int i = listeners.size(); --i >= 0;)
  40674. {
  40675. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40676. i = jmin (i, listeners.size() - 1);
  40677. }
  40678. }
  40679. if (changed)
  40680. {
  40681. for (int i = listeners.size(); --i >= 0;)
  40682. {
  40683. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40684. i = jmin (i, listeners.size() - 1);
  40685. }
  40686. }
  40687. if (sized)
  40688. {
  40689. for (int i = listeners.size(); --i >= 0;)
  40690. {
  40691. listeners.getUnchecked(i)->tableColumnsResized (this);
  40692. i = jmin (i, listeners.size() - 1);
  40693. }
  40694. }
  40695. }
  40696. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40697. {
  40698. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40699. {
  40700. const int draggableDistance = 3;
  40701. int x = 0;
  40702. for (int i = 0; i < columns.size(); ++i)
  40703. {
  40704. const ColumnInfo* const ci = columns.getUnchecked(i);
  40705. if (ci->isVisible())
  40706. {
  40707. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40708. && (ci->propertyFlags & resizable) != 0)
  40709. return ci->id;
  40710. x += ci->width;
  40711. }
  40712. }
  40713. }
  40714. return 0;
  40715. }
  40716. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40717. {
  40718. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40719. ? getColumnIdAtX (x) : 0;
  40720. if (newCol != columnIdUnderMouse)
  40721. {
  40722. columnIdUnderMouse = newCol;
  40723. repaint();
  40724. }
  40725. }
  40726. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40727. {
  40728. PopupMenu m;
  40729. addMenuItems (m, columnIdClicked);
  40730. if (m.getNumItems() > 0)
  40731. {
  40732. m.setLookAndFeel (&getLookAndFeel());
  40733. const int result = m.show();
  40734. if (result != 0)
  40735. reactToMenuItem (result, columnIdClicked);
  40736. }
  40737. }
  40738. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40739. {
  40740. }
  40741. END_JUCE_NAMESPACE
  40742. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40743. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40744. BEGIN_JUCE_NAMESPACE
  40745. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40746. class TableListRowComp : public Component,
  40747. public TooltipClient
  40748. {
  40749. public:
  40750. TableListRowComp (TableListBox& owner_)
  40751. : owner (owner_),
  40752. row (-1),
  40753. isSelected (false)
  40754. {
  40755. }
  40756. ~TableListRowComp()
  40757. {
  40758. deleteAllChildren();
  40759. }
  40760. void paint (Graphics& g)
  40761. {
  40762. TableListBoxModel* const model = owner.getModel();
  40763. if (model != 0)
  40764. {
  40765. const TableHeaderComponent* const header = owner.getHeader();
  40766. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40767. const int numColumns = header->getNumColumns (true);
  40768. for (int i = 0; i < numColumns; ++i)
  40769. {
  40770. if (! columnsWithComponents [i])
  40771. {
  40772. const int columnId = header->getColumnIdOfIndex (i, true);
  40773. Rectangle<int> columnRect (header->getColumnPosition (i));
  40774. columnRect.setSize (columnRect.getWidth(), getHeight());
  40775. g.saveState();
  40776. g.reduceClipRegion (columnRect);
  40777. g.setOrigin (columnRect.getX(), 0);
  40778. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40779. g.restoreState();
  40780. }
  40781. }
  40782. }
  40783. }
  40784. void update (const int newRow, const bool isNowSelected)
  40785. {
  40786. if (newRow != row || isNowSelected != isSelected)
  40787. {
  40788. row = newRow;
  40789. isSelected = isNowSelected;
  40790. repaint();
  40791. }
  40792. if (row < owner.getNumRows())
  40793. {
  40794. jassert (row >= 0);
  40795. const Identifier tagPropertyName ("_tableLastUseNum");
  40796. const int newTag = Random::getSystemRandom().nextInt();
  40797. const TableHeaderComponent* const header = owner.getHeader();
  40798. const int numColumns = header->getNumColumns (true);
  40799. int i;
  40800. columnsWithComponents.clear();
  40801. if (owner.getModel() != 0)
  40802. {
  40803. for (i = 0; i < numColumns; ++i)
  40804. {
  40805. const int columnId = header->getColumnIdOfIndex (i, true);
  40806. Component* const newComp
  40807. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  40808. findChildComponentForColumn (columnId));
  40809. if (newComp != 0)
  40810. {
  40811. addAndMakeVisible (newComp);
  40812. newComp->getProperties().set (tagPropertyName, newTag);
  40813. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  40814. const Rectangle<int> columnRect (header->getColumnPosition (i));
  40815. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40816. columnsWithComponents.setBit (i);
  40817. }
  40818. }
  40819. }
  40820. for (i = getNumChildComponents(); --i >= 0;)
  40821. {
  40822. Component* const c = getChildComponent (i);
  40823. if ((int) c->getProperties() [tagPropertyName] != newTag)
  40824. delete c;
  40825. }
  40826. }
  40827. else
  40828. {
  40829. columnsWithComponents.clear();
  40830. deleteAllChildren();
  40831. }
  40832. }
  40833. void resized()
  40834. {
  40835. for (int i = getNumChildComponents(); --i >= 0;)
  40836. {
  40837. Component* const c = getChildComponent (i);
  40838. const int columnId = c->getProperties() [tableColumnPropertyTag];
  40839. if (columnId != 0)
  40840. {
  40841. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  40842. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40843. }
  40844. }
  40845. }
  40846. void mouseDown (const MouseEvent& e)
  40847. {
  40848. isDragging = false;
  40849. selectRowOnMouseUp = false;
  40850. if (isEnabled())
  40851. {
  40852. if (! isSelected)
  40853. {
  40854. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40855. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40856. if (columnId != 0 && owner.getModel() != 0)
  40857. owner.getModel()->cellClicked (row, columnId, e);
  40858. }
  40859. else
  40860. {
  40861. selectRowOnMouseUp = true;
  40862. }
  40863. }
  40864. }
  40865. void mouseDrag (const MouseEvent& e)
  40866. {
  40867. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  40868. {
  40869. const SparseSet<int> selectedRows (owner.getSelectedRows());
  40870. if (selectedRows.size() > 0)
  40871. {
  40872. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  40873. if (dragDescription.isNotEmpty())
  40874. {
  40875. isDragging = true;
  40876. owner.startDragAndDrop (e, dragDescription);
  40877. }
  40878. }
  40879. }
  40880. }
  40881. void mouseUp (const MouseEvent& e)
  40882. {
  40883. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  40884. {
  40885. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40886. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40887. if (columnId != 0 && owner.getModel() != 0)
  40888. owner.getModel()->cellClicked (row, columnId, e);
  40889. }
  40890. }
  40891. void mouseDoubleClick (const MouseEvent& e)
  40892. {
  40893. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40894. if (columnId != 0 && owner.getModel() != 0)
  40895. owner.getModel()->cellDoubleClicked (row, columnId, e);
  40896. }
  40897. const String getTooltip()
  40898. {
  40899. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  40900. if (columnId != 0 && owner.getModel() != 0)
  40901. return owner.getModel()->getCellTooltip (row, columnId);
  40902. return String::empty;
  40903. }
  40904. juce_UseDebuggingNewOperator
  40905. private:
  40906. TableListBox& owner;
  40907. int row;
  40908. bool isSelected, isDragging, selectRowOnMouseUp;
  40909. BigInteger columnsWithComponents;
  40910. Component* findChildComponentForColumn (const int columnId) const
  40911. {
  40912. for (int i = getNumChildComponents(); --i >= 0;)
  40913. {
  40914. Component* const c = getChildComponent (i);
  40915. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  40916. return c;
  40917. }
  40918. return 0;
  40919. }
  40920. TableListRowComp (const TableListRowComp&);
  40921. TableListRowComp& operator= (const TableListRowComp&);
  40922. };
  40923. class TableListBoxHeader : public TableHeaderComponent
  40924. {
  40925. public:
  40926. TableListBoxHeader (TableListBox& owner_)
  40927. : owner (owner_)
  40928. {
  40929. }
  40930. ~TableListBoxHeader()
  40931. {
  40932. }
  40933. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  40934. {
  40935. if (owner.isAutoSizeMenuOptionShown())
  40936. {
  40937. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  40938. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  40939. menu.addSeparator();
  40940. }
  40941. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  40942. }
  40943. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  40944. {
  40945. if (menuReturnId == 0xf836743)
  40946. {
  40947. owner.autoSizeColumn (columnIdClicked);
  40948. }
  40949. else if (menuReturnId == 0xf836744)
  40950. {
  40951. owner.autoSizeAllColumns();
  40952. }
  40953. else
  40954. {
  40955. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  40956. }
  40957. }
  40958. juce_UseDebuggingNewOperator
  40959. private:
  40960. TableListBox& owner;
  40961. TableListBoxHeader (const TableListBoxHeader&);
  40962. TableListBoxHeader& operator= (const TableListBoxHeader&);
  40963. };
  40964. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  40965. : ListBox (name, 0),
  40966. model (model_),
  40967. autoSizeOptionsShown (true)
  40968. {
  40969. ListBox::model = this;
  40970. header = new TableListBoxHeader (*this);
  40971. header->setSize (100, 28);
  40972. header->addListener (this);
  40973. setHeaderComponent (header);
  40974. }
  40975. TableListBox::~TableListBox()
  40976. {
  40977. deleteAllChildren();
  40978. }
  40979. void TableListBox::setModel (TableListBoxModel* const newModel)
  40980. {
  40981. if (model != newModel)
  40982. {
  40983. model = newModel;
  40984. updateContent();
  40985. }
  40986. }
  40987. int TableListBox::getHeaderHeight() const
  40988. {
  40989. return header->getHeight();
  40990. }
  40991. void TableListBox::setHeaderHeight (const int newHeight)
  40992. {
  40993. header->setSize (header->getWidth(), newHeight);
  40994. resized();
  40995. }
  40996. void TableListBox::autoSizeColumn (const int columnId)
  40997. {
  40998. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  40999. if (width > 0)
  41000. header->setColumnWidth (columnId, width);
  41001. }
  41002. void TableListBox::autoSizeAllColumns()
  41003. {
  41004. for (int i = 0; i < header->getNumColumns (true); ++i)
  41005. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41006. }
  41007. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41008. {
  41009. autoSizeOptionsShown = shouldBeShown;
  41010. }
  41011. bool TableListBox::isAutoSizeMenuOptionShown() const
  41012. {
  41013. return autoSizeOptionsShown;
  41014. }
  41015. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41016. const int rowNumber,
  41017. const bool relativeToComponentTopLeft) const
  41018. {
  41019. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41020. if (relativeToComponentTopLeft)
  41021. headerCell.translate (header->getX(), 0);
  41022. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41023. return Rectangle<int> (headerCell.getX(), row.getY(),
  41024. headerCell.getWidth(), row.getHeight());
  41025. }
  41026. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41027. {
  41028. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41029. if (scrollbar != 0)
  41030. {
  41031. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41032. double x = scrollbar->getCurrentRangeStart();
  41033. const double w = scrollbar->getCurrentRangeSize();
  41034. if (pos.getX() < x)
  41035. x = pos.getX();
  41036. else if (pos.getRight() > x + w)
  41037. x += jmax (0.0, pos.getRight() - (x + w));
  41038. scrollbar->setCurrentRangeStart (x);
  41039. }
  41040. }
  41041. int TableListBox::getNumRows()
  41042. {
  41043. return model != 0 ? model->getNumRows() : 0;
  41044. }
  41045. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41046. {
  41047. }
  41048. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41049. {
  41050. if (existingComponentToUpdate == 0)
  41051. existingComponentToUpdate = new TableListRowComp (*this);
  41052. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41053. return existingComponentToUpdate;
  41054. }
  41055. void TableListBox::selectedRowsChanged (int row)
  41056. {
  41057. if (model != 0)
  41058. model->selectedRowsChanged (row);
  41059. }
  41060. void TableListBox::deleteKeyPressed (int row)
  41061. {
  41062. if (model != 0)
  41063. model->deleteKeyPressed (row);
  41064. }
  41065. void TableListBox::returnKeyPressed (int row)
  41066. {
  41067. if (model != 0)
  41068. model->returnKeyPressed (row);
  41069. }
  41070. void TableListBox::backgroundClicked()
  41071. {
  41072. if (model != 0)
  41073. model->backgroundClicked();
  41074. }
  41075. void TableListBox::listWasScrolled()
  41076. {
  41077. if (model != 0)
  41078. model->listWasScrolled();
  41079. }
  41080. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41081. {
  41082. setMinimumContentWidth (header->getTotalWidth());
  41083. repaint();
  41084. updateColumnComponents();
  41085. }
  41086. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41087. {
  41088. setMinimumContentWidth (header->getTotalWidth());
  41089. repaint();
  41090. updateColumnComponents();
  41091. }
  41092. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41093. {
  41094. if (model != 0)
  41095. model->sortOrderChanged (header->getSortColumnId(),
  41096. header->isSortedForwards());
  41097. }
  41098. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41099. {
  41100. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41101. repaint();
  41102. }
  41103. void TableListBox::resized()
  41104. {
  41105. ListBox::resized();
  41106. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41107. setMinimumContentWidth (header->getTotalWidth());
  41108. }
  41109. void TableListBox::updateColumnComponents() const
  41110. {
  41111. const int firstRow = getRowContainingPosition (0, 0);
  41112. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41113. {
  41114. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41115. if (rowComp != 0)
  41116. rowComp->resized();
  41117. }
  41118. }
  41119. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41120. {
  41121. }
  41122. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41123. {
  41124. }
  41125. void TableListBoxModel::backgroundClicked()
  41126. {
  41127. }
  41128. void TableListBoxModel::sortOrderChanged (int, const bool)
  41129. {
  41130. }
  41131. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41132. {
  41133. return 0;
  41134. }
  41135. void TableListBoxModel::selectedRowsChanged (int)
  41136. {
  41137. }
  41138. void TableListBoxModel::deleteKeyPressed (int)
  41139. {
  41140. }
  41141. void TableListBoxModel::returnKeyPressed (int)
  41142. {
  41143. }
  41144. void TableListBoxModel::listWasScrolled()
  41145. {
  41146. }
  41147. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41148. {
  41149. return String::empty;
  41150. }
  41151. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41152. {
  41153. return String::empty;
  41154. }
  41155. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41156. {
  41157. (void) existingComponentToUpdate;
  41158. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41159. return 0;
  41160. }
  41161. END_JUCE_NAMESPACE
  41162. /*** End of inlined file: juce_TableListBox.cpp ***/
  41163. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41164. BEGIN_JUCE_NAMESPACE
  41165. // a word or space that can't be broken down any further
  41166. struct TextAtom
  41167. {
  41168. String atomText;
  41169. float width;
  41170. uint16 numChars;
  41171. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41172. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41173. const String getText (const juce_wchar passwordCharacter) const
  41174. {
  41175. if (passwordCharacter == 0)
  41176. return atomText;
  41177. else
  41178. return String::repeatedString (String::charToString (passwordCharacter),
  41179. atomText.length());
  41180. }
  41181. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41182. {
  41183. if (passwordCharacter == 0)
  41184. return atomText.substring (0, numChars);
  41185. else if (isNewLine())
  41186. return String::empty;
  41187. else
  41188. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41189. }
  41190. };
  41191. // a run of text with a single font and colour
  41192. class TextEditor::UniformTextSection
  41193. {
  41194. public:
  41195. UniformTextSection (const String& text,
  41196. const Font& font_,
  41197. const Colour& colour_,
  41198. const juce_wchar passwordCharacter)
  41199. : font (font_),
  41200. colour (colour_)
  41201. {
  41202. initialiseAtoms (text, passwordCharacter);
  41203. }
  41204. UniformTextSection (const UniformTextSection& other)
  41205. : font (other.font),
  41206. colour (other.colour)
  41207. {
  41208. atoms.ensureStorageAllocated (other.atoms.size());
  41209. for (int i = 0; i < other.atoms.size(); ++i)
  41210. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41211. }
  41212. ~UniformTextSection()
  41213. {
  41214. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41215. }
  41216. void clear()
  41217. {
  41218. for (int i = atoms.size(); --i >= 0;)
  41219. delete getAtom(i);
  41220. atoms.clear();
  41221. }
  41222. int getNumAtoms() const
  41223. {
  41224. return atoms.size();
  41225. }
  41226. TextAtom* getAtom (const int index) const throw()
  41227. {
  41228. return atoms.getUnchecked (index);
  41229. }
  41230. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41231. {
  41232. if (other.atoms.size() > 0)
  41233. {
  41234. TextAtom* const lastAtom = atoms.getLast();
  41235. int i = 0;
  41236. if (lastAtom != 0)
  41237. {
  41238. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41239. {
  41240. TextAtom* const first = other.getAtom(0);
  41241. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41242. {
  41243. lastAtom->atomText += first->atomText;
  41244. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41245. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41246. delete first;
  41247. ++i;
  41248. }
  41249. }
  41250. }
  41251. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41252. while (i < other.atoms.size())
  41253. {
  41254. atoms.add (other.getAtom(i));
  41255. ++i;
  41256. }
  41257. }
  41258. }
  41259. UniformTextSection* split (const int indexToBreakAt,
  41260. const juce_wchar passwordCharacter)
  41261. {
  41262. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41263. font, colour,
  41264. passwordCharacter);
  41265. int index = 0;
  41266. for (int i = 0; i < atoms.size(); ++i)
  41267. {
  41268. TextAtom* const atom = getAtom(i);
  41269. const int nextIndex = index + atom->numChars;
  41270. if (index == indexToBreakAt)
  41271. {
  41272. int j;
  41273. for (j = i; j < atoms.size(); ++j)
  41274. section2->atoms.add (getAtom (j));
  41275. for (j = atoms.size(); --j >= i;)
  41276. atoms.remove (j);
  41277. break;
  41278. }
  41279. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41280. {
  41281. TextAtom* const secondAtom = new TextAtom();
  41282. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41283. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41284. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41285. section2->atoms.add (secondAtom);
  41286. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41287. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41288. atom->numChars = (uint16) (indexToBreakAt - index);
  41289. int j;
  41290. for (j = i + 1; j < atoms.size(); ++j)
  41291. section2->atoms.add (getAtom (j));
  41292. for (j = atoms.size(); --j > i;)
  41293. atoms.remove (j);
  41294. break;
  41295. }
  41296. index = nextIndex;
  41297. }
  41298. return section2;
  41299. }
  41300. void appendAllText (String::Concatenator& concatenator) const
  41301. {
  41302. for (int i = 0; i < atoms.size(); ++i)
  41303. concatenator.append (getAtom(i)->atomText);
  41304. }
  41305. void appendSubstring (String::Concatenator& concatenator,
  41306. const Range<int>& range) const
  41307. {
  41308. int index = 0;
  41309. for (int i = 0; i < atoms.size(); ++i)
  41310. {
  41311. const TextAtom* const atom = getAtom (i);
  41312. const int nextIndex = index + atom->numChars;
  41313. if (range.getStart() < nextIndex)
  41314. {
  41315. if (range.getEnd() <= index)
  41316. break;
  41317. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41318. if (! r.isEmpty())
  41319. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41320. }
  41321. index = nextIndex;
  41322. }
  41323. }
  41324. int getTotalLength() const
  41325. {
  41326. int total = 0;
  41327. for (int i = atoms.size(); --i >= 0;)
  41328. total += getAtom(i)->numChars;
  41329. return total;
  41330. }
  41331. void setFont (const Font& newFont,
  41332. const juce_wchar passwordCharacter)
  41333. {
  41334. if (font != newFont)
  41335. {
  41336. font = newFont;
  41337. for (int i = atoms.size(); --i >= 0;)
  41338. {
  41339. TextAtom* const atom = atoms.getUnchecked(i);
  41340. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41341. }
  41342. }
  41343. }
  41344. juce_UseDebuggingNewOperator
  41345. Font font;
  41346. Colour colour;
  41347. private:
  41348. Array <TextAtom*> atoms;
  41349. void initialiseAtoms (const String& textToParse,
  41350. const juce_wchar passwordCharacter)
  41351. {
  41352. int i = 0;
  41353. const int len = textToParse.length();
  41354. const juce_wchar* const text = textToParse;
  41355. while (i < len)
  41356. {
  41357. int start = i;
  41358. // create a whitespace atom unless it starts with non-ws
  41359. if (CharacterFunctions::isWhitespace (text[i])
  41360. && text[i] != '\r'
  41361. && text[i] != '\n')
  41362. {
  41363. while (i < len
  41364. && CharacterFunctions::isWhitespace (text[i])
  41365. && text[i] != '\r'
  41366. && text[i] != '\n')
  41367. {
  41368. ++i;
  41369. }
  41370. }
  41371. else
  41372. {
  41373. if (text[i] == '\r')
  41374. {
  41375. ++i;
  41376. if ((i < len) && (text[i] == '\n'))
  41377. {
  41378. ++start;
  41379. ++i;
  41380. }
  41381. }
  41382. else if (text[i] == '\n')
  41383. {
  41384. ++i;
  41385. }
  41386. else
  41387. {
  41388. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41389. ++i;
  41390. }
  41391. }
  41392. TextAtom* const atom = new TextAtom();
  41393. atom->atomText = String (text + start, i - start);
  41394. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41395. atom->numChars = (uint16) (i - start);
  41396. atoms.add (atom);
  41397. }
  41398. }
  41399. UniformTextSection& operator= (const UniformTextSection& other);
  41400. };
  41401. class TextEditor::Iterator
  41402. {
  41403. public:
  41404. Iterator (const Array <UniformTextSection*>& sections_,
  41405. const float wordWrapWidth_,
  41406. const juce_wchar passwordCharacter_)
  41407. : indexInText (0),
  41408. lineY (0),
  41409. lineHeight (0),
  41410. maxDescent (0),
  41411. atomX (0),
  41412. atomRight (0),
  41413. atom (0),
  41414. currentSection (0),
  41415. sections (sections_),
  41416. sectionIndex (0),
  41417. atomIndex (0),
  41418. wordWrapWidth (wordWrapWidth_),
  41419. passwordCharacter (passwordCharacter_)
  41420. {
  41421. jassert (wordWrapWidth_ > 0);
  41422. if (sections.size() > 0)
  41423. {
  41424. currentSection = sections.getUnchecked (sectionIndex);
  41425. if (currentSection != 0)
  41426. beginNewLine();
  41427. }
  41428. }
  41429. Iterator (const Iterator& other)
  41430. : indexInText (other.indexInText),
  41431. lineY (other.lineY),
  41432. lineHeight (other.lineHeight),
  41433. maxDescent (other.maxDescent),
  41434. atomX (other.atomX),
  41435. atomRight (other.atomRight),
  41436. atom (other.atom),
  41437. currentSection (other.currentSection),
  41438. sections (other.sections),
  41439. sectionIndex (other.sectionIndex),
  41440. atomIndex (other.atomIndex),
  41441. wordWrapWidth (other.wordWrapWidth),
  41442. passwordCharacter (other.passwordCharacter),
  41443. tempAtom (other.tempAtom)
  41444. {
  41445. }
  41446. ~Iterator()
  41447. {
  41448. }
  41449. bool next()
  41450. {
  41451. if (atom == &tempAtom)
  41452. {
  41453. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41454. if (numRemaining > 0)
  41455. {
  41456. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41457. atomX = 0;
  41458. if (tempAtom.numChars > 0)
  41459. lineY += lineHeight;
  41460. indexInText += tempAtom.numChars;
  41461. GlyphArrangement g;
  41462. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41463. int split;
  41464. for (split = 0; split < g.getNumGlyphs(); ++split)
  41465. if (shouldWrap (g.getGlyph (split).getRight()))
  41466. break;
  41467. if (split > 0 && split <= numRemaining)
  41468. {
  41469. tempAtom.numChars = (uint16) split;
  41470. tempAtom.width = g.getGlyph (split - 1).getRight();
  41471. atomRight = atomX + tempAtom.width;
  41472. return true;
  41473. }
  41474. }
  41475. }
  41476. bool forceNewLine = false;
  41477. if (sectionIndex >= sections.size())
  41478. {
  41479. moveToEndOfLastAtom();
  41480. return false;
  41481. }
  41482. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41483. {
  41484. if (atomIndex >= currentSection->getNumAtoms())
  41485. {
  41486. if (++sectionIndex >= sections.size())
  41487. {
  41488. moveToEndOfLastAtom();
  41489. return false;
  41490. }
  41491. atomIndex = 0;
  41492. currentSection = sections.getUnchecked (sectionIndex);
  41493. }
  41494. else
  41495. {
  41496. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41497. if (! lastAtom->isWhitespace())
  41498. {
  41499. // handle the case where the last atom in a section is actually part of the same
  41500. // word as the first atom of the next section...
  41501. float right = atomRight + lastAtom->width;
  41502. float lineHeight2 = lineHeight;
  41503. float maxDescent2 = maxDescent;
  41504. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41505. {
  41506. const UniformTextSection* const s = sections.getUnchecked (section);
  41507. if (s->getNumAtoms() == 0)
  41508. break;
  41509. const TextAtom* const nextAtom = s->getAtom (0);
  41510. if (nextAtom->isWhitespace())
  41511. break;
  41512. right += nextAtom->width;
  41513. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41514. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41515. if (shouldWrap (right))
  41516. {
  41517. lineHeight = lineHeight2;
  41518. maxDescent = maxDescent2;
  41519. forceNewLine = true;
  41520. break;
  41521. }
  41522. if (s->getNumAtoms() > 1)
  41523. break;
  41524. }
  41525. }
  41526. }
  41527. }
  41528. if (atom != 0)
  41529. {
  41530. atomX = atomRight;
  41531. indexInText += atom->numChars;
  41532. if (atom->isNewLine())
  41533. beginNewLine();
  41534. }
  41535. atom = currentSection->getAtom (atomIndex);
  41536. atomRight = atomX + atom->width;
  41537. ++atomIndex;
  41538. if (shouldWrap (atomRight) || forceNewLine)
  41539. {
  41540. if (atom->isWhitespace())
  41541. {
  41542. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41543. atomRight = jmin (atomRight, wordWrapWidth);
  41544. }
  41545. else
  41546. {
  41547. atomRight = atom->width;
  41548. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41549. {
  41550. tempAtom = *atom;
  41551. tempAtom.width = 0;
  41552. tempAtom.numChars = 0;
  41553. atom = &tempAtom;
  41554. if (atomX > 0)
  41555. beginNewLine();
  41556. return next();
  41557. }
  41558. beginNewLine();
  41559. return true;
  41560. }
  41561. }
  41562. return true;
  41563. }
  41564. void beginNewLine()
  41565. {
  41566. atomX = 0;
  41567. lineY += lineHeight;
  41568. int tempSectionIndex = sectionIndex;
  41569. int tempAtomIndex = atomIndex;
  41570. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41571. lineHeight = section->font.getHeight();
  41572. maxDescent = section->font.getDescent();
  41573. float x = (atom != 0) ? atom->width : 0;
  41574. while (! shouldWrap (x))
  41575. {
  41576. if (tempSectionIndex >= sections.size())
  41577. break;
  41578. bool checkSize = false;
  41579. if (tempAtomIndex >= section->getNumAtoms())
  41580. {
  41581. if (++tempSectionIndex >= sections.size())
  41582. break;
  41583. tempAtomIndex = 0;
  41584. section = sections.getUnchecked (tempSectionIndex);
  41585. checkSize = true;
  41586. }
  41587. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41588. if (nextAtom == 0)
  41589. break;
  41590. x += nextAtom->width;
  41591. if (shouldWrap (x) || nextAtom->isNewLine())
  41592. break;
  41593. if (checkSize)
  41594. {
  41595. lineHeight = jmax (lineHeight, section->font.getHeight());
  41596. maxDescent = jmax (maxDescent, section->font.getDescent());
  41597. }
  41598. ++tempAtomIndex;
  41599. }
  41600. }
  41601. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41602. {
  41603. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41604. {
  41605. if (lastSection != currentSection)
  41606. {
  41607. lastSection = currentSection;
  41608. g.setColour (currentSection->colour);
  41609. g.setFont (currentSection->font);
  41610. }
  41611. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41612. GlyphArrangement ga;
  41613. ga.addLineOfText (currentSection->font,
  41614. atom->getTrimmedText (passwordCharacter),
  41615. atomX,
  41616. (float) roundToInt (lineY + lineHeight - maxDescent));
  41617. ga.draw (g);
  41618. }
  41619. }
  41620. void drawSelection (Graphics& g,
  41621. const Range<int>& selection) const
  41622. {
  41623. const int startX = roundToInt (indexToX (selection.getStart()));
  41624. const int endX = roundToInt (indexToX (selection.getEnd()));
  41625. const int y = roundToInt (lineY);
  41626. const int nextY = roundToInt (lineY + lineHeight);
  41627. g.fillRect (startX, y, endX - startX, nextY - y);
  41628. }
  41629. void drawSelectedText (Graphics& g,
  41630. const Range<int>& selection,
  41631. const Colour& selectedTextColour) const
  41632. {
  41633. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41634. {
  41635. GlyphArrangement ga;
  41636. ga.addLineOfText (currentSection->font,
  41637. atom->getTrimmedText (passwordCharacter),
  41638. atomX,
  41639. (float) roundToInt (lineY + lineHeight - maxDescent));
  41640. if (selection.getEnd() < indexInText + atom->numChars)
  41641. {
  41642. GlyphArrangement ga2 (ga);
  41643. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41644. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41645. g.setColour (currentSection->colour);
  41646. ga2.draw (g);
  41647. }
  41648. if (selection.getStart() > indexInText)
  41649. {
  41650. GlyphArrangement ga2 (ga);
  41651. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41652. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41653. g.setColour (currentSection->colour);
  41654. ga2.draw (g);
  41655. }
  41656. g.setColour (selectedTextColour);
  41657. ga.draw (g);
  41658. }
  41659. }
  41660. float indexToX (const int indexToFind) const
  41661. {
  41662. if (indexToFind <= indexInText)
  41663. return atomX;
  41664. if (indexToFind >= indexInText + atom->numChars)
  41665. return atomRight;
  41666. GlyphArrangement g;
  41667. g.addLineOfText (currentSection->font,
  41668. atom->getText (passwordCharacter),
  41669. atomX, 0.0f);
  41670. if (indexToFind - indexInText >= g.getNumGlyphs())
  41671. return atomRight;
  41672. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41673. }
  41674. int xToIndex (const float xToFind) const
  41675. {
  41676. if (xToFind <= atomX || atom->isNewLine())
  41677. return indexInText;
  41678. if (xToFind >= atomRight)
  41679. return indexInText + atom->numChars;
  41680. GlyphArrangement g;
  41681. g.addLineOfText (currentSection->font,
  41682. atom->getText (passwordCharacter),
  41683. atomX, 0.0f);
  41684. int j;
  41685. for (j = 0; j < g.getNumGlyphs(); ++j)
  41686. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41687. break;
  41688. return indexInText + j;
  41689. }
  41690. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41691. {
  41692. while (next())
  41693. {
  41694. if (indexInText + atom->numChars > index)
  41695. {
  41696. cx = indexToX (index);
  41697. cy = lineY;
  41698. lineHeight_ = lineHeight;
  41699. return true;
  41700. }
  41701. }
  41702. cx = atomX;
  41703. cy = lineY;
  41704. lineHeight_ = lineHeight;
  41705. return false;
  41706. }
  41707. juce_UseDebuggingNewOperator
  41708. int indexInText;
  41709. float lineY, lineHeight, maxDescent;
  41710. float atomX, atomRight;
  41711. const TextAtom* atom;
  41712. const UniformTextSection* currentSection;
  41713. private:
  41714. const Array <UniformTextSection*>& sections;
  41715. int sectionIndex, atomIndex;
  41716. const float wordWrapWidth;
  41717. const juce_wchar passwordCharacter;
  41718. TextAtom tempAtom;
  41719. Iterator& operator= (const Iterator&);
  41720. void moveToEndOfLastAtom()
  41721. {
  41722. if (atom != 0)
  41723. {
  41724. atomX = atomRight;
  41725. if (atom->isNewLine())
  41726. {
  41727. atomX = 0.0f;
  41728. lineY += lineHeight;
  41729. }
  41730. }
  41731. }
  41732. bool shouldWrap (const float x) const
  41733. {
  41734. return (x - 0.0001f) >= wordWrapWidth;
  41735. }
  41736. };
  41737. class TextEditor::InsertAction : public UndoableAction
  41738. {
  41739. TextEditor& owner;
  41740. const String text;
  41741. const int insertIndex, oldCaretPos, newCaretPos;
  41742. const Font font;
  41743. const Colour colour;
  41744. InsertAction (const InsertAction&);
  41745. InsertAction& operator= (const InsertAction&);
  41746. public:
  41747. InsertAction (TextEditor& owner_,
  41748. const String& text_,
  41749. const int insertIndex_,
  41750. const Font& font_,
  41751. const Colour& colour_,
  41752. const int oldCaretPos_,
  41753. const int newCaretPos_)
  41754. : owner (owner_),
  41755. text (text_),
  41756. insertIndex (insertIndex_),
  41757. oldCaretPos (oldCaretPos_),
  41758. newCaretPos (newCaretPos_),
  41759. font (font_),
  41760. colour (colour_)
  41761. {
  41762. }
  41763. ~InsertAction()
  41764. {
  41765. }
  41766. bool perform()
  41767. {
  41768. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41769. return true;
  41770. }
  41771. bool undo()
  41772. {
  41773. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41774. return true;
  41775. }
  41776. int getSizeInUnits()
  41777. {
  41778. return text.length() + 16;
  41779. }
  41780. };
  41781. class TextEditor::RemoveAction : public UndoableAction
  41782. {
  41783. TextEditor& owner;
  41784. const Range<int> range;
  41785. const int oldCaretPos, newCaretPos;
  41786. Array <UniformTextSection*> removedSections;
  41787. RemoveAction (const RemoveAction&);
  41788. RemoveAction& operator= (const RemoveAction&);
  41789. public:
  41790. RemoveAction (TextEditor& owner_,
  41791. const Range<int> range_,
  41792. const int oldCaretPos_,
  41793. const int newCaretPos_,
  41794. const Array <UniformTextSection*>& removedSections_)
  41795. : owner (owner_),
  41796. range (range_),
  41797. oldCaretPos (oldCaretPos_),
  41798. newCaretPos (newCaretPos_),
  41799. removedSections (removedSections_)
  41800. {
  41801. }
  41802. ~RemoveAction()
  41803. {
  41804. for (int i = removedSections.size(); --i >= 0;)
  41805. {
  41806. UniformTextSection* const section = removedSections.getUnchecked (i);
  41807. section->clear();
  41808. delete section;
  41809. }
  41810. }
  41811. bool perform()
  41812. {
  41813. owner.remove (range, 0, newCaretPos);
  41814. return true;
  41815. }
  41816. bool undo()
  41817. {
  41818. owner.reinsert (range.getStart(), removedSections);
  41819. owner.moveCursorTo (oldCaretPos, false);
  41820. return true;
  41821. }
  41822. int getSizeInUnits()
  41823. {
  41824. int n = 0;
  41825. for (int i = removedSections.size(); --i >= 0;)
  41826. n += removedSections.getUnchecked (i)->getTotalLength();
  41827. return n + 16;
  41828. }
  41829. };
  41830. class TextEditor::TextHolderComponent : public Component,
  41831. public Timer,
  41832. public Value::Listener
  41833. {
  41834. public:
  41835. TextHolderComponent (TextEditor& owner_)
  41836. : owner (owner_)
  41837. {
  41838. setWantsKeyboardFocus (false);
  41839. setInterceptsMouseClicks (false, true);
  41840. owner.getTextValue().addListener (this);
  41841. }
  41842. ~TextHolderComponent()
  41843. {
  41844. owner.getTextValue().removeListener (this);
  41845. }
  41846. void paint (Graphics& g)
  41847. {
  41848. owner.drawContent (g);
  41849. }
  41850. void timerCallback()
  41851. {
  41852. owner.timerCallbackInt();
  41853. }
  41854. const MouseCursor getMouseCursor()
  41855. {
  41856. return owner.getMouseCursor();
  41857. }
  41858. void valueChanged (Value&)
  41859. {
  41860. owner.textWasChangedByValue();
  41861. }
  41862. private:
  41863. TextEditor& owner;
  41864. TextHolderComponent (const TextHolderComponent&);
  41865. TextHolderComponent& operator= (const TextHolderComponent&);
  41866. };
  41867. class TextEditorViewport : public Viewport
  41868. {
  41869. public:
  41870. TextEditorViewport (TextEditor* const owner_)
  41871. : owner (owner_),
  41872. lastWordWrapWidth (0)
  41873. {
  41874. }
  41875. ~TextEditorViewport()
  41876. {
  41877. }
  41878. void visibleAreaChanged (int, int, int, int)
  41879. {
  41880. const float wordWrapWidth = owner->getWordWrapWidth();
  41881. if (wordWrapWidth != lastWordWrapWidth)
  41882. {
  41883. lastWordWrapWidth = wordWrapWidth;
  41884. owner->updateTextHolderSize();
  41885. }
  41886. }
  41887. private:
  41888. TextEditor* const owner;
  41889. float lastWordWrapWidth;
  41890. TextEditorViewport (const TextEditorViewport&);
  41891. TextEditorViewport& operator= (const TextEditorViewport&);
  41892. };
  41893. namespace TextEditorDefs
  41894. {
  41895. const int flashSpeedIntervalMs = 380;
  41896. const int textChangeMessageId = 0x10003001;
  41897. const int returnKeyMessageId = 0x10003002;
  41898. const int escapeKeyMessageId = 0x10003003;
  41899. const int focusLossMessageId = 0x10003004;
  41900. const int maxActionsPerTransaction = 100;
  41901. }
  41902. TextEditor::TextEditor (const String& name,
  41903. const juce_wchar passwordCharacter_)
  41904. : Component (name),
  41905. borderSize (1, 1, 1, 3),
  41906. readOnly (false),
  41907. multiline (false),
  41908. wordWrap (false),
  41909. returnKeyStartsNewLine (false),
  41910. caretVisible (true),
  41911. popupMenuEnabled (true),
  41912. selectAllTextWhenFocused (false),
  41913. scrollbarVisible (true),
  41914. wasFocused (false),
  41915. caretFlashState (true),
  41916. keepCursorOnScreen (true),
  41917. tabKeyUsed (false),
  41918. menuActive (false),
  41919. valueTextNeedsUpdating (false),
  41920. cursorX (0),
  41921. cursorY (0),
  41922. cursorHeight (0),
  41923. maxTextLength (0),
  41924. leftIndent (4),
  41925. topIndent (4),
  41926. lastTransactionTime (0),
  41927. currentFont (14.0f),
  41928. totalNumChars (0),
  41929. caretPosition (0),
  41930. passwordCharacter (passwordCharacter_),
  41931. dragType (notDragging)
  41932. {
  41933. setOpaque (true);
  41934. addAndMakeVisible (viewport = new TextEditorViewport (this));
  41935. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  41936. viewport->setWantsKeyboardFocus (false);
  41937. viewport->setScrollBarsShown (false, false);
  41938. setMouseCursor (MouseCursor::IBeamCursor);
  41939. setWantsKeyboardFocus (true);
  41940. }
  41941. TextEditor::~TextEditor()
  41942. {
  41943. textValue.referTo (Value());
  41944. clearInternal (0);
  41945. viewport = 0;
  41946. textHolder = 0;
  41947. }
  41948. void TextEditor::newTransaction()
  41949. {
  41950. lastTransactionTime = Time::getApproximateMillisecondCounter();
  41951. undoManager.beginNewTransaction();
  41952. }
  41953. void TextEditor::doUndoRedo (const bool isRedo)
  41954. {
  41955. if (! isReadOnly())
  41956. {
  41957. if (isRedo ? undoManager.redo()
  41958. : undoManager.undo())
  41959. {
  41960. scrollToMakeSureCursorIsVisible();
  41961. repaint();
  41962. textChanged();
  41963. }
  41964. }
  41965. }
  41966. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  41967. const bool shouldWordWrap)
  41968. {
  41969. if (multiline != shouldBeMultiLine
  41970. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  41971. {
  41972. multiline = shouldBeMultiLine;
  41973. wordWrap = shouldWordWrap && shouldBeMultiLine;
  41974. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  41975. scrollbarVisible && multiline);
  41976. viewport->setViewPosition (0, 0);
  41977. resized();
  41978. scrollToMakeSureCursorIsVisible();
  41979. }
  41980. }
  41981. bool TextEditor::isMultiLine() const
  41982. {
  41983. return multiline;
  41984. }
  41985. void TextEditor::setScrollbarsShown (bool shown)
  41986. {
  41987. if (scrollbarVisible != shown)
  41988. {
  41989. scrollbarVisible = shown;
  41990. shown = shown && isMultiLine();
  41991. viewport->setScrollBarsShown (shown, shown);
  41992. }
  41993. }
  41994. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  41995. {
  41996. if (readOnly != shouldBeReadOnly)
  41997. {
  41998. readOnly = shouldBeReadOnly;
  41999. enablementChanged();
  42000. }
  42001. }
  42002. bool TextEditor::isReadOnly() const
  42003. {
  42004. return readOnly || ! isEnabled();
  42005. }
  42006. bool TextEditor::isTextInputActive() const
  42007. {
  42008. return ! isReadOnly();
  42009. }
  42010. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42011. {
  42012. returnKeyStartsNewLine = shouldStartNewLine;
  42013. }
  42014. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42015. {
  42016. tabKeyUsed = shouldTabKeyBeUsed;
  42017. }
  42018. void TextEditor::setPopupMenuEnabled (const bool b)
  42019. {
  42020. popupMenuEnabled = b;
  42021. }
  42022. void TextEditor::setSelectAllWhenFocused (const bool b)
  42023. {
  42024. selectAllTextWhenFocused = b;
  42025. }
  42026. const Font TextEditor::getFont() const
  42027. {
  42028. return currentFont;
  42029. }
  42030. void TextEditor::setFont (const Font& newFont)
  42031. {
  42032. currentFont = newFont;
  42033. scrollToMakeSureCursorIsVisible();
  42034. }
  42035. void TextEditor::applyFontToAllText (const Font& newFont)
  42036. {
  42037. currentFont = newFont;
  42038. const Colour overallColour (findColour (textColourId));
  42039. for (int i = sections.size(); --i >= 0;)
  42040. {
  42041. UniformTextSection* const uts = sections.getUnchecked (i);
  42042. uts->setFont (newFont, passwordCharacter);
  42043. uts->colour = overallColour;
  42044. }
  42045. coalesceSimilarSections();
  42046. updateTextHolderSize();
  42047. scrollToMakeSureCursorIsVisible();
  42048. repaint();
  42049. }
  42050. void TextEditor::colourChanged()
  42051. {
  42052. setOpaque (findColour (backgroundColourId).isOpaque());
  42053. repaint();
  42054. }
  42055. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42056. {
  42057. caretVisible = shouldCaretBeVisible;
  42058. if (shouldCaretBeVisible)
  42059. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42060. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42061. : MouseCursor::NormalCursor);
  42062. }
  42063. void TextEditor::setInputRestrictions (const int maxLen,
  42064. const String& chars)
  42065. {
  42066. maxTextLength = jmax (0, maxLen);
  42067. allowedCharacters = chars;
  42068. }
  42069. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42070. {
  42071. textToShowWhenEmpty = text;
  42072. colourForTextWhenEmpty = colourToUse;
  42073. }
  42074. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42075. {
  42076. if (passwordCharacter != newPasswordCharacter)
  42077. {
  42078. passwordCharacter = newPasswordCharacter;
  42079. resized();
  42080. repaint();
  42081. }
  42082. }
  42083. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42084. {
  42085. viewport->setScrollBarThickness (newThicknessPixels);
  42086. }
  42087. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42088. {
  42089. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42090. }
  42091. void TextEditor::clear()
  42092. {
  42093. clearInternal (0);
  42094. updateTextHolderSize();
  42095. undoManager.clearUndoHistory();
  42096. }
  42097. void TextEditor::setText (const String& newText,
  42098. const bool sendTextChangeMessage)
  42099. {
  42100. const int newLength = newText.length();
  42101. if (newLength != getTotalNumChars() || getText() != newText)
  42102. {
  42103. const int oldCursorPos = caretPosition;
  42104. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42105. clearInternal (0);
  42106. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42107. // if you're adding text with line-feeds to a single-line text editor, it
  42108. // ain't gonna look right!
  42109. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42110. if (cursorWasAtEnd && ! isMultiLine())
  42111. moveCursorTo (getTotalNumChars(), false);
  42112. else
  42113. moveCursorTo (oldCursorPos, false);
  42114. if (sendTextChangeMessage)
  42115. textChanged();
  42116. updateTextHolderSize();
  42117. scrollToMakeSureCursorIsVisible();
  42118. undoManager.clearUndoHistory();
  42119. repaint();
  42120. }
  42121. }
  42122. Value& TextEditor::getTextValue()
  42123. {
  42124. if (valueTextNeedsUpdating)
  42125. {
  42126. valueTextNeedsUpdating = false;
  42127. textValue = getText();
  42128. }
  42129. return textValue;
  42130. }
  42131. void TextEditor::textWasChangedByValue()
  42132. {
  42133. if (textValue.getValueSource().getReferenceCount() > 1)
  42134. setText (textValue.getValue());
  42135. }
  42136. void TextEditor::textChanged()
  42137. {
  42138. updateTextHolderSize();
  42139. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42140. if (textValue.getValueSource().getReferenceCount() > 1)
  42141. {
  42142. valueTextNeedsUpdating = false;
  42143. textValue = getText();
  42144. }
  42145. }
  42146. void TextEditor::returnPressed()
  42147. {
  42148. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42149. }
  42150. void TextEditor::escapePressed()
  42151. {
  42152. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42153. }
  42154. void TextEditor::addListener (TextEditorListener* const newListener)
  42155. {
  42156. listeners.add (newListener);
  42157. }
  42158. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42159. {
  42160. listeners.remove (listenerToRemove);
  42161. }
  42162. void TextEditor::timerCallbackInt()
  42163. {
  42164. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42165. if (caretFlashState != newState)
  42166. {
  42167. caretFlashState = newState;
  42168. if (caretFlashState)
  42169. wasFocused = true;
  42170. if (caretVisible
  42171. && hasKeyboardFocus (false)
  42172. && ! isReadOnly())
  42173. {
  42174. repaintCaret();
  42175. }
  42176. }
  42177. const unsigned int now = Time::getApproximateMillisecondCounter();
  42178. if (now > lastTransactionTime + 200)
  42179. newTransaction();
  42180. }
  42181. void TextEditor::repaintCaret()
  42182. {
  42183. if (! findColour (caretColourId).isTransparent())
  42184. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42185. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42186. 4,
  42187. roundToInt (cursorHeight) + 2);
  42188. }
  42189. void TextEditor::repaintText (const Range<int>& range)
  42190. {
  42191. if (! range.isEmpty())
  42192. {
  42193. float x = 0, y = 0, lh = currentFont.getHeight();
  42194. const float wordWrapWidth = getWordWrapWidth();
  42195. if (wordWrapWidth > 0)
  42196. {
  42197. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42198. i.getCharPosition (range.getStart(), x, y, lh);
  42199. const int y1 = (int) y;
  42200. int y2;
  42201. if (range.getEnd() >= getTotalNumChars())
  42202. {
  42203. y2 = textHolder->getHeight();
  42204. }
  42205. else
  42206. {
  42207. i.getCharPosition (range.getEnd(), x, y, lh);
  42208. y2 = (int) (y + lh * 2.0f);
  42209. }
  42210. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42211. }
  42212. }
  42213. }
  42214. void TextEditor::moveCaret (int newCaretPos)
  42215. {
  42216. if (newCaretPos < 0)
  42217. newCaretPos = 0;
  42218. else if (newCaretPos > getTotalNumChars())
  42219. newCaretPos = getTotalNumChars();
  42220. if (newCaretPos != getCaretPosition())
  42221. {
  42222. repaintCaret();
  42223. caretFlashState = true;
  42224. caretPosition = newCaretPos;
  42225. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42226. scrollToMakeSureCursorIsVisible();
  42227. repaintCaret();
  42228. }
  42229. }
  42230. void TextEditor::setCaretPosition (const int newIndex)
  42231. {
  42232. moveCursorTo (newIndex, false);
  42233. }
  42234. int TextEditor::getCaretPosition() const
  42235. {
  42236. return caretPosition;
  42237. }
  42238. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42239. const int desiredCaretY)
  42240. {
  42241. updateCaretPosition();
  42242. int vx = roundToInt (cursorX) - desiredCaretX;
  42243. int vy = roundToInt (cursorY) - desiredCaretY;
  42244. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42245. {
  42246. vx += desiredCaretX - proportionOfWidth (0.2f);
  42247. }
  42248. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42249. {
  42250. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42251. }
  42252. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42253. if (! isMultiLine())
  42254. {
  42255. vy = viewport->getViewPositionY();
  42256. }
  42257. else
  42258. {
  42259. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42260. const int curH = roundToInt (cursorHeight);
  42261. if (desiredCaretY < 0)
  42262. {
  42263. vy = jmax (0, desiredCaretY + vy);
  42264. }
  42265. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42266. {
  42267. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42268. }
  42269. }
  42270. viewport->setViewPosition (vx, vy);
  42271. }
  42272. const Rectangle<int> TextEditor::getCaretRectangle()
  42273. {
  42274. updateCaretPosition();
  42275. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42276. roundToInt (cursorY) - viewport->getY(),
  42277. 1, roundToInt (cursorHeight));
  42278. }
  42279. float TextEditor::getWordWrapWidth() const
  42280. {
  42281. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42282. : 1.0e10f;
  42283. }
  42284. void TextEditor::updateTextHolderSize()
  42285. {
  42286. const float wordWrapWidth = getWordWrapWidth();
  42287. if (wordWrapWidth > 0)
  42288. {
  42289. float maxWidth = 0.0f;
  42290. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42291. while (i.next())
  42292. maxWidth = jmax (maxWidth, i.atomRight);
  42293. const int w = leftIndent + roundToInt (maxWidth);
  42294. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42295. currentFont.getHeight()));
  42296. textHolder->setSize (w + 1, h + 1);
  42297. }
  42298. }
  42299. int TextEditor::getTextWidth() const
  42300. {
  42301. return textHolder->getWidth();
  42302. }
  42303. int TextEditor::getTextHeight() const
  42304. {
  42305. return textHolder->getHeight();
  42306. }
  42307. void TextEditor::setIndents (const int newLeftIndent,
  42308. const int newTopIndent)
  42309. {
  42310. leftIndent = newLeftIndent;
  42311. topIndent = newTopIndent;
  42312. }
  42313. void TextEditor::setBorder (const BorderSize& border)
  42314. {
  42315. borderSize = border;
  42316. resized();
  42317. }
  42318. const BorderSize TextEditor::getBorder() const
  42319. {
  42320. return borderSize;
  42321. }
  42322. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42323. {
  42324. keepCursorOnScreen = shouldScrollToShowCursor;
  42325. }
  42326. void TextEditor::updateCaretPosition()
  42327. {
  42328. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42329. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42330. }
  42331. void TextEditor::scrollToMakeSureCursorIsVisible()
  42332. {
  42333. updateCaretPosition();
  42334. if (keepCursorOnScreen)
  42335. {
  42336. int x = viewport->getViewPositionX();
  42337. int y = viewport->getViewPositionY();
  42338. const int relativeCursorX = roundToInt (cursorX) - x;
  42339. const int relativeCursorY = roundToInt (cursorY) - y;
  42340. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42341. {
  42342. x += relativeCursorX - proportionOfWidth (0.2f);
  42343. }
  42344. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42345. {
  42346. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42347. }
  42348. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42349. if (! isMultiLine())
  42350. {
  42351. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42352. }
  42353. else
  42354. {
  42355. const int curH = roundToInt (cursorHeight);
  42356. if (relativeCursorY < 0)
  42357. {
  42358. y = jmax (0, relativeCursorY + y);
  42359. }
  42360. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42361. {
  42362. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42363. }
  42364. }
  42365. viewport->setViewPosition (x, y);
  42366. }
  42367. }
  42368. void TextEditor::moveCursorTo (const int newPosition,
  42369. const bool isSelecting)
  42370. {
  42371. if (isSelecting)
  42372. {
  42373. moveCaret (newPosition);
  42374. const Range<int> oldSelection (selection);
  42375. if (dragType == notDragging)
  42376. {
  42377. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42378. dragType = draggingSelectionStart;
  42379. else
  42380. dragType = draggingSelectionEnd;
  42381. }
  42382. if (dragType == draggingSelectionStart)
  42383. {
  42384. if (getCaretPosition() >= selection.getEnd())
  42385. dragType = draggingSelectionEnd;
  42386. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42387. }
  42388. else
  42389. {
  42390. if (getCaretPosition() < selection.getStart())
  42391. dragType = draggingSelectionStart;
  42392. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42393. }
  42394. repaintText (selection.getUnionWith (oldSelection));
  42395. }
  42396. else
  42397. {
  42398. dragType = notDragging;
  42399. repaintText (selection);
  42400. moveCaret (newPosition);
  42401. selection = Range<int>::emptyRange (getCaretPosition());
  42402. }
  42403. }
  42404. int TextEditor::getTextIndexAt (const int x,
  42405. const int y)
  42406. {
  42407. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42408. (float) (y + viewport->getViewPositionY() - topIndent));
  42409. }
  42410. void TextEditor::insertTextAtCaret (const String& newText_)
  42411. {
  42412. String newText (newText_);
  42413. if (allowedCharacters.isNotEmpty())
  42414. newText = newText.retainCharacters (allowedCharacters);
  42415. if ((! returnKeyStartsNewLine) && newText == "\n")
  42416. {
  42417. returnPressed();
  42418. return;
  42419. }
  42420. if (! isMultiLine())
  42421. newText = newText.replaceCharacters ("\r\n", " ");
  42422. else
  42423. newText = newText.replace ("\r\n", "\n");
  42424. const int newCaretPos = selection.getStart() + newText.length();
  42425. const int insertIndex = selection.getStart();
  42426. remove (selection, getUndoManager(),
  42427. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42428. if (maxTextLength > 0)
  42429. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42430. if (newText.isNotEmpty())
  42431. insert (newText,
  42432. insertIndex,
  42433. currentFont,
  42434. findColour (textColourId),
  42435. getUndoManager(),
  42436. newCaretPos);
  42437. textChanged();
  42438. }
  42439. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42440. {
  42441. moveCursorTo (newSelection.getStart(), false);
  42442. moveCursorTo (newSelection.getEnd(), true);
  42443. }
  42444. void TextEditor::copy()
  42445. {
  42446. if (passwordCharacter == 0)
  42447. {
  42448. const String selectedText (getHighlightedText());
  42449. if (selectedText.isNotEmpty())
  42450. SystemClipboard::copyTextToClipboard (selectedText);
  42451. }
  42452. }
  42453. void TextEditor::paste()
  42454. {
  42455. if (! isReadOnly())
  42456. {
  42457. const String clip (SystemClipboard::getTextFromClipboard());
  42458. if (clip.isNotEmpty())
  42459. insertTextAtCaret (clip);
  42460. }
  42461. }
  42462. void TextEditor::cut()
  42463. {
  42464. if (! isReadOnly())
  42465. {
  42466. moveCaret (selection.getEnd());
  42467. insertTextAtCaret (String::empty);
  42468. }
  42469. }
  42470. void TextEditor::drawContent (Graphics& g)
  42471. {
  42472. const float wordWrapWidth = getWordWrapWidth();
  42473. if (wordWrapWidth > 0)
  42474. {
  42475. g.setOrigin (leftIndent, topIndent);
  42476. const Rectangle<int> clip (g.getClipBounds());
  42477. Colour selectedTextColour;
  42478. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42479. while (i.lineY + 200.0 < clip.getY() && i.next())
  42480. {}
  42481. if (! selection.isEmpty())
  42482. {
  42483. g.setColour (findColour (highlightColourId)
  42484. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42485. selectedTextColour = findColour (highlightedTextColourId);
  42486. Iterator i2 (i);
  42487. while (i2.next() && i2.lineY < clip.getBottom())
  42488. {
  42489. if (i2.lineY + i2.lineHeight >= clip.getY()
  42490. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42491. {
  42492. i2.drawSelection (g, selection);
  42493. }
  42494. }
  42495. }
  42496. const UniformTextSection* lastSection = 0;
  42497. while (i.next() && i.lineY < clip.getBottom())
  42498. {
  42499. if (i.lineY + i.lineHeight >= clip.getY())
  42500. {
  42501. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42502. {
  42503. i.drawSelectedText (g, selection, selectedTextColour);
  42504. lastSection = 0;
  42505. }
  42506. else
  42507. {
  42508. i.draw (g, lastSection);
  42509. }
  42510. }
  42511. }
  42512. }
  42513. }
  42514. void TextEditor::paint (Graphics& g)
  42515. {
  42516. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42517. }
  42518. void TextEditor::paintOverChildren (Graphics& g)
  42519. {
  42520. if (caretFlashState
  42521. && hasKeyboardFocus (false)
  42522. && caretVisible
  42523. && ! isReadOnly())
  42524. {
  42525. g.setColour (findColour (caretColourId));
  42526. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42527. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42528. 2.0f, cursorHeight);
  42529. }
  42530. if (textToShowWhenEmpty.isNotEmpty()
  42531. && (! hasKeyboardFocus (false))
  42532. && getTotalNumChars() == 0)
  42533. {
  42534. g.setColour (colourForTextWhenEmpty);
  42535. g.setFont (getFont());
  42536. if (isMultiLine())
  42537. {
  42538. g.drawText (textToShowWhenEmpty,
  42539. 0, 0, getWidth(), getHeight(),
  42540. Justification::centred, true);
  42541. }
  42542. else
  42543. {
  42544. g.drawText (textToShowWhenEmpty,
  42545. leftIndent, topIndent,
  42546. viewport->getWidth() - leftIndent,
  42547. viewport->getHeight() - topIndent,
  42548. Justification::centredLeft, true);
  42549. }
  42550. }
  42551. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42552. }
  42553. void TextEditor::mouseDown (const MouseEvent& e)
  42554. {
  42555. beginDragAutoRepeat (100);
  42556. newTransaction();
  42557. if (wasFocused || ! selectAllTextWhenFocused)
  42558. {
  42559. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42560. {
  42561. moveCursorTo (getTextIndexAt (e.x, e.y),
  42562. e.mods.isShiftDown());
  42563. }
  42564. else
  42565. {
  42566. PopupMenu m;
  42567. m.setLookAndFeel (&getLookAndFeel());
  42568. addPopupMenuItems (m, &e);
  42569. menuActive = true;
  42570. const int result = m.show();
  42571. menuActive = false;
  42572. if (result != 0)
  42573. performPopupMenuAction (result);
  42574. }
  42575. }
  42576. }
  42577. void TextEditor::mouseDrag (const MouseEvent& e)
  42578. {
  42579. if (wasFocused || ! selectAllTextWhenFocused)
  42580. {
  42581. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42582. {
  42583. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42584. }
  42585. }
  42586. }
  42587. void TextEditor::mouseUp (const MouseEvent& e)
  42588. {
  42589. newTransaction();
  42590. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42591. if (wasFocused || ! selectAllTextWhenFocused)
  42592. {
  42593. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42594. {
  42595. moveCaret (getTextIndexAt (e.x, e.y));
  42596. }
  42597. }
  42598. wasFocused = true;
  42599. }
  42600. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42601. {
  42602. int tokenEnd = getTextIndexAt (e.x, e.y);
  42603. int tokenStart = tokenEnd;
  42604. if (e.getNumberOfClicks() > 3)
  42605. {
  42606. tokenStart = 0;
  42607. tokenEnd = getTotalNumChars();
  42608. }
  42609. else
  42610. {
  42611. const String t (getText());
  42612. const int totalLength = getTotalNumChars();
  42613. while (tokenEnd < totalLength)
  42614. {
  42615. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  42616. ++tokenEnd;
  42617. else
  42618. break;
  42619. }
  42620. tokenStart = tokenEnd;
  42621. while (tokenStart > 0)
  42622. {
  42623. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  42624. --tokenStart;
  42625. else
  42626. break;
  42627. }
  42628. if (e.getNumberOfClicks() > 2)
  42629. {
  42630. while (tokenEnd < totalLength)
  42631. {
  42632. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42633. ++tokenEnd;
  42634. else
  42635. break;
  42636. }
  42637. while (tokenStart > 0)
  42638. {
  42639. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42640. --tokenStart;
  42641. else
  42642. break;
  42643. }
  42644. }
  42645. }
  42646. moveCursorTo (tokenEnd, false);
  42647. moveCursorTo (tokenStart, true);
  42648. }
  42649. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42650. {
  42651. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42652. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42653. }
  42654. bool TextEditor::keyPressed (const KeyPress& key)
  42655. {
  42656. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42657. return false;
  42658. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42659. if (key.isKeyCode (KeyPress::leftKey)
  42660. || key.isKeyCode (KeyPress::upKey))
  42661. {
  42662. newTransaction();
  42663. int newPos;
  42664. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42665. newPos = indexAtPosition (cursorX, cursorY - 1);
  42666. else if (moveInWholeWordSteps)
  42667. newPos = findWordBreakBefore (getCaretPosition());
  42668. else
  42669. newPos = getCaretPosition() - 1;
  42670. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42671. }
  42672. else if (key.isKeyCode (KeyPress::rightKey)
  42673. || key.isKeyCode (KeyPress::downKey))
  42674. {
  42675. newTransaction();
  42676. int newPos;
  42677. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42678. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42679. else if (moveInWholeWordSteps)
  42680. newPos = findWordBreakAfter (getCaretPosition());
  42681. else
  42682. newPos = getCaretPosition() + 1;
  42683. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42684. }
  42685. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42686. {
  42687. newTransaction();
  42688. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42689. key.getModifiers().isShiftDown());
  42690. }
  42691. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42692. {
  42693. newTransaction();
  42694. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42695. key.getModifiers().isShiftDown());
  42696. }
  42697. else if (key.isKeyCode (KeyPress::homeKey))
  42698. {
  42699. newTransaction();
  42700. if (isMultiLine() && ! moveInWholeWordSteps)
  42701. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42702. key.getModifiers().isShiftDown());
  42703. else
  42704. moveCursorTo (0, key.getModifiers().isShiftDown());
  42705. }
  42706. else if (key.isKeyCode (KeyPress::endKey))
  42707. {
  42708. newTransaction();
  42709. if (isMultiLine() && ! moveInWholeWordSteps)
  42710. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42711. key.getModifiers().isShiftDown());
  42712. else
  42713. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42714. }
  42715. else if (key.isKeyCode (KeyPress::backspaceKey))
  42716. {
  42717. if (moveInWholeWordSteps)
  42718. {
  42719. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42720. }
  42721. else
  42722. {
  42723. if (selection.isEmpty() && selection.getStart() > 0)
  42724. selection.setStart (selection.getEnd() - 1);
  42725. }
  42726. cut();
  42727. }
  42728. else if (key.isKeyCode (KeyPress::deleteKey))
  42729. {
  42730. if (key.getModifiers().isShiftDown())
  42731. copy();
  42732. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42733. selection.setEnd (selection.getStart() + 1);
  42734. cut();
  42735. }
  42736. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42737. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42738. {
  42739. newTransaction();
  42740. copy();
  42741. }
  42742. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42743. {
  42744. newTransaction();
  42745. copy();
  42746. cut();
  42747. }
  42748. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42749. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42750. {
  42751. newTransaction();
  42752. paste();
  42753. }
  42754. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42755. {
  42756. newTransaction();
  42757. doUndoRedo (false);
  42758. }
  42759. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42760. {
  42761. newTransaction();
  42762. doUndoRedo (true);
  42763. }
  42764. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42765. {
  42766. newTransaction();
  42767. moveCursorTo (getTotalNumChars(), false);
  42768. moveCursorTo (0, true);
  42769. }
  42770. else if (key == KeyPress::returnKey)
  42771. {
  42772. newTransaction();
  42773. insertTextAtCaret ("\n");
  42774. }
  42775. else if (key.isKeyCode (KeyPress::escapeKey))
  42776. {
  42777. newTransaction();
  42778. moveCursorTo (getCaretPosition(), false);
  42779. escapePressed();
  42780. }
  42781. else if (key.getTextCharacter() >= ' '
  42782. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42783. {
  42784. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42785. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42786. }
  42787. else
  42788. {
  42789. return false;
  42790. }
  42791. return true;
  42792. }
  42793. bool TextEditor::keyStateChanged (const bool isKeyDown)
  42794. {
  42795. if (! isKeyDown)
  42796. return false;
  42797. #if JUCE_WINDOWS
  42798. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  42799. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  42800. #endif
  42801. // (overridden to avoid forwarding key events to the parent)
  42802. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  42803. }
  42804. const int baseMenuItemID = 0x7fff0000;
  42805. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  42806. {
  42807. const bool writable = ! isReadOnly();
  42808. if (passwordCharacter == 0)
  42809. {
  42810. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  42811. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  42812. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  42813. }
  42814. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  42815. m.addSeparator();
  42816. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  42817. m.addSeparator();
  42818. if (getUndoManager() != 0)
  42819. {
  42820. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  42821. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  42822. }
  42823. }
  42824. void TextEditor::performPopupMenuAction (const int menuItemID)
  42825. {
  42826. switch (menuItemID)
  42827. {
  42828. case baseMenuItemID + 1:
  42829. copy();
  42830. cut();
  42831. break;
  42832. case baseMenuItemID + 2:
  42833. copy();
  42834. break;
  42835. case baseMenuItemID + 3:
  42836. paste();
  42837. break;
  42838. case baseMenuItemID + 4:
  42839. cut();
  42840. break;
  42841. case baseMenuItemID + 5:
  42842. moveCursorTo (getTotalNumChars(), false);
  42843. moveCursorTo (0, true);
  42844. break;
  42845. case baseMenuItemID + 6:
  42846. doUndoRedo (false);
  42847. break;
  42848. case baseMenuItemID + 7:
  42849. doUndoRedo (true);
  42850. break;
  42851. default:
  42852. break;
  42853. }
  42854. }
  42855. void TextEditor::focusGained (FocusChangeType)
  42856. {
  42857. newTransaction();
  42858. caretFlashState = true;
  42859. if (selectAllTextWhenFocused)
  42860. {
  42861. moveCursorTo (0, false);
  42862. moveCursorTo (getTotalNumChars(), true);
  42863. }
  42864. repaint();
  42865. if (caretVisible)
  42866. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42867. ComponentPeer* const peer = getPeer();
  42868. if (peer != 0 && ! isReadOnly())
  42869. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  42870. }
  42871. void TextEditor::focusLost (FocusChangeType)
  42872. {
  42873. newTransaction();
  42874. wasFocused = false;
  42875. textHolder->stopTimer();
  42876. caretFlashState = false;
  42877. postCommandMessage (TextEditorDefs::focusLossMessageId);
  42878. repaint();
  42879. }
  42880. void TextEditor::resized()
  42881. {
  42882. viewport->setBoundsInset (borderSize);
  42883. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  42884. updateTextHolderSize();
  42885. if (! isMultiLine())
  42886. {
  42887. scrollToMakeSureCursorIsVisible();
  42888. }
  42889. else
  42890. {
  42891. updateCaretPosition();
  42892. }
  42893. }
  42894. void TextEditor::handleCommandMessage (const int commandId)
  42895. {
  42896. Component::BailOutChecker checker (this);
  42897. switch (commandId)
  42898. {
  42899. case TextEditorDefs::textChangeMessageId:
  42900. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  42901. break;
  42902. case TextEditorDefs::returnKeyMessageId:
  42903. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  42904. break;
  42905. case TextEditorDefs::escapeKeyMessageId:
  42906. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  42907. break;
  42908. case TextEditorDefs::focusLossMessageId:
  42909. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  42910. break;
  42911. default:
  42912. jassertfalse;
  42913. break;
  42914. }
  42915. }
  42916. void TextEditor::enablementChanged()
  42917. {
  42918. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  42919. : MouseCursor::IBeamCursor);
  42920. repaint();
  42921. }
  42922. UndoManager* TextEditor::getUndoManager() throw()
  42923. {
  42924. return isReadOnly() ? &undoManager : 0;
  42925. }
  42926. void TextEditor::clearInternal (UndoManager* const um)
  42927. {
  42928. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  42929. }
  42930. void TextEditor::insert (const String& text,
  42931. const int insertIndex,
  42932. const Font& font,
  42933. const Colour& colour,
  42934. UndoManager* const um,
  42935. const int caretPositionToMoveTo)
  42936. {
  42937. if (text.isNotEmpty())
  42938. {
  42939. if (um != 0)
  42940. {
  42941. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  42942. newTransaction();
  42943. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  42944. caretPosition, caretPositionToMoveTo));
  42945. }
  42946. else
  42947. {
  42948. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  42949. // a line gets moved due to word wrap
  42950. int index = 0;
  42951. int nextIndex = 0;
  42952. for (int i = 0; i < sections.size(); ++i)
  42953. {
  42954. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42955. if (insertIndex == index)
  42956. {
  42957. sections.insert (i, new UniformTextSection (text,
  42958. font, colour,
  42959. passwordCharacter));
  42960. break;
  42961. }
  42962. else if (insertIndex > index && insertIndex < nextIndex)
  42963. {
  42964. splitSection (i, insertIndex - index);
  42965. sections.insert (i + 1, new UniformTextSection (text,
  42966. font, colour,
  42967. passwordCharacter));
  42968. break;
  42969. }
  42970. index = nextIndex;
  42971. }
  42972. if (nextIndex == insertIndex)
  42973. sections.add (new UniformTextSection (text,
  42974. font, colour,
  42975. passwordCharacter));
  42976. coalesceSimilarSections();
  42977. totalNumChars = -1;
  42978. valueTextNeedsUpdating = true;
  42979. moveCursorTo (caretPositionToMoveTo, false);
  42980. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  42981. }
  42982. }
  42983. }
  42984. void TextEditor::reinsert (const int insertIndex,
  42985. const Array <UniformTextSection*>& sectionsToInsert)
  42986. {
  42987. int index = 0;
  42988. int nextIndex = 0;
  42989. for (int i = 0; i < sections.size(); ++i)
  42990. {
  42991. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42992. if (insertIndex == index)
  42993. {
  42994. for (int j = sectionsToInsert.size(); --j >= 0;)
  42995. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  42996. break;
  42997. }
  42998. else if (insertIndex > index && insertIndex < nextIndex)
  42999. {
  43000. splitSection (i, insertIndex - index);
  43001. for (int j = sectionsToInsert.size(); --j >= 0;)
  43002. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43003. break;
  43004. }
  43005. index = nextIndex;
  43006. }
  43007. if (nextIndex == insertIndex)
  43008. {
  43009. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43010. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43011. }
  43012. coalesceSimilarSections();
  43013. totalNumChars = -1;
  43014. valueTextNeedsUpdating = true;
  43015. }
  43016. void TextEditor::remove (const Range<int>& range,
  43017. UndoManager* const um,
  43018. const int caretPositionToMoveTo)
  43019. {
  43020. if (! range.isEmpty())
  43021. {
  43022. int index = 0;
  43023. for (int i = 0; i < sections.size(); ++i)
  43024. {
  43025. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43026. if (range.getStart() > index && range.getStart() < nextIndex)
  43027. {
  43028. splitSection (i, range.getStart() - index);
  43029. --i;
  43030. }
  43031. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43032. {
  43033. splitSection (i, range.getEnd() - index);
  43034. --i;
  43035. }
  43036. else
  43037. {
  43038. index = nextIndex;
  43039. if (index > range.getEnd())
  43040. break;
  43041. }
  43042. }
  43043. index = 0;
  43044. if (um != 0)
  43045. {
  43046. Array <UniformTextSection*> removedSections;
  43047. for (int i = 0; i < sections.size(); ++i)
  43048. {
  43049. if (range.getEnd() <= range.getStart())
  43050. break;
  43051. UniformTextSection* const section = sections.getUnchecked (i);
  43052. const int nextIndex = index + section->getTotalLength();
  43053. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43054. removedSections.add (new UniformTextSection (*section));
  43055. index = nextIndex;
  43056. }
  43057. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43058. newTransaction();
  43059. um->perform (new RemoveAction (*this, range, caretPosition,
  43060. caretPositionToMoveTo, removedSections));
  43061. }
  43062. else
  43063. {
  43064. Range<int> remainingRange (range);
  43065. for (int i = 0; i < sections.size(); ++i)
  43066. {
  43067. UniformTextSection* const section = sections.getUnchecked (i);
  43068. const int nextIndex = index + section->getTotalLength();
  43069. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43070. {
  43071. sections.remove(i);
  43072. section->clear();
  43073. delete section;
  43074. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43075. if (remainingRange.isEmpty())
  43076. break;
  43077. --i;
  43078. }
  43079. else
  43080. {
  43081. index = nextIndex;
  43082. }
  43083. }
  43084. coalesceSimilarSections();
  43085. totalNumChars = -1;
  43086. valueTextNeedsUpdating = true;
  43087. moveCursorTo (caretPositionToMoveTo, false);
  43088. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43089. }
  43090. }
  43091. }
  43092. const String TextEditor::getText() const
  43093. {
  43094. String t;
  43095. t.preallocateStorage (getTotalNumChars());
  43096. String::Concatenator concatenator (t);
  43097. for (int i = 0; i < sections.size(); ++i)
  43098. sections.getUnchecked (i)->appendAllText (concatenator);
  43099. return t;
  43100. }
  43101. const String TextEditor::getTextInRange (const Range<int>& range) const
  43102. {
  43103. String t;
  43104. if (! range.isEmpty())
  43105. {
  43106. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43107. String::Concatenator concatenator (t);
  43108. int index = 0;
  43109. for (int i = 0; i < sections.size(); ++i)
  43110. {
  43111. const UniformTextSection* const s = sections.getUnchecked (i);
  43112. const int nextIndex = index + s->getTotalLength();
  43113. if (range.getStart() < nextIndex)
  43114. {
  43115. if (range.getEnd() <= index)
  43116. break;
  43117. s->appendSubstring (concatenator, range - index);
  43118. }
  43119. index = nextIndex;
  43120. }
  43121. }
  43122. return t;
  43123. }
  43124. const String TextEditor::getHighlightedText() const
  43125. {
  43126. return getTextInRange (selection);
  43127. }
  43128. int TextEditor::getTotalNumChars() const
  43129. {
  43130. if (totalNumChars < 0)
  43131. {
  43132. totalNumChars = 0;
  43133. for (int i = sections.size(); --i >= 0;)
  43134. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43135. }
  43136. return totalNumChars;
  43137. }
  43138. bool TextEditor::isEmpty() const
  43139. {
  43140. return getTotalNumChars() == 0;
  43141. }
  43142. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43143. {
  43144. const float wordWrapWidth = getWordWrapWidth();
  43145. if (wordWrapWidth > 0 && sections.size() > 0)
  43146. {
  43147. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43148. i.getCharPosition (index, cx, cy, lineHeight);
  43149. }
  43150. else
  43151. {
  43152. cx = cy = 0;
  43153. lineHeight = currentFont.getHeight();
  43154. }
  43155. }
  43156. int TextEditor::indexAtPosition (const float x, const float y)
  43157. {
  43158. const float wordWrapWidth = getWordWrapWidth();
  43159. if (wordWrapWidth > 0)
  43160. {
  43161. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43162. while (i.next())
  43163. {
  43164. if (i.lineY + i.lineHeight > y)
  43165. {
  43166. if (i.lineY > y)
  43167. return jmax (0, i.indexInText - 1);
  43168. if (i.atomX >= x)
  43169. return i.indexInText;
  43170. if (x < i.atomRight)
  43171. return i.xToIndex (x);
  43172. }
  43173. }
  43174. }
  43175. return getTotalNumChars();
  43176. }
  43177. static int getCharacterCategory (const juce_wchar character)
  43178. {
  43179. return CharacterFunctions::isLetterOrDigit (character)
  43180. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43181. }
  43182. int TextEditor::findWordBreakAfter (const int position) const
  43183. {
  43184. const String t (getTextInRange (Range<int> (position, position + 512)));
  43185. const int totalLength = t.length();
  43186. int i = 0;
  43187. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43188. ++i;
  43189. const int type = getCharacterCategory (t[i]);
  43190. while (i < totalLength && type == getCharacterCategory (t[i]))
  43191. ++i;
  43192. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43193. ++i;
  43194. return position + i;
  43195. }
  43196. int TextEditor::findWordBreakBefore (const int position) const
  43197. {
  43198. if (position <= 0)
  43199. return 0;
  43200. const int startOfBuffer = jmax (0, position - 512);
  43201. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43202. int i = position - startOfBuffer;
  43203. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43204. --i;
  43205. if (i > 0)
  43206. {
  43207. const int type = getCharacterCategory (t [i - 1]);
  43208. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43209. --i;
  43210. }
  43211. jassert (startOfBuffer + i >= 0);
  43212. return startOfBuffer + i;
  43213. }
  43214. void TextEditor::splitSection (const int sectionIndex,
  43215. const int charToSplitAt)
  43216. {
  43217. jassert (sections[sectionIndex] != 0);
  43218. sections.insert (sectionIndex + 1,
  43219. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43220. }
  43221. void TextEditor::coalesceSimilarSections()
  43222. {
  43223. for (int i = 0; i < sections.size() - 1; ++i)
  43224. {
  43225. UniformTextSection* const s1 = sections.getUnchecked (i);
  43226. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43227. if (s1->font == s2->font
  43228. && s1->colour == s2->colour)
  43229. {
  43230. s1->append (*s2, passwordCharacter);
  43231. sections.remove (i + 1);
  43232. delete s2;
  43233. --i;
  43234. }
  43235. }
  43236. }
  43237. END_JUCE_NAMESPACE
  43238. /*** End of inlined file: juce_TextEditor.cpp ***/
  43239. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43240. BEGIN_JUCE_NAMESPACE
  43241. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43242. class ToolbarSpacerComp : public ToolbarItemComponent
  43243. {
  43244. public:
  43245. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43246. : ToolbarItemComponent (itemId_, String::empty, false),
  43247. fixedSize (fixedSize_),
  43248. drawBar (drawBar_)
  43249. {
  43250. }
  43251. ~ToolbarSpacerComp()
  43252. {
  43253. }
  43254. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43255. int& preferredSize, int& minSize, int& maxSize)
  43256. {
  43257. if (fixedSize <= 0)
  43258. {
  43259. preferredSize = toolbarThickness * 2;
  43260. minSize = 4;
  43261. maxSize = 32768;
  43262. }
  43263. else
  43264. {
  43265. maxSize = roundToInt (toolbarThickness * fixedSize);
  43266. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43267. preferredSize = maxSize;
  43268. if (getEditingMode() == editableOnPalette)
  43269. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43270. }
  43271. return true;
  43272. }
  43273. void paintButtonArea (Graphics&, int, int, bool, bool)
  43274. {
  43275. }
  43276. void contentAreaChanged (const Rectangle<int>&)
  43277. {
  43278. }
  43279. int getResizeOrder() const throw()
  43280. {
  43281. return fixedSize <= 0 ? 0 : 1;
  43282. }
  43283. void paint (Graphics& g)
  43284. {
  43285. const int w = getWidth();
  43286. const int h = getHeight();
  43287. if (drawBar)
  43288. {
  43289. g.setColour (findColour (Toolbar::separatorColourId, true));
  43290. const float thickness = 0.2f;
  43291. if (isToolbarVertical())
  43292. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43293. else
  43294. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43295. }
  43296. if (getEditingMode() != normalMode && ! drawBar)
  43297. {
  43298. g.setColour (findColour (Toolbar::separatorColourId, true));
  43299. const int indentX = jmin (2, (w - 3) / 2);
  43300. const int indentY = jmin (2, (h - 3) / 2);
  43301. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43302. if (fixedSize <= 0)
  43303. {
  43304. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43305. if (isToolbarVertical())
  43306. {
  43307. x1 = w * 0.5f;
  43308. y1 = h * 0.4f;
  43309. x2 = x1;
  43310. y2 = indentX * 2.0f;
  43311. x3 = x1;
  43312. y3 = h * 0.6f;
  43313. x4 = x1;
  43314. y4 = h - y2;
  43315. hw = w * 0.15f;
  43316. hl = w * 0.2f;
  43317. }
  43318. else
  43319. {
  43320. x1 = w * 0.4f;
  43321. y1 = h * 0.5f;
  43322. x2 = indentX * 2.0f;
  43323. y2 = y1;
  43324. x3 = w * 0.6f;
  43325. y3 = y1;
  43326. x4 = w - x2;
  43327. y4 = y1;
  43328. hw = h * 0.15f;
  43329. hl = h * 0.2f;
  43330. }
  43331. Path p;
  43332. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43333. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43334. g.fillPath (p);
  43335. }
  43336. }
  43337. }
  43338. juce_UseDebuggingNewOperator
  43339. private:
  43340. const float fixedSize;
  43341. const bool drawBar;
  43342. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43343. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43344. };
  43345. class MissingItemsComponent : public PopupMenuCustomComponent
  43346. {
  43347. public:
  43348. MissingItemsComponent (Toolbar& owner_, const int height_)
  43349. : PopupMenuCustomComponent (true),
  43350. owner (owner_),
  43351. height (height_)
  43352. {
  43353. for (int i = owner_.items.size(); --i >= 0;)
  43354. {
  43355. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43356. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43357. {
  43358. oldIndexes.insert (0, i);
  43359. addAndMakeVisible (tc, 0);
  43360. }
  43361. }
  43362. layout (400);
  43363. }
  43364. ~MissingItemsComponent()
  43365. {
  43366. // deleting the toolbar while its menu it open??
  43367. jassert (owner.isValidComponent());
  43368. for (int i = 0; i < getNumChildComponents(); ++i)
  43369. {
  43370. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43371. if (tc != 0)
  43372. {
  43373. tc->setVisible (false);
  43374. const int index = oldIndexes.remove (i);
  43375. owner.addChildComponent (tc, index);
  43376. --i;
  43377. }
  43378. }
  43379. owner.resized();
  43380. }
  43381. void layout (const int preferredWidth)
  43382. {
  43383. const int indent = 8;
  43384. int x = indent;
  43385. int y = indent;
  43386. int maxX = 0;
  43387. for (int i = 0; i < getNumChildComponents(); ++i)
  43388. {
  43389. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43390. if (tc != 0)
  43391. {
  43392. int preferredSize = 1, minSize = 1, maxSize = 1;
  43393. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43394. {
  43395. if (x + preferredSize > preferredWidth && x > indent)
  43396. {
  43397. x = indent;
  43398. y += height;
  43399. }
  43400. tc->setBounds (x, y, preferredSize, height);
  43401. x += preferredSize;
  43402. maxX = jmax (maxX, x);
  43403. }
  43404. }
  43405. }
  43406. setSize (maxX + 8, y + height + 8);
  43407. }
  43408. void getIdealSize (int& idealWidth, int& idealHeight)
  43409. {
  43410. idealWidth = getWidth();
  43411. idealHeight = getHeight();
  43412. }
  43413. juce_UseDebuggingNewOperator
  43414. private:
  43415. Toolbar& owner;
  43416. const int height;
  43417. Array <int> oldIndexes;
  43418. MissingItemsComponent (const MissingItemsComponent&);
  43419. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43420. };
  43421. Toolbar::Toolbar()
  43422. : vertical (false),
  43423. isEditingActive (false),
  43424. toolbarStyle (Toolbar::iconsOnly)
  43425. {
  43426. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43427. missingItemsButton->setAlwaysOnTop (true);
  43428. missingItemsButton->addButtonListener (this);
  43429. }
  43430. Toolbar::~Toolbar()
  43431. {
  43432. animator.cancelAllAnimations (true);
  43433. deleteAllChildren();
  43434. }
  43435. void Toolbar::setVertical (const bool shouldBeVertical)
  43436. {
  43437. if (vertical != shouldBeVertical)
  43438. {
  43439. vertical = shouldBeVertical;
  43440. resized();
  43441. }
  43442. }
  43443. void Toolbar::clear()
  43444. {
  43445. for (int i = items.size(); --i >= 0;)
  43446. {
  43447. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43448. items.remove (i);
  43449. delete tc;
  43450. }
  43451. resized();
  43452. }
  43453. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43454. {
  43455. if (itemId == ToolbarItemFactory::separatorBarId)
  43456. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43457. else if (itemId == ToolbarItemFactory::spacerId)
  43458. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43459. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43460. return new ToolbarSpacerComp (itemId, 0, false);
  43461. return factory.createItem (itemId);
  43462. }
  43463. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43464. const int itemId,
  43465. const int insertIndex)
  43466. {
  43467. // An ID can't be zero - this might indicate a mistake somewhere?
  43468. jassert (itemId != 0);
  43469. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43470. if (tc != 0)
  43471. {
  43472. #if JUCE_DEBUG
  43473. Array <int> allowedIds;
  43474. factory.getAllToolbarItemIds (allowedIds);
  43475. // If your factory can create an item for a given ID, it must also return
  43476. // that ID from its getAllToolbarItemIds() method!
  43477. jassert (allowedIds.contains (itemId));
  43478. #endif
  43479. items.insert (insertIndex, tc);
  43480. addAndMakeVisible (tc, insertIndex);
  43481. }
  43482. }
  43483. void Toolbar::addItem (ToolbarItemFactory& factory,
  43484. const int itemId,
  43485. const int insertIndex)
  43486. {
  43487. addItemInternal (factory, itemId, insertIndex);
  43488. resized();
  43489. }
  43490. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43491. {
  43492. Array <int> ids;
  43493. factoryToUse.getDefaultItemSet (ids);
  43494. clear();
  43495. for (int i = 0; i < ids.size(); ++i)
  43496. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43497. resized();
  43498. }
  43499. void Toolbar::removeToolbarItem (const int itemIndex)
  43500. {
  43501. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43502. if (tc != 0)
  43503. {
  43504. items.removeValue (tc);
  43505. delete tc;
  43506. resized();
  43507. }
  43508. }
  43509. int Toolbar::getNumItems() const throw()
  43510. {
  43511. return items.size();
  43512. }
  43513. int Toolbar::getItemId (const int itemIndex) const throw()
  43514. {
  43515. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43516. return tc != 0 ? tc->getItemId() : 0;
  43517. }
  43518. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43519. {
  43520. return items [itemIndex];
  43521. }
  43522. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43523. {
  43524. for (;;)
  43525. {
  43526. index += delta;
  43527. ToolbarItemComponent* const tc = getItemComponent (index);
  43528. if (tc == 0)
  43529. break;
  43530. if (tc->isActive)
  43531. return tc;
  43532. }
  43533. return 0;
  43534. }
  43535. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43536. {
  43537. if (toolbarStyle != newStyle)
  43538. {
  43539. toolbarStyle = newStyle;
  43540. updateAllItemPositions (false);
  43541. }
  43542. }
  43543. const String Toolbar::toString() const
  43544. {
  43545. String s ("TB:");
  43546. for (int i = 0; i < getNumItems(); ++i)
  43547. s << getItemId(i) << ' ';
  43548. return s.trimEnd();
  43549. }
  43550. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43551. const String& savedVersion)
  43552. {
  43553. if (! savedVersion.startsWith ("TB:"))
  43554. return false;
  43555. StringArray tokens;
  43556. tokens.addTokens (savedVersion.substring (3), false);
  43557. clear();
  43558. for (int i = 0; i < tokens.size(); ++i)
  43559. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43560. resized();
  43561. return true;
  43562. }
  43563. void Toolbar::paint (Graphics& g)
  43564. {
  43565. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43566. }
  43567. int Toolbar::getThickness() const throw()
  43568. {
  43569. return vertical ? getWidth() : getHeight();
  43570. }
  43571. int Toolbar::getLength() const throw()
  43572. {
  43573. return vertical ? getHeight() : getWidth();
  43574. }
  43575. void Toolbar::setEditingActive (const bool active)
  43576. {
  43577. if (isEditingActive != active)
  43578. {
  43579. isEditingActive = active;
  43580. updateAllItemPositions (false);
  43581. }
  43582. }
  43583. void Toolbar::resized()
  43584. {
  43585. updateAllItemPositions (false);
  43586. }
  43587. void Toolbar::updateAllItemPositions (const bool animate)
  43588. {
  43589. if (getWidth() > 0 && getHeight() > 0)
  43590. {
  43591. StretchableObjectResizer resizer;
  43592. int i;
  43593. for (i = 0; i < items.size(); ++i)
  43594. {
  43595. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43596. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43597. : ToolbarItemComponent::normalMode);
  43598. tc->setStyle (toolbarStyle);
  43599. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43600. int preferredSize = 1, minSize = 1, maxSize = 1;
  43601. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43602. preferredSize, minSize, maxSize))
  43603. {
  43604. tc->isActive = true;
  43605. resizer.addItem (preferredSize, minSize, maxSize,
  43606. spacer != 0 ? spacer->getResizeOrder() : 2);
  43607. }
  43608. else
  43609. {
  43610. tc->isActive = false;
  43611. tc->setVisible (false);
  43612. }
  43613. }
  43614. resizer.resizeToFit (getLength());
  43615. int totalLength = 0;
  43616. for (i = 0; i < resizer.getNumItems(); ++i)
  43617. totalLength += (int) resizer.getItemSize (i);
  43618. const bool itemsOffTheEnd = totalLength > getLength();
  43619. const int extrasButtonSize = getThickness() / 2;
  43620. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43621. missingItemsButton->setVisible (itemsOffTheEnd);
  43622. missingItemsButton->setEnabled (! isEditingActive);
  43623. if (vertical)
  43624. missingItemsButton->setCentrePosition (getWidth() / 2,
  43625. getHeight() - 4 - extrasButtonSize / 2);
  43626. else
  43627. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43628. getHeight() / 2);
  43629. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43630. : missingItemsButton->getX()) - 4
  43631. : getLength();
  43632. int pos = 0, activeIndex = 0;
  43633. for (i = 0; i < items.size(); ++i)
  43634. {
  43635. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43636. if (tc->isActive)
  43637. {
  43638. const int size = (int) resizer.getItemSize (activeIndex++);
  43639. Rectangle<int> newBounds;
  43640. if (vertical)
  43641. newBounds.setBounds (0, pos, getWidth(), size);
  43642. else
  43643. newBounds.setBounds (pos, 0, size, getHeight());
  43644. if (animate)
  43645. {
  43646. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43647. }
  43648. else
  43649. {
  43650. animator.cancelAnimation (tc, false);
  43651. tc->setBounds (newBounds);
  43652. }
  43653. pos += size;
  43654. tc->setVisible (pos <= maxLength
  43655. && ((! tc->isBeingDragged)
  43656. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43657. }
  43658. }
  43659. }
  43660. }
  43661. void Toolbar::buttonClicked (Button*)
  43662. {
  43663. jassert (missingItemsButton->isShowing());
  43664. if (missingItemsButton->isShowing())
  43665. {
  43666. PopupMenu m;
  43667. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43668. m.showAt (missingItemsButton);
  43669. }
  43670. }
  43671. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43672. Component* /*sourceComponent*/)
  43673. {
  43674. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43675. }
  43676. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43677. {
  43678. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43679. if (tc != 0)
  43680. {
  43681. if (getNumItems() == 0)
  43682. {
  43683. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43684. {
  43685. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43686. if (palette != 0)
  43687. palette->replaceComponent (tc);
  43688. }
  43689. else
  43690. {
  43691. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43692. }
  43693. items.add (tc);
  43694. addChildComponent (tc);
  43695. updateAllItemPositions (false);
  43696. }
  43697. else
  43698. {
  43699. for (int i = getNumItems(); --i >= 0;)
  43700. {
  43701. int currentIndex = getIndexOfChildComponent (tc);
  43702. if (currentIndex < 0)
  43703. {
  43704. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43705. {
  43706. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43707. if (palette != 0)
  43708. palette->replaceComponent (tc);
  43709. }
  43710. else
  43711. {
  43712. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43713. }
  43714. items.add (tc);
  43715. addChildComponent (tc);
  43716. currentIndex = getIndexOfChildComponent (tc);
  43717. updateAllItemPositions (true);
  43718. }
  43719. int newIndex = currentIndex;
  43720. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43721. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43722. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43723. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43724. if (prev != 0)
  43725. {
  43726. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43727. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43728. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43729. {
  43730. newIndex = getIndexOfChildComponent (prev);
  43731. }
  43732. }
  43733. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43734. if (next != 0)
  43735. {
  43736. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43737. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43738. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43739. {
  43740. newIndex = getIndexOfChildComponent (next) + 1;
  43741. }
  43742. }
  43743. if (newIndex != currentIndex)
  43744. {
  43745. items.removeValue (tc);
  43746. removeChildComponent (tc);
  43747. addChildComponent (tc, newIndex);
  43748. items.insert (newIndex, tc);
  43749. updateAllItemPositions (true);
  43750. }
  43751. else
  43752. {
  43753. break;
  43754. }
  43755. }
  43756. }
  43757. }
  43758. }
  43759. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43760. {
  43761. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43762. if (tc != 0)
  43763. {
  43764. if (isParentOf (tc))
  43765. {
  43766. items.removeValue (tc);
  43767. removeChildComponent (tc);
  43768. updateAllItemPositions (true);
  43769. }
  43770. }
  43771. }
  43772. void Toolbar::itemDropped (const String&, Component*, int, int)
  43773. {
  43774. }
  43775. void Toolbar::mouseDown (const MouseEvent& e)
  43776. {
  43777. if (e.mods.isPopupMenu())
  43778. {
  43779. }
  43780. }
  43781. class ToolbarCustomisationDialog : public DialogWindow
  43782. {
  43783. public:
  43784. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43785. Toolbar* const toolbar_,
  43786. const int optionFlags)
  43787. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  43788. toolbar (toolbar_)
  43789. {
  43790. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  43791. setResizable (true, true);
  43792. setResizeLimits (400, 300, 1500, 1000);
  43793. positionNearBar();
  43794. }
  43795. ~ToolbarCustomisationDialog()
  43796. {
  43797. setContentComponent (0, true);
  43798. }
  43799. void closeButtonPressed()
  43800. {
  43801. setVisible (false);
  43802. }
  43803. bool canModalEventBeSentToComponent (const Component* comp)
  43804. {
  43805. return toolbar->isParentOf (comp);
  43806. }
  43807. void positionNearBar()
  43808. {
  43809. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  43810. const int tbx = toolbar->getScreenX();
  43811. const int tby = toolbar->getScreenY();
  43812. const int gap = 8;
  43813. int x, y;
  43814. if (toolbar->isVertical())
  43815. {
  43816. y = tby;
  43817. if (tbx > screenSize.getCentreX())
  43818. x = tbx - getWidth() - gap;
  43819. else
  43820. x = tbx + toolbar->getWidth() + gap;
  43821. }
  43822. else
  43823. {
  43824. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  43825. if (tby > screenSize.getCentreY())
  43826. y = tby - getHeight() - gap;
  43827. else
  43828. y = tby + toolbar->getHeight() + gap;
  43829. }
  43830. setTopLeftPosition (x, y);
  43831. }
  43832. private:
  43833. Toolbar* const toolbar;
  43834. class CustomiserPanel : public Component,
  43835. private ComboBoxListener,
  43836. private ButtonListener
  43837. {
  43838. public:
  43839. CustomiserPanel (ToolbarItemFactory& factory_,
  43840. Toolbar* const toolbar_,
  43841. const int optionFlags)
  43842. : factory (factory_),
  43843. toolbar (toolbar_),
  43844. styleBox (0),
  43845. defaultButton (0)
  43846. {
  43847. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  43848. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  43849. | Toolbar::allowIconsWithTextChoice
  43850. | Toolbar::allowTextOnlyChoice)) != 0)
  43851. {
  43852. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  43853. styleBox->setEditableText (false);
  43854. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  43855. styleBox->addItem (TRANS("Show icons only"), 1);
  43856. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  43857. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  43858. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  43859. styleBox->addItem (TRANS("Show descriptions only"), 3);
  43860. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  43861. styleBox->setSelectedId (1);
  43862. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  43863. styleBox->setSelectedId (2);
  43864. else if (toolbar_->getStyle() == Toolbar::textOnly)
  43865. styleBox->setSelectedId (3);
  43866. styleBox->addListener (this);
  43867. }
  43868. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  43869. {
  43870. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  43871. defaultButton->addButtonListener (this);
  43872. }
  43873. addAndMakeVisible (instructions = new Label (String::empty,
  43874. TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\nItems on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")));
  43875. instructions->setFont (Font (13.0f));
  43876. setSize (500, 300);
  43877. }
  43878. ~CustomiserPanel()
  43879. {
  43880. deleteAllChildren();
  43881. }
  43882. void comboBoxChanged (ComboBox*)
  43883. {
  43884. if (styleBox->getSelectedId() == 1)
  43885. toolbar->setStyle (Toolbar::iconsOnly);
  43886. else if (styleBox->getSelectedId() == 2)
  43887. toolbar->setStyle (Toolbar::iconsWithText);
  43888. else if (styleBox->getSelectedId() == 3)
  43889. toolbar->setStyle (Toolbar::textOnly);
  43890. palette->resized(); // to make it update the styles
  43891. }
  43892. void buttonClicked (Button*)
  43893. {
  43894. toolbar->addDefaultItems (factory);
  43895. }
  43896. void paint (Graphics& g)
  43897. {
  43898. Colour background;
  43899. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  43900. if (dw != 0)
  43901. background = dw->getBackgroundColour();
  43902. g.setColour (background.contrasting().withAlpha (0.3f));
  43903. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  43904. }
  43905. void resized()
  43906. {
  43907. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  43908. if (styleBox != 0)
  43909. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  43910. if (defaultButton != 0)
  43911. {
  43912. defaultButton->changeWidthToFitText (22);
  43913. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  43914. }
  43915. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  43916. }
  43917. private:
  43918. ToolbarItemFactory& factory;
  43919. Toolbar* const toolbar;
  43920. Label* instructions;
  43921. ToolbarItemPalette* palette;
  43922. ComboBox* styleBox;
  43923. TextButton* defaultButton;
  43924. };
  43925. };
  43926. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  43927. {
  43928. setEditingActive (true);
  43929. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  43930. dw.runModalLoop();
  43931. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  43932. setEditingActive (false);
  43933. }
  43934. END_JUCE_NAMESPACE
  43935. /*** End of inlined file: juce_Toolbar.cpp ***/
  43936. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  43937. BEGIN_JUCE_NAMESPACE
  43938. ToolbarItemFactory::ToolbarItemFactory()
  43939. {
  43940. }
  43941. ToolbarItemFactory::~ToolbarItemFactory()
  43942. {
  43943. }
  43944. class ItemDragAndDropOverlayComponent : public Component
  43945. {
  43946. public:
  43947. ItemDragAndDropOverlayComponent()
  43948. : isDragging (false)
  43949. {
  43950. setAlwaysOnTop (true);
  43951. setRepaintsOnMouseActivity (true);
  43952. setMouseCursor (MouseCursor::DraggingHandCursor);
  43953. }
  43954. ~ItemDragAndDropOverlayComponent()
  43955. {
  43956. }
  43957. void paint (Graphics& g)
  43958. {
  43959. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43960. if (isMouseOverOrDragging()
  43961. && tc != 0
  43962. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43963. {
  43964. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  43965. g.drawRect (0, 0, getWidth(), getHeight(),
  43966. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  43967. }
  43968. }
  43969. void mouseDown (const MouseEvent& e)
  43970. {
  43971. isDragging = false;
  43972. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43973. if (tc != 0)
  43974. {
  43975. tc->dragOffsetX = e.x;
  43976. tc->dragOffsetY = e.y;
  43977. }
  43978. }
  43979. void mouseDrag (const MouseEvent& e)
  43980. {
  43981. if (! (isDragging || e.mouseWasClicked()))
  43982. {
  43983. isDragging = true;
  43984. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  43985. if (dnd != 0)
  43986. {
  43987. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image(), true);
  43988. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43989. if (tc != 0)
  43990. {
  43991. tc->isBeingDragged = true;
  43992. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43993. tc->setVisible (false);
  43994. }
  43995. }
  43996. }
  43997. }
  43998. void mouseUp (const MouseEvent&)
  43999. {
  44000. isDragging = false;
  44001. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44002. if (tc != 0)
  44003. {
  44004. tc->isBeingDragged = false;
  44005. Toolbar* const tb = tc->getToolbar();
  44006. if (tb != 0)
  44007. tb->updateAllItemPositions (true);
  44008. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44009. delete tc;
  44010. }
  44011. }
  44012. void parentSizeChanged()
  44013. {
  44014. setBounds (0, 0, getParentWidth(), getParentHeight());
  44015. }
  44016. juce_UseDebuggingNewOperator
  44017. private:
  44018. bool isDragging;
  44019. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44020. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44021. };
  44022. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44023. const String& labelText,
  44024. const bool isBeingUsedAsAButton_)
  44025. : Button (labelText),
  44026. itemId (itemId_),
  44027. mode (normalMode),
  44028. toolbarStyle (Toolbar::iconsOnly),
  44029. dragOffsetX (0),
  44030. dragOffsetY (0),
  44031. isActive (true),
  44032. isBeingDragged (false),
  44033. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44034. {
  44035. // Your item ID can't be 0!
  44036. jassert (itemId_ != 0);
  44037. }
  44038. ToolbarItemComponent::~ToolbarItemComponent()
  44039. {
  44040. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44041. overlayComp = 0;
  44042. }
  44043. Toolbar* ToolbarItemComponent::getToolbar() const
  44044. {
  44045. return dynamic_cast <Toolbar*> (getParentComponent());
  44046. }
  44047. bool ToolbarItemComponent::isToolbarVertical() const
  44048. {
  44049. const Toolbar* const t = getToolbar();
  44050. return t != 0 && t->isVertical();
  44051. }
  44052. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44053. {
  44054. if (toolbarStyle != newStyle)
  44055. {
  44056. toolbarStyle = newStyle;
  44057. repaint();
  44058. resized();
  44059. }
  44060. }
  44061. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44062. {
  44063. if (isBeingUsedAsAButton)
  44064. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44065. over, down, *this);
  44066. if (toolbarStyle != Toolbar::iconsOnly)
  44067. {
  44068. const int indent = contentArea.getX();
  44069. int y = indent;
  44070. int h = getHeight() - indent * 2;
  44071. if (toolbarStyle == Toolbar::iconsWithText)
  44072. {
  44073. y = contentArea.getBottom() + indent / 2;
  44074. h -= contentArea.getHeight();
  44075. }
  44076. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44077. getButtonText(), *this);
  44078. }
  44079. if (! contentArea.isEmpty())
  44080. {
  44081. g.saveState();
  44082. g.setOrigin (contentArea.getX(), contentArea.getY());
  44083. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44084. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44085. g.restoreState();
  44086. }
  44087. }
  44088. void ToolbarItemComponent::resized()
  44089. {
  44090. if (toolbarStyle != Toolbar::textOnly)
  44091. {
  44092. const int indent = jmin (proportionOfWidth (0.08f),
  44093. proportionOfHeight (0.08f));
  44094. contentArea = Rectangle<int> (indent, indent,
  44095. getWidth() - indent * 2,
  44096. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44097. : (getHeight() - indent * 2));
  44098. }
  44099. else
  44100. {
  44101. contentArea = Rectangle<int>();
  44102. }
  44103. contentAreaChanged (contentArea);
  44104. }
  44105. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44106. {
  44107. if (mode != newMode)
  44108. {
  44109. mode = newMode;
  44110. repaint();
  44111. if (mode == normalMode)
  44112. {
  44113. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44114. overlayComp = 0;
  44115. }
  44116. else if (overlayComp == 0)
  44117. {
  44118. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44119. overlayComp->parentSizeChanged();
  44120. }
  44121. resized();
  44122. }
  44123. }
  44124. END_JUCE_NAMESPACE
  44125. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44126. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44127. BEGIN_JUCE_NAMESPACE
  44128. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44129. Toolbar* const toolbar_)
  44130. : factory (factory_),
  44131. toolbar (toolbar_)
  44132. {
  44133. Component* const itemHolder = new Component();
  44134. Array <int> allIds;
  44135. factory_.getAllToolbarItemIds (allIds);
  44136. for (int i = 0; i < allIds.size(); ++i)
  44137. {
  44138. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44139. jassert (tc != 0);
  44140. if (tc != 0)
  44141. {
  44142. itemHolder->addAndMakeVisible (tc);
  44143. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44144. }
  44145. }
  44146. viewport = new Viewport();
  44147. viewport->setViewedComponent (itemHolder);
  44148. addAndMakeVisible (viewport);
  44149. }
  44150. ToolbarItemPalette::~ToolbarItemPalette()
  44151. {
  44152. viewport->getViewedComponent()->deleteAllChildren();
  44153. deleteAllChildren();
  44154. }
  44155. void ToolbarItemPalette::resized()
  44156. {
  44157. viewport->setBoundsInset (BorderSize (1));
  44158. Component* const itemHolder = viewport->getViewedComponent();
  44159. const int indent = 8;
  44160. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44161. const int height = toolbar->getThickness();
  44162. int x = indent;
  44163. int y = indent;
  44164. int maxX = 0;
  44165. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44166. {
  44167. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44168. if (tc != 0)
  44169. {
  44170. tc->setStyle (toolbar->getStyle());
  44171. int preferredSize = 1, minSize = 1, maxSize = 1;
  44172. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44173. {
  44174. if (x + preferredSize > preferredWidth && x > indent)
  44175. {
  44176. x = indent;
  44177. y += height;
  44178. }
  44179. tc->setBounds (x, y, preferredSize, height);
  44180. x += preferredSize + 8;
  44181. maxX = jmax (maxX, x);
  44182. }
  44183. }
  44184. }
  44185. itemHolder->setSize (maxX, y + height + 8);
  44186. }
  44187. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44188. {
  44189. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44190. jassert (tc != 0);
  44191. if (tc != 0)
  44192. {
  44193. tc->setBounds (comp->getBounds());
  44194. tc->setStyle (toolbar->getStyle());
  44195. tc->setEditingMode (comp->getEditingMode());
  44196. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44197. }
  44198. }
  44199. END_JUCE_NAMESPACE
  44200. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44201. /*** Start of inlined file: juce_TreeView.cpp ***/
  44202. BEGIN_JUCE_NAMESPACE
  44203. class TreeViewContentComponent : public Component,
  44204. public TooltipClient
  44205. {
  44206. public:
  44207. TreeViewContentComponent (TreeView& owner_)
  44208. : owner (owner_),
  44209. buttonUnderMouse (0),
  44210. isDragging (false)
  44211. {
  44212. }
  44213. ~TreeViewContentComponent()
  44214. {
  44215. deleteAllChildren();
  44216. }
  44217. void mouseDown (const MouseEvent& e)
  44218. {
  44219. updateButtonUnderMouse (e);
  44220. isDragging = false;
  44221. needSelectionOnMouseUp = false;
  44222. Rectangle<int> pos;
  44223. TreeViewItem* const item = findItemAt (e.y, pos);
  44224. if (item == 0)
  44225. return;
  44226. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44227. // as selection clicks)
  44228. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44229. {
  44230. if (e.x >= pos.getX() - owner.getIndentSize())
  44231. item->setOpen (! item->isOpen());
  44232. // (clicks to the left of an open/close button are ignored)
  44233. }
  44234. else
  44235. {
  44236. // mouse-down inside the body of the item..
  44237. if (! owner.isMultiSelectEnabled())
  44238. item->setSelected (true, true);
  44239. else if (item->isSelected())
  44240. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44241. else
  44242. selectBasedOnModifiers (item, e.mods);
  44243. if (e.x >= pos.getX())
  44244. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44245. }
  44246. }
  44247. void mouseUp (const MouseEvent& e)
  44248. {
  44249. updateButtonUnderMouse (e);
  44250. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44251. {
  44252. Rectangle<int> pos;
  44253. TreeViewItem* const item = findItemAt (e.y, pos);
  44254. if (item != 0)
  44255. selectBasedOnModifiers (item, e.mods);
  44256. }
  44257. }
  44258. void mouseDoubleClick (const MouseEvent& e)
  44259. {
  44260. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44261. {
  44262. Rectangle<int> pos;
  44263. TreeViewItem* const item = findItemAt (e.y, pos);
  44264. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44265. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44266. }
  44267. }
  44268. void mouseDrag (const MouseEvent& e)
  44269. {
  44270. if (isEnabled()
  44271. && ! (isDragging || e.mouseWasClicked()
  44272. || e.getDistanceFromDragStart() < 5
  44273. || e.mods.isPopupMenu()))
  44274. {
  44275. isDragging = true;
  44276. Rectangle<int> pos;
  44277. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44278. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44279. {
  44280. const String dragDescription (item->getDragSourceDescription());
  44281. if (dragDescription.isNotEmpty())
  44282. {
  44283. DragAndDropContainer* const dragContainer
  44284. = DragAndDropContainer::findParentDragContainerFor (this);
  44285. if (dragContainer != 0)
  44286. {
  44287. pos.setSize (pos.getWidth(), item->itemHeight);
  44288. Image dragImage (Component::createComponentSnapshot (pos, true));
  44289. dragImage.multiplyAllAlphas (0.6f);
  44290. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44291. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44292. }
  44293. else
  44294. {
  44295. // to be able to do a drag-and-drop operation, the treeview needs to
  44296. // be inside a component which is also a DragAndDropContainer.
  44297. jassertfalse;
  44298. }
  44299. }
  44300. }
  44301. }
  44302. }
  44303. void mouseMove (const MouseEvent& e)
  44304. {
  44305. updateButtonUnderMouse (e);
  44306. }
  44307. void mouseExit (const MouseEvent& e)
  44308. {
  44309. updateButtonUnderMouse (e);
  44310. }
  44311. void paint (Graphics& g)
  44312. {
  44313. if (owner.rootItem != 0)
  44314. {
  44315. owner.handleAsyncUpdate();
  44316. if (! owner.rootItemVisible)
  44317. g.setOrigin (0, -owner.rootItem->itemHeight);
  44318. owner.rootItem->paintRecursively (g, getWidth());
  44319. }
  44320. }
  44321. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44322. {
  44323. if (owner.rootItem != 0)
  44324. {
  44325. owner.handleAsyncUpdate();
  44326. if (! owner.rootItemVisible)
  44327. y += owner.rootItem->itemHeight;
  44328. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44329. if (ti != 0)
  44330. itemPosition = ti->getItemPosition (false);
  44331. return ti;
  44332. }
  44333. return 0;
  44334. }
  44335. void updateComponents()
  44336. {
  44337. const int visibleTop = -getY();
  44338. const int visibleBottom = visibleTop + getParentHeight();
  44339. BigInteger itemsToKeep;
  44340. {
  44341. TreeViewItem* item = owner.rootItem;
  44342. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44343. while (item != 0 && y < visibleBottom)
  44344. {
  44345. y += item->itemHeight;
  44346. if (y >= visibleTop)
  44347. {
  44348. const int index = rowComponentIds.indexOf (item->uid);
  44349. if (index < 0)
  44350. {
  44351. Component* const comp = item->createItemComponent();
  44352. if (comp != 0)
  44353. {
  44354. addAndMakeVisible (comp);
  44355. itemsToKeep.setBit (rowComponentItems.size());
  44356. rowComponentItems.add (item);
  44357. rowComponentIds.add (item->uid);
  44358. rowComponents.add (comp);
  44359. }
  44360. }
  44361. else
  44362. {
  44363. itemsToKeep.setBit (index);
  44364. }
  44365. }
  44366. item = item->getNextVisibleItem (true);
  44367. }
  44368. }
  44369. for (int i = rowComponentItems.size(); --i >= 0;)
  44370. {
  44371. Component* const comp = rowComponents.getUnchecked(i);
  44372. bool keep = false;
  44373. if (isParentOf (comp))
  44374. {
  44375. if (itemsToKeep[i])
  44376. {
  44377. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44378. Rectangle<int> pos (item->getItemPosition (false));
  44379. pos.setSize (pos.getWidth(), item->itemHeight);
  44380. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44381. {
  44382. keep = true;
  44383. comp->setBounds (pos);
  44384. }
  44385. }
  44386. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44387. {
  44388. keep = true;
  44389. comp->setSize (0, 0);
  44390. }
  44391. }
  44392. if (! keep)
  44393. {
  44394. delete comp;
  44395. rowComponents.remove (i);
  44396. rowComponentIds.remove (i);
  44397. rowComponentItems.remove (i);
  44398. }
  44399. }
  44400. }
  44401. void updateButtonUnderMouse (const MouseEvent& e)
  44402. {
  44403. TreeViewItem* newItem = 0;
  44404. if (owner.openCloseButtonsVisible)
  44405. {
  44406. Rectangle<int> pos;
  44407. TreeViewItem* item = findItemAt (e.y, pos);
  44408. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44409. {
  44410. newItem = item;
  44411. if (! newItem->mightContainSubItems())
  44412. newItem = 0;
  44413. }
  44414. }
  44415. if (buttonUnderMouse != newItem)
  44416. {
  44417. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44418. {
  44419. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44420. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44421. }
  44422. buttonUnderMouse = newItem;
  44423. if (buttonUnderMouse != 0)
  44424. {
  44425. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44426. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44427. }
  44428. }
  44429. }
  44430. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44431. {
  44432. return item == buttonUnderMouse;
  44433. }
  44434. void resized()
  44435. {
  44436. owner.itemsChanged();
  44437. }
  44438. const String getTooltip()
  44439. {
  44440. Rectangle<int> pos;
  44441. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44442. if (item != 0)
  44443. return item->getTooltip();
  44444. return owner.getTooltip();
  44445. }
  44446. juce_UseDebuggingNewOperator
  44447. private:
  44448. TreeView& owner;
  44449. Array <TreeViewItem*> rowComponentItems;
  44450. Array <int> rowComponentIds;
  44451. Array <Component*> rowComponents;
  44452. TreeViewItem* buttonUnderMouse;
  44453. bool isDragging, needSelectionOnMouseUp;
  44454. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44455. {
  44456. TreeViewItem* firstSelected = 0;
  44457. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44458. {
  44459. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44460. jassert (lastSelected != 0);
  44461. int rowStart = firstSelected->getRowNumberInTree();
  44462. int rowEnd = lastSelected->getRowNumberInTree();
  44463. if (rowStart > rowEnd)
  44464. swapVariables (rowStart, rowEnd);
  44465. int ourRow = item->getRowNumberInTree();
  44466. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44467. if (ourRow > otherEnd)
  44468. swapVariables (ourRow, otherEnd);
  44469. for (int i = ourRow; i <= otherEnd; ++i)
  44470. owner.getItemOnRow (i)->setSelected (true, false);
  44471. }
  44472. else
  44473. {
  44474. const bool cmd = modifiers.isCommandDown();
  44475. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44476. }
  44477. }
  44478. bool containsItem (TreeViewItem* const item) const
  44479. {
  44480. for (int i = rowComponentItems.size(); --i >= 0;)
  44481. if (rowComponentItems.getUnchecked(i) == item)
  44482. return true;
  44483. return false;
  44484. }
  44485. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44486. {
  44487. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44488. {
  44489. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44490. if (source->isDragging())
  44491. {
  44492. Component* const underMouse = source->getComponentUnderMouse();
  44493. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44494. return true;
  44495. }
  44496. }
  44497. return false;
  44498. }
  44499. TreeViewContentComponent (const TreeViewContentComponent&);
  44500. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44501. };
  44502. class TreeView::TreeViewport : public Viewport
  44503. {
  44504. public:
  44505. TreeViewport() throw() : lastX (-1) {}
  44506. ~TreeViewport() throw() {}
  44507. void updateComponents (const bool triggerResize = false)
  44508. {
  44509. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44510. if (tvc != 0)
  44511. {
  44512. if (triggerResize)
  44513. tvc->resized();
  44514. else
  44515. tvc->updateComponents();
  44516. }
  44517. repaint();
  44518. }
  44519. void visibleAreaChanged (int x, int, int, int)
  44520. {
  44521. const bool hasScrolledSideways = (x != lastX);
  44522. lastX = x;
  44523. updateComponents (hasScrolledSideways);
  44524. }
  44525. juce_UseDebuggingNewOperator
  44526. private:
  44527. int lastX;
  44528. TreeViewport (const TreeViewport&);
  44529. TreeViewport& operator= (const TreeViewport&);
  44530. };
  44531. TreeView::TreeView (const String& componentName)
  44532. : Component (componentName),
  44533. rootItem (0),
  44534. dragInsertPointHighlight (0),
  44535. dragTargetGroupHighlight (0),
  44536. indentSize (24),
  44537. defaultOpenness (false),
  44538. needsRecalculating (true),
  44539. rootItemVisible (true),
  44540. multiSelectEnabled (false),
  44541. openCloseButtonsVisible (true)
  44542. {
  44543. addAndMakeVisible (viewport = new TreeViewport());
  44544. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44545. viewport->setWantsKeyboardFocus (false);
  44546. setWantsKeyboardFocus (true);
  44547. }
  44548. TreeView::~TreeView()
  44549. {
  44550. if (rootItem != 0)
  44551. rootItem->setOwnerView (0);
  44552. deleteAllChildren();
  44553. }
  44554. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44555. {
  44556. if (rootItem != newRootItem)
  44557. {
  44558. if (newRootItem != 0)
  44559. {
  44560. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44561. if (newRootItem->ownerView != 0)
  44562. newRootItem->ownerView->setRootItem (0);
  44563. }
  44564. if (rootItem != 0)
  44565. rootItem->setOwnerView (0);
  44566. rootItem = newRootItem;
  44567. if (newRootItem != 0)
  44568. newRootItem->setOwnerView (this);
  44569. needsRecalculating = true;
  44570. handleAsyncUpdate();
  44571. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44572. {
  44573. rootItem->setOpen (false); // force a re-open
  44574. rootItem->setOpen (true);
  44575. }
  44576. }
  44577. }
  44578. void TreeView::deleteRootItem()
  44579. {
  44580. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44581. setRootItem (0);
  44582. }
  44583. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44584. {
  44585. rootItemVisible = shouldBeVisible;
  44586. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44587. {
  44588. rootItem->setOpen (false); // force a re-open
  44589. rootItem->setOpen (true);
  44590. }
  44591. itemsChanged();
  44592. }
  44593. void TreeView::colourChanged()
  44594. {
  44595. setOpaque (findColour (backgroundColourId).isOpaque());
  44596. repaint();
  44597. }
  44598. void TreeView::setIndentSize (const int newIndentSize)
  44599. {
  44600. if (indentSize != newIndentSize)
  44601. {
  44602. indentSize = newIndentSize;
  44603. resized();
  44604. }
  44605. }
  44606. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44607. {
  44608. if (defaultOpenness != isOpenByDefault)
  44609. {
  44610. defaultOpenness = isOpenByDefault;
  44611. itemsChanged();
  44612. }
  44613. }
  44614. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44615. {
  44616. multiSelectEnabled = canMultiSelect;
  44617. }
  44618. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44619. {
  44620. if (openCloseButtonsVisible != shouldBeVisible)
  44621. {
  44622. openCloseButtonsVisible = shouldBeVisible;
  44623. itemsChanged();
  44624. }
  44625. }
  44626. Viewport* TreeView::getViewport() const throw()
  44627. {
  44628. return viewport;
  44629. }
  44630. void TreeView::clearSelectedItems()
  44631. {
  44632. if (rootItem != 0)
  44633. rootItem->deselectAllRecursively();
  44634. }
  44635. int TreeView::getNumSelectedItems() const throw()
  44636. {
  44637. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44638. }
  44639. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44640. {
  44641. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44642. }
  44643. int TreeView::getNumRowsInTree() const
  44644. {
  44645. if (rootItem != 0)
  44646. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44647. return 0;
  44648. }
  44649. TreeViewItem* TreeView::getItemOnRow (int index) const
  44650. {
  44651. if (! rootItemVisible)
  44652. ++index;
  44653. if (rootItem != 0 && index >= 0)
  44654. return rootItem->getItemOnRow (index);
  44655. return 0;
  44656. }
  44657. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44658. {
  44659. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44660. Rectangle<int> pos;
  44661. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44662. }
  44663. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44664. {
  44665. if (rootItem == 0)
  44666. return 0;
  44667. return rootItem->findItemFromIdentifierString (identifierString);
  44668. }
  44669. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44670. {
  44671. XmlElement* e = 0;
  44672. if (rootItem != 0)
  44673. {
  44674. e = rootItem->getOpennessState();
  44675. if (e != 0 && alsoIncludeScrollPosition)
  44676. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44677. }
  44678. return e;
  44679. }
  44680. void TreeView::restoreOpennessState (const XmlElement& newState)
  44681. {
  44682. if (rootItem != 0)
  44683. {
  44684. rootItem->restoreOpennessState (newState);
  44685. if (newState.hasAttribute ("scrollPos"))
  44686. viewport->setViewPosition (viewport->getViewPositionX(),
  44687. newState.getIntAttribute ("scrollPos"));
  44688. }
  44689. }
  44690. void TreeView::paint (Graphics& g)
  44691. {
  44692. g.fillAll (findColour (backgroundColourId));
  44693. }
  44694. void TreeView::resized()
  44695. {
  44696. viewport->setBounds (0, 0, getWidth(), getHeight());
  44697. itemsChanged();
  44698. handleAsyncUpdate();
  44699. }
  44700. void TreeView::enablementChanged()
  44701. {
  44702. repaint();
  44703. }
  44704. void TreeView::moveSelectedRow (int delta)
  44705. {
  44706. if (delta == 0)
  44707. return;
  44708. int rowSelected = 0;
  44709. TreeViewItem* const firstSelected = getSelectedItem (0);
  44710. if (firstSelected != 0)
  44711. rowSelected = firstSelected->getRowNumberInTree();
  44712. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44713. for (;;)
  44714. {
  44715. TreeViewItem* item = getItemOnRow (rowSelected);
  44716. if (item != 0)
  44717. {
  44718. if (! item->canBeSelected())
  44719. {
  44720. // if the row we want to highlight doesn't allow it, try skipping
  44721. // to the next item..
  44722. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44723. rowSelected + (delta < 0 ? -1 : 1));
  44724. if (rowSelected != nextRowToTry)
  44725. {
  44726. rowSelected = nextRowToTry;
  44727. continue;
  44728. }
  44729. else
  44730. {
  44731. break;
  44732. }
  44733. }
  44734. item->setSelected (true, true);
  44735. scrollToKeepItemVisible (item);
  44736. }
  44737. break;
  44738. }
  44739. }
  44740. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44741. {
  44742. if (item != 0 && item->ownerView == this)
  44743. {
  44744. handleAsyncUpdate();
  44745. item = item->getDeepestOpenParentItem();
  44746. int y = item->y;
  44747. int viewTop = viewport->getViewPositionY();
  44748. if (y < viewTop)
  44749. {
  44750. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44751. }
  44752. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44753. {
  44754. viewport->setViewPosition (viewport->getViewPositionX(),
  44755. (y + item->itemHeight) - viewport->getViewHeight());
  44756. }
  44757. }
  44758. }
  44759. bool TreeView::keyPressed (const KeyPress& key)
  44760. {
  44761. if (key.isKeyCode (KeyPress::upKey))
  44762. {
  44763. moveSelectedRow (-1);
  44764. }
  44765. else if (key.isKeyCode (KeyPress::downKey))
  44766. {
  44767. moveSelectedRow (1);
  44768. }
  44769. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44770. {
  44771. if (rootItem != 0)
  44772. {
  44773. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44774. if (key.isKeyCode (KeyPress::pageUpKey))
  44775. rowsOnScreen = -rowsOnScreen;
  44776. moveSelectedRow (rowsOnScreen);
  44777. }
  44778. }
  44779. else if (key.isKeyCode (KeyPress::homeKey))
  44780. {
  44781. moveSelectedRow (-0x3fffffff);
  44782. }
  44783. else if (key.isKeyCode (KeyPress::endKey))
  44784. {
  44785. moveSelectedRow (0x3fffffff);
  44786. }
  44787. else if (key.isKeyCode (KeyPress::returnKey))
  44788. {
  44789. TreeViewItem* const firstSelected = getSelectedItem (0);
  44790. if (firstSelected != 0)
  44791. firstSelected->setOpen (! firstSelected->isOpen());
  44792. }
  44793. else if (key.isKeyCode (KeyPress::leftKey))
  44794. {
  44795. TreeViewItem* const firstSelected = getSelectedItem (0);
  44796. if (firstSelected != 0)
  44797. {
  44798. if (firstSelected->isOpen())
  44799. {
  44800. firstSelected->setOpen (false);
  44801. }
  44802. else
  44803. {
  44804. TreeViewItem* parent = firstSelected->parentItem;
  44805. if ((! rootItemVisible) && parent == rootItem)
  44806. parent = 0;
  44807. if (parent != 0)
  44808. {
  44809. parent->setSelected (true, true);
  44810. scrollToKeepItemVisible (parent);
  44811. }
  44812. }
  44813. }
  44814. }
  44815. else if (key.isKeyCode (KeyPress::rightKey))
  44816. {
  44817. TreeViewItem* const firstSelected = getSelectedItem (0);
  44818. if (firstSelected != 0)
  44819. {
  44820. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  44821. moveSelectedRow (1);
  44822. else
  44823. firstSelected->setOpen (true);
  44824. }
  44825. }
  44826. else
  44827. {
  44828. return false;
  44829. }
  44830. return true;
  44831. }
  44832. void TreeView::itemsChanged() throw()
  44833. {
  44834. needsRecalculating = true;
  44835. repaint();
  44836. triggerAsyncUpdate();
  44837. }
  44838. void TreeView::handleAsyncUpdate()
  44839. {
  44840. if (needsRecalculating)
  44841. {
  44842. needsRecalculating = false;
  44843. const ScopedLock sl (nodeAlterationLock);
  44844. if (rootItem != 0)
  44845. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  44846. viewport->updateComponents();
  44847. if (rootItem != 0)
  44848. {
  44849. viewport->getViewedComponent()
  44850. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  44851. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  44852. }
  44853. else
  44854. {
  44855. viewport->getViewedComponent()->setSize (0, 0);
  44856. }
  44857. }
  44858. }
  44859. class TreeView::InsertPointHighlight : public Component
  44860. {
  44861. public:
  44862. InsertPointHighlight()
  44863. : lastItem (0)
  44864. {
  44865. setSize (100, 12);
  44866. setAlwaysOnTop (true);
  44867. setInterceptsMouseClicks (false, false);
  44868. }
  44869. ~InsertPointHighlight() {}
  44870. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  44871. {
  44872. lastItem = item;
  44873. lastIndex = insertIndex;
  44874. const int offset = getHeight() / 2;
  44875. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  44876. }
  44877. void paint (Graphics& g)
  44878. {
  44879. Path p;
  44880. const float h = (float) getHeight();
  44881. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  44882. p.startNewSubPath (h - 2.0f, h / 2.0f);
  44883. p.lineTo ((float) getWidth(), h / 2.0f);
  44884. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44885. g.strokePath (p, PathStrokeType (2.0f));
  44886. }
  44887. TreeViewItem* lastItem;
  44888. int lastIndex;
  44889. private:
  44890. InsertPointHighlight (const InsertPointHighlight&);
  44891. InsertPointHighlight& operator= (const InsertPointHighlight&);
  44892. };
  44893. class TreeView::TargetGroupHighlight : public Component
  44894. {
  44895. public:
  44896. TargetGroupHighlight()
  44897. {
  44898. setAlwaysOnTop (true);
  44899. setInterceptsMouseClicks (false, false);
  44900. }
  44901. ~TargetGroupHighlight() {}
  44902. void setTargetPosition (TreeViewItem* const item) throw()
  44903. {
  44904. Rectangle<int> r (item->getItemPosition (true));
  44905. r.setHeight (item->getItemHeight());
  44906. setBounds (r);
  44907. }
  44908. void paint (Graphics& g)
  44909. {
  44910. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44911. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  44912. }
  44913. private:
  44914. TargetGroupHighlight (const TargetGroupHighlight&);
  44915. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  44916. };
  44917. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  44918. {
  44919. beginDragAutoRepeat (1000 / 30);
  44920. if (dragInsertPointHighlight == 0)
  44921. {
  44922. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  44923. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  44924. }
  44925. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  44926. dragTargetGroupHighlight->setTargetPosition (item);
  44927. }
  44928. void TreeView::hideDragHighlight() throw()
  44929. {
  44930. deleteAndZero (dragInsertPointHighlight);
  44931. deleteAndZero (dragTargetGroupHighlight);
  44932. }
  44933. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  44934. const StringArray& files, const String& sourceDescription,
  44935. Component* sourceComponent) const throw()
  44936. {
  44937. insertIndex = 0;
  44938. TreeViewItem* item = getItemAt (y);
  44939. if (item == 0)
  44940. return 0;
  44941. Rectangle<int> itemPos (item->getItemPosition (true));
  44942. insertIndex = item->getIndexInParent();
  44943. const int oldY = y;
  44944. y = itemPos.getY();
  44945. if (item->getNumSubItems() == 0 || ! item->isOpen())
  44946. {
  44947. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44948. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44949. {
  44950. // Check if we're trying to drag into an empty group item..
  44951. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  44952. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  44953. {
  44954. insertIndex = 0;
  44955. x = itemPos.getX() + getIndentSize();
  44956. y = itemPos.getBottom();
  44957. return item;
  44958. }
  44959. }
  44960. }
  44961. if (oldY > itemPos.getCentreY())
  44962. {
  44963. y += item->getItemHeight();
  44964. while (item->isLastOfSiblings() && item->parentItem != 0
  44965. && item->parentItem->parentItem != 0)
  44966. {
  44967. if (x > itemPos.getX())
  44968. break;
  44969. item = item->parentItem;
  44970. itemPos = item->getItemPosition (true);
  44971. insertIndex = item->getIndexInParent();
  44972. }
  44973. ++insertIndex;
  44974. }
  44975. x = itemPos.getX();
  44976. return item->parentItem;
  44977. }
  44978. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  44979. {
  44980. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  44981. int insertIndex;
  44982. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  44983. if (item != 0)
  44984. {
  44985. if (scrolled || dragInsertPointHighlight == 0
  44986. || dragInsertPointHighlight->lastItem != item
  44987. || dragInsertPointHighlight->lastIndex != insertIndex)
  44988. {
  44989. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44990. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44991. showDragHighlight (item, insertIndex, x, y);
  44992. else
  44993. hideDragHighlight();
  44994. }
  44995. }
  44996. else
  44997. {
  44998. hideDragHighlight();
  44999. }
  45000. }
  45001. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45002. {
  45003. hideDragHighlight();
  45004. int insertIndex;
  45005. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45006. if (item != 0)
  45007. {
  45008. if (files.size() > 0)
  45009. {
  45010. if (item->isInterestedInFileDrag (files))
  45011. item->filesDropped (files, insertIndex);
  45012. }
  45013. else
  45014. {
  45015. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45016. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45017. }
  45018. }
  45019. }
  45020. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45021. {
  45022. return true;
  45023. }
  45024. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45025. {
  45026. fileDragMove (files, x, y);
  45027. }
  45028. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45029. {
  45030. handleDrag (files, String::empty, 0, x, y);
  45031. }
  45032. void TreeView::fileDragExit (const StringArray&)
  45033. {
  45034. hideDragHighlight();
  45035. }
  45036. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45037. {
  45038. handleDrop (files, String::empty, 0, x, y);
  45039. }
  45040. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45041. {
  45042. return true;
  45043. }
  45044. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45045. {
  45046. itemDragMove (sourceDescription, sourceComponent, x, y);
  45047. }
  45048. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45049. {
  45050. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45051. }
  45052. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45053. {
  45054. hideDragHighlight();
  45055. }
  45056. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45057. {
  45058. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45059. }
  45060. enum TreeViewOpenness
  45061. {
  45062. opennessDefault = 0,
  45063. opennessClosed = 1,
  45064. opennessOpen = 2
  45065. };
  45066. TreeViewItem::TreeViewItem()
  45067. : ownerView (0),
  45068. parentItem (0),
  45069. y (0),
  45070. itemHeight (0),
  45071. totalHeight (0),
  45072. selected (false),
  45073. redrawNeeded (true),
  45074. drawLinesInside (true),
  45075. drawsInLeftMargin (false),
  45076. openness (opennessDefault)
  45077. {
  45078. static int nextUID = 0;
  45079. uid = nextUID++;
  45080. }
  45081. TreeViewItem::~TreeViewItem()
  45082. {
  45083. }
  45084. const String TreeViewItem::getUniqueName() const
  45085. {
  45086. return String::empty;
  45087. }
  45088. void TreeViewItem::itemOpennessChanged (bool)
  45089. {
  45090. }
  45091. int TreeViewItem::getNumSubItems() const throw()
  45092. {
  45093. return subItems.size();
  45094. }
  45095. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45096. {
  45097. return subItems [index];
  45098. }
  45099. void TreeViewItem::clearSubItems()
  45100. {
  45101. if (subItems.size() > 0)
  45102. {
  45103. if (ownerView != 0)
  45104. {
  45105. const ScopedLock sl (ownerView->nodeAlterationLock);
  45106. subItems.clear();
  45107. treeHasChanged();
  45108. }
  45109. else
  45110. {
  45111. subItems.clear();
  45112. }
  45113. }
  45114. }
  45115. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45116. {
  45117. if (newItem != 0)
  45118. {
  45119. newItem->parentItem = this;
  45120. newItem->setOwnerView (ownerView);
  45121. newItem->y = 0;
  45122. newItem->itemHeight = newItem->getItemHeight();
  45123. newItem->totalHeight = 0;
  45124. newItem->itemWidth = newItem->getItemWidth();
  45125. newItem->totalWidth = 0;
  45126. if (ownerView != 0)
  45127. {
  45128. const ScopedLock sl (ownerView->nodeAlterationLock);
  45129. subItems.insert (insertPosition, newItem);
  45130. treeHasChanged();
  45131. if (newItem->isOpen())
  45132. newItem->itemOpennessChanged (true);
  45133. }
  45134. else
  45135. {
  45136. subItems.insert (insertPosition, newItem);
  45137. if (newItem->isOpen())
  45138. newItem->itemOpennessChanged (true);
  45139. }
  45140. }
  45141. }
  45142. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45143. {
  45144. if (ownerView != 0)
  45145. {
  45146. const ScopedLock sl (ownerView->nodeAlterationLock);
  45147. if (((unsigned int) index) < (unsigned int) subItems.size())
  45148. {
  45149. subItems.remove (index, deleteItem);
  45150. treeHasChanged();
  45151. }
  45152. }
  45153. else
  45154. {
  45155. subItems.remove (index, deleteItem);
  45156. }
  45157. }
  45158. bool TreeViewItem::isOpen() const throw()
  45159. {
  45160. if (openness == opennessDefault)
  45161. return ownerView != 0 && ownerView->defaultOpenness;
  45162. else
  45163. return openness == opennessOpen;
  45164. }
  45165. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45166. {
  45167. if (isOpen() != shouldBeOpen)
  45168. {
  45169. openness = shouldBeOpen ? opennessOpen
  45170. : opennessClosed;
  45171. treeHasChanged();
  45172. itemOpennessChanged (isOpen());
  45173. }
  45174. }
  45175. bool TreeViewItem::isSelected() const throw()
  45176. {
  45177. return selected;
  45178. }
  45179. void TreeViewItem::deselectAllRecursively()
  45180. {
  45181. setSelected (false, false);
  45182. for (int i = 0; i < subItems.size(); ++i)
  45183. subItems.getUnchecked(i)->deselectAllRecursively();
  45184. }
  45185. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45186. const bool deselectOtherItemsFirst)
  45187. {
  45188. if (shouldBeSelected && ! canBeSelected())
  45189. return;
  45190. if (deselectOtherItemsFirst)
  45191. getTopLevelItem()->deselectAllRecursively();
  45192. if (shouldBeSelected != selected)
  45193. {
  45194. selected = shouldBeSelected;
  45195. if (ownerView != 0)
  45196. ownerView->repaint();
  45197. itemSelectionChanged (shouldBeSelected);
  45198. }
  45199. }
  45200. void TreeViewItem::paintItem (Graphics&, int, int)
  45201. {
  45202. }
  45203. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45204. {
  45205. ownerView->getLookAndFeel()
  45206. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45207. }
  45208. void TreeViewItem::itemClicked (const MouseEvent&)
  45209. {
  45210. }
  45211. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45212. {
  45213. if (mightContainSubItems())
  45214. setOpen (! isOpen());
  45215. }
  45216. void TreeViewItem::itemSelectionChanged (bool)
  45217. {
  45218. }
  45219. const String TreeViewItem::getTooltip()
  45220. {
  45221. return String::empty;
  45222. }
  45223. const String TreeViewItem::getDragSourceDescription()
  45224. {
  45225. return String::empty;
  45226. }
  45227. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45228. {
  45229. return false;
  45230. }
  45231. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45232. {
  45233. }
  45234. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45235. {
  45236. return false;
  45237. }
  45238. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45239. {
  45240. }
  45241. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45242. {
  45243. const int indentX = getIndentX();
  45244. int width = itemWidth;
  45245. if (ownerView != 0 && width < 0)
  45246. width = ownerView->viewport->getViewWidth() - indentX;
  45247. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45248. if (relativeToTreeViewTopLeft)
  45249. r -= ownerView->viewport->getViewPosition();
  45250. return r;
  45251. }
  45252. void TreeViewItem::treeHasChanged() const throw()
  45253. {
  45254. if (ownerView != 0)
  45255. ownerView->itemsChanged();
  45256. }
  45257. void TreeViewItem::repaintItem() const
  45258. {
  45259. if (ownerView != 0 && areAllParentsOpen())
  45260. {
  45261. Rectangle<int> r (getItemPosition (true));
  45262. r.setLeft (0);
  45263. ownerView->viewport->repaint (r);
  45264. }
  45265. }
  45266. bool TreeViewItem::areAllParentsOpen() const throw()
  45267. {
  45268. return parentItem == 0
  45269. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45270. }
  45271. void TreeViewItem::updatePositions (int newY)
  45272. {
  45273. y = newY;
  45274. itemHeight = getItemHeight();
  45275. totalHeight = itemHeight;
  45276. itemWidth = getItemWidth();
  45277. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45278. if (isOpen())
  45279. {
  45280. newY += totalHeight;
  45281. for (int i = 0; i < subItems.size(); ++i)
  45282. {
  45283. TreeViewItem* const ti = subItems.getUnchecked(i);
  45284. ti->updatePositions (newY);
  45285. newY += ti->totalHeight;
  45286. totalHeight += ti->totalHeight;
  45287. totalWidth = jmax (totalWidth, ti->totalWidth);
  45288. }
  45289. }
  45290. }
  45291. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45292. {
  45293. TreeViewItem* result = this;
  45294. TreeViewItem* item = this;
  45295. while (item->parentItem != 0)
  45296. {
  45297. item = item->parentItem;
  45298. if (! item->isOpen())
  45299. result = item;
  45300. }
  45301. return result;
  45302. }
  45303. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45304. {
  45305. ownerView = newOwner;
  45306. for (int i = subItems.size(); --i >= 0;)
  45307. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45308. }
  45309. int TreeViewItem::getIndentX() const throw()
  45310. {
  45311. const int indentWidth = ownerView->getIndentSize();
  45312. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45313. if (! ownerView->openCloseButtonsVisible)
  45314. x -= indentWidth;
  45315. TreeViewItem* p = parentItem;
  45316. while (p != 0)
  45317. {
  45318. x += indentWidth;
  45319. p = p->parentItem;
  45320. }
  45321. return x;
  45322. }
  45323. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45324. {
  45325. drawsInLeftMargin = canDrawInLeftMargin;
  45326. }
  45327. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45328. {
  45329. jassert (ownerView != 0);
  45330. if (ownerView == 0)
  45331. return;
  45332. const int indent = getIndentX();
  45333. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45334. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45335. const float halfH = itemHeight * 0.5f;
  45336. int depth = 0;
  45337. TreeViewItem* p = parentItem;
  45338. while (p != 0)
  45339. {
  45340. ++depth;
  45341. p = p->parentItem;
  45342. }
  45343. if (! ownerView->rootItemVisible)
  45344. --depth;
  45345. const int indentWidth = ownerView->getIndentSize();
  45346. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45347. {
  45348. float x = (depth + 0.5f) * indentWidth;
  45349. if (depth >= 0)
  45350. {
  45351. if (parentItem != 0 && parentItem->drawLinesInside)
  45352. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45353. if ((parentItem != 0 && parentItem->drawLinesInside)
  45354. || (parentItem == 0 && drawLinesInside))
  45355. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45356. }
  45357. p = parentItem;
  45358. int d = depth;
  45359. while (p != 0 && --d >= 0)
  45360. {
  45361. x -= (float) indentWidth;
  45362. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45363. && ! p->isLastOfSiblings())
  45364. {
  45365. g.drawLine (x, 0, x, (float) itemHeight);
  45366. }
  45367. p = p->parentItem;
  45368. }
  45369. if (mightContainSubItems())
  45370. {
  45371. g.saveState();
  45372. g.setOrigin (depth * indentWidth, 0);
  45373. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45374. paintOpenCloseButton (g, indentWidth, itemHeight,
  45375. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45376. ->isMouseOverButton (this));
  45377. g.restoreState();
  45378. }
  45379. }
  45380. {
  45381. g.saveState();
  45382. g.setOrigin (indent, 0);
  45383. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45384. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45385. paintItem (g, itemW, itemHeight);
  45386. g.restoreState();
  45387. }
  45388. if (isOpen())
  45389. {
  45390. const Rectangle<int> clip (g.getClipBounds());
  45391. for (int i = 0; i < subItems.size(); ++i)
  45392. {
  45393. TreeViewItem* const ti = subItems.getUnchecked(i);
  45394. const int relY = ti->y - y;
  45395. if (relY >= clip.getBottom())
  45396. break;
  45397. if (relY + ti->totalHeight >= clip.getY())
  45398. {
  45399. g.saveState();
  45400. g.setOrigin (0, relY);
  45401. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45402. ti->paintRecursively (g, width);
  45403. g.restoreState();
  45404. }
  45405. }
  45406. }
  45407. }
  45408. bool TreeViewItem::isLastOfSiblings() const throw()
  45409. {
  45410. return parentItem == 0
  45411. || parentItem->subItems.getLast() == this;
  45412. }
  45413. int TreeViewItem::getIndexInParent() const throw()
  45414. {
  45415. if (parentItem == 0)
  45416. return 0;
  45417. return parentItem->subItems.indexOf (this);
  45418. }
  45419. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45420. {
  45421. return (parentItem == 0) ? this
  45422. : parentItem->getTopLevelItem();
  45423. }
  45424. int TreeViewItem::getNumRows() const throw()
  45425. {
  45426. int num = 1;
  45427. if (isOpen())
  45428. {
  45429. for (int i = subItems.size(); --i >= 0;)
  45430. num += subItems.getUnchecked(i)->getNumRows();
  45431. }
  45432. return num;
  45433. }
  45434. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45435. {
  45436. if (index == 0)
  45437. return this;
  45438. if (index > 0 && isOpen())
  45439. {
  45440. --index;
  45441. for (int i = 0; i < subItems.size(); ++i)
  45442. {
  45443. TreeViewItem* const item = subItems.getUnchecked(i);
  45444. if (index == 0)
  45445. return item;
  45446. const int numRows = item->getNumRows();
  45447. if (numRows > index)
  45448. return item->getItemOnRow (index);
  45449. index -= numRows;
  45450. }
  45451. }
  45452. return 0;
  45453. }
  45454. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45455. {
  45456. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45457. {
  45458. const int h = itemHeight;
  45459. if (targetY < h)
  45460. return this;
  45461. if (isOpen())
  45462. {
  45463. targetY -= h;
  45464. for (int i = 0; i < subItems.size(); ++i)
  45465. {
  45466. TreeViewItem* const ti = subItems.getUnchecked(i);
  45467. if (targetY < ti->totalHeight)
  45468. return ti->findItemRecursively (targetY);
  45469. targetY -= ti->totalHeight;
  45470. }
  45471. }
  45472. }
  45473. return 0;
  45474. }
  45475. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45476. {
  45477. int total = 0;
  45478. if (isSelected())
  45479. ++total;
  45480. for (int i = subItems.size(); --i >= 0;)
  45481. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45482. return total;
  45483. }
  45484. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45485. {
  45486. if (isSelected())
  45487. {
  45488. if (index == 0)
  45489. return this;
  45490. --index;
  45491. }
  45492. if (index >= 0)
  45493. {
  45494. for (int i = 0; i < subItems.size(); ++i)
  45495. {
  45496. TreeViewItem* const item = subItems.getUnchecked(i);
  45497. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45498. if (found != 0)
  45499. return found;
  45500. index -= item->countSelectedItemsRecursively();
  45501. }
  45502. }
  45503. return 0;
  45504. }
  45505. int TreeViewItem::getRowNumberInTree() const throw()
  45506. {
  45507. if (parentItem != 0 && ownerView != 0)
  45508. {
  45509. int n = 1 + parentItem->getRowNumberInTree();
  45510. int ourIndex = parentItem->subItems.indexOf (this);
  45511. jassert (ourIndex >= 0);
  45512. while (--ourIndex >= 0)
  45513. n += parentItem->subItems [ourIndex]->getNumRows();
  45514. if (parentItem->parentItem == 0
  45515. && ! ownerView->rootItemVisible)
  45516. --n;
  45517. return n;
  45518. }
  45519. else
  45520. {
  45521. return 0;
  45522. }
  45523. }
  45524. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45525. {
  45526. drawLinesInside = drawLines;
  45527. }
  45528. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45529. {
  45530. if (recurse && isOpen() && subItems.size() > 0)
  45531. return subItems [0];
  45532. if (parentItem != 0)
  45533. {
  45534. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45535. if (nextIndex >= parentItem->subItems.size())
  45536. return parentItem->getNextVisibleItem (false);
  45537. return parentItem->subItems [nextIndex];
  45538. }
  45539. return 0;
  45540. }
  45541. const String TreeViewItem::getItemIdentifierString() const
  45542. {
  45543. String s;
  45544. if (parentItem != 0)
  45545. s = parentItem->getItemIdentifierString();
  45546. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45547. }
  45548. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45549. {
  45550. const String thisId (getUniqueName());
  45551. if (thisId == identifierString)
  45552. return this;
  45553. if (identifierString.startsWith (thisId + "/"))
  45554. {
  45555. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45556. bool wasOpen = isOpen();
  45557. setOpen (true);
  45558. for (int i = subItems.size(); --i >= 0;)
  45559. {
  45560. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45561. if (item != 0)
  45562. return item;
  45563. }
  45564. setOpen (wasOpen);
  45565. }
  45566. return 0;
  45567. }
  45568. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45569. {
  45570. if (e.hasTagName ("CLOSED"))
  45571. {
  45572. setOpen (false);
  45573. }
  45574. else if (e.hasTagName ("OPEN"))
  45575. {
  45576. setOpen (true);
  45577. forEachXmlChildElement (e, n)
  45578. {
  45579. const String id (n->getStringAttribute ("id"));
  45580. for (int i = 0; i < subItems.size(); ++i)
  45581. {
  45582. TreeViewItem* const ti = subItems.getUnchecked(i);
  45583. if (ti->getUniqueName() == id)
  45584. {
  45585. ti->restoreOpennessState (*n);
  45586. break;
  45587. }
  45588. }
  45589. }
  45590. }
  45591. }
  45592. XmlElement* TreeViewItem::getOpennessState() const throw()
  45593. {
  45594. const String name (getUniqueName());
  45595. if (name.isNotEmpty())
  45596. {
  45597. XmlElement* e;
  45598. if (isOpen())
  45599. {
  45600. e = new XmlElement ("OPEN");
  45601. for (int i = 0; i < subItems.size(); ++i)
  45602. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45603. }
  45604. else
  45605. {
  45606. e = new XmlElement ("CLOSED");
  45607. }
  45608. e->setAttribute ("id", name);
  45609. return e;
  45610. }
  45611. else
  45612. {
  45613. // trying to save the openness for an element that has no name - this won't
  45614. // work because it needs the names to identify what to open.
  45615. jassertfalse;
  45616. }
  45617. return 0;
  45618. }
  45619. END_JUCE_NAMESPACE
  45620. /*** End of inlined file: juce_TreeView.cpp ***/
  45621. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45622. BEGIN_JUCE_NAMESPACE
  45623. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45624. : fileList (listToShow)
  45625. {
  45626. }
  45627. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45628. {
  45629. }
  45630. FileBrowserListener::~FileBrowserListener()
  45631. {
  45632. }
  45633. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45634. {
  45635. listeners.add (listener);
  45636. }
  45637. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45638. {
  45639. listeners.remove (listener);
  45640. }
  45641. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45642. {
  45643. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45644. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45645. }
  45646. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45647. {
  45648. if (fileList.getDirectory().exists())
  45649. {
  45650. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45651. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45652. }
  45653. }
  45654. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45655. {
  45656. if (fileList.getDirectory().exists())
  45657. {
  45658. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45659. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45660. }
  45661. }
  45662. END_JUCE_NAMESPACE
  45663. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45664. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45665. BEGIN_JUCE_NAMESPACE
  45666. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45667. TimeSliceThread& thread_)
  45668. : fileFilter (fileFilter_),
  45669. thread (thread_),
  45670. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45671. fileFindHandle (0),
  45672. shouldStop (true)
  45673. {
  45674. }
  45675. DirectoryContentsList::~DirectoryContentsList()
  45676. {
  45677. clear();
  45678. }
  45679. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45680. {
  45681. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45682. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45683. }
  45684. bool DirectoryContentsList::ignoresHiddenFiles() const
  45685. {
  45686. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45687. }
  45688. const File& DirectoryContentsList::getDirectory() const
  45689. {
  45690. return root;
  45691. }
  45692. void DirectoryContentsList::setDirectory (const File& directory,
  45693. const bool includeDirectories,
  45694. const bool includeFiles)
  45695. {
  45696. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45697. if (directory != root)
  45698. {
  45699. clear();
  45700. root = directory;
  45701. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45702. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45703. }
  45704. int newFlags = fileTypeFlags;
  45705. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45706. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45707. setTypeFlags (newFlags);
  45708. }
  45709. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45710. {
  45711. if (fileTypeFlags != newFlags)
  45712. {
  45713. fileTypeFlags = newFlags;
  45714. refresh();
  45715. }
  45716. }
  45717. void DirectoryContentsList::clear()
  45718. {
  45719. shouldStop = true;
  45720. thread.removeTimeSliceClient (this);
  45721. fileFindHandle = 0;
  45722. if (files.size() > 0)
  45723. {
  45724. files.clear();
  45725. changed();
  45726. }
  45727. }
  45728. void DirectoryContentsList::refresh()
  45729. {
  45730. clear();
  45731. if (root.isDirectory())
  45732. {
  45733. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45734. shouldStop = false;
  45735. thread.addTimeSliceClient (this);
  45736. }
  45737. }
  45738. int DirectoryContentsList::getNumFiles() const
  45739. {
  45740. return files.size();
  45741. }
  45742. bool DirectoryContentsList::getFileInfo (const int index,
  45743. FileInfo& result) const
  45744. {
  45745. const ScopedLock sl (fileListLock);
  45746. const FileInfo* const info = files [index];
  45747. if (info != 0)
  45748. {
  45749. result = *info;
  45750. return true;
  45751. }
  45752. return false;
  45753. }
  45754. const File DirectoryContentsList::getFile (const int index) const
  45755. {
  45756. const ScopedLock sl (fileListLock);
  45757. const FileInfo* const info = files [index];
  45758. if (info != 0)
  45759. return root.getChildFile (info->filename);
  45760. return File::nonexistent;
  45761. }
  45762. bool DirectoryContentsList::isStillLoading() const
  45763. {
  45764. return fileFindHandle != 0;
  45765. }
  45766. void DirectoryContentsList::changed()
  45767. {
  45768. sendChangeMessage (this);
  45769. }
  45770. bool DirectoryContentsList::useTimeSlice()
  45771. {
  45772. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45773. bool hasChanged = false;
  45774. for (int i = 100; --i >= 0;)
  45775. {
  45776. if (! checkNextFile (hasChanged))
  45777. {
  45778. if (hasChanged)
  45779. changed();
  45780. return false;
  45781. }
  45782. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45783. break;
  45784. }
  45785. if (hasChanged)
  45786. changed();
  45787. return true;
  45788. }
  45789. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  45790. {
  45791. if (fileFindHandle != 0)
  45792. {
  45793. bool fileFoundIsDir, isHidden, isReadOnly;
  45794. int64 fileSize;
  45795. Time modTime, creationTime;
  45796. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  45797. &modTime, &creationTime, &isReadOnly))
  45798. {
  45799. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  45800. fileSize, modTime, creationTime, isReadOnly))
  45801. {
  45802. hasChanged = true;
  45803. }
  45804. return true;
  45805. }
  45806. else
  45807. {
  45808. fileFindHandle = 0;
  45809. }
  45810. }
  45811. return false;
  45812. }
  45813. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  45814. const DirectoryContentsList::FileInfo* const second)
  45815. {
  45816. #if JUCE_WINDOWS
  45817. if (first->isDirectory != second->isDirectory)
  45818. return first->isDirectory ? -1 : 1;
  45819. #endif
  45820. return first->filename.compareIgnoreCase (second->filename);
  45821. }
  45822. bool DirectoryContentsList::addFile (const File& file,
  45823. const bool isDir,
  45824. const int64 fileSize,
  45825. const Time& modTime,
  45826. const Time& creationTime,
  45827. const bool isReadOnly)
  45828. {
  45829. if (fileFilter == 0
  45830. || ((! isDir) && fileFilter->isFileSuitable (file))
  45831. || (isDir && fileFilter->isDirectorySuitable (file)))
  45832. {
  45833. ScopedPointer <FileInfo> info (new FileInfo());
  45834. info->filename = file.getFileName();
  45835. info->fileSize = fileSize;
  45836. info->modificationTime = modTime;
  45837. info->creationTime = creationTime;
  45838. info->isDirectory = isDir;
  45839. info->isReadOnly = isReadOnly;
  45840. const ScopedLock sl (fileListLock);
  45841. for (int i = files.size(); --i >= 0;)
  45842. if (files.getUnchecked(i)->filename == info->filename)
  45843. return false;
  45844. files.addSorted (*this, info.release());
  45845. return true;
  45846. }
  45847. return false;
  45848. }
  45849. END_JUCE_NAMESPACE
  45850. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  45851. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  45852. BEGIN_JUCE_NAMESPACE
  45853. FileBrowserComponent::FileBrowserComponent (int flags_,
  45854. const File& initialFileOrDirectory,
  45855. const FileFilter* fileFilter_,
  45856. FilePreviewComponent* previewComp_)
  45857. : FileFilter (String::empty),
  45858. fileFilter (fileFilter_),
  45859. flags (flags_),
  45860. previewComp (previewComp_),
  45861. thread ("Juce FileBrowser")
  45862. {
  45863. // You need to specify one or other of the open/save flags..
  45864. jassert ((flags & (saveMode | openMode)) != 0);
  45865. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  45866. // You need to specify at least one of these flags..
  45867. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  45868. String filename;
  45869. if (initialFileOrDirectory == File::nonexistent)
  45870. {
  45871. currentRoot = File::getCurrentWorkingDirectory();
  45872. }
  45873. else if (initialFileOrDirectory.isDirectory())
  45874. {
  45875. currentRoot = initialFileOrDirectory;
  45876. }
  45877. else
  45878. {
  45879. chosenFiles.add (initialFileOrDirectory);
  45880. currentRoot = initialFileOrDirectory.getParentDirectory();
  45881. filename = initialFileOrDirectory.getFileName();
  45882. }
  45883. fileList = new DirectoryContentsList (this, thread);
  45884. if ((flags & useTreeView) != 0)
  45885. {
  45886. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  45887. if ((flags & canSelectMultipleItems) != 0)
  45888. tree->setMultiSelectEnabled (true);
  45889. addAndMakeVisible (tree);
  45890. fileListComponent = tree;
  45891. }
  45892. else
  45893. {
  45894. FileListComponent* const list = new FileListComponent (*fileList);
  45895. list->setOutlineThickness (1);
  45896. if ((flags & canSelectMultipleItems) != 0)
  45897. list->setMultipleSelectionEnabled (true);
  45898. addAndMakeVisible (list);
  45899. fileListComponent = list;
  45900. }
  45901. fileListComponent->addListener (this);
  45902. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  45903. currentPathBox->setEditableText (true);
  45904. StringArray rootNames, rootPaths;
  45905. const BigInteger separators (getRoots (rootNames, rootPaths));
  45906. for (int i = 0; i < rootNames.size(); ++i)
  45907. {
  45908. if (separators [i])
  45909. currentPathBox->addSeparator();
  45910. currentPathBox->addItem (rootNames[i], i + 1);
  45911. }
  45912. currentPathBox->addSeparator();
  45913. currentPathBox->addListener (this);
  45914. addAndMakeVisible (filenameBox = new TextEditor());
  45915. filenameBox->setMultiLine (false);
  45916. filenameBox->setSelectAllWhenFocused (true);
  45917. filenameBox->setText (filename, false);
  45918. filenameBox->addListener (this);
  45919. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  45920. Label* label = new Label ("f", TRANS("file:"));
  45921. addAndMakeVisible (label);
  45922. label->attachToComponent (filenameBox, true);
  45923. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  45924. goUpButton->addButtonListener (this);
  45925. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  45926. if (previewComp != 0)
  45927. addAndMakeVisible (previewComp);
  45928. setRoot (currentRoot);
  45929. thread.startThread (4);
  45930. }
  45931. FileBrowserComponent::~FileBrowserComponent()
  45932. {
  45933. if (previewComp != 0)
  45934. removeChildComponent (previewComp);
  45935. deleteAllChildren();
  45936. fileList = 0;
  45937. thread.stopThread (10000);
  45938. }
  45939. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  45940. {
  45941. listeners.add (newListener);
  45942. }
  45943. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  45944. {
  45945. listeners.remove (listener);
  45946. }
  45947. bool FileBrowserComponent::isSaveMode() const throw()
  45948. {
  45949. return (flags & saveMode) != 0;
  45950. }
  45951. int FileBrowserComponent::getNumSelectedFiles() const throw()
  45952. {
  45953. if (chosenFiles.size() == 0 && currentFileIsValid())
  45954. return 1;
  45955. return chosenFiles.size();
  45956. }
  45957. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  45958. {
  45959. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  45960. return currentRoot;
  45961. if (! filenameBox->isReadOnly())
  45962. return currentRoot.getChildFile (filenameBox->getText());
  45963. return chosenFiles[index];
  45964. }
  45965. bool FileBrowserComponent::currentFileIsValid() const
  45966. {
  45967. if (isSaveMode())
  45968. return ! getSelectedFile (0).isDirectory();
  45969. else
  45970. return getSelectedFile (0).exists();
  45971. }
  45972. const File FileBrowserComponent::getHighlightedFile() const throw()
  45973. {
  45974. return fileListComponent->getSelectedFile (0);
  45975. }
  45976. void FileBrowserComponent::deselectAllFiles()
  45977. {
  45978. fileListComponent->deselectAllFiles();
  45979. }
  45980. bool FileBrowserComponent::isFileSuitable (const File& file) const
  45981. {
  45982. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  45983. : false;
  45984. }
  45985. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  45986. {
  45987. return true;
  45988. }
  45989. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  45990. {
  45991. if (f.isDirectory())
  45992. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  45993. return (flags & canSelectFiles) != 0 && f.exists()
  45994. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  45995. }
  45996. const File FileBrowserComponent::getRoot() const
  45997. {
  45998. return currentRoot;
  45999. }
  46000. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46001. {
  46002. if (currentRoot != newRootDirectory)
  46003. {
  46004. fileListComponent->scrollToTop();
  46005. String path (newRootDirectory.getFullPathName());
  46006. if (path.isEmpty())
  46007. path = File::separatorString;
  46008. StringArray rootNames, rootPaths;
  46009. getRoots (rootNames, rootPaths);
  46010. if (! rootPaths.contains (path, true))
  46011. {
  46012. bool alreadyListed = false;
  46013. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  46014. {
  46015. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46016. {
  46017. alreadyListed = true;
  46018. break;
  46019. }
  46020. }
  46021. if (! alreadyListed)
  46022. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46023. }
  46024. }
  46025. currentRoot = newRootDirectory;
  46026. fileList->setDirectory (currentRoot, true, true);
  46027. String currentRootName (currentRoot.getFullPathName());
  46028. if (currentRootName.isEmpty())
  46029. currentRootName = File::separatorString;
  46030. currentPathBox->setText (currentRootName, true);
  46031. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46032. && currentRoot.getParentDirectory() != currentRoot);
  46033. }
  46034. void FileBrowserComponent::goUp()
  46035. {
  46036. setRoot (getRoot().getParentDirectory());
  46037. }
  46038. void FileBrowserComponent::refresh()
  46039. {
  46040. fileList->refresh();
  46041. }
  46042. const String FileBrowserComponent::getActionVerb() const
  46043. {
  46044. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46045. }
  46046. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46047. {
  46048. return previewComp;
  46049. }
  46050. void FileBrowserComponent::resized()
  46051. {
  46052. getLookAndFeel()
  46053. .layoutFileBrowserComponent (*this, fileListComponent,
  46054. previewComp, currentPathBox,
  46055. filenameBox, goUpButton);
  46056. }
  46057. void FileBrowserComponent::sendListenerChangeMessage()
  46058. {
  46059. Component::BailOutChecker checker (this);
  46060. if (previewComp != 0)
  46061. previewComp->selectedFileChanged (getSelectedFile (0));
  46062. // You shouldn't delete the browser when the file gets changed!
  46063. jassert (! checker.shouldBailOut());
  46064. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46065. }
  46066. void FileBrowserComponent::selectionChanged()
  46067. {
  46068. StringArray newFilenames;
  46069. bool resetChosenFiles = true;
  46070. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46071. {
  46072. const File f (fileListComponent->getSelectedFile (i));
  46073. if (isFileOrDirSuitable (f))
  46074. {
  46075. if (resetChosenFiles)
  46076. {
  46077. chosenFiles.clear();
  46078. resetChosenFiles = false;
  46079. }
  46080. chosenFiles.add (f);
  46081. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46082. }
  46083. }
  46084. if (newFilenames.size() > 0)
  46085. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46086. sendListenerChangeMessage();
  46087. }
  46088. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46089. {
  46090. Component::BailOutChecker checker (this);
  46091. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46092. }
  46093. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46094. {
  46095. if (f.isDirectory())
  46096. {
  46097. setRoot (f);
  46098. if ((flags & canSelectDirectories) != 0)
  46099. filenameBox->setText (String::empty);
  46100. }
  46101. else
  46102. {
  46103. Component::BailOutChecker checker (this);
  46104. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46105. }
  46106. }
  46107. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46108. {
  46109. (void) key;
  46110. #if JUCE_LINUX || JUCE_WINDOWS
  46111. if (key.getModifiers().isCommandDown()
  46112. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46113. {
  46114. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46115. fileList->refresh();
  46116. return true;
  46117. }
  46118. #endif
  46119. return false;
  46120. }
  46121. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46122. {
  46123. sendListenerChangeMessage();
  46124. }
  46125. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46126. {
  46127. if (filenameBox->getText().containsChar (File::separator))
  46128. {
  46129. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46130. if (f.isDirectory())
  46131. {
  46132. setRoot (f);
  46133. chosenFiles.clear();
  46134. filenameBox->setText (String::empty);
  46135. }
  46136. else
  46137. {
  46138. setRoot (f.getParentDirectory());
  46139. chosenFiles.clear();
  46140. chosenFiles.add (f);
  46141. filenameBox->setText (f.getFileName());
  46142. }
  46143. }
  46144. else
  46145. {
  46146. fileDoubleClicked (getSelectedFile (0));
  46147. }
  46148. }
  46149. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46150. {
  46151. }
  46152. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46153. {
  46154. if (! isSaveMode())
  46155. selectionChanged();
  46156. }
  46157. void FileBrowserComponent::buttonClicked (Button*)
  46158. {
  46159. goUp();
  46160. }
  46161. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46162. {
  46163. const String newText (currentPathBox->getText().trim().unquoted());
  46164. if (newText.isNotEmpty())
  46165. {
  46166. const int index = currentPathBox->getSelectedId() - 1;
  46167. StringArray rootNames, rootPaths;
  46168. getRoots (rootNames, rootPaths);
  46169. if (rootPaths [index].isNotEmpty())
  46170. {
  46171. setRoot (File (rootPaths [index]));
  46172. }
  46173. else
  46174. {
  46175. File f (newText);
  46176. for (;;)
  46177. {
  46178. if (f.isDirectory())
  46179. {
  46180. setRoot (f);
  46181. break;
  46182. }
  46183. if (f.getParentDirectory() == f)
  46184. break;
  46185. f = f.getParentDirectory();
  46186. }
  46187. }
  46188. }
  46189. }
  46190. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46191. {
  46192. BigInteger separators;
  46193. #if JUCE_WINDOWS
  46194. Array<File> roots;
  46195. File::findFileSystemRoots (roots);
  46196. rootPaths.clear();
  46197. for (int i = 0; i < roots.size(); ++i)
  46198. {
  46199. const File& drive = roots.getReference(i);
  46200. String name (drive.getFullPathName());
  46201. rootPaths.add (name);
  46202. if (drive.isOnHardDisk())
  46203. {
  46204. String volume (drive.getVolumeLabel());
  46205. if (volume.isEmpty())
  46206. volume = TRANS("Hard Drive");
  46207. name << " [" << drive.getVolumeLabel() << ']';
  46208. }
  46209. else if (drive.isOnCDRomDrive())
  46210. {
  46211. name << TRANS(" [CD/DVD drive]");
  46212. }
  46213. rootNames.add (name);
  46214. }
  46215. separators.setBit (rootPaths.size());
  46216. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46217. rootNames.add ("Documents");
  46218. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46219. rootNames.add ("Desktop");
  46220. #endif
  46221. #if JUCE_MAC
  46222. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46223. rootNames.add ("Home folder");
  46224. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46225. rootNames.add ("Documents");
  46226. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46227. rootNames.add ("Desktop");
  46228. separators.setBit (rootPaths.size());
  46229. Array <File> volumes;
  46230. File vol ("/Volumes");
  46231. vol.findChildFiles (volumes, File::findDirectories, false);
  46232. for (int i = 0; i < volumes.size(); ++i)
  46233. {
  46234. const File& volume = volumes.getReference(i);
  46235. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46236. {
  46237. rootPaths.add (volume.getFullPathName());
  46238. rootNames.add (volume.getFileName());
  46239. }
  46240. }
  46241. #endif
  46242. #if JUCE_LINUX
  46243. rootPaths.add ("/");
  46244. rootNames.add ("/");
  46245. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46246. rootNames.add ("Home folder");
  46247. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46248. rootNames.add ("Desktop");
  46249. #endif
  46250. return separators;
  46251. }
  46252. END_JUCE_NAMESPACE
  46253. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46254. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46255. BEGIN_JUCE_NAMESPACE
  46256. FileChooser::FileChooser (const String& chooserBoxTitle,
  46257. const File& currentFileOrDirectory,
  46258. const String& fileFilters,
  46259. const bool useNativeDialogBox_)
  46260. : title (chooserBoxTitle),
  46261. filters (fileFilters),
  46262. startingFile (currentFileOrDirectory),
  46263. useNativeDialogBox (useNativeDialogBox_)
  46264. {
  46265. #if JUCE_LINUX
  46266. useNativeDialogBox = false;
  46267. #endif
  46268. if (! fileFilters.containsNonWhitespaceChars())
  46269. filters = "*";
  46270. }
  46271. FileChooser::~FileChooser()
  46272. {
  46273. }
  46274. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46275. {
  46276. return showDialog (false, true, false, false, false, previewComponent);
  46277. }
  46278. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46279. {
  46280. return showDialog (false, true, false, false, true, previewComponent);
  46281. }
  46282. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46283. {
  46284. return showDialog (true, true, false, false, true, previewComponent);
  46285. }
  46286. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46287. {
  46288. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46289. }
  46290. bool FileChooser::browseForDirectory()
  46291. {
  46292. return showDialog (true, false, false, false, false, 0);
  46293. }
  46294. const File FileChooser::getResult() const
  46295. {
  46296. // if you've used a multiple-file select, you should use the getResults() method
  46297. // to retrieve all the files that were chosen.
  46298. jassert (results.size() <= 1);
  46299. return results.getFirst();
  46300. }
  46301. const Array<File>& FileChooser::getResults() const
  46302. {
  46303. return results;
  46304. }
  46305. bool FileChooser::showDialog (const bool selectsDirectories,
  46306. const bool selectsFiles,
  46307. const bool isSave,
  46308. const bool warnAboutOverwritingExistingFiles,
  46309. const bool selectMultipleFiles,
  46310. FilePreviewComponent* const previewComponent)
  46311. {
  46312. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46313. results.clear();
  46314. // the preview component needs to be the right size before you pass it in here..
  46315. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46316. && previewComponent->getHeight() > 10));
  46317. #if JUCE_WINDOWS
  46318. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46319. #elif JUCE_MAC
  46320. if (useNativeDialogBox && (previewComponent == 0))
  46321. #else
  46322. if (false)
  46323. #endif
  46324. {
  46325. showPlatformDialog (results, title, startingFile, filters,
  46326. selectsDirectories, selectsFiles, isSave,
  46327. warnAboutOverwritingExistingFiles,
  46328. selectMultipleFiles,
  46329. previewComponent);
  46330. }
  46331. else
  46332. {
  46333. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46334. selectsDirectories ? "*" : String::empty,
  46335. String::empty);
  46336. int flags = isSave ? FileBrowserComponent::saveMode
  46337. : FileBrowserComponent::openMode;
  46338. if (selectsFiles)
  46339. flags |= FileBrowserComponent::canSelectFiles;
  46340. if (selectsDirectories)
  46341. {
  46342. flags |= FileBrowserComponent::canSelectDirectories;
  46343. if (! isSave)
  46344. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46345. }
  46346. if (selectMultipleFiles)
  46347. flags |= FileBrowserComponent::canSelectMultipleItems;
  46348. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46349. FileChooserDialogBox box (title, String::empty,
  46350. browserComponent,
  46351. warnAboutOverwritingExistingFiles,
  46352. browserComponent.findColour (AlertWindow::backgroundColourId));
  46353. if (box.show())
  46354. {
  46355. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46356. results.add (browserComponent.getSelectedFile (i));
  46357. }
  46358. }
  46359. if (previouslyFocused != 0)
  46360. previouslyFocused->grabKeyboardFocus();
  46361. return results.size() > 0;
  46362. }
  46363. FilePreviewComponent::FilePreviewComponent()
  46364. {
  46365. }
  46366. FilePreviewComponent::~FilePreviewComponent()
  46367. {
  46368. }
  46369. END_JUCE_NAMESPACE
  46370. /*** End of inlined file: juce_FileChooser.cpp ***/
  46371. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46372. BEGIN_JUCE_NAMESPACE
  46373. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46374. const String& instructions,
  46375. FileBrowserComponent& chooserComponent,
  46376. const bool warnAboutOverwritingExistingFiles_,
  46377. const Colour& backgroundColour)
  46378. : ResizableWindow (name, backgroundColour, true),
  46379. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46380. {
  46381. content = new ContentComponent();
  46382. content->setName (name);
  46383. content->instructions = instructions;
  46384. content->chooserComponent = &chooserComponent;
  46385. content->addAndMakeVisible (&chooserComponent);
  46386. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46387. content->addAndMakeVisible (content->okButton);
  46388. content->okButton->addButtonListener (this);
  46389. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46390. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46391. content->cancelButton = new TextButton (TRANS("Cancel"));
  46392. content->addAndMakeVisible (content->cancelButton);
  46393. content->cancelButton->addButtonListener (this);
  46394. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46395. setContentComponent (content);
  46396. setResizable (true, true);
  46397. setResizeLimits (300, 300, 1200, 1000);
  46398. content->chooserComponent->addListener (this);
  46399. }
  46400. FileChooserDialogBox::~FileChooserDialogBox()
  46401. {
  46402. content->chooserComponent->removeListener (this);
  46403. }
  46404. bool FileChooserDialogBox::show (int w, int h)
  46405. {
  46406. if (w <= 0)
  46407. {
  46408. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46409. if (previewComp != 0)
  46410. w = 400 + previewComp->getWidth();
  46411. else
  46412. w = 600;
  46413. }
  46414. if (h <= 0)
  46415. h = 500;
  46416. centreWithSize (w, h);
  46417. const bool ok = (runModalLoop() != 0);
  46418. setVisible (false);
  46419. return ok;
  46420. }
  46421. void FileChooserDialogBox::buttonClicked (Button* button)
  46422. {
  46423. if (button == content->okButton)
  46424. {
  46425. if (warnAboutOverwritingExistingFiles
  46426. && content->chooserComponent->isSaveMode()
  46427. && content->chooserComponent->getSelectedFile(0).exists())
  46428. {
  46429. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46430. TRANS("File already exists"),
  46431. TRANS("There's already a file called:")
  46432. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46433. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46434. TRANS("overwrite"),
  46435. TRANS("cancel")))
  46436. {
  46437. return;
  46438. }
  46439. }
  46440. exitModalState (1);
  46441. }
  46442. else if (button == content->cancelButton)
  46443. closeButtonPressed();
  46444. }
  46445. void FileChooserDialogBox::closeButtonPressed()
  46446. {
  46447. setVisible (false);
  46448. }
  46449. void FileChooserDialogBox::selectionChanged()
  46450. {
  46451. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46452. }
  46453. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46454. {
  46455. }
  46456. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46457. {
  46458. selectionChanged();
  46459. content->okButton->triggerClick();
  46460. }
  46461. FileChooserDialogBox::ContentComponent::ContentComponent()
  46462. {
  46463. setInterceptsMouseClicks (false, true);
  46464. }
  46465. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46466. {
  46467. delete okButton;
  46468. delete cancelButton;
  46469. }
  46470. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46471. {
  46472. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46473. text.draw (g);
  46474. }
  46475. void FileChooserDialogBox::ContentComponent::resized()
  46476. {
  46477. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46478. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46479. const int y = roundToInt (bb.getBottom()) + 10;
  46480. const int buttonHeight = 26;
  46481. const int buttonY = getHeight() - buttonHeight - 8;
  46482. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46483. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46484. proportionOfWidth (0.2f), buttonHeight);
  46485. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46486. proportionOfWidth (0.2f), buttonHeight);
  46487. }
  46488. END_JUCE_NAMESPACE
  46489. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46490. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46491. BEGIN_JUCE_NAMESPACE
  46492. FileFilter::FileFilter (const String& filterDescription)
  46493. : description (filterDescription)
  46494. {
  46495. }
  46496. FileFilter::~FileFilter()
  46497. {
  46498. }
  46499. const String& FileFilter::getDescription() const throw()
  46500. {
  46501. return description;
  46502. }
  46503. END_JUCE_NAMESPACE
  46504. /*** End of inlined file: juce_FileFilter.cpp ***/
  46505. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46506. BEGIN_JUCE_NAMESPACE
  46507. const Image juce_createIconForFile (const File& file);
  46508. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46509. : ListBox (String::empty, 0),
  46510. DirectoryContentsDisplayComponent (listToShow)
  46511. {
  46512. setModel (this);
  46513. fileList.addChangeListener (this);
  46514. }
  46515. FileListComponent::~FileListComponent()
  46516. {
  46517. fileList.removeChangeListener (this);
  46518. deleteAllChildren();
  46519. }
  46520. int FileListComponent::getNumSelectedFiles() const
  46521. {
  46522. return getNumSelectedRows();
  46523. }
  46524. const File FileListComponent::getSelectedFile (int index) const
  46525. {
  46526. return fileList.getFile (getSelectedRow (index));
  46527. }
  46528. void FileListComponent::deselectAllFiles()
  46529. {
  46530. deselectAllRows();
  46531. }
  46532. void FileListComponent::scrollToTop()
  46533. {
  46534. getVerticalScrollBar()->setCurrentRangeStart (0);
  46535. }
  46536. void FileListComponent::changeListenerCallback (void*)
  46537. {
  46538. updateContent();
  46539. if (lastDirectory != fileList.getDirectory())
  46540. {
  46541. lastDirectory = fileList.getDirectory();
  46542. deselectAllRows();
  46543. }
  46544. }
  46545. class FileListItemComponent : public Component,
  46546. public TimeSliceClient,
  46547. public AsyncUpdater
  46548. {
  46549. public:
  46550. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46551. : owner (owner_), thread (thread_),
  46552. highlighted (false), index (0), icon (0)
  46553. {
  46554. }
  46555. ~FileListItemComponent()
  46556. {
  46557. thread.removeTimeSliceClient (this);
  46558. clearIcon();
  46559. }
  46560. void paint (Graphics& g)
  46561. {
  46562. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46563. file.getFileName(),
  46564. &icon,
  46565. fileSize, modTime,
  46566. isDirectory, highlighted,
  46567. index);
  46568. }
  46569. void mouseDown (const MouseEvent& e)
  46570. {
  46571. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46572. owner.sendMouseClickMessage (file, e);
  46573. }
  46574. void mouseDoubleClick (const MouseEvent&)
  46575. {
  46576. owner.sendDoubleClickMessage (file);
  46577. }
  46578. void update (const File& root,
  46579. const DirectoryContentsList::FileInfo* const fileInfo,
  46580. const int index_,
  46581. const bool highlighted_)
  46582. {
  46583. thread.removeTimeSliceClient (this);
  46584. if (highlighted_ != highlighted
  46585. || index_ != index)
  46586. {
  46587. index = index_;
  46588. highlighted = highlighted_;
  46589. repaint();
  46590. }
  46591. File newFile;
  46592. String newFileSize;
  46593. String newModTime;
  46594. if (fileInfo != 0)
  46595. {
  46596. newFile = root.getChildFile (fileInfo->filename);
  46597. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46598. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46599. }
  46600. if (newFile != file
  46601. || fileSize != newFileSize
  46602. || modTime != newModTime)
  46603. {
  46604. file = newFile;
  46605. fileSize = newFileSize;
  46606. modTime = newModTime;
  46607. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46608. repaint();
  46609. clearIcon();
  46610. }
  46611. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  46612. {
  46613. updateIcon (true);
  46614. if (! icon.isValid())
  46615. thread.addTimeSliceClient (this);
  46616. }
  46617. }
  46618. bool useTimeSlice()
  46619. {
  46620. updateIcon (false);
  46621. return false;
  46622. }
  46623. void handleAsyncUpdate()
  46624. {
  46625. repaint();
  46626. }
  46627. juce_UseDebuggingNewOperator
  46628. private:
  46629. FileListComponent& owner;
  46630. TimeSliceThread& thread;
  46631. bool highlighted;
  46632. int index;
  46633. File file;
  46634. String fileSize;
  46635. String modTime;
  46636. Image icon;
  46637. bool isDirectory;
  46638. void clearIcon()
  46639. {
  46640. icon = Image();
  46641. }
  46642. void updateIcon (const bool onlyUpdateIfCached)
  46643. {
  46644. if (icon.isNull())
  46645. {
  46646. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46647. Image im (ImageCache::getFromHashCode (hashCode));
  46648. if (im.isNull() && ! onlyUpdateIfCached)
  46649. {
  46650. im = juce_createIconForFile (file);
  46651. if (im.isValid())
  46652. ImageCache::addImageToCache (im, hashCode);
  46653. }
  46654. if (im.isValid())
  46655. {
  46656. icon = im;
  46657. triggerAsyncUpdate();
  46658. }
  46659. }
  46660. }
  46661. };
  46662. int FileListComponent::getNumRows()
  46663. {
  46664. return fileList.getNumFiles();
  46665. }
  46666. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46667. {
  46668. }
  46669. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46670. {
  46671. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46672. if (comp == 0)
  46673. {
  46674. delete existingComponentToUpdate;
  46675. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46676. }
  46677. DirectoryContentsList::FileInfo fileInfo;
  46678. if (fileList.getFileInfo (row, fileInfo))
  46679. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46680. else
  46681. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46682. return comp;
  46683. }
  46684. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46685. {
  46686. sendSelectionChangeMessage();
  46687. }
  46688. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46689. {
  46690. }
  46691. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46692. {
  46693. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46694. }
  46695. END_JUCE_NAMESPACE
  46696. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46697. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46698. BEGIN_JUCE_NAMESPACE
  46699. FilenameComponent::FilenameComponent (const String& name,
  46700. const File& currentFile,
  46701. const bool canEditFilename,
  46702. const bool isDirectory,
  46703. const bool isForSaving,
  46704. const String& fileBrowserWildcard,
  46705. const String& enforcedSuffix_,
  46706. const String& textWhenNothingSelected)
  46707. : Component (name),
  46708. maxRecentFiles (30),
  46709. isDir (isDirectory),
  46710. isSaving (isForSaving),
  46711. isFileDragOver (false),
  46712. wildcard (fileBrowserWildcard),
  46713. enforcedSuffix (enforcedSuffix_)
  46714. {
  46715. addAndMakeVisible (filenameBox = new ComboBox ("fn"));
  46716. filenameBox->setEditableText (canEditFilename);
  46717. filenameBox->addListener (this);
  46718. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  46719. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46720. browseButton = 0;
  46721. setBrowseButtonText ("...");
  46722. setCurrentFile (currentFile, true);
  46723. }
  46724. FilenameComponent::~FilenameComponent()
  46725. {
  46726. deleteAllChildren();
  46727. }
  46728. void FilenameComponent::paintOverChildren (Graphics& g)
  46729. {
  46730. if (isFileDragOver)
  46731. {
  46732. g.setColour (Colours::red.withAlpha (0.2f));
  46733. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46734. }
  46735. }
  46736. void FilenameComponent::resized()
  46737. {
  46738. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  46739. }
  46740. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46741. {
  46742. browseButtonText = newBrowseButtonText;
  46743. lookAndFeelChanged();
  46744. }
  46745. void FilenameComponent::lookAndFeelChanged()
  46746. {
  46747. deleteAndZero (browseButton);
  46748. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46749. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46750. resized();
  46751. browseButton->addButtonListener (this);
  46752. }
  46753. void FilenameComponent::setTooltip (const String& newTooltip)
  46754. {
  46755. SettableTooltipClient::setTooltip (newTooltip);
  46756. filenameBox->setTooltip (newTooltip);
  46757. }
  46758. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46759. {
  46760. defaultBrowseFile = newDefaultDirectory;
  46761. }
  46762. void FilenameComponent::buttonClicked (Button*)
  46763. {
  46764. FileChooser fc (TRANS("Choose a new file"),
  46765. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46766. : getCurrentFile(),
  46767. wildcard);
  46768. if (isDir ? fc.browseForDirectory()
  46769. : (isSaving ? fc.browseForFileToSave (false)
  46770. : fc.browseForFileToOpen()))
  46771. {
  46772. setCurrentFile (fc.getResult(), true);
  46773. }
  46774. }
  46775. void FilenameComponent::comboBoxChanged (ComboBox*)
  46776. {
  46777. setCurrentFile (getCurrentFile(), true);
  46778. }
  46779. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46780. {
  46781. return true;
  46782. }
  46783. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46784. {
  46785. isFileDragOver = false;
  46786. repaint();
  46787. const File f (filenames[0]);
  46788. if (f.exists() && (f.isDirectory() == isDir))
  46789. setCurrentFile (f, true);
  46790. }
  46791. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  46792. {
  46793. isFileDragOver = true;
  46794. repaint();
  46795. }
  46796. void FilenameComponent::fileDragExit (const StringArray&)
  46797. {
  46798. isFileDragOver = false;
  46799. repaint();
  46800. }
  46801. const File FilenameComponent::getCurrentFile() const
  46802. {
  46803. File f (filenameBox->getText());
  46804. if (enforcedSuffix.isNotEmpty())
  46805. f = f.withFileExtension (enforcedSuffix);
  46806. return f;
  46807. }
  46808. void FilenameComponent::setCurrentFile (File newFile,
  46809. const bool addToRecentlyUsedList,
  46810. const bool sendChangeNotification)
  46811. {
  46812. if (enforcedSuffix.isNotEmpty())
  46813. newFile = newFile.withFileExtension (enforcedSuffix);
  46814. if (newFile.getFullPathName() != lastFilename)
  46815. {
  46816. lastFilename = newFile.getFullPathName();
  46817. if (addToRecentlyUsedList)
  46818. addRecentlyUsedFile (newFile);
  46819. filenameBox->setText (lastFilename, true);
  46820. if (sendChangeNotification)
  46821. triggerAsyncUpdate();
  46822. }
  46823. }
  46824. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  46825. {
  46826. filenameBox->setEditableText (shouldBeEditable);
  46827. }
  46828. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  46829. {
  46830. StringArray names;
  46831. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  46832. names.add (filenameBox->getItemText (i));
  46833. return names;
  46834. }
  46835. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  46836. {
  46837. if (filenames != getRecentlyUsedFilenames())
  46838. {
  46839. filenameBox->clear();
  46840. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  46841. filenameBox->addItem (filenames[i], i + 1);
  46842. }
  46843. }
  46844. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  46845. {
  46846. maxRecentFiles = jmax (1, newMaximum);
  46847. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  46848. }
  46849. void FilenameComponent::addRecentlyUsedFile (const File& file)
  46850. {
  46851. StringArray files (getRecentlyUsedFilenames());
  46852. if (file.getFullPathName().isNotEmpty())
  46853. {
  46854. files.removeString (file.getFullPathName(), true);
  46855. files.insert (0, file.getFullPathName());
  46856. setRecentlyUsedFilenames (files);
  46857. }
  46858. }
  46859. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  46860. {
  46861. listeners.add (listener);
  46862. }
  46863. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  46864. {
  46865. listeners.remove (listener);
  46866. }
  46867. void FilenameComponent::handleAsyncUpdate()
  46868. {
  46869. Component::BailOutChecker checker (this);
  46870. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  46871. }
  46872. END_JUCE_NAMESPACE
  46873. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  46874. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  46875. BEGIN_JUCE_NAMESPACE
  46876. FileSearchPathListComponent::FileSearchPathListComponent()
  46877. {
  46878. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  46879. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  46880. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  46881. listBox->setOutlineThickness (1);
  46882. addAndMakeVisible (addButton = new TextButton ("+"));
  46883. addButton->addButtonListener (this);
  46884. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46885. addAndMakeVisible (removeButton = new TextButton ("-"));
  46886. removeButton->addButtonListener (this);
  46887. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46888. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  46889. changeButton->addButtonListener (this);
  46890. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46891. upButton->addButtonListener (this);
  46892. {
  46893. Path arrowPath;
  46894. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  46895. DrawablePath arrowImage;
  46896. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46897. arrowImage.setPath (arrowPath);
  46898. upButton->setImages (&arrowImage);
  46899. }
  46900. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46901. downButton->addButtonListener (this);
  46902. {
  46903. Path arrowPath;
  46904. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  46905. DrawablePath arrowImage;
  46906. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46907. arrowImage.setPath (arrowPath);
  46908. downButton->setImages (&arrowImage);
  46909. }
  46910. updateButtons();
  46911. }
  46912. FileSearchPathListComponent::~FileSearchPathListComponent()
  46913. {
  46914. deleteAllChildren();
  46915. }
  46916. void FileSearchPathListComponent::updateButtons()
  46917. {
  46918. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  46919. removeButton->setEnabled (anythingSelected);
  46920. changeButton->setEnabled (anythingSelected);
  46921. upButton->setEnabled (anythingSelected);
  46922. downButton->setEnabled (anythingSelected);
  46923. }
  46924. void FileSearchPathListComponent::changed()
  46925. {
  46926. listBox->updateContent();
  46927. listBox->repaint();
  46928. updateButtons();
  46929. }
  46930. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  46931. {
  46932. if (newPath.toString() != path.toString())
  46933. {
  46934. path = newPath;
  46935. changed();
  46936. }
  46937. }
  46938. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46939. {
  46940. defaultBrowseTarget = newDefaultDirectory;
  46941. }
  46942. int FileSearchPathListComponent::getNumRows()
  46943. {
  46944. return path.getNumPaths();
  46945. }
  46946. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  46947. {
  46948. if (rowIsSelected)
  46949. g.fillAll (findColour (TextEditor::highlightColourId));
  46950. g.setColour (findColour (ListBox::textColourId));
  46951. Font f (height * 0.7f);
  46952. f.setHorizontalScale (0.9f);
  46953. g.setFont (f);
  46954. g.drawText (path [rowNumber].getFullPathName(),
  46955. 4, 0, width - 6, height,
  46956. Justification::centredLeft, true);
  46957. }
  46958. void FileSearchPathListComponent::deleteKeyPressed (int row)
  46959. {
  46960. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  46961. {
  46962. path.remove (row);
  46963. changed();
  46964. }
  46965. }
  46966. void FileSearchPathListComponent::returnKeyPressed (int row)
  46967. {
  46968. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  46969. if (chooser.browseForDirectory())
  46970. {
  46971. path.remove (row);
  46972. path.add (chooser.getResult(), row);
  46973. changed();
  46974. }
  46975. }
  46976. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  46977. {
  46978. returnKeyPressed (row);
  46979. }
  46980. void FileSearchPathListComponent::selectedRowsChanged (int)
  46981. {
  46982. updateButtons();
  46983. }
  46984. void FileSearchPathListComponent::paint (Graphics& g)
  46985. {
  46986. g.fillAll (findColour (backgroundColourId));
  46987. }
  46988. void FileSearchPathListComponent::resized()
  46989. {
  46990. const int buttonH = 22;
  46991. const int buttonY = getHeight() - buttonH - 4;
  46992. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  46993. addButton->setBounds (2, buttonY, buttonH, buttonH);
  46994. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  46995. changeButton->changeWidthToFitText (buttonH);
  46996. downButton->setSize (buttonH * 2, buttonH);
  46997. upButton->setSize (buttonH * 2, buttonH);
  46998. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  46999. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  47000. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  47001. }
  47002. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47003. {
  47004. return true;
  47005. }
  47006. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47007. {
  47008. for (int i = filenames.size(); --i >= 0;)
  47009. {
  47010. const File f (filenames[i]);
  47011. if (f.isDirectory())
  47012. {
  47013. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47014. path.add (f, row);
  47015. changed();
  47016. }
  47017. }
  47018. }
  47019. void FileSearchPathListComponent::buttonClicked (Button* button)
  47020. {
  47021. const int currentRow = listBox->getSelectedRow();
  47022. if (button == removeButton)
  47023. {
  47024. deleteKeyPressed (currentRow);
  47025. }
  47026. else if (button == addButton)
  47027. {
  47028. File start (defaultBrowseTarget);
  47029. if (start == File::nonexistent)
  47030. start = path [0];
  47031. if (start == File::nonexistent)
  47032. start = File::getCurrentWorkingDirectory();
  47033. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47034. if (chooser.browseForDirectory())
  47035. {
  47036. path.add (chooser.getResult(), currentRow);
  47037. }
  47038. }
  47039. else if (button == changeButton)
  47040. {
  47041. returnKeyPressed (currentRow);
  47042. }
  47043. else if (button == upButton)
  47044. {
  47045. if (currentRow > 0 && currentRow < path.getNumPaths())
  47046. {
  47047. const File f (path[currentRow]);
  47048. path.remove (currentRow);
  47049. path.add (f, currentRow - 1);
  47050. listBox->selectRow (currentRow - 1);
  47051. }
  47052. }
  47053. else if (button == downButton)
  47054. {
  47055. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47056. {
  47057. const File f (path[currentRow]);
  47058. path.remove (currentRow);
  47059. path.add (f, currentRow + 1);
  47060. listBox->selectRow (currentRow + 1);
  47061. }
  47062. }
  47063. changed();
  47064. }
  47065. END_JUCE_NAMESPACE
  47066. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47067. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47068. BEGIN_JUCE_NAMESPACE
  47069. const Image juce_createIconForFile (const File& file);
  47070. class FileListTreeItem : public TreeViewItem,
  47071. public TimeSliceClient,
  47072. public AsyncUpdater,
  47073. public ChangeListener
  47074. {
  47075. public:
  47076. FileListTreeItem (FileTreeComponent& owner_,
  47077. DirectoryContentsList* const parentContentsList_,
  47078. const int indexInContentsList_,
  47079. const File& file_,
  47080. TimeSliceThread& thread_)
  47081. : file (file_),
  47082. owner (owner_),
  47083. parentContentsList (parentContentsList_),
  47084. indexInContentsList (indexInContentsList_),
  47085. subContentsList (0),
  47086. canDeleteSubContentsList (false),
  47087. thread (thread_),
  47088. icon (0)
  47089. {
  47090. DirectoryContentsList::FileInfo fileInfo;
  47091. if (parentContentsList_ != 0
  47092. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47093. {
  47094. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47095. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47096. isDirectory = fileInfo.isDirectory;
  47097. }
  47098. else
  47099. {
  47100. isDirectory = true;
  47101. }
  47102. }
  47103. ~FileListTreeItem()
  47104. {
  47105. thread.removeTimeSliceClient (this);
  47106. clearSubItems();
  47107. if (canDeleteSubContentsList)
  47108. delete subContentsList;
  47109. }
  47110. bool mightContainSubItems() { return isDirectory; }
  47111. const String getUniqueName() const { return file.getFullPathName(); }
  47112. int getItemHeight() const { return 22; }
  47113. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47114. void itemOpennessChanged (bool isNowOpen)
  47115. {
  47116. if (isNowOpen)
  47117. {
  47118. clearSubItems();
  47119. isDirectory = file.isDirectory();
  47120. if (isDirectory)
  47121. {
  47122. if (subContentsList == 0)
  47123. {
  47124. jassert (parentContentsList != 0);
  47125. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47126. l->setDirectory (file, true, true);
  47127. setSubContentsList (l);
  47128. canDeleteSubContentsList = true;
  47129. }
  47130. changeListenerCallback (0);
  47131. }
  47132. }
  47133. }
  47134. void setSubContentsList (DirectoryContentsList* newList)
  47135. {
  47136. jassert (subContentsList == 0);
  47137. subContentsList = newList;
  47138. newList->addChangeListener (this);
  47139. }
  47140. void changeListenerCallback (void*)
  47141. {
  47142. clearSubItems();
  47143. if (isOpen() && subContentsList != 0)
  47144. {
  47145. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47146. {
  47147. FileListTreeItem* const item
  47148. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47149. addSubItem (item);
  47150. }
  47151. }
  47152. }
  47153. void paintItem (Graphics& g, int width, int height)
  47154. {
  47155. if (file != File::nonexistent)
  47156. {
  47157. updateIcon (true);
  47158. if (icon.isNull())
  47159. thread.addTimeSliceClient (this);
  47160. }
  47161. owner.getLookAndFeel()
  47162. .drawFileBrowserRow (g, width, height,
  47163. file.getFileName(),
  47164. &icon, fileSize, modTime,
  47165. isDirectory, isSelected(),
  47166. indexInContentsList);
  47167. }
  47168. void itemClicked (const MouseEvent& e)
  47169. {
  47170. owner.sendMouseClickMessage (file, e);
  47171. }
  47172. void itemDoubleClicked (const MouseEvent& e)
  47173. {
  47174. TreeViewItem::itemDoubleClicked (e);
  47175. owner.sendDoubleClickMessage (file);
  47176. }
  47177. void itemSelectionChanged (bool)
  47178. {
  47179. owner.sendSelectionChangeMessage();
  47180. }
  47181. bool useTimeSlice()
  47182. {
  47183. updateIcon (false);
  47184. thread.removeTimeSliceClient (this);
  47185. return false;
  47186. }
  47187. void handleAsyncUpdate()
  47188. {
  47189. owner.repaint();
  47190. }
  47191. const File file;
  47192. juce_UseDebuggingNewOperator
  47193. private:
  47194. FileTreeComponent& owner;
  47195. DirectoryContentsList* parentContentsList;
  47196. int indexInContentsList;
  47197. DirectoryContentsList* subContentsList;
  47198. bool isDirectory, canDeleteSubContentsList;
  47199. TimeSliceThread& thread;
  47200. Image icon;
  47201. String fileSize;
  47202. String modTime;
  47203. void updateIcon (const bool onlyUpdateIfCached)
  47204. {
  47205. if (icon.isNull())
  47206. {
  47207. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47208. Image im (ImageCache::getFromHashCode (hashCode));
  47209. if (im.isNull() && ! onlyUpdateIfCached)
  47210. {
  47211. im = juce_createIconForFile (file);
  47212. if (im.isValid())
  47213. ImageCache::addImageToCache (im, hashCode);
  47214. }
  47215. if (im.isValid())
  47216. {
  47217. icon = im;
  47218. triggerAsyncUpdate();
  47219. }
  47220. }
  47221. }
  47222. };
  47223. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47224. : DirectoryContentsDisplayComponent (listToShow)
  47225. {
  47226. FileListTreeItem* const root
  47227. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47228. listToShow.getTimeSliceThread());
  47229. root->setSubContentsList (&listToShow);
  47230. setRootItemVisible (false);
  47231. setRootItem (root);
  47232. }
  47233. FileTreeComponent::~FileTreeComponent()
  47234. {
  47235. deleteRootItem();
  47236. }
  47237. const File FileTreeComponent::getSelectedFile (const int index) const
  47238. {
  47239. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47240. return item != 0 ? item->file
  47241. : File::nonexistent;
  47242. }
  47243. void FileTreeComponent::deselectAllFiles()
  47244. {
  47245. clearSelectedItems();
  47246. }
  47247. void FileTreeComponent::scrollToTop()
  47248. {
  47249. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47250. }
  47251. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47252. {
  47253. dragAndDropDescription = description;
  47254. }
  47255. END_JUCE_NAMESPACE
  47256. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47257. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47258. BEGIN_JUCE_NAMESPACE
  47259. ImagePreviewComponent::ImagePreviewComponent()
  47260. {
  47261. }
  47262. ImagePreviewComponent::~ImagePreviewComponent()
  47263. {
  47264. }
  47265. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47266. {
  47267. const int availableW = proportionOfWidth (0.97f);
  47268. const int availableH = getHeight() - 13 * 4;
  47269. const double scale = jmin (1.0,
  47270. availableW / (double) w,
  47271. availableH / (double) h);
  47272. w = roundToInt (scale * w);
  47273. h = roundToInt (scale * h);
  47274. }
  47275. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47276. {
  47277. if (fileToLoad != file)
  47278. {
  47279. fileToLoad = file;
  47280. startTimer (100);
  47281. }
  47282. }
  47283. void ImagePreviewComponent::timerCallback()
  47284. {
  47285. stopTimer();
  47286. currentThumbnail = Image();
  47287. currentDetails = String::empty;
  47288. repaint();
  47289. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47290. if (in != 0)
  47291. {
  47292. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47293. if (format != 0)
  47294. {
  47295. currentThumbnail = format->decodeImage (*in);
  47296. if (currentThumbnail.isValid())
  47297. {
  47298. int w = currentThumbnail.getWidth();
  47299. int h = currentThumbnail.getHeight();
  47300. currentDetails
  47301. << fileToLoad.getFileName() << "\n"
  47302. << format->getFormatName() << "\n"
  47303. << w << " x " << h << " pixels\n"
  47304. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47305. getThumbSize (w, h);
  47306. currentThumbnail = currentThumbnail.rescaled (w, h);
  47307. }
  47308. }
  47309. }
  47310. }
  47311. void ImagePreviewComponent::paint (Graphics& g)
  47312. {
  47313. if (currentThumbnail.isValid())
  47314. {
  47315. g.setFont (13.0f);
  47316. int w = currentThumbnail.getWidth();
  47317. int h = currentThumbnail.getHeight();
  47318. getThumbSize (w, h);
  47319. const int numLines = 4;
  47320. const int totalH = 13 * numLines + h + 4;
  47321. const int y = (getHeight() - totalH) / 2;
  47322. g.drawImageWithin (currentThumbnail,
  47323. (getWidth() - w) / 2, y, w, h,
  47324. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47325. false);
  47326. g.drawFittedText (currentDetails,
  47327. 0, y + h + 4, getWidth(), 100,
  47328. Justification::centredTop, numLines);
  47329. }
  47330. }
  47331. END_JUCE_NAMESPACE
  47332. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47333. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47334. BEGIN_JUCE_NAMESPACE
  47335. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47336. const String& directoryWildcardPatterns,
  47337. const String& description_)
  47338. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47339. : (description_ + " (" + fileWildcardPatterns + ")"))
  47340. {
  47341. parse (fileWildcardPatterns, fileWildcards);
  47342. parse (directoryWildcardPatterns, directoryWildcards);
  47343. }
  47344. WildcardFileFilter::~WildcardFileFilter()
  47345. {
  47346. }
  47347. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47348. {
  47349. return match (file, fileWildcards);
  47350. }
  47351. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47352. {
  47353. return match (file, directoryWildcards);
  47354. }
  47355. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47356. {
  47357. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47358. result.trim();
  47359. result.removeEmptyStrings();
  47360. // special case for *.*, because people use it to mean "any file", but it
  47361. // would actually ignore files with no extension.
  47362. for (int i = result.size(); --i >= 0;)
  47363. if (result[i] == "*.*")
  47364. result.set (i, "*");
  47365. }
  47366. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47367. {
  47368. const String filename (file.getFileName());
  47369. for (int i = wildcards.size(); --i >= 0;)
  47370. if (filename.matchesWildcard (wildcards[i], true))
  47371. return true;
  47372. return false;
  47373. }
  47374. END_JUCE_NAMESPACE
  47375. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47376. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47377. BEGIN_JUCE_NAMESPACE
  47378. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47379. {
  47380. }
  47381. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47382. {
  47383. }
  47384. namespace KeyboardFocusHelpers
  47385. {
  47386. // This will sort a set of components, so that they are ordered in terms of
  47387. // left-to-right and then top-to-bottom.
  47388. class ScreenPositionComparator
  47389. {
  47390. public:
  47391. ScreenPositionComparator() {}
  47392. static int compareElements (const Component* const first, const Component* const second)
  47393. {
  47394. int explicitOrder1 = first->getExplicitFocusOrder();
  47395. if (explicitOrder1 <= 0)
  47396. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47397. int explicitOrder2 = second->getExplicitFocusOrder();
  47398. if (explicitOrder2 <= 0)
  47399. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47400. if (explicitOrder1 != explicitOrder2)
  47401. return explicitOrder1 - explicitOrder2;
  47402. const int diff = first->getY() - second->getY();
  47403. return (diff == 0) ? first->getX() - second->getX()
  47404. : diff;
  47405. }
  47406. };
  47407. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47408. {
  47409. if (parent->getNumChildComponents() > 0)
  47410. {
  47411. Array <Component*> localComps;
  47412. ScreenPositionComparator comparator;
  47413. int i;
  47414. for (i = parent->getNumChildComponents(); --i >= 0;)
  47415. {
  47416. Component* const c = parent->getChildComponent (i);
  47417. if (c->isVisible() && c->isEnabled())
  47418. localComps.addSorted (comparator, c);
  47419. }
  47420. for (i = 0; i < localComps.size(); ++i)
  47421. {
  47422. Component* const c = localComps.getUnchecked (i);
  47423. if (c->getWantsKeyboardFocus())
  47424. comps.add (c);
  47425. if (! c->isFocusContainer())
  47426. findAllFocusableComponents (c, comps);
  47427. }
  47428. }
  47429. }
  47430. }
  47431. static Component* getIncrementedComponent (Component* const current, const int delta)
  47432. {
  47433. Component* focusContainer = current->getParentComponent();
  47434. if (focusContainer != 0)
  47435. {
  47436. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47437. focusContainer = focusContainer->getParentComponent();
  47438. if (focusContainer != 0)
  47439. {
  47440. Array <Component*> comps;
  47441. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47442. if (comps.size() > 0)
  47443. {
  47444. const int index = comps.indexOf (current);
  47445. return comps [(index + comps.size() + delta) % comps.size()];
  47446. }
  47447. }
  47448. }
  47449. return 0;
  47450. }
  47451. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47452. {
  47453. return getIncrementedComponent (current, 1);
  47454. }
  47455. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47456. {
  47457. return getIncrementedComponent (current, -1);
  47458. }
  47459. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47460. {
  47461. Array <Component*> comps;
  47462. if (parentComponent != 0)
  47463. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47464. return comps.getFirst();
  47465. }
  47466. END_JUCE_NAMESPACE
  47467. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47468. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47469. BEGIN_JUCE_NAMESPACE
  47470. bool KeyListener::keyStateChanged (const bool, Component*)
  47471. {
  47472. return false;
  47473. }
  47474. END_JUCE_NAMESPACE
  47475. /*** End of inlined file: juce_KeyListener.cpp ***/
  47476. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47477. BEGIN_JUCE_NAMESPACE
  47478. // N.B. these two includes are put here deliberately to avoid problems with
  47479. // old GCCs failing on long include paths
  47480. const int maxKeys = 3;
  47481. class KeyMappingChangeButton : public Button
  47482. {
  47483. public:
  47484. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47485. const CommandID commandID_,
  47486. const String& keyName,
  47487. const int keyNum_)
  47488. : Button (keyName),
  47489. owner (owner_),
  47490. commandID (commandID_),
  47491. keyNum (keyNum_)
  47492. {
  47493. setWantsKeyboardFocus (false);
  47494. setTriggeredOnMouseDown (keyNum >= 0);
  47495. if (keyNum_ < 0)
  47496. setTooltip (TRANS("adds a new key-mapping"));
  47497. else
  47498. setTooltip (TRANS("click to change this key-mapping"));
  47499. }
  47500. ~KeyMappingChangeButton()
  47501. {
  47502. }
  47503. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47504. {
  47505. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47506. keyNum >= 0 ? getName() : String::empty);
  47507. }
  47508. void clicked()
  47509. {
  47510. if (keyNum >= 0)
  47511. {
  47512. // existing key clicked..
  47513. PopupMenu m;
  47514. m.addItem (1, TRANS("change this key-mapping"));
  47515. m.addSeparator();
  47516. m.addItem (2, TRANS("remove this key-mapping"));
  47517. const int res = m.show();
  47518. if (res == 1)
  47519. {
  47520. owner->assignNewKey (commandID, keyNum);
  47521. }
  47522. else if (res == 2)
  47523. {
  47524. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47525. }
  47526. }
  47527. else
  47528. {
  47529. // + button pressed..
  47530. owner->assignNewKey (commandID, -1);
  47531. }
  47532. }
  47533. void fitToContent (const int h) throw()
  47534. {
  47535. if (keyNum < 0)
  47536. {
  47537. setSize (h, h);
  47538. }
  47539. else
  47540. {
  47541. Font f (h * 0.6f);
  47542. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47543. }
  47544. }
  47545. juce_UseDebuggingNewOperator
  47546. private:
  47547. KeyMappingEditorComponent* const owner;
  47548. const CommandID commandID;
  47549. const int keyNum;
  47550. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47551. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47552. };
  47553. class KeyMappingItemComponent : public Component
  47554. {
  47555. public:
  47556. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47557. const CommandID commandID_)
  47558. : owner (owner_),
  47559. commandID (commandID_)
  47560. {
  47561. setInterceptsMouseClicks (false, true);
  47562. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47563. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47564. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47565. {
  47566. KeyMappingChangeButton* const kb
  47567. = new KeyMappingChangeButton (owner_, commandID,
  47568. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47569. kb->setEnabled (! isReadOnly);
  47570. addAndMakeVisible (kb);
  47571. }
  47572. KeyMappingChangeButton* const kb
  47573. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47574. addChildComponent (kb);
  47575. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47576. }
  47577. ~KeyMappingItemComponent()
  47578. {
  47579. deleteAllChildren();
  47580. }
  47581. void paint (Graphics& g)
  47582. {
  47583. g.setFont (getHeight() * 0.7f);
  47584. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47585. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47586. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47587. Justification::centredLeft, true);
  47588. }
  47589. void resized()
  47590. {
  47591. int x = getWidth() - 4;
  47592. for (int i = getNumChildComponents(); --i >= 0;)
  47593. {
  47594. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47595. kb->fitToContent (getHeight() - 2);
  47596. kb->setTopRightPosition (x, 1);
  47597. x -= kb->getWidth() + 5;
  47598. }
  47599. }
  47600. juce_UseDebuggingNewOperator
  47601. private:
  47602. KeyMappingEditorComponent* const owner;
  47603. const CommandID commandID;
  47604. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47605. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47606. };
  47607. class KeyMappingTreeViewItem : public TreeViewItem
  47608. {
  47609. public:
  47610. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47611. const CommandID commandID_)
  47612. : owner (owner_),
  47613. commandID (commandID_)
  47614. {
  47615. }
  47616. ~KeyMappingTreeViewItem()
  47617. {
  47618. }
  47619. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47620. bool mightContainSubItems() { return false; }
  47621. int getItemHeight() const { return 20; }
  47622. Component* createItemComponent()
  47623. {
  47624. return new KeyMappingItemComponent (owner, commandID);
  47625. }
  47626. juce_UseDebuggingNewOperator
  47627. private:
  47628. KeyMappingEditorComponent* const owner;
  47629. const CommandID commandID;
  47630. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47631. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47632. };
  47633. class KeyCategoryTreeViewItem : public TreeViewItem
  47634. {
  47635. public:
  47636. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47637. const String& name)
  47638. : owner (owner_),
  47639. categoryName (name)
  47640. {
  47641. }
  47642. ~KeyCategoryTreeViewItem()
  47643. {
  47644. }
  47645. const String getUniqueName() const { return categoryName + "_cat"; }
  47646. bool mightContainSubItems() { return true; }
  47647. int getItemHeight() const { return 28; }
  47648. void paintItem (Graphics& g, int width, int height)
  47649. {
  47650. g.setFont (height * 0.6f, Font::bold);
  47651. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47652. g.drawText (categoryName,
  47653. 2, 0, width - 2, height,
  47654. Justification::centredLeft, true);
  47655. }
  47656. void itemOpennessChanged (bool isNowOpen)
  47657. {
  47658. if (isNowOpen)
  47659. {
  47660. if (getNumSubItems() == 0)
  47661. {
  47662. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47663. for (int i = 0; i < commands.size(); ++i)
  47664. {
  47665. if (owner->shouldCommandBeIncluded (commands[i]))
  47666. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47667. }
  47668. }
  47669. }
  47670. else
  47671. {
  47672. clearSubItems();
  47673. }
  47674. }
  47675. juce_UseDebuggingNewOperator
  47676. private:
  47677. KeyMappingEditorComponent* owner;
  47678. String categoryName;
  47679. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47680. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47681. };
  47682. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47683. const bool showResetToDefaultButton)
  47684. : mappings (mappingManager)
  47685. {
  47686. jassert (mappingManager != 0); // can't be null!
  47687. mappingManager->addChangeListener (this);
  47688. setLinesDrawnForSubItems (false);
  47689. resetButton = 0;
  47690. if (showResetToDefaultButton)
  47691. {
  47692. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47693. resetButton->addButtonListener (this);
  47694. }
  47695. addAndMakeVisible (tree = new TreeView());
  47696. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47697. tree->setRootItemVisible (false);
  47698. tree->setDefaultOpenness (true);
  47699. tree->setRootItem (this);
  47700. }
  47701. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47702. {
  47703. mappings->removeChangeListener (this);
  47704. deleteAllChildren();
  47705. }
  47706. bool KeyMappingEditorComponent::mightContainSubItems()
  47707. {
  47708. return true;
  47709. }
  47710. const String KeyMappingEditorComponent::getUniqueName() const
  47711. {
  47712. return "keys";
  47713. }
  47714. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47715. const Colour& textColour)
  47716. {
  47717. setColour (backgroundColourId, mainBackground);
  47718. setColour (textColourId, textColour);
  47719. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47720. }
  47721. void KeyMappingEditorComponent::parentHierarchyChanged()
  47722. {
  47723. changeListenerCallback (0);
  47724. }
  47725. void KeyMappingEditorComponent::resized()
  47726. {
  47727. int h = getHeight();
  47728. if (resetButton != 0)
  47729. {
  47730. const int buttonHeight = 20;
  47731. h -= buttonHeight + 8;
  47732. int x = getWidth() - 8;
  47733. resetButton->changeWidthToFitText (buttonHeight);
  47734. resetButton->setTopRightPosition (x, h + 6);
  47735. }
  47736. tree->setBounds (0, 0, getWidth(), h);
  47737. }
  47738. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47739. {
  47740. if (button == resetButton)
  47741. {
  47742. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47743. TRANS("Reset to defaults"),
  47744. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47745. TRANS("Reset")))
  47746. {
  47747. mappings->resetToDefaultMappings();
  47748. }
  47749. }
  47750. }
  47751. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47752. {
  47753. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47754. clearSubItems();
  47755. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47756. for (int i = 0; i < categories.size(); ++i)
  47757. {
  47758. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47759. int count = 0;
  47760. for (int j = 0; j < commands.size(); ++j)
  47761. if (shouldCommandBeIncluded (commands[j]))
  47762. ++count;
  47763. if (count > 0)
  47764. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47765. }
  47766. if (oldOpenness != 0)
  47767. tree->restoreOpennessState (*oldOpenness);
  47768. }
  47769. class KeyEntryWindow : public AlertWindow
  47770. {
  47771. public:
  47772. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47773. : AlertWindow (TRANS("New key-mapping"),
  47774. TRANS("Please press a key combination now..."),
  47775. AlertWindow::NoIcon),
  47776. owner (owner_)
  47777. {
  47778. addButton (TRANS("ok"), 1);
  47779. addButton (TRANS("cancel"), 0);
  47780. // (avoid return + escape keys getting processed by the buttons..)
  47781. for (int i = getNumChildComponents(); --i >= 0;)
  47782. getChildComponent (i)->setWantsKeyboardFocus (false);
  47783. setWantsKeyboardFocus (true);
  47784. grabKeyboardFocus();
  47785. }
  47786. ~KeyEntryWindow()
  47787. {
  47788. }
  47789. bool keyPressed (const KeyPress& key)
  47790. {
  47791. lastPress = key;
  47792. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  47793. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  47794. if (previousCommand != 0)
  47795. {
  47796. message << "\n\n"
  47797. << TRANS("(Currently assigned to \"")
  47798. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  47799. << "\")";
  47800. }
  47801. setMessage (message);
  47802. return true;
  47803. }
  47804. bool keyStateChanged (bool)
  47805. {
  47806. return true;
  47807. }
  47808. KeyPress lastPress;
  47809. juce_UseDebuggingNewOperator
  47810. private:
  47811. KeyMappingEditorComponent* owner;
  47812. KeyEntryWindow (const KeyEntryWindow&);
  47813. KeyEntryWindow& operator= (const KeyEntryWindow&);
  47814. };
  47815. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  47816. {
  47817. KeyEntryWindow entryWindow (this);
  47818. if (entryWindow.runModalLoop() != 0)
  47819. {
  47820. entryWindow.setVisible (false);
  47821. if (entryWindow.lastPress.isValid())
  47822. {
  47823. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  47824. if (previousCommand != 0)
  47825. {
  47826. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47827. TRANS("Change key-mapping"),
  47828. TRANS("This key is already assigned to the command \"")
  47829. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  47830. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  47831. TRANS("re-assign"),
  47832. TRANS("cancel")))
  47833. {
  47834. return;
  47835. }
  47836. }
  47837. mappings->removeKeyPress (entryWindow.lastPress);
  47838. if (index >= 0)
  47839. mappings->removeKeyPress (commandID, index);
  47840. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  47841. }
  47842. }
  47843. }
  47844. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  47845. {
  47846. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47847. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  47848. }
  47849. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  47850. {
  47851. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47852. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  47853. }
  47854. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  47855. {
  47856. return key.getTextDescription();
  47857. }
  47858. END_JUCE_NAMESPACE
  47859. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47860. /*** Start of inlined file: juce_KeyPress.cpp ***/
  47861. BEGIN_JUCE_NAMESPACE
  47862. KeyPress::KeyPress() throw()
  47863. : keyCode (0),
  47864. mods (0),
  47865. textCharacter (0)
  47866. {
  47867. }
  47868. KeyPress::KeyPress (const int keyCode_,
  47869. const ModifierKeys& mods_,
  47870. const juce_wchar textCharacter_) throw()
  47871. : keyCode (keyCode_),
  47872. mods (mods_),
  47873. textCharacter (textCharacter_)
  47874. {
  47875. }
  47876. KeyPress::KeyPress (const int keyCode_) throw()
  47877. : keyCode (keyCode_),
  47878. textCharacter (0)
  47879. {
  47880. }
  47881. KeyPress::KeyPress (const KeyPress& other) throw()
  47882. : keyCode (other.keyCode),
  47883. mods (other.mods),
  47884. textCharacter (other.textCharacter)
  47885. {
  47886. }
  47887. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  47888. {
  47889. keyCode = other.keyCode;
  47890. mods = other.mods;
  47891. textCharacter = other.textCharacter;
  47892. return *this;
  47893. }
  47894. bool KeyPress::operator== (const KeyPress& other) const throw()
  47895. {
  47896. return mods.getRawFlags() == other.mods.getRawFlags()
  47897. && (textCharacter == other.textCharacter
  47898. || textCharacter == 0
  47899. || other.textCharacter == 0)
  47900. && (keyCode == other.keyCode
  47901. || (keyCode < 256
  47902. && other.keyCode < 256
  47903. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  47904. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  47905. }
  47906. bool KeyPress::operator!= (const KeyPress& other) const throw()
  47907. {
  47908. return ! operator== (other);
  47909. }
  47910. bool KeyPress::isCurrentlyDown() const
  47911. {
  47912. return isKeyCurrentlyDown (keyCode)
  47913. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  47914. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  47915. }
  47916. namespace KeyPressHelpers
  47917. {
  47918. struct KeyNameAndCode
  47919. {
  47920. const char* name;
  47921. int code;
  47922. };
  47923. static const KeyNameAndCode translations[] =
  47924. {
  47925. { "spacebar", KeyPress::spaceKey },
  47926. { "return", KeyPress::returnKey },
  47927. { "escape", KeyPress::escapeKey },
  47928. { "backspace", KeyPress::backspaceKey },
  47929. { "cursor left", KeyPress::leftKey },
  47930. { "cursor right", KeyPress::rightKey },
  47931. { "cursor up", KeyPress::upKey },
  47932. { "cursor down", KeyPress::downKey },
  47933. { "page up", KeyPress::pageUpKey },
  47934. { "page down", KeyPress::pageDownKey },
  47935. { "home", KeyPress::homeKey },
  47936. { "end", KeyPress::endKey },
  47937. { "delete", KeyPress::deleteKey },
  47938. { "insert", KeyPress::insertKey },
  47939. { "tab", KeyPress::tabKey },
  47940. { "play", KeyPress::playKey },
  47941. { "stop", KeyPress::stopKey },
  47942. { "fast forward", KeyPress::fastForwardKey },
  47943. { "rewind", KeyPress::rewindKey }
  47944. };
  47945. static const String numberPadPrefix() { return "numpad "; }
  47946. }
  47947. const KeyPress KeyPress::createFromDescription (const String& desc)
  47948. {
  47949. int modifiers = 0;
  47950. if (desc.containsWholeWordIgnoreCase ("ctrl")
  47951. || desc.containsWholeWordIgnoreCase ("control")
  47952. || desc.containsWholeWordIgnoreCase ("ctl"))
  47953. modifiers |= ModifierKeys::ctrlModifier;
  47954. if (desc.containsWholeWordIgnoreCase ("shift")
  47955. || desc.containsWholeWordIgnoreCase ("shft"))
  47956. modifiers |= ModifierKeys::shiftModifier;
  47957. if (desc.containsWholeWordIgnoreCase ("alt")
  47958. || desc.containsWholeWordIgnoreCase ("option"))
  47959. modifiers |= ModifierKeys::altModifier;
  47960. if (desc.containsWholeWordIgnoreCase ("command")
  47961. || desc.containsWholeWordIgnoreCase ("cmd"))
  47962. modifiers |= ModifierKeys::commandModifier;
  47963. int key = 0;
  47964. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  47965. {
  47966. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  47967. {
  47968. key = KeyPressHelpers::translations[i].code;
  47969. break;
  47970. }
  47971. }
  47972. if (key == 0)
  47973. {
  47974. // see if it's a numpad key..
  47975. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  47976. {
  47977. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  47978. if (lastChar >= '0' && lastChar <= '9')
  47979. key = numberPad0 + lastChar - '0';
  47980. else if (lastChar == '+')
  47981. key = numberPadAdd;
  47982. else if (lastChar == '-')
  47983. key = numberPadSubtract;
  47984. else if (lastChar == '*')
  47985. key = numberPadMultiply;
  47986. else if (lastChar == '/')
  47987. key = numberPadDivide;
  47988. else if (lastChar == '.')
  47989. key = numberPadDecimalPoint;
  47990. else if (lastChar == '=')
  47991. key = numberPadEquals;
  47992. else if (desc.endsWith ("separator"))
  47993. key = numberPadSeparator;
  47994. else if (desc.endsWith ("delete"))
  47995. key = numberPadDelete;
  47996. }
  47997. if (key == 0)
  47998. {
  47999. // see if it's a function key..
  48000. for (int i = 1; i <= 12; ++i)
  48001. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48002. key = F1Key + i - 1;
  48003. if (key == 0)
  48004. {
  48005. // give up and use the hex code..
  48006. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48007. .toLowerCase()
  48008. .retainCharacters ("0123456789abcdef")
  48009. .getHexValue32();
  48010. if (hexCode > 0)
  48011. key = hexCode;
  48012. else
  48013. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48014. }
  48015. }
  48016. }
  48017. return KeyPress (key, ModifierKeys (modifiers), 0);
  48018. }
  48019. const String KeyPress::getTextDescription() const
  48020. {
  48021. String desc;
  48022. if (keyCode > 0)
  48023. {
  48024. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48025. // want to store it as being a slash, not shift+whatever.
  48026. if (textCharacter == '/')
  48027. return "/";
  48028. if (mods.isCtrlDown())
  48029. desc << "ctrl + ";
  48030. if (mods.isShiftDown())
  48031. desc << "shift + ";
  48032. #if JUCE_MAC
  48033. // only do this on the mac, because on Windows ctrl and command are the same,
  48034. // and this would get confusing
  48035. if (mods.isCommandDown())
  48036. desc << "command + ";
  48037. if (mods.isAltDown())
  48038. desc << "option + ";
  48039. #else
  48040. if (mods.isAltDown())
  48041. desc << "alt + ";
  48042. #endif
  48043. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48044. if (keyCode == KeyPressHelpers::translations[i].code)
  48045. return desc + KeyPressHelpers::translations[i].name;
  48046. if (keyCode >= F1Key && keyCode <= F16Key)
  48047. desc << 'F' << (1 + keyCode - F1Key);
  48048. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48049. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48050. else if (keyCode >= 33 && keyCode < 176)
  48051. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48052. else if (keyCode == numberPadAdd)
  48053. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48054. else if (keyCode == numberPadSubtract)
  48055. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48056. else if (keyCode == numberPadMultiply)
  48057. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48058. else if (keyCode == numberPadDivide)
  48059. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48060. else if (keyCode == numberPadSeparator)
  48061. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48062. else if (keyCode == numberPadDecimalPoint)
  48063. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48064. else if (keyCode == numberPadDelete)
  48065. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48066. else
  48067. desc << '#' << String::toHexString (keyCode);
  48068. }
  48069. return desc;
  48070. }
  48071. END_JUCE_NAMESPACE
  48072. /*** End of inlined file: juce_KeyPress.cpp ***/
  48073. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48074. BEGIN_JUCE_NAMESPACE
  48075. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48076. : commandManager (commandManager_)
  48077. {
  48078. // A manager is needed to get the descriptions of commands, and will be called when
  48079. // a command is invoked. So you can't leave this null..
  48080. jassert (commandManager_ != 0);
  48081. Desktop::getInstance().addFocusChangeListener (this);
  48082. }
  48083. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48084. : commandManager (other.commandManager)
  48085. {
  48086. Desktop::getInstance().addFocusChangeListener (this);
  48087. }
  48088. KeyPressMappingSet::~KeyPressMappingSet()
  48089. {
  48090. Desktop::getInstance().removeFocusChangeListener (this);
  48091. }
  48092. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48093. {
  48094. for (int i = 0; i < mappings.size(); ++i)
  48095. if (mappings.getUnchecked(i)->commandID == commandID)
  48096. return mappings.getUnchecked (i)->keypresses;
  48097. return Array <KeyPress> ();
  48098. }
  48099. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48100. const KeyPress& newKeyPress,
  48101. int insertIndex)
  48102. {
  48103. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48104. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48105. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48106. && ! newKeyPress.getModifiers().isShiftDown()));
  48107. if (findCommandForKeyPress (newKeyPress) != commandID)
  48108. {
  48109. removeKeyPress (newKeyPress);
  48110. if (newKeyPress.isValid())
  48111. {
  48112. for (int i = mappings.size(); --i >= 0;)
  48113. {
  48114. if (mappings.getUnchecked(i)->commandID == commandID)
  48115. {
  48116. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48117. sendChangeMessage (this);
  48118. return;
  48119. }
  48120. }
  48121. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48122. if (ci != 0)
  48123. {
  48124. CommandMapping* const cm = new CommandMapping();
  48125. cm->commandID = commandID;
  48126. cm->keypresses.add (newKeyPress);
  48127. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48128. mappings.add (cm);
  48129. sendChangeMessage (this);
  48130. }
  48131. }
  48132. }
  48133. }
  48134. void KeyPressMappingSet::resetToDefaultMappings()
  48135. {
  48136. mappings.clear();
  48137. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48138. {
  48139. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48140. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48141. {
  48142. addKeyPress (ci->commandID,
  48143. ci->defaultKeypresses.getReference (j));
  48144. }
  48145. }
  48146. sendChangeMessage (this);
  48147. }
  48148. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48149. {
  48150. clearAllKeyPresses (commandID);
  48151. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48152. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48153. {
  48154. addKeyPress (ci->commandID,
  48155. ci->defaultKeypresses.getReference (j));
  48156. }
  48157. }
  48158. void KeyPressMappingSet::clearAllKeyPresses()
  48159. {
  48160. if (mappings.size() > 0)
  48161. {
  48162. sendChangeMessage (this);
  48163. mappings.clear();
  48164. }
  48165. }
  48166. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48167. {
  48168. for (int i = mappings.size(); --i >= 0;)
  48169. {
  48170. if (mappings.getUnchecked(i)->commandID == commandID)
  48171. {
  48172. mappings.remove (i);
  48173. sendChangeMessage (this);
  48174. }
  48175. }
  48176. }
  48177. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48178. {
  48179. if (keypress.isValid())
  48180. {
  48181. for (int i = mappings.size(); --i >= 0;)
  48182. {
  48183. CommandMapping* const cm = mappings.getUnchecked(i);
  48184. for (int j = cm->keypresses.size(); --j >= 0;)
  48185. {
  48186. if (keypress == cm->keypresses [j])
  48187. {
  48188. cm->keypresses.remove (j);
  48189. sendChangeMessage (this);
  48190. }
  48191. }
  48192. }
  48193. }
  48194. }
  48195. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48196. {
  48197. for (int i = mappings.size(); --i >= 0;)
  48198. {
  48199. if (mappings.getUnchecked(i)->commandID == commandID)
  48200. {
  48201. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48202. sendChangeMessage (this);
  48203. break;
  48204. }
  48205. }
  48206. }
  48207. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48208. {
  48209. for (int i = 0; i < mappings.size(); ++i)
  48210. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48211. return mappings.getUnchecked(i)->commandID;
  48212. return 0;
  48213. }
  48214. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48215. {
  48216. for (int i = mappings.size(); --i >= 0;)
  48217. if (mappings.getUnchecked(i)->commandID == commandID)
  48218. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48219. return false;
  48220. }
  48221. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48222. const KeyPress& key,
  48223. const bool isKeyDown,
  48224. const int millisecsSinceKeyPressed,
  48225. Component* const originatingComponent) const
  48226. {
  48227. ApplicationCommandTarget::InvocationInfo info (commandID);
  48228. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48229. info.isKeyDown = isKeyDown;
  48230. info.keyPress = key;
  48231. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48232. info.originatingComponent = originatingComponent;
  48233. commandManager->invoke (info, false);
  48234. }
  48235. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48236. {
  48237. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48238. {
  48239. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48240. {
  48241. // if the XML was created as a set of differences from the default mappings,
  48242. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48243. resetToDefaultMappings();
  48244. }
  48245. else
  48246. {
  48247. // if the XML was created calling createXml (false), then we need to clear all
  48248. // the keys and treat the xml as describing the entire set of mappings.
  48249. clearAllKeyPresses();
  48250. }
  48251. forEachXmlChildElement (xmlVersion, map)
  48252. {
  48253. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48254. if (commandId != 0)
  48255. {
  48256. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48257. if (map->hasTagName ("MAPPING"))
  48258. {
  48259. addKeyPress (commandId, key);
  48260. }
  48261. else if (map->hasTagName ("UNMAPPING"))
  48262. {
  48263. if (containsMapping (commandId, key))
  48264. removeKeyPress (key);
  48265. }
  48266. }
  48267. }
  48268. return true;
  48269. }
  48270. return false;
  48271. }
  48272. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48273. {
  48274. ScopedPointer <KeyPressMappingSet> defaultSet;
  48275. if (saveDifferencesFromDefaultSet)
  48276. {
  48277. defaultSet = new KeyPressMappingSet (commandManager);
  48278. defaultSet->resetToDefaultMappings();
  48279. }
  48280. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48281. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48282. int i;
  48283. for (i = 0; i < mappings.size(); ++i)
  48284. {
  48285. const CommandMapping* const cm = mappings.getUnchecked(i);
  48286. for (int j = 0; j < cm->keypresses.size(); ++j)
  48287. {
  48288. if (defaultSet == 0
  48289. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48290. {
  48291. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48292. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48293. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48294. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48295. }
  48296. }
  48297. }
  48298. if (defaultSet != 0)
  48299. {
  48300. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48301. {
  48302. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48303. for (int j = 0; j < cm->keypresses.size(); ++j)
  48304. {
  48305. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48306. {
  48307. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48308. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48309. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48310. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48311. }
  48312. }
  48313. }
  48314. }
  48315. return doc;
  48316. }
  48317. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48318. Component* originatingComponent)
  48319. {
  48320. bool used = false;
  48321. const CommandID commandID = findCommandForKeyPress (key);
  48322. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48323. if (ci != 0
  48324. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48325. {
  48326. ApplicationCommandInfo info (0);
  48327. if (commandManager->getTargetForCommand (commandID, info) != 0
  48328. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48329. {
  48330. invokeCommand (commandID, key, true, 0, originatingComponent);
  48331. used = true;
  48332. }
  48333. else
  48334. {
  48335. if (originatingComponent != 0)
  48336. originatingComponent->getLookAndFeel().playAlertSound();
  48337. }
  48338. }
  48339. return used;
  48340. }
  48341. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48342. {
  48343. bool used = false;
  48344. const uint32 now = Time::getMillisecondCounter();
  48345. for (int i = mappings.size(); --i >= 0;)
  48346. {
  48347. CommandMapping* const cm = mappings.getUnchecked(i);
  48348. if (cm->wantsKeyUpDownCallbacks)
  48349. {
  48350. for (int j = cm->keypresses.size(); --j >= 0;)
  48351. {
  48352. const KeyPress key (cm->keypresses.getReference (j));
  48353. const bool isDown = key.isCurrentlyDown();
  48354. int keyPressEntryIndex = 0;
  48355. bool wasDown = false;
  48356. for (int k = keysDown.size(); --k >= 0;)
  48357. {
  48358. if (key == keysDown.getUnchecked(k)->key)
  48359. {
  48360. keyPressEntryIndex = k;
  48361. wasDown = true;
  48362. used = true;
  48363. break;
  48364. }
  48365. }
  48366. if (isDown != wasDown)
  48367. {
  48368. int millisecs = 0;
  48369. if (isDown)
  48370. {
  48371. KeyPressTime* const k = new KeyPressTime();
  48372. k->key = key;
  48373. k->timeWhenPressed = now;
  48374. keysDown.add (k);
  48375. }
  48376. else
  48377. {
  48378. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48379. if (now > pressTime)
  48380. millisecs = now - pressTime;
  48381. keysDown.remove (keyPressEntryIndex);
  48382. }
  48383. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48384. used = true;
  48385. }
  48386. }
  48387. }
  48388. }
  48389. return used;
  48390. }
  48391. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48392. {
  48393. if (focusedComponent != 0)
  48394. focusedComponent->keyStateChanged (false);
  48395. }
  48396. END_JUCE_NAMESPACE
  48397. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48398. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48399. BEGIN_JUCE_NAMESPACE
  48400. ModifierKeys::ModifierKeys (const int flags_) throw()
  48401. : flags (flags_)
  48402. {
  48403. }
  48404. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48405. : flags (other.flags)
  48406. {
  48407. }
  48408. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48409. {
  48410. flags = other.flags;
  48411. return *this;
  48412. }
  48413. ModifierKeys ModifierKeys::currentModifiers;
  48414. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48415. {
  48416. return currentModifiers;
  48417. }
  48418. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48419. {
  48420. int num = 0;
  48421. if (isLeftButtonDown()) ++num;
  48422. if (isRightButtonDown()) ++num;
  48423. if (isMiddleButtonDown()) ++num;
  48424. return num;
  48425. }
  48426. END_JUCE_NAMESPACE
  48427. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48428. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48429. BEGIN_JUCE_NAMESPACE
  48430. class ComponentAnimator::AnimationTask
  48431. {
  48432. public:
  48433. AnimationTask (Component* const comp)
  48434. : component (comp)
  48435. {
  48436. }
  48437. Component::SafePointer<Component> component;
  48438. Rectangle<int> destination;
  48439. int msElapsed, msTotal;
  48440. double startSpeed, midSpeed, endSpeed, lastProgress;
  48441. double left, top, right, bottom;
  48442. bool useTimeslice (const int elapsed)
  48443. {
  48444. if (component == 0)
  48445. return false;
  48446. msElapsed += elapsed;
  48447. double newProgress = msElapsed / (double) msTotal;
  48448. if (newProgress >= 0 && newProgress < 1.0)
  48449. {
  48450. newProgress = timeToDistance (newProgress);
  48451. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48452. jassert (newProgress >= lastProgress);
  48453. lastProgress = newProgress;
  48454. left += (destination.getX() - left) * delta;
  48455. top += (destination.getY() - top) * delta;
  48456. right += (destination.getRight() - right) * delta;
  48457. bottom += (destination.getBottom() - bottom) * delta;
  48458. if (delta < 1.0)
  48459. {
  48460. const Rectangle<int> newBounds (roundToInt (left),
  48461. roundToInt (top),
  48462. roundToInt (right - left),
  48463. roundToInt (bottom - top));
  48464. if (newBounds != destination)
  48465. {
  48466. component->setBounds (newBounds);
  48467. return true;
  48468. }
  48469. }
  48470. }
  48471. component->setBounds (destination);
  48472. return false;
  48473. }
  48474. void moveToFinalDestination()
  48475. {
  48476. if (component != 0)
  48477. component->setBounds (destination);
  48478. }
  48479. private:
  48480. inline double timeToDistance (const double time) const
  48481. {
  48482. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48483. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48484. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48485. }
  48486. };
  48487. ComponentAnimator::ComponentAnimator()
  48488. : lastTime (0)
  48489. {
  48490. }
  48491. ComponentAnimator::~ComponentAnimator()
  48492. {
  48493. cancelAllAnimations (false);
  48494. jassert (tasks.size() == 0);
  48495. }
  48496. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48497. {
  48498. for (int i = tasks.size(); --i >= 0;)
  48499. if (component == tasks.getUnchecked(i)->component.getComponent())
  48500. return tasks.getUnchecked(i);
  48501. return 0;
  48502. }
  48503. void ComponentAnimator::animateComponent (Component* const component,
  48504. const Rectangle<int>& finalPosition,
  48505. const int millisecondsToSpendMoving,
  48506. const double startSpeed,
  48507. const double endSpeed)
  48508. {
  48509. if (component != 0)
  48510. {
  48511. AnimationTask* at = findTaskFor (component);
  48512. if (at == 0)
  48513. {
  48514. at = new AnimationTask (component);
  48515. tasks.add (at);
  48516. sendChangeMessage (this);
  48517. }
  48518. at->msElapsed = 0;
  48519. at->lastProgress = 0;
  48520. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48521. at->destination = finalPosition;
  48522. // the speeds must be 0 or greater!
  48523. jassert (startSpeed >= 0 && endSpeed >= 0)
  48524. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48525. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48526. at->midSpeed = invTotalDistance;
  48527. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48528. at->left = component->getX();
  48529. at->top = component->getY();
  48530. at->right = component->getRight();
  48531. at->bottom = component->getBottom();
  48532. if (! isTimerRunning())
  48533. {
  48534. lastTime = Time::getMillisecondCounter();
  48535. startTimer (1000 / 50);
  48536. }
  48537. }
  48538. }
  48539. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48540. {
  48541. for (int i = tasks.size(); --i >= 0;)
  48542. {
  48543. AnimationTask* const at = tasks.getUnchecked(i);
  48544. if (moveComponentsToTheirFinalPositions)
  48545. at->moveToFinalDestination();
  48546. delete at;
  48547. tasks.remove (i);
  48548. sendChangeMessage (this);
  48549. }
  48550. }
  48551. void ComponentAnimator::cancelAnimation (Component* const component,
  48552. const bool moveComponentToItsFinalPosition)
  48553. {
  48554. AnimationTask* const at = findTaskFor (component);
  48555. if (at != 0)
  48556. {
  48557. if (moveComponentToItsFinalPosition)
  48558. at->moveToFinalDestination();
  48559. tasks.removeValue (at);
  48560. delete at;
  48561. sendChangeMessage (this);
  48562. }
  48563. }
  48564. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48565. {
  48566. AnimationTask* const at = findTaskFor (component);
  48567. if (at != 0)
  48568. return at->destination;
  48569. else if (component != 0)
  48570. return component->getBounds();
  48571. return Rectangle<int>();
  48572. }
  48573. bool ComponentAnimator::isAnimating (Component* component) const
  48574. {
  48575. return findTaskFor (component) != 0;
  48576. }
  48577. void ComponentAnimator::timerCallback()
  48578. {
  48579. const uint32 timeNow = Time::getMillisecondCounter();
  48580. if (lastTime == 0 || lastTime == timeNow)
  48581. lastTime = timeNow;
  48582. const int elapsed = timeNow - lastTime;
  48583. for (int i = tasks.size(); --i >= 0;)
  48584. {
  48585. AnimationTask* const at = tasks.getUnchecked(i);
  48586. if (! at->useTimeslice (elapsed))
  48587. {
  48588. tasks.remove (i);
  48589. delete at;
  48590. sendChangeMessage (this);
  48591. }
  48592. }
  48593. lastTime = timeNow;
  48594. if (tasks.size() == 0)
  48595. stopTimer();
  48596. }
  48597. END_JUCE_NAMESPACE
  48598. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48599. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48600. BEGIN_JUCE_NAMESPACE
  48601. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48602. : minW (0),
  48603. maxW (0x3fffffff),
  48604. minH (0),
  48605. maxH (0x3fffffff),
  48606. minOffTop (0),
  48607. minOffLeft (0),
  48608. minOffBottom (0),
  48609. minOffRight (0),
  48610. aspectRatio (0.0)
  48611. {
  48612. }
  48613. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48614. {
  48615. }
  48616. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48617. {
  48618. minW = minimumWidth;
  48619. }
  48620. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48621. {
  48622. maxW = maximumWidth;
  48623. }
  48624. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48625. {
  48626. minH = minimumHeight;
  48627. }
  48628. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48629. {
  48630. maxH = maximumHeight;
  48631. }
  48632. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48633. {
  48634. jassert (maxW >= minimumWidth);
  48635. jassert (maxH >= minimumHeight);
  48636. jassert (minimumWidth > 0 && minimumHeight > 0);
  48637. minW = minimumWidth;
  48638. minH = minimumHeight;
  48639. if (minW > maxW)
  48640. maxW = minW;
  48641. if (minH > maxH)
  48642. maxH = minH;
  48643. }
  48644. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48645. {
  48646. jassert (maximumWidth >= minW);
  48647. jassert (maximumHeight >= minH);
  48648. jassert (maximumWidth > 0 && maximumHeight > 0);
  48649. maxW = jmax (minW, maximumWidth);
  48650. maxH = jmax (minH, maximumHeight);
  48651. }
  48652. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48653. const int minimumHeight,
  48654. const int maximumWidth,
  48655. const int maximumHeight) throw()
  48656. {
  48657. jassert (maximumWidth >= minimumWidth);
  48658. jassert (maximumHeight >= minimumHeight);
  48659. jassert (maximumWidth > 0 && maximumHeight > 0);
  48660. jassert (minimumWidth > 0 && minimumHeight > 0);
  48661. minW = jmax (0, minimumWidth);
  48662. minH = jmax (0, minimumHeight);
  48663. maxW = jmax (minW, maximumWidth);
  48664. maxH = jmax (minH, maximumHeight);
  48665. }
  48666. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48667. const int minimumWhenOffTheLeft,
  48668. const int minimumWhenOffTheBottom,
  48669. const int minimumWhenOffTheRight) throw()
  48670. {
  48671. minOffTop = minimumWhenOffTheTop;
  48672. minOffLeft = minimumWhenOffTheLeft;
  48673. minOffBottom = minimumWhenOffTheBottom;
  48674. minOffRight = minimumWhenOffTheRight;
  48675. }
  48676. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48677. {
  48678. aspectRatio = jmax (0.0, widthOverHeight);
  48679. }
  48680. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48681. {
  48682. return aspectRatio;
  48683. }
  48684. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48685. const Rectangle<int>& targetBounds,
  48686. const bool isStretchingTop,
  48687. const bool isStretchingLeft,
  48688. const bool isStretchingBottom,
  48689. const bool isStretchingRight)
  48690. {
  48691. jassert (component != 0);
  48692. Rectangle<int> limits, bounds (targetBounds);
  48693. BorderSize border;
  48694. Component* const parent = component->getParentComponent();
  48695. if (parent == 0)
  48696. {
  48697. ComponentPeer* peer = component->getPeer();
  48698. if (peer != 0)
  48699. border = peer->getFrameSize();
  48700. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48701. }
  48702. else
  48703. {
  48704. limits.setSize (parent->getWidth(), parent->getHeight());
  48705. }
  48706. border.addTo (bounds);
  48707. checkBounds (bounds,
  48708. border.addedTo (component->getBounds()), limits,
  48709. isStretchingTop, isStretchingLeft,
  48710. isStretchingBottom, isStretchingRight);
  48711. border.subtractFrom (bounds);
  48712. applyBoundsToComponent (component, bounds);
  48713. }
  48714. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48715. {
  48716. setBoundsForComponent (component, component->getBounds(),
  48717. false, false, false, false);
  48718. }
  48719. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48720. const Rectangle<int>& bounds)
  48721. {
  48722. component->setBounds (bounds);
  48723. }
  48724. void ComponentBoundsConstrainer::resizeStart()
  48725. {
  48726. }
  48727. void ComponentBoundsConstrainer::resizeEnd()
  48728. {
  48729. }
  48730. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48731. const Rectangle<int>& old,
  48732. const Rectangle<int>& limits,
  48733. const bool isStretchingTop,
  48734. const bool isStretchingLeft,
  48735. const bool isStretchingBottom,
  48736. const bool isStretchingRight)
  48737. {
  48738. int x = bounds.getX();
  48739. int y = bounds.getY();
  48740. int w = bounds.getWidth();
  48741. int h = bounds.getHeight();
  48742. // constrain the size if it's being stretched..
  48743. if (isStretchingLeft)
  48744. {
  48745. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48746. w = old.getRight() - x;
  48747. }
  48748. if (isStretchingRight)
  48749. {
  48750. w = jlimit (minW, maxW, w);
  48751. }
  48752. if (isStretchingTop)
  48753. {
  48754. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48755. h = old.getBottom() - y;
  48756. }
  48757. if (isStretchingBottom)
  48758. {
  48759. h = jlimit (minH, maxH, h);
  48760. }
  48761. // constrain the aspect ratio if one has been specified..
  48762. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48763. {
  48764. bool adjustWidth;
  48765. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48766. {
  48767. adjustWidth = true;
  48768. }
  48769. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48770. {
  48771. adjustWidth = false;
  48772. }
  48773. else
  48774. {
  48775. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48776. const double newRatio = std::abs (w / (double) h);
  48777. adjustWidth = (oldRatio > newRatio);
  48778. }
  48779. if (adjustWidth)
  48780. {
  48781. w = roundToInt (h * aspectRatio);
  48782. if (w > maxW || w < minW)
  48783. {
  48784. w = jlimit (minW, maxW, w);
  48785. h = roundToInt (w / aspectRatio);
  48786. }
  48787. }
  48788. else
  48789. {
  48790. h = roundToInt (w / aspectRatio);
  48791. if (h > maxH || h < minH)
  48792. {
  48793. h = jlimit (minH, maxH, h);
  48794. w = roundToInt (h * aspectRatio);
  48795. }
  48796. }
  48797. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48798. {
  48799. x = old.getX() + (old.getWidth() - w) / 2;
  48800. }
  48801. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48802. {
  48803. y = old.getY() + (old.getHeight() - h) / 2;
  48804. }
  48805. else
  48806. {
  48807. if (isStretchingLeft)
  48808. x = old.getRight() - w;
  48809. if (isStretchingTop)
  48810. y = old.getBottom() - h;
  48811. }
  48812. }
  48813. // ...and constrain the position if limits have been set for that.
  48814. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  48815. {
  48816. if (minOffTop > 0)
  48817. {
  48818. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  48819. if (y < limit)
  48820. {
  48821. if (isStretchingTop)
  48822. h -= (limit - y);
  48823. y = limit;
  48824. }
  48825. }
  48826. if (minOffLeft > 0)
  48827. {
  48828. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  48829. if (x < limit)
  48830. {
  48831. if (isStretchingLeft)
  48832. w -= (limit - x);
  48833. x = limit;
  48834. }
  48835. }
  48836. if (minOffBottom > 0)
  48837. {
  48838. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  48839. if (y > limit)
  48840. {
  48841. if (isStretchingBottom)
  48842. h += (limit - y);
  48843. else
  48844. y = limit;
  48845. }
  48846. }
  48847. if (minOffRight > 0)
  48848. {
  48849. const int limit = limits.getRight() - jmin (minOffRight, w);
  48850. if (x > limit)
  48851. {
  48852. if (isStretchingRight)
  48853. w += (limit - x);
  48854. else
  48855. x = limit;
  48856. }
  48857. }
  48858. }
  48859. jassert (w >= 0 && h >= 0);
  48860. bounds = Rectangle<int> (x, y, w, h);
  48861. }
  48862. END_JUCE_NAMESPACE
  48863. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48864. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48865. BEGIN_JUCE_NAMESPACE
  48866. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  48867. : component (component_),
  48868. lastPeer (0),
  48869. reentrant (false)
  48870. {
  48871. jassert (component != 0); // can't use this with a null pointer..
  48872. component->addComponentListener (this);
  48873. registerWithParentComps();
  48874. }
  48875. ComponentMovementWatcher::~ComponentMovementWatcher()
  48876. {
  48877. component->removeComponentListener (this);
  48878. unregister();
  48879. }
  48880. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  48881. {
  48882. // agh! don't delete the target component without deleting this object first!
  48883. jassert (component != 0);
  48884. if (! reentrant)
  48885. {
  48886. reentrant = true;
  48887. ComponentPeer* const peer = component->getPeer();
  48888. if (peer != lastPeer)
  48889. {
  48890. componentPeerChanged();
  48891. if (component == 0)
  48892. return;
  48893. lastPeer = peer;
  48894. }
  48895. unregister();
  48896. registerWithParentComps();
  48897. reentrant = false;
  48898. componentMovedOrResized (*component, true, true);
  48899. }
  48900. }
  48901. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  48902. {
  48903. // agh! don't delete the target component without deleting this object first!
  48904. jassert (component != 0);
  48905. if (wasMoved)
  48906. {
  48907. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  48908. wasMoved = lastBounds.getPosition() != pos;
  48909. lastBounds.setPosition (pos);
  48910. }
  48911. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  48912. lastBounds.setSize (component->getWidth(), component->getHeight());
  48913. if (wasMoved || wasResized)
  48914. componentMovedOrResized (wasMoved, wasResized);
  48915. }
  48916. void ComponentMovementWatcher::registerWithParentComps() throw()
  48917. {
  48918. Component* p = component->getParentComponent();
  48919. while (p != 0)
  48920. {
  48921. p->addComponentListener (this);
  48922. registeredParentComps.add (p);
  48923. p = p->getParentComponent();
  48924. }
  48925. }
  48926. void ComponentMovementWatcher::unregister() throw()
  48927. {
  48928. for (int i = registeredParentComps.size(); --i >= 0;)
  48929. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  48930. registeredParentComps.clear();
  48931. }
  48932. END_JUCE_NAMESPACE
  48933. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48934. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  48935. BEGIN_JUCE_NAMESPACE
  48936. GroupComponent::GroupComponent (const String& componentName,
  48937. const String& labelText)
  48938. : Component (componentName),
  48939. text (labelText),
  48940. justification (Justification::left)
  48941. {
  48942. setInterceptsMouseClicks (false, true);
  48943. }
  48944. GroupComponent::~GroupComponent()
  48945. {
  48946. }
  48947. void GroupComponent::setText (const String& newText)
  48948. {
  48949. if (text != newText)
  48950. {
  48951. text = newText;
  48952. repaint();
  48953. }
  48954. }
  48955. const String GroupComponent::getText() const
  48956. {
  48957. return text;
  48958. }
  48959. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  48960. {
  48961. if (justification != newJustification)
  48962. {
  48963. justification = newJustification;
  48964. repaint();
  48965. }
  48966. }
  48967. void GroupComponent::paint (Graphics& g)
  48968. {
  48969. getLookAndFeel()
  48970. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  48971. text, justification,
  48972. *this);
  48973. }
  48974. void GroupComponent::enablementChanged()
  48975. {
  48976. repaint();
  48977. }
  48978. void GroupComponent::colourChanged()
  48979. {
  48980. repaint();
  48981. }
  48982. END_JUCE_NAMESPACE
  48983. /*** End of inlined file: juce_GroupComponent.cpp ***/
  48984. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  48985. BEGIN_JUCE_NAMESPACE
  48986. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  48987. : DocumentWindow (String::empty, backgroundColour,
  48988. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  48989. {
  48990. }
  48991. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  48992. {
  48993. }
  48994. void MultiDocumentPanelWindow::maximiseButtonPressed()
  48995. {
  48996. MultiDocumentPanel* const owner = getOwner();
  48997. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  48998. if (owner != 0)
  48999. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49000. }
  49001. void MultiDocumentPanelWindow::closeButtonPressed()
  49002. {
  49003. MultiDocumentPanel* const owner = getOwner();
  49004. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49005. if (owner != 0)
  49006. owner->closeDocument (getContentComponent(), true);
  49007. }
  49008. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49009. {
  49010. DocumentWindow::activeWindowStatusChanged();
  49011. updateOrder();
  49012. }
  49013. void MultiDocumentPanelWindow::broughtToFront()
  49014. {
  49015. DocumentWindow::broughtToFront();
  49016. updateOrder();
  49017. }
  49018. void MultiDocumentPanelWindow::updateOrder()
  49019. {
  49020. MultiDocumentPanel* const owner = getOwner();
  49021. if (owner != 0)
  49022. owner->updateOrder();
  49023. }
  49024. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49025. {
  49026. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49027. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49028. }
  49029. class MDITabbedComponentInternal : public TabbedComponent
  49030. {
  49031. public:
  49032. MDITabbedComponentInternal()
  49033. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49034. {
  49035. }
  49036. ~MDITabbedComponentInternal()
  49037. {
  49038. }
  49039. void currentTabChanged (int, const String&)
  49040. {
  49041. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49042. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49043. if (owner != 0)
  49044. owner->updateOrder();
  49045. }
  49046. };
  49047. MultiDocumentPanel::MultiDocumentPanel()
  49048. : mode (MaximisedWindowsWithTabs),
  49049. tabComponent (0),
  49050. backgroundColour (Colours::lightblue),
  49051. maximumNumDocuments (0),
  49052. numDocsBeforeTabsUsed (0)
  49053. {
  49054. setOpaque (true);
  49055. }
  49056. MultiDocumentPanel::~MultiDocumentPanel()
  49057. {
  49058. closeAllDocuments (false);
  49059. }
  49060. static bool shouldDeleteComp (Component* const c)
  49061. {
  49062. return c->getProperties() ["mdiDocumentDelete_"];
  49063. }
  49064. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49065. {
  49066. while (components.size() > 0)
  49067. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49068. return false;
  49069. return true;
  49070. }
  49071. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49072. {
  49073. return new MultiDocumentPanelWindow (backgroundColour);
  49074. }
  49075. void MultiDocumentPanel::addWindow (Component* component)
  49076. {
  49077. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49078. dw->setResizable (true, false);
  49079. dw->setContentComponent (component, false, true);
  49080. dw->setName (component->getName());
  49081. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49082. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49083. int x = 4;
  49084. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49085. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49086. x += 16;
  49087. dw->setTopLeftPosition (x, x);
  49088. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49089. if (pos.toString().isNotEmpty())
  49090. dw->restoreWindowStateFromString (pos.toString());
  49091. addAndMakeVisible (dw);
  49092. dw->toFront (true);
  49093. }
  49094. bool MultiDocumentPanel::addDocument (Component* const component,
  49095. const Colour& docColour,
  49096. const bool deleteWhenRemoved)
  49097. {
  49098. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49099. // with a frame-within-a-frame! Just pass in the bare content component.
  49100. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49101. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49102. return false;
  49103. components.add (component);
  49104. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49105. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49106. component->addComponentListener (this);
  49107. if (mode == FloatingWindows)
  49108. {
  49109. if (isFullscreenWhenOneDocument())
  49110. {
  49111. if (components.size() == 1)
  49112. {
  49113. addAndMakeVisible (component);
  49114. }
  49115. else
  49116. {
  49117. if (components.size() == 2)
  49118. addWindow (components.getFirst());
  49119. addWindow (component);
  49120. }
  49121. }
  49122. else
  49123. {
  49124. addWindow (component);
  49125. }
  49126. }
  49127. else
  49128. {
  49129. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49130. {
  49131. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49132. Array <Component*> temp (components);
  49133. for (int i = 0; i < temp.size(); ++i)
  49134. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49135. resized();
  49136. }
  49137. else
  49138. {
  49139. if (tabComponent != 0)
  49140. tabComponent->addTab (component->getName(), docColour, component, false);
  49141. else
  49142. addAndMakeVisible (component);
  49143. }
  49144. setActiveDocument (component);
  49145. }
  49146. resized();
  49147. activeDocumentChanged();
  49148. return true;
  49149. }
  49150. bool MultiDocumentPanel::closeDocument (Component* component,
  49151. const bool checkItsOkToCloseFirst)
  49152. {
  49153. if (components.contains (component))
  49154. {
  49155. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49156. return false;
  49157. component->removeComponentListener (this);
  49158. const bool shouldDelete = shouldDeleteComp (component);
  49159. component->getProperties().remove ("mdiDocumentDelete_");
  49160. component->getProperties().remove ("mdiDocumentBkg_");
  49161. if (mode == FloatingWindows)
  49162. {
  49163. for (int i = getNumChildComponents(); --i >= 0;)
  49164. {
  49165. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49166. if (dw != 0 && dw->getContentComponent() == component)
  49167. {
  49168. dw->setContentComponent (0, false);
  49169. delete dw;
  49170. break;
  49171. }
  49172. }
  49173. if (shouldDelete)
  49174. delete component;
  49175. components.removeValue (component);
  49176. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49177. {
  49178. for (int i = getNumChildComponents(); --i >= 0;)
  49179. {
  49180. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49181. if (dw != 0)
  49182. {
  49183. dw->setContentComponent (0, false);
  49184. delete dw;
  49185. }
  49186. }
  49187. addAndMakeVisible (components.getFirst());
  49188. }
  49189. }
  49190. else
  49191. {
  49192. jassert (components.indexOf (component) >= 0);
  49193. if (tabComponent != 0)
  49194. {
  49195. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49196. if (tabComponent->getTabContentComponent (i) == component)
  49197. tabComponent->removeTab (i);
  49198. }
  49199. else
  49200. {
  49201. removeChildComponent (component);
  49202. }
  49203. if (shouldDelete)
  49204. delete component;
  49205. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49206. deleteAndZero (tabComponent);
  49207. components.removeValue (component);
  49208. if (components.size() > 0 && tabComponent == 0)
  49209. addAndMakeVisible (components.getFirst());
  49210. }
  49211. resized();
  49212. activeDocumentChanged();
  49213. }
  49214. else
  49215. {
  49216. jassertfalse;
  49217. }
  49218. return true;
  49219. }
  49220. int MultiDocumentPanel::getNumDocuments() const throw()
  49221. {
  49222. return components.size();
  49223. }
  49224. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49225. {
  49226. return components [index];
  49227. }
  49228. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49229. {
  49230. if (mode == FloatingWindows)
  49231. {
  49232. for (int i = getNumChildComponents(); --i >= 0;)
  49233. {
  49234. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49235. if (dw != 0 && dw->isActiveWindow())
  49236. return dw->getContentComponent();
  49237. }
  49238. }
  49239. return components.getLast();
  49240. }
  49241. void MultiDocumentPanel::setActiveDocument (Component* component)
  49242. {
  49243. if (mode == FloatingWindows)
  49244. {
  49245. component = getContainerComp (component);
  49246. if (component != 0)
  49247. component->toFront (true);
  49248. }
  49249. else if (tabComponent != 0)
  49250. {
  49251. jassert (components.indexOf (component) >= 0);
  49252. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49253. {
  49254. if (tabComponent->getTabContentComponent (i) == component)
  49255. {
  49256. tabComponent->setCurrentTabIndex (i);
  49257. break;
  49258. }
  49259. }
  49260. }
  49261. else
  49262. {
  49263. component->grabKeyboardFocus();
  49264. }
  49265. }
  49266. void MultiDocumentPanel::activeDocumentChanged()
  49267. {
  49268. }
  49269. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49270. {
  49271. maximumNumDocuments = newNumber;
  49272. }
  49273. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49274. {
  49275. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49276. }
  49277. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49278. {
  49279. return numDocsBeforeTabsUsed != 0;
  49280. }
  49281. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49282. {
  49283. if (mode != newLayoutMode)
  49284. {
  49285. mode = newLayoutMode;
  49286. if (mode == FloatingWindows)
  49287. {
  49288. deleteAndZero (tabComponent);
  49289. }
  49290. else
  49291. {
  49292. for (int i = getNumChildComponents(); --i >= 0;)
  49293. {
  49294. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49295. if (dw != 0)
  49296. {
  49297. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49298. dw->setContentComponent (0, false);
  49299. delete dw;
  49300. }
  49301. }
  49302. }
  49303. resized();
  49304. const Array <Component*> tempComps (components);
  49305. components.clear();
  49306. for (int i = 0; i < tempComps.size(); ++i)
  49307. {
  49308. Component* const c = tempComps.getUnchecked(i);
  49309. addDocument (c,
  49310. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49311. shouldDeleteComp (c));
  49312. }
  49313. }
  49314. }
  49315. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49316. {
  49317. if (backgroundColour != newBackgroundColour)
  49318. {
  49319. backgroundColour = newBackgroundColour;
  49320. setOpaque (newBackgroundColour.isOpaque());
  49321. repaint();
  49322. }
  49323. }
  49324. void MultiDocumentPanel::paint (Graphics& g)
  49325. {
  49326. g.fillAll (backgroundColour);
  49327. }
  49328. void MultiDocumentPanel::resized()
  49329. {
  49330. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49331. {
  49332. for (int i = getNumChildComponents(); --i >= 0;)
  49333. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  49334. }
  49335. setWantsKeyboardFocus (components.size() == 0);
  49336. }
  49337. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49338. {
  49339. if (mode == FloatingWindows)
  49340. {
  49341. for (int i = 0; i < getNumChildComponents(); ++i)
  49342. {
  49343. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49344. if (dw != 0 && dw->getContentComponent() == c)
  49345. {
  49346. c = dw;
  49347. break;
  49348. }
  49349. }
  49350. }
  49351. return c;
  49352. }
  49353. void MultiDocumentPanel::componentNameChanged (Component&)
  49354. {
  49355. if (mode == FloatingWindows)
  49356. {
  49357. for (int i = 0; i < getNumChildComponents(); ++i)
  49358. {
  49359. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49360. if (dw != 0)
  49361. dw->setName (dw->getContentComponent()->getName());
  49362. }
  49363. }
  49364. else if (tabComponent != 0)
  49365. {
  49366. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49367. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49368. }
  49369. }
  49370. void MultiDocumentPanel::updateOrder()
  49371. {
  49372. const Array <Component*> oldList (components);
  49373. if (mode == FloatingWindows)
  49374. {
  49375. components.clear();
  49376. for (int i = 0; i < getNumChildComponents(); ++i)
  49377. {
  49378. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49379. if (dw != 0)
  49380. components.add (dw->getContentComponent());
  49381. }
  49382. }
  49383. else
  49384. {
  49385. if (tabComponent != 0)
  49386. {
  49387. Component* const current = tabComponent->getCurrentContentComponent();
  49388. if (current != 0)
  49389. {
  49390. components.removeValue (current);
  49391. components.add (current);
  49392. }
  49393. }
  49394. }
  49395. if (components != oldList)
  49396. activeDocumentChanged();
  49397. }
  49398. END_JUCE_NAMESPACE
  49399. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49400. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49401. BEGIN_JUCE_NAMESPACE
  49402. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49403. : zone (zoneFlags)
  49404. {
  49405. }
  49406. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49407. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49408. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49409. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49410. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49411. const BorderSize& border,
  49412. const Point<int>& position)
  49413. {
  49414. int z = 0;
  49415. if (totalSize.contains (position)
  49416. && ! border.subtractedFrom (totalSize).contains (position))
  49417. {
  49418. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49419. if (position.getX() < jmax (border.getLeft(), minW))
  49420. z |= left;
  49421. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49422. z |= right;
  49423. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49424. if (position.getY() < jmax (border.getTop(), minH))
  49425. z |= top;
  49426. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49427. z |= bottom;
  49428. }
  49429. return Zone (z);
  49430. }
  49431. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49432. {
  49433. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49434. switch (zone)
  49435. {
  49436. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49437. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49438. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49439. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49440. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49441. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49442. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49443. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49444. default: break;
  49445. }
  49446. return mc;
  49447. }
  49448. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49449. {
  49450. if (isDraggingWholeObject())
  49451. return b + offset;
  49452. if (isDraggingLeftEdge())
  49453. b.setLeft (b.getX() + offset.getX());
  49454. if (isDraggingRightEdge())
  49455. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49456. if (isDraggingTopEdge())
  49457. b.setTop (b.getY() + offset.getY());
  49458. if (isDraggingBottomEdge())
  49459. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49460. return b;
  49461. }
  49462. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49463. {
  49464. if (isDraggingWholeObject())
  49465. return b + offset;
  49466. if (isDraggingLeftEdge())
  49467. b.setLeft (b.getX() + offset.getX());
  49468. if (isDraggingRightEdge())
  49469. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49470. if (isDraggingTopEdge())
  49471. b.setTop (b.getY() + offset.getY());
  49472. if (isDraggingBottomEdge())
  49473. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49474. return b;
  49475. }
  49476. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49477. ComponentBoundsConstrainer* const constrainer_)
  49478. : component (componentToResize),
  49479. constrainer (constrainer_),
  49480. borderSize (5),
  49481. mouseZone (0)
  49482. {
  49483. }
  49484. ResizableBorderComponent::~ResizableBorderComponent()
  49485. {
  49486. }
  49487. void ResizableBorderComponent::paint (Graphics& g)
  49488. {
  49489. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49490. }
  49491. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49492. {
  49493. updateMouseZone (e);
  49494. }
  49495. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49496. {
  49497. updateMouseZone (e);
  49498. }
  49499. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49500. {
  49501. if (component == 0)
  49502. {
  49503. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49504. return;
  49505. }
  49506. updateMouseZone (e);
  49507. originalBounds = component->getBounds();
  49508. if (constrainer != 0)
  49509. constrainer->resizeStart();
  49510. }
  49511. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49512. {
  49513. if (component == 0)
  49514. {
  49515. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49516. return;
  49517. }
  49518. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49519. if (constrainer != 0)
  49520. constrainer->setBoundsForComponent (component, bounds,
  49521. mouseZone.isDraggingTopEdge(),
  49522. mouseZone.isDraggingLeftEdge(),
  49523. mouseZone.isDraggingBottomEdge(),
  49524. mouseZone.isDraggingRightEdge());
  49525. else
  49526. component->setBounds (bounds);
  49527. }
  49528. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49529. {
  49530. if (constrainer != 0)
  49531. constrainer->resizeEnd();
  49532. }
  49533. bool ResizableBorderComponent::hitTest (int x, int y)
  49534. {
  49535. return x < borderSize.getLeft()
  49536. || x >= getWidth() - borderSize.getRight()
  49537. || y < borderSize.getTop()
  49538. || y >= getHeight() - borderSize.getBottom();
  49539. }
  49540. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49541. {
  49542. if (borderSize != newBorderSize)
  49543. {
  49544. borderSize = newBorderSize;
  49545. repaint();
  49546. }
  49547. }
  49548. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49549. {
  49550. return borderSize;
  49551. }
  49552. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49553. {
  49554. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49555. if (mouseZone != newZone)
  49556. {
  49557. mouseZone = newZone;
  49558. setMouseCursor (newZone.getMouseCursor());
  49559. }
  49560. }
  49561. END_JUCE_NAMESPACE
  49562. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49563. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49564. BEGIN_JUCE_NAMESPACE
  49565. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49566. ComponentBoundsConstrainer* const constrainer_)
  49567. : component (componentToResize),
  49568. constrainer (constrainer_)
  49569. {
  49570. setRepaintsOnMouseActivity (true);
  49571. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49572. }
  49573. ResizableCornerComponent::~ResizableCornerComponent()
  49574. {
  49575. }
  49576. void ResizableCornerComponent::paint (Graphics& g)
  49577. {
  49578. getLookAndFeel()
  49579. .drawCornerResizer (g, getWidth(), getHeight(),
  49580. isMouseOverOrDragging(),
  49581. isMouseButtonDown());
  49582. }
  49583. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49584. {
  49585. if (component == 0)
  49586. {
  49587. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49588. return;
  49589. }
  49590. originalBounds = component->getBounds();
  49591. if (constrainer != 0)
  49592. constrainer->resizeStart();
  49593. }
  49594. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49595. {
  49596. if (component == 0)
  49597. {
  49598. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49599. return;
  49600. }
  49601. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49602. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49603. if (constrainer != 0)
  49604. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49605. else
  49606. component->setBounds (r);
  49607. }
  49608. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49609. {
  49610. if (constrainer != 0)
  49611. constrainer->resizeStart();
  49612. }
  49613. bool ResizableCornerComponent::hitTest (int x, int y)
  49614. {
  49615. if (getWidth() <= 0)
  49616. return false;
  49617. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49618. return y >= yAtX - getHeight() / 4;
  49619. }
  49620. END_JUCE_NAMESPACE
  49621. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49622. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49623. BEGIN_JUCE_NAMESPACE
  49624. class ScrollBar::ScrollbarButton : public Button
  49625. {
  49626. public:
  49627. int direction;
  49628. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49629. : Button (String::empty),
  49630. direction (direction_),
  49631. owner (owner_)
  49632. {
  49633. setWantsKeyboardFocus (false);
  49634. }
  49635. ~ScrollbarButton()
  49636. {
  49637. }
  49638. void paintButton (Graphics& g, bool over, bool down)
  49639. {
  49640. getLookAndFeel()
  49641. .drawScrollbarButton (g, owner,
  49642. getWidth(), getHeight(),
  49643. direction,
  49644. owner.isVertical(),
  49645. over, down);
  49646. }
  49647. void clicked()
  49648. {
  49649. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49650. }
  49651. juce_UseDebuggingNewOperator
  49652. private:
  49653. ScrollBar& owner;
  49654. ScrollbarButton (const ScrollbarButton&);
  49655. ScrollbarButton& operator= (const ScrollbarButton&);
  49656. };
  49657. ScrollBar::ScrollBar (const bool vertical_,
  49658. const bool buttonsAreVisible)
  49659. : totalRange (0.0, 1.0),
  49660. visibleRange (0.0, 0.1),
  49661. singleStepSize (0.1),
  49662. thumbAreaStart (0),
  49663. thumbAreaSize (0),
  49664. thumbStart (0),
  49665. thumbSize (0),
  49666. initialDelayInMillisecs (100),
  49667. repeatDelayInMillisecs (50),
  49668. minimumDelayInMillisecs (10),
  49669. vertical (vertical_),
  49670. isDraggingThumb (false),
  49671. autohides (true),
  49672. upButton (0),
  49673. downButton (0)
  49674. {
  49675. setButtonVisibility (buttonsAreVisible);
  49676. setRepaintsOnMouseActivity (true);
  49677. setFocusContainer (true);
  49678. }
  49679. ScrollBar::~ScrollBar()
  49680. {
  49681. deleteAllChildren();
  49682. }
  49683. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49684. {
  49685. if (totalRange != newRangeLimit)
  49686. {
  49687. totalRange = newRangeLimit;
  49688. setCurrentRange (visibleRange);
  49689. updateThumbPosition();
  49690. }
  49691. }
  49692. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49693. {
  49694. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49695. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49696. }
  49697. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49698. {
  49699. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49700. if (visibleRange != constrainedRange)
  49701. {
  49702. visibleRange = constrainedRange;
  49703. updateThumbPosition();
  49704. triggerAsyncUpdate();
  49705. }
  49706. }
  49707. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49708. {
  49709. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49710. }
  49711. void ScrollBar::setCurrentRangeStart (const double newStart)
  49712. {
  49713. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49714. }
  49715. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49716. {
  49717. singleStepSize = newSingleStepSize;
  49718. }
  49719. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49720. {
  49721. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49722. }
  49723. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49724. {
  49725. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49726. }
  49727. void ScrollBar::scrollToTop()
  49728. {
  49729. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49730. }
  49731. void ScrollBar::scrollToBottom()
  49732. {
  49733. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49734. }
  49735. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49736. const int repeatDelayInMillisecs_,
  49737. const int minimumDelayInMillisecs_)
  49738. {
  49739. initialDelayInMillisecs = initialDelayInMillisecs_;
  49740. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49741. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49742. if (upButton != 0)
  49743. {
  49744. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49745. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49746. }
  49747. }
  49748. void ScrollBar::addListener (ScrollBarListener* const listener)
  49749. {
  49750. listeners.add (listener);
  49751. }
  49752. void ScrollBar::removeListener (ScrollBarListener* const listener)
  49753. {
  49754. listeners.remove (listener);
  49755. }
  49756. void ScrollBar::handleAsyncUpdate()
  49757. {
  49758. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49759. listeners.call (&ScrollBarListener::scrollBarMoved, this, start);
  49760. }
  49761. void ScrollBar::updateThumbPosition()
  49762. {
  49763. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49764. : thumbAreaSize);
  49765. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49766. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49767. if (newThumbSize > thumbAreaSize)
  49768. newThumbSize = thumbAreaSize;
  49769. int newThumbStart = thumbAreaStart;
  49770. if (totalRange.getLength() > visibleRange.getLength())
  49771. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49772. / (totalRange.getLength() - visibleRange.getLength()));
  49773. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49774. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49775. {
  49776. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49777. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49778. if (vertical)
  49779. repaint (0, repaintStart, getWidth(), repaintSize);
  49780. else
  49781. repaint (repaintStart, 0, repaintSize, getHeight());
  49782. thumbStart = newThumbStart;
  49783. thumbSize = newThumbSize;
  49784. }
  49785. }
  49786. void ScrollBar::setOrientation (const bool shouldBeVertical)
  49787. {
  49788. if (vertical != shouldBeVertical)
  49789. {
  49790. vertical = shouldBeVertical;
  49791. if (upButton != 0)
  49792. {
  49793. upButton->direction = vertical ? 0 : 3;
  49794. downButton->direction = vertical ? 2 : 1;
  49795. }
  49796. updateThumbPosition();
  49797. }
  49798. }
  49799. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  49800. {
  49801. delete upButton;
  49802. upButton = 0;
  49803. delete downButton;
  49804. downButton = 0;
  49805. if (buttonsAreVisible)
  49806. {
  49807. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  49808. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  49809. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49810. }
  49811. updateThumbPosition();
  49812. }
  49813. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  49814. {
  49815. autohides = shouldHideWhenFullRange;
  49816. updateThumbPosition();
  49817. }
  49818. bool ScrollBar::autoHides() const throw()
  49819. {
  49820. return autohides;
  49821. }
  49822. void ScrollBar::paint (Graphics& g)
  49823. {
  49824. if (thumbAreaSize > 0)
  49825. {
  49826. LookAndFeel& lf = getLookAndFeel();
  49827. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  49828. ? thumbSize : 0;
  49829. if (vertical)
  49830. {
  49831. lf.drawScrollbar (g, *this,
  49832. 0, thumbAreaStart,
  49833. getWidth(), thumbAreaSize,
  49834. vertical,
  49835. thumbStart, thumb,
  49836. isMouseOver(), isMouseButtonDown());
  49837. }
  49838. else
  49839. {
  49840. lf.drawScrollbar (g, *this,
  49841. thumbAreaStart, 0,
  49842. thumbAreaSize, getHeight(),
  49843. vertical,
  49844. thumbStart, thumb,
  49845. isMouseOver(), isMouseButtonDown());
  49846. }
  49847. }
  49848. }
  49849. void ScrollBar::lookAndFeelChanged()
  49850. {
  49851. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  49852. }
  49853. void ScrollBar::resized()
  49854. {
  49855. const int length = ((vertical) ? getHeight() : getWidth());
  49856. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  49857. : 0;
  49858. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49859. {
  49860. thumbAreaStart = length >> 1;
  49861. thumbAreaSize = 0;
  49862. }
  49863. else
  49864. {
  49865. thumbAreaStart = buttonSize;
  49866. thumbAreaSize = length - (buttonSize << 1);
  49867. }
  49868. if (upButton != 0)
  49869. {
  49870. if (vertical)
  49871. {
  49872. upButton->setBounds (0, 0, getWidth(), buttonSize);
  49873. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  49874. }
  49875. else
  49876. {
  49877. upButton->setBounds (0, 0, buttonSize, getHeight());
  49878. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  49879. }
  49880. }
  49881. updateThumbPosition();
  49882. }
  49883. void ScrollBar::mouseDown (const MouseEvent& e)
  49884. {
  49885. isDraggingThumb = false;
  49886. lastMousePos = vertical ? e.y : e.x;
  49887. dragStartMousePos = lastMousePos;
  49888. dragStartRange = visibleRange.getStart();
  49889. if (dragStartMousePos < thumbStart)
  49890. {
  49891. moveScrollbarInPages (-1);
  49892. startTimer (400);
  49893. }
  49894. else if (dragStartMousePos >= thumbStart + thumbSize)
  49895. {
  49896. moveScrollbarInPages (1);
  49897. startTimer (400);
  49898. }
  49899. else
  49900. {
  49901. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49902. && (thumbAreaSize > thumbSize);
  49903. }
  49904. }
  49905. void ScrollBar::mouseDrag (const MouseEvent& e)
  49906. {
  49907. if (isDraggingThumb)
  49908. {
  49909. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  49910. setCurrentRangeStart (dragStartRange
  49911. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  49912. / (thumbAreaSize - thumbSize));
  49913. }
  49914. else
  49915. {
  49916. lastMousePos = (vertical) ? e.y : e.x;
  49917. }
  49918. }
  49919. void ScrollBar::mouseUp (const MouseEvent&)
  49920. {
  49921. isDraggingThumb = false;
  49922. stopTimer();
  49923. repaint();
  49924. }
  49925. void ScrollBar::mouseWheelMove (const MouseEvent&,
  49926. float wheelIncrementX,
  49927. float wheelIncrementY)
  49928. {
  49929. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  49930. if (increment < 0)
  49931. increment = jmin (increment * 10.0f, -1.0f);
  49932. else if (increment > 0)
  49933. increment = jmax (increment * 10.0f, 1.0f);
  49934. setCurrentRange (visibleRange - singleStepSize * increment);
  49935. }
  49936. void ScrollBar::timerCallback()
  49937. {
  49938. if (isMouseButtonDown())
  49939. {
  49940. startTimer (40);
  49941. if (lastMousePos < thumbStart)
  49942. setCurrentRange (visibleRange - visibleRange.getLength());
  49943. else if (lastMousePos > thumbStart + thumbSize)
  49944. setCurrentRangeStart (visibleRange.getEnd());
  49945. }
  49946. else
  49947. {
  49948. stopTimer();
  49949. }
  49950. }
  49951. bool ScrollBar::keyPressed (const KeyPress& key)
  49952. {
  49953. if (! isVisible())
  49954. return false;
  49955. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  49956. moveScrollbarInSteps (-1);
  49957. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  49958. moveScrollbarInSteps (1);
  49959. else if (key.isKeyCode (KeyPress::pageUpKey))
  49960. moveScrollbarInPages (-1);
  49961. else if (key.isKeyCode (KeyPress::pageDownKey))
  49962. moveScrollbarInPages (1);
  49963. else if (key.isKeyCode (KeyPress::homeKey))
  49964. scrollToTop();
  49965. else if (key.isKeyCode (KeyPress::endKey))
  49966. scrollToBottom();
  49967. else
  49968. return false;
  49969. return true;
  49970. }
  49971. END_JUCE_NAMESPACE
  49972. /*** End of inlined file: juce_ScrollBar.cpp ***/
  49973. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  49974. BEGIN_JUCE_NAMESPACE
  49975. StretchableLayoutManager::StretchableLayoutManager()
  49976. : totalSize (0)
  49977. {
  49978. }
  49979. StretchableLayoutManager::~StretchableLayoutManager()
  49980. {
  49981. }
  49982. void StretchableLayoutManager::clearAllItems()
  49983. {
  49984. items.clear();
  49985. totalSize = 0;
  49986. }
  49987. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  49988. const double minimumSize,
  49989. const double maximumSize,
  49990. const double preferredSize)
  49991. {
  49992. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  49993. if (layout == 0)
  49994. {
  49995. layout = new ItemLayoutProperties();
  49996. layout->itemIndex = itemIndex;
  49997. int i;
  49998. for (i = 0; i < items.size(); ++i)
  49999. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50000. break;
  50001. items.insert (i, layout);
  50002. }
  50003. layout->minSize = minimumSize;
  50004. layout->maxSize = maximumSize;
  50005. layout->preferredSize = preferredSize;
  50006. layout->currentSize = 0;
  50007. }
  50008. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50009. double& minimumSize,
  50010. double& maximumSize,
  50011. double& preferredSize) const
  50012. {
  50013. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50014. if (layout != 0)
  50015. {
  50016. minimumSize = layout->minSize;
  50017. maximumSize = layout->maxSize;
  50018. preferredSize = layout->preferredSize;
  50019. return true;
  50020. }
  50021. return false;
  50022. }
  50023. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50024. {
  50025. totalSize = newTotalSize;
  50026. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50027. }
  50028. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50029. {
  50030. int pos = 0;
  50031. for (int i = 0; i < itemIndex; ++i)
  50032. {
  50033. const ItemLayoutProperties* const layout = getInfoFor (i);
  50034. if (layout != 0)
  50035. pos += layout->currentSize;
  50036. }
  50037. return pos;
  50038. }
  50039. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50040. {
  50041. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50042. if (layout != 0)
  50043. return layout->currentSize;
  50044. return 0;
  50045. }
  50046. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50047. {
  50048. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50049. if (layout != 0)
  50050. return -layout->currentSize / (double) totalSize;
  50051. return 0;
  50052. }
  50053. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50054. int newPosition)
  50055. {
  50056. for (int i = items.size(); --i >= 0;)
  50057. {
  50058. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50059. if (layout->itemIndex == itemIndex)
  50060. {
  50061. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50062. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50063. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50064. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50065. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50066. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50067. endPos += layout->currentSize;
  50068. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50069. updatePrefSizesToMatchCurrentPositions();
  50070. break;
  50071. }
  50072. }
  50073. }
  50074. void StretchableLayoutManager::layOutComponents (Component** const components,
  50075. int numComponents,
  50076. int x, int y, int w, int h,
  50077. const bool vertically,
  50078. const bool resizeOtherDimension)
  50079. {
  50080. setTotalSize (vertically ? h : w);
  50081. int pos = vertically ? y : x;
  50082. for (int i = 0; i < numComponents; ++i)
  50083. {
  50084. const ItemLayoutProperties* const layout = getInfoFor (i);
  50085. if (layout != 0)
  50086. {
  50087. Component* const c = components[i];
  50088. if (c != 0)
  50089. {
  50090. if (i == numComponents - 1)
  50091. {
  50092. // if it's the last item, crop it to exactly fit the available space..
  50093. if (resizeOtherDimension)
  50094. {
  50095. if (vertically)
  50096. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50097. else
  50098. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50099. }
  50100. else
  50101. {
  50102. if (vertically)
  50103. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50104. else
  50105. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50106. }
  50107. }
  50108. else
  50109. {
  50110. if (resizeOtherDimension)
  50111. {
  50112. if (vertically)
  50113. c->setBounds (x, pos, w, layout->currentSize);
  50114. else
  50115. c->setBounds (pos, y, layout->currentSize, h);
  50116. }
  50117. else
  50118. {
  50119. if (vertically)
  50120. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50121. else
  50122. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50123. }
  50124. }
  50125. }
  50126. pos += layout->currentSize;
  50127. }
  50128. }
  50129. }
  50130. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50131. {
  50132. for (int i = items.size(); --i >= 0;)
  50133. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50134. return items.getUnchecked(i);
  50135. return 0;
  50136. }
  50137. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50138. const int endIndex,
  50139. const int availableSpace,
  50140. int startPos)
  50141. {
  50142. // calculate the total sizes
  50143. int i;
  50144. double totalIdealSize = 0.0;
  50145. int totalMinimums = 0;
  50146. for (i = startIndex; i < endIndex; ++i)
  50147. {
  50148. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50149. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50150. totalMinimums += layout->currentSize;
  50151. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  50152. }
  50153. if (totalIdealSize <= 0)
  50154. totalIdealSize = 1.0;
  50155. // now calc the best sizes..
  50156. int extraSpace = availableSpace - totalMinimums;
  50157. while (extraSpace > 0)
  50158. {
  50159. int numWantingMoreSpace = 0;
  50160. int numHavingTakenExtraSpace = 0;
  50161. // first figure out how many comps want a slice of the extra space..
  50162. for (i = startIndex; i < endIndex; ++i)
  50163. {
  50164. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50165. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50166. const int bestSize = jlimit (layout->currentSize,
  50167. jmax (layout->currentSize,
  50168. sizeToRealSize (layout->maxSize, totalSize)),
  50169. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50170. if (bestSize > layout->currentSize)
  50171. ++numWantingMoreSpace;
  50172. }
  50173. // ..share out the extra space..
  50174. for (i = startIndex; i < endIndex; ++i)
  50175. {
  50176. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50177. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50178. int bestSize = jlimit (layout->currentSize,
  50179. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50180. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50181. const int extraWanted = bestSize - layout->currentSize;
  50182. if (extraWanted > 0)
  50183. {
  50184. const int extraAllowed = jmin (extraWanted,
  50185. extraSpace / jmax (1, numWantingMoreSpace));
  50186. if (extraAllowed > 0)
  50187. {
  50188. ++numHavingTakenExtraSpace;
  50189. --numWantingMoreSpace;
  50190. layout->currentSize += extraAllowed;
  50191. extraSpace -= extraAllowed;
  50192. }
  50193. }
  50194. }
  50195. if (numHavingTakenExtraSpace <= 0)
  50196. break;
  50197. }
  50198. // ..and calculate the end position
  50199. for (i = startIndex; i < endIndex; ++i)
  50200. {
  50201. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50202. startPos += layout->currentSize;
  50203. }
  50204. return startPos;
  50205. }
  50206. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50207. const int endIndex) const
  50208. {
  50209. int totalMinimums = 0;
  50210. for (int i = startIndex; i < endIndex; ++i)
  50211. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50212. return totalMinimums;
  50213. }
  50214. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50215. {
  50216. int totalMaximums = 0;
  50217. for (int i = startIndex; i < endIndex; ++i)
  50218. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50219. return totalMaximums;
  50220. }
  50221. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50222. {
  50223. for (int i = 0; i < items.size(); ++i)
  50224. {
  50225. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50226. layout->preferredSize
  50227. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50228. : getItemCurrentAbsoluteSize (i);
  50229. }
  50230. }
  50231. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50232. {
  50233. if (size < 0)
  50234. size *= -totalSpace;
  50235. return roundToInt (size);
  50236. }
  50237. END_JUCE_NAMESPACE
  50238. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50239. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50240. BEGIN_JUCE_NAMESPACE
  50241. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50242. const int itemIndex_,
  50243. const bool isVertical_)
  50244. : layout (layout_),
  50245. itemIndex (itemIndex_),
  50246. isVertical (isVertical_)
  50247. {
  50248. setRepaintsOnMouseActivity (true);
  50249. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50250. : MouseCursor::UpDownResizeCursor));
  50251. }
  50252. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50253. {
  50254. }
  50255. void StretchableLayoutResizerBar::paint (Graphics& g)
  50256. {
  50257. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50258. getWidth(), getHeight(),
  50259. isVertical,
  50260. isMouseOver(),
  50261. isMouseButtonDown());
  50262. }
  50263. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50264. {
  50265. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50266. }
  50267. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50268. {
  50269. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50270. : e.getDistanceFromDragStartY());
  50271. layout->setItemPosition (itemIndex, desiredPos);
  50272. hasBeenMoved();
  50273. }
  50274. void StretchableLayoutResizerBar::hasBeenMoved()
  50275. {
  50276. if (getParentComponent() != 0)
  50277. getParentComponent()->resized();
  50278. }
  50279. END_JUCE_NAMESPACE
  50280. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50281. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50282. BEGIN_JUCE_NAMESPACE
  50283. StretchableObjectResizer::StretchableObjectResizer()
  50284. {
  50285. }
  50286. StretchableObjectResizer::~StretchableObjectResizer()
  50287. {
  50288. }
  50289. void StretchableObjectResizer::addItem (const double size,
  50290. const double minSize, const double maxSize,
  50291. const int order)
  50292. {
  50293. // the order must be >= 0 but less than the maximum integer value.
  50294. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50295. Item* const item = new Item();
  50296. item->size = size;
  50297. item->minSize = minSize;
  50298. item->maxSize = maxSize;
  50299. item->order = order;
  50300. items.add (item);
  50301. }
  50302. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50303. {
  50304. const Item* const it = items [index];
  50305. return it != 0 ? it->size : 0;
  50306. }
  50307. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50308. {
  50309. int order = 0;
  50310. for (;;)
  50311. {
  50312. double currentSize = 0;
  50313. double minSize = 0;
  50314. double maxSize = 0;
  50315. int nextHighestOrder = std::numeric_limits<int>::max();
  50316. for (int i = 0; i < items.size(); ++i)
  50317. {
  50318. const Item* const it = items.getUnchecked(i);
  50319. currentSize += it->size;
  50320. if (it->order <= order)
  50321. {
  50322. minSize += it->minSize;
  50323. maxSize += it->maxSize;
  50324. }
  50325. else
  50326. {
  50327. minSize += it->size;
  50328. maxSize += it->size;
  50329. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50330. }
  50331. }
  50332. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50333. if (thisIterationTarget >= currentSize)
  50334. {
  50335. const double availableExtraSpace = maxSize - currentSize;
  50336. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50337. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50338. for (int i = 0; i < items.size(); ++i)
  50339. {
  50340. Item* const it = items.getUnchecked(i);
  50341. if (it->order <= order)
  50342. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50343. }
  50344. }
  50345. else
  50346. {
  50347. const double amountOfSlack = currentSize - minSize;
  50348. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50349. const double scale = targetAmountOfSlack / amountOfSlack;
  50350. for (int i = 0; i < items.size(); ++i)
  50351. {
  50352. Item* const it = items.getUnchecked(i);
  50353. if (it->order <= order)
  50354. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50355. }
  50356. }
  50357. if (nextHighestOrder < std::numeric_limits<int>::max())
  50358. order = nextHighestOrder;
  50359. else
  50360. break;
  50361. }
  50362. }
  50363. END_JUCE_NAMESPACE
  50364. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50365. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50366. BEGIN_JUCE_NAMESPACE
  50367. TabBarButton::TabBarButton (const String& name,
  50368. TabbedButtonBar* const owner_,
  50369. const int index)
  50370. : Button (name),
  50371. owner (owner_),
  50372. tabIndex (index),
  50373. overlapPixels (0)
  50374. {
  50375. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50376. setComponentEffect (&shadow);
  50377. setWantsKeyboardFocus (false);
  50378. }
  50379. TabBarButton::~TabBarButton()
  50380. {
  50381. }
  50382. void TabBarButton::paintButton (Graphics& g,
  50383. bool isMouseOverButton,
  50384. bool isButtonDown)
  50385. {
  50386. int x, y, w, h;
  50387. getActiveArea (x, y, w, h);
  50388. g.setOrigin (x, y);
  50389. getLookAndFeel()
  50390. .drawTabButton (g, w, h,
  50391. owner->getTabBackgroundColour (tabIndex),
  50392. tabIndex, getButtonText(), *this,
  50393. owner->getOrientation(),
  50394. isMouseOverButton, isButtonDown,
  50395. getToggleState());
  50396. }
  50397. void TabBarButton::clicked (const ModifierKeys& mods)
  50398. {
  50399. if (mods.isPopupMenu())
  50400. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50401. else
  50402. owner->setCurrentTabIndex (tabIndex);
  50403. }
  50404. bool TabBarButton::hitTest (int mx, int my)
  50405. {
  50406. int x, y, w, h;
  50407. getActiveArea (x, y, w, h);
  50408. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50409. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50410. {
  50411. if (((unsigned int) mx) < (unsigned int) getWidth()
  50412. && my >= y + overlapPixels
  50413. && my < y + h - overlapPixels)
  50414. return true;
  50415. }
  50416. else
  50417. {
  50418. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50419. && ((unsigned int) my) < (unsigned int) getHeight())
  50420. return true;
  50421. }
  50422. Path p;
  50423. getLookAndFeel()
  50424. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50425. owner->getOrientation(),
  50426. false, false, getToggleState());
  50427. return p.contains ((float) (mx - x),
  50428. (float) (my - y));
  50429. }
  50430. int TabBarButton::getBestTabLength (const int depth)
  50431. {
  50432. return jlimit (depth * 2,
  50433. depth * 7,
  50434. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50435. }
  50436. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50437. {
  50438. x = 0;
  50439. y = 0;
  50440. int r = getWidth();
  50441. int b = getHeight();
  50442. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50443. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50444. r -= spaceAroundImage;
  50445. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50446. x += spaceAroundImage;
  50447. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50448. y += spaceAroundImage;
  50449. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50450. b -= spaceAroundImage;
  50451. w = r - x;
  50452. h = b - y;
  50453. }
  50454. class TabAreaBehindFrontButtonComponent : public Component
  50455. {
  50456. public:
  50457. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50458. : owner (owner_)
  50459. {
  50460. setInterceptsMouseClicks (false, false);
  50461. }
  50462. ~TabAreaBehindFrontButtonComponent()
  50463. {
  50464. }
  50465. void paint (Graphics& g)
  50466. {
  50467. getLookAndFeel()
  50468. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50469. *owner, owner->getOrientation());
  50470. }
  50471. void enablementChanged()
  50472. {
  50473. repaint();
  50474. }
  50475. private:
  50476. TabbedButtonBar* const owner;
  50477. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50478. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50479. };
  50480. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50481. : orientation (orientation_),
  50482. currentTabIndex (-1),
  50483. extraTabsButton (0)
  50484. {
  50485. setInterceptsMouseClicks (false, true);
  50486. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50487. setFocusContainer (true);
  50488. }
  50489. TabbedButtonBar::~TabbedButtonBar()
  50490. {
  50491. deleteAllChildren();
  50492. }
  50493. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50494. {
  50495. orientation = newOrientation;
  50496. for (int i = getNumChildComponents(); --i >= 0;)
  50497. getChildComponent (i)->resized();
  50498. resized();
  50499. }
  50500. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50501. {
  50502. return new TabBarButton (name, this, index);
  50503. }
  50504. void TabbedButtonBar::clearTabs()
  50505. {
  50506. tabs.clear();
  50507. tabColours.clear();
  50508. currentTabIndex = -1;
  50509. deleteAndZero (extraTabsButton);
  50510. removeChildComponent (behindFrontTab);
  50511. deleteAllChildren();
  50512. addChildComponent (behindFrontTab);
  50513. setCurrentTabIndex (-1);
  50514. }
  50515. void TabbedButtonBar::addTab (const String& tabName,
  50516. const Colour& tabBackgroundColour,
  50517. int insertIndex)
  50518. {
  50519. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50520. if (tabName.isNotEmpty())
  50521. {
  50522. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50523. insertIndex = tabs.size();
  50524. for (int i = tabs.size(); --i >= insertIndex;)
  50525. {
  50526. TabBarButton* const tb = getTabButton (i);
  50527. if (tb != 0)
  50528. tb->tabIndex++;
  50529. }
  50530. tabs.insert (insertIndex, tabName);
  50531. tabColours.insert (insertIndex, tabBackgroundColour);
  50532. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50533. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50534. addAndMakeVisible (tb, insertIndex);
  50535. resized();
  50536. if (currentTabIndex < 0)
  50537. setCurrentTabIndex (0);
  50538. }
  50539. }
  50540. void TabbedButtonBar::setTabName (const int tabIndex,
  50541. const String& newName)
  50542. {
  50543. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50544. && tabs[tabIndex] != newName)
  50545. {
  50546. tabs.set (tabIndex, newName);
  50547. TabBarButton* const tb = getTabButton (tabIndex);
  50548. if (tb != 0)
  50549. tb->setButtonText (newName);
  50550. resized();
  50551. }
  50552. }
  50553. void TabbedButtonBar::removeTab (const int tabIndex)
  50554. {
  50555. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50556. {
  50557. const int oldTabIndex = currentTabIndex;
  50558. if (currentTabIndex == tabIndex)
  50559. currentTabIndex = -1;
  50560. tabs.remove (tabIndex);
  50561. tabColours.remove (tabIndex);
  50562. delete getTabButton (tabIndex);
  50563. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50564. {
  50565. TabBarButton* const tb = getTabButton (i);
  50566. if (tb != 0)
  50567. tb->tabIndex--;
  50568. }
  50569. resized();
  50570. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50571. }
  50572. }
  50573. void TabbedButtonBar::moveTab (const int currentIndex,
  50574. const int newIndex)
  50575. {
  50576. tabs.move (currentIndex, newIndex);
  50577. tabColours.move (currentIndex, newIndex);
  50578. resized();
  50579. }
  50580. int TabbedButtonBar::getNumTabs() const
  50581. {
  50582. return tabs.size();
  50583. }
  50584. const StringArray TabbedButtonBar::getTabNames() const
  50585. {
  50586. return tabs;
  50587. }
  50588. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50589. {
  50590. if (currentTabIndex != newIndex)
  50591. {
  50592. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50593. newIndex = -1;
  50594. currentTabIndex = newIndex;
  50595. for (int i = 0; i < getNumChildComponents(); ++i)
  50596. {
  50597. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50598. if (tb != 0)
  50599. tb->setToggleState (tb->tabIndex == newIndex, false);
  50600. }
  50601. resized();
  50602. if (sendChangeMessage_)
  50603. sendChangeMessage (this);
  50604. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50605. }
  50606. }
  50607. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50608. {
  50609. for (int i = getNumChildComponents(); --i >= 0;)
  50610. {
  50611. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50612. if (tb != 0 && tb->tabIndex == index)
  50613. return tb;
  50614. }
  50615. return 0;
  50616. }
  50617. void TabbedButtonBar::lookAndFeelChanged()
  50618. {
  50619. deleteAndZero (extraTabsButton);
  50620. resized();
  50621. }
  50622. void TabbedButtonBar::resized()
  50623. {
  50624. const double minimumScale = 0.7;
  50625. int depth = getWidth();
  50626. int length = getHeight();
  50627. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50628. swapVariables (depth, length);
  50629. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50630. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50631. int i, totalLength = overlap;
  50632. int numVisibleButtons = tabs.size();
  50633. for (i = 0; i < getNumChildComponents(); ++i)
  50634. {
  50635. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50636. if (tb != 0)
  50637. {
  50638. totalLength += tb->getBestTabLength (depth) - overlap;
  50639. tb->overlapPixels = overlap / 2;
  50640. }
  50641. }
  50642. double scale = 1.0;
  50643. if (totalLength > length)
  50644. scale = jmax (minimumScale, length / (double) totalLength);
  50645. const bool isTooBig = totalLength * scale > length;
  50646. int tabsButtonPos = 0;
  50647. if (isTooBig)
  50648. {
  50649. if (extraTabsButton == 0)
  50650. {
  50651. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50652. extraTabsButton->addButtonListener (this);
  50653. extraTabsButton->setAlwaysOnTop (true);
  50654. extraTabsButton->setTriggeredOnMouseDown (true);
  50655. }
  50656. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50657. extraTabsButton->setSize (buttonSize, buttonSize);
  50658. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50659. {
  50660. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50661. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50662. }
  50663. else
  50664. {
  50665. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50666. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50667. }
  50668. totalLength = 0;
  50669. for (i = 0; i < tabs.size(); ++i)
  50670. {
  50671. TabBarButton* const tb = getTabButton (i);
  50672. if (tb != 0)
  50673. {
  50674. const int newLength = totalLength + tb->getBestTabLength (depth);
  50675. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50676. {
  50677. totalLength += overlap;
  50678. break;
  50679. }
  50680. numVisibleButtons = i + 1;
  50681. totalLength = newLength - overlap;
  50682. }
  50683. }
  50684. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50685. }
  50686. else
  50687. {
  50688. deleteAndZero (extraTabsButton);
  50689. }
  50690. int pos = 0;
  50691. TabBarButton* frontTab = 0;
  50692. for (i = 0; i < tabs.size(); ++i)
  50693. {
  50694. TabBarButton* const tb = getTabButton (i);
  50695. if (tb != 0)
  50696. {
  50697. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50698. if (i < numVisibleButtons)
  50699. {
  50700. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50701. tb->setBounds (pos, 0, bestLength, getHeight());
  50702. else
  50703. tb->setBounds (0, pos, getWidth(), bestLength);
  50704. tb->toBack();
  50705. if (tb->tabIndex == currentTabIndex)
  50706. frontTab = tb;
  50707. tb->setVisible (true);
  50708. }
  50709. else
  50710. {
  50711. tb->setVisible (false);
  50712. }
  50713. pos += bestLength - overlap;
  50714. }
  50715. }
  50716. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  50717. if (frontTab != 0)
  50718. {
  50719. frontTab->toFront (false);
  50720. behindFrontTab->toBehind (frontTab);
  50721. }
  50722. }
  50723. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50724. {
  50725. return tabColours [tabIndex];
  50726. }
  50727. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50728. {
  50729. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50730. && tabColours [tabIndex] != newColour)
  50731. {
  50732. tabColours.set (tabIndex, newColour);
  50733. repaint();
  50734. }
  50735. }
  50736. void TabbedButtonBar::buttonClicked (Button* button)
  50737. {
  50738. if (extraTabsButton == button)
  50739. {
  50740. PopupMenu m;
  50741. for (int i = 0; i < tabs.size(); ++i)
  50742. {
  50743. TabBarButton* const tb = getTabButton (i);
  50744. if (tb != 0 && ! tb->isVisible())
  50745. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50746. }
  50747. const int res = m.showAt (extraTabsButton);
  50748. if (res != 0)
  50749. setCurrentTabIndex (res - 1);
  50750. }
  50751. }
  50752. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50753. {
  50754. }
  50755. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50756. {
  50757. }
  50758. END_JUCE_NAMESPACE
  50759. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50760. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50761. BEGIN_JUCE_NAMESPACE
  50762. class TabCompButtonBar : public TabbedButtonBar
  50763. {
  50764. public:
  50765. TabCompButtonBar (TabbedComponent* const owner_,
  50766. const TabbedButtonBar::Orientation orientation_)
  50767. : TabbedButtonBar (orientation_),
  50768. owner (owner_)
  50769. {
  50770. }
  50771. ~TabCompButtonBar()
  50772. {
  50773. }
  50774. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  50775. {
  50776. owner->changeCallback (newCurrentTabIndex, newTabName);
  50777. }
  50778. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  50779. {
  50780. owner->popupMenuClickOnTab (tabIndex, tabName);
  50781. }
  50782. const Colour getTabBackgroundColour (const int tabIndex)
  50783. {
  50784. return owner->tabs->getTabBackgroundColour (tabIndex);
  50785. }
  50786. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50787. {
  50788. return owner->createTabButton (tabName, tabIndex);
  50789. }
  50790. juce_UseDebuggingNewOperator
  50791. private:
  50792. TabbedComponent* const owner;
  50793. TabCompButtonBar (const TabCompButtonBar&);
  50794. TabCompButtonBar& operator= (const TabCompButtonBar&);
  50795. };
  50796. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  50797. : panelComponent (0),
  50798. tabDepth (30),
  50799. outlineThickness (1),
  50800. edgeIndent (0)
  50801. {
  50802. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  50803. }
  50804. TabbedComponent::~TabbedComponent()
  50805. {
  50806. clearTabs();
  50807. delete tabs;
  50808. }
  50809. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  50810. {
  50811. tabs->setOrientation (orientation);
  50812. resized();
  50813. }
  50814. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  50815. {
  50816. return tabs->getOrientation();
  50817. }
  50818. void TabbedComponent::setTabBarDepth (const int newDepth)
  50819. {
  50820. if (tabDepth != newDepth)
  50821. {
  50822. tabDepth = newDepth;
  50823. resized();
  50824. }
  50825. }
  50826. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  50827. {
  50828. return new TabBarButton (tabName, tabs, tabIndex);
  50829. }
  50830. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  50831. void TabbedComponent::clearTabs()
  50832. {
  50833. if (panelComponent != 0)
  50834. {
  50835. panelComponent->setVisible (false);
  50836. removeChildComponent (panelComponent);
  50837. panelComponent = 0;
  50838. }
  50839. tabs->clearTabs();
  50840. for (int i = contentComponents.size(); --i >= 0;)
  50841. {
  50842. Component* const c = contentComponents.getUnchecked(i);
  50843. // be careful not to delete these components until they've been removed from the tab component
  50844. jassert (c == 0 || c->isValidComponent());
  50845. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  50846. delete c;
  50847. }
  50848. contentComponents.clear();
  50849. }
  50850. void TabbedComponent::addTab (const String& tabName,
  50851. const Colour& tabBackgroundColour,
  50852. Component* const contentComponent,
  50853. const bool deleteComponentWhenNotNeeded,
  50854. const int insertIndex)
  50855. {
  50856. contentComponents.insert (insertIndex, contentComponent);
  50857. if (contentComponent != 0)
  50858. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  50859. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  50860. }
  50861. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  50862. {
  50863. tabs->setTabName (tabIndex, newName);
  50864. }
  50865. void TabbedComponent::removeTab (const int tabIndex)
  50866. {
  50867. Component* const c = contentComponents [tabIndex];
  50868. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  50869. {
  50870. if (c == panelComponent)
  50871. panelComponent = 0;
  50872. delete c;
  50873. }
  50874. contentComponents.remove (tabIndex);
  50875. tabs->removeTab (tabIndex);
  50876. }
  50877. int TabbedComponent::getNumTabs() const
  50878. {
  50879. return tabs->getNumTabs();
  50880. }
  50881. const StringArray TabbedComponent::getTabNames() const
  50882. {
  50883. return tabs->getTabNames();
  50884. }
  50885. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  50886. {
  50887. return contentComponents [tabIndex];
  50888. }
  50889. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  50890. {
  50891. return tabs->getTabBackgroundColour (tabIndex);
  50892. }
  50893. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50894. {
  50895. tabs->setTabBackgroundColour (tabIndex, newColour);
  50896. if (getCurrentTabIndex() == tabIndex)
  50897. repaint();
  50898. }
  50899. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  50900. {
  50901. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  50902. }
  50903. int TabbedComponent::getCurrentTabIndex() const
  50904. {
  50905. return tabs->getCurrentTabIndex();
  50906. }
  50907. const String& TabbedComponent::getCurrentTabName() const
  50908. {
  50909. return tabs->getCurrentTabName();
  50910. }
  50911. void TabbedComponent::setOutline (int thickness)
  50912. {
  50913. outlineThickness = thickness;
  50914. repaint();
  50915. }
  50916. void TabbedComponent::setIndent (const int indentThickness)
  50917. {
  50918. edgeIndent = indentThickness;
  50919. }
  50920. void TabbedComponent::paint (Graphics& g)
  50921. {
  50922. g.fillAll (findColour (backgroundColourId));
  50923. const TabbedButtonBar::Orientation o = getOrientation();
  50924. int x = 0;
  50925. int y = 0;
  50926. int r = getWidth();
  50927. int b = getHeight();
  50928. if (o == TabbedButtonBar::TabsAtTop)
  50929. y += tabDepth;
  50930. else if (o == TabbedButtonBar::TabsAtBottom)
  50931. b -= tabDepth;
  50932. else if (o == TabbedButtonBar::TabsAtLeft)
  50933. x += tabDepth;
  50934. else if (o == TabbedButtonBar::TabsAtRight)
  50935. r -= tabDepth;
  50936. g.reduceClipRegion (x, y, r - x, b - y);
  50937. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  50938. if (outlineThickness > 0)
  50939. {
  50940. if (o == TabbedButtonBar::TabsAtTop)
  50941. --y;
  50942. else if (o == TabbedButtonBar::TabsAtBottom)
  50943. ++b;
  50944. else if (o == TabbedButtonBar::TabsAtLeft)
  50945. --x;
  50946. else if (o == TabbedButtonBar::TabsAtRight)
  50947. ++r;
  50948. g.setColour (findColour (outlineColourId));
  50949. g.drawRect (x, y, r - x, b - y, outlineThickness);
  50950. }
  50951. }
  50952. void TabbedComponent::resized()
  50953. {
  50954. const TabbedButtonBar::Orientation o = getOrientation();
  50955. const int indent = edgeIndent + outlineThickness;
  50956. BorderSize indents (indent);
  50957. if (o == TabbedButtonBar::TabsAtTop)
  50958. {
  50959. tabs->setBounds (0, 0, getWidth(), tabDepth);
  50960. indents.setTop (tabDepth + edgeIndent);
  50961. }
  50962. else if (o == TabbedButtonBar::TabsAtBottom)
  50963. {
  50964. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  50965. indents.setBottom (tabDepth + edgeIndent);
  50966. }
  50967. else if (o == TabbedButtonBar::TabsAtLeft)
  50968. {
  50969. tabs->setBounds (0, 0, tabDepth, getHeight());
  50970. indents.setLeft (tabDepth + edgeIndent);
  50971. }
  50972. else if (o == TabbedButtonBar::TabsAtRight)
  50973. {
  50974. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  50975. indents.setRight (tabDepth + edgeIndent);
  50976. }
  50977. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  50978. for (int i = contentComponents.size(); --i >= 0;)
  50979. if (contentComponents.getUnchecked (i) != 0)
  50980. contentComponents.getUnchecked (i)->setBounds (bounds);
  50981. }
  50982. void TabbedComponent::lookAndFeelChanged()
  50983. {
  50984. for (int i = contentComponents.size(); --i >= 0;)
  50985. if (contentComponents.getUnchecked (i) != 0)
  50986. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  50987. }
  50988. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  50989. const String& newTabName)
  50990. {
  50991. if (panelComponent != 0)
  50992. {
  50993. panelComponent->setVisible (false);
  50994. removeChildComponent (panelComponent);
  50995. panelComponent = 0;
  50996. }
  50997. if (getCurrentTabIndex() >= 0)
  50998. {
  50999. panelComponent = contentComponents [getCurrentTabIndex()];
  51000. if (panelComponent != 0)
  51001. {
  51002. // do these ops as two stages instead of addAndMakeVisible() so that the
  51003. // component has always got a parent when it gets the visibilityChanged() callback
  51004. addChildComponent (panelComponent);
  51005. panelComponent->setVisible (true);
  51006. panelComponent->toFront (true);
  51007. }
  51008. repaint();
  51009. }
  51010. resized();
  51011. currentTabChanged (newCurrentTabIndex, newTabName);
  51012. }
  51013. void TabbedComponent::currentTabChanged (const int, const String&)
  51014. {
  51015. }
  51016. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51017. {
  51018. }
  51019. END_JUCE_NAMESPACE
  51020. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51021. /*** Start of inlined file: juce_Viewport.cpp ***/
  51022. BEGIN_JUCE_NAMESPACE
  51023. Viewport::Viewport (const String& componentName)
  51024. : Component (componentName),
  51025. scrollBarThickness (0),
  51026. singleStepX (16),
  51027. singleStepY (16),
  51028. showHScrollbar (true),
  51029. showVScrollbar (true),
  51030. verticalScrollBar (true),
  51031. horizontalScrollBar (false)
  51032. {
  51033. // content holder is used to clip the contents so they don't overlap the scrollbars
  51034. addAndMakeVisible (&contentHolder);
  51035. contentHolder.setInterceptsMouseClicks (false, true);
  51036. addChildComponent (&verticalScrollBar);
  51037. addChildComponent (&horizontalScrollBar);
  51038. verticalScrollBar.addListener (this);
  51039. horizontalScrollBar.addListener (this);
  51040. setInterceptsMouseClicks (false, true);
  51041. setWantsKeyboardFocus (true);
  51042. }
  51043. Viewport::~Viewport()
  51044. {
  51045. contentHolder.deleteAllChildren();
  51046. }
  51047. void Viewport::visibleAreaChanged (int, int, int, int)
  51048. {
  51049. }
  51050. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51051. {
  51052. if (contentComp.getComponent() != newViewedComponent)
  51053. {
  51054. {
  51055. ScopedPointer<Component> oldCompDeleter (contentComp);
  51056. contentComp = 0;
  51057. }
  51058. contentComp = newViewedComponent;
  51059. if (contentComp != 0)
  51060. {
  51061. contentComp->setTopLeftPosition (0, 0);
  51062. contentHolder.addAndMakeVisible (contentComp);
  51063. contentComp->addComponentListener (this);
  51064. }
  51065. updateVisibleArea();
  51066. }
  51067. }
  51068. int Viewport::getMaximumVisibleWidth() const
  51069. {
  51070. return contentHolder.getWidth();
  51071. }
  51072. int Viewport::getMaximumVisibleHeight() const
  51073. {
  51074. return contentHolder.getHeight();
  51075. }
  51076. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51077. {
  51078. if (contentComp != 0)
  51079. contentComp->setTopLeftPosition (-xPixelsOffset, -yPixelsOffset);
  51080. }
  51081. void Viewport::setViewPositionProportionately (const double x, const double y)
  51082. {
  51083. if (contentComp != 0)
  51084. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51085. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51086. }
  51087. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51088. {
  51089. if (contentComp != 0)
  51090. {
  51091. int dx = 0, dy = 0;
  51092. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51093. {
  51094. if (mouseX < activeBorderThickness)
  51095. dx = activeBorderThickness - mouseX;
  51096. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51097. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51098. if (dx < 0)
  51099. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51100. else
  51101. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51102. }
  51103. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51104. {
  51105. if (mouseY < activeBorderThickness)
  51106. dy = activeBorderThickness - mouseY;
  51107. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51108. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51109. if (dy < 0)
  51110. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51111. else
  51112. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51113. }
  51114. if (dx != 0 || dy != 0)
  51115. {
  51116. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51117. contentComp->getY() + dy);
  51118. return true;
  51119. }
  51120. }
  51121. return false;
  51122. }
  51123. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51124. {
  51125. updateVisibleArea();
  51126. }
  51127. void Viewport::resized()
  51128. {
  51129. updateVisibleArea();
  51130. }
  51131. void Viewport::updateVisibleArea()
  51132. {
  51133. const int scrollbarWidth = getScrollBarThickness();
  51134. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51135. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51136. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51137. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51138. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51139. Rectangle<int> contentArea (getLocalBounds());
  51140. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51141. {
  51142. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51143. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51144. if (vBarVisible)
  51145. contentArea.setWidth (getWidth() - scrollbarWidth);
  51146. if (hBarVisible)
  51147. contentArea.setHeight (getHeight() - scrollbarWidth);
  51148. if (! contentArea.contains (contentComp->getBounds()))
  51149. {
  51150. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51151. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51152. }
  51153. }
  51154. if (vBarVisible)
  51155. contentArea.setWidth (getWidth() - scrollbarWidth);
  51156. if (hBarVisible)
  51157. contentArea.setHeight (getHeight() - scrollbarWidth);
  51158. contentHolder.setBounds (contentArea);
  51159. Rectangle<int> contentBounds;
  51160. if (contentComp != 0)
  51161. contentBounds = contentComp->getBounds();
  51162. const Point<int> visibleOrigin (-contentBounds.getPosition());
  51163. if (hBarVisible)
  51164. {
  51165. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51166. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51167. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51168. horizontalScrollBar.setSingleStepSize (singleStepX);
  51169. }
  51170. if (vBarVisible)
  51171. {
  51172. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51173. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51174. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51175. verticalScrollBar.setSingleStepSize (singleStepY);
  51176. }
  51177. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51178. horizontalScrollBar.setVisible (hBarVisible);
  51179. verticalScrollBar.setVisible (vBarVisible);
  51180. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51181. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51182. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51183. if (lastVisibleArea != visibleArea)
  51184. {
  51185. lastVisibleArea = visibleArea;
  51186. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  51187. }
  51188. horizontalScrollBar.handleUpdateNowIfNeeded();
  51189. verticalScrollBar.handleUpdateNowIfNeeded();
  51190. }
  51191. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51192. {
  51193. if (singleStepX != stepX || singleStepY != stepY)
  51194. {
  51195. singleStepX = stepX;
  51196. singleStepY = stepY;
  51197. updateVisibleArea();
  51198. }
  51199. }
  51200. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51201. const bool showHorizontalScrollbarIfNeeded)
  51202. {
  51203. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51204. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51205. {
  51206. showVScrollbar = showVerticalScrollbarIfNeeded;
  51207. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51208. updateVisibleArea();
  51209. }
  51210. }
  51211. void Viewport::setScrollBarThickness (const int thickness)
  51212. {
  51213. if (scrollBarThickness != thickness)
  51214. {
  51215. scrollBarThickness = thickness;
  51216. updateVisibleArea();
  51217. }
  51218. }
  51219. int Viewport::getScrollBarThickness() const
  51220. {
  51221. return scrollBarThickness > 0 ? scrollBarThickness
  51222. : getLookAndFeel().getDefaultScrollbarWidth();
  51223. }
  51224. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51225. {
  51226. verticalScrollBar.setButtonVisibility (buttonsVisible);
  51227. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  51228. }
  51229. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51230. {
  51231. const int newRangeStartInt = roundToInt (newRangeStart);
  51232. if (scrollBarThatHasMoved == &horizontalScrollBar)
  51233. {
  51234. setViewPosition (newRangeStartInt, getViewPositionY());
  51235. }
  51236. else if (scrollBarThatHasMoved == &verticalScrollBar)
  51237. {
  51238. setViewPosition (getViewPositionX(), newRangeStartInt);
  51239. }
  51240. }
  51241. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  51242. {
  51243. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51244. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51245. }
  51246. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51247. {
  51248. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51249. {
  51250. const bool hasVertBar = verticalScrollBar.isVisible();
  51251. const bool hasHorzBar = horizontalScrollBar.isVisible();
  51252. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51253. {
  51254. if (wheelIncrementX == 0 && ! hasVertBar)
  51255. wheelIncrementX = wheelIncrementY;
  51256. horizontalScrollBar.mouseWheelMove (e.getEventRelativeTo (&horizontalScrollBar),
  51257. wheelIncrementX, wheelIncrementY);
  51258. return true;
  51259. }
  51260. else if (hasVertBar && wheelIncrementY != 0)
  51261. {
  51262. verticalScrollBar.mouseWheelMove (e.getEventRelativeTo (&verticalScrollBar),
  51263. wheelIncrementX, wheelIncrementY);
  51264. return true;
  51265. }
  51266. }
  51267. return false;
  51268. }
  51269. bool Viewport::keyPressed (const KeyPress& key)
  51270. {
  51271. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51272. || key.isKeyCode (KeyPress::downKey)
  51273. || key.isKeyCode (KeyPress::pageUpKey)
  51274. || key.isKeyCode (KeyPress::pageDownKey)
  51275. || key.isKeyCode (KeyPress::homeKey)
  51276. || key.isKeyCode (KeyPress::endKey);
  51277. if (verticalScrollBar.isVisible() && isUpDownKey)
  51278. return verticalScrollBar.keyPressed (key);
  51279. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51280. || key.isKeyCode (KeyPress::rightKey);
  51281. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  51282. return horizontalScrollBar.keyPressed (key);
  51283. return false;
  51284. }
  51285. END_JUCE_NAMESPACE
  51286. /*** End of inlined file: juce_Viewport.cpp ***/
  51287. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51288. BEGIN_JUCE_NAMESPACE
  51289. static const Colour createBaseColour (const Colour& buttonColour,
  51290. const bool hasKeyboardFocus,
  51291. const bool isMouseOverButton,
  51292. const bool isButtonDown) throw()
  51293. {
  51294. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51295. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51296. if (isButtonDown)
  51297. return baseColour.contrasting (0.2f);
  51298. else if (isMouseOverButton)
  51299. return baseColour.contrasting (0.1f);
  51300. return baseColour;
  51301. }
  51302. LookAndFeel::LookAndFeel()
  51303. {
  51304. /* if this fails it means you're trying to create a LookAndFeel object before
  51305. the static Colours have been initialised. That ain't gonna work. It probably
  51306. means that you're using a static LookAndFeel object and that your compiler has
  51307. decided to intialise it before the Colours class.
  51308. */
  51309. jassert (Colours::white == Colour (0xffffffff));
  51310. // set up the standard set of colours..
  51311. const int textButtonColour = 0xffbbbbff;
  51312. const int textHighlightColour = 0x401111ee;
  51313. const int standardOutlineColour = 0xb2808080;
  51314. static const int standardColours[] =
  51315. {
  51316. TextButton::buttonColourId, textButtonColour,
  51317. TextButton::buttonOnColourId, 0xff4444ff,
  51318. TextButton::textColourOnId, 0xff000000,
  51319. TextButton::textColourOffId, 0xff000000,
  51320. ComboBox::buttonColourId, 0xffbbbbff,
  51321. ComboBox::outlineColourId, standardOutlineColour,
  51322. ToggleButton::textColourId, 0xff000000,
  51323. TextEditor::backgroundColourId, 0xffffffff,
  51324. TextEditor::textColourId, 0xff000000,
  51325. TextEditor::highlightColourId, textHighlightColour,
  51326. TextEditor::highlightedTextColourId, 0xff000000,
  51327. TextEditor::caretColourId, 0xff000000,
  51328. TextEditor::outlineColourId, 0x00000000,
  51329. TextEditor::focusedOutlineColourId, textButtonColour,
  51330. TextEditor::shadowColourId, 0x38000000,
  51331. Label::backgroundColourId, 0x00000000,
  51332. Label::textColourId, 0xff000000,
  51333. Label::outlineColourId, 0x00000000,
  51334. ScrollBar::backgroundColourId, 0x00000000,
  51335. ScrollBar::thumbColourId, 0xffffffff,
  51336. ScrollBar::trackColourId, 0xffffffff,
  51337. TreeView::linesColourId, 0x4c000000,
  51338. TreeView::backgroundColourId, 0x00000000,
  51339. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51340. PopupMenu::backgroundColourId, 0xffffffff,
  51341. PopupMenu::textColourId, 0xff000000,
  51342. PopupMenu::headerTextColourId, 0xff000000,
  51343. PopupMenu::highlightedTextColourId, 0xffffffff,
  51344. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51345. ComboBox::textColourId, 0xff000000,
  51346. ComboBox::backgroundColourId, 0xffffffff,
  51347. ComboBox::arrowColourId, 0x99000000,
  51348. ListBox::backgroundColourId, 0xffffffff,
  51349. ListBox::outlineColourId, standardOutlineColour,
  51350. ListBox::textColourId, 0xff000000,
  51351. Slider::backgroundColourId, 0x00000000,
  51352. Slider::thumbColourId, textButtonColour,
  51353. Slider::trackColourId, 0x7fffffff,
  51354. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51355. Slider::rotarySliderOutlineColourId, 0x66000000,
  51356. Slider::textBoxTextColourId, 0xff000000,
  51357. Slider::textBoxBackgroundColourId, 0xffffffff,
  51358. Slider::textBoxHighlightColourId, textHighlightColour,
  51359. Slider::textBoxOutlineColourId, standardOutlineColour,
  51360. ResizableWindow::backgroundColourId, 0xff777777,
  51361. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51362. AlertWindow::backgroundColourId, 0xffededed,
  51363. AlertWindow::textColourId, 0xff000000,
  51364. AlertWindow::outlineColourId, 0xff666666,
  51365. ProgressBar::backgroundColourId, 0xffeeeeee,
  51366. ProgressBar::foregroundColourId, 0xffaaaaee,
  51367. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51368. TooltipWindow::textColourId, 0xff000000,
  51369. TooltipWindow::outlineColourId, 0x4c000000,
  51370. TabbedComponent::backgroundColourId, 0x00000000,
  51371. TabbedComponent::outlineColourId, 0xff777777,
  51372. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51373. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51374. Toolbar::backgroundColourId, 0xfff6f8f9,
  51375. Toolbar::separatorColourId, 0x4c000000,
  51376. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51377. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51378. Toolbar::labelTextColourId, 0xff000000,
  51379. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51380. HyperlinkButton::textColourId, 0xcc1111ee,
  51381. GroupComponent::outlineColourId, 0x66000000,
  51382. GroupComponent::textColourId, 0xff000000,
  51383. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51384. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51385. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51386. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51387. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51388. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51389. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51390. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51391. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51392. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51393. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51394. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51395. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51396. CodeEditorComponent::caretColourId, 0xff000000,
  51397. CodeEditorComponent::highlightColourId, textHighlightColour,
  51398. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51399. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51400. ColourSelector::labelTextColourId, 0xff000000,
  51401. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51402. KeyMappingEditorComponent::textColourId, 0xff000000,
  51403. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51404. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51405. };
  51406. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51407. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51408. static String defaultSansName, defaultSerifName, defaultFixedName;
  51409. if (defaultSansName.isEmpty())
  51410. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51411. defaultSans = defaultSansName;
  51412. defaultSerif = defaultSerifName;
  51413. defaultFixed = defaultFixedName;
  51414. }
  51415. LookAndFeel::~LookAndFeel()
  51416. {
  51417. }
  51418. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51419. {
  51420. const int index = colourIds.indexOf (colourId);
  51421. if (index >= 0)
  51422. return colours [index];
  51423. jassertfalse;
  51424. return Colours::black;
  51425. }
  51426. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51427. {
  51428. const int index = colourIds.indexOf (colourId);
  51429. if (index >= 0)
  51430. {
  51431. colours.set (index, colour);
  51432. }
  51433. else
  51434. {
  51435. colourIds.add (colourId);
  51436. colours.add (colour);
  51437. }
  51438. }
  51439. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51440. {
  51441. return colourIds.contains (colourId);
  51442. }
  51443. static LookAndFeel* defaultLF = 0;
  51444. static LookAndFeel* currentDefaultLF = 0;
  51445. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51446. {
  51447. // if this happens, your app hasn't initialised itself properly.. if you're
  51448. // trying to hack your own main() function, have a look at
  51449. // JUCEApplication::initialiseForGUI()
  51450. jassert (currentDefaultLF != 0);
  51451. return *currentDefaultLF;
  51452. }
  51453. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51454. {
  51455. if (newDefaultLookAndFeel == 0)
  51456. {
  51457. if (defaultLF == 0)
  51458. defaultLF = new LookAndFeel();
  51459. newDefaultLookAndFeel = defaultLF;
  51460. }
  51461. currentDefaultLF = newDefaultLookAndFeel;
  51462. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51463. {
  51464. Component* const c = Desktop::getInstance().getComponent (i);
  51465. if (c != 0)
  51466. c->sendLookAndFeelChange();
  51467. }
  51468. }
  51469. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51470. {
  51471. if (currentDefaultLF == defaultLF)
  51472. currentDefaultLF = 0;
  51473. deleteAndZero (defaultLF);
  51474. }
  51475. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51476. {
  51477. String faceName (font.getTypefaceName());
  51478. if (faceName == Font::getDefaultSansSerifFontName())
  51479. faceName = defaultSans;
  51480. else if (faceName == Font::getDefaultSerifFontName())
  51481. faceName = defaultSerif;
  51482. else if (faceName == Font::getDefaultMonospacedFontName())
  51483. faceName = defaultFixed;
  51484. Font f (font);
  51485. f.setTypefaceName (faceName);
  51486. return Typeface::createSystemTypefaceFor (f);
  51487. }
  51488. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51489. {
  51490. defaultSans = newName;
  51491. }
  51492. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51493. {
  51494. return component.getMouseCursor();
  51495. }
  51496. void LookAndFeel::drawButtonBackground (Graphics& g,
  51497. Button& button,
  51498. const Colour& backgroundColour,
  51499. bool isMouseOverButton,
  51500. bool isButtonDown)
  51501. {
  51502. const int width = button.getWidth();
  51503. const int height = button.getHeight();
  51504. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51505. const float halfThickness = outlineThickness * 0.5f;
  51506. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51507. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51508. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51509. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51510. const Colour baseColour (createBaseColour (backgroundColour,
  51511. button.hasKeyboardFocus (true),
  51512. isMouseOverButton, isButtonDown)
  51513. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51514. drawGlassLozenge (g,
  51515. indentL,
  51516. indentT,
  51517. width - indentL - indentR,
  51518. height - indentT - indentB,
  51519. baseColour, outlineThickness, -1.0f,
  51520. button.isConnectedOnLeft(),
  51521. button.isConnectedOnRight(),
  51522. button.isConnectedOnTop(),
  51523. button.isConnectedOnBottom());
  51524. }
  51525. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51526. {
  51527. return button.getFont();
  51528. }
  51529. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51530. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51531. {
  51532. Font font (getFontForTextButton (button));
  51533. g.setFont (font);
  51534. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51535. : TextButton::textColourOffId)
  51536. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51537. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51538. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51539. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51540. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51541. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51542. g.drawFittedText (button.getButtonText(),
  51543. leftIndent,
  51544. yIndent,
  51545. button.getWidth() - leftIndent - rightIndent,
  51546. button.getHeight() - yIndent * 2,
  51547. Justification::centred, 2);
  51548. }
  51549. void LookAndFeel::drawTickBox (Graphics& g,
  51550. Component& component,
  51551. float x, float y, float w, float h,
  51552. const bool ticked,
  51553. const bool isEnabled,
  51554. const bool isMouseOverButton,
  51555. const bool isButtonDown)
  51556. {
  51557. const float boxSize = w * 0.7f;
  51558. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51559. createBaseColour (component.findColour (TextButton::buttonColourId)
  51560. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51561. true,
  51562. isMouseOverButton,
  51563. isButtonDown),
  51564. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51565. if (ticked)
  51566. {
  51567. Path tick;
  51568. tick.startNewSubPath (1.5f, 3.0f);
  51569. tick.lineTo (3.0f, 6.0f);
  51570. tick.lineTo (6.0f, 0.0f);
  51571. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51572. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51573. .translated (x, y));
  51574. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51575. }
  51576. }
  51577. void LookAndFeel::drawToggleButton (Graphics& g,
  51578. ToggleButton& button,
  51579. bool isMouseOverButton,
  51580. bool isButtonDown)
  51581. {
  51582. if (button.hasKeyboardFocus (true))
  51583. {
  51584. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51585. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51586. }
  51587. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51588. const float tickWidth = fontSize * 1.1f;
  51589. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51590. tickWidth, tickWidth,
  51591. button.getToggleState(),
  51592. button.isEnabled(),
  51593. isMouseOverButton,
  51594. isButtonDown);
  51595. g.setColour (button.findColour (ToggleButton::textColourId));
  51596. g.setFont (fontSize);
  51597. if (! button.isEnabled())
  51598. g.setOpacity (0.5f);
  51599. const int textX = (int) tickWidth + 5;
  51600. g.drawFittedText (button.getButtonText(),
  51601. textX, 0,
  51602. button.getWidth() - textX - 2, button.getHeight(),
  51603. Justification::centredLeft, 10);
  51604. }
  51605. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51606. {
  51607. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51608. const int tickWidth = jmin (24, button.getHeight());
  51609. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51610. button.getHeight());
  51611. }
  51612. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51613. const String& message,
  51614. const String& button1,
  51615. const String& button2,
  51616. const String& button3,
  51617. AlertWindow::AlertIconType iconType,
  51618. int numButtons,
  51619. Component* associatedComponent)
  51620. {
  51621. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51622. if (numButtons == 1)
  51623. {
  51624. aw->addButton (button1, 0,
  51625. KeyPress (KeyPress::escapeKey, 0, 0),
  51626. KeyPress (KeyPress::returnKey, 0, 0));
  51627. }
  51628. else
  51629. {
  51630. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51631. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51632. if (button1ShortCut == button2ShortCut)
  51633. button2ShortCut = KeyPress();
  51634. if (numButtons == 2)
  51635. {
  51636. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51637. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51638. }
  51639. else if (numButtons == 3)
  51640. {
  51641. aw->addButton (button1, 1, button1ShortCut);
  51642. aw->addButton (button2, 2, button2ShortCut);
  51643. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51644. }
  51645. }
  51646. return aw;
  51647. }
  51648. void LookAndFeel::drawAlertBox (Graphics& g,
  51649. AlertWindow& alert,
  51650. const Rectangle<int>& textArea,
  51651. TextLayout& textLayout)
  51652. {
  51653. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51654. int iconSpaceUsed = 0;
  51655. Justification alignment (Justification::horizontallyCentred);
  51656. const int iconWidth = 80;
  51657. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51658. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51659. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51660. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51661. iconSize, iconSize);
  51662. if (alert.getAlertType() != AlertWindow::NoIcon)
  51663. {
  51664. Path icon;
  51665. uint32 colour;
  51666. char character;
  51667. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51668. {
  51669. colour = 0x55ff5555;
  51670. character = '!';
  51671. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51672. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51673. (float) iconRect.getX(), (float) iconRect.getBottom());
  51674. icon = icon.createPathWithRoundedCorners (5.0f);
  51675. }
  51676. else
  51677. {
  51678. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51679. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51680. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51681. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51682. }
  51683. GlyphArrangement ga;
  51684. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51685. String::charToString (character),
  51686. (float) iconRect.getX(), (float) iconRect.getY(),
  51687. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51688. Justification::centred, false);
  51689. ga.createPath (icon);
  51690. icon.setUsingNonZeroWinding (false);
  51691. g.setColour (Colour (colour));
  51692. g.fillPath (icon);
  51693. iconSpaceUsed = iconWidth;
  51694. alignment = Justification::left;
  51695. }
  51696. g.setColour (alert.findColour (AlertWindow::textColourId));
  51697. textLayout.drawWithin (g,
  51698. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51699. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51700. alignment.getFlags() | Justification::top);
  51701. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51702. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51703. }
  51704. int LookAndFeel::getAlertBoxWindowFlags()
  51705. {
  51706. return ComponentPeer::windowAppearsOnTaskbar
  51707. | ComponentPeer::windowHasDropShadow;
  51708. }
  51709. int LookAndFeel::getAlertWindowButtonHeight()
  51710. {
  51711. return 28;
  51712. }
  51713. const Font LookAndFeel::getAlertWindowFont()
  51714. {
  51715. return Font (12.0f);
  51716. }
  51717. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51718. int width, int height,
  51719. double progress, const String& textToShow)
  51720. {
  51721. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51722. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51723. g.fillAll (background);
  51724. if (progress >= 0.0f && progress < 1.0f)
  51725. {
  51726. drawGlassLozenge (g, 1.0f, 1.0f,
  51727. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51728. (float) (height - 2),
  51729. foreground,
  51730. 0.5f, 0.0f,
  51731. true, true, true, true);
  51732. }
  51733. else
  51734. {
  51735. // spinning bar..
  51736. g.setColour (foreground);
  51737. const int stripeWidth = height * 2;
  51738. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51739. Path p;
  51740. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51741. p.addQuadrilateral (x, 0.0f,
  51742. x + stripeWidth * 0.5f, 0.0f,
  51743. x, (float) height,
  51744. x - stripeWidth * 0.5f, (float) height);
  51745. Image im (Image::ARGB, width, height, true);
  51746. {
  51747. Graphics g2 (im);
  51748. drawGlassLozenge (g2, 1.0f, 1.0f,
  51749. (float) (width - 2),
  51750. (float) (height - 2),
  51751. foreground,
  51752. 0.5f, 0.0f,
  51753. true, true, true, true);
  51754. }
  51755. g.setTiledImageFill (im, 0, 0, 0.85f);
  51756. g.fillPath (p);
  51757. }
  51758. if (textToShow.isNotEmpty())
  51759. {
  51760. g.setColour (Colour::contrasting (background, foreground));
  51761. g.setFont (height * 0.6f);
  51762. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51763. }
  51764. }
  51765. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  51766. {
  51767. const float radius = jmin (w, h) * 0.4f;
  51768. const float thickness = radius * 0.15f;
  51769. Path p;
  51770. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  51771. radius * 0.6f, thickness,
  51772. thickness * 0.5f);
  51773. const float cx = x + w * 0.5f;
  51774. const float cy = y + h * 0.5f;
  51775. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  51776. for (int i = 0; i < 12; ++i)
  51777. {
  51778. const int n = (i + 12 - animationIndex) % 12;
  51779. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  51780. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  51781. .translated (cx, cy));
  51782. }
  51783. }
  51784. void LookAndFeel::drawScrollbarButton (Graphics& g,
  51785. ScrollBar& scrollbar,
  51786. int width, int height,
  51787. int buttonDirection,
  51788. bool /*isScrollbarVertical*/,
  51789. bool /*isMouseOverButton*/,
  51790. bool isButtonDown)
  51791. {
  51792. Path p;
  51793. if (buttonDirection == 0)
  51794. p.addTriangle (width * 0.5f, height * 0.2f,
  51795. width * 0.1f, height * 0.7f,
  51796. width * 0.9f, height * 0.7f);
  51797. else if (buttonDirection == 1)
  51798. p.addTriangle (width * 0.8f, height * 0.5f,
  51799. width * 0.3f, height * 0.1f,
  51800. width * 0.3f, height * 0.9f);
  51801. else if (buttonDirection == 2)
  51802. p.addTriangle (width * 0.5f, height * 0.8f,
  51803. width * 0.1f, height * 0.3f,
  51804. width * 0.9f, height * 0.3f);
  51805. else if (buttonDirection == 3)
  51806. p.addTriangle (width * 0.2f, height * 0.5f,
  51807. width * 0.7f, height * 0.1f,
  51808. width * 0.7f, height * 0.9f);
  51809. if (isButtonDown)
  51810. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  51811. else
  51812. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51813. g.fillPath (p);
  51814. g.setColour (Colour (0x80000000));
  51815. g.strokePath (p, PathStrokeType (0.5f));
  51816. }
  51817. void LookAndFeel::drawScrollbar (Graphics& g,
  51818. ScrollBar& scrollbar,
  51819. int x, int y,
  51820. int width, int height,
  51821. bool isScrollbarVertical,
  51822. int thumbStartPosition,
  51823. int thumbSize,
  51824. bool /*isMouseOver*/,
  51825. bool /*isMouseDown*/)
  51826. {
  51827. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  51828. Path slotPath, thumbPath;
  51829. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  51830. const float slotIndentx2 = slotIndent * 2.0f;
  51831. const float thumbIndent = slotIndent + 1.0f;
  51832. const float thumbIndentx2 = thumbIndent * 2.0f;
  51833. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  51834. if (isScrollbarVertical)
  51835. {
  51836. slotPath.addRoundedRectangle (x + slotIndent,
  51837. y + slotIndent,
  51838. width - slotIndentx2,
  51839. height - slotIndentx2,
  51840. (width - slotIndentx2) * 0.5f);
  51841. if (thumbSize > 0)
  51842. thumbPath.addRoundedRectangle (x + thumbIndent,
  51843. thumbStartPosition + thumbIndent,
  51844. width - thumbIndentx2,
  51845. thumbSize - thumbIndentx2,
  51846. (width - thumbIndentx2) * 0.5f);
  51847. gx1 = (float) x;
  51848. gx2 = x + width * 0.7f;
  51849. }
  51850. else
  51851. {
  51852. slotPath.addRoundedRectangle (x + slotIndent,
  51853. y + slotIndent,
  51854. width - slotIndentx2,
  51855. height - slotIndentx2,
  51856. (height - slotIndentx2) * 0.5f);
  51857. if (thumbSize > 0)
  51858. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  51859. y + thumbIndent,
  51860. thumbSize - thumbIndentx2,
  51861. height - thumbIndentx2,
  51862. (height - thumbIndentx2) * 0.5f);
  51863. gy1 = (float) y;
  51864. gy2 = y + height * 0.7f;
  51865. }
  51866. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51867. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  51868. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  51869. g.fillPath (slotPath);
  51870. if (isScrollbarVertical)
  51871. {
  51872. gx1 = x + width * 0.6f;
  51873. gx2 = (float) x + width;
  51874. }
  51875. else
  51876. {
  51877. gy1 = y + height * 0.6f;
  51878. gy2 = (float) y + height;
  51879. }
  51880. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  51881. Colour (0x19000000), gx2, gy2, false));
  51882. g.fillPath (slotPath);
  51883. g.setColour (thumbColour);
  51884. g.fillPath (thumbPath);
  51885. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  51886. Colours::transparentBlack, gx2, gy2, false));
  51887. g.saveState();
  51888. if (isScrollbarVertical)
  51889. g.reduceClipRegion (x + width / 2, y, width, height);
  51890. else
  51891. g.reduceClipRegion (x, y + height / 2, width, height);
  51892. g.fillPath (thumbPath);
  51893. g.restoreState();
  51894. g.setColour (Colour (0x4c000000));
  51895. g.strokePath (thumbPath, PathStrokeType (0.4f));
  51896. }
  51897. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  51898. {
  51899. return 0;
  51900. }
  51901. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  51902. {
  51903. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  51904. }
  51905. int LookAndFeel::getDefaultScrollbarWidth()
  51906. {
  51907. return 18;
  51908. }
  51909. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  51910. {
  51911. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  51912. : scrollbar.getHeight());
  51913. }
  51914. const Path LookAndFeel::getTickShape (const float height)
  51915. {
  51916. static const unsigned char tickShapeData[] =
  51917. {
  51918. 109,0,224,168,68,0,0,119,67,108,0,224,172,68,0,128,146,67,113,0,192,148,68,0,0,219,67,0,96,110,68,0,224,56,68,113,0,64,51,68,0,32,130,68,0,64,20,68,0,224,
  51919. 162,68,108,0,128,3,68,0,128,168,68,113,0,128,221,67,0,192,175,68,0,0,207,67,0,32,179,68,113,0,0,201,67,0,224,173,68,0,0,181,67,0,224,161,68,108,0,128,168,67,
  51920. 0,128,154,68,113,0,128,141,67,0,192,138,68,0,128,108,67,0,64,131,68,113,0,0,62,67,0,128,119,68,0,0,5,67,0,128,114,68,113,0,0,102,67,0,192,88,68,0,128,155,
  51921. 67,0,192,88,68,113,0,0,190,67,0,192,88,68,0,128,232,67,0,224,131,68,108,0,128,246,67,0,192,139,68,113,0,64,33,68,0,128,87,68,0,0,93,68,0,224,26,68,113,0,
  51922. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  51923. };
  51924. Path p;
  51925. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  51926. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51927. return p;
  51928. }
  51929. const Path LookAndFeel::getCrossShape (const float height)
  51930. {
  51931. static const unsigned char crossShapeData[] =
  51932. {
  51933. 109,0,0,17,68,0,96,145,68,108,0,192,13,68,0,192,147,68,113,0,0,213,67,0,64,174,68,0,0,168,67,0,64,174,68,113,0,0,104,67,0,64,174,68,0,0,5,67,0,64,
  51934. 153,68,113,0,0,18,67,0,64,153,68,0,0,24,67,0,64,153,68,113,0,0,135,67,0,64,153,68,0,128,207,67,0,224,130,68,108,0,0,220,67,0,0,126,68,108,0,0,204,67,
  51935. 0,128,117,68,113,0,0,138,67,0,64,82,68,0,0,138,67,0,192,57,68,113,0,0,138,67,0,192,37,68,0,128,210,67,0,64,10,68,113,0,128,220,67,0,64,45,68,0,0,8,
  51936. 68,0,128,78,68,108,0,192,14,68,0,0,87,68,108,0,64,20,68,0,0,80,68,113,0,192,57,68,0,0,32,68,0,128,88,68,0,0,32,68,113,0,64,112,68,0,0,32,68,0,
  51937. 128,124,68,0,64,68,68,113,0,0,121,68,0,192,67,68,0,128,119,68,0,192,67,68,113,0,192,108,68,0,192,67,68,0,32,89,68,0,96,82,68,113,0,128,69,68,0,0,97,68,
  51938. 0,0,56,68,0,64,115,68,108,0,64,49,68,0,128,124,68,108,0,192,55,68,0,96,129,68,113,0,0,92,68,0,224,146,68,0,192,129,68,0,224,146,68,113,0,64,110,68,0,64,
  51939. 168,68,0,64,87,68,0,64,168,68,113,0,128,66,68,0,64,168,68,0,64,27,68,0,32,150,68,99,101
  51940. };
  51941. Path p;
  51942. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  51943. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51944. return p;
  51945. }
  51946. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  51947. {
  51948. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  51949. x += (w - boxSize) >> 1;
  51950. y += (h - boxSize) >> 1;
  51951. w = boxSize;
  51952. h = boxSize;
  51953. g.setColour (Colour (0xe5ffffff));
  51954. g.fillRect (x, y, w, h);
  51955. g.setColour (Colour (0x80000000));
  51956. g.drawRect (x, y, w, h);
  51957. const float size = boxSize / 2 + 1.0f;
  51958. const float centre = (float) (boxSize / 2);
  51959. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  51960. if (isPlus)
  51961. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  51962. }
  51963. void LookAndFeel::drawBubble (Graphics& g,
  51964. float tipX, float tipY,
  51965. float boxX, float boxY,
  51966. float boxW, float boxH)
  51967. {
  51968. int side = 0;
  51969. if (tipX < boxX)
  51970. side = 1;
  51971. else if (tipX > boxX + boxW)
  51972. side = 3;
  51973. else if (tipY > boxY + boxH)
  51974. side = 2;
  51975. const float indent = 2.0f;
  51976. Path p;
  51977. p.addBubble (boxX + indent,
  51978. boxY + indent,
  51979. boxW - indent * 2.0f,
  51980. boxH - indent * 2.0f,
  51981. 5.0f,
  51982. tipX, tipY,
  51983. side,
  51984. 0.5f,
  51985. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  51986. //xxx need to take comp as param for colour
  51987. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  51988. g.fillPath (p);
  51989. //xxx as above
  51990. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  51991. g.strokePath (p, PathStrokeType (1.33f));
  51992. }
  51993. const Font LookAndFeel::getPopupMenuFont()
  51994. {
  51995. return Font (17.0f);
  51996. }
  51997. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  51998. const bool isSeparator,
  51999. int standardMenuItemHeight,
  52000. int& idealWidth,
  52001. int& idealHeight)
  52002. {
  52003. if (isSeparator)
  52004. {
  52005. idealWidth = 50;
  52006. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52007. }
  52008. else
  52009. {
  52010. Font font (getPopupMenuFont());
  52011. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52012. font.setHeight (standardMenuItemHeight / 1.3f);
  52013. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52014. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52015. }
  52016. }
  52017. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52018. {
  52019. const Colour background (findColour (PopupMenu::backgroundColourId));
  52020. g.fillAll (background);
  52021. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52022. for (int i = 0; i < height; i += 3)
  52023. g.fillRect (0, i, width, 1);
  52024. #if ! JUCE_MAC
  52025. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52026. g.drawRect (0, 0, width, height);
  52027. #endif
  52028. }
  52029. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52030. int width, int height,
  52031. bool isScrollUpArrow)
  52032. {
  52033. const Colour background (findColour (PopupMenu::backgroundColourId));
  52034. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52035. background.withAlpha (0.0f),
  52036. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52037. false));
  52038. g.fillRect (1, 1, width - 2, height - 2);
  52039. const float hw = width * 0.5f;
  52040. const float arrowW = height * 0.3f;
  52041. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52042. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52043. Path p;
  52044. p.addTriangle (hw - arrowW, y1,
  52045. hw + arrowW, y1,
  52046. hw, y2);
  52047. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52048. g.fillPath (p);
  52049. }
  52050. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52051. int width, int height,
  52052. const bool isSeparator,
  52053. const bool isActive,
  52054. const bool isHighlighted,
  52055. const bool isTicked,
  52056. const bool hasSubMenu,
  52057. const String& text,
  52058. const String& shortcutKeyText,
  52059. Image* image,
  52060. const Colour* const textColourToUse)
  52061. {
  52062. const float halfH = height * 0.5f;
  52063. if (isSeparator)
  52064. {
  52065. const float separatorIndent = 5.5f;
  52066. g.setColour (Colour (0x33000000));
  52067. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52068. g.setColour (Colour (0x66ffffff));
  52069. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52070. }
  52071. else
  52072. {
  52073. Colour textColour (findColour (PopupMenu::textColourId));
  52074. if (textColourToUse != 0)
  52075. textColour = *textColourToUse;
  52076. if (isHighlighted)
  52077. {
  52078. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52079. g.fillRect (1, 1, width - 2, height - 2);
  52080. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52081. }
  52082. else
  52083. {
  52084. g.setColour (textColour);
  52085. }
  52086. if (! isActive)
  52087. g.setOpacity (0.3f);
  52088. Font font (getPopupMenuFont());
  52089. if (font.getHeight() > height / 1.3f)
  52090. font.setHeight (height / 1.3f);
  52091. g.setFont (font);
  52092. const int leftBorder = (height * 5) / 4;
  52093. const int rightBorder = 4;
  52094. if (image != 0)
  52095. {
  52096. g.drawImageWithin (*image,
  52097. 2, 1, leftBorder - 4, height - 2,
  52098. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52099. }
  52100. else if (isTicked)
  52101. {
  52102. const Path tick (getTickShape (1.0f));
  52103. const float th = font.getAscent();
  52104. const float ty = halfH - th * 0.5f;
  52105. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52106. th, true));
  52107. }
  52108. g.drawFittedText (text,
  52109. leftBorder, 0,
  52110. width - (leftBorder + rightBorder), height,
  52111. Justification::centredLeft, 1);
  52112. if (shortcutKeyText.isNotEmpty())
  52113. {
  52114. Font f2 (font);
  52115. f2.setHeight (f2.getHeight() * 0.75f);
  52116. f2.setHorizontalScale (0.95f);
  52117. g.setFont (f2);
  52118. g.drawText (shortcutKeyText,
  52119. leftBorder,
  52120. 0,
  52121. width - (leftBorder + rightBorder + 4),
  52122. height,
  52123. Justification::centredRight,
  52124. true);
  52125. }
  52126. if (hasSubMenu)
  52127. {
  52128. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52129. const float x = width - height * 0.6f;
  52130. Path p;
  52131. p.addTriangle (x, halfH - arrowH * 0.5f,
  52132. x, halfH + arrowH * 0.5f,
  52133. x + arrowH * 0.6f, halfH);
  52134. g.fillPath (p);
  52135. }
  52136. }
  52137. }
  52138. int LookAndFeel::getMenuWindowFlags()
  52139. {
  52140. return ComponentPeer::windowHasDropShadow;
  52141. }
  52142. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52143. bool, MenuBarComponent& menuBar)
  52144. {
  52145. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52146. if (menuBar.isEnabled())
  52147. {
  52148. drawShinyButtonShape (g,
  52149. -4.0f, 0.0f,
  52150. width + 8.0f, (float) height,
  52151. 0.0f,
  52152. baseColour,
  52153. 0.4f,
  52154. true, true, true, true);
  52155. }
  52156. else
  52157. {
  52158. g.fillAll (baseColour);
  52159. }
  52160. }
  52161. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52162. {
  52163. return Font (menuBar.getHeight() * 0.7f);
  52164. }
  52165. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52166. {
  52167. return getMenuBarFont (menuBar, itemIndex, itemText)
  52168. .getStringWidth (itemText) + menuBar.getHeight();
  52169. }
  52170. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52171. int width, int height,
  52172. int itemIndex,
  52173. const String& itemText,
  52174. bool isMouseOverItem,
  52175. bool isMenuOpen,
  52176. bool /*isMouseOverBar*/,
  52177. MenuBarComponent& menuBar)
  52178. {
  52179. if (! menuBar.isEnabled())
  52180. {
  52181. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52182. .withMultipliedAlpha (0.5f));
  52183. }
  52184. else if (isMenuOpen || isMouseOverItem)
  52185. {
  52186. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52187. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52188. }
  52189. else
  52190. {
  52191. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52192. }
  52193. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52194. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52195. }
  52196. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52197. TextEditor& textEditor)
  52198. {
  52199. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52200. }
  52201. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52202. {
  52203. if (textEditor.isEnabled())
  52204. {
  52205. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52206. {
  52207. const int border = 2;
  52208. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52209. g.drawRect (0, 0, width, height, border);
  52210. g.setOpacity (1.0f);
  52211. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52212. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52213. }
  52214. else
  52215. {
  52216. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52217. g.drawRect (0, 0, width, height);
  52218. g.setOpacity (1.0f);
  52219. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52220. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52221. }
  52222. }
  52223. }
  52224. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52225. const bool isButtonDown,
  52226. int buttonX, int buttonY,
  52227. int buttonW, int buttonH,
  52228. ComboBox& box)
  52229. {
  52230. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52231. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52232. {
  52233. g.setColour (box.findColour (TextButton::buttonColourId));
  52234. g.drawRect (0, 0, width, height, 2);
  52235. }
  52236. else
  52237. {
  52238. g.setColour (box.findColour (ComboBox::outlineColourId));
  52239. g.drawRect (0, 0, width, height);
  52240. }
  52241. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52242. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52243. box.hasKeyboardFocus (true),
  52244. false, isButtonDown)
  52245. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52246. drawGlassLozenge (g,
  52247. buttonX + outlineThickness, buttonY + outlineThickness,
  52248. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52249. baseColour, outlineThickness, -1.0f,
  52250. true, true, true, true);
  52251. if (box.isEnabled())
  52252. {
  52253. const float arrowX = 0.3f;
  52254. const float arrowH = 0.2f;
  52255. Path p;
  52256. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52257. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52258. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52259. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52260. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52261. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52262. g.setColour (box.findColour (ComboBox::arrowColourId));
  52263. g.fillPath (p);
  52264. }
  52265. }
  52266. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52267. {
  52268. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52269. }
  52270. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52271. {
  52272. return new Label (String::empty, String::empty);
  52273. }
  52274. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52275. {
  52276. label.setBounds (1, 1,
  52277. box.getWidth() + 3 - box.getHeight(),
  52278. box.getHeight() - 2);
  52279. label.setFont (getComboBoxFont (box));
  52280. }
  52281. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52282. {
  52283. g.fillAll (label.findColour (Label::backgroundColourId));
  52284. if (! label.isBeingEdited())
  52285. {
  52286. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52287. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52288. g.setFont (label.getFont());
  52289. g.drawFittedText (label.getText(),
  52290. label.getHorizontalBorderSize(),
  52291. label.getVerticalBorderSize(),
  52292. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52293. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52294. label.getJustificationType(),
  52295. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52296. label.getMinimumHorizontalScale());
  52297. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52298. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52299. }
  52300. else if (label.isEnabled())
  52301. {
  52302. g.setColour (label.findColour (Label::outlineColourId));
  52303. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52304. }
  52305. }
  52306. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52307. int x, int y,
  52308. int width, int height,
  52309. float /*sliderPos*/,
  52310. float /*minSliderPos*/,
  52311. float /*maxSliderPos*/,
  52312. const Slider::SliderStyle /*style*/,
  52313. Slider& slider)
  52314. {
  52315. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52316. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52317. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52318. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52319. Path indent;
  52320. if (slider.isHorizontal())
  52321. {
  52322. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52323. const float ih = sliderRadius;
  52324. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52325. gradCol2, 0.0f, iy + ih, false));
  52326. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52327. width + sliderRadius, ih,
  52328. 5.0f);
  52329. g.fillPath (indent);
  52330. }
  52331. else
  52332. {
  52333. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52334. const float iw = sliderRadius;
  52335. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52336. gradCol2, ix + iw, 0.0f, false));
  52337. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52338. iw, height + sliderRadius,
  52339. 5.0f);
  52340. g.fillPath (indent);
  52341. }
  52342. g.setColour (Colour (0x4c000000));
  52343. g.strokePath (indent, PathStrokeType (0.5f));
  52344. }
  52345. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52346. int x, int y,
  52347. int width, int height,
  52348. float sliderPos,
  52349. float minSliderPos,
  52350. float maxSliderPos,
  52351. const Slider::SliderStyle style,
  52352. Slider& slider)
  52353. {
  52354. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52355. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52356. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52357. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52358. slider.isMouseButtonDown() && slider.isEnabled()));
  52359. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52360. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52361. {
  52362. float kx, ky;
  52363. if (style == Slider::LinearVertical)
  52364. {
  52365. kx = x + width * 0.5f;
  52366. ky = sliderPos;
  52367. }
  52368. else
  52369. {
  52370. kx = sliderPos;
  52371. ky = y + height * 0.5f;
  52372. }
  52373. drawGlassSphere (g,
  52374. kx - sliderRadius,
  52375. ky - sliderRadius,
  52376. sliderRadius * 2.0f,
  52377. knobColour, outlineThickness);
  52378. }
  52379. else
  52380. {
  52381. if (style == Slider::ThreeValueVertical)
  52382. {
  52383. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52384. sliderPos - sliderRadius,
  52385. sliderRadius * 2.0f,
  52386. knobColour, outlineThickness);
  52387. }
  52388. else if (style == Slider::ThreeValueHorizontal)
  52389. {
  52390. drawGlassSphere (g,sliderPos - sliderRadius,
  52391. y + height * 0.5f - sliderRadius,
  52392. sliderRadius * 2.0f,
  52393. knobColour, outlineThickness);
  52394. }
  52395. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52396. {
  52397. const float sr = jmin (sliderRadius, width * 0.4f);
  52398. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52399. minSliderPos - sliderRadius,
  52400. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52401. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52402. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52403. }
  52404. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52405. {
  52406. const float sr = jmin (sliderRadius, height * 0.4f);
  52407. drawGlassPointer (g, minSliderPos - sr,
  52408. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52409. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52410. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52411. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52412. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52413. }
  52414. }
  52415. }
  52416. void LookAndFeel::drawLinearSlider (Graphics& g,
  52417. int x, int y,
  52418. int width, int height,
  52419. float sliderPos,
  52420. float minSliderPos,
  52421. float maxSliderPos,
  52422. const Slider::SliderStyle style,
  52423. Slider& slider)
  52424. {
  52425. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52426. if (style == Slider::LinearBar)
  52427. {
  52428. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52429. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52430. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52431. false,
  52432. isMouseOver,
  52433. isMouseOver || slider.isMouseButtonDown()));
  52434. drawShinyButtonShape (g,
  52435. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52436. baseColour,
  52437. slider.isEnabled() ? 0.9f : 0.3f,
  52438. true, true, true, true);
  52439. }
  52440. else
  52441. {
  52442. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52443. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52444. }
  52445. }
  52446. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52447. {
  52448. return jmin (7,
  52449. slider.getHeight() / 2,
  52450. slider.getWidth() / 2) + 2;
  52451. }
  52452. void LookAndFeel::drawRotarySlider (Graphics& g,
  52453. int x, int y,
  52454. int width, int height,
  52455. float sliderPos,
  52456. const float rotaryStartAngle,
  52457. const float rotaryEndAngle,
  52458. Slider& slider)
  52459. {
  52460. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52461. const float centreX = x + width * 0.5f;
  52462. const float centreY = y + height * 0.5f;
  52463. const float rx = centreX - radius;
  52464. const float ry = centreY - radius;
  52465. const float rw = radius * 2.0f;
  52466. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52467. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52468. if (radius > 12.0f)
  52469. {
  52470. if (slider.isEnabled())
  52471. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52472. else
  52473. g.setColour (Colour (0x80808080));
  52474. const float thickness = 0.7f;
  52475. {
  52476. Path filledArc;
  52477. filledArc.addPieSegment (rx, ry, rw, rw,
  52478. rotaryStartAngle,
  52479. angle,
  52480. thickness);
  52481. g.fillPath (filledArc);
  52482. }
  52483. if (thickness > 0)
  52484. {
  52485. const float innerRadius = radius * 0.2f;
  52486. Path p;
  52487. p.addTriangle (-innerRadius, 0.0f,
  52488. 0.0f, -radius * thickness * 1.1f,
  52489. innerRadius, 0.0f);
  52490. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52491. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52492. }
  52493. if (slider.isEnabled())
  52494. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52495. else
  52496. g.setColour (Colour (0x80808080));
  52497. Path outlineArc;
  52498. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52499. outlineArc.closeSubPath();
  52500. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52501. }
  52502. else
  52503. {
  52504. if (slider.isEnabled())
  52505. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52506. else
  52507. g.setColour (Colour (0x80808080));
  52508. Path p;
  52509. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52510. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52511. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  52512. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52513. }
  52514. }
  52515. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52516. {
  52517. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52518. }
  52519. class SliderLabelComp : public Label
  52520. {
  52521. public:
  52522. SliderLabelComp() : Label (String::empty, String::empty) {}
  52523. ~SliderLabelComp() {}
  52524. void mouseWheelMove (const MouseEvent&, float, float) {}
  52525. };
  52526. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52527. {
  52528. Label* const l = new SliderLabelComp();
  52529. l->setJustificationType (Justification::centred);
  52530. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52531. l->setColour (Label::backgroundColourId,
  52532. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52533. : slider.findColour (Slider::textBoxBackgroundColourId));
  52534. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52535. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52536. l->setColour (TextEditor::backgroundColourId,
  52537. slider.findColour (Slider::textBoxBackgroundColourId)
  52538. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52539. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52540. return l;
  52541. }
  52542. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52543. {
  52544. return 0;
  52545. }
  52546. static const TextLayout layoutTooltipText (const String& text) throw()
  52547. {
  52548. const float tooltipFontSize = 12.0f;
  52549. const int maxToolTipWidth = 400;
  52550. const Font f (tooltipFontSize, Font::bold);
  52551. TextLayout tl (text, f);
  52552. tl.layout (maxToolTipWidth, Justification::left, true);
  52553. return tl;
  52554. }
  52555. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52556. {
  52557. const TextLayout tl (layoutTooltipText (tipText));
  52558. width = tl.getWidth() + 14;
  52559. height = tl.getHeight() + 6;
  52560. }
  52561. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52562. {
  52563. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52564. const Colour textCol (findColour (TooltipWindow::textColourId));
  52565. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52566. g.setColour (findColour (TooltipWindow::outlineColourId));
  52567. g.drawRect (0, 0, width, height, 1);
  52568. #endif
  52569. const TextLayout tl (layoutTooltipText (text));
  52570. g.setColour (findColour (TooltipWindow::textColourId));
  52571. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52572. }
  52573. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52574. {
  52575. return new TextButton (text, TRANS("click to browse for a different file"));
  52576. }
  52577. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52578. ComboBox* filenameBox,
  52579. Button* browseButton)
  52580. {
  52581. browseButton->setSize (80, filenameComp.getHeight());
  52582. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52583. if (tb != 0)
  52584. tb->changeWidthToFitText();
  52585. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52586. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52587. }
  52588. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52589. int imageX, int imageY, int imageW, int imageH,
  52590. const Colour& overlayColour,
  52591. float imageOpacity,
  52592. ImageButton& button)
  52593. {
  52594. if (! button.isEnabled())
  52595. imageOpacity *= 0.3f;
  52596. if (! overlayColour.isOpaque())
  52597. {
  52598. g.setOpacity (imageOpacity);
  52599. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52600. 0, 0, image->getWidth(), image->getHeight(), false);
  52601. }
  52602. if (! overlayColour.isTransparent())
  52603. {
  52604. g.setColour (overlayColour);
  52605. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52606. 0, 0, image->getWidth(), image->getHeight(), true);
  52607. }
  52608. }
  52609. void LookAndFeel::drawCornerResizer (Graphics& g,
  52610. int w, int h,
  52611. bool /*isMouseOver*/,
  52612. bool /*isMouseDragging*/)
  52613. {
  52614. const float lineThickness = jmin (w, h) * 0.075f;
  52615. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52616. {
  52617. g.setColour (Colours::lightgrey);
  52618. g.drawLine (w * i,
  52619. h + 1.0f,
  52620. w + 1.0f,
  52621. h * i,
  52622. lineThickness);
  52623. g.setColour (Colours::darkgrey);
  52624. g.drawLine (w * i + lineThickness,
  52625. h + 1.0f,
  52626. w + 1.0f,
  52627. h * i + lineThickness,
  52628. lineThickness);
  52629. }
  52630. }
  52631. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52632. const BorderSize& /*borders*/)
  52633. {
  52634. }
  52635. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52636. const BorderSize& /*border*/, ResizableWindow& window)
  52637. {
  52638. g.fillAll (window.getBackgroundColour());
  52639. }
  52640. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52641. const BorderSize& border, ResizableWindow&)
  52642. {
  52643. g.setColour (Colour (0x80000000));
  52644. g.drawRect (0, 0, w, h);
  52645. g.setColour (Colour (0x19000000));
  52646. g.drawRect (border.getLeft() - 1,
  52647. border.getTop() - 1,
  52648. w + 2 - border.getLeftAndRight(),
  52649. h + 2 - border.getTopAndBottom());
  52650. }
  52651. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52652. Graphics& g, int w, int h,
  52653. int titleSpaceX, int titleSpaceW,
  52654. const Image* icon,
  52655. bool drawTitleTextOnLeft)
  52656. {
  52657. const bool isActive = window.isActiveWindow();
  52658. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52659. 0.0f, 0.0f,
  52660. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52661. 0.0f, (float) h, false));
  52662. g.fillAll();
  52663. Font font (h * 0.65f, Font::bold);
  52664. g.setFont (font);
  52665. int textW = font.getStringWidth (window.getName());
  52666. int iconW = 0;
  52667. int iconH = 0;
  52668. if (icon != 0)
  52669. {
  52670. iconH = (int) font.getHeight();
  52671. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52672. }
  52673. textW = jmin (titleSpaceW, textW + iconW);
  52674. int textX = drawTitleTextOnLeft ? titleSpaceX
  52675. : jmax (titleSpaceX, (w - textW) / 2);
  52676. if (textX + textW > titleSpaceX + titleSpaceW)
  52677. textX = titleSpaceX + titleSpaceW - textW;
  52678. if (icon != 0)
  52679. {
  52680. g.setOpacity (isActive ? 1.0f : 0.6f);
  52681. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  52682. RectanglePlacement::centred, false);
  52683. textX += iconW;
  52684. textW -= iconW;
  52685. }
  52686. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52687. g.setColour (findColour (DocumentWindow::textColourId));
  52688. else
  52689. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52690. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52691. }
  52692. class GlassWindowButton : public Button
  52693. {
  52694. public:
  52695. GlassWindowButton (const String& name, const Colour& col,
  52696. const Path& normalShape_,
  52697. const Path& toggledShape_) throw()
  52698. : Button (name),
  52699. colour (col),
  52700. normalShape (normalShape_),
  52701. toggledShape (toggledShape_)
  52702. {
  52703. }
  52704. ~GlassWindowButton()
  52705. {
  52706. }
  52707. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52708. {
  52709. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52710. if (! isEnabled())
  52711. alpha *= 0.5f;
  52712. float x = 0, y = 0, diam;
  52713. if (getWidth() < getHeight())
  52714. {
  52715. diam = (float) getWidth();
  52716. y = (getHeight() - getWidth()) * 0.5f;
  52717. }
  52718. else
  52719. {
  52720. diam = (float) getHeight();
  52721. y = (getWidth() - getHeight()) * 0.5f;
  52722. }
  52723. x += diam * 0.05f;
  52724. y += diam * 0.05f;
  52725. diam *= 0.9f;
  52726. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52727. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52728. g.fillEllipse (x, y, diam, diam);
  52729. x += 2.0f;
  52730. y += 2.0f;
  52731. diam -= 4.0f;
  52732. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52733. Path& p = getToggleState() ? toggledShape : normalShape;
  52734. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52735. diam * 0.4f, diam * 0.4f, true));
  52736. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52737. g.fillPath (p, t);
  52738. }
  52739. juce_UseDebuggingNewOperator
  52740. private:
  52741. Colour colour;
  52742. Path normalShape, toggledShape;
  52743. GlassWindowButton (const GlassWindowButton&);
  52744. GlassWindowButton& operator= (const GlassWindowButton&);
  52745. };
  52746. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52747. {
  52748. Path shape;
  52749. const float crossThickness = 0.25f;
  52750. if (buttonType == DocumentWindow::closeButton)
  52751. {
  52752. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  52753. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  52754. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52755. }
  52756. else if (buttonType == DocumentWindow::minimiseButton)
  52757. {
  52758. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52759. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  52760. }
  52761. else if (buttonType == DocumentWindow::maximiseButton)
  52762. {
  52763. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  52764. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52765. Path fullscreenShape;
  52766. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  52767. fullscreenShape.lineTo (0.0f, 100.0f);
  52768. fullscreenShape.lineTo (0.0f, 0.0f);
  52769. fullscreenShape.lineTo (100.0f, 0.0f);
  52770. fullscreenShape.lineTo (100.0f, 45.0f);
  52771. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  52772. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  52773. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  52774. }
  52775. jassertfalse;
  52776. return 0;
  52777. }
  52778. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  52779. int titleBarX,
  52780. int titleBarY,
  52781. int titleBarW,
  52782. int titleBarH,
  52783. Button* minimiseButton,
  52784. Button* maximiseButton,
  52785. Button* closeButton,
  52786. bool positionTitleBarButtonsOnLeft)
  52787. {
  52788. const int buttonW = titleBarH - titleBarH / 8;
  52789. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  52790. : titleBarX + titleBarW - buttonW - buttonW / 4;
  52791. if (closeButton != 0)
  52792. {
  52793. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52794. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  52795. }
  52796. if (positionTitleBarButtonsOnLeft)
  52797. swapVariables (minimiseButton, maximiseButton);
  52798. if (maximiseButton != 0)
  52799. {
  52800. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52801. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  52802. }
  52803. if (minimiseButton != 0)
  52804. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52805. }
  52806. int LookAndFeel::getDefaultMenuBarHeight()
  52807. {
  52808. return 24;
  52809. }
  52810. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  52811. {
  52812. return new DropShadower (0.4f, 1, 5, 10);
  52813. }
  52814. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  52815. int w, int h,
  52816. bool /*isVerticalBar*/,
  52817. bool isMouseOver,
  52818. bool isMouseDragging)
  52819. {
  52820. float alpha = 0.5f;
  52821. if (isMouseOver || isMouseDragging)
  52822. {
  52823. g.fillAll (Colour (0x190000ff));
  52824. alpha = 1.0f;
  52825. }
  52826. const float cx = w * 0.5f;
  52827. const float cy = h * 0.5f;
  52828. const float cr = jmin (w, h) * 0.4f;
  52829. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  52830. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  52831. true));
  52832. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  52833. }
  52834. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  52835. const String& text,
  52836. const Justification& position,
  52837. GroupComponent& group)
  52838. {
  52839. const float textH = 15.0f;
  52840. const float indent = 3.0f;
  52841. const float textEdgeGap = 4.0f;
  52842. float cs = 5.0f;
  52843. Font f (textH);
  52844. Path p;
  52845. float x = indent;
  52846. float y = f.getAscent() - 3.0f;
  52847. float w = jmax (0.0f, width - x * 2.0f);
  52848. float h = jmax (0.0f, height - y - indent);
  52849. cs = jmin (cs, w * 0.5f, h * 0.5f);
  52850. const float cs2 = 2.0f * cs;
  52851. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  52852. float textX = cs + textEdgeGap;
  52853. if (position.testFlags (Justification::horizontallyCentred))
  52854. textX = cs + (w - cs2 - textW) * 0.5f;
  52855. else if (position.testFlags (Justification::right))
  52856. textX = w - cs - textW - textEdgeGap;
  52857. p.startNewSubPath (x + textX + textW, y);
  52858. p.lineTo (x + w - cs, y);
  52859. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  52860. p.lineTo (x + w, y + h - cs);
  52861. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52862. p.lineTo (x + cs, y + h);
  52863. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52864. p.lineTo (x, y + cs);
  52865. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52866. p.lineTo (x + textX, y);
  52867. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  52868. g.setColour (group.findColour (GroupComponent::outlineColourId)
  52869. .withMultipliedAlpha (alpha));
  52870. g.strokePath (p, PathStrokeType (2.0f));
  52871. g.setColour (group.findColour (GroupComponent::textColourId)
  52872. .withMultipliedAlpha (alpha));
  52873. g.setFont (f);
  52874. g.drawText (text,
  52875. roundToInt (x + textX), 0,
  52876. roundToInt (textW),
  52877. roundToInt (textH),
  52878. Justification::centred, true);
  52879. }
  52880. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  52881. {
  52882. return 1 + tabDepth / 3;
  52883. }
  52884. int LookAndFeel::getTabButtonSpaceAroundImage()
  52885. {
  52886. return 4;
  52887. }
  52888. void LookAndFeel::createTabButtonShape (Path& p,
  52889. int width, int height,
  52890. int /*tabIndex*/,
  52891. const String& /*text*/,
  52892. Button& /*button*/,
  52893. TabbedButtonBar::Orientation orientation,
  52894. const bool /*isMouseOver*/,
  52895. const bool /*isMouseDown*/,
  52896. const bool /*isFrontTab*/)
  52897. {
  52898. const float w = (float) width;
  52899. const float h = (float) height;
  52900. float length = w;
  52901. float depth = h;
  52902. if (orientation == TabbedButtonBar::TabsAtLeft
  52903. || orientation == TabbedButtonBar::TabsAtRight)
  52904. {
  52905. swapVariables (length, depth);
  52906. }
  52907. const float indent = (float) getTabButtonOverlap ((int) depth);
  52908. const float overhang = 4.0f;
  52909. if (orientation == TabbedButtonBar::TabsAtLeft)
  52910. {
  52911. p.startNewSubPath (w, 0.0f);
  52912. p.lineTo (0.0f, indent);
  52913. p.lineTo (0.0f, h - indent);
  52914. p.lineTo (w, h);
  52915. p.lineTo (w + overhang, h + overhang);
  52916. p.lineTo (w + overhang, -overhang);
  52917. }
  52918. else if (orientation == TabbedButtonBar::TabsAtRight)
  52919. {
  52920. p.startNewSubPath (0.0f, 0.0f);
  52921. p.lineTo (w, indent);
  52922. p.lineTo (w, h - indent);
  52923. p.lineTo (0.0f, h);
  52924. p.lineTo (-overhang, h + overhang);
  52925. p.lineTo (-overhang, -overhang);
  52926. }
  52927. else if (orientation == TabbedButtonBar::TabsAtBottom)
  52928. {
  52929. p.startNewSubPath (0.0f, 0.0f);
  52930. p.lineTo (indent, h);
  52931. p.lineTo (w - indent, h);
  52932. p.lineTo (w, 0.0f);
  52933. p.lineTo (w + overhang, -overhang);
  52934. p.lineTo (-overhang, -overhang);
  52935. }
  52936. else
  52937. {
  52938. p.startNewSubPath (0.0f, h);
  52939. p.lineTo (indent, 0.0f);
  52940. p.lineTo (w - indent, 0.0f);
  52941. p.lineTo (w, h);
  52942. p.lineTo (w + overhang, h + overhang);
  52943. p.lineTo (-overhang, h + overhang);
  52944. }
  52945. p.closeSubPath();
  52946. p = p.createPathWithRoundedCorners (3.0f);
  52947. }
  52948. void LookAndFeel::fillTabButtonShape (Graphics& g,
  52949. const Path& path,
  52950. const Colour& preferredColour,
  52951. int /*tabIndex*/,
  52952. const String& /*text*/,
  52953. Button& button,
  52954. TabbedButtonBar::Orientation /*orientation*/,
  52955. const bool /*isMouseOver*/,
  52956. const bool /*isMouseDown*/,
  52957. const bool isFrontTab)
  52958. {
  52959. g.setColour (isFrontTab ? preferredColour
  52960. : preferredColour.withMultipliedAlpha (0.9f));
  52961. g.fillPath (path);
  52962. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  52963. : TabbedButtonBar::tabOutlineColourId, false)
  52964. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52965. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  52966. }
  52967. void LookAndFeel::drawTabButtonText (Graphics& g,
  52968. int x, int y, int w, int h,
  52969. const Colour& preferredBackgroundColour,
  52970. int /*tabIndex*/,
  52971. const String& text,
  52972. Button& button,
  52973. TabbedButtonBar::Orientation orientation,
  52974. const bool isMouseOver,
  52975. const bool isMouseDown,
  52976. const bool isFrontTab)
  52977. {
  52978. int length = w;
  52979. int depth = h;
  52980. if (orientation == TabbedButtonBar::TabsAtLeft
  52981. || orientation == TabbedButtonBar::TabsAtRight)
  52982. {
  52983. swapVariables (length, depth);
  52984. }
  52985. Font font (depth * 0.6f);
  52986. font.setUnderline (button.hasKeyboardFocus (false));
  52987. GlyphArrangement textLayout;
  52988. textLayout.addFittedText (font, text.trim(),
  52989. 0.0f, 0.0f, (float) length, (float) depth,
  52990. Justification::centred,
  52991. jmax (1, depth / 12));
  52992. AffineTransform transform;
  52993. if (orientation == TabbedButtonBar::TabsAtLeft)
  52994. {
  52995. transform = transform.rotated (float_Pi * -0.5f)
  52996. .translated ((float) x, (float) (y + h));
  52997. }
  52998. else if (orientation == TabbedButtonBar::TabsAtRight)
  52999. {
  53000. transform = transform.rotated (float_Pi * 0.5f)
  53001. .translated ((float) (x + w), (float) y);
  53002. }
  53003. else
  53004. {
  53005. transform = transform.translated ((float) x, (float) y);
  53006. }
  53007. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53008. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53009. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53010. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53011. else
  53012. g.setColour (preferredBackgroundColour.contrasting());
  53013. if (! (isMouseOver || isMouseDown))
  53014. g.setOpacity (0.8f);
  53015. if (! button.isEnabled())
  53016. g.setOpacity (0.3f);
  53017. textLayout.draw (g, transform);
  53018. }
  53019. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53020. const String& text,
  53021. int tabDepth,
  53022. Button&)
  53023. {
  53024. Font f (tabDepth * 0.6f);
  53025. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53026. }
  53027. void LookAndFeel::drawTabButton (Graphics& g,
  53028. int w, int h,
  53029. const Colour& preferredColour,
  53030. int tabIndex,
  53031. const String& text,
  53032. Button& button,
  53033. TabbedButtonBar::Orientation orientation,
  53034. const bool isMouseOver,
  53035. const bool isMouseDown,
  53036. const bool isFrontTab)
  53037. {
  53038. int length = w;
  53039. int depth = h;
  53040. if (orientation == TabbedButtonBar::TabsAtLeft
  53041. || orientation == TabbedButtonBar::TabsAtRight)
  53042. {
  53043. swapVariables (length, depth);
  53044. }
  53045. Path tabShape;
  53046. createTabButtonShape (tabShape, w, h,
  53047. tabIndex, text, button, orientation,
  53048. isMouseOver, isMouseDown, isFrontTab);
  53049. fillTabButtonShape (g, tabShape, preferredColour,
  53050. tabIndex, text, button, orientation,
  53051. isMouseOver, isMouseDown, isFrontTab);
  53052. const int indent = getTabButtonOverlap (depth);
  53053. int x = 0, y = 0;
  53054. if (orientation == TabbedButtonBar::TabsAtLeft
  53055. || orientation == TabbedButtonBar::TabsAtRight)
  53056. {
  53057. y += indent;
  53058. h -= indent * 2;
  53059. }
  53060. else
  53061. {
  53062. x += indent;
  53063. w -= indent * 2;
  53064. }
  53065. drawTabButtonText (g, x, y, w, h, preferredColour,
  53066. tabIndex, text, button, orientation,
  53067. isMouseOver, isMouseDown, isFrontTab);
  53068. }
  53069. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53070. int w, int h,
  53071. TabbedButtonBar& tabBar,
  53072. TabbedButtonBar::Orientation orientation)
  53073. {
  53074. const float shadowSize = 0.2f;
  53075. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53076. Rectangle<int> shadowRect;
  53077. if (orientation == TabbedButtonBar::TabsAtLeft)
  53078. {
  53079. x1 = (float) w;
  53080. x2 = w * (1.0f - shadowSize);
  53081. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53082. }
  53083. else if (orientation == TabbedButtonBar::TabsAtRight)
  53084. {
  53085. x2 = w * shadowSize;
  53086. shadowRect.setBounds (0, 0, (int) x2, h);
  53087. }
  53088. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53089. {
  53090. y2 = h * shadowSize;
  53091. shadowRect.setBounds (0, 0, w, (int) y2);
  53092. }
  53093. else
  53094. {
  53095. y1 = (float) h;
  53096. y2 = h * (1.0f - shadowSize);
  53097. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53098. }
  53099. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53100. Colours::transparentBlack, x2, y2, false));
  53101. shadowRect.expand (2, 2);
  53102. g.fillRect (shadowRect);
  53103. g.setColour (Colour (0x80000000));
  53104. if (orientation == TabbedButtonBar::TabsAtLeft)
  53105. {
  53106. g.fillRect (w - 1, 0, 1, h);
  53107. }
  53108. else if (orientation == TabbedButtonBar::TabsAtRight)
  53109. {
  53110. g.fillRect (0, 0, 1, h);
  53111. }
  53112. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53113. {
  53114. g.fillRect (0, 0, w, 1);
  53115. }
  53116. else
  53117. {
  53118. g.fillRect (0, h - 1, w, 1);
  53119. }
  53120. }
  53121. Button* LookAndFeel::createTabBarExtrasButton()
  53122. {
  53123. const float thickness = 7.0f;
  53124. const float indent = 22.0f;
  53125. Path p;
  53126. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53127. DrawablePath ellipse;
  53128. ellipse.setPath (p);
  53129. ellipse.setFill (Colour (0x99ffffff));
  53130. p.clear();
  53131. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53132. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53133. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53134. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53135. p.setUsingNonZeroWinding (false);
  53136. DrawablePath dp;
  53137. dp.setPath (p);
  53138. dp.setFill (Colour (0x59000000));
  53139. DrawableComposite normalImage;
  53140. normalImage.insertDrawable (ellipse);
  53141. normalImage.insertDrawable (dp);
  53142. dp.setFill (Colour (0xcc000000));
  53143. DrawableComposite overImage;
  53144. overImage.insertDrawable (ellipse);
  53145. overImage.insertDrawable (dp);
  53146. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53147. db->setImages (&normalImage, &overImage, 0);
  53148. return db;
  53149. }
  53150. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53151. {
  53152. g.fillAll (Colours::white);
  53153. const int w = header.getWidth();
  53154. const int h = header.getHeight();
  53155. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53156. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53157. false));
  53158. g.fillRect (0, h / 2, w, h);
  53159. g.setColour (Colour (0x33000000));
  53160. g.fillRect (0, h - 1, w, 1);
  53161. for (int i = header.getNumColumns (true); --i >= 0;)
  53162. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53163. }
  53164. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53165. int width, int height,
  53166. bool isMouseOver, bool isMouseDown,
  53167. int columnFlags)
  53168. {
  53169. if (isMouseDown)
  53170. g.fillAll (Colour (0x8899aadd));
  53171. else if (isMouseOver)
  53172. g.fillAll (Colour (0x5599aadd));
  53173. int rightOfText = width - 4;
  53174. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53175. {
  53176. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53177. const float bottom = height - top;
  53178. const float w = height * 0.5f;
  53179. const float x = rightOfText - (w * 1.25f);
  53180. rightOfText = (int) x;
  53181. Path sortArrow;
  53182. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53183. g.setColour (Colour (0x99000000));
  53184. g.fillPath (sortArrow);
  53185. }
  53186. g.setColour (Colours::black);
  53187. g.setFont (height * 0.5f, Font::bold);
  53188. const int textX = 4;
  53189. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53190. }
  53191. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53192. {
  53193. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53194. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53195. background.darker (0.1f),
  53196. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53197. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53198. false));
  53199. g.fillAll();
  53200. }
  53201. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53202. {
  53203. return createTabBarExtrasButton();
  53204. }
  53205. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53206. bool isMouseOver, bool isMouseDown,
  53207. ToolbarItemComponent& component)
  53208. {
  53209. if (isMouseDown)
  53210. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53211. else if (isMouseOver)
  53212. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53213. }
  53214. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53215. const String& text, ToolbarItemComponent& component)
  53216. {
  53217. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53218. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53219. const float fontHeight = jmin (14.0f, height * 0.85f);
  53220. g.setFont (fontHeight);
  53221. g.drawFittedText (text,
  53222. x, y, width, height,
  53223. Justification::centred,
  53224. jmax (1, height / (int) fontHeight));
  53225. }
  53226. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53227. bool isOpen, int width, int height)
  53228. {
  53229. const int buttonSize = (height * 3) / 4;
  53230. const int buttonIndent = (height - buttonSize) / 2;
  53231. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53232. const int textX = buttonIndent * 2 + buttonSize + 2;
  53233. g.setColour (Colours::black);
  53234. g.setFont (height * 0.7f, Font::bold);
  53235. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53236. }
  53237. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53238. PropertyComponent&)
  53239. {
  53240. g.setColour (Colour (0x66ffffff));
  53241. g.fillRect (0, 0, width, height - 1);
  53242. }
  53243. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53244. PropertyComponent& component)
  53245. {
  53246. g.setColour (Colours::black);
  53247. if (! component.isEnabled())
  53248. g.setOpacity (0.6f);
  53249. g.setFont (jmin (height, 24) * 0.65f);
  53250. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53251. g.drawFittedText (component.getName(),
  53252. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53253. Justification::centredLeft, 2);
  53254. }
  53255. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53256. {
  53257. return Rectangle<int> (component.getWidth() / 3, 1,
  53258. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53259. }
  53260. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53261. const String& instructions,
  53262. GlyphArrangement& text,
  53263. int width)
  53264. {
  53265. text.clear();
  53266. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53267. 8.0f, 22.0f, width - 16.0f,
  53268. Justification::centred);
  53269. text.addJustifiedText (Font (14.0f), instructions,
  53270. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53271. Justification::centred);
  53272. }
  53273. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53274. const String& filename, Image* icon,
  53275. const String& fileSizeDescription,
  53276. const String& fileTimeDescription,
  53277. const bool isDirectory,
  53278. const bool isItemSelected,
  53279. const int /*itemIndex*/)
  53280. {
  53281. if (isItemSelected)
  53282. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53283. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53284. g.setFont (height * 0.7f);
  53285. Image im;
  53286. if (icon != 0)
  53287. im = *icon;
  53288. if (im.isNull())
  53289. im = isDirectory ? getDefaultFolderImage()
  53290. : getDefaultDocumentFileImage();
  53291. const int x = 32;
  53292. if (im.isValid())
  53293. {
  53294. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53295. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53296. false);
  53297. }
  53298. if (width > 450 && ! isDirectory)
  53299. {
  53300. const int sizeX = roundToInt (width * 0.7f);
  53301. const int dateX = roundToInt (width * 0.8f);
  53302. g.drawFittedText (filename,
  53303. x, 0, sizeX - x, height,
  53304. Justification::centredLeft, 1);
  53305. g.setFont (height * 0.5f);
  53306. g.setColour (Colours::darkgrey);
  53307. if (! isDirectory)
  53308. {
  53309. g.drawFittedText (fileSizeDescription,
  53310. sizeX, 0, dateX - sizeX - 8, height,
  53311. Justification::centredRight, 1);
  53312. g.drawFittedText (fileTimeDescription,
  53313. dateX, 0, width - 8 - dateX, height,
  53314. Justification::centredRight, 1);
  53315. }
  53316. }
  53317. else
  53318. {
  53319. g.drawFittedText (filename,
  53320. x, 0, width - x, height,
  53321. Justification::centredLeft, 1);
  53322. }
  53323. }
  53324. Button* LookAndFeel::createFileBrowserGoUpButton()
  53325. {
  53326. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53327. Path arrowPath;
  53328. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  53329. DrawablePath arrowImage;
  53330. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53331. arrowImage.setPath (arrowPath);
  53332. goUpButton->setImages (&arrowImage);
  53333. return goUpButton;
  53334. }
  53335. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53336. DirectoryContentsDisplayComponent* fileListComponent,
  53337. FilePreviewComponent* previewComp,
  53338. ComboBox* currentPathBox,
  53339. TextEditor* filenameBox,
  53340. Button* goUpButton)
  53341. {
  53342. const int x = 8;
  53343. int w = browserComp.getWidth() - x - x;
  53344. if (previewComp != 0)
  53345. {
  53346. const int previewWidth = w / 3;
  53347. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53348. w -= previewWidth + 4;
  53349. }
  53350. int y = 4;
  53351. const int controlsHeight = 22;
  53352. const int bottomSectionHeight = controlsHeight + 8;
  53353. const int upButtonWidth = 50;
  53354. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53355. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53356. y += controlsHeight + 4;
  53357. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53358. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53359. y = listAsComp->getBottom() + 4;
  53360. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53361. }
  53362. const Image LookAndFeel::getDefaultFolderImage()
  53363. {
  53364. static const unsigned char foldericon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,28,8,6,0,0,0,0,194,189,34,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  53365. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,9,46,73,68,65,84,120,218,98,252,255,255,63,3,50,240,41,95,192,
  53366. 197,205,198,32,202,204,202,33,241,254,235,47,133,47,191,24,180,213,164,133,152,69,24,222,44,234,42,77,188,245,31,170,129,145,145,145,1,29,128,164,226,91,86,113,252,248,207,200,171,37,39,204,239,170,43,
  53367. 254,206,218,88,231,61,62,61,0,1,196,2,149,96,116,200,158,102,194,202,201,227,197,193,206,166,194,204,193,33,195,202,204,38,42,197,197,42,196,193,202,33,240,241,231,15,134,151,95,127,9,2,149,22,0,241,47,
  53368. 152,230,128,134,245,204,63,191,188,103,83,144,16,16,228,229,102,151,76,239,217,32,199,204,198,169,205,254,159,65,245,203,79,6,169,131,151,30,47,1,42,91,10,196,127,208,236,101,76,235,90,43,101,160,40,242,
  53369. 19,32,128,64,78,98,52,12,41,149,145,215,52,89,162,38,35,107,39,196,203,203,192,206,194,206,192,197,198,202,192,203,197,198,192,205,193,206,240,252,227,103,134,139,55,175,191,127,243,242,78,219,187,207,
  53370. 63,215,255,98,23,48,228,227,96,83,98,102,102,85,225,224,228,80,20,224,230,86,226,225,228,150,103,101,97,101,230,227,228,96,224,0,234,191,243,252,5,195,222,19,199,38,191,127,112,161,83,66,199,86,141,131,
  53371. 149,69,146,133,153,69,137,149,133,89,157,141,131,77,83,140,143,243,219,255,31,159,123,0,2,136,69,90,207,129,157,71,68,42,66,71,73,209,210,81,91,27,24,142,140,12,127,255,253,103,0,185,236,31,3,144,6,50,
  53372. 148,68,216,25,216,24,117,4,239,11,243,214,49,50,51,84,178,48,114,240,112,177,114,177,240,115,113,49,241,112,112,48,176,179,178,51,176,48,49,3,85,255,99,248,253,247,15,195,247,159,191,25,30,191,126,253,
  53373. 71,74,76,200,66,75,197,119,138,168,144,160,150,168,0,183,160,152,32,15,175,188,184,32,199,175,191,127,25,214,31,184,120,247,236,209,253,159,0,2,136,133,95,70,93,74,88,80,196,83,69,66,130,149,9,104,219,
  53374. 151,31,191,193,150,194,146,6,136,102,102,98,100,16,227,231,103,16,23,210,230,101,101,102,100,248,255,143,137,225,223,63,6,6,22,102,38,134,239,191,126,49,220,123,241,134,225,227,247,175,64,7,252,101,96,
  53375. 97,249,207,192,193,198,200,160,171,34,192,108,165,235,104,42,204,207,101,42,194,199,197,192,199,201,198,192,197,193,202,192,198,202,194,176,247,194,3,134,155,183,110,61,188,127,124,221,19,128,0,92,146,
  53376. 49,14,64,64,16,69,63,153,85,16,52,18,74,71,112,6,87,119,0,165,160,86,138,32,172,216,29,49,182,84,253,169,94,94,230,127,17,87,133,34,146,174,3,88,126,240,219,164,147,113,31,145,244,152,112,179,211,130,
  53377. 34,31,203,113,162,233,6,36,49,163,174,74,124,140,60,141,144,165,161,220,228,25,3,24,105,255,17,168,101,1,139,245,188,93,104,251,73,239,235,50,90,189,111,175,0,98,249,254,254,249,175,239,223,190,126,6,
  53378. 5,27,19,47,90,170,102,0,249,158,129,129,141,133,25,228,20,6,38,38,72,74,7,185,243,243,247,239,12,23,31,60,98,228,231,253,207,144,227,107,206,32,202,199,193,240,249,251,127,134,95,191,255,49,124,249,250,
  53379. 159,225,237,239,95,12,63,127,1,35,229,31,194,71,32,71,63,123,251,245,223,197,27,183,159,189,187,178,103,61,80,232,59,64,0,177,48,252,5,134,225,255,191,223,126,254,250,13,182,132,1,41,167,176,3,53,128,
  53380. 188,254,226,253,103,96,212,252,96,120,247,249,203,255,79,223,191,254,255,250,235,199,191,239,63,191,255,87,145,17,100,73,116,181,100,252,249,243,63,195,149,123,223,193,14,132,101,55,96,52,3,125,255,15,
  53381. 204,254,15,132,160,232,253,13,20,124,248,226,227,223,23,207,30,221,120,119,255,226,109,160,210,31,0,1,196,242,231,219,135,175,140,255,126,190,7,197,37,35,19,34,216,65,248,211,143,111,255,79,223,121,240,
  53382. 255,211,183,79,76,220,156,172,12,236,204,140,140,252,124,28,140,250,226,82,140,106,82,34,140,124,156,156,12,175,222,253,1,90,4,137,162,63,127,33,161,6,178,242,215,239,255,224,160,255,15,198,12,64,7,48,
  53383. 128,211,200,253,151,111,254,254,248,240,236,44,80,217,71,80,246,4,8,32,160,31,255,255,100,102,248,243,238,199,159,63,16,221,16,19,128,248,31,195,181,199,207,254,255,253,247,133,49,212,78,27,104,8,11,40,
  53384. 94,25,184,216,89,129,108,38,70,144,242,183,31,17,105,230,63,148,248,15,97,49,252,248,249,15,20,85,72,105,9,148,187,254,49,220,127,254,242,207,243,75,135,14,128,130,31,84,64,1,4,16,203,247,143,175,127,
  53385. 48,253,254,246,234,7,48,206,96,137,13,4,64,65,248,234,195,7,6,7,3,57,70,33,46,97,134,111,63,254,50,252,5,250,244,51,216,103,255,192,185,0,150,91,80,44,135,242,127,253,129,164,23,24,96,102,250,207,112,
  53386. 255,213,219,255,247,31,63,188,251,246,201,173,199,176,2,13,32,128,88,62,188,121,241,243,211,231,207,31,126,2,147,236,63,168,6,144,193,223,190,255,254,207,198,198,192,40,35,44,206,240,252,205,79,6,132,
  53387. 223,24,224,150,32,251,28,25,128,211,29,19,170,24,51,48,88,111,61,127,206,248,254,245,179,139,192,18,247,219,239,239,95,192,249,9,32,128,88,126,124,249,248,231,203,183,111,159,128,33,240,15,24,68,160,180,
  53388. 2,204,223,140,12,111,63,127,102,16,228,229,4,6,53,35,195,31,176,119,25,112,3,70,84,55,0,203,50,112,33,134,108,249,103,160,7,159,189,126,253,235,235,227,203,7,255,255,251,247,13,86,63,0,4,16,168,46,248,
  53389. 199,250,231,243,235,159,191,126,254,248,245,251,47,23,11,51,51,48,184,152,24,94,127,250,248,95,68,136,151,241,243,55,96,208,51,160,218,255,31,139,27,144,197,254,98,201,202,79,223,124,96,120,245,232,250,
  53390. 185,119,143,174,95,250,243,243,219,119,152,60,64,0,129,2,234,223,183,215,15,95,48,254,255,253,3,146,109,192,229,5,195,135,47,159,25,248,184,121,24,126,0,227,29,88,240,49,252,101,36,14,255,1,90,249,7,156,
  53391. 222,17,24,24,164,12,207,223,189,99,248,250,252,230,97,96,229,245,2,104,231,111,152,3,0,2,8,228,128,191,15,239,220,120,255,255,223,159,47,160,116,0,42,44,222,124,250,244,239,207,255,63,12,236,108,236,64,
  53392. 67,65,81,0,52,244,63,113,248,47,52,10,96,14,98,2,230,191,119,223,127,48,60,121,254,248,235,151,55,207,46,1,163,252,35,114,128,1,4,16,40,10,254,191,121,249,252,199,175,159,63,191,254,2,230,45,118,22,22,
  53393. 134,219,207,94,252,231,224,100,103,250,247,15,148,32,64,85,12,34,14,254,227,72,6,255,225,9,240,63,138,26,46,96,214,189,249,244,37,195,139,167,143,30,124,253,246,253,9,40,245,255,71,202,30,0,1,196,2,226,
  53394. 0,243,232,159,239,63,127,124,253,11,202,94,64,169,23,31,62,50,138,137,242,49,50,0,211,195,223,255,80,7,252,199,159,6,224,137,145,9,146,231,153,160,165,218,23,96,29,240,244,237,59,134,111,175,31,95,250,
  53395. 252,230,241,83,244,182,1,64,0,177,192,28,14,76,132,31,128,169,19,88,220,126,253,207,206,198,196,32,38,36,0,244,61,11,176,148,251,139,145,3,208,29,0,178,16,82,228,66,42,174,223,192,26,8,152,162,25,222,
  53396. 125,248,200,240,242,253,39,134,151,79,238,126,254,242,242,238,177,15,47,30,190,5,215,242,72,0,32,128,224,14,96,254,255,231,61,168,92,123,241,254,253,127,1,62,78,6,78,110,78,134,223,64,195,254,50,98,183,
  53397. 24,36,12,202,179,224,202,9,88,228,253,132,90,250,246,211,71,134,55,175,94,254,122,255,250,249,247,15,175,159,126,249,251,237,195,135,95,175,110,31,122,117,251,244,49,160,150,111,255,209,218,128,0,1,152,
  53398. 44,183,21,0,65,32,136,110,247,254,255,243,122,9,187,64,105,174,74,22,138,25,173,80,208,194,188,238,156,151,217,217,15,32,182,197,37,83,201,4,31,243,178,169,232,242,214,224,223,252,103,175,35,85,1,41,129,
  53399. 228,148,142,8,214,30,32,149,6,161,204,109,182,53,236,184,156,78,142,147,195,153,89,35,198,3,87,166,249,220,227,198,59,218,48,252,223,185,111,30,1,132,228,128,127,31,222,124,248,248,27,24,152,28,60,220,
  53400. 220,12,44,172,172,224,224,103,5,102,98,144,133,160,236,244,229,231,47,134,239,223,127,49,188,121,251,158,225,241,179,103,12,31,223,189,254,251,227,221,139,55,191,62,188,120,246,235,205,189,59,207,238,
  53401. 94,58,241,228,254,109,144,101,159,128,248,51,40,9,32,97,80,217,255,15,221,1,0,1,4,143,130,207,159,191,126,252,246,234,213,111,94,126,94,118,73,94,9,198,127,64,223,126,252,246,147,225,243,215,239,12,223,
  53402. 128,229,198,251,15,239,24,62,189,126,249,227,203,171,135,47,63,189,122,252,228,235,155,199,247,95,63,188,118,227,197,227,123,247,127,255,250,249,30,104,198,7,32,126,11,181,252,7,212,183,160,4,247,7,155,
  53403. 197,48,0,16,64,112,7,60,121,241,238,189,16,207,15,134,63,63,216,25,95,125,248,198,112,227,241,27,134,15,239,223,50,124,126,245,228,253,143,55,143,158,191,123,116,237,226,171,135,55,175,126,253,252,225,
  53404. 229,183,47,159,95,254,253,245,227,253,175,159,223,223,193,124,7,181,20,84,105,252,70,143,103,124,0,32,128,224,14,224,102,253,251,81,144,253,223,235,167,207,30,254,124,127,231,252,155,143,175,159,188,250,
  53405. 246,254,249,125,96,60,62,248,250,233,253,147,119,207,238,221,6,150,214,175,129,106,191,130,18,19,146,133,120,125,72,8,0,4,16,34,27,190,121,112,251,3,211,159,69,143,110,223,229,120,255,232,230,221,215,
  53406. 79,239,62,4,102,203,207,72,241,9,11,218,63,72,89,137,20,207,98,100,93,16,0,8,32,70,144,1,64,14,168,209,199,7,196,194,160,166,27,212,135,95,96,65,10,173,95,254,34,219,6,51,128,88,7,96,235,21,129,0,64,0,
  53407. 193,28,192,8,174,53,33,152,1,155,133,184,12,196,165,4,151,133,232,0,32,192,0,151,97,210,163,246,134,208,52,0,0,0,0,73,69,78,68,174,66,96,130,0,0};
  53408. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53409. }
  53410. const Image LookAndFeel::getDefaultDocumentFileImage()
  53411. {
  53412. static const unsigned char fileicon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,244,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  53413. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,4,99,73,68,65,84,120,218,98,252,255,255,63,3,12,48,50,50,50,1,
  53414. 169,127,200,98,148,2,160,153,204,64,243,254,226,146,7,8,32,22,52,203,255,107,233,233,91,76,93,176,184,232,239,239,95,127,24,40,112,8,19,51,203,255,179,23,175,108,1,90,190,28,104,54,43,80,232,207,127,44,
  53415. 62,3,8,32,6,144,24,84,156,25,132,189,252,3,146,255,83,9,220,127,254,242,134,162,138,170,10,208,92,144,3,152,97,118,33,99,128,0,98,66,114,11,200,1,92,255,254,252,225,32,215,215,32,127,64,240,127,80,60,
  53416. 50,40,72,136,169,47,95,179,118,130,136,148,140,0,40,80,128,33,193,136,174,7,32,128,144,29,192,8,117,41,59,209,22,66,241,191,255,16,12,244,19,195,63,48,134,240,255,0,9,115,125,93,239,252,130,130,108,168,
  53417. 249,44,232,102,0,4,16,19,22,62,51,33,11,255,195,44,4,211,255,25,96,16,33,6,117,24,56,226,25,24,202,139,10,75,226,51,115,66,160,105,13,197,17,0,1,196,68,172,79,255,33,91,206,192,192,128,176,22,17,10,200,
  53418. 234,32,161,240,31,24,10,255,24,152,153,153,184,39,244,247,117,107,234,234,105,131,66,1,154,224,193,0,32,128,240,58,0,22,180,255,144,18,13,40,136,33,113,140,36,255,15,17,26,48,12,81,15,145,255,254,251,
  53419. 31,131,0,59,171,84,81,73,105,33,208,216,191,200,161,12,16,64,44,248,131,251,63,10,31,198,253,143,38,6,83,7,11,33,228,232,2,123,4,202,226,228,96,151,132,166,49,144,35,126,131,196,0,2,136,5,103,60,51,252,
  53420. 71,49,12,213,130,255,168,226,232,150,254,255,15,143,6,80,202,3,133,16,200,198,63,127,193,229,17,39,16,127,135,217,7,16,64,88,67,0,28,143,255,25,225,46,135,249,18,155,133,240,178,4,205,145,8,62,52,186,
  53421. 32,234,152,160,118,194,179,35,64,0,177,96,11,123,144,236,95,104,92,162,228,113,36,11,81,125,140,112,56,186,131,96,226,176,172,137,148,229,193,0,32,128,88,112,167,248,255,112,223,48,34,165,110,6,124,190,
  53422. 253,143,61,106,192,9,19,73,28,25,0,4,16,206,40,248,251,15,45,104,209,130,21,51,222,145,18,238,127,180,68,8,244,250,95,164,16,66,6,0,1,196,130,45,253,195,12,250,135,53,206,255,195,131,18,213,98,236,81,
  53423. 243,31,154,11,144,115,8,50,0,8,32,156,81,0,203,227,12,80,223,98,230,4,68,72,96,38,78,84,11,65,9,250,47,146,3,145,1,64,0,97,117,192,95,112,34,68,138,130,255,176,224,251,143,226,51,6,6,68,29,192,136,20,
  53424. 77,200,69,54,35,3,36,49,255,69,77,132,112,0,16,64,44,56,139,94,36,7,96,102,59,164,108,249,31,181,82,98,64,203,174,255,144,234,142,127,88,146,33,64,0,97,205,134,240,120,67,75,76,136,224,198,140,22,6,44,
  53425. 142,66,201,41,255,177,231,2,128,0,194,25,5,255,254,161,134,192,127,6,28,229,0,129,242,1,150,56,33,81,138,209,28,96,0,8,32,172,81,0,78,3,104,190,68,182,224,31,146,197,224,56,6,146,140,176,202,135,17,169,
  53426. 96,130,40,64,56,0,139,93,0,1,132,61,10,64,248,31,106,156,162,199,55,204,65,255,144,178,38,74,84,252,71,51,239,63,246,68,8,16,64,44,216,74,1,88,217,13,203,191,32,1,80,58,7,133,224,127,6,68,114,6,241,65,
  53427. 81,197,8,101,255,71,114,33,92,237,127,228,52,128,233,2,128,0,98,193,149,3,64,117,193,255,127,255,81,75,191,127,168,5,18,136,255,31,45,161,49,32,151,134,72,252,127,12,216,203,98,128,0,98,193,210,144,135,
  53428. 248,30,201,242,127,208,252,140,145,27,160,113,206,136,148,197,192,121,159,17,53,184,225,149,17,22,23,0,4,16,11,182,150,237,63,168,207,96,142,248,143,163,72,6,203,253,67,13,61,6,104,14,66,46,17,254,65,
  53429. 19,40,182,16,0,8,32,22,108,109,235,255,176,234,24,35,79,255,199,222,30,64,81,135,90,35,194,211,4,142,92,0,16,64,88,29,0,107,7,254,251,247,31,53,78,241,54,207,80,29,135,209,96,249,143,189,46,0,8,32,116,
  53430. 7,252,101,102,103,103,228,103,99,96,248,193,198,137,53,248,49,125,204,128,225,227,255,88,18,54,47,176,25,202,205,195,205,6,109,11,194,149,0,4,16,35,204,85,208,254,27,159,128,176,176,142,166,182,142,21,
  53431. 48,4,248,129,41,143,13,217,16,70,52,95,147,0,254,0,187,69,95,223,188,122,125,235,206,141,107,7,129,252,247,64,123,193,237,66,128,0,66,118,0,168,189,198,3,196,252,32,135,64,105,54,228,230,19,185,29,100,
  53432. 168,175,191,0,241,7,32,254,4,196,159,129,246,254,2,73,2,4,16,11,90,72,125,135,210,63,161,138,153,169,212,75,255,15,117,196,15,40,134,119,215,1,2,12,0,187,0,132,247,216,161,197,124,0,0,0,0,73,69,78,68,
  53433. 174,66,96,130,0,0};
  53434. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53435. }
  53436. void LookAndFeel::playAlertSound()
  53437. {
  53438. PlatformUtilities::beep();
  53439. }
  53440. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53441. {
  53442. g.setColour (Colours::white.withAlpha (0.7f));
  53443. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53444. g.setColour (Colours::black.withAlpha (0.2f));
  53445. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53446. const int totalBlocks = 7;
  53447. const int numBlocks = roundToInt (totalBlocks * level);
  53448. const float w = (width - 6.0f) / (float) totalBlocks;
  53449. for (int i = 0; i < totalBlocks; ++i)
  53450. {
  53451. if (i >= numBlocks)
  53452. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53453. else
  53454. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53455. : Colours::red);
  53456. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53457. }
  53458. }
  53459. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53460. {
  53461. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53462. if (keyDescription.isNotEmpty())
  53463. {
  53464. if (button.isEnabled())
  53465. {
  53466. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53467. g.fillAll (textColour.withAlpha (alpha));
  53468. g.setOpacity (0.3f);
  53469. g.drawBevel (0, 0, width, height, 2);
  53470. }
  53471. g.setColour (textColour);
  53472. g.setFont (height * 0.6f);
  53473. g.drawFittedText (keyDescription,
  53474. 3, 0, width - 6, height,
  53475. Justification::centred, 1);
  53476. }
  53477. else
  53478. {
  53479. const float thickness = 7.0f;
  53480. const float indent = 22.0f;
  53481. Path p;
  53482. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53483. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53484. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53485. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53486. p.setUsingNonZeroWinding (false);
  53487. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53488. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53489. }
  53490. if (button.hasKeyboardFocus (false))
  53491. {
  53492. g.setColour (textColour.withAlpha (0.4f));
  53493. g.drawRect (0, 0, width, height);
  53494. }
  53495. }
  53496. static void createRoundedPath (Path& p,
  53497. const float x, const float y,
  53498. const float w, const float h,
  53499. const float cs,
  53500. const bool curveTopLeft, const bool curveTopRight,
  53501. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53502. {
  53503. const float cs2 = 2.0f * cs;
  53504. if (curveTopLeft)
  53505. {
  53506. p.startNewSubPath (x, y + cs);
  53507. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53508. }
  53509. else
  53510. {
  53511. p.startNewSubPath (x, y);
  53512. }
  53513. if (curveTopRight)
  53514. {
  53515. p.lineTo (x + w - cs, y);
  53516. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53517. }
  53518. else
  53519. {
  53520. p.lineTo (x + w, y);
  53521. }
  53522. if (curveBottomRight)
  53523. {
  53524. p.lineTo (x + w, y + h - cs);
  53525. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53526. }
  53527. else
  53528. {
  53529. p.lineTo (x + w, y + h);
  53530. }
  53531. if (curveBottomLeft)
  53532. {
  53533. p.lineTo (x + cs, y + h);
  53534. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53535. }
  53536. else
  53537. {
  53538. p.lineTo (x, y + h);
  53539. }
  53540. p.closeSubPath();
  53541. }
  53542. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53543. float x, float y, float w, float h,
  53544. float maxCornerSize,
  53545. const Colour& baseColour,
  53546. const float strokeWidth,
  53547. const bool flatOnLeft,
  53548. const bool flatOnRight,
  53549. const bool flatOnTop,
  53550. const bool flatOnBottom) throw()
  53551. {
  53552. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53553. return;
  53554. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53555. Path outline;
  53556. createRoundedPath (outline, x, y, w, h, cs,
  53557. ! (flatOnLeft || flatOnTop),
  53558. ! (flatOnRight || flatOnTop),
  53559. ! (flatOnLeft || flatOnBottom),
  53560. ! (flatOnRight || flatOnBottom));
  53561. ColourGradient cg (baseColour, 0.0f, y,
  53562. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53563. false);
  53564. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53565. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53566. g.setGradientFill (cg);
  53567. g.fillPath (outline);
  53568. g.setColour (Colour (0x80000000));
  53569. g.strokePath (outline, PathStrokeType (strokeWidth));
  53570. }
  53571. void LookAndFeel::drawGlassSphere (Graphics& g,
  53572. const float x, const float y,
  53573. const float diameter,
  53574. const Colour& colour,
  53575. const float outlineThickness) throw()
  53576. {
  53577. if (diameter <= outlineThickness)
  53578. return;
  53579. Path p;
  53580. p.addEllipse (x, y, diameter, diameter);
  53581. {
  53582. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53583. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53584. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53585. g.setGradientFill (cg);
  53586. g.fillPath (p);
  53587. }
  53588. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53589. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53590. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53591. ColourGradient cg (Colours::transparentBlack,
  53592. x + diameter * 0.5f, y + diameter * 0.5f,
  53593. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53594. x, y + diameter * 0.5f, true);
  53595. cg.addColour (0.7, Colours::transparentBlack);
  53596. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53597. g.setGradientFill (cg);
  53598. g.fillPath (p);
  53599. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53600. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53601. }
  53602. void LookAndFeel::drawGlassPointer (Graphics& g,
  53603. const float x, const float y,
  53604. const float diameter,
  53605. const Colour& colour, const float outlineThickness,
  53606. const int direction) throw()
  53607. {
  53608. if (diameter <= outlineThickness)
  53609. return;
  53610. Path p;
  53611. p.startNewSubPath (x + diameter * 0.5f, y);
  53612. p.lineTo (x + diameter, y + diameter * 0.6f);
  53613. p.lineTo (x + diameter, y + diameter);
  53614. p.lineTo (x, y + diameter);
  53615. p.lineTo (x, y + diameter * 0.6f);
  53616. p.closeSubPath();
  53617. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53618. {
  53619. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53620. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53621. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53622. g.setGradientFill (cg);
  53623. g.fillPath (p);
  53624. }
  53625. ColourGradient cg (Colours::transparentBlack,
  53626. x + diameter * 0.5f, y + diameter * 0.5f,
  53627. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53628. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53629. cg.addColour (0.5, Colours::transparentBlack);
  53630. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53631. g.setGradientFill (cg);
  53632. g.fillPath (p);
  53633. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53634. g.strokePath (p, PathStrokeType (outlineThickness));
  53635. }
  53636. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53637. const float x, const float y,
  53638. const float width, const float height,
  53639. const Colour& colour,
  53640. const float outlineThickness,
  53641. const float cornerSize,
  53642. const bool flatOnLeft,
  53643. const bool flatOnRight,
  53644. const bool flatOnTop,
  53645. const bool flatOnBottom) throw()
  53646. {
  53647. if (width <= outlineThickness || height <= outlineThickness)
  53648. return;
  53649. const int intX = (int) x;
  53650. const int intY = (int) y;
  53651. const int intW = (int) width;
  53652. const int intH = (int) height;
  53653. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53654. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53655. const int intEdge = (int) edgeBlurRadius;
  53656. Path outline;
  53657. createRoundedPath (outline, x, y, width, height, cs,
  53658. ! (flatOnLeft || flatOnTop),
  53659. ! (flatOnRight || flatOnTop),
  53660. ! (flatOnLeft || flatOnBottom),
  53661. ! (flatOnRight || flatOnBottom));
  53662. {
  53663. ColourGradient cg (colour.darker (0.2f), 0, y,
  53664. colour.darker (0.2f), 0, y + height, false);
  53665. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53666. cg.addColour (0.4, colour);
  53667. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53668. g.setGradientFill (cg);
  53669. g.fillPath (outline);
  53670. }
  53671. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53672. colour.darker (0.2f), x, y + height * 0.5f, true);
  53673. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53674. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53675. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53676. {
  53677. g.saveState();
  53678. g.setGradientFill (cg);
  53679. g.reduceClipRegion (intX, intY, intEdge, intH);
  53680. g.fillPath (outline);
  53681. g.restoreState();
  53682. }
  53683. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53684. {
  53685. cg.point1.setX (x + width - edgeBlurRadius);
  53686. cg.point2.setX (x + width);
  53687. g.saveState();
  53688. g.setGradientFill (cg);
  53689. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53690. g.fillPath (outline);
  53691. g.restoreState();
  53692. }
  53693. {
  53694. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53695. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53696. Path highlight;
  53697. createRoundedPath (highlight,
  53698. x + leftIndent,
  53699. y + cs * 0.1f,
  53700. width - (leftIndent + rightIndent),
  53701. height * 0.4f, cs * 0.4f,
  53702. ! (flatOnLeft || flatOnTop),
  53703. ! (flatOnRight || flatOnTop),
  53704. ! (flatOnLeft || flatOnBottom),
  53705. ! (flatOnRight || flatOnBottom));
  53706. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53707. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53708. g.fillPath (highlight);
  53709. }
  53710. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53711. g.strokePath (outline, PathStrokeType (outlineThickness));
  53712. }
  53713. END_JUCE_NAMESPACE
  53714. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53715. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53716. BEGIN_JUCE_NAMESPACE
  53717. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53718. {
  53719. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53720. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53721. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53722. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53723. setColour (Slider::thumbColourId, Colours::white);
  53724. setColour (Slider::trackColourId, Colour (0x7f000000));
  53725. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53726. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53727. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53728. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53729. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53730. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53731. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53732. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53733. }
  53734. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53735. {
  53736. }
  53737. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53738. Button& button,
  53739. const Colour& backgroundColour,
  53740. bool isMouseOverButton,
  53741. bool isButtonDown)
  53742. {
  53743. const int width = button.getWidth();
  53744. const int height = button.getHeight();
  53745. const float indent = 2.0f;
  53746. const int cornerSize = jmin (roundToInt (width * 0.4f),
  53747. roundToInt (height * 0.4f));
  53748. Path p;
  53749. p.addRoundedRectangle (indent, indent,
  53750. width - indent * 2.0f,
  53751. height - indent * 2.0f,
  53752. (float) cornerSize);
  53753. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  53754. if (isMouseOverButton)
  53755. {
  53756. if (isButtonDown)
  53757. bc = bc.brighter();
  53758. else if (bc.getBrightness() > 0.5f)
  53759. bc = bc.darker (0.1f);
  53760. else
  53761. bc = bc.brighter (0.1f);
  53762. }
  53763. g.setColour (bc);
  53764. g.fillPath (p);
  53765. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  53766. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  53767. }
  53768. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  53769. Component& /*component*/,
  53770. float x, float y, float w, float h,
  53771. const bool ticked,
  53772. const bool isEnabled,
  53773. const bool /*isMouseOverButton*/,
  53774. const bool isButtonDown)
  53775. {
  53776. Path box;
  53777. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  53778. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  53779. : Colours::lightgrey.withAlpha (0.1f));
  53780. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  53781. g.fillPath (box, trans);
  53782. g.setColour (Colours::black.withAlpha (0.6f));
  53783. g.strokePath (box, PathStrokeType (0.9f), trans);
  53784. if (ticked)
  53785. {
  53786. Path tick;
  53787. tick.startNewSubPath (1.5f, 3.0f);
  53788. tick.lineTo (3.0f, 6.0f);
  53789. tick.lineTo (6.0f, 0.0f);
  53790. g.setColour (isEnabled ? Colours::black : Colours::grey);
  53791. g.strokePath (tick, PathStrokeType (2.5f), trans);
  53792. }
  53793. }
  53794. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  53795. ToggleButton& button,
  53796. bool isMouseOverButton,
  53797. bool isButtonDown)
  53798. {
  53799. if (button.hasKeyboardFocus (true))
  53800. {
  53801. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  53802. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  53803. }
  53804. const int tickWidth = jmin (20, button.getHeight() - 4);
  53805. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  53806. (float) tickWidth, (float) tickWidth,
  53807. button.getToggleState(),
  53808. button.isEnabled(),
  53809. isMouseOverButton,
  53810. isButtonDown);
  53811. g.setColour (button.findColour (ToggleButton::textColourId));
  53812. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  53813. if (! button.isEnabled())
  53814. g.setOpacity (0.5f);
  53815. const int textX = tickWidth + 5;
  53816. g.drawFittedText (button.getButtonText(),
  53817. textX, 4,
  53818. button.getWidth() - textX - 2, button.getHeight() - 8,
  53819. Justification::centredLeft, 10);
  53820. }
  53821. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  53822. int width, int height,
  53823. double progress, const String& textToShow)
  53824. {
  53825. if (progress < 0 || progress >= 1.0)
  53826. {
  53827. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  53828. }
  53829. else
  53830. {
  53831. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  53832. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  53833. g.fillAll (background);
  53834. g.setColour (foreground);
  53835. g.fillRect (1, 1,
  53836. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  53837. height - 2);
  53838. if (textToShow.isNotEmpty())
  53839. {
  53840. g.setColour (Colour::contrasting (background, foreground));
  53841. g.setFont (height * 0.6f);
  53842. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  53843. }
  53844. }
  53845. }
  53846. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  53847. ScrollBar& bar,
  53848. int width, int height,
  53849. int buttonDirection,
  53850. bool isScrollbarVertical,
  53851. bool isMouseOverButton,
  53852. bool isButtonDown)
  53853. {
  53854. if (isScrollbarVertical)
  53855. width -= 2;
  53856. else
  53857. height -= 2;
  53858. Path p;
  53859. if (buttonDirection == 0)
  53860. p.addTriangle (width * 0.5f, height * 0.2f,
  53861. width * 0.1f, height * 0.7f,
  53862. width * 0.9f, height * 0.7f);
  53863. else if (buttonDirection == 1)
  53864. p.addTriangle (width * 0.8f, height * 0.5f,
  53865. width * 0.3f, height * 0.1f,
  53866. width * 0.3f, height * 0.9f);
  53867. else if (buttonDirection == 2)
  53868. p.addTriangle (width * 0.5f, height * 0.8f,
  53869. width * 0.1f, height * 0.3f,
  53870. width * 0.9f, height * 0.3f);
  53871. else if (buttonDirection == 3)
  53872. p.addTriangle (width * 0.2f, height * 0.5f,
  53873. width * 0.7f, height * 0.1f,
  53874. width * 0.7f, height * 0.9f);
  53875. if (isButtonDown)
  53876. g.setColour (Colours::white);
  53877. else if (isMouseOverButton)
  53878. g.setColour (Colours::white.withAlpha (0.7f));
  53879. else
  53880. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  53881. g.fillPath (p);
  53882. g.setColour (Colours::black.withAlpha (0.5f));
  53883. g.strokePath (p, PathStrokeType (0.5f));
  53884. }
  53885. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  53886. ScrollBar& bar,
  53887. int x, int y,
  53888. int width, int height,
  53889. bool isScrollbarVertical,
  53890. int thumbStartPosition,
  53891. int thumbSize,
  53892. bool isMouseOver,
  53893. bool isMouseDown)
  53894. {
  53895. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  53896. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53897. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  53898. if (thumbSize > 0.0f)
  53899. {
  53900. Rectangle<int> thumb;
  53901. if (isScrollbarVertical)
  53902. {
  53903. width -= 2;
  53904. g.fillRect (x + roundToInt (width * 0.35f), y,
  53905. roundToInt (width * 0.3f), height);
  53906. thumb.setBounds (x + 1, thumbStartPosition,
  53907. width - 2, thumbSize);
  53908. }
  53909. else
  53910. {
  53911. height -= 2;
  53912. g.fillRect (x, y + roundToInt (height * 0.35f),
  53913. width, roundToInt (height * 0.3f));
  53914. thumb.setBounds (thumbStartPosition, y + 1,
  53915. thumbSize, height - 2);
  53916. }
  53917. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53918. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  53919. g.fillRect (thumb);
  53920. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  53921. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  53922. if (thumbSize > 16)
  53923. {
  53924. for (int i = 3; --i >= 0;)
  53925. {
  53926. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  53927. g.setColour (Colours::black.withAlpha (0.15f));
  53928. if (isScrollbarVertical)
  53929. {
  53930. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  53931. g.setColour (Colours::white.withAlpha (0.15f));
  53932. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  53933. }
  53934. else
  53935. {
  53936. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  53937. g.setColour (Colours::white.withAlpha (0.15f));
  53938. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  53939. }
  53940. }
  53941. }
  53942. }
  53943. }
  53944. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  53945. {
  53946. return &scrollbarShadow;
  53947. }
  53948. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53949. {
  53950. g.fillAll (findColour (PopupMenu::backgroundColourId));
  53951. g.setColour (Colours::black.withAlpha (0.6f));
  53952. g.drawRect (0, 0, width, height);
  53953. }
  53954. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  53955. bool, MenuBarComponent& menuBar)
  53956. {
  53957. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  53958. }
  53959. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53960. {
  53961. if (textEditor.isEnabled())
  53962. {
  53963. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53964. g.drawRect (0, 0, width, height);
  53965. }
  53966. }
  53967. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53968. const bool isButtonDown,
  53969. int buttonX, int buttonY,
  53970. int buttonW, int buttonH,
  53971. ComboBox& box)
  53972. {
  53973. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53974. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  53975. : ComboBox::backgroundColourId));
  53976. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  53977. g.setColour (box.findColour (ComboBox::outlineColourId));
  53978. g.drawRect (0, 0, width, height);
  53979. const float arrowX = 0.2f;
  53980. const float arrowH = 0.3f;
  53981. if (box.isEnabled())
  53982. {
  53983. Path p;
  53984. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53985. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53986. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53987. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53988. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53989. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53990. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  53991. : ComboBox::buttonColourId));
  53992. g.fillPath (p);
  53993. }
  53994. }
  53995. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  53996. {
  53997. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  53998. f.setHorizontalScale (0.9f);
  53999. return f;
  54000. }
  54001. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54002. {
  54003. Path p;
  54004. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54005. g.setColour (fill);
  54006. g.fillPath (p);
  54007. g.setColour (outline);
  54008. g.strokePath (p, PathStrokeType (0.3f));
  54009. }
  54010. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54011. int x, int y,
  54012. int w, int h,
  54013. float sliderPos,
  54014. float minSliderPos,
  54015. float maxSliderPos,
  54016. const Slider::SliderStyle style,
  54017. Slider& slider)
  54018. {
  54019. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54020. if (style == Slider::LinearBar)
  54021. {
  54022. g.setColour (slider.findColour (Slider::thumbColourId));
  54023. g.fillRect (x, y, (int) sliderPos - x, h);
  54024. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54025. g.drawRect (x, y, (int) sliderPos - x, h);
  54026. }
  54027. else
  54028. {
  54029. g.setColour (slider.findColour (Slider::trackColourId)
  54030. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54031. if (slider.isHorizontal())
  54032. {
  54033. g.fillRect (x, y + roundToInt (h * 0.6f),
  54034. w, roundToInt (h * 0.2f));
  54035. }
  54036. else
  54037. {
  54038. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54039. jmin (4, roundToInt (w * 0.2f)), h);
  54040. }
  54041. float alpha = 0.35f;
  54042. if (slider.isEnabled())
  54043. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54044. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54045. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54046. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54047. {
  54048. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54049. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54050. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54051. fill, outline);
  54052. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54053. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54054. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54055. fill, outline);
  54056. }
  54057. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54058. {
  54059. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54060. minSliderPos - 7.0f, y + h * 0.9f ,
  54061. minSliderPos, y + h * 0.9f,
  54062. fill, outline);
  54063. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54064. maxSliderPos, y + h * 0.9f,
  54065. maxSliderPos + 7.0f, y + h * 0.9f,
  54066. fill, outline);
  54067. }
  54068. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54069. {
  54070. drawTriangle (g, sliderPos, y + h * 0.9f,
  54071. sliderPos - 7.0f, y + h * 0.2f,
  54072. sliderPos + 7.0f, y + h * 0.2f,
  54073. fill, outline);
  54074. }
  54075. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54076. {
  54077. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54078. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54079. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54080. fill, outline);
  54081. }
  54082. }
  54083. }
  54084. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54085. {
  54086. if (isIncrement)
  54087. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54088. else
  54089. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54090. }
  54091. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54092. {
  54093. return &scrollbarShadow;
  54094. }
  54095. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54096. {
  54097. return 8;
  54098. }
  54099. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54100. int w, int h,
  54101. bool isMouseOver,
  54102. bool isMouseDragging)
  54103. {
  54104. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54105. : Colours::darkgrey);
  54106. const float lineThickness = jmin (w, h) * 0.1f;
  54107. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54108. {
  54109. g.drawLine (w * i,
  54110. h + 1.0f,
  54111. w + 1.0f,
  54112. h * i,
  54113. lineThickness);
  54114. }
  54115. }
  54116. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54117. {
  54118. Path shape;
  54119. if (buttonType == DocumentWindow::closeButton)
  54120. {
  54121. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54122. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54123. ShapeButton* const b = new ShapeButton ("close",
  54124. Colour (0x7fff3333),
  54125. Colour (0xd7ff3333),
  54126. Colour (0xf7ff3333));
  54127. b->setShape (shape, true, true, true);
  54128. return b;
  54129. }
  54130. else if (buttonType == DocumentWindow::minimiseButton)
  54131. {
  54132. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54133. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54134. DrawablePath dp;
  54135. dp.setPath (shape);
  54136. dp.setFill (Colours::black.withAlpha (0.3f));
  54137. b->setImages (&dp);
  54138. return b;
  54139. }
  54140. else if (buttonType == DocumentWindow::maximiseButton)
  54141. {
  54142. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54143. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54144. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54145. DrawablePath dp;
  54146. dp.setPath (shape);
  54147. dp.setFill (Colours::black.withAlpha (0.3f));
  54148. b->setImages (&dp);
  54149. return b;
  54150. }
  54151. jassertfalse;
  54152. return 0;
  54153. }
  54154. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54155. int titleBarX,
  54156. int titleBarY,
  54157. int titleBarW,
  54158. int titleBarH,
  54159. Button* minimiseButton,
  54160. Button* maximiseButton,
  54161. Button* closeButton,
  54162. bool positionTitleBarButtonsOnLeft)
  54163. {
  54164. titleBarY += titleBarH / 8;
  54165. titleBarH -= titleBarH / 4;
  54166. const int buttonW = titleBarH;
  54167. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54168. : titleBarX + titleBarW - buttonW - 4;
  54169. if (closeButton != 0)
  54170. {
  54171. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54172. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54173. : -(buttonW + buttonW / 5);
  54174. }
  54175. if (positionTitleBarButtonsOnLeft)
  54176. swapVariables (minimiseButton, maximiseButton);
  54177. if (maximiseButton != 0)
  54178. {
  54179. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54180. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54181. }
  54182. if (minimiseButton != 0)
  54183. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54184. }
  54185. END_JUCE_NAMESPACE
  54186. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54187. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54188. BEGIN_JUCE_NAMESPACE
  54189. class DummyMenuComponent : public Component
  54190. {
  54191. DummyMenuComponent (const DummyMenuComponent&);
  54192. DummyMenuComponent& operator= (const DummyMenuComponent&);
  54193. public:
  54194. DummyMenuComponent() {}
  54195. ~DummyMenuComponent() {}
  54196. void inputAttemptWhenModal()
  54197. {
  54198. exitModalState (0);
  54199. }
  54200. };
  54201. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54202. : model (0),
  54203. itemUnderMouse (-1),
  54204. currentPopupIndex (-1),
  54205. indexToShowAgain (-1),
  54206. lastMouseX (0),
  54207. lastMouseY (0),
  54208. inModalState (false)
  54209. {
  54210. setRepaintsOnMouseActivity (true);
  54211. setWantsKeyboardFocus (false);
  54212. setMouseClickGrabsKeyboardFocus (false);
  54213. setModel (model_);
  54214. }
  54215. MenuBarComponent::~MenuBarComponent()
  54216. {
  54217. setModel (0);
  54218. Desktop::getInstance().removeGlobalMouseListener (this);
  54219. currentPopup = 0;
  54220. }
  54221. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54222. {
  54223. if (model != newModel)
  54224. {
  54225. if (model != 0)
  54226. model->removeListener (this);
  54227. model = newModel;
  54228. if (model != 0)
  54229. model->addListener (this);
  54230. repaint();
  54231. menuBarItemsChanged (0);
  54232. }
  54233. }
  54234. void MenuBarComponent::paint (Graphics& g)
  54235. {
  54236. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54237. getLookAndFeel().drawMenuBarBackground (g,
  54238. getWidth(),
  54239. getHeight(),
  54240. isMouseOverBar,
  54241. *this);
  54242. if (model != 0)
  54243. {
  54244. for (int i = 0; i < menuNames.size(); ++i)
  54245. {
  54246. g.saveState();
  54247. g.setOrigin (xPositions [i], 0);
  54248. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54249. getLookAndFeel().drawMenuBarItem (g,
  54250. xPositions[i + 1] - xPositions[i],
  54251. getHeight(),
  54252. i,
  54253. menuNames[i],
  54254. i == itemUnderMouse,
  54255. i == currentPopupIndex,
  54256. isMouseOverBar,
  54257. *this);
  54258. g.restoreState();
  54259. }
  54260. }
  54261. }
  54262. void MenuBarComponent::resized()
  54263. {
  54264. xPositions.clear();
  54265. int x = 2;
  54266. xPositions.add (x);
  54267. for (int i = 0; i < menuNames.size(); ++i)
  54268. {
  54269. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54270. xPositions.add (x);
  54271. }
  54272. }
  54273. int MenuBarComponent::getItemAt (const int x, const int y)
  54274. {
  54275. for (int i = 0; i < xPositions.size(); ++i)
  54276. if (x >= xPositions[i] && x < xPositions[i + 1])
  54277. return reallyContains (x, y, true) ? i : -1;
  54278. return -1;
  54279. }
  54280. void MenuBarComponent::repaintMenuItem (int index)
  54281. {
  54282. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54283. {
  54284. const int x1 = xPositions [index];
  54285. const int x2 = xPositions [index + 1];
  54286. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54287. }
  54288. }
  54289. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54290. {
  54291. const int newItem = getItemAt (x, y);
  54292. if (itemUnderMouse != newItem)
  54293. {
  54294. repaintMenuItem (itemUnderMouse);
  54295. itemUnderMouse = newItem;
  54296. repaintMenuItem (itemUnderMouse);
  54297. }
  54298. }
  54299. void MenuBarComponent::hideCurrentMenu()
  54300. {
  54301. currentPopup = 0;
  54302. repaint();
  54303. }
  54304. void MenuBarComponent::showMenu (int index)
  54305. {
  54306. if (index != currentPopupIndex)
  54307. {
  54308. if (inModalState)
  54309. {
  54310. hideCurrentMenu();
  54311. indexToShowAgain = index;
  54312. return;
  54313. }
  54314. indexToShowAgain = -1;
  54315. currentPopupIndex = -1;
  54316. itemUnderMouse = index;
  54317. currentPopup = 0;
  54318. menuBarItemsChanged (0);
  54319. Component::SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  54320. Component::SafePointer<Component> deletionChecker (this);
  54321. enterModalState (false);
  54322. inModalState = true;
  54323. int result = 0;
  54324. ApplicationCommandManager* managerOfChosenCommand = 0;
  54325. Desktop::getInstance().addGlobalMouseListener (this);
  54326. for (;;)
  54327. {
  54328. const int x = getScreenX() + xPositions [itemUnderMouse];
  54329. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  54330. currentPopupIndex = itemUnderMouse;
  54331. indexToShowAgain = -1;
  54332. repaint();
  54333. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  54334. {
  54335. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54336. menuNames [itemUnderMouse]));
  54337. if (m.lookAndFeel == 0)
  54338. m.setLookAndFeel (&getLookAndFeel());
  54339. currentPopup = m.createMenuComponent (x, getScreenY(),
  54340. w, getHeight(),
  54341. 0, w, 0, 0,
  54342. true, this,
  54343. &managerOfChosenCommand,
  54344. this);
  54345. }
  54346. if (currentPopup == 0)
  54347. {
  54348. currentPopup = new DummyMenuComponent();
  54349. addAndMakeVisible (currentPopup);
  54350. }
  54351. currentPopup->enterModalState (false);
  54352. currentPopup->toFront (false); // need to do this after making it modal, or it could
  54353. // be stuck behind other comps that are already modal..
  54354. result = currentPopup->runModalLoop();
  54355. if (deletionChecker == 0)
  54356. return;
  54357. const int lastPopupIndex = currentPopupIndex;
  54358. currentPopup = 0;
  54359. currentPopupIndex = -1;
  54360. if (result != 0)
  54361. {
  54362. topLevelIndexClicked = lastPopupIndex;
  54363. break;
  54364. }
  54365. else if (indexToShowAgain >= 0)
  54366. {
  54367. menuBarItemsChanged (0);
  54368. repaint();
  54369. itemUnderMouse = indexToShowAgain;
  54370. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  54371. break;
  54372. }
  54373. else
  54374. {
  54375. break;
  54376. }
  54377. }
  54378. Desktop::getInstance().removeGlobalMouseListener (this);
  54379. inModalState = false;
  54380. exitModalState (0);
  54381. if (prevFocused != 0)
  54382. prevFocused->grabKeyboardFocus();
  54383. const Point<int> mousePos (getMouseXYRelative());
  54384. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54385. repaint();
  54386. if (result != 0)
  54387. {
  54388. if (managerOfChosenCommand != 0)
  54389. {
  54390. ApplicationCommandTarget::InvocationInfo info (result);
  54391. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  54392. managerOfChosenCommand->invoke (info, true);
  54393. }
  54394. postCommandMessage (result);
  54395. }
  54396. }
  54397. }
  54398. void MenuBarComponent::handleCommandMessage (int commandId)
  54399. {
  54400. if (model != 0)
  54401. model->menuItemSelected (commandId, topLevelIndexClicked);
  54402. }
  54403. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54404. {
  54405. if (e.eventComponent == this)
  54406. updateItemUnderMouse (e.x, e.y);
  54407. }
  54408. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54409. {
  54410. if (e.eventComponent == this)
  54411. updateItemUnderMouse (e.x, e.y);
  54412. }
  54413. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54414. {
  54415. if (currentPopupIndex < 0)
  54416. {
  54417. const MouseEvent e2 (e.getEventRelativeTo (this));
  54418. updateItemUnderMouse (e2.x, e2.y);
  54419. currentPopupIndex = -2;
  54420. showMenu (itemUnderMouse);
  54421. }
  54422. }
  54423. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54424. {
  54425. const MouseEvent e2 (e.getEventRelativeTo (this));
  54426. const int item = getItemAt (e2.x, e2.y);
  54427. if (item >= 0)
  54428. showMenu (item);
  54429. }
  54430. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54431. {
  54432. const MouseEvent e2 (e.getEventRelativeTo (this));
  54433. updateItemUnderMouse (e2.x, e2.y);
  54434. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (static_cast <Component*> (currentPopup)) != 0)
  54435. hideCurrentMenu();
  54436. }
  54437. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54438. {
  54439. const MouseEvent e2 (e.getEventRelativeTo (this));
  54440. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54441. {
  54442. if (currentPopupIndex >= 0)
  54443. {
  54444. const int item = getItemAt (e2.x, e2.y);
  54445. if (item >= 0)
  54446. showMenu (item);
  54447. }
  54448. else
  54449. {
  54450. updateItemUnderMouse (e2.x, e2.y);
  54451. }
  54452. lastMouseX = e2.x;
  54453. lastMouseY = e2.y;
  54454. }
  54455. }
  54456. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54457. {
  54458. bool used = false;
  54459. const int numMenus = menuNames.size();
  54460. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54461. if (key.isKeyCode (KeyPress::leftKey))
  54462. {
  54463. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54464. used = true;
  54465. }
  54466. else if (key.isKeyCode (KeyPress::rightKey))
  54467. {
  54468. showMenu ((currentIndex + 1) % numMenus);
  54469. used = true;
  54470. }
  54471. return used;
  54472. }
  54473. void MenuBarComponent::inputAttemptWhenModal()
  54474. {
  54475. hideCurrentMenu();
  54476. }
  54477. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54478. {
  54479. StringArray newNames;
  54480. if (model != 0)
  54481. newNames = model->getMenuBarNames();
  54482. if (newNames != menuNames)
  54483. {
  54484. menuNames = newNames;
  54485. repaint();
  54486. resized();
  54487. }
  54488. }
  54489. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54490. const ApplicationCommandTarget::InvocationInfo& info)
  54491. {
  54492. if (model == 0
  54493. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54494. return;
  54495. for (int i = 0; i < menuNames.size(); ++i)
  54496. {
  54497. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54498. if (menu.containsCommandItem (info.commandID))
  54499. {
  54500. itemUnderMouse = i;
  54501. repaintMenuItem (i);
  54502. startTimer (200);
  54503. break;
  54504. }
  54505. }
  54506. }
  54507. void MenuBarComponent::timerCallback()
  54508. {
  54509. stopTimer();
  54510. const Point<int> mousePos (getMouseXYRelative());
  54511. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54512. }
  54513. END_JUCE_NAMESPACE
  54514. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54515. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54516. BEGIN_JUCE_NAMESPACE
  54517. MenuBarModel::MenuBarModel() throw()
  54518. : manager (0)
  54519. {
  54520. }
  54521. MenuBarModel::~MenuBarModel()
  54522. {
  54523. setApplicationCommandManagerToWatch (0);
  54524. }
  54525. void MenuBarModel::menuItemsChanged()
  54526. {
  54527. triggerAsyncUpdate();
  54528. }
  54529. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54530. {
  54531. if (manager != newManager)
  54532. {
  54533. if (manager != 0)
  54534. manager->removeListener (this);
  54535. manager = newManager;
  54536. if (manager != 0)
  54537. manager->addListener (this);
  54538. }
  54539. }
  54540. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  54541. {
  54542. listeners.add (newListener);
  54543. }
  54544. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  54545. {
  54546. // Trying to remove a listener that isn't on the list!
  54547. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54548. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54549. jassert (listeners.contains (listenerToRemove));
  54550. listeners.remove (listenerToRemove);
  54551. }
  54552. void MenuBarModel::handleAsyncUpdate()
  54553. {
  54554. listeners.call (&MenuBarModelListener::menuBarItemsChanged, this);
  54555. }
  54556. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54557. {
  54558. listeners.call (&MenuBarModelListener::menuCommandInvoked, this, info);
  54559. }
  54560. void MenuBarModel::applicationCommandListChanged()
  54561. {
  54562. menuItemsChanged();
  54563. }
  54564. END_JUCE_NAMESPACE
  54565. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54566. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54567. BEGIN_JUCE_NAMESPACE
  54568. class PopupMenu::Item
  54569. {
  54570. public:
  54571. Item()
  54572. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54573. usesColour (false), customComp (0), commandManager (0)
  54574. {
  54575. }
  54576. Item (const int itemId_,
  54577. const String& text_,
  54578. const bool active_,
  54579. const bool isTicked_,
  54580. const Image& im,
  54581. const Colour& textColour_,
  54582. const bool usesColour_,
  54583. PopupMenuCustomComponent* const customComp_,
  54584. const PopupMenu* const subMenu_,
  54585. ApplicationCommandManager* const commandManager_)
  54586. : itemId (itemId_), text (text_), textColour (textColour_),
  54587. active (active_), isSeparator (false), isTicked (isTicked_),
  54588. usesColour (usesColour_), image (im), customComp (customComp_),
  54589. commandManager (commandManager_)
  54590. {
  54591. if (subMenu_ != 0)
  54592. subMenu = new PopupMenu (*subMenu_);
  54593. if (commandManager_ != 0 && itemId_ != 0)
  54594. {
  54595. String shortcutKey;
  54596. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54597. ->getKeyPressesAssignedToCommand (itemId_));
  54598. for (int i = 0; i < keyPresses.size(); ++i)
  54599. {
  54600. const String key (keyPresses.getReference(i).getTextDescription());
  54601. if (shortcutKey.isNotEmpty())
  54602. shortcutKey << ", ";
  54603. if (key.length() == 1)
  54604. shortcutKey << "shortcut: '" << key << '\'';
  54605. else
  54606. shortcutKey << key;
  54607. }
  54608. shortcutKey = shortcutKey.trim();
  54609. if (shortcutKey.isNotEmpty())
  54610. text << "<end>" << shortcutKey;
  54611. }
  54612. }
  54613. Item (const Item& other)
  54614. : itemId (other.itemId),
  54615. text (other.text),
  54616. textColour (other.textColour),
  54617. active (other.active),
  54618. isSeparator (other.isSeparator),
  54619. isTicked (other.isTicked),
  54620. usesColour (other.usesColour),
  54621. image (other.image),
  54622. customComp (other.customComp),
  54623. commandManager (other.commandManager)
  54624. {
  54625. if (other.subMenu != 0)
  54626. subMenu = new PopupMenu (*(other.subMenu));
  54627. }
  54628. ~Item()
  54629. {
  54630. customComp = 0;
  54631. }
  54632. bool canBeTriggered() const throw()
  54633. {
  54634. return active && ! (isSeparator || (subMenu != 0));
  54635. }
  54636. bool hasActiveSubMenu() const throw()
  54637. {
  54638. return active && (subMenu != 0);
  54639. }
  54640. const int itemId;
  54641. String text;
  54642. const Colour textColour;
  54643. const bool active, isSeparator, isTicked, usesColour;
  54644. Image image;
  54645. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54646. ScopedPointer <PopupMenu> subMenu;
  54647. ApplicationCommandManager* const commandManager;
  54648. juce_UseDebuggingNewOperator
  54649. private:
  54650. Item& operator= (const Item&);
  54651. };
  54652. class PopupMenu::ItemComponent : public Component
  54653. {
  54654. public:
  54655. ItemComponent (const PopupMenu::Item& itemInfo_)
  54656. : itemInfo (itemInfo_),
  54657. isHighlighted (false)
  54658. {
  54659. if (itemInfo.customComp != 0)
  54660. addAndMakeVisible (itemInfo.customComp);
  54661. }
  54662. ~ItemComponent()
  54663. {
  54664. if (itemInfo.customComp != 0)
  54665. removeChildComponent (itemInfo.customComp);
  54666. }
  54667. void getIdealSize (int& idealWidth,
  54668. int& idealHeight,
  54669. const int standardItemHeight)
  54670. {
  54671. if (itemInfo.customComp != 0)
  54672. {
  54673. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54674. }
  54675. else
  54676. {
  54677. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54678. itemInfo.isSeparator,
  54679. standardItemHeight,
  54680. idealWidth,
  54681. idealHeight);
  54682. }
  54683. }
  54684. void paint (Graphics& g)
  54685. {
  54686. if (itemInfo.customComp == 0)
  54687. {
  54688. String mainText (itemInfo.text);
  54689. String endText;
  54690. const int endIndex = mainText.indexOf ("<end>");
  54691. if (endIndex >= 0)
  54692. {
  54693. endText = mainText.substring (endIndex + 5).trim();
  54694. mainText = mainText.substring (0, endIndex);
  54695. }
  54696. getLookAndFeel()
  54697. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54698. itemInfo.isSeparator,
  54699. itemInfo.active,
  54700. isHighlighted,
  54701. itemInfo.isTicked,
  54702. itemInfo.subMenu != 0,
  54703. mainText, endText,
  54704. itemInfo.image.isValid() ? &itemInfo.image : 0,
  54705. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54706. }
  54707. }
  54708. void resized()
  54709. {
  54710. if (getNumChildComponents() > 0)
  54711. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54712. }
  54713. void setHighlighted (bool shouldBeHighlighted)
  54714. {
  54715. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54716. if (isHighlighted != shouldBeHighlighted)
  54717. {
  54718. isHighlighted = shouldBeHighlighted;
  54719. if (itemInfo.customComp != 0)
  54720. {
  54721. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54722. itemInfo.customComp->repaint();
  54723. }
  54724. repaint();
  54725. }
  54726. }
  54727. PopupMenu::Item itemInfo;
  54728. juce_UseDebuggingNewOperator
  54729. private:
  54730. bool isHighlighted;
  54731. ItemComponent (const ItemComponent&);
  54732. ItemComponent& operator= (const ItemComponent&);
  54733. };
  54734. namespace PopupMenuSettings
  54735. {
  54736. static const int scrollZone = 24;
  54737. static const int borderSize = 2;
  54738. static const int timerInterval = 50;
  54739. static const int dismissCommandId = 0x6287345f;
  54740. }
  54741. class PopupMenu::Window : public Component,
  54742. private Timer
  54743. {
  54744. public:
  54745. Window()
  54746. : Component ("menu"),
  54747. owner (0),
  54748. currentChild (0),
  54749. activeSubMenu (0),
  54750. menuBarComponent (0),
  54751. managerOfChosenCommand (0),
  54752. minimumWidth (0),
  54753. maximumNumColumns (7),
  54754. standardItemHeight (0),
  54755. isOver (false),
  54756. hasBeenOver (false),
  54757. isDown (false),
  54758. needsToScroll (false),
  54759. hideOnExit (false),
  54760. disableMouseMoves (false),
  54761. hasAnyJuceCompHadFocus (false),
  54762. numColumns (0),
  54763. contentHeight (0),
  54764. childYOffset (0),
  54765. timeEnteredCurrentChildComp (0),
  54766. scrollAcceleration (1.0)
  54767. {
  54768. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54769. setWantsKeyboardFocus (true);
  54770. setMouseClickGrabsKeyboardFocus (false);
  54771. setOpaque (true);
  54772. setAlwaysOnTop (true);
  54773. Desktop::getInstance().addGlobalMouseListener (this);
  54774. getActiveWindows().add (this);
  54775. }
  54776. ~Window()
  54777. {
  54778. getActiveWindows().removeValue (this);
  54779. Desktop::getInstance().removeGlobalMouseListener (this);
  54780. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54781. activeSubMenu = 0;
  54782. deleteAllChildren();
  54783. }
  54784. static Window* create (const PopupMenu& menu,
  54785. const bool dismissOnMouseUp,
  54786. Window* const owner_,
  54787. const int minX, const int maxX,
  54788. const int minY, const int maxY,
  54789. const int minimumWidth,
  54790. const int maximumNumColumns,
  54791. const int standardItemHeight,
  54792. const bool alignToRectangle,
  54793. const int itemIdThatMustBeVisible,
  54794. Component* const menuBarComponent,
  54795. ApplicationCommandManager** managerOfChosenCommand,
  54796. Component* const componentAttachedTo)
  54797. {
  54798. if (menu.items.size() > 0)
  54799. {
  54800. int totalItems = 0;
  54801. ScopedPointer <Window> mw (new Window());
  54802. mw->setLookAndFeel (menu.lookAndFeel);
  54803. mw->setWantsKeyboardFocus (false);
  54804. mw->minimumWidth = minimumWidth;
  54805. mw->maximumNumColumns = maximumNumColumns;
  54806. mw->standardItemHeight = standardItemHeight;
  54807. mw->dismissOnMouseUp = dismissOnMouseUp;
  54808. for (int i = 0; i < menu.items.size(); ++i)
  54809. {
  54810. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  54811. mw->addItem (*item);
  54812. ++totalItems;
  54813. }
  54814. if (totalItems > 0)
  54815. {
  54816. mw->owner = owner_;
  54817. mw->menuBarComponent = menuBarComponent;
  54818. mw->managerOfChosenCommand = managerOfChosenCommand;
  54819. mw->componentAttachedTo = componentAttachedTo;
  54820. mw->componentAttachedToOriginal = componentAttachedTo;
  54821. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  54822. mw->setTopLeftPosition (mw->windowPos.getX(),
  54823. mw->windowPos.getY());
  54824. mw->updateYPositions();
  54825. if (itemIdThatMustBeVisible != 0)
  54826. {
  54827. const int y = minY - mw->windowPos.getY();
  54828. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  54829. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  54830. }
  54831. mw->resizeToBestWindowPos();
  54832. mw->addToDesktop (ComponentPeer::windowIsTemporary
  54833. | mw->getLookAndFeel().getMenuWindowFlags());
  54834. return mw.release();
  54835. }
  54836. }
  54837. return 0;
  54838. }
  54839. void paint (Graphics& g)
  54840. {
  54841. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  54842. }
  54843. void paintOverChildren (Graphics& g)
  54844. {
  54845. if (isScrolling())
  54846. {
  54847. LookAndFeel& lf = getLookAndFeel();
  54848. if (isScrollZoneActive (false))
  54849. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  54850. if (isScrollZoneActive (true))
  54851. {
  54852. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  54853. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  54854. }
  54855. }
  54856. }
  54857. bool isScrollZoneActive (bool bottomOne) const
  54858. {
  54859. return isScrolling()
  54860. && (bottomOne
  54861. ? childYOffset < contentHeight - windowPos.getHeight()
  54862. : childYOffset > 0);
  54863. }
  54864. void addItem (const PopupMenu::Item& item)
  54865. {
  54866. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  54867. addAndMakeVisible (mic);
  54868. int itemW = 80;
  54869. int itemH = 16;
  54870. mic->getIdealSize (itemW, itemH, standardItemHeight);
  54871. mic->setSize (itemW, jlimit (2, 600, itemH));
  54872. mic->addMouseListener (this, false);
  54873. }
  54874. // hide this and all sub-comps
  54875. void hide (const PopupMenu::Item* const item)
  54876. {
  54877. if (isVisible())
  54878. {
  54879. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54880. activeSubMenu = 0;
  54881. currentChild = 0;
  54882. exitModalState (item != 0 ? item->itemId : 0);
  54883. setVisible (false);
  54884. if (item != 0
  54885. && item->commandManager != 0
  54886. && item->itemId != 0)
  54887. {
  54888. *managerOfChosenCommand = item->commandManager;
  54889. }
  54890. }
  54891. }
  54892. void dismissMenu (const PopupMenu::Item* const item)
  54893. {
  54894. if (owner != 0)
  54895. {
  54896. owner->dismissMenu (item);
  54897. }
  54898. else
  54899. {
  54900. if (item != 0)
  54901. {
  54902. // need a copy of this on the stack as the one passed in will get deleted during this call
  54903. const PopupMenu::Item mi (*item);
  54904. hide (&mi);
  54905. }
  54906. else
  54907. {
  54908. hide (0);
  54909. }
  54910. }
  54911. }
  54912. void mouseMove (const MouseEvent&)
  54913. {
  54914. timerCallback();
  54915. }
  54916. void mouseDown (const MouseEvent&)
  54917. {
  54918. timerCallback();
  54919. }
  54920. void mouseDrag (const MouseEvent&)
  54921. {
  54922. timerCallback();
  54923. }
  54924. void mouseUp (const MouseEvent&)
  54925. {
  54926. timerCallback();
  54927. }
  54928. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  54929. {
  54930. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  54931. lastMouse = Point<int> (-1, -1);
  54932. }
  54933. bool keyPressed (const KeyPress& key)
  54934. {
  54935. if (key.isKeyCode (KeyPress::downKey))
  54936. {
  54937. selectNextItem (1);
  54938. }
  54939. else if (key.isKeyCode (KeyPress::upKey))
  54940. {
  54941. selectNextItem (-1);
  54942. }
  54943. else if (key.isKeyCode (KeyPress::leftKey))
  54944. {
  54945. if (owner != 0)
  54946. {
  54947. Component::SafePointer<Window> parentWindow (owner);
  54948. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  54949. hide (0);
  54950. if (parentWindow != 0)
  54951. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  54952. disableTimerUntilMouseMoves();
  54953. }
  54954. else if (menuBarComponent != 0)
  54955. {
  54956. menuBarComponent->keyPressed (key);
  54957. }
  54958. }
  54959. else if (key.isKeyCode (KeyPress::rightKey))
  54960. {
  54961. disableTimerUntilMouseMoves();
  54962. if (showSubMenuFor (currentChild))
  54963. {
  54964. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54965. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  54966. activeSubMenu->selectNextItem (1);
  54967. }
  54968. else if (menuBarComponent != 0)
  54969. {
  54970. menuBarComponent->keyPressed (key);
  54971. }
  54972. }
  54973. else if (key.isKeyCode (KeyPress::returnKey))
  54974. {
  54975. triggerCurrentlyHighlightedItem();
  54976. }
  54977. else if (key.isKeyCode (KeyPress::escapeKey))
  54978. {
  54979. dismissMenu (0);
  54980. }
  54981. else
  54982. {
  54983. return false;
  54984. }
  54985. return true;
  54986. }
  54987. void inputAttemptWhenModal()
  54988. {
  54989. Component::SafePointer<Component> deletionChecker (this);
  54990. timerCallback();
  54991. if (deletionChecker != 0 && ! isOverAnyMenu())
  54992. {
  54993. if (componentAttachedTo != 0)
  54994. {
  54995. // we want to dismiss the menu, but if we do it synchronously, then
  54996. // the mouse-click will be allowed to pass through. That's good, except
  54997. // when the user clicks on the button that orginally popped the menu up,
  54998. // as they'll expect the menu to go away, and in fact it'll just
  54999. // come back. So only dismiss synchronously if they're not on the original
  55000. // comp that we're attached to.
  55001. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55002. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55003. {
  55004. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55005. return;
  55006. }
  55007. }
  55008. dismissMenu (0);
  55009. }
  55010. }
  55011. void handleCommandMessage (int commandId)
  55012. {
  55013. Component::handleCommandMessage (commandId);
  55014. if (commandId == PopupMenuSettings::dismissCommandId)
  55015. dismissMenu (0);
  55016. }
  55017. void timerCallback()
  55018. {
  55019. if (! isVisible())
  55020. return;
  55021. if (componentAttachedTo != componentAttachedToOriginal)
  55022. {
  55023. dismissMenu (0);
  55024. return;
  55025. }
  55026. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55027. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55028. return;
  55029. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55030. // move rather than a real timer callback
  55031. const Point<int> globalMousePos (Desktop::getMousePosition());
  55032. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55033. const uint32 now = Time::getMillisecondCounter();
  55034. if (now > timeEnteredCurrentChildComp + 100
  55035. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55036. && currentChild->isValidComponent()
  55037. && (! disableMouseMoves)
  55038. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55039. {
  55040. showSubMenuFor (currentChild);
  55041. }
  55042. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55043. {
  55044. highlightItemUnderMouse (globalMousePos, localMousePos);
  55045. }
  55046. bool overScrollArea = false;
  55047. if (isScrolling()
  55048. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55049. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55050. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55051. {
  55052. if (now > lastScroll + 20)
  55053. {
  55054. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55055. int amount = 0;
  55056. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55057. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55058. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55059. lastScroll = now;
  55060. }
  55061. overScrollArea = true;
  55062. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55063. }
  55064. else
  55065. {
  55066. scrollAcceleration = 1.0;
  55067. }
  55068. const bool wasDown = isDown;
  55069. bool isOverAny = isOverAnyMenu();
  55070. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55071. {
  55072. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55073. isOverAny = isOverAnyMenu();
  55074. }
  55075. if (hideOnExit && hasBeenOver && ! isOverAny)
  55076. {
  55077. hide (0);
  55078. }
  55079. else
  55080. {
  55081. isDown = hasBeenOver
  55082. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55083. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55084. bool anyFocused = Process::isForegroundProcess();
  55085. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55086. {
  55087. // because no component at all may have focus, our test here will
  55088. // only be triggered when something has focus and then loses it.
  55089. anyFocused = ! hasAnyJuceCompHadFocus;
  55090. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55091. {
  55092. if (ComponentPeer::getPeer (i)->isFocused())
  55093. {
  55094. anyFocused = true;
  55095. hasAnyJuceCompHadFocus = true;
  55096. break;
  55097. }
  55098. }
  55099. }
  55100. if (! anyFocused)
  55101. {
  55102. if (now > lastFocused + 10)
  55103. {
  55104. wasHiddenBecauseOfAppChange() = true;
  55105. dismissMenu (0);
  55106. return; // may have been deleted by the previous call..
  55107. }
  55108. }
  55109. else if (wasDown && now > menuCreationTime + 250
  55110. && ! (isDown || overScrollArea))
  55111. {
  55112. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55113. if (isOver)
  55114. {
  55115. triggerCurrentlyHighlightedItem();
  55116. }
  55117. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55118. {
  55119. dismissMenu (0);
  55120. }
  55121. return; // may have been deleted by the previous calls..
  55122. }
  55123. else
  55124. {
  55125. lastFocused = now;
  55126. }
  55127. }
  55128. }
  55129. static Array<Window*>& getActiveWindows()
  55130. {
  55131. static Array<Window*> activeMenuWindows;
  55132. return activeMenuWindows;
  55133. }
  55134. static bool& wasHiddenBecauseOfAppChange() throw()
  55135. {
  55136. static bool b = false;
  55137. return b;
  55138. }
  55139. juce_UseDebuggingNewOperator
  55140. private:
  55141. Window* owner;
  55142. PopupMenu::ItemComponent* currentChild;
  55143. ScopedPointer <Window> activeSubMenu;
  55144. Component* menuBarComponent;
  55145. ApplicationCommandManager** managerOfChosenCommand;
  55146. Component::SafePointer<Component> componentAttachedTo;
  55147. Component* componentAttachedToOriginal;
  55148. Rectangle<int> windowPos;
  55149. Point<int> lastMouse;
  55150. int minimumWidth, maximumNumColumns, standardItemHeight;
  55151. bool isOver, hasBeenOver, isDown, needsToScroll;
  55152. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55153. int numColumns, contentHeight, childYOffset;
  55154. Array <int> columnWidths;
  55155. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55156. double scrollAcceleration;
  55157. bool overlaps (const Rectangle<int>& r) const
  55158. {
  55159. return r.intersects (getBounds())
  55160. || (owner != 0 && owner->overlaps (r));
  55161. }
  55162. bool isOverAnyMenu() const
  55163. {
  55164. return (owner != 0) ? owner->isOverAnyMenu()
  55165. : isOverChildren();
  55166. }
  55167. bool isOverChildren() const
  55168. {
  55169. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55170. return isVisible()
  55171. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55172. }
  55173. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55174. {
  55175. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55176. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55177. if (activeSubMenu != 0)
  55178. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55179. }
  55180. bool treeContains (const Window* const window) const throw()
  55181. {
  55182. const Window* mw = this;
  55183. while (mw->owner != 0)
  55184. mw = mw->owner;
  55185. while (mw != 0)
  55186. {
  55187. if (mw == window)
  55188. return true;
  55189. mw = mw->activeSubMenu;
  55190. }
  55191. return false;
  55192. }
  55193. void calculateWindowPos (const int minX, const int maxX,
  55194. const int minY, const int maxY,
  55195. const bool alignToRectangle)
  55196. {
  55197. const Rectangle<int> mon (Desktop::getInstance()
  55198. .getMonitorAreaContaining (Point<int> ((minX + maxX) / 2,
  55199. (minY + maxY) / 2),
  55200. #if JUCE_MAC
  55201. true));
  55202. #else
  55203. false)); // on windows, don't stop the menu overlapping the taskbar
  55204. #endif
  55205. int x, y, widthToUse, heightToUse;
  55206. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55207. if (alignToRectangle)
  55208. {
  55209. x = minX;
  55210. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  55211. const int spaceOver = minY - mon.getY();
  55212. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55213. y = maxY;
  55214. else
  55215. y = minY - heightToUse;
  55216. }
  55217. else
  55218. {
  55219. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  55220. if (owner != 0)
  55221. {
  55222. if (owner->owner != 0)
  55223. {
  55224. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55225. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55226. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  55227. tendTowardsRight = true;
  55228. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  55229. tendTowardsRight = false;
  55230. }
  55231. else if (maxX + widthToUse < mon.getRight() - 32)
  55232. {
  55233. tendTowardsRight = true;
  55234. }
  55235. }
  55236. const int biggestSpace = jmax (mon.getRight() - maxX,
  55237. minX - mon.getX()) - 32;
  55238. if (biggestSpace < widthToUse)
  55239. {
  55240. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  55241. if (numColumns > 1)
  55242. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55243. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  55244. }
  55245. if (tendTowardsRight)
  55246. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  55247. else
  55248. x = jmax (mon.getX() + 4, minX - widthToUse);
  55249. y = minY;
  55250. if ((minY + maxY) / 2 > mon.getCentreY())
  55251. y = jmax (mon.getY(), maxY - heightToUse);
  55252. }
  55253. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55254. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55255. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55256. // sets this flag if it's big enough to obscure any of its parent menus
  55257. hideOnExit = (owner != 0)
  55258. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55259. }
  55260. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55261. {
  55262. numColumns = 0;
  55263. contentHeight = 0;
  55264. const int maxMenuH = getParentHeight() - 24;
  55265. int totalW;
  55266. do
  55267. {
  55268. ++numColumns;
  55269. totalW = workOutBestSize (maxMenuW);
  55270. if (totalW > maxMenuW)
  55271. {
  55272. numColumns = jmax (1, numColumns - 1);
  55273. totalW = workOutBestSize (maxMenuW); // to update col widths
  55274. break;
  55275. }
  55276. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55277. {
  55278. break;
  55279. }
  55280. } while (numColumns < maximumNumColumns);
  55281. const int actualH = jmin (contentHeight, maxMenuH);
  55282. needsToScroll = contentHeight > actualH;
  55283. width = updateYPositions();
  55284. height = actualH + PopupMenuSettings::borderSize * 2;
  55285. }
  55286. int workOutBestSize (const int maxMenuW)
  55287. {
  55288. int totalW = 0;
  55289. contentHeight = 0;
  55290. int childNum = 0;
  55291. for (int col = 0; col < numColumns; ++col)
  55292. {
  55293. int i, colW = 50, colH = 0;
  55294. const int numChildren = jmin (getNumChildComponents() - childNum,
  55295. (getNumChildComponents() + numColumns - 1) / numColumns);
  55296. for (i = numChildren; --i >= 0;)
  55297. {
  55298. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55299. colH += getChildComponent (childNum + i)->getHeight();
  55300. }
  55301. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55302. columnWidths.set (col, colW);
  55303. totalW += colW;
  55304. contentHeight = jmax (contentHeight, colH);
  55305. childNum += numChildren;
  55306. }
  55307. if (totalW < minimumWidth)
  55308. {
  55309. totalW = minimumWidth;
  55310. for (int col = 0; col < numColumns; ++col)
  55311. columnWidths.set (0, totalW / numColumns);
  55312. }
  55313. return totalW;
  55314. }
  55315. void ensureItemIsVisible (const int itemId, int wantedY)
  55316. {
  55317. jassert (itemId != 0)
  55318. for (int i = getNumChildComponents(); --i >= 0;)
  55319. {
  55320. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55321. if (m != 0
  55322. && m->itemInfo.itemId == itemId
  55323. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55324. {
  55325. const int currentY = m->getY();
  55326. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55327. {
  55328. if (wantedY < 0)
  55329. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55330. jmax (PopupMenuSettings::scrollZone,
  55331. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55332. currentY);
  55333. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55334. int deltaY = wantedY - currentY;
  55335. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55336. jmin (windowPos.getHeight(), mon.getHeight()));
  55337. const int newY = jlimit (mon.getY(),
  55338. mon.getBottom() - windowPos.getHeight(),
  55339. windowPos.getY() + deltaY);
  55340. deltaY -= newY - windowPos.getY();
  55341. childYOffset -= deltaY;
  55342. windowPos.setPosition (windowPos.getX(), newY);
  55343. updateYPositions();
  55344. }
  55345. break;
  55346. }
  55347. }
  55348. }
  55349. void resizeToBestWindowPos()
  55350. {
  55351. Rectangle<int> r (windowPos);
  55352. if (childYOffset < 0)
  55353. {
  55354. r.setBounds (r.getX(), r.getY() - childYOffset,
  55355. r.getWidth(), r.getHeight() + childYOffset);
  55356. }
  55357. else if (childYOffset > 0)
  55358. {
  55359. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55360. if (spaceAtBottom > 0)
  55361. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55362. }
  55363. setBounds (r);
  55364. updateYPositions();
  55365. }
  55366. void alterChildYPos (const int delta)
  55367. {
  55368. if (isScrolling())
  55369. {
  55370. childYOffset += delta;
  55371. if (delta < 0)
  55372. {
  55373. childYOffset = jmax (childYOffset, 0);
  55374. }
  55375. else if (delta > 0)
  55376. {
  55377. childYOffset = jmin (childYOffset,
  55378. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55379. }
  55380. updateYPositions();
  55381. }
  55382. else
  55383. {
  55384. childYOffset = 0;
  55385. }
  55386. resizeToBestWindowPos();
  55387. repaint();
  55388. }
  55389. int updateYPositions()
  55390. {
  55391. int x = 0;
  55392. int childNum = 0;
  55393. for (int col = 0; col < numColumns; ++col)
  55394. {
  55395. const int numChildren = jmin (getNumChildComponents() - childNum,
  55396. (getNumChildComponents() + numColumns - 1) / numColumns);
  55397. const int colW = columnWidths [col];
  55398. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55399. for (int i = 0; i < numChildren; ++i)
  55400. {
  55401. Component* const c = getChildComponent (childNum + i);
  55402. c->setBounds (x, y, colW, c->getHeight());
  55403. y += c->getHeight();
  55404. }
  55405. x += colW;
  55406. childNum += numChildren;
  55407. }
  55408. return x;
  55409. }
  55410. bool isScrolling() const throw()
  55411. {
  55412. return childYOffset != 0 || needsToScroll;
  55413. }
  55414. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55415. {
  55416. if (currentChild->isValidComponent())
  55417. currentChild->setHighlighted (false);
  55418. currentChild = child;
  55419. if (currentChild != 0)
  55420. {
  55421. currentChild->setHighlighted (true);
  55422. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55423. }
  55424. }
  55425. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55426. {
  55427. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55428. activeSubMenu = 0;
  55429. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55430. {
  55431. const Point<int> topLeft (childComp->relativePositionToGlobal (Point<int>()));
  55432. const Point<int> bottomRight (childComp->relativePositionToGlobal (Point<int> (childComp->getWidth(), childComp->getHeight())));
  55433. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55434. dismissOnMouseUp,
  55435. this,
  55436. topLeft.getX(), bottomRight.getX(), topLeft.getY(), bottomRight.getY(),
  55437. 0, maximumNumColumns,
  55438. standardItemHeight,
  55439. false, 0, menuBarComponent,
  55440. managerOfChosenCommand,
  55441. componentAttachedTo);
  55442. if (activeSubMenu != 0)
  55443. {
  55444. activeSubMenu->setVisible (true);
  55445. activeSubMenu->enterModalState (false);
  55446. activeSubMenu->toFront (false);
  55447. return true;
  55448. }
  55449. }
  55450. return false;
  55451. }
  55452. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55453. {
  55454. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55455. if (isOver)
  55456. hasBeenOver = true;
  55457. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55458. {
  55459. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55460. if (disableMouseMoves && isOver)
  55461. disableMouseMoves = false;
  55462. }
  55463. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55464. return;
  55465. bool isMovingTowardsMenu = false;
  55466. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55467. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55468. {
  55469. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55470. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55471. // extends from the last mouse pos to the submenu's rectangle..
  55472. float subX = (float) activeSubMenu->getScreenX();
  55473. if (activeSubMenu->getX() > getX())
  55474. {
  55475. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55476. }
  55477. else
  55478. {
  55479. lastMouse += Point<int> (2, 0);
  55480. subX += activeSubMenu->getWidth();
  55481. }
  55482. Path areaTowardsSubMenu;
  55483. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55484. (float) lastMouse.getY(),
  55485. subX,
  55486. (float) activeSubMenu->getScreenY(),
  55487. subX,
  55488. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55489. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55490. }
  55491. lastMouse = globalMousePos;
  55492. if (! isMovingTowardsMenu)
  55493. {
  55494. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55495. if (c == this)
  55496. c = 0;
  55497. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55498. if (mic == 0 && c != 0)
  55499. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55500. if (mic != currentChild
  55501. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55502. {
  55503. if (isOver && (c != 0) && (activeSubMenu != 0))
  55504. {
  55505. activeSubMenu->hide (0);
  55506. }
  55507. if (! isOver)
  55508. mic = 0;
  55509. setCurrentlyHighlightedChild (mic);
  55510. }
  55511. }
  55512. }
  55513. void triggerCurrentlyHighlightedItem()
  55514. {
  55515. if (currentChild->isValidComponent()
  55516. && currentChild->itemInfo.canBeTriggered()
  55517. && (currentChild->itemInfo.customComp == 0
  55518. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55519. {
  55520. dismissMenu (&currentChild->itemInfo);
  55521. }
  55522. }
  55523. void selectNextItem (const int delta)
  55524. {
  55525. disableTimerUntilMouseMoves();
  55526. PopupMenu::ItemComponent* mic = 0;
  55527. bool wasLastOne = (currentChild == 0);
  55528. const int numItems = getNumChildComponents();
  55529. for (int i = 0; i < numItems + 1; ++i)
  55530. {
  55531. int index = (delta > 0) ? i : (numItems - 1 - i);
  55532. index = (index + numItems) % numItems;
  55533. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55534. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55535. && wasLastOne)
  55536. break;
  55537. if (mic == currentChild)
  55538. wasLastOne = true;
  55539. }
  55540. setCurrentlyHighlightedChild (mic);
  55541. }
  55542. void disableTimerUntilMouseMoves()
  55543. {
  55544. disableMouseMoves = true;
  55545. if (owner != 0)
  55546. owner->disableTimerUntilMouseMoves();
  55547. }
  55548. Window (const Window&);
  55549. Window& operator= (const Window&);
  55550. };
  55551. PopupMenu::PopupMenu()
  55552. : lookAndFeel (0),
  55553. separatorPending (false)
  55554. {
  55555. }
  55556. PopupMenu::PopupMenu (const PopupMenu& other)
  55557. : lookAndFeel (other.lookAndFeel),
  55558. separatorPending (false)
  55559. {
  55560. items.addCopiesOf (other.items);
  55561. }
  55562. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55563. {
  55564. if (this != &other)
  55565. {
  55566. lookAndFeel = other.lookAndFeel;
  55567. clear();
  55568. items.addCopiesOf (other.items);
  55569. }
  55570. return *this;
  55571. }
  55572. PopupMenu::~PopupMenu()
  55573. {
  55574. clear();
  55575. }
  55576. void PopupMenu::clear()
  55577. {
  55578. items.clear();
  55579. separatorPending = false;
  55580. }
  55581. void PopupMenu::addSeparatorIfPending()
  55582. {
  55583. if (separatorPending)
  55584. {
  55585. separatorPending = false;
  55586. if (items.size() > 0)
  55587. items.add (new Item());
  55588. }
  55589. }
  55590. void PopupMenu::addItem (const int itemResultId,
  55591. const String& itemText,
  55592. const bool isActive,
  55593. const bool isTicked,
  55594. const Image& iconToUse)
  55595. {
  55596. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55597. // didn't pick anything, so you shouldn't use it as the id
  55598. // for an item..
  55599. addSeparatorIfPending();
  55600. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55601. Colours::black, false, 0, 0, 0));
  55602. }
  55603. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55604. const int commandID,
  55605. const String& displayName)
  55606. {
  55607. jassert (commandManager != 0 && commandID != 0);
  55608. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55609. if (registeredInfo != 0)
  55610. {
  55611. ApplicationCommandInfo info (*registeredInfo);
  55612. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55613. addSeparatorIfPending();
  55614. items.add (new Item (commandID,
  55615. displayName.isNotEmpty() ? displayName
  55616. : info.shortName,
  55617. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55618. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55619. Image(),
  55620. Colours::black,
  55621. false,
  55622. 0, 0,
  55623. commandManager));
  55624. }
  55625. }
  55626. void PopupMenu::addColouredItem (const int itemResultId,
  55627. const String& itemText,
  55628. const Colour& itemTextColour,
  55629. const bool isActive,
  55630. const bool isTicked,
  55631. const Image& iconToUse)
  55632. {
  55633. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55634. // didn't pick anything, so you shouldn't use it as the id
  55635. // for an item..
  55636. addSeparatorIfPending();
  55637. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55638. itemTextColour, true, 0, 0, 0));
  55639. }
  55640. void PopupMenu::addCustomItem (const int itemResultId,
  55641. PopupMenuCustomComponent* const customComponent)
  55642. {
  55643. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55644. // didn't pick anything, so you shouldn't use it as the id
  55645. // for an item..
  55646. addSeparatorIfPending();
  55647. items.add (new Item (itemResultId, String::empty, true, false, Image(),
  55648. Colours::black, false, customComponent, 0, 0));
  55649. }
  55650. class NormalComponentWrapper : public PopupMenuCustomComponent
  55651. {
  55652. public:
  55653. NormalComponentWrapper (Component* const comp,
  55654. const int w, const int h,
  55655. const bool triggerMenuItemAutomaticallyWhenClicked)
  55656. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55657. width (w),
  55658. height (h)
  55659. {
  55660. addAndMakeVisible (comp);
  55661. }
  55662. ~NormalComponentWrapper() {}
  55663. void getIdealSize (int& idealWidth, int& idealHeight)
  55664. {
  55665. idealWidth = width;
  55666. idealHeight = height;
  55667. }
  55668. void resized()
  55669. {
  55670. if (getChildComponent(0) != 0)
  55671. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  55672. }
  55673. juce_UseDebuggingNewOperator
  55674. private:
  55675. const int width, height;
  55676. NormalComponentWrapper (const NormalComponentWrapper&);
  55677. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55678. };
  55679. void PopupMenu::addCustomItem (const int itemResultId,
  55680. Component* customComponent,
  55681. int idealWidth, int idealHeight,
  55682. const bool triggerMenuItemAutomaticallyWhenClicked)
  55683. {
  55684. addCustomItem (itemResultId,
  55685. new NormalComponentWrapper (customComponent,
  55686. idealWidth, idealHeight,
  55687. triggerMenuItemAutomaticallyWhenClicked));
  55688. }
  55689. void PopupMenu::addSubMenu (const String& subMenuName,
  55690. const PopupMenu& subMenu,
  55691. const bool isActive,
  55692. const Image& iconToUse,
  55693. const bool isTicked)
  55694. {
  55695. addSeparatorIfPending();
  55696. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55697. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55698. }
  55699. void PopupMenu::addSeparator()
  55700. {
  55701. separatorPending = true;
  55702. }
  55703. class HeaderItemComponent : public PopupMenuCustomComponent
  55704. {
  55705. public:
  55706. HeaderItemComponent (const String& name)
  55707. : PopupMenuCustomComponent (false)
  55708. {
  55709. setName (name);
  55710. }
  55711. ~HeaderItemComponent()
  55712. {
  55713. }
  55714. void paint (Graphics& g)
  55715. {
  55716. Font f (getLookAndFeel().getPopupMenuFont());
  55717. f.setBold (true);
  55718. g.setFont (f);
  55719. g.setColour (findColour (PopupMenu::headerTextColourId));
  55720. g.drawFittedText (getName(),
  55721. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55722. Justification::bottomLeft, 1);
  55723. }
  55724. void getIdealSize (int& idealWidth,
  55725. int& idealHeight)
  55726. {
  55727. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55728. idealHeight += idealHeight / 2;
  55729. idealWidth += idealWidth / 4;
  55730. }
  55731. juce_UseDebuggingNewOperator
  55732. };
  55733. void PopupMenu::addSectionHeader (const String& title)
  55734. {
  55735. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55736. }
  55737. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  55738. const int itemIdThatMustBeVisible,
  55739. const int minimumWidth,
  55740. const int maximumNumColumns,
  55741. const int standardItemHeight,
  55742. const bool alignToRectangle,
  55743. Component* menuBarComponent,
  55744. ApplicationCommandManager** managerOfChosenCommand,
  55745. Component* const componentAttachedTo)
  55746. {
  55747. Window* const pw
  55748. = Window::create (*this,
  55749. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55750. 0,
  55751. x, x + w,
  55752. y, y + h,
  55753. minimumWidth,
  55754. maximumNumColumns,
  55755. standardItemHeight,
  55756. alignToRectangle,
  55757. itemIdThatMustBeVisible,
  55758. menuBarComponent,
  55759. managerOfChosenCommand,
  55760. componentAttachedTo);
  55761. if (pw != 0)
  55762. pw->setVisible (true);
  55763. return pw;
  55764. }
  55765. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  55766. const int itemIdThatMustBeVisible,
  55767. const int minimumWidth,
  55768. const int maximumNumColumns,
  55769. const int standardItemHeight,
  55770. const bool alignToRectangle,
  55771. Component* const componentAttachedTo)
  55772. {
  55773. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55774. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55775. Window::wasHiddenBecauseOfAppChange() = false;
  55776. int result = 0;
  55777. ApplicationCommandManager* managerOfChosenCommand = 0;
  55778. ScopedPointer <Component> popupComp (createMenuComponent (x, y, w, h,
  55779. itemIdThatMustBeVisible,
  55780. minimumWidth,
  55781. maximumNumColumns > 0 ? maximumNumColumns : 7,
  55782. standardItemHeight,
  55783. alignToRectangle, 0,
  55784. &managerOfChosenCommand,
  55785. componentAttachedTo));
  55786. if (popupComp != 0)
  55787. {
  55788. popupComp->enterModalState (false);
  55789. popupComp->toFront (false); // need to do this after making it modal, or it could
  55790. // be stuck behind other comps that are already modal..
  55791. result = popupComp->runModalLoop();
  55792. popupComp = 0;
  55793. if (! Window::wasHiddenBecauseOfAppChange())
  55794. {
  55795. if (prevTopLevel != 0)
  55796. prevTopLevel->toFront (true);
  55797. if (prevFocused != 0)
  55798. prevFocused->grabKeyboardFocus();
  55799. }
  55800. }
  55801. if (managerOfChosenCommand != 0 && result != 0)
  55802. {
  55803. ApplicationCommandTarget::InvocationInfo info (result);
  55804. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55805. managerOfChosenCommand->invoke (info, true);
  55806. }
  55807. return result;
  55808. }
  55809. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55810. const int minimumWidth,
  55811. const int maximumNumColumns,
  55812. const int standardItemHeight)
  55813. {
  55814. const Point<int> mousePos (Desktop::getMousePosition());
  55815. return showAt (mousePos.getX(), mousePos.getY(),
  55816. itemIdThatMustBeVisible,
  55817. minimumWidth,
  55818. maximumNumColumns,
  55819. standardItemHeight);
  55820. }
  55821. int PopupMenu::showAt (const int screenX,
  55822. const int screenY,
  55823. const int itemIdThatMustBeVisible,
  55824. const int minimumWidth,
  55825. const int maximumNumColumns,
  55826. const int standardItemHeight)
  55827. {
  55828. return showMenu (screenX, screenY, 1, 1,
  55829. itemIdThatMustBeVisible,
  55830. minimumWidth, maximumNumColumns,
  55831. standardItemHeight,
  55832. false, 0);
  55833. }
  55834. int PopupMenu::showAt (Component* componentToAttachTo,
  55835. const int itemIdThatMustBeVisible,
  55836. const int minimumWidth,
  55837. const int maximumNumColumns,
  55838. const int standardItemHeight)
  55839. {
  55840. if (componentToAttachTo != 0)
  55841. {
  55842. return showMenu (componentToAttachTo->getScreenX(),
  55843. componentToAttachTo->getScreenY(),
  55844. componentToAttachTo->getWidth(),
  55845. componentToAttachTo->getHeight(),
  55846. itemIdThatMustBeVisible,
  55847. minimumWidth,
  55848. maximumNumColumns,
  55849. standardItemHeight,
  55850. true, componentToAttachTo);
  55851. }
  55852. else
  55853. {
  55854. return show (itemIdThatMustBeVisible,
  55855. minimumWidth,
  55856. maximumNumColumns,
  55857. standardItemHeight);
  55858. }
  55859. }
  55860. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  55861. {
  55862. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  55863. {
  55864. Window* const pmw = Window::getActiveWindows()[i];
  55865. if (pmw != 0)
  55866. pmw->dismissMenu (0);
  55867. }
  55868. }
  55869. int PopupMenu::getNumItems() const throw()
  55870. {
  55871. int num = 0;
  55872. for (int i = items.size(); --i >= 0;)
  55873. if (! (items.getUnchecked(i))->isSeparator)
  55874. ++num;
  55875. return num;
  55876. }
  55877. bool PopupMenu::containsCommandItem (const int commandID) const
  55878. {
  55879. for (int i = items.size(); --i >= 0;)
  55880. {
  55881. const Item* mi = items.getUnchecked (i);
  55882. if ((mi->itemId == commandID && mi->commandManager != 0)
  55883. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  55884. {
  55885. return true;
  55886. }
  55887. }
  55888. return false;
  55889. }
  55890. bool PopupMenu::containsAnyActiveItems() const throw()
  55891. {
  55892. for (int i = items.size(); --i >= 0;)
  55893. {
  55894. const Item* const mi = items.getUnchecked (i);
  55895. if (mi->subMenu != 0)
  55896. {
  55897. if (mi->subMenu->containsAnyActiveItems())
  55898. return true;
  55899. }
  55900. else if (mi->active)
  55901. {
  55902. return true;
  55903. }
  55904. }
  55905. return false;
  55906. }
  55907. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  55908. {
  55909. lookAndFeel = newLookAndFeel;
  55910. }
  55911. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  55912. : isHighlighted (false),
  55913. isTriggeredAutomatically (isTriggeredAutomatically_)
  55914. {
  55915. }
  55916. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  55917. {
  55918. }
  55919. void PopupMenuCustomComponent::triggerMenuItem()
  55920. {
  55921. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  55922. if (mic != 0)
  55923. {
  55924. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  55925. if (pmw != 0)
  55926. {
  55927. pmw->dismissMenu (&mic->itemInfo);
  55928. }
  55929. else
  55930. {
  55931. // something must have gone wrong with the component hierarchy if this happens..
  55932. jassertfalse;
  55933. }
  55934. }
  55935. else
  55936. {
  55937. // why isn't this component inside a menu? Not much point triggering the item if
  55938. // there's no menu.
  55939. jassertfalse;
  55940. }
  55941. }
  55942. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  55943. : subMenu (0),
  55944. itemId (0),
  55945. isSeparator (false),
  55946. isTicked (false),
  55947. isEnabled (false),
  55948. isCustomComponent (false),
  55949. isSectionHeader (false),
  55950. customColour (0),
  55951. customImage (0),
  55952. menu (menu_),
  55953. index (0)
  55954. {
  55955. }
  55956. PopupMenu::MenuItemIterator::~MenuItemIterator()
  55957. {
  55958. }
  55959. bool PopupMenu::MenuItemIterator::next()
  55960. {
  55961. if (index >= menu.items.size())
  55962. return false;
  55963. const Item* const item = menu.items.getUnchecked (index);
  55964. ++index;
  55965. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  55966. subMenu = item->subMenu;
  55967. itemId = item->itemId;
  55968. isSeparator = item->isSeparator;
  55969. isTicked = item->isTicked;
  55970. isEnabled = item->active;
  55971. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  55972. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  55973. customColour = item->usesColour ? &(item->textColour) : 0;
  55974. customImage = item->image;
  55975. commandManager = item->commandManager;
  55976. return true;
  55977. }
  55978. END_JUCE_NAMESPACE
  55979. /*** End of inlined file: juce_PopupMenu.cpp ***/
  55980. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  55981. BEGIN_JUCE_NAMESPACE
  55982. ComponentDragger::ComponentDragger()
  55983. : constrainer (0)
  55984. {
  55985. }
  55986. ComponentDragger::~ComponentDragger()
  55987. {
  55988. }
  55989. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  55990. ComponentBoundsConstrainer* const constrainer_)
  55991. {
  55992. jassert (componentToDrag->isValidComponent());
  55993. if (componentToDrag != 0)
  55994. {
  55995. constrainer = constrainer_;
  55996. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  55997. }
  55998. }
  55999. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56000. {
  56001. jassert (componentToDrag->isValidComponent());
  56002. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56003. if (componentToDrag != 0)
  56004. {
  56005. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56006. const Component* const parentComp = componentToDrag->getParentComponent();
  56007. if (parentComp != 0)
  56008. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56009. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56010. if (constrainer != 0)
  56011. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56012. else
  56013. componentToDrag->setBounds (bounds);
  56014. }
  56015. }
  56016. END_JUCE_NAMESPACE
  56017. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56018. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56019. BEGIN_JUCE_NAMESPACE
  56020. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56021. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56022. class DragImageComponent : public Component,
  56023. public Timer
  56024. {
  56025. public:
  56026. DragImageComponent (const Image& im,
  56027. const String& desc,
  56028. Component* const sourceComponent,
  56029. Component* const mouseDragSource_,
  56030. DragAndDropContainer* const o,
  56031. const Point<int>& imageOffset_)
  56032. : image (im),
  56033. source (sourceComponent),
  56034. mouseDragSource (mouseDragSource_),
  56035. owner (o),
  56036. dragDesc (desc),
  56037. imageOffset (imageOffset_),
  56038. hasCheckedForExternalDrag (false),
  56039. drawImage (true)
  56040. {
  56041. setSize (im.getWidth(), im.getHeight());
  56042. if (mouseDragSource == 0)
  56043. mouseDragSource = source;
  56044. mouseDragSource->addMouseListener (this, false);
  56045. startTimer (200);
  56046. setInterceptsMouseClicks (false, false);
  56047. setAlwaysOnTop (true);
  56048. }
  56049. ~DragImageComponent()
  56050. {
  56051. if (owner->dragImageComponent == this)
  56052. owner->dragImageComponent.release();
  56053. if (mouseDragSource != 0)
  56054. {
  56055. mouseDragSource->removeMouseListener (this);
  56056. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56057. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56058. }
  56059. }
  56060. void paint (Graphics& g)
  56061. {
  56062. if (isOpaque())
  56063. g.fillAll (Colours::white);
  56064. if (drawImage)
  56065. {
  56066. g.setOpacity (1.0f);
  56067. g.drawImageAt (image, 0, 0);
  56068. }
  56069. }
  56070. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56071. {
  56072. Component* hit = getParentComponent();
  56073. if (hit == 0)
  56074. {
  56075. hit = Desktop::getInstance().findComponentAt (screenPos);
  56076. }
  56077. else
  56078. {
  56079. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56080. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56081. }
  56082. // (note: use a local copy of the dragDesc member in case the callback runs
  56083. // a modal loop and deletes this object before the method completes)
  56084. const String dragDescLocal (dragDesc);
  56085. while (hit != 0)
  56086. {
  56087. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56088. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56089. {
  56090. relativePos = hit->globalPositionToRelative (screenPos);
  56091. return ddt;
  56092. }
  56093. hit = hit->getParentComponent();
  56094. }
  56095. return 0;
  56096. }
  56097. void mouseUp (const MouseEvent& e)
  56098. {
  56099. if (e.originalComponent != this)
  56100. {
  56101. if (mouseDragSource != 0)
  56102. mouseDragSource->removeMouseListener (this);
  56103. bool dropAccepted = false;
  56104. DragAndDropTarget* ddt = 0;
  56105. Point<int> relPos;
  56106. if (isVisible())
  56107. {
  56108. setVisible (false);
  56109. ddt = findTarget (e.getScreenPosition(), relPos);
  56110. // fade this component and remove it - it'll be deleted later by the timer callback
  56111. dropAccepted = ddt != 0;
  56112. setVisible (true);
  56113. if (dropAccepted || source == 0)
  56114. {
  56115. fadeOutComponent (120);
  56116. }
  56117. else
  56118. {
  56119. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56120. source->getHeight() / 2)));
  56121. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56122. getHeight() / 2)));
  56123. fadeOutComponent (120,
  56124. target.getX() - ourCentre.getX(),
  56125. target.getY() - ourCentre.getY());
  56126. }
  56127. }
  56128. if (getParentComponent() != 0)
  56129. getParentComponent()->removeChildComponent (this);
  56130. if (dropAccepted && ddt != 0)
  56131. {
  56132. // (note: use a local copy of the dragDesc member in case the callback runs
  56133. // a modal loop and deletes this object before the method completes)
  56134. const String dragDescLocal (dragDesc);
  56135. currentlyOverComp = 0;
  56136. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56137. }
  56138. // careful - this object could now be deleted..
  56139. }
  56140. }
  56141. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56142. {
  56143. // (note: use a local copy of the dragDesc member in case the callback runs
  56144. // a modal loop and deletes this object before it returns)
  56145. const String dragDescLocal (dragDesc);
  56146. Point<int> newPos (screenPos + imageOffset);
  56147. if (getParentComponent() != 0)
  56148. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56149. //if (newX != getX() || newY != getY())
  56150. {
  56151. setTopLeftPosition (newPos.getX(), newPos.getY());
  56152. Point<int> relPos;
  56153. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56154. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56155. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56156. if (ddtComp != currentlyOverComp)
  56157. {
  56158. if (currentlyOverComp != 0 && source != 0
  56159. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56160. {
  56161. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56162. }
  56163. currentlyOverComp = ddtComp;
  56164. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56165. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56166. }
  56167. DragAndDropTarget* target = getCurrentlyOver();
  56168. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56169. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56170. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56171. {
  56172. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56173. {
  56174. hasCheckedForExternalDrag = true;
  56175. StringArray files;
  56176. bool canMoveFiles = false;
  56177. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56178. && files.size() > 0)
  56179. {
  56180. Component::SafePointer<Component> cdw (this);
  56181. setVisible (false);
  56182. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56183. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56184. if (cdw != 0)
  56185. delete this;
  56186. return;
  56187. }
  56188. }
  56189. }
  56190. }
  56191. }
  56192. void mouseDrag (const MouseEvent& e)
  56193. {
  56194. if (e.originalComponent != this)
  56195. updateLocation (true, e.getScreenPosition());
  56196. }
  56197. void timerCallback()
  56198. {
  56199. if (source == 0)
  56200. {
  56201. delete this;
  56202. }
  56203. else if (! isMouseButtonDownAnywhere())
  56204. {
  56205. if (mouseDragSource != 0)
  56206. mouseDragSource->removeMouseListener (this);
  56207. delete this;
  56208. }
  56209. }
  56210. private:
  56211. Image image;
  56212. Component::SafePointer<Component> source;
  56213. Component::SafePointer<Component> mouseDragSource;
  56214. DragAndDropContainer* const owner;
  56215. Component::SafePointer<Component> currentlyOverComp;
  56216. DragAndDropTarget* getCurrentlyOver()
  56217. {
  56218. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56219. }
  56220. String dragDesc;
  56221. const Point<int> imageOffset;
  56222. bool hasCheckedForExternalDrag, drawImage;
  56223. DragImageComponent (const DragImageComponent&);
  56224. DragImageComponent& operator= (const DragImageComponent&);
  56225. };
  56226. DragAndDropContainer::DragAndDropContainer()
  56227. {
  56228. }
  56229. DragAndDropContainer::~DragAndDropContainer()
  56230. {
  56231. dragImageComponent = 0;
  56232. }
  56233. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56234. Component* sourceComponent,
  56235. const Image& dragImage_,
  56236. const bool allowDraggingToExternalWindows,
  56237. const Point<int>* imageOffsetFromMouse)
  56238. {
  56239. Image dragImage (dragImage_);
  56240. if (dragImageComponent == 0)
  56241. {
  56242. Component* const thisComp = dynamic_cast <Component*> (this);
  56243. if (thisComp == 0)
  56244. {
  56245. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56246. return;
  56247. }
  56248. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56249. if (draggingSource == 0 || ! draggingSource->isDragging())
  56250. {
  56251. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56252. return;
  56253. }
  56254. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56255. Point<int> imageOffset;
  56256. if (dragImage.isNull())
  56257. {
  56258. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56259. .convertedToFormat (Image::ARGB);
  56260. dragImage.multiplyAllAlphas (0.6f);
  56261. const int lo = 150;
  56262. const int hi = 400;
  56263. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56264. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56265. for (int y = dragImage.getHeight(); --y >= 0;)
  56266. {
  56267. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56268. for (int x = dragImage.getWidth(); --x >= 0;)
  56269. {
  56270. const int dx = x - clipped.getX();
  56271. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56272. if (distance > lo)
  56273. {
  56274. const float alpha = (distance > hi) ? 0
  56275. : (hi - distance) / (float) (hi - lo)
  56276. + Random::getSystemRandom().nextFloat() * 0.008f;
  56277. dragImage.multiplyAlphaAt (x, y, alpha);
  56278. }
  56279. }
  56280. }
  56281. imageOffset = -clipped;
  56282. }
  56283. else
  56284. {
  56285. if (imageOffsetFromMouse == 0)
  56286. imageOffset = -dragImage.getBounds().getCentre();
  56287. else
  56288. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56289. }
  56290. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56291. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56292. currentDragDesc = sourceDescription;
  56293. if (allowDraggingToExternalWindows)
  56294. {
  56295. if (! Desktop::canUseSemiTransparentWindows())
  56296. dragImageComponent->setOpaque (true);
  56297. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56298. | ComponentPeer::windowIsTemporary
  56299. | ComponentPeer::windowIgnoresKeyPresses);
  56300. }
  56301. else
  56302. thisComp->addChildComponent (dragImageComponent);
  56303. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56304. dragImageComponent->setVisible (true);
  56305. }
  56306. }
  56307. bool DragAndDropContainer::isDragAndDropActive() const
  56308. {
  56309. return dragImageComponent != 0;
  56310. }
  56311. const String DragAndDropContainer::getCurrentDragDescription() const
  56312. {
  56313. return (dragImageComponent != 0) ? currentDragDesc
  56314. : String::empty;
  56315. }
  56316. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56317. {
  56318. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56319. }
  56320. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56321. {
  56322. return false;
  56323. }
  56324. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56325. {
  56326. }
  56327. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56328. {
  56329. }
  56330. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56331. {
  56332. }
  56333. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56334. {
  56335. return true;
  56336. }
  56337. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56338. {
  56339. }
  56340. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56341. {
  56342. }
  56343. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56344. {
  56345. }
  56346. END_JUCE_NAMESPACE
  56347. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56348. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56349. BEGIN_JUCE_NAMESPACE
  56350. class MouseCursor::SharedCursorHandle
  56351. {
  56352. public:
  56353. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56354. : handle (createStandardMouseCursor (type)),
  56355. refCount (1),
  56356. standardType (type),
  56357. isStandard (true)
  56358. {
  56359. }
  56360. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56361. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56362. refCount (1),
  56363. standardType (MouseCursor::NormalCursor),
  56364. isStandard (false)
  56365. {
  56366. }
  56367. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56368. {
  56369. const ScopedLock sl (getLock());
  56370. for (int i = getCursors().size(); --i >= 0;)
  56371. {
  56372. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56373. if (sc->standardType == type)
  56374. return sc->retain();
  56375. }
  56376. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56377. getCursors().add (sc);
  56378. return sc;
  56379. }
  56380. SharedCursorHandle* retain() throw()
  56381. {
  56382. ++refCount;
  56383. return this;
  56384. }
  56385. void release()
  56386. {
  56387. if (--refCount == 0)
  56388. {
  56389. if (isStandard)
  56390. {
  56391. const ScopedLock sl (getLock());
  56392. getCursors().removeValue (this);
  56393. }
  56394. delete this;
  56395. }
  56396. }
  56397. void* getHandle() const throw() { return handle; }
  56398. juce_UseDebuggingNewOperator
  56399. private:
  56400. void* const handle;
  56401. Atomic <int> refCount;
  56402. const MouseCursor::StandardCursorType standardType;
  56403. const bool isStandard;
  56404. static CriticalSection& getLock()
  56405. {
  56406. static CriticalSection lock;
  56407. return lock;
  56408. }
  56409. static Array <SharedCursorHandle*>& getCursors()
  56410. {
  56411. static Array <SharedCursorHandle*> cursors;
  56412. return cursors;
  56413. }
  56414. ~SharedCursorHandle()
  56415. {
  56416. deleteMouseCursor (handle, isStandard);
  56417. }
  56418. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56419. };
  56420. MouseCursor::MouseCursor()
  56421. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56422. {
  56423. jassert (cursorHandle != 0);
  56424. }
  56425. MouseCursor::MouseCursor (const StandardCursorType type)
  56426. : cursorHandle (SharedCursorHandle::createStandard (type))
  56427. {
  56428. jassert (cursorHandle != 0);
  56429. }
  56430. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56431. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56432. {
  56433. }
  56434. MouseCursor::MouseCursor (const MouseCursor& other)
  56435. : cursorHandle (other.cursorHandle->retain())
  56436. {
  56437. }
  56438. MouseCursor::~MouseCursor()
  56439. {
  56440. cursorHandle->release();
  56441. }
  56442. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56443. {
  56444. other.cursorHandle->retain();
  56445. cursorHandle->release();
  56446. cursorHandle = other.cursorHandle;
  56447. return *this;
  56448. }
  56449. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56450. {
  56451. return getHandle() == other.getHandle();
  56452. }
  56453. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56454. {
  56455. return getHandle() != other.getHandle();
  56456. }
  56457. void* MouseCursor::getHandle() const throw()
  56458. {
  56459. return cursorHandle->getHandle();
  56460. }
  56461. void MouseCursor::showWaitCursor()
  56462. {
  56463. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56464. }
  56465. void MouseCursor::hideWaitCursor()
  56466. {
  56467. Desktop::getInstance().getMainMouseSource().revealCursor();
  56468. }
  56469. END_JUCE_NAMESPACE
  56470. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56471. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56472. BEGIN_JUCE_NAMESPACE
  56473. MouseEvent::MouseEvent (MouseInputSource& source_,
  56474. const Point<int>& position,
  56475. const ModifierKeys& mods_,
  56476. Component* const eventComponent_,
  56477. Component* const originator,
  56478. const Time& eventTime_,
  56479. const Point<int> mouseDownPos_,
  56480. const Time& mouseDownTime_,
  56481. const int numberOfClicks_,
  56482. const bool mouseWasDragged) throw()
  56483. : x (position.getX()),
  56484. y (position.getY()),
  56485. mods (mods_),
  56486. eventComponent (eventComponent_),
  56487. originalComponent (originator),
  56488. eventTime (eventTime_),
  56489. source (source_),
  56490. mouseDownPos (mouseDownPos_),
  56491. mouseDownTime (mouseDownTime_),
  56492. numberOfClicks (numberOfClicks_),
  56493. wasMovedSinceMouseDown (mouseWasDragged)
  56494. {
  56495. }
  56496. MouseEvent::~MouseEvent() throw()
  56497. {
  56498. }
  56499. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56500. {
  56501. if (otherComponent == 0)
  56502. {
  56503. jassertfalse;
  56504. return *this;
  56505. }
  56506. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56507. mods, otherComponent, originalComponent, eventTime,
  56508. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56509. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56510. }
  56511. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56512. {
  56513. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  56514. eventTime, mouseDownPos, mouseDownTime,
  56515. numberOfClicks, wasMovedSinceMouseDown);
  56516. }
  56517. bool MouseEvent::mouseWasClicked() const throw()
  56518. {
  56519. return ! wasMovedSinceMouseDown;
  56520. }
  56521. int MouseEvent::getMouseDownX() const throw()
  56522. {
  56523. return mouseDownPos.getX();
  56524. }
  56525. int MouseEvent::getMouseDownY() const throw()
  56526. {
  56527. return mouseDownPos.getY();
  56528. }
  56529. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56530. {
  56531. return mouseDownPos;
  56532. }
  56533. int MouseEvent::getDistanceFromDragStartX() const throw()
  56534. {
  56535. return x - mouseDownPos.getX();
  56536. }
  56537. int MouseEvent::getDistanceFromDragStartY() const throw()
  56538. {
  56539. return y - mouseDownPos.getY();
  56540. }
  56541. int MouseEvent::getDistanceFromDragStart() const throw()
  56542. {
  56543. return mouseDownPos.getDistanceFrom (getPosition());
  56544. }
  56545. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56546. {
  56547. return getPosition() - mouseDownPos;
  56548. }
  56549. int MouseEvent::getLengthOfMousePress() const throw()
  56550. {
  56551. if (mouseDownTime.toMilliseconds() > 0)
  56552. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56553. return 0;
  56554. }
  56555. const Point<int> MouseEvent::getPosition() const throw()
  56556. {
  56557. return Point<int> (x, y);
  56558. }
  56559. int MouseEvent::getScreenX() const
  56560. {
  56561. return getScreenPosition().getX();
  56562. }
  56563. int MouseEvent::getScreenY() const
  56564. {
  56565. return getScreenPosition().getY();
  56566. }
  56567. const Point<int> MouseEvent::getScreenPosition() const
  56568. {
  56569. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56570. }
  56571. int MouseEvent::getMouseDownScreenX() const
  56572. {
  56573. return getMouseDownScreenPosition().getX();
  56574. }
  56575. int MouseEvent::getMouseDownScreenY() const
  56576. {
  56577. return getMouseDownScreenPosition().getY();
  56578. }
  56579. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56580. {
  56581. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56582. }
  56583. static int doubleClickTimeOutMs = 400;
  56584. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56585. {
  56586. doubleClickTimeOutMs = newTime;
  56587. }
  56588. int MouseEvent::getDoubleClickTimeout() throw()
  56589. {
  56590. return doubleClickTimeOutMs;
  56591. }
  56592. END_JUCE_NAMESPACE
  56593. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56594. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56595. BEGIN_JUCE_NAMESPACE
  56596. class MouseInputSourceInternal : public AsyncUpdater
  56597. {
  56598. public:
  56599. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56600. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56601. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56602. mouseEventCounter (0)
  56603. {
  56604. zerostruct (mouseDowns);
  56605. }
  56606. ~MouseInputSourceInternal()
  56607. {
  56608. }
  56609. bool isDragging() const throw()
  56610. {
  56611. return buttonState.isAnyMouseButtonDown();
  56612. }
  56613. Component* getComponentUnderMouse() const
  56614. {
  56615. return static_cast <Component*> (componentUnderMouse);
  56616. }
  56617. const ModifierKeys getCurrentModifiers() const
  56618. {
  56619. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56620. }
  56621. ComponentPeer* getPeer()
  56622. {
  56623. if (! ComponentPeer::isValidPeer (lastPeer))
  56624. lastPeer = 0;
  56625. return lastPeer;
  56626. }
  56627. Component* findComponentAt (const Point<int>& screenPos)
  56628. {
  56629. ComponentPeer* const peer = getPeer();
  56630. if (peer != 0)
  56631. {
  56632. Component* const comp = peer->getComponent();
  56633. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56634. // (the contains() call is needed to test for overlapping desktop windows)
  56635. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56636. return comp->getComponentAt (relativePos);
  56637. }
  56638. return 0;
  56639. }
  56640. const Point<int> getScreenPosition() const throw()
  56641. {
  56642. return lastScreenPos + unboundedMouseOffset;
  56643. }
  56644. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56645. {
  56646. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56647. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56648. }
  56649. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56650. {
  56651. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56652. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56653. }
  56654. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56655. {
  56656. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56657. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56658. }
  56659. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56660. {
  56661. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56662. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56663. }
  56664. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56665. {
  56666. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56667. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56668. }
  56669. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56670. {
  56671. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56672. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56673. }
  56674. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56675. {
  56676. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56677. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56678. }
  56679. // (returns true if the button change caused a modal event loop)
  56680. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56681. {
  56682. if (buttonState == newButtonState)
  56683. return false;
  56684. // (ignore secondary clicks when there's already a button down)
  56685. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56686. {
  56687. buttonState = newButtonState;
  56688. return false;
  56689. }
  56690. const int lastCounter = mouseEventCounter;
  56691. if (buttonState.isAnyMouseButtonDown())
  56692. {
  56693. Component* const current = getComponentUnderMouse();
  56694. if (current != 0)
  56695. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56696. enableUnboundedMouseMovement (false, false);
  56697. }
  56698. buttonState = newButtonState;
  56699. if (buttonState.isAnyMouseButtonDown())
  56700. {
  56701. Desktop::getInstance().incrementMouseClickCounter();
  56702. Component* const current = getComponentUnderMouse();
  56703. if (current != 0)
  56704. {
  56705. registerMouseDown (screenPos, time, current);
  56706. sendMouseDown (current, screenPos, time);
  56707. }
  56708. }
  56709. return lastCounter != mouseEventCounter;
  56710. }
  56711. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56712. {
  56713. Component* current = getComponentUnderMouse();
  56714. if (newComponent != current)
  56715. {
  56716. Component::SafePointer<Component> safeNewComp (newComponent);
  56717. const ModifierKeys originalButtonState (buttonState);
  56718. if (current != 0)
  56719. {
  56720. setButtons (screenPos, time, ModifierKeys());
  56721. sendMouseExit (current, screenPos, time);
  56722. buttonState = originalButtonState;
  56723. }
  56724. componentUnderMouse = safeNewComp;
  56725. current = getComponentUnderMouse();
  56726. if (current != 0)
  56727. sendMouseEnter (current, screenPos, time);
  56728. revealCursor (false);
  56729. setButtons (screenPos, time, originalButtonState);
  56730. }
  56731. }
  56732. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56733. {
  56734. ModifierKeys::updateCurrentModifiers();
  56735. if (newPeer != lastPeer)
  56736. {
  56737. setComponentUnderMouse (0, screenPos, time);
  56738. lastPeer = newPeer;
  56739. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56740. }
  56741. }
  56742. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56743. {
  56744. if (! isDragging())
  56745. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56746. if (newScreenPos != lastScreenPos || forceUpdate)
  56747. {
  56748. cancelPendingUpdate();
  56749. lastScreenPos = newScreenPos;
  56750. Component* const current = getComponentUnderMouse();
  56751. if (current != 0)
  56752. {
  56753. if (isDragging())
  56754. {
  56755. registerMouseDrag (newScreenPos);
  56756. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56757. if (isUnboundedMouseModeOn)
  56758. handleUnboundedDrag (current);
  56759. }
  56760. else
  56761. {
  56762. sendMouseMove (current, newScreenPos, time);
  56763. }
  56764. }
  56765. revealCursor (false);
  56766. }
  56767. }
  56768. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56769. {
  56770. jassert (newPeer != 0);
  56771. lastTime = time;
  56772. ++mouseEventCounter;
  56773. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56774. if (isDragging() && newMods.isAnyMouseButtonDown())
  56775. {
  56776. setScreenPos (screenPos, time, false);
  56777. }
  56778. else
  56779. {
  56780. setPeer (newPeer, screenPos, time);
  56781. ComponentPeer* peer = getPeer();
  56782. if (peer != 0)
  56783. {
  56784. if (setButtons (screenPos, time, newMods))
  56785. return; // some modal events have been dispatched, so the current event is now out-of-date
  56786. peer = getPeer();
  56787. if (peer != 0)
  56788. setScreenPos (screenPos, time, false);
  56789. }
  56790. }
  56791. }
  56792. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56793. {
  56794. jassert (peer != 0);
  56795. lastTime = time;
  56796. ++mouseEventCounter;
  56797. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56798. setPeer (peer, screenPos, time);
  56799. setScreenPos (screenPos, time, false);
  56800. triggerFakeMove();
  56801. if (! isDragging())
  56802. {
  56803. Component* current = getComponentUnderMouse();
  56804. if (current != 0)
  56805. sendMouseWheel (current, screenPos, time, x, y);
  56806. }
  56807. }
  56808. const Time getLastMouseDownTime() const throw()
  56809. {
  56810. return Time (mouseDowns[0].time);
  56811. }
  56812. const Point<int> getLastMouseDownPosition() const throw()
  56813. {
  56814. return mouseDowns[0].position;
  56815. }
  56816. int getNumberOfMultipleClicks() const throw()
  56817. {
  56818. int numClicks = 0;
  56819. if (mouseDowns[0].time != 0)
  56820. {
  56821. if (! mouseMovedSignificantlySincePressed)
  56822. ++numClicks;
  56823. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  56824. {
  56825. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  56826. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  56827. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  56828. {
  56829. ++numClicks;
  56830. }
  56831. else
  56832. {
  56833. break;
  56834. }
  56835. }
  56836. }
  56837. return numClicks;
  56838. }
  56839. bool hasMouseMovedSignificantlySincePressed() const throw()
  56840. {
  56841. return mouseMovedSignificantlySincePressed
  56842. || lastTime > mouseDowns[0].time + 300;
  56843. }
  56844. void triggerFakeMove()
  56845. {
  56846. triggerAsyncUpdate();
  56847. }
  56848. void handleAsyncUpdate()
  56849. {
  56850. if (! isDragging())
  56851. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  56852. }
  56853. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  56854. {
  56855. enable = enable && isDragging();
  56856. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  56857. if (enable != isUnboundedMouseModeOn)
  56858. {
  56859. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  56860. {
  56861. // when released, return the mouse to within the component's bounds
  56862. Component* current = getComponentUnderMouse();
  56863. if (current != 0)
  56864. Desktop::setMousePosition (current->getScreenBounds()
  56865. .getConstrainedPoint (current->getMouseXYRelative()));
  56866. }
  56867. isUnboundedMouseModeOn = enable;
  56868. unboundedMouseOffset = Point<int>();
  56869. revealCursor (true);
  56870. }
  56871. }
  56872. void handleUnboundedDrag (Component* current)
  56873. {
  56874. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  56875. if (! screenArea.contains (lastScreenPos))
  56876. {
  56877. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  56878. unboundedMouseOffset += (lastScreenPos - componentCentre);
  56879. Desktop::setMousePosition (componentCentre);
  56880. }
  56881. else if (isCursorVisibleUntilOffscreen
  56882. && (! unboundedMouseOffset.isOrigin())
  56883. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  56884. {
  56885. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  56886. unboundedMouseOffset = Point<int>();
  56887. }
  56888. }
  56889. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  56890. {
  56891. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  56892. {
  56893. cursor = MouseCursor::NoCursor;
  56894. forcedUpdate = true;
  56895. }
  56896. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  56897. {
  56898. currentCursorHandle = cursor.getHandle();
  56899. cursor.showInWindow (getPeer());
  56900. }
  56901. }
  56902. void hideCursor()
  56903. {
  56904. showMouseCursor (MouseCursor::NoCursor, true);
  56905. }
  56906. void revealCursor (bool forcedUpdate)
  56907. {
  56908. MouseCursor mc (MouseCursor::NormalCursor);
  56909. Component* current = getComponentUnderMouse();
  56910. if (current != 0)
  56911. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  56912. showMouseCursor (mc, forcedUpdate);
  56913. }
  56914. int index;
  56915. bool isMouseDevice;
  56916. Point<int> lastScreenPos;
  56917. ModifierKeys buttonState;
  56918. private:
  56919. MouseInputSource& source;
  56920. Component::SafePointer<Component> componentUnderMouse;
  56921. ComponentPeer* lastPeer;
  56922. Point<int> unboundedMouseOffset;
  56923. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  56924. void* currentCursorHandle;
  56925. int mouseEventCounter;
  56926. struct RecentMouseDown
  56927. {
  56928. Point<int> position;
  56929. int64 time;
  56930. Component* component;
  56931. };
  56932. RecentMouseDown mouseDowns[4];
  56933. bool mouseMovedSignificantlySincePressed;
  56934. int64 lastTime;
  56935. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  56936. {
  56937. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  56938. mouseDowns[i] = mouseDowns[i - 1];
  56939. mouseDowns[0].position = screenPos;
  56940. mouseDowns[0].time = time;
  56941. mouseDowns[0].component = component;
  56942. mouseMovedSignificantlySincePressed = false;
  56943. }
  56944. void registerMouseDrag (const Point<int>& screenPos) throw()
  56945. {
  56946. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  56947. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  56948. }
  56949. MouseInputSourceInternal (const MouseInputSourceInternal&);
  56950. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  56951. };
  56952. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  56953. {
  56954. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  56955. }
  56956. MouseInputSource::~MouseInputSource()
  56957. {
  56958. }
  56959. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  56960. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  56961. bool MouseInputSource::canHover() const { return isMouse(); }
  56962. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  56963. int MouseInputSource::getIndex() const { return pimpl->index; }
  56964. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  56965. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  56966. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  56967. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  56968. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  56969. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  56970. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  56971. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  56972. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  56973. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  56974. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  56975. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  56976. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  56977. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  56978. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  56979. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  56980. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  56981. {
  56982. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  56983. }
  56984. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  56985. {
  56986. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  56987. }
  56988. END_JUCE_NAMESPACE
  56989. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  56990. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  56991. BEGIN_JUCE_NAMESPACE
  56992. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  56993. : source (0),
  56994. hoverTimeMillisecs (hoverTimeMillisecs_),
  56995. hasJustHovered (false)
  56996. {
  56997. internalTimer.owner = this;
  56998. }
  56999. MouseHoverDetector::~MouseHoverDetector()
  57000. {
  57001. setHoverComponent (0);
  57002. }
  57003. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57004. {
  57005. hoverTimeMillisecs = newTimeInMillisecs;
  57006. }
  57007. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57008. {
  57009. if (source != newSourceComponent)
  57010. {
  57011. internalTimer.stopTimer();
  57012. hasJustHovered = false;
  57013. if (source != 0)
  57014. {
  57015. // ! you need to delete the hover detector before deleting its component
  57016. jassert (source->isValidComponent());
  57017. source->removeMouseListener (&internalTimer);
  57018. }
  57019. source = newSourceComponent;
  57020. if (newSourceComponent != 0)
  57021. newSourceComponent->addMouseListener (&internalTimer, false);
  57022. }
  57023. }
  57024. void MouseHoverDetector::hoverTimerCallback()
  57025. {
  57026. internalTimer.stopTimer();
  57027. if (source != 0)
  57028. {
  57029. const Point<int> pos (source->getMouseXYRelative());
  57030. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57031. {
  57032. hasJustHovered = true;
  57033. mouseHovered (pos.getX(), pos.getY());
  57034. }
  57035. }
  57036. }
  57037. void MouseHoverDetector::checkJustHoveredCallback()
  57038. {
  57039. if (hasJustHovered)
  57040. {
  57041. hasJustHovered = false;
  57042. mouseMovedAfterHover();
  57043. }
  57044. }
  57045. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57046. {
  57047. owner->hoverTimerCallback();
  57048. }
  57049. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57050. {
  57051. stopTimer();
  57052. owner->checkJustHoveredCallback();
  57053. }
  57054. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57055. {
  57056. stopTimer();
  57057. owner->checkJustHoveredCallback();
  57058. }
  57059. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57060. {
  57061. stopTimer();
  57062. owner->checkJustHoveredCallback();
  57063. }
  57064. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57065. {
  57066. stopTimer();
  57067. owner->checkJustHoveredCallback();
  57068. }
  57069. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57070. {
  57071. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57072. {
  57073. lastX = e.x;
  57074. lastY = e.y;
  57075. if (owner->source != 0)
  57076. startTimer (owner->hoverTimeMillisecs);
  57077. owner->checkJustHoveredCallback();
  57078. }
  57079. }
  57080. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57081. {
  57082. stopTimer();
  57083. owner->checkJustHoveredCallback();
  57084. }
  57085. END_JUCE_NAMESPACE
  57086. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57087. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57088. BEGIN_JUCE_NAMESPACE
  57089. void MouseListener::mouseEnter (const MouseEvent&)
  57090. {
  57091. }
  57092. void MouseListener::mouseExit (const MouseEvent&)
  57093. {
  57094. }
  57095. void MouseListener::mouseDown (const MouseEvent&)
  57096. {
  57097. }
  57098. void MouseListener::mouseUp (const MouseEvent&)
  57099. {
  57100. }
  57101. void MouseListener::mouseDrag (const MouseEvent&)
  57102. {
  57103. }
  57104. void MouseListener::mouseMove (const MouseEvent&)
  57105. {
  57106. }
  57107. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57108. {
  57109. }
  57110. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57111. {
  57112. }
  57113. END_JUCE_NAMESPACE
  57114. /*** End of inlined file: juce_MouseListener.cpp ***/
  57115. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57116. BEGIN_JUCE_NAMESPACE
  57117. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57118. const String& buttonTextWhenTrue,
  57119. const String& buttonTextWhenFalse)
  57120. : PropertyComponent (name),
  57121. onText (buttonTextWhenTrue),
  57122. offText (buttonTextWhenFalse)
  57123. {
  57124. createButton();
  57125. button->addButtonListener (this);
  57126. }
  57127. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57128. const String& name,
  57129. const String& buttonText)
  57130. : PropertyComponent (name),
  57131. onText (buttonText),
  57132. offText (buttonText)
  57133. {
  57134. createButton();
  57135. button->setButtonText (buttonText);
  57136. button->getToggleStateValue().referTo (valueToControl);
  57137. button->setClickingTogglesState (true);
  57138. }
  57139. BooleanPropertyComponent::~BooleanPropertyComponent()
  57140. {
  57141. deleteAllChildren();
  57142. }
  57143. void BooleanPropertyComponent::createButton()
  57144. {
  57145. addAndMakeVisible (button = new ToggleButton (String::empty));
  57146. button->setClickingTogglesState (false);
  57147. }
  57148. void BooleanPropertyComponent::setState (const bool newState)
  57149. {
  57150. button->setToggleState (newState, true);
  57151. }
  57152. bool BooleanPropertyComponent::getState() const
  57153. {
  57154. return button->getToggleState();
  57155. }
  57156. void BooleanPropertyComponent::paint (Graphics& g)
  57157. {
  57158. PropertyComponent::paint (g);
  57159. g.setColour (Colours::white);
  57160. g.fillRect (button->getBounds());
  57161. g.setColour (findColour (ComboBox::outlineColourId));
  57162. g.drawRect (button->getBounds());
  57163. }
  57164. void BooleanPropertyComponent::refresh()
  57165. {
  57166. button->setToggleState (getState(), false);
  57167. button->setButtonText (button->getToggleState() ? onText : offText);
  57168. }
  57169. void BooleanPropertyComponent::buttonClicked (Button*)
  57170. {
  57171. setState (! getState());
  57172. }
  57173. END_JUCE_NAMESPACE
  57174. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57175. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57176. BEGIN_JUCE_NAMESPACE
  57177. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57178. const bool triggerOnMouseDown)
  57179. : PropertyComponent (name)
  57180. {
  57181. addAndMakeVisible (button = new TextButton (String::empty));
  57182. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  57183. button->addButtonListener (this);
  57184. }
  57185. ButtonPropertyComponent::~ButtonPropertyComponent()
  57186. {
  57187. deleteAllChildren();
  57188. }
  57189. void ButtonPropertyComponent::refresh()
  57190. {
  57191. button->setButtonText (getButtonText());
  57192. }
  57193. void ButtonPropertyComponent::buttonClicked (Button*)
  57194. {
  57195. buttonClicked();
  57196. }
  57197. END_JUCE_NAMESPACE
  57198. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57199. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57200. BEGIN_JUCE_NAMESPACE
  57201. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57202. public Value::Listener
  57203. {
  57204. public:
  57205. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57206. : sourceValue (sourceValue_),
  57207. mappings (mappings_)
  57208. {
  57209. sourceValue.addListener (this);
  57210. }
  57211. ~RemapperValueSource() {}
  57212. const var getValue() const
  57213. {
  57214. return mappings.indexOf (sourceValue.getValue()) + 1;
  57215. }
  57216. void setValue (const var& newValue)
  57217. {
  57218. const var remappedVal (mappings [(int) newValue - 1]);
  57219. if (remappedVal != sourceValue)
  57220. sourceValue = remappedVal;
  57221. }
  57222. void valueChanged (Value&)
  57223. {
  57224. sendChangeMessage (true);
  57225. }
  57226. juce_UseDebuggingNewOperator
  57227. protected:
  57228. Value sourceValue;
  57229. Array<var> mappings;
  57230. RemapperValueSource (const RemapperValueSource&);
  57231. const RemapperValueSource& operator= (const RemapperValueSource&);
  57232. };
  57233. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57234. : PropertyComponent (name),
  57235. comboBox (0),
  57236. isCustomClass (true)
  57237. {
  57238. }
  57239. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57240. const String& name,
  57241. const StringArray& choices_,
  57242. const Array <var>& correspondingValues)
  57243. : PropertyComponent (name),
  57244. choices (choices_),
  57245. comboBox (0),
  57246. isCustomClass (false)
  57247. {
  57248. // The array of corresponding values must contain one value for each of the items in
  57249. // the choices array!
  57250. jassert (correspondingValues.size() == choices.size());
  57251. createComboBox();
  57252. comboBox->getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57253. }
  57254. ChoicePropertyComponent::~ChoicePropertyComponent()
  57255. {
  57256. deleteAllChildren();
  57257. }
  57258. void ChoicePropertyComponent::createComboBox()
  57259. {
  57260. addAndMakeVisible (comboBox = new ComboBox());
  57261. for (int i = 0; i < choices.size(); ++i)
  57262. {
  57263. if (choices[i].isNotEmpty())
  57264. comboBox->addItem (choices[i], i + 1);
  57265. else
  57266. comboBox->addSeparator();
  57267. }
  57268. comboBox->setEditableText (false);
  57269. }
  57270. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57271. {
  57272. jassertfalse; // you need to override this method in your subclass!
  57273. }
  57274. int ChoicePropertyComponent::getIndex() const
  57275. {
  57276. jassertfalse; // you need to override this method in your subclass!
  57277. return -1;
  57278. }
  57279. const StringArray& ChoicePropertyComponent::getChoices() const
  57280. {
  57281. return choices;
  57282. }
  57283. void ChoicePropertyComponent::refresh()
  57284. {
  57285. if (isCustomClass)
  57286. {
  57287. if (comboBox == 0)
  57288. {
  57289. createComboBox();
  57290. comboBox->addListener (this);
  57291. }
  57292. comboBox->setSelectedId (getIndex() + 1, true);
  57293. }
  57294. }
  57295. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57296. {
  57297. if (isCustomClass)
  57298. {
  57299. const int newIndex = comboBox->getSelectedId() - 1;
  57300. if (newIndex != getIndex())
  57301. setIndex (newIndex);
  57302. }
  57303. }
  57304. END_JUCE_NAMESPACE
  57305. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57306. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57307. BEGIN_JUCE_NAMESPACE
  57308. PropertyComponent::PropertyComponent (const String& name,
  57309. const int preferredHeight_)
  57310. : Component (name),
  57311. preferredHeight (preferredHeight_)
  57312. {
  57313. jassert (name.isNotEmpty());
  57314. }
  57315. PropertyComponent::~PropertyComponent()
  57316. {
  57317. }
  57318. void PropertyComponent::paint (Graphics& g)
  57319. {
  57320. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57321. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57322. }
  57323. void PropertyComponent::resized()
  57324. {
  57325. if (getNumChildComponents() > 0)
  57326. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57327. }
  57328. void PropertyComponent::enablementChanged()
  57329. {
  57330. repaint();
  57331. }
  57332. END_JUCE_NAMESPACE
  57333. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57334. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57335. BEGIN_JUCE_NAMESPACE
  57336. class PropertyPanel::PropertyHolderComponent : public Component
  57337. {
  57338. public:
  57339. PropertyHolderComponent()
  57340. {
  57341. }
  57342. ~PropertyHolderComponent()
  57343. {
  57344. deleteAllChildren();
  57345. }
  57346. void paint (Graphics&)
  57347. {
  57348. }
  57349. void updateLayout (int width);
  57350. void refreshAll() const;
  57351. private:
  57352. PropertyHolderComponent (const PropertyHolderComponent&);
  57353. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57354. };
  57355. class PropertySectionComponent : public Component
  57356. {
  57357. public:
  57358. PropertySectionComponent (const String& sectionTitle,
  57359. const Array <PropertyComponent*>& newProperties,
  57360. const bool open)
  57361. : Component (sectionTitle),
  57362. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57363. isOpen_ (open)
  57364. {
  57365. for (int i = newProperties.size(); --i >= 0;)
  57366. {
  57367. addAndMakeVisible (newProperties.getUnchecked(i));
  57368. newProperties.getUnchecked(i)->refresh();
  57369. }
  57370. }
  57371. ~PropertySectionComponent()
  57372. {
  57373. deleteAllChildren();
  57374. }
  57375. void paint (Graphics& g)
  57376. {
  57377. if (titleHeight > 0)
  57378. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57379. }
  57380. void resized()
  57381. {
  57382. int y = titleHeight;
  57383. for (int i = getNumChildComponents(); --i >= 0;)
  57384. {
  57385. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57386. if (pec != 0)
  57387. {
  57388. const int prefH = pec->getPreferredHeight();
  57389. pec->setBounds (1, y, getWidth() - 2, prefH);
  57390. y += prefH;
  57391. }
  57392. }
  57393. }
  57394. int getPreferredHeight() const
  57395. {
  57396. int y = titleHeight;
  57397. if (isOpen())
  57398. {
  57399. for (int i = 0; i < getNumChildComponents(); ++i)
  57400. {
  57401. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57402. if (pec != 0)
  57403. y += pec->getPreferredHeight();
  57404. }
  57405. }
  57406. return y;
  57407. }
  57408. void setOpen (const bool open)
  57409. {
  57410. if (isOpen_ != open)
  57411. {
  57412. isOpen_ = open;
  57413. for (int i = 0; i < getNumChildComponents(); ++i)
  57414. {
  57415. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57416. if (pec != 0)
  57417. pec->setVisible (open);
  57418. }
  57419. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57420. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57421. if (pp != 0)
  57422. pp->resized();
  57423. }
  57424. }
  57425. bool isOpen() const
  57426. {
  57427. return isOpen_;
  57428. }
  57429. void refreshAll() const
  57430. {
  57431. for (int i = 0; i < getNumChildComponents(); ++i)
  57432. {
  57433. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57434. if (pec != 0)
  57435. pec->refresh();
  57436. }
  57437. }
  57438. void mouseDown (const MouseEvent&)
  57439. {
  57440. }
  57441. void mouseUp (const MouseEvent& e)
  57442. {
  57443. if (e.getMouseDownX() < titleHeight
  57444. && e.x < titleHeight
  57445. && e.y < titleHeight
  57446. && e.getNumberOfClicks() != 2)
  57447. {
  57448. setOpen (! isOpen());
  57449. }
  57450. }
  57451. void mouseDoubleClick (const MouseEvent& e)
  57452. {
  57453. if (e.y < titleHeight)
  57454. setOpen (! isOpen());
  57455. }
  57456. private:
  57457. int titleHeight;
  57458. bool isOpen_;
  57459. PropertySectionComponent (const PropertySectionComponent&);
  57460. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57461. };
  57462. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57463. {
  57464. int y = 0;
  57465. for (int i = getNumChildComponents(); --i >= 0;)
  57466. {
  57467. PropertySectionComponent* const section
  57468. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57469. if (section != 0)
  57470. {
  57471. const int prefH = section->getPreferredHeight();
  57472. section->setBounds (0, y, width, prefH);
  57473. y += prefH;
  57474. }
  57475. }
  57476. setSize (width, y);
  57477. repaint();
  57478. }
  57479. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57480. {
  57481. for (int i = getNumChildComponents(); --i >= 0;)
  57482. {
  57483. PropertySectionComponent* const section
  57484. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57485. if (section != 0)
  57486. section->refreshAll();
  57487. }
  57488. }
  57489. PropertyPanel::PropertyPanel()
  57490. {
  57491. messageWhenEmpty = TRANS("(nothing selected)");
  57492. addAndMakeVisible (viewport = new Viewport());
  57493. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57494. viewport->setFocusContainer (true);
  57495. }
  57496. PropertyPanel::~PropertyPanel()
  57497. {
  57498. clear();
  57499. deleteAllChildren();
  57500. }
  57501. void PropertyPanel::paint (Graphics& g)
  57502. {
  57503. if (propertyHolderComponent->getNumChildComponents() == 0)
  57504. {
  57505. g.setColour (Colours::black.withAlpha (0.5f));
  57506. g.setFont (14.0f);
  57507. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57508. Justification::centred, true);
  57509. }
  57510. }
  57511. void PropertyPanel::resized()
  57512. {
  57513. viewport->setBounds (0, 0, getWidth(), getHeight());
  57514. updatePropHolderLayout();
  57515. }
  57516. void PropertyPanel::clear()
  57517. {
  57518. if (propertyHolderComponent->getNumChildComponents() > 0)
  57519. {
  57520. propertyHolderComponent->deleteAllChildren();
  57521. repaint();
  57522. }
  57523. }
  57524. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57525. {
  57526. if (propertyHolderComponent->getNumChildComponents() == 0)
  57527. repaint();
  57528. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57529. newProperties,
  57530. true), 0);
  57531. updatePropHolderLayout();
  57532. }
  57533. void PropertyPanel::addSection (const String& sectionTitle,
  57534. const Array <PropertyComponent*>& newProperties,
  57535. const bool shouldBeOpen)
  57536. {
  57537. jassert (sectionTitle.isNotEmpty());
  57538. if (propertyHolderComponent->getNumChildComponents() == 0)
  57539. repaint();
  57540. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57541. newProperties,
  57542. shouldBeOpen), 0);
  57543. updatePropHolderLayout();
  57544. }
  57545. void PropertyPanel::updatePropHolderLayout() const
  57546. {
  57547. const int maxWidth = viewport->getMaximumVisibleWidth();
  57548. propertyHolderComponent->updateLayout (maxWidth);
  57549. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  57550. if (maxWidth != newMaxWidth)
  57551. {
  57552. // need to do this twice because of scrollbars changing the size, etc.
  57553. propertyHolderComponent->updateLayout (newMaxWidth);
  57554. }
  57555. }
  57556. void PropertyPanel::refreshAll() const
  57557. {
  57558. propertyHolderComponent->refreshAll();
  57559. }
  57560. const StringArray PropertyPanel::getSectionNames() const
  57561. {
  57562. StringArray s;
  57563. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57564. {
  57565. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57566. if (section != 0 && section->getName().isNotEmpty())
  57567. s.add (section->getName());
  57568. }
  57569. return s;
  57570. }
  57571. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57572. {
  57573. int index = 0;
  57574. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57575. {
  57576. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57577. if (section != 0 && section->getName().isNotEmpty())
  57578. {
  57579. if (index == sectionIndex)
  57580. return section->isOpen();
  57581. ++index;
  57582. }
  57583. }
  57584. return false;
  57585. }
  57586. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57587. {
  57588. int index = 0;
  57589. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57590. {
  57591. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57592. if (section != 0 && section->getName().isNotEmpty())
  57593. {
  57594. if (index == sectionIndex)
  57595. {
  57596. section->setOpen (shouldBeOpen);
  57597. break;
  57598. }
  57599. ++index;
  57600. }
  57601. }
  57602. }
  57603. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57604. {
  57605. int index = 0;
  57606. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57607. {
  57608. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57609. if (section != 0 && section->getName().isNotEmpty())
  57610. {
  57611. if (index == sectionIndex)
  57612. {
  57613. section->setEnabled (shouldBeEnabled);
  57614. break;
  57615. }
  57616. ++index;
  57617. }
  57618. }
  57619. }
  57620. XmlElement* PropertyPanel::getOpennessState() const
  57621. {
  57622. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57623. xml->setAttribute ("scrollPos", viewport->getViewPositionY());
  57624. const StringArray sections (getSectionNames());
  57625. for (int i = 0; i < sections.size(); ++i)
  57626. {
  57627. if (sections[i].isNotEmpty())
  57628. {
  57629. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57630. e->setAttribute ("name", sections[i]);
  57631. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57632. }
  57633. }
  57634. return xml;
  57635. }
  57636. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57637. {
  57638. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57639. {
  57640. const StringArray sections (getSectionNames());
  57641. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57642. {
  57643. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57644. e->getBoolAttribute ("open"));
  57645. }
  57646. viewport->setViewPosition (viewport->getViewPositionX(),
  57647. xml.getIntAttribute ("scrollPos", viewport->getViewPositionY()));
  57648. }
  57649. }
  57650. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57651. {
  57652. if (messageWhenEmpty != newMessage)
  57653. {
  57654. messageWhenEmpty = newMessage;
  57655. repaint();
  57656. }
  57657. }
  57658. const String& PropertyPanel::getMessageWhenEmpty() const
  57659. {
  57660. return messageWhenEmpty;
  57661. }
  57662. END_JUCE_NAMESPACE
  57663. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57664. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57665. BEGIN_JUCE_NAMESPACE
  57666. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57667. const double rangeMin,
  57668. const double rangeMax,
  57669. const double interval,
  57670. const double skewFactor)
  57671. : PropertyComponent (name)
  57672. {
  57673. addAndMakeVisible (slider = new Slider (name));
  57674. slider->setRange (rangeMin, rangeMax, interval);
  57675. slider->setSkewFactor (skewFactor);
  57676. slider->setSliderStyle (Slider::LinearBar);
  57677. slider->addListener (this);
  57678. }
  57679. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57680. const String& name,
  57681. const double rangeMin,
  57682. const double rangeMax,
  57683. const double interval,
  57684. const double skewFactor)
  57685. : PropertyComponent (name)
  57686. {
  57687. addAndMakeVisible (slider = new Slider (name));
  57688. slider->setRange (rangeMin, rangeMax, interval);
  57689. slider->setSkewFactor (skewFactor);
  57690. slider->setSliderStyle (Slider::LinearBar);
  57691. slider->getValueObject().referTo (valueToControl);
  57692. }
  57693. SliderPropertyComponent::~SliderPropertyComponent()
  57694. {
  57695. deleteAllChildren();
  57696. }
  57697. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57698. {
  57699. }
  57700. double SliderPropertyComponent::getValue() const
  57701. {
  57702. return slider->getValue();
  57703. }
  57704. void SliderPropertyComponent::refresh()
  57705. {
  57706. slider->setValue (getValue(), false);
  57707. }
  57708. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57709. {
  57710. if (getValue() != slider->getValue())
  57711. setValue (slider->getValue());
  57712. }
  57713. END_JUCE_NAMESPACE
  57714. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57715. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57716. BEGIN_JUCE_NAMESPACE
  57717. class TextPropLabel : public Label
  57718. {
  57719. TextPropertyComponent& owner;
  57720. int maxChars;
  57721. bool isMultiline;
  57722. public:
  57723. TextPropLabel (TextPropertyComponent& owner_,
  57724. const int maxChars_, const bool isMultiline_)
  57725. : Label (String::empty, String::empty),
  57726. owner (owner_),
  57727. maxChars (maxChars_),
  57728. isMultiline (isMultiline_)
  57729. {
  57730. setEditable (true, true, false);
  57731. setColour (backgroundColourId, Colours::white);
  57732. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57733. }
  57734. ~TextPropLabel()
  57735. {
  57736. }
  57737. TextEditor* createEditorComponent()
  57738. {
  57739. TextEditor* const textEditor = Label::createEditorComponent();
  57740. textEditor->setInputRestrictions (maxChars);
  57741. if (isMultiline)
  57742. {
  57743. textEditor->setMultiLine (true, true);
  57744. textEditor->setReturnKeyStartsNewLine (true);
  57745. }
  57746. return textEditor;
  57747. }
  57748. void textWasEdited()
  57749. {
  57750. owner.textWasEdited();
  57751. }
  57752. };
  57753. TextPropertyComponent::TextPropertyComponent (const String& name,
  57754. const int maxNumChars,
  57755. const bool isMultiLine)
  57756. : PropertyComponent (name)
  57757. {
  57758. createEditor (maxNumChars, isMultiLine);
  57759. }
  57760. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57761. const String& name,
  57762. const int maxNumChars,
  57763. const bool isMultiLine)
  57764. : PropertyComponent (name)
  57765. {
  57766. createEditor (maxNumChars, isMultiLine);
  57767. textEditor->getTextValue().referTo (valueToControl);
  57768. }
  57769. TextPropertyComponent::~TextPropertyComponent()
  57770. {
  57771. deleteAllChildren();
  57772. }
  57773. void TextPropertyComponent::setText (const String& newText)
  57774. {
  57775. textEditor->setText (newText, true);
  57776. }
  57777. const String TextPropertyComponent::getText() const
  57778. {
  57779. return textEditor->getText();
  57780. }
  57781. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57782. {
  57783. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57784. if (isMultiLine)
  57785. {
  57786. textEditor->setJustificationType (Justification::topLeft);
  57787. preferredHeight = 120;
  57788. }
  57789. }
  57790. void TextPropertyComponent::refresh()
  57791. {
  57792. textEditor->setText (getText(), false);
  57793. }
  57794. void TextPropertyComponent::textWasEdited()
  57795. {
  57796. const String newText (textEditor->getText());
  57797. if (getText() != newText)
  57798. setText (newText);
  57799. }
  57800. END_JUCE_NAMESPACE
  57801. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57802. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57803. BEGIN_JUCE_NAMESPACE
  57804. class SimpleDeviceManagerInputLevelMeter : public Component,
  57805. public Timer
  57806. {
  57807. public:
  57808. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57809. : manager (manager_),
  57810. level (0)
  57811. {
  57812. startTimer (50);
  57813. manager->enableInputLevelMeasurement (true);
  57814. }
  57815. ~SimpleDeviceManagerInputLevelMeter()
  57816. {
  57817. manager->enableInputLevelMeasurement (false);
  57818. }
  57819. void timerCallback()
  57820. {
  57821. const float newLevel = (float) manager->getCurrentInputLevel();
  57822. if (std::abs (level - newLevel) > 0.005f)
  57823. {
  57824. level = newLevel;
  57825. repaint();
  57826. }
  57827. }
  57828. void paint (Graphics& g)
  57829. {
  57830. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  57831. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  57832. }
  57833. private:
  57834. AudioDeviceManager* const manager;
  57835. float level;
  57836. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  57837. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  57838. };
  57839. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  57840. public ListBoxModel
  57841. {
  57842. public:
  57843. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  57844. const String& noItemsMessage_,
  57845. const int minNumber_,
  57846. const int maxNumber_)
  57847. : ListBox (String::empty, 0),
  57848. deviceManager (deviceManager_),
  57849. noItemsMessage (noItemsMessage_),
  57850. minNumber (minNumber_),
  57851. maxNumber (maxNumber_)
  57852. {
  57853. items = MidiInput::getDevices();
  57854. setModel (this);
  57855. setOutlineThickness (1);
  57856. }
  57857. ~MidiInputSelectorComponentListBox()
  57858. {
  57859. }
  57860. int getNumRows()
  57861. {
  57862. return items.size();
  57863. }
  57864. void paintListBoxItem (int row,
  57865. Graphics& g,
  57866. int width, int height,
  57867. bool rowIsSelected)
  57868. {
  57869. if (((unsigned int) row) < (unsigned int) items.size())
  57870. {
  57871. if (rowIsSelected)
  57872. g.fillAll (findColour (TextEditor::highlightColourId)
  57873. .withMultipliedAlpha (0.3f));
  57874. const String item (items [row]);
  57875. bool enabled = deviceManager.isMidiInputEnabled (item);
  57876. const int x = getTickX();
  57877. const float tickW = height * 0.75f;
  57878. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  57879. enabled, true, true, false);
  57880. g.setFont (height * 0.6f);
  57881. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  57882. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  57883. }
  57884. }
  57885. void listBoxItemClicked (int row, const MouseEvent& e)
  57886. {
  57887. selectRow (row);
  57888. if (e.x < getTickX())
  57889. flipEnablement (row);
  57890. }
  57891. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  57892. {
  57893. flipEnablement (row);
  57894. }
  57895. void returnKeyPressed (int row)
  57896. {
  57897. flipEnablement (row);
  57898. }
  57899. void paint (Graphics& g)
  57900. {
  57901. ListBox::paint (g);
  57902. if (items.size() == 0)
  57903. {
  57904. g.setColour (Colours::grey);
  57905. g.setFont (13.0f);
  57906. g.drawText (noItemsMessage,
  57907. 0, 0, getWidth(), getHeight() / 2,
  57908. Justification::centred, true);
  57909. }
  57910. }
  57911. int getBestHeight (const int preferredHeight)
  57912. {
  57913. const int extra = getOutlineThickness() * 2;
  57914. return jmax (getRowHeight() * 2 + extra,
  57915. jmin (getRowHeight() * getNumRows() + extra,
  57916. preferredHeight));
  57917. }
  57918. juce_UseDebuggingNewOperator
  57919. private:
  57920. AudioDeviceManager& deviceManager;
  57921. const String noItemsMessage;
  57922. StringArray items;
  57923. int minNumber, maxNumber;
  57924. void flipEnablement (const int row)
  57925. {
  57926. if (((unsigned int) row) < (unsigned int) items.size())
  57927. {
  57928. const String item (items [row]);
  57929. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  57930. }
  57931. }
  57932. int getTickX() const
  57933. {
  57934. return getRowHeight() + 5;
  57935. }
  57936. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  57937. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  57938. };
  57939. class AudioDeviceSettingsPanel : public Component,
  57940. public ComboBoxListener,
  57941. public ChangeListener,
  57942. public ButtonListener
  57943. {
  57944. public:
  57945. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  57946. AudioIODeviceType::DeviceSetupDetails& setup_,
  57947. const bool hideAdvancedOptionsWithButton)
  57948. : type (type_),
  57949. setup (setup_)
  57950. {
  57951. sampleRateDropDown = 0;
  57952. sampleRateLabel = 0;
  57953. bufferSizeDropDown = 0;
  57954. bufferSizeLabel = 0;
  57955. outputDeviceDropDown = 0;
  57956. outputDeviceLabel = 0;
  57957. inputDeviceDropDown = 0;
  57958. inputDeviceLabel = 0;
  57959. testButton = 0;
  57960. inputLevelMeter = 0;
  57961. showUIButton = 0;
  57962. inputChanList = 0;
  57963. outputChanList = 0;
  57964. inputChanLabel = 0;
  57965. outputChanLabel = 0;
  57966. showAdvancedSettingsButton = 0;
  57967. if (hideAdvancedOptionsWithButton)
  57968. {
  57969. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  57970. showAdvancedSettingsButton->addButtonListener (this);
  57971. }
  57972. type->scanForDevices();
  57973. setup.manager->addChangeListener (this);
  57974. changeListenerCallback (0);
  57975. }
  57976. ~AudioDeviceSettingsPanel()
  57977. {
  57978. setup.manager->removeChangeListener (this);
  57979. deleteAndZero (outputDeviceLabel);
  57980. deleteAndZero (inputDeviceLabel);
  57981. deleteAndZero (sampleRateLabel);
  57982. deleteAndZero (bufferSizeLabel);
  57983. deleteAndZero (showUIButton);
  57984. deleteAndZero (inputChanLabel);
  57985. deleteAndZero (outputChanLabel);
  57986. deleteAndZero (showAdvancedSettingsButton);
  57987. deleteAllChildren();
  57988. }
  57989. void resized()
  57990. {
  57991. const int lx = proportionOfWidth (0.35f);
  57992. const int w = proportionOfWidth (0.4f);
  57993. const int h = 24;
  57994. const int space = 6;
  57995. const int dh = h + space;
  57996. int y = 0;
  57997. if (outputDeviceDropDown != 0)
  57998. {
  57999. outputDeviceDropDown->setBounds (lx, y, w, h);
  58000. if (testButton != 0)
  58001. testButton->setBounds (proportionOfWidth (0.77f),
  58002. outputDeviceDropDown->getY(),
  58003. proportionOfWidth (0.18f),
  58004. h);
  58005. y += dh;
  58006. }
  58007. if (inputDeviceDropDown != 0)
  58008. {
  58009. inputDeviceDropDown->setBounds (lx, y, w, h);
  58010. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58011. inputDeviceDropDown->getY(),
  58012. proportionOfWidth (0.18f),
  58013. h);
  58014. y += dh;
  58015. }
  58016. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58017. if (outputChanList != 0)
  58018. {
  58019. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58020. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58021. y += bh + space;
  58022. }
  58023. if (inputChanList != 0)
  58024. {
  58025. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58026. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58027. y += bh + space;
  58028. }
  58029. y += space * 2;
  58030. if (showAdvancedSettingsButton != 0)
  58031. {
  58032. showAdvancedSettingsButton->changeWidthToFitText (h);
  58033. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58034. }
  58035. if (sampleRateDropDown != 0)
  58036. {
  58037. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58038. || ! showAdvancedSettingsButton->isVisible());
  58039. sampleRateDropDown->setBounds (lx, y, w, h);
  58040. y += dh;
  58041. }
  58042. if (bufferSizeDropDown != 0)
  58043. {
  58044. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58045. || ! showAdvancedSettingsButton->isVisible());
  58046. bufferSizeDropDown->setBounds (lx, y, w, h);
  58047. y += dh;
  58048. }
  58049. if (showUIButton != 0)
  58050. {
  58051. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58052. || ! showAdvancedSettingsButton->isVisible());
  58053. showUIButton->changeWidthToFitText (h);
  58054. showUIButton->setTopLeftPosition (lx, y);
  58055. }
  58056. }
  58057. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58058. {
  58059. if (comboBoxThatHasChanged == 0)
  58060. return;
  58061. AudioDeviceManager::AudioDeviceSetup config;
  58062. setup.manager->getAudioDeviceSetup (config);
  58063. String error;
  58064. if (comboBoxThatHasChanged == outputDeviceDropDown
  58065. || comboBoxThatHasChanged == inputDeviceDropDown)
  58066. {
  58067. if (outputDeviceDropDown != 0)
  58068. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58069. : outputDeviceDropDown->getText();
  58070. if (inputDeviceDropDown != 0)
  58071. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58072. : inputDeviceDropDown->getText();
  58073. if (! type->hasSeparateInputsAndOutputs())
  58074. config.inputDeviceName = config.outputDeviceName;
  58075. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58076. config.useDefaultInputChannels = true;
  58077. else
  58078. config.useDefaultOutputChannels = true;
  58079. error = setup.manager->setAudioDeviceSetup (config, true);
  58080. showCorrectDeviceName (inputDeviceDropDown, true);
  58081. showCorrectDeviceName (outputDeviceDropDown, false);
  58082. updateControlPanelButton();
  58083. resized();
  58084. }
  58085. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58086. {
  58087. if (sampleRateDropDown->getSelectedId() > 0)
  58088. {
  58089. config.sampleRate = sampleRateDropDown->getSelectedId();
  58090. error = setup.manager->setAudioDeviceSetup (config, true);
  58091. }
  58092. }
  58093. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58094. {
  58095. if (bufferSizeDropDown->getSelectedId() > 0)
  58096. {
  58097. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58098. error = setup.manager->setAudioDeviceSetup (config, true);
  58099. }
  58100. }
  58101. if (error.isNotEmpty())
  58102. {
  58103. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58104. "Error when trying to open audio device!",
  58105. error);
  58106. }
  58107. }
  58108. void buttonClicked (Button* button)
  58109. {
  58110. if (button == showAdvancedSettingsButton)
  58111. {
  58112. showAdvancedSettingsButton->setVisible (false);
  58113. resized();
  58114. }
  58115. else if (button == showUIButton)
  58116. {
  58117. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58118. if (device != 0 && device->showControlPanel())
  58119. {
  58120. setup.manager->closeAudioDevice();
  58121. setup.manager->restartLastAudioDevice();
  58122. getTopLevelComponent()->toFront (true);
  58123. }
  58124. }
  58125. else if (button == testButton && testButton != 0)
  58126. {
  58127. setup.manager->playTestSound();
  58128. }
  58129. }
  58130. void updateControlPanelButton()
  58131. {
  58132. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58133. deleteAndZero (showUIButton);
  58134. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58135. {
  58136. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58137. TRANS ("opens the device's own control panel")));
  58138. showUIButton->addButtonListener (this);
  58139. }
  58140. resized();
  58141. }
  58142. void changeListenerCallback (void*)
  58143. {
  58144. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58145. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58146. {
  58147. if (outputDeviceDropDown == 0)
  58148. {
  58149. outputDeviceDropDown = new ComboBox (String::empty);
  58150. outputDeviceDropDown->addListener (this);
  58151. addAndMakeVisible (outputDeviceDropDown);
  58152. outputDeviceLabel = new Label (String::empty,
  58153. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58154. : TRANS ("device:"));
  58155. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58156. if (setup.maxNumOutputChannels > 0)
  58157. {
  58158. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58159. testButton->addButtonListener (this);
  58160. }
  58161. }
  58162. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58163. }
  58164. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58165. {
  58166. if (inputDeviceDropDown == 0)
  58167. {
  58168. inputDeviceDropDown = new ComboBox (String::empty);
  58169. inputDeviceDropDown->addListener (this);
  58170. addAndMakeVisible (inputDeviceDropDown);
  58171. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58172. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58173. addAndMakeVisible (inputLevelMeter
  58174. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58175. }
  58176. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58177. }
  58178. updateControlPanelButton();
  58179. showCorrectDeviceName (inputDeviceDropDown, true);
  58180. showCorrectDeviceName (outputDeviceDropDown, false);
  58181. if (currentDevice != 0)
  58182. {
  58183. if (setup.maxNumOutputChannels > 0
  58184. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58185. {
  58186. if (outputChanList == 0)
  58187. {
  58188. addAndMakeVisible (outputChanList
  58189. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58190. TRANS ("(no audio output channels found)")));
  58191. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58192. outputChanLabel->attachToComponent (outputChanList, true);
  58193. }
  58194. outputChanList->refresh();
  58195. }
  58196. else
  58197. {
  58198. deleteAndZero (outputChanLabel);
  58199. deleteAndZero (outputChanList);
  58200. }
  58201. if (setup.maxNumInputChannels > 0
  58202. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58203. {
  58204. if (inputChanList == 0)
  58205. {
  58206. addAndMakeVisible (inputChanList
  58207. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58208. TRANS ("(no audio input channels found)")));
  58209. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58210. inputChanLabel->attachToComponent (inputChanList, true);
  58211. }
  58212. inputChanList->refresh();
  58213. }
  58214. else
  58215. {
  58216. deleteAndZero (inputChanLabel);
  58217. deleteAndZero (inputChanList);
  58218. }
  58219. // sample rate..
  58220. {
  58221. if (sampleRateDropDown == 0)
  58222. {
  58223. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58224. sampleRateDropDown->addListener (this);
  58225. delete sampleRateLabel;
  58226. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58227. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58228. }
  58229. else
  58230. {
  58231. sampleRateDropDown->clear();
  58232. sampleRateDropDown->removeListener (this);
  58233. }
  58234. const int numRates = currentDevice->getNumSampleRates();
  58235. for (int i = 0; i < numRates; ++i)
  58236. {
  58237. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58238. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58239. }
  58240. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58241. sampleRateDropDown->addListener (this);
  58242. }
  58243. // buffer size
  58244. {
  58245. if (bufferSizeDropDown == 0)
  58246. {
  58247. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58248. bufferSizeDropDown->addListener (this);
  58249. delete bufferSizeLabel;
  58250. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58251. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58252. }
  58253. else
  58254. {
  58255. bufferSizeDropDown->clear();
  58256. }
  58257. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58258. double currentRate = currentDevice->getCurrentSampleRate();
  58259. if (currentRate == 0)
  58260. currentRate = 48000.0;
  58261. for (int i = 0; i < numBufferSizes; ++i)
  58262. {
  58263. const int bs = currentDevice->getBufferSizeSamples (i);
  58264. bufferSizeDropDown->addItem (String (bs)
  58265. + " samples ("
  58266. + String (bs * 1000.0 / currentRate, 1)
  58267. + " ms)",
  58268. bs);
  58269. }
  58270. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58271. }
  58272. }
  58273. else
  58274. {
  58275. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58276. deleteAndZero (sampleRateLabel);
  58277. deleteAndZero (bufferSizeLabel);
  58278. deleteAndZero (sampleRateDropDown);
  58279. deleteAndZero (bufferSizeDropDown);
  58280. if (outputDeviceDropDown != 0)
  58281. outputDeviceDropDown->setSelectedId (-1, true);
  58282. if (inputDeviceDropDown != 0)
  58283. inputDeviceDropDown->setSelectedId (-1, true);
  58284. }
  58285. resized();
  58286. setSize (getWidth(), getLowestY() + 4);
  58287. }
  58288. private:
  58289. AudioIODeviceType* const type;
  58290. const AudioIODeviceType::DeviceSetupDetails setup;
  58291. ComboBox* outputDeviceDropDown;
  58292. ComboBox* inputDeviceDropDown;
  58293. ComboBox* sampleRateDropDown;
  58294. ComboBox* bufferSizeDropDown;
  58295. Label* outputDeviceLabel;
  58296. Label* inputDeviceLabel;
  58297. Label* sampleRateLabel;
  58298. Label* bufferSizeLabel;
  58299. Label* inputChanLabel;
  58300. Label* outputChanLabel;
  58301. TextButton* testButton;
  58302. Component* inputLevelMeter;
  58303. TextButton* showUIButton;
  58304. TextButton* showAdvancedSettingsButton;
  58305. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58306. {
  58307. if (box != 0)
  58308. {
  58309. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58310. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58311. box->setSelectedId (index + 1, true);
  58312. if (testButton != 0 && ! isInput)
  58313. testButton->setEnabled (index >= 0);
  58314. }
  58315. }
  58316. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58317. {
  58318. const StringArray devs (type->getDeviceNames (isInputs));
  58319. combo.clear (true);
  58320. for (int i = 0; i < devs.size(); ++i)
  58321. combo.addItem (devs[i], i + 1);
  58322. combo.addItem (TRANS("<< none >>"), -1);
  58323. combo.setSelectedId (-1, true);
  58324. }
  58325. int getLowestY() const
  58326. {
  58327. int y = 0;
  58328. for (int i = getNumChildComponents(); --i >= 0;)
  58329. y = jmax (y, getChildComponent (i)->getBottom());
  58330. return y;
  58331. }
  58332. public:
  58333. class ChannelSelectorListBox : public ListBox,
  58334. public ListBoxModel
  58335. {
  58336. public:
  58337. enum BoxType
  58338. {
  58339. audioInputType,
  58340. audioOutputType
  58341. };
  58342. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58343. const BoxType type_,
  58344. const String& noItemsMessage_)
  58345. : ListBox (String::empty, 0),
  58346. setup (setup_),
  58347. type (type_),
  58348. noItemsMessage (noItemsMessage_)
  58349. {
  58350. refresh();
  58351. setModel (this);
  58352. setOutlineThickness (1);
  58353. }
  58354. ~ChannelSelectorListBox()
  58355. {
  58356. }
  58357. void refresh()
  58358. {
  58359. items.clear();
  58360. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58361. if (currentDevice != 0)
  58362. {
  58363. if (type == audioInputType)
  58364. items = currentDevice->getInputChannelNames();
  58365. else if (type == audioOutputType)
  58366. items = currentDevice->getOutputChannelNames();
  58367. if (setup.useStereoPairs)
  58368. {
  58369. StringArray pairs;
  58370. for (int i = 0; i < items.size(); i += 2)
  58371. {
  58372. const String name (items[i]);
  58373. const String name2 (items[i + 1]);
  58374. String commonBit;
  58375. for (int j = 0; j < name.length(); ++j)
  58376. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58377. commonBit = name.substring (0, j);
  58378. // Make sure we only split the name at a space, because otherwise, things
  58379. // like "input 11" + "input 12" would become "input 11 + 2"
  58380. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58381. commonBit = commonBit.dropLastCharacters (1);
  58382. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58383. }
  58384. items = pairs;
  58385. }
  58386. }
  58387. updateContent();
  58388. repaint();
  58389. }
  58390. int getNumRows()
  58391. {
  58392. return items.size();
  58393. }
  58394. void paintListBoxItem (int row,
  58395. Graphics& g,
  58396. int width, int height,
  58397. bool rowIsSelected)
  58398. {
  58399. if (((unsigned int) row) < (unsigned int) items.size())
  58400. {
  58401. if (rowIsSelected)
  58402. g.fillAll (findColour (TextEditor::highlightColourId)
  58403. .withMultipliedAlpha (0.3f));
  58404. const String item (items [row]);
  58405. bool enabled = false;
  58406. AudioDeviceManager::AudioDeviceSetup config;
  58407. setup.manager->getAudioDeviceSetup (config);
  58408. if (setup.useStereoPairs)
  58409. {
  58410. if (type == audioInputType)
  58411. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58412. else if (type == audioOutputType)
  58413. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58414. }
  58415. else
  58416. {
  58417. if (type == audioInputType)
  58418. enabled = config.inputChannels [row];
  58419. else if (type == audioOutputType)
  58420. enabled = config.outputChannels [row];
  58421. }
  58422. const int x = getTickX();
  58423. const float tickW = height * 0.75f;
  58424. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58425. enabled, true, true, false);
  58426. g.setFont (height * 0.6f);
  58427. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58428. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58429. }
  58430. }
  58431. void listBoxItemClicked (int row, const MouseEvent& e)
  58432. {
  58433. selectRow (row);
  58434. if (e.x < getTickX())
  58435. flipEnablement (row);
  58436. }
  58437. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58438. {
  58439. flipEnablement (row);
  58440. }
  58441. void returnKeyPressed (int row)
  58442. {
  58443. flipEnablement (row);
  58444. }
  58445. void paint (Graphics& g)
  58446. {
  58447. ListBox::paint (g);
  58448. if (items.size() == 0)
  58449. {
  58450. g.setColour (Colours::grey);
  58451. g.setFont (13.0f);
  58452. g.drawText (noItemsMessage,
  58453. 0, 0, getWidth(), getHeight() / 2,
  58454. Justification::centred, true);
  58455. }
  58456. }
  58457. int getBestHeight (int maxHeight)
  58458. {
  58459. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58460. getNumRows())
  58461. + getOutlineThickness() * 2;
  58462. }
  58463. juce_UseDebuggingNewOperator
  58464. private:
  58465. const AudioIODeviceType::DeviceSetupDetails setup;
  58466. const BoxType type;
  58467. const String noItemsMessage;
  58468. StringArray items;
  58469. void flipEnablement (const int row)
  58470. {
  58471. jassert (type == audioInputType || type == audioOutputType);
  58472. if (((unsigned int) row) < (unsigned int) items.size())
  58473. {
  58474. AudioDeviceManager::AudioDeviceSetup config;
  58475. setup.manager->getAudioDeviceSetup (config);
  58476. if (setup.useStereoPairs)
  58477. {
  58478. BigInteger bits;
  58479. BigInteger& original = (type == audioInputType ? config.inputChannels
  58480. : config.outputChannels);
  58481. int i;
  58482. for (i = 0; i < 256; i += 2)
  58483. bits.setBit (i / 2, original [i] || original [i + 1]);
  58484. if (type == audioInputType)
  58485. {
  58486. config.useDefaultInputChannels = false;
  58487. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58488. }
  58489. else
  58490. {
  58491. config.useDefaultOutputChannels = false;
  58492. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58493. }
  58494. for (i = 0; i < 256; ++i)
  58495. original.setBit (i, bits [i / 2]);
  58496. }
  58497. else
  58498. {
  58499. if (type == audioInputType)
  58500. {
  58501. config.useDefaultInputChannels = false;
  58502. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58503. }
  58504. else
  58505. {
  58506. config.useDefaultOutputChannels = false;
  58507. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58508. }
  58509. }
  58510. String error (setup.manager->setAudioDeviceSetup (config, true));
  58511. if (! error.isEmpty())
  58512. {
  58513. //xxx
  58514. }
  58515. }
  58516. }
  58517. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58518. {
  58519. const int numActive = chans.countNumberOfSetBits();
  58520. if (chans [index])
  58521. {
  58522. if (numActive > minNumber)
  58523. chans.setBit (index, false);
  58524. }
  58525. else
  58526. {
  58527. if (numActive >= maxNumber)
  58528. {
  58529. const int firstActiveChan = chans.findNextSetBit();
  58530. chans.setBit (index > firstActiveChan
  58531. ? firstActiveChan : chans.getHighestBit(),
  58532. false);
  58533. }
  58534. chans.setBit (index, true);
  58535. }
  58536. }
  58537. int getTickX() const
  58538. {
  58539. return getRowHeight() + 5;
  58540. }
  58541. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58542. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58543. };
  58544. private:
  58545. ChannelSelectorListBox* inputChanList;
  58546. ChannelSelectorListBox* outputChanList;
  58547. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58548. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58549. };
  58550. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58551. const int minInputChannels_,
  58552. const int maxInputChannels_,
  58553. const int minOutputChannels_,
  58554. const int maxOutputChannels_,
  58555. const bool showMidiInputOptions,
  58556. const bool showMidiOutputSelector,
  58557. const bool showChannelsAsStereoPairs_,
  58558. const bool hideAdvancedOptionsWithButton_)
  58559. : deviceManager (deviceManager_),
  58560. deviceTypeDropDown (0),
  58561. deviceTypeDropDownLabel (0),
  58562. audioDeviceSettingsComp (0),
  58563. minOutputChannels (minOutputChannels_),
  58564. maxOutputChannels (maxOutputChannels_),
  58565. minInputChannels (minInputChannels_),
  58566. maxInputChannels (maxInputChannels_),
  58567. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58568. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58569. {
  58570. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58571. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58572. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58573. {
  58574. deviceTypeDropDown = new ComboBox (String::empty);
  58575. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58576. {
  58577. deviceTypeDropDown
  58578. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58579. i + 1);
  58580. }
  58581. addAndMakeVisible (deviceTypeDropDown);
  58582. deviceTypeDropDown->addListener (this);
  58583. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58584. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58585. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58586. }
  58587. if (showMidiInputOptions)
  58588. {
  58589. addAndMakeVisible (midiInputsList
  58590. = new MidiInputSelectorComponentListBox (deviceManager,
  58591. TRANS("(no midi inputs available)"),
  58592. 0, 0));
  58593. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58594. midiInputsLabel->setJustificationType (Justification::topRight);
  58595. midiInputsLabel->attachToComponent (midiInputsList, true);
  58596. }
  58597. else
  58598. {
  58599. midiInputsList = 0;
  58600. midiInputsLabel = 0;
  58601. }
  58602. if (showMidiOutputSelector)
  58603. {
  58604. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58605. midiOutputSelector->addListener (this);
  58606. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58607. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58608. }
  58609. else
  58610. {
  58611. midiOutputSelector = 0;
  58612. midiOutputLabel = 0;
  58613. }
  58614. deviceManager_.addChangeListener (this);
  58615. changeListenerCallback (0);
  58616. }
  58617. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58618. {
  58619. deviceManager.removeChangeListener (this);
  58620. deleteAllChildren();
  58621. }
  58622. void AudioDeviceSelectorComponent::resized()
  58623. {
  58624. const int lx = proportionOfWidth (0.35f);
  58625. const int w = proportionOfWidth (0.4f);
  58626. const int h = 24;
  58627. const int space = 6;
  58628. const int dh = h + space;
  58629. int y = 15;
  58630. if (deviceTypeDropDown != 0)
  58631. {
  58632. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58633. y += dh + space * 2;
  58634. }
  58635. if (audioDeviceSettingsComp != 0)
  58636. {
  58637. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58638. y += audioDeviceSettingsComp->getHeight() + space;
  58639. }
  58640. if (midiInputsList != 0)
  58641. {
  58642. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58643. midiInputsList->setBounds (lx, y, w, bh);
  58644. y += bh + space;
  58645. }
  58646. if (midiOutputSelector != 0)
  58647. midiOutputSelector->setBounds (lx, y, w, h);
  58648. }
  58649. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58650. {
  58651. if (child == audioDeviceSettingsComp)
  58652. resized();
  58653. }
  58654. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58655. {
  58656. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58657. if (device != 0 && device->hasControlPanel())
  58658. {
  58659. if (device->showControlPanel())
  58660. deviceManager.restartLastAudioDevice();
  58661. getTopLevelComponent()->toFront (true);
  58662. }
  58663. }
  58664. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58665. {
  58666. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58667. {
  58668. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58669. if (type != 0)
  58670. {
  58671. deleteAndZero (audioDeviceSettingsComp);
  58672. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58673. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58674. }
  58675. }
  58676. else if (comboBoxThatHasChanged == midiOutputSelector)
  58677. {
  58678. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58679. }
  58680. }
  58681. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58682. {
  58683. if (deviceTypeDropDown != 0)
  58684. {
  58685. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58686. }
  58687. if (audioDeviceSettingsComp == 0
  58688. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58689. {
  58690. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58691. deleteAndZero (audioDeviceSettingsComp);
  58692. AudioIODeviceType* const type
  58693. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58694. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58695. if (type != 0)
  58696. {
  58697. AudioIODeviceType::DeviceSetupDetails details;
  58698. details.manager = &deviceManager;
  58699. details.minNumInputChannels = minInputChannels;
  58700. details.maxNumInputChannels = maxInputChannels;
  58701. details.minNumOutputChannels = minOutputChannels;
  58702. details.maxNumOutputChannels = maxOutputChannels;
  58703. details.useStereoPairs = showChannelsAsStereoPairs;
  58704. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58705. if (audioDeviceSettingsComp != 0)
  58706. {
  58707. addAndMakeVisible (audioDeviceSettingsComp);
  58708. audioDeviceSettingsComp->resized();
  58709. }
  58710. }
  58711. }
  58712. if (midiInputsList != 0)
  58713. {
  58714. midiInputsList->updateContent();
  58715. midiInputsList->repaint();
  58716. }
  58717. if (midiOutputSelector != 0)
  58718. {
  58719. midiOutputSelector->clear();
  58720. const StringArray midiOuts (MidiOutput::getDevices());
  58721. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58722. midiOutputSelector->addSeparator();
  58723. for (int i = 0; i < midiOuts.size(); ++i)
  58724. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58725. int current = -1;
  58726. if (deviceManager.getDefaultMidiOutput() != 0)
  58727. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58728. midiOutputSelector->setSelectedId (current, true);
  58729. }
  58730. resized();
  58731. }
  58732. END_JUCE_NAMESPACE
  58733. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58734. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58735. BEGIN_JUCE_NAMESPACE
  58736. BubbleComponent::BubbleComponent()
  58737. : side (0),
  58738. allowablePlacements (above | below | left | right),
  58739. arrowTipX (0.0f),
  58740. arrowTipY (0.0f)
  58741. {
  58742. setInterceptsMouseClicks (false, false);
  58743. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58744. setComponentEffect (&shadow);
  58745. }
  58746. BubbleComponent::~BubbleComponent()
  58747. {
  58748. }
  58749. void BubbleComponent::paint (Graphics& g)
  58750. {
  58751. int x = content.getX();
  58752. int y = content.getY();
  58753. int w = content.getWidth();
  58754. int h = content.getHeight();
  58755. int cw, ch;
  58756. getContentSize (cw, ch);
  58757. if (side == 3)
  58758. x += w - cw;
  58759. else if (side != 1)
  58760. x += (w - cw) / 2;
  58761. w = cw;
  58762. if (side == 2)
  58763. y += h - ch;
  58764. else if (side != 0)
  58765. y += (h - ch) / 2;
  58766. h = ch;
  58767. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58768. (float) x, (float) y,
  58769. (float) w, (float) h);
  58770. const int cx = x + (w - cw) / 2;
  58771. const int cy = y + (h - ch) / 2;
  58772. const int indent = 3;
  58773. g.setOrigin (cx + indent, cy + indent);
  58774. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58775. paintContent (g, cw - indent * 2, ch - indent * 2);
  58776. }
  58777. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58778. {
  58779. allowablePlacements = newPlacement;
  58780. }
  58781. void BubbleComponent::setPosition (Component* componentToPointTo)
  58782. {
  58783. jassert (componentToPointTo->isValidComponent());
  58784. Point<int> pos;
  58785. if (getParentComponent() != 0)
  58786. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58787. else
  58788. pos = componentToPointTo->relativePositionToGlobal (pos);
  58789. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58790. }
  58791. void BubbleComponent::setPosition (const int arrowTipX_,
  58792. const int arrowTipY_)
  58793. {
  58794. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58795. }
  58796. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58797. {
  58798. Rectangle<int> availableSpace;
  58799. if (getParentComponent() != 0)
  58800. {
  58801. availableSpace.setSize (getParentComponent()->getWidth(),
  58802. getParentComponent()->getHeight());
  58803. }
  58804. else
  58805. {
  58806. availableSpace = getParentMonitorArea();
  58807. }
  58808. int x = 0;
  58809. int y = 0;
  58810. int w = 150;
  58811. int h = 30;
  58812. getContentSize (w, h);
  58813. w += 30;
  58814. h += 30;
  58815. const float edgeIndent = 2.0f;
  58816. const int arrowLength = jmin (10, h / 3, w / 3);
  58817. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58818. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58819. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58820. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58821. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58822. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58823. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58824. {
  58825. spaceLeft = spaceRight = 0;
  58826. }
  58827. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58828. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58829. {
  58830. spaceAbove = spaceBelow = 0;
  58831. }
  58832. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58833. {
  58834. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58835. arrowTipX = w * 0.5f;
  58836. content.setSize (w, h - arrowLength);
  58837. if (spaceAbove >= spaceBelow)
  58838. {
  58839. // above
  58840. y = rectangleToPointTo.getY() - h;
  58841. content.setPosition (0, 0);
  58842. arrowTipY = h - edgeIndent;
  58843. side = 2;
  58844. }
  58845. else
  58846. {
  58847. // below
  58848. y = rectangleToPointTo.getBottom();
  58849. content.setPosition (0, arrowLength);
  58850. arrowTipY = edgeIndent;
  58851. side = 0;
  58852. }
  58853. }
  58854. else
  58855. {
  58856. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58857. arrowTipY = h * 0.5f;
  58858. content.setSize (w - arrowLength, h);
  58859. if (spaceLeft > spaceRight)
  58860. {
  58861. // on the left
  58862. x = rectangleToPointTo.getX() - w;
  58863. content.setPosition (0, 0);
  58864. arrowTipX = w - edgeIndent;
  58865. side = 3;
  58866. }
  58867. else
  58868. {
  58869. // on the right
  58870. x = rectangleToPointTo.getRight();
  58871. content.setPosition (arrowLength, 0);
  58872. arrowTipX = edgeIndent;
  58873. side = 1;
  58874. }
  58875. }
  58876. setBounds (x, y, w, h);
  58877. }
  58878. END_JUCE_NAMESPACE
  58879. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  58880. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  58881. BEGIN_JUCE_NAMESPACE
  58882. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  58883. : fadeOutLength (fadeOutLengthMs),
  58884. deleteAfterUse (false)
  58885. {
  58886. }
  58887. BubbleMessageComponent::~BubbleMessageComponent()
  58888. {
  58889. fadeOutComponent (fadeOutLength);
  58890. }
  58891. void BubbleMessageComponent::showAt (int x, int y,
  58892. const String& text,
  58893. const int numMillisecondsBeforeRemoving,
  58894. const bool removeWhenMouseClicked,
  58895. const bool deleteSelfAfterUse)
  58896. {
  58897. textLayout.clear();
  58898. textLayout.setText (text, Font (14.0f));
  58899. textLayout.layout (256, Justification::centredLeft, true);
  58900. setPosition (x, y);
  58901. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58902. }
  58903. void BubbleMessageComponent::showAt (Component* const component,
  58904. const String& text,
  58905. const int numMillisecondsBeforeRemoving,
  58906. const bool removeWhenMouseClicked,
  58907. const bool deleteSelfAfterUse)
  58908. {
  58909. textLayout.clear();
  58910. textLayout.setText (text, Font (14.0f));
  58911. textLayout.layout (256, Justification::centredLeft, true);
  58912. setPosition (component);
  58913. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58914. }
  58915. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  58916. const bool removeWhenMouseClicked,
  58917. const bool deleteSelfAfterUse)
  58918. {
  58919. setVisible (true);
  58920. deleteAfterUse = deleteSelfAfterUse;
  58921. if (numMillisecondsBeforeRemoving > 0)
  58922. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  58923. else
  58924. expiryTime = 0;
  58925. startTimer (77);
  58926. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  58927. if (! (removeWhenMouseClicked && isShowing()))
  58928. mouseClickCounter += 0xfffff;
  58929. repaint();
  58930. }
  58931. void BubbleMessageComponent::getContentSize (int& w, int& h)
  58932. {
  58933. w = textLayout.getWidth() + 16;
  58934. h = textLayout.getHeight() + 16;
  58935. }
  58936. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  58937. {
  58938. g.setColour (findColour (TooltipWindow::textColourId));
  58939. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  58940. }
  58941. void BubbleMessageComponent::timerCallback()
  58942. {
  58943. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  58944. {
  58945. stopTimer();
  58946. setVisible (false);
  58947. if (deleteAfterUse)
  58948. delete this;
  58949. }
  58950. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  58951. {
  58952. stopTimer();
  58953. fadeOutComponent (fadeOutLength);
  58954. if (deleteAfterUse)
  58955. delete this;
  58956. }
  58957. }
  58958. END_JUCE_NAMESPACE
  58959. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  58960. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  58961. BEGIN_JUCE_NAMESPACE
  58962. static const int swatchesPerRow = 8;
  58963. static const int swatchHeight = 22;
  58964. class ColourComponentSlider : public Slider
  58965. {
  58966. public:
  58967. ColourComponentSlider (const String& name)
  58968. : Slider (name)
  58969. {
  58970. setRange (0.0, 255.0, 1.0);
  58971. }
  58972. ~ColourComponentSlider()
  58973. {
  58974. }
  58975. const String getTextFromValue (double value)
  58976. {
  58977. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  58978. }
  58979. double getValueFromText (const String& text)
  58980. {
  58981. return (double) text.getHexValue32();
  58982. }
  58983. private:
  58984. ColourComponentSlider (const ColourComponentSlider&);
  58985. ColourComponentSlider& operator= (const ColourComponentSlider&);
  58986. };
  58987. class ColourSpaceMarker : public Component
  58988. {
  58989. public:
  58990. ColourSpaceMarker()
  58991. {
  58992. setInterceptsMouseClicks (false, false);
  58993. }
  58994. ~ColourSpaceMarker()
  58995. {
  58996. }
  58997. void paint (Graphics& g)
  58998. {
  58999. g.setColour (Colour::greyLevel (0.1f));
  59000. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59001. g.setColour (Colour::greyLevel (0.9f));
  59002. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59003. }
  59004. private:
  59005. ColourSpaceMarker (const ColourSpaceMarker&);
  59006. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59007. };
  59008. class ColourSelector::ColourSpaceView : public Component
  59009. {
  59010. public:
  59011. ColourSpaceView (ColourSelector* owner_,
  59012. float& h_, float& s_, float& v_,
  59013. const int edgeSize)
  59014. : owner (owner_),
  59015. h (h_), s (s_), v (v_),
  59016. lastHue (0.0f),
  59017. edge (edgeSize)
  59018. {
  59019. addAndMakeVisible (marker = new ColourSpaceMarker());
  59020. setMouseCursor (MouseCursor::CrosshairCursor);
  59021. }
  59022. ~ColourSpaceView()
  59023. {
  59024. deleteAllChildren();
  59025. }
  59026. void paint (Graphics& g)
  59027. {
  59028. if (colours.isNull())
  59029. {
  59030. const int width = getWidth() / 2;
  59031. const int height = getHeight() / 2;
  59032. colours = Image (Image::RGB, width, height, false);
  59033. Image::BitmapData pixels (colours, 0, 0, width, height, true);
  59034. for (int y = 0; y < height; ++y)
  59035. {
  59036. const float val = 1.0f - y / (float) height;
  59037. for (int x = 0; x < width; ++x)
  59038. {
  59039. const float sat = x / (float) width;
  59040. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59041. }
  59042. }
  59043. }
  59044. g.setOpacity (1.0f);
  59045. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59046. 0, 0, colours.getWidth(), colours.getHeight());
  59047. }
  59048. void mouseDown (const MouseEvent& e)
  59049. {
  59050. mouseDrag (e);
  59051. }
  59052. void mouseDrag (const MouseEvent& e)
  59053. {
  59054. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59055. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59056. owner->setSV (sat, val);
  59057. }
  59058. void updateIfNeeded()
  59059. {
  59060. if (lastHue != h)
  59061. {
  59062. lastHue = h;
  59063. colours = Image();
  59064. repaint();
  59065. }
  59066. updateMarker();
  59067. }
  59068. void resized()
  59069. {
  59070. colours = Image();
  59071. updateMarker();
  59072. }
  59073. private:
  59074. ColourSelector* const owner;
  59075. float& h;
  59076. float& s;
  59077. float& v;
  59078. float lastHue;
  59079. ColourSpaceMarker* marker;
  59080. const int edge;
  59081. Image colours;
  59082. void updateMarker() const
  59083. {
  59084. marker->setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59085. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59086. edge * 2, edge * 2);
  59087. }
  59088. ColourSpaceView (const ColourSpaceView&);
  59089. ColourSpaceView& operator= (const ColourSpaceView&);
  59090. };
  59091. class HueSelectorMarker : public Component
  59092. {
  59093. public:
  59094. HueSelectorMarker()
  59095. {
  59096. setInterceptsMouseClicks (false, false);
  59097. }
  59098. ~HueSelectorMarker()
  59099. {
  59100. }
  59101. void paint (Graphics& g)
  59102. {
  59103. Path p;
  59104. p.addTriangle (1.0f, 1.0f,
  59105. getWidth() * 0.3f, getHeight() * 0.5f,
  59106. 1.0f, getHeight() - 1.0f);
  59107. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59108. getWidth() * 0.7f, getHeight() * 0.5f,
  59109. getWidth() - 1.0f, getHeight() - 1.0f);
  59110. g.setColour (Colours::white.withAlpha (0.75f));
  59111. g.fillPath (p);
  59112. g.setColour (Colours::black.withAlpha (0.75f));
  59113. g.strokePath (p, PathStrokeType (1.2f));
  59114. }
  59115. private:
  59116. HueSelectorMarker (const HueSelectorMarker&);
  59117. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59118. };
  59119. class ColourSelector::HueSelectorComp : public Component
  59120. {
  59121. public:
  59122. HueSelectorComp (ColourSelector* owner_,
  59123. float& h_, float& s_, float& v_,
  59124. const int edgeSize)
  59125. : owner (owner_),
  59126. h (h_), s (s_), v (v_),
  59127. lastHue (0.0f),
  59128. edge (edgeSize)
  59129. {
  59130. addAndMakeVisible (marker = new HueSelectorMarker());
  59131. }
  59132. ~HueSelectorComp()
  59133. {
  59134. deleteAllChildren();
  59135. }
  59136. void paint (Graphics& g)
  59137. {
  59138. const float yScale = 1.0f / (getHeight() - edge * 2);
  59139. const Rectangle<int> clip (g.getClipBounds());
  59140. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59141. {
  59142. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59143. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59144. }
  59145. }
  59146. void resized()
  59147. {
  59148. marker->setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59149. getWidth(), edge * 2);
  59150. }
  59151. void mouseDown (const MouseEvent& e)
  59152. {
  59153. mouseDrag (e);
  59154. }
  59155. void mouseDrag (const MouseEvent& e)
  59156. {
  59157. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59158. owner->setHue (hue);
  59159. }
  59160. void updateIfNeeded()
  59161. {
  59162. resized();
  59163. }
  59164. private:
  59165. ColourSelector* const owner;
  59166. float& h;
  59167. float& s;
  59168. float& v;
  59169. float lastHue;
  59170. HueSelectorMarker* marker;
  59171. const int edge;
  59172. HueSelectorComp (const HueSelectorComp&);
  59173. HueSelectorComp& operator= (const HueSelectorComp&);
  59174. };
  59175. class ColourSelector::SwatchComponent : public Component
  59176. {
  59177. public:
  59178. SwatchComponent (ColourSelector* owner_, int index_)
  59179. : owner (owner_),
  59180. index (index_)
  59181. {
  59182. }
  59183. ~SwatchComponent()
  59184. {
  59185. }
  59186. void paint (Graphics& g)
  59187. {
  59188. const Colour colour (owner->getSwatchColour (index));
  59189. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  59190. 6, 6,
  59191. Colour (0xffdddddd).overlaidWith (colour),
  59192. Colour (0xffffffff).overlaidWith (colour));
  59193. }
  59194. void mouseDown (const MouseEvent&)
  59195. {
  59196. PopupMenu m;
  59197. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59198. m.addSeparator();
  59199. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59200. const int r = m.showAt (this);
  59201. if (r == 1)
  59202. {
  59203. owner->setCurrentColour (owner->getSwatchColour (index));
  59204. }
  59205. else if (r == 2)
  59206. {
  59207. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59208. {
  59209. owner->setSwatchColour (index, owner->getCurrentColour());
  59210. repaint();
  59211. }
  59212. }
  59213. }
  59214. private:
  59215. ColourSelector* const owner;
  59216. const int index;
  59217. SwatchComponent (const SwatchComponent&);
  59218. SwatchComponent& operator= (const SwatchComponent&);
  59219. };
  59220. ColourSelector::ColourSelector (const int flags_,
  59221. const int edgeGap_,
  59222. const int gapAroundColourSpaceComponent)
  59223. : colour (Colours::white),
  59224. flags (flags_),
  59225. topSpace (0),
  59226. edgeGap (edgeGap_)
  59227. {
  59228. // not much point having a selector with no components in it!
  59229. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59230. updateHSV();
  59231. if ((flags & showSliders) != 0)
  59232. {
  59233. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59234. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59235. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59236. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59237. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59238. for (int i = 4; --i >= 0;)
  59239. sliders[i]->addListener (this);
  59240. }
  59241. else
  59242. {
  59243. zeromem (sliders, sizeof (sliders));
  59244. }
  59245. if ((flags & showColourspace) != 0)
  59246. {
  59247. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59248. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59249. }
  59250. else
  59251. {
  59252. colourSpace = 0;
  59253. hueSelector = 0;
  59254. }
  59255. update();
  59256. }
  59257. ColourSelector::~ColourSelector()
  59258. {
  59259. dispatchPendingMessages();
  59260. swatchComponents.clear();
  59261. deleteAllChildren();
  59262. }
  59263. const Colour ColourSelector::getCurrentColour() const
  59264. {
  59265. return ((flags & showAlphaChannel) != 0) ? colour
  59266. : colour.withAlpha ((uint8) 0xff);
  59267. }
  59268. void ColourSelector::setCurrentColour (const Colour& c)
  59269. {
  59270. if (c != colour)
  59271. {
  59272. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59273. updateHSV();
  59274. update();
  59275. }
  59276. }
  59277. void ColourSelector::setHue (float newH)
  59278. {
  59279. newH = jlimit (0.0f, 1.0f, newH);
  59280. if (h != newH)
  59281. {
  59282. h = newH;
  59283. colour = Colour (h, s, v, colour.getFloatAlpha());
  59284. update();
  59285. }
  59286. }
  59287. void ColourSelector::setSV (float newS, float newV)
  59288. {
  59289. newS = jlimit (0.0f, 1.0f, newS);
  59290. newV = jlimit (0.0f, 1.0f, newV);
  59291. if (s != newS || v != newV)
  59292. {
  59293. s = newS;
  59294. v = newV;
  59295. colour = Colour (h, s, v, colour.getFloatAlpha());
  59296. update();
  59297. }
  59298. }
  59299. void ColourSelector::updateHSV()
  59300. {
  59301. colour.getHSB (h, s, v);
  59302. }
  59303. void ColourSelector::update()
  59304. {
  59305. if (sliders[0] != 0)
  59306. {
  59307. sliders[0]->setValue ((int) colour.getRed());
  59308. sliders[1]->setValue ((int) colour.getGreen());
  59309. sliders[2]->setValue ((int) colour.getBlue());
  59310. sliders[3]->setValue ((int) colour.getAlpha());
  59311. }
  59312. if (colourSpace != 0)
  59313. {
  59314. colourSpace->updateIfNeeded();
  59315. hueSelector->updateIfNeeded();
  59316. }
  59317. if ((flags & showColourAtTop) != 0)
  59318. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  59319. sendChangeMessage (this);
  59320. }
  59321. void ColourSelector::paint (Graphics& g)
  59322. {
  59323. g.fillAll (findColour (backgroundColourId));
  59324. if ((flags & showColourAtTop) != 0)
  59325. {
  59326. const Colour currentColour (getCurrentColour());
  59327. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  59328. 10, 10,
  59329. Colour (0xffdddddd).overlaidWith (currentColour),
  59330. Colour (0xffffffff).overlaidWith (currentColour));
  59331. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59332. g.setFont (14.0f, true);
  59333. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59334. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  59335. Justification::centred, false);
  59336. }
  59337. if ((flags & showSliders) != 0)
  59338. {
  59339. g.setColour (findColour (labelTextColourId));
  59340. g.setFont (11.0f);
  59341. for (int i = 4; --i >= 0;)
  59342. {
  59343. if (sliders[i]->isVisible())
  59344. g.drawText (sliders[i]->getName() + ":",
  59345. 0, sliders[i]->getY(),
  59346. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59347. Justification::centredRight, false);
  59348. }
  59349. }
  59350. }
  59351. void ColourSelector::resized()
  59352. {
  59353. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59354. const int numSwatches = getNumSwatches();
  59355. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59356. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59357. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59358. int y = topSpace;
  59359. if ((flags & showColourspace) != 0)
  59360. {
  59361. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59362. colourSpace->setBounds (edgeGap, y,
  59363. getWidth() - hueWidth - edgeGap - 4,
  59364. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59365. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59366. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59367. colourSpace->getHeight());
  59368. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59369. }
  59370. if ((flags & showSliders) != 0)
  59371. {
  59372. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59373. for (int i = 0; i < numSliders; ++i)
  59374. {
  59375. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59376. proportionOfWidth (0.72f), sliderHeight - 2);
  59377. y += sliderHeight;
  59378. }
  59379. }
  59380. if (numSwatches > 0)
  59381. {
  59382. const int startX = 8;
  59383. const int xGap = 4;
  59384. const int yGap = 4;
  59385. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59386. y += edgeGap;
  59387. if (swatchComponents.size() != numSwatches)
  59388. {
  59389. swatchComponents.clear();
  59390. for (int i = 0; i < numSwatches; ++i)
  59391. {
  59392. SwatchComponent* const sc = new SwatchComponent (this, i);
  59393. swatchComponents.add (sc);
  59394. addAndMakeVisible (sc);
  59395. }
  59396. }
  59397. int x = startX;
  59398. for (int i = 0; i < swatchComponents.size(); ++i)
  59399. {
  59400. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59401. sc->setBounds (x + xGap / 2,
  59402. y + yGap / 2,
  59403. swatchWidth - xGap,
  59404. swatchHeight - yGap);
  59405. if (((i + 1) % swatchesPerRow) == 0)
  59406. {
  59407. x = startX;
  59408. y += swatchHeight;
  59409. }
  59410. else
  59411. {
  59412. x += swatchWidth;
  59413. }
  59414. }
  59415. }
  59416. }
  59417. void ColourSelector::sliderValueChanged (Slider*)
  59418. {
  59419. if (sliders[0] != 0)
  59420. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59421. (uint8) sliders[1]->getValue(),
  59422. (uint8) sliders[2]->getValue(),
  59423. (uint8) sliders[3]->getValue()));
  59424. }
  59425. int ColourSelector::getNumSwatches() const
  59426. {
  59427. return 0;
  59428. }
  59429. const Colour ColourSelector::getSwatchColour (const int) const
  59430. {
  59431. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59432. return Colours::black;
  59433. }
  59434. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59435. {
  59436. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59437. }
  59438. END_JUCE_NAMESPACE
  59439. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59440. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59441. BEGIN_JUCE_NAMESPACE
  59442. class ShadowWindow : public Component
  59443. {
  59444. Component* owner;
  59445. Image shadowImageSections [12];
  59446. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59447. public:
  59448. ShadowWindow (Component* const owner_,
  59449. const int type_,
  59450. const Image shadowImageSections_ [12])
  59451. : owner (owner_),
  59452. type (type_)
  59453. {
  59454. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  59455. shadowImageSections [i] = shadowImageSections_ [i];
  59456. setInterceptsMouseClicks (false, false);
  59457. if (owner_->isOnDesktop())
  59458. {
  59459. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59460. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59461. | ComponentPeer::windowIsTemporary
  59462. | ComponentPeer::windowIgnoresKeyPresses);
  59463. }
  59464. else if (owner_->getParentComponent() != 0)
  59465. {
  59466. owner_->getParentComponent()->addChildComponent (this);
  59467. }
  59468. }
  59469. ~ShadowWindow()
  59470. {
  59471. }
  59472. void paint (Graphics& g)
  59473. {
  59474. const Image& topLeft = shadowImageSections [type * 3];
  59475. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  59476. const Image& filler = shadowImageSections [type * 3 + 2];
  59477. g.setOpacity (1.0f);
  59478. if (type < 2)
  59479. {
  59480. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59481. g.drawImage (topLeft,
  59482. 0, 0, topLeft.getWidth(), imH,
  59483. 0, 0, topLeft.getWidth(), imH);
  59484. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59485. g.drawImage (bottomRight,
  59486. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59487. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59488. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59489. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59490. }
  59491. else
  59492. {
  59493. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59494. g.drawImage (topLeft,
  59495. 0, 0, imW, topLeft.getHeight(),
  59496. 0, 0, imW, topLeft.getHeight());
  59497. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59498. g.drawImage (bottomRight,
  59499. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59500. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59501. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59502. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59503. }
  59504. }
  59505. void resized()
  59506. {
  59507. repaint(); // (needed for correct repainting)
  59508. }
  59509. private:
  59510. ShadowWindow (const ShadowWindow&);
  59511. ShadowWindow& operator= (const ShadowWindow&);
  59512. };
  59513. DropShadower::DropShadower (const float alpha_,
  59514. const int xOffset_,
  59515. const int yOffset_,
  59516. const float blurRadius_)
  59517. : owner (0),
  59518. numShadows (0),
  59519. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59520. xOffset (xOffset_),
  59521. yOffset (yOffset_),
  59522. alpha (alpha_),
  59523. blurRadius (blurRadius_),
  59524. inDestructor (false),
  59525. reentrant (false)
  59526. {
  59527. }
  59528. DropShadower::~DropShadower()
  59529. {
  59530. if (owner != 0)
  59531. owner->removeComponentListener (this);
  59532. inDestructor = true;
  59533. deleteShadowWindows();
  59534. }
  59535. void DropShadower::deleteShadowWindows()
  59536. {
  59537. if (numShadows > 0)
  59538. {
  59539. int i;
  59540. for (i = numShadows; --i >= 0;)
  59541. delete shadowWindows[i];
  59542. numShadows = 0;
  59543. }
  59544. }
  59545. void DropShadower::setOwner (Component* componentToFollow)
  59546. {
  59547. if (componentToFollow != owner)
  59548. {
  59549. if (owner != 0)
  59550. owner->removeComponentListener (this);
  59551. // (the component can't be null)
  59552. jassert (componentToFollow != 0);
  59553. owner = componentToFollow;
  59554. jassert (owner != 0);
  59555. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59556. owner->addComponentListener (this);
  59557. updateShadows();
  59558. }
  59559. }
  59560. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59561. {
  59562. updateShadows();
  59563. }
  59564. void DropShadower::componentBroughtToFront (Component&)
  59565. {
  59566. bringShadowWindowsToFront();
  59567. }
  59568. void DropShadower::componentChildrenChanged (Component&)
  59569. {
  59570. }
  59571. void DropShadower::componentParentHierarchyChanged (Component&)
  59572. {
  59573. deleteShadowWindows();
  59574. updateShadows();
  59575. }
  59576. void DropShadower::componentVisibilityChanged (Component&)
  59577. {
  59578. updateShadows();
  59579. }
  59580. void DropShadower::updateShadows()
  59581. {
  59582. if (reentrant || inDestructor || (owner == 0))
  59583. return;
  59584. reentrant = true;
  59585. ComponentPeer* const nw = owner->getPeer();
  59586. const bool isOwnerVisible = owner->isVisible()
  59587. && (nw == 0 || ! nw->isMinimised());
  59588. const bool createShadowWindows = numShadows == 0
  59589. && owner->getWidth() > 0
  59590. && owner->getHeight() > 0
  59591. && isOwnerVisible
  59592. && (Desktop::canUseSemiTransparentWindows()
  59593. || owner->getParentComponent() != 0);
  59594. if (createShadowWindows)
  59595. {
  59596. // keep a cached version of the image to save doing the gaussian too often
  59597. String imageId;
  59598. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59599. const int hash = imageId.hashCode();
  59600. Image bigIm (ImageCache::getFromHashCode (hash));
  59601. if (bigIm.isNull())
  59602. {
  59603. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  59604. Graphics bigG (bigIm);
  59605. bigG.setColour (Colours::black.withAlpha (alpha));
  59606. bigG.fillRect (shadowEdge + xOffset,
  59607. shadowEdge + yOffset,
  59608. bigIm.getWidth() - (shadowEdge * 2),
  59609. bigIm.getHeight() - (shadowEdge * 2));
  59610. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59611. blurKernel.createGaussianBlur (blurRadius);
  59612. blurKernel.applyToImage (bigIm, bigIm,
  59613. Rectangle<int> (xOffset, yOffset,
  59614. bigIm.getWidth(), bigIm.getHeight()));
  59615. ImageCache::addImageToCache (bigIm, hash);
  59616. }
  59617. const int iw = bigIm.getWidth();
  59618. const int ih = bigIm.getHeight();
  59619. const int shadowEdge2 = shadowEdge * 2;
  59620. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59621. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59622. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59623. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59624. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59625. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59626. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59627. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59628. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59629. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59630. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59631. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59632. for (int i = 0; i < 4; ++i)
  59633. {
  59634. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59635. ++numShadows;
  59636. }
  59637. }
  59638. if (numShadows > 0)
  59639. {
  59640. for (int i = numShadows; --i >= 0;)
  59641. {
  59642. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59643. shadowWindows[i]->setVisible (isOwnerVisible);
  59644. }
  59645. const int x = owner->getX();
  59646. const int y = owner->getY() - shadowEdge;
  59647. const int w = owner->getWidth();
  59648. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59649. shadowWindows[0]->setBounds (x - shadowEdge,
  59650. y,
  59651. shadowEdge,
  59652. h);
  59653. shadowWindows[1]->setBounds (x + w,
  59654. y,
  59655. shadowEdge,
  59656. h);
  59657. shadowWindows[2]->setBounds (x,
  59658. y,
  59659. w,
  59660. shadowEdge);
  59661. shadowWindows[3]->setBounds (x,
  59662. owner->getBottom(),
  59663. w,
  59664. shadowEdge);
  59665. }
  59666. reentrant = false;
  59667. if (createShadowWindows)
  59668. bringShadowWindowsToFront();
  59669. }
  59670. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  59671. const int sx, const int sy)
  59672. {
  59673. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  59674. Graphics g (shadowImageSections[num]);
  59675. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59676. }
  59677. void DropShadower::bringShadowWindowsToFront()
  59678. {
  59679. if (! (inDestructor || reentrant))
  59680. {
  59681. updateShadows();
  59682. reentrant = true;
  59683. for (int i = numShadows; --i >= 0;)
  59684. shadowWindows[i]->toBehind (owner);
  59685. reentrant = false;
  59686. }
  59687. }
  59688. END_JUCE_NAMESPACE
  59689. /*** End of inlined file: juce_DropShadower.cpp ***/
  59690. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59691. BEGIN_JUCE_NAMESPACE
  59692. class MagnifyingPeer : public ComponentPeer
  59693. {
  59694. public:
  59695. MagnifyingPeer (Component* const component_,
  59696. MagnifierComponent* const magnifierComp_)
  59697. : ComponentPeer (component_, 0),
  59698. magnifierComp (magnifierComp_)
  59699. {
  59700. }
  59701. ~MagnifyingPeer()
  59702. {
  59703. }
  59704. void* getNativeHandle() const { return 0; }
  59705. void setVisible (bool) {}
  59706. void setTitle (const String&) {}
  59707. void setPosition (int, int) {}
  59708. void setSize (int, int) {}
  59709. void setBounds (int, int, int, int, bool) {}
  59710. void setMinimised (bool) {}
  59711. bool isMinimised() const { return false; }
  59712. void setFullScreen (bool) {}
  59713. bool isFullScreen() const { return false; }
  59714. const BorderSize getFrameSize() const { return BorderSize (0); }
  59715. bool setAlwaysOnTop (bool) { return true; }
  59716. void toFront (bool) {}
  59717. void toBehind (ComponentPeer*) {}
  59718. void setIcon (const Image&) {}
  59719. bool isFocused() const
  59720. {
  59721. return magnifierComp->hasKeyboardFocus (true);
  59722. }
  59723. void grabFocus()
  59724. {
  59725. ComponentPeer* peer = magnifierComp->getPeer();
  59726. if (peer != 0)
  59727. peer->grabFocus();
  59728. }
  59729. void textInputRequired (const Point<int>& position)
  59730. {
  59731. ComponentPeer* peer = magnifierComp->getPeer();
  59732. if (peer != 0)
  59733. peer->textInputRequired (position);
  59734. }
  59735. const Rectangle<int> getBounds() const
  59736. {
  59737. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59738. component->getWidth(), component->getHeight());
  59739. }
  59740. const Point<int> getScreenPosition() const
  59741. {
  59742. return magnifierComp->getScreenPosition();
  59743. }
  59744. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59745. {
  59746. const double zoom = magnifierComp->getScaleFactor();
  59747. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59748. roundToInt (relativePosition.getY() * zoom)));
  59749. }
  59750. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59751. {
  59752. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59753. const double zoom = magnifierComp->getScaleFactor();
  59754. return Point<int> (roundToInt (p.getX() / zoom),
  59755. roundToInt (p.getY() / zoom));
  59756. }
  59757. bool contains (const Point<int>& position, bool) const
  59758. {
  59759. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59760. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59761. }
  59762. void repaint (const Rectangle<int>& area)
  59763. {
  59764. const double zoom = magnifierComp->getScaleFactor();
  59765. magnifierComp->repaint ((int) (area.getX() * zoom),
  59766. (int) (area.getY() * zoom),
  59767. roundToInt (area.getWidth() * zoom) + 1,
  59768. roundToInt (area.getHeight() * zoom) + 1);
  59769. }
  59770. void performAnyPendingRepaintsNow()
  59771. {
  59772. }
  59773. juce_UseDebuggingNewOperator
  59774. private:
  59775. MagnifierComponent* const magnifierComp;
  59776. MagnifyingPeer (const MagnifyingPeer&);
  59777. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59778. };
  59779. class PeerHolderComp : public Component
  59780. {
  59781. public:
  59782. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59783. : magnifierComp (magnifierComp_)
  59784. {
  59785. setVisible (true);
  59786. }
  59787. ~PeerHolderComp()
  59788. {
  59789. }
  59790. ComponentPeer* createNewPeer (int, void*)
  59791. {
  59792. return new MagnifyingPeer (this, magnifierComp);
  59793. }
  59794. void childBoundsChanged (Component* c)
  59795. {
  59796. if (c != 0)
  59797. {
  59798. setSize (c->getWidth(), c->getHeight());
  59799. magnifierComp->childBoundsChanged (this);
  59800. }
  59801. }
  59802. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59803. {
  59804. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59805. Component* const p = magnifierComp->getParentComponent();
  59806. if (p != 0)
  59807. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59808. }
  59809. private:
  59810. MagnifierComponent* const magnifierComp;
  59811. PeerHolderComp (const PeerHolderComp&);
  59812. PeerHolderComp& operator= (const PeerHolderComp&);
  59813. };
  59814. MagnifierComponent::MagnifierComponent (Component* const content_,
  59815. const bool deleteContentCompWhenNoLongerNeeded)
  59816. : content (content_),
  59817. scaleFactor (0.0),
  59818. peer (0),
  59819. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59820. quality (Graphics::lowResamplingQuality),
  59821. mouseSource (0, true)
  59822. {
  59823. holderComp = new PeerHolderComp (this);
  59824. setScaleFactor (1.0);
  59825. }
  59826. MagnifierComponent::~MagnifierComponent()
  59827. {
  59828. delete holderComp;
  59829. if (deleteContent)
  59830. delete content;
  59831. }
  59832. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59833. {
  59834. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59835. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59836. if (scaleFactor != newScaleFactor)
  59837. {
  59838. scaleFactor = newScaleFactor;
  59839. if (scaleFactor == 1.0)
  59840. {
  59841. holderComp->removeFromDesktop();
  59842. peer = 0;
  59843. addChildComponent (content);
  59844. childBoundsChanged (content);
  59845. }
  59846. else
  59847. {
  59848. holderComp->addAndMakeVisible (content);
  59849. holderComp->childBoundsChanged (content);
  59850. childBoundsChanged (holderComp);
  59851. holderComp->addToDesktop (0);
  59852. peer = holderComp->getPeer();
  59853. }
  59854. repaint();
  59855. }
  59856. }
  59857. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59858. {
  59859. quality = newQuality;
  59860. }
  59861. void MagnifierComponent::paint (Graphics& g)
  59862. {
  59863. const int w = holderComp->getWidth();
  59864. const int h = holderComp->getHeight();
  59865. if (w == 0 || h == 0)
  59866. return;
  59867. const Rectangle<int> r (g.getClipBounds());
  59868. const int srcX = (int) (r.getX() / scaleFactor);
  59869. const int srcY = (int) (r.getY() / scaleFactor);
  59870. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  59871. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  59872. if (scaleFactor >= 1.0)
  59873. {
  59874. ++srcW;
  59875. ++srcH;
  59876. }
  59877. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  59878. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  59879. {
  59880. Graphics g2 (temp);
  59881. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  59882. holderComp->paintEntireComponent (g2);
  59883. }
  59884. g.setImageResamplingQuality (quality);
  59885. g.drawImageTransformed (temp, temp.getBounds(),
  59886. AffineTransform::scale ((float) scaleFactor, (float) scaleFactor),
  59887. false);
  59888. }
  59889. void MagnifierComponent::childBoundsChanged (Component* c)
  59890. {
  59891. if (c != 0)
  59892. setSize (roundToInt (c->getWidth() * scaleFactor),
  59893. roundToInt (c->getHeight() * scaleFactor));
  59894. }
  59895. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  59896. {
  59897. if (peer != 0)
  59898. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  59899. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  59900. }
  59901. void MagnifierComponent::mouseDown (const MouseEvent& e)
  59902. {
  59903. passOnMouseEventToPeer (e);
  59904. }
  59905. void MagnifierComponent::mouseUp (const MouseEvent& e)
  59906. {
  59907. passOnMouseEventToPeer (e);
  59908. }
  59909. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  59910. {
  59911. passOnMouseEventToPeer (e);
  59912. }
  59913. void MagnifierComponent::mouseMove (const MouseEvent& e)
  59914. {
  59915. passOnMouseEventToPeer (e);
  59916. }
  59917. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  59918. {
  59919. passOnMouseEventToPeer (e);
  59920. }
  59921. void MagnifierComponent::mouseExit (const MouseEvent& e)
  59922. {
  59923. passOnMouseEventToPeer (e);
  59924. }
  59925. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59926. {
  59927. if (peer != 0)
  59928. peer->handleMouseWheel (e.source.getIndex(),
  59929. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  59930. ix * 256.0f, iy * 256.0f);
  59931. else
  59932. Component::mouseWheelMove (e, ix, iy);
  59933. }
  59934. int MagnifierComponent::scaleInt (const int n) const
  59935. {
  59936. return roundToInt (n / scaleFactor);
  59937. }
  59938. END_JUCE_NAMESPACE
  59939. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  59940. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  59941. BEGIN_JUCE_NAMESPACE
  59942. class MidiKeyboardUpDownButton : public Button
  59943. {
  59944. public:
  59945. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  59946. const int delta_)
  59947. : Button (String::empty),
  59948. owner (owner_),
  59949. delta (delta_)
  59950. {
  59951. setOpaque (true);
  59952. }
  59953. ~MidiKeyboardUpDownButton()
  59954. {
  59955. }
  59956. void clicked()
  59957. {
  59958. int note = owner->getLowestVisibleKey();
  59959. if (delta < 0)
  59960. note = (note - 1) / 12;
  59961. else
  59962. note = note / 12 + 1;
  59963. owner->setLowestVisibleKey (note * 12);
  59964. }
  59965. void paintButton (Graphics& g,
  59966. bool isMouseOverButton,
  59967. bool isButtonDown)
  59968. {
  59969. owner->drawUpDownButton (g, getWidth(), getHeight(),
  59970. isMouseOverButton, isButtonDown,
  59971. delta > 0);
  59972. }
  59973. private:
  59974. MidiKeyboardComponent* const owner;
  59975. const int delta;
  59976. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  59977. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  59978. };
  59979. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  59980. const Orientation orientation_)
  59981. : state (state_),
  59982. xOffset (0),
  59983. blackNoteLength (1),
  59984. keyWidth (16.0f),
  59985. orientation (orientation_),
  59986. midiChannel (1),
  59987. midiInChannelMask (0xffff),
  59988. velocity (1.0f),
  59989. noteUnderMouse (-1),
  59990. mouseDownNote (-1),
  59991. rangeStart (0),
  59992. rangeEnd (127),
  59993. firstKey (12 * 4),
  59994. canScroll (true),
  59995. mouseDragging (false),
  59996. useMousePositionForVelocity (true),
  59997. keyMappingOctave (6),
  59998. octaveNumForMiddleC (3)
  59999. {
  60000. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60001. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60002. // initialise with a default set of querty key-mappings..
  60003. const char* const keymap = "awsedftgyhujkolp;";
  60004. for (int i = String (keymap).length(); --i >= 0;)
  60005. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60006. setOpaque (true);
  60007. setWantsKeyboardFocus (true);
  60008. state.addListener (this);
  60009. }
  60010. MidiKeyboardComponent::~MidiKeyboardComponent()
  60011. {
  60012. state.removeListener (this);
  60013. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60014. deleteAllChildren();
  60015. }
  60016. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60017. {
  60018. keyWidth = widthInPixels;
  60019. resized();
  60020. }
  60021. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60022. {
  60023. if (orientation != newOrientation)
  60024. {
  60025. orientation = newOrientation;
  60026. resized();
  60027. }
  60028. }
  60029. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60030. const int highestNote)
  60031. {
  60032. jassert (lowestNote >= 0 && lowestNote <= 127);
  60033. jassert (highestNote >= 0 && highestNote <= 127);
  60034. jassert (lowestNote <= highestNote);
  60035. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60036. {
  60037. rangeStart = jlimit (0, 127, lowestNote);
  60038. rangeEnd = jlimit (0, 127, highestNote);
  60039. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60040. resized();
  60041. }
  60042. }
  60043. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60044. {
  60045. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60046. if (noteNumber != firstKey)
  60047. {
  60048. firstKey = noteNumber;
  60049. sendChangeMessage (this);
  60050. resized();
  60051. }
  60052. }
  60053. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60054. {
  60055. if (canScroll != canScroll_)
  60056. {
  60057. canScroll = canScroll_;
  60058. resized();
  60059. }
  60060. }
  60061. void MidiKeyboardComponent::colourChanged()
  60062. {
  60063. repaint();
  60064. }
  60065. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60066. {
  60067. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60068. if (midiChannel != midiChannelNumber)
  60069. {
  60070. resetAnyKeysInUse();
  60071. midiChannel = jlimit (1, 16, midiChannelNumber);
  60072. }
  60073. }
  60074. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60075. {
  60076. midiInChannelMask = midiChannelMask;
  60077. triggerAsyncUpdate();
  60078. }
  60079. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60080. {
  60081. velocity = jlimit (0.0f, 1.0f, velocity_);
  60082. useMousePositionForVelocity = useMousePositionForVelocity_;
  60083. }
  60084. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60085. {
  60086. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60087. static const float blackNoteWidth = 0.7f;
  60088. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60089. 1.0f, 2 - blackNoteWidth * 0.4f,
  60090. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60091. 4.0f, 5 - blackNoteWidth * 0.5f,
  60092. 5.0f, 6 - blackNoteWidth * 0.3f,
  60093. 6.0f };
  60094. static const float widths[] = { 1.0f, blackNoteWidth,
  60095. 1.0f, blackNoteWidth,
  60096. 1.0f, 1.0f, blackNoteWidth,
  60097. 1.0f, blackNoteWidth,
  60098. 1.0f, blackNoteWidth,
  60099. 1.0f };
  60100. const int octave = midiNoteNumber / 12;
  60101. const int note = midiNoteNumber % 12;
  60102. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60103. w = roundToInt (widths [note] * keyWidth_);
  60104. }
  60105. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60106. {
  60107. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60108. int rx, rw;
  60109. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60110. x -= xOffset + rx;
  60111. }
  60112. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60113. {
  60114. int x, y;
  60115. getKeyPos (midiNoteNumber, x, y);
  60116. return x;
  60117. }
  60118. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60119. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  60120. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60121. {
  60122. if (! reallyContains (pos.getX(), pos.getY(), false))
  60123. return -1;
  60124. Point<int> p (pos);
  60125. if (orientation != horizontalKeyboard)
  60126. {
  60127. p = Point<int> (p.getY(), p.getX());
  60128. if (orientation == verticalKeyboardFacingLeft)
  60129. p = Point<int> (p.getX(), getWidth() - p.getY());
  60130. else
  60131. p = Point<int> (getHeight() - p.getX(), p.getY());
  60132. }
  60133. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60134. }
  60135. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60136. {
  60137. if (pos.getY() < blackNoteLength)
  60138. {
  60139. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60140. {
  60141. for (int i = 0; i < 5; ++i)
  60142. {
  60143. const int note = octaveStart + blackNotes [i];
  60144. if (note >= rangeStart && note <= rangeEnd)
  60145. {
  60146. int kx, kw;
  60147. getKeyPos (note, kx, kw);
  60148. kx += xOffset;
  60149. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60150. {
  60151. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60152. return note;
  60153. }
  60154. }
  60155. }
  60156. }
  60157. }
  60158. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60159. {
  60160. for (int i = 0; i < 7; ++i)
  60161. {
  60162. const int note = octaveStart + whiteNotes [i];
  60163. if (note >= rangeStart && note <= rangeEnd)
  60164. {
  60165. int kx, kw;
  60166. getKeyPos (note, kx, kw);
  60167. kx += xOffset;
  60168. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60169. {
  60170. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60171. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60172. return note;
  60173. }
  60174. }
  60175. }
  60176. }
  60177. mousePositionVelocity = 0;
  60178. return -1;
  60179. }
  60180. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60181. {
  60182. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60183. {
  60184. int x, w;
  60185. getKeyPos (noteNum, x, w);
  60186. if (orientation == horizontalKeyboard)
  60187. repaint (x, 0, w, getHeight());
  60188. else if (orientation == verticalKeyboardFacingLeft)
  60189. repaint (0, x, getWidth(), w);
  60190. else if (orientation == verticalKeyboardFacingRight)
  60191. repaint (0, getHeight() - x - w, getWidth(), w);
  60192. }
  60193. }
  60194. void MidiKeyboardComponent::paint (Graphics& g)
  60195. {
  60196. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60197. const Colour lineColour (findColour (keySeparatorLineColourId));
  60198. const Colour textColour (findColour (textLabelColourId));
  60199. int x, w, octave;
  60200. for (octave = 0; octave < 128; octave += 12)
  60201. {
  60202. for (int white = 0; white < 7; ++white)
  60203. {
  60204. const int noteNum = octave + whiteNotes [white];
  60205. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60206. {
  60207. getKeyPos (noteNum, x, w);
  60208. if (orientation == horizontalKeyboard)
  60209. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60210. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60211. noteUnderMouse == noteNum,
  60212. lineColour, textColour);
  60213. else if (orientation == verticalKeyboardFacingLeft)
  60214. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60215. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60216. noteUnderMouse == noteNum,
  60217. lineColour, textColour);
  60218. else if (orientation == verticalKeyboardFacingRight)
  60219. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60220. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60221. noteUnderMouse == noteNum,
  60222. lineColour, textColour);
  60223. }
  60224. }
  60225. }
  60226. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60227. if (orientation == verticalKeyboardFacingLeft)
  60228. {
  60229. x1 = getWidth() - 1.0f;
  60230. x2 = getWidth() - 5.0f;
  60231. }
  60232. else if (orientation == verticalKeyboardFacingRight)
  60233. x2 = 5.0f;
  60234. else
  60235. y2 = 5.0f;
  60236. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60237. Colours::transparentBlack, x2, y2, false));
  60238. getKeyPos (rangeEnd, x, w);
  60239. x += w;
  60240. if (orientation == verticalKeyboardFacingLeft)
  60241. g.fillRect (getWidth() - 5, 0, 5, x);
  60242. else if (orientation == verticalKeyboardFacingRight)
  60243. g.fillRect (0, 0, 5, x);
  60244. else
  60245. g.fillRect (0, 0, x, 5);
  60246. g.setColour (lineColour);
  60247. if (orientation == verticalKeyboardFacingLeft)
  60248. g.fillRect (0, 0, 1, x);
  60249. else if (orientation == verticalKeyboardFacingRight)
  60250. g.fillRect (getWidth() - 1, 0, 1, x);
  60251. else
  60252. g.fillRect (0, getHeight() - 1, x, 1);
  60253. const Colour blackNoteColour (findColour (blackNoteColourId));
  60254. for (octave = 0; octave < 128; octave += 12)
  60255. {
  60256. for (int black = 0; black < 5; ++black)
  60257. {
  60258. const int noteNum = octave + blackNotes [black];
  60259. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60260. {
  60261. getKeyPos (noteNum, x, w);
  60262. if (orientation == horizontalKeyboard)
  60263. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60264. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60265. noteUnderMouse == noteNum,
  60266. blackNoteColour);
  60267. else if (orientation == verticalKeyboardFacingLeft)
  60268. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60269. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60270. noteUnderMouse == noteNum,
  60271. blackNoteColour);
  60272. else if (orientation == verticalKeyboardFacingRight)
  60273. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60274. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60275. noteUnderMouse == noteNum,
  60276. blackNoteColour);
  60277. }
  60278. }
  60279. }
  60280. }
  60281. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60282. Graphics& g, int x, int y, int w, int h,
  60283. bool isDown, bool isOver,
  60284. const Colour& lineColour,
  60285. const Colour& textColour)
  60286. {
  60287. Colour c (Colours::transparentWhite);
  60288. if (isDown)
  60289. c = findColour (keyDownOverlayColourId);
  60290. if (isOver)
  60291. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60292. g.setColour (c);
  60293. g.fillRect (x, y, w, h);
  60294. const String text (getWhiteNoteText (midiNoteNumber));
  60295. if (! text.isEmpty())
  60296. {
  60297. g.setColour (textColour);
  60298. Font f (jmin (12.0f, keyWidth * 0.9f));
  60299. f.setHorizontalScale (0.8f);
  60300. g.setFont (f);
  60301. Justification justification (Justification::centredBottom);
  60302. if (orientation == verticalKeyboardFacingLeft)
  60303. justification = Justification::centredLeft;
  60304. else if (orientation == verticalKeyboardFacingRight)
  60305. justification = Justification::centredRight;
  60306. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60307. }
  60308. g.setColour (lineColour);
  60309. if (orientation == horizontalKeyboard)
  60310. g.fillRect (x, y, 1, h);
  60311. else if (orientation == verticalKeyboardFacingLeft)
  60312. g.fillRect (x, y, w, 1);
  60313. else if (orientation == verticalKeyboardFacingRight)
  60314. g.fillRect (x, y + h - 1, w, 1);
  60315. if (midiNoteNumber == rangeEnd)
  60316. {
  60317. if (orientation == horizontalKeyboard)
  60318. g.fillRect (x + w, y, 1, h);
  60319. else if (orientation == verticalKeyboardFacingLeft)
  60320. g.fillRect (x, y + h, w, 1);
  60321. else if (orientation == verticalKeyboardFacingRight)
  60322. g.fillRect (x, y - 1, w, 1);
  60323. }
  60324. }
  60325. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60326. Graphics& g, int x, int y, int w, int h,
  60327. bool isDown, bool isOver,
  60328. const Colour& noteFillColour)
  60329. {
  60330. Colour c (noteFillColour);
  60331. if (isDown)
  60332. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60333. if (isOver)
  60334. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60335. g.setColour (c);
  60336. g.fillRect (x, y, w, h);
  60337. if (isDown)
  60338. {
  60339. g.setColour (noteFillColour);
  60340. g.drawRect (x, y, w, h);
  60341. }
  60342. else
  60343. {
  60344. const int xIndent = jmax (1, jmin (w, h) / 8);
  60345. g.setColour (c.brighter());
  60346. if (orientation == horizontalKeyboard)
  60347. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60348. else if (orientation == verticalKeyboardFacingLeft)
  60349. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60350. else if (orientation == verticalKeyboardFacingRight)
  60351. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60352. }
  60353. }
  60354. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60355. {
  60356. octaveNumForMiddleC = octaveNumForMiddleC_;
  60357. repaint();
  60358. }
  60359. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60360. {
  60361. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60362. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60363. return String::empty;
  60364. }
  60365. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60366. const bool isMouseOver_,
  60367. const bool isButtonDown,
  60368. const bool movesOctavesUp)
  60369. {
  60370. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60371. float angle;
  60372. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60373. angle = movesOctavesUp ? 0.0f : 0.5f;
  60374. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60375. angle = movesOctavesUp ? 0.25f : 0.75f;
  60376. else
  60377. angle = movesOctavesUp ? 0.75f : 0.25f;
  60378. Path path;
  60379. path.lineTo (0.0f, 1.0f);
  60380. path.lineTo (1.0f, 0.5f);
  60381. path.closeSubPath();
  60382. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60383. g.setColour (findColour (upDownButtonArrowColourId)
  60384. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60385. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60386. w - 2.0f,
  60387. h - 2.0f,
  60388. true));
  60389. }
  60390. void MidiKeyboardComponent::resized()
  60391. {
  60392. int w = getWidth();
  60393. int h = getHeight();
  60394. if (w > 0 && h > 0)
  60395. {
  60396. if (orientation != horizontalKeyboard)
  60397. swapVariables (w, h);
  60398. blackNoteLength = roundToInt (h * 0.7f);
  60399. int kx2, kw2;
  60400. getKeyPos (rangeEnd, kx2, kw2);
  60401. kx2 += kw2;
  60402. if (firstKey != rangeStart)
  60403. {
  60404. int kx1, kw1;
  60405. getKeyPos (rangeStart, kx1, kw1);
  60406. if (kx2 - kx1 <= w)
  60407. {
  60408. firstKey = rangeStart;
  60409. sendChangeMessage (this);
  60410. repaint();
  60411. }
  60412. }
  60413. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60414. scrollDown->setVisible (showScrollButtons);
  60415. scrollUp->setVisible (showScrollButtons);
  60416. xOffset = 0;
  60417. if (showScrollButtons)
  60418. {
  60419. const int scrollButtonW = jmin (12, w / 2);
  60420. if (orientation == horizontalKeyboard)
  60421. {
  60422. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60423. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60424. }
  60425. else if (orientation == verticalKeyboardFacingLeft)
  60426. {
  60427. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60428. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60429. }
  60430. else if (orientation == verticalKeyboardFacingRight)
  60431. {
  60432. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60433. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60434. }
  60435. int endOfLastKey, kw;
  60436. getKeyPos (rangeEnd, endOfLastKey, kw);
  60437. endOfLastKey += kw;
  60438. float mousePositionVelocity;
  60439. const int spaceAvailable = w - scrollButtonW * 2;
  60440. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60441. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60442. {
  60443. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60444. sendChangeMessage (this);
  60445. }
  60446. int newOffset = 0;
  60447. getKeyPos (firstKey, newOffset, kw);
  60448. xOffset = newOffset - scrollButtonW;
  60449. }
  60450. else
  60451. {
  60452. firstKey = rangeStart;
  60453. }
  60454. timerCallback();
  60455. repaint();
  60456. }
  60457. }
  60458. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60459. {
  60460. triggerAsyncUpdate();
  60461. }
  60462. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60463. {
  60464. triggerAsyncUpdate();
  60465. }
  60466. void MidiKeyboardComponent::handleAsyncUpdate()
  60467. {
  60468. for (int i = rangeStart; i <= rangeEnd; ++i)
  60469. {
  60470. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60471. {
  60472. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60473. repaintNote (i);
  60474. }
  60475. }
  60476. }
  60477. void MidiKeyboardComponent::resetAnyKeysInUse()
  60478. {
  60479. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60480. {
  60481. state.allNotesOff (midiChannel);
  60482. keysPressed.clear();
  60483. mouseDownNote = -1;
  60484. }
  60485. }
  60486. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60487. {
  60488. float mousePositionVelocity = 0.0f;
  60489. const int newNote = (mouseDragging || isMouseOver())
  60490. ? xyToNote (pos, mousePositionVelocity) : -1;
  60491. if (noteUnderMouse != newNote)
  60492. {
  60493. if (mouseDownNote >= 0)
  60494. {
  60495. state.noteOff (midiChannel, mouseDownNote);
  60496. mouseDownNote = -1;
  60497. }
  60498. if (mouseDragging && newNote >= 0)
  60499. {
  60500. if (! useMousePositionForVelocity)
  60501. mousePositionVelocity = 1.0f;
  60502. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60503. mouseDownNote = newNote;
  60504. }
  60505. repaintNote (noteUnderMouse);
  60506. noteUnderMouse = newNote;
  60507. repaintNote (noteUnderMouse);
  60508. }
  60509. else if (mouseDownNote >= 0 && ! mouseDragging)
  60510. {
  60511. state.noteOff (midiChannel, mouseDownNote);
  60512. mouseDownNote = -1;
  60513. }
  60514. }
  60515. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60516. {
  60517. updateNoteUnderMouse (e.getPosition());
  60518. stopTimer();
  60519. }
  60520. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60521. {
  60522. float mousePositionVelocity;
  60523. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60524. if (newNote >= 0)
  60525. mouseDraggedToKey (newNote, e);
  60526. updateNoteUnderMouse (e.getPosition());
  60527. }
  60528. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60529. {
  60530. return true;
  60531. }
  60532. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60533. {
  60534. }
  60535. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60536. {
  60537. float mousePositionVelocity;
  60538. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60539. mouseDragging = false;
  60540. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60541. {
  60542. repaintNote (noteUnderMouse);
  60543. noteUnderMouse = -1;
  60544. mouseDragging = true;
  60545. updateNoteUnderMouse (e.getPosition());
  60546. startTimer (500);
  60547. }
  60548. }
  60549. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60550. {
  60551. mouseDragging = false;
  60552. updateNoteUnderMouse (e.getPosition());
  60553. stopTimer();
  60554. }
  60555. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60556. {
  60557. updateNoteUnderMouse (e.getPosition());
  60558. }
  60559. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60560. {
  60561. updateNoteUnderMouse (e.getPosition());
  60562. }
  60563. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60564. {
  60565. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60566. }
  60567. void MidiKeyboardComponent::timerCallback()
  60568. {
  60569. updateNoteUnderMouse (getMouseXYRelative());
  60570. }
  60571. void MidiKeyboardComponent::clearKeyMappings()
  60572. {
  60573. resetAnyKeysInUse();
  60574. keyPressNotes.clear();
  60575. keyPresses.clear();
  60576. }
  60577. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60578. const int midiNoteOffsetFromC)
  60579. {
  60580. removeKeyPressForNote (midiNoteOffsetFromC);
  60581. keyPressNotes.add (midiNoteOffsetFromC);
  60582. keyPresses.add (key);
  60583. }
  60584. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60585. {
  60586. for (int i = keyPressNotes.size(); --i >= 0;)
  60587. {
  60588. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60589. {
  60590. keyPressNotes.remove (i);
  60591. keyPresses.remove (i);
  60592. }
  60593. }
  60594. }
  60595. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60596. {
  60597. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60598. keyMappingOctave = newOctaveNumber;
  60599. }
  60600. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60601. {
  60602. bool keyPressUsed = false;
  60603. for (int i = keyPresses.size(); --i >= 0;)
  60604. {
  60605. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60606. if (keyPresses.getReference(i).isCurrentlyDown())
  60607. {
  60608. if (! keysPressed [note])
  60609. {
  60610. keysPressed.setBit (note);
  60611. state.noteOn (midiChannel, note, velocity);
  60612. keyPressUsed = true;
  60613. }
  60614. }
  60615. else
  60616. {
  60617. if (keysPressed [note])
  60618. {
  60619. keysPressed.clearBit (note);
  60620. state.noteOff (midiChannel, note);
  60621. keyPressUsed = true;
  60622. }
  60623. }
  60624. }
  60625. return keyPressUsed;
  60626. }
  60627. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60628. {
  60629. resetAnyKeysInUse();
  60630. }
  60631. END_JUCE_NAMESPACE
  60632. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60633. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60634. #if JUCE_OPENGL
  60635. BEGIN_JUCE_NAMESPACE
  60636. extern void juce_glViewport (const int w, const int h);
  60637. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60638. const int alphaBits_,
  60639. const int depthBufferBits_,
  60640. const int stencilBufferBits_)
  60641. : redBits (bitsPerRGBComponent),
  60642. greenBits (bitsPerRGBComponent),
  60643. blueBits (bitsPerRGBComponent),
  60644. alphaBits (alphaBits_),
  60645. depthBufferBits (depthBufferBits_),
  60646. stencilBufferBits (stencilBufferBits_),
  60647. accumulationBufferRedBits (0),
  60648. accumulationBufferGreenBits (0),
  60649. accumulationBufferBlueBits (0),
  60650. accumulationBufferAlphaBits (0),
  60651. fullSceneAntiAliasingNumSamples (0)
  60652. {
  60653. }
  60654. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60655. : redBits (other.redBits),
  60656. greenBits (other.greenBits),
  60657. blueBits (other.blueBits),
  60658. alphaBits (other.alphaBits),
  60659. depthBufferBits (other.depthBufferBits),
  60660. stencilBufferBits (other.stencilBufferBits),
  60661. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60662. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60663. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60664. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60665. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60666. {
  60667. }
  60668. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60669. {
  60670. redBits = other.redBits;
  60671. greenBits = other.greenBits;
  60672. blueBits = other.blueBits;
  60673. alphaBits = other.alphaBits;
  60674. depthBufferBits = other.depthBufferBits;
  60675. stencilBufferBits = other.stencilBufferBits;
  60676. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60677. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60678. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60679. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60680. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60681. return *this;
  60682. }
  60683. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60684. {
  60685. return redBits == other.redBits
  60686. && greenBits == other.greenBits
  60687. && blueBits == other.blueBits
  60688. && alphaBits == other.alphaBits
  60689. && depthBufferBits == other.depthBufferBits
  60690. && stencilBufferBits == other.stencilBufferBits
  60691. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60692. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60693. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60694. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60695. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60696. }
  60697. static Array<OpenGLContext*> knownContexts;
  60698. OpenGLContext::OpenGLContext() throw()
  60699. {
  60700. knownContexts.add (this);
  60701. }
  60702. OpenGLContext::~OpenGLContext()
  60703. {
  60704. knownContexts.removeValue (this);
  60705. }
  60706. OpenGLContext* OpenGLContext::getCurrentContext()
  60707. {
  60708. for (int i = knownContexts.size(); --i >= 0;)
  60709. {
  60710. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60711. if (oglc->isActive())
  60712. return oglc;
  60713. }
  60714. return 0;
  60715. }
  60716. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60717. {
  60718. public:
  60719. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60720. : ComponentMovementWatcher (owner_),
  60721. owner (owner_),
  60722. wasShowing (false)
  60723. {
  60724. }
  60725. ~OpenGLComponentWatcher() {}
  60726. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60727. {
  60728. owner->updateContextPosition();
  60729. }
  60730. void componentPeerChanged()
  60731. {
  60732. const ScopedLock sl (owner->getContextLock());
  60733. owner->deleteContext();
  60734. }
  60735. void componentVisibilityChanged (Component&)
  60736. {
  60737. const bool isShowingNow = owner->isShowing();
  60738. if (wasShowing != isShowingNow)
  60739. {
  60740. wasShowing = isShowingNow;
  60741. owner->updateContextPosition();
  60742. }
  60743. }
  60744. juce_UseDebuggingNewOperator
  60745. private:
  60746. OpenGLComponent* const owner;
  60747. bool wasShowing;
  60748. };
  60749. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60750. : type (type_),
  60751. contextToShareListsWith (0),
  60752. needToUpdateViewport (true)
  60753. {
  60754. setOpaque (true);
  60755. componentWatcher = new OpenGLComponentWatcher (this);
  60756. }
  60757. OpenGLComponent::~OpenGLComponent()
  60758. {
  60759. deleteContext();
  60760. componentWatcher = 0;
  60761. }
  60762. void OpenGLComponent::deleteContext()
  60763. {
  60764. const ScopedLock sl (contextLock);
  60765. context = 0;
  60766. }
  60767. void OpenGLComponent::updateContextPosition()
  60768. {
  60769. needToUpdateViewport = true;
  60770. if (getWidth() > 0 && getHeight() > 0)
  60771. {
  60772. Component* const topComp = getTopLevelComponent();
  60773. if (topComp->getPeer() != 0)
  60774. {
  60775. const ScopedLock sl (contextLock);
  60776. if (context != 0)
  60777. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60778. getScreenY() - topComp->getScreenY(),
  60779. getWidth(),
  60780. getHeight(),
  60781. topComp->getHeight());
  60782. }
  60783. }
  60784. }
  60785. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60786. {
  60787. OpenGLPixelFormat pf;
  60788. const ScopedLock sl (contextLock);
  60789. if (context != 0)
  60790. pf = context->getPixelFormat();
  60791. return pf;
  60792. }
  60793. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60794. {
  60795. if (! (preferredPixelFormat == formatToUse))
  60796. {
  60797. const ScopedLock sl (contextLock);
  60798. deleteContext();
  60799. preferredPixelFormat = formatToUse;
  60800. }
  60801. }
  60802. void OpenGLComponent::shareWith (OpenGLContext* c)
  60803. {
  60804. if (contextToShareListsWith != c)
  60805. {
  60806. const ScopedLock sl (contextLock);
  60807. deleteContext();
  60808. contextToShareListsWith = c;
  60809. }
  60810. }
  60811. bool OpenGLComponent::makeCurrentContextActive()
  60812. {
  60813. if (context == 0)
  60814. {
  60815. const ScopedLock sl (contextLock);
  60816. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60817. {
  60818. context = createContext();
  60819. if (context != 0)
  60820. {
  60821. updateContextPosition();
  60822. if (context->makeActive())
  60823. newOpenGLContextCreated();
  60824. }
  60825. }
  60826. }
  60827. return context != 0 && context->makeActive();
  60828. }
  60829. void OpenGLComponent::makeCurrentContextInactive()
  60830. {
  60831. if (context != 0)
  60832. context->makeInactive();
  60833. }
  60834. bool OpenGLComponent::isActiveContext() const throw()
  60835. {
  60836. return context != 0 && context->isActive();
  60837. }
  60838. void OpenGLComponent::swapBuffers()
  60839. {
  60840. if (context != 0)
  60841. context->swapBuffers();
  60842. }
  60843. void OpenGLComponent::paint (Graphics&)
  60844. {
  60845. if (renderAndSwapBuffers())
  60846. {
  60847. ComponentPeer* const peer = getPeer();
  60848. if (peer != 0)
  60849. {
  60850. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60851. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60852. }
  60853. }
  60854. }
  60855. bool OpenGLComponent::renderAndSwapBuffers()
  60856. {
  60857. const ScopedLock sl (contextLock);
  60858. if (! makeCurrentContextActive())
  60859. return false;
  60860. if (needToUpdateViewport)
  60861. {
  60862. needToUpdateViewport = false;
  60863. juce_glViewport (getWidth(), getHeight());
  60864. }
  60865. renderOpenGL();
  60866. swapBuffers();
  60867. return true;
  60868. }
  60869. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  60870. {
  60871. Component::internalRepaint (x, y, w, h);
  60872. if (context != 0)
  60873. context->repaint();
  60874. }
  60875. END_JUCE_NAMESPACE
  60876. #endif
  60877. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  60878. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  60879. BEGIN_JUCE_NAMESPACE
  60880. PreferencesPanel::PreferencesPanel()
  60881. : buttonSize (70)
  60882. {
  60883. }
  60884. PreferencesPanel::~PreferencesPanel()
  60885. {
  60886. currentPage = 0;
  60887. deleteAllChildren();
  60888. }
  60889. void PreferencesPanel::addSettingsPage (const String& title,
  60890. const Drawable* icon,
  60891. const Drawable* overIcon,
  60892. const Drawable* downIcon)
  60893. {
  60894. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  60895. button->setImages (icon, overIcon, downIcon);
  60896. button->setRadioGroupId (1);
  60897. button->addButtonListener (this);
  60898. button->setClickingTogglesState (true);
  60899. button->setWantsKeyboardFocus (false);
  60900. addAndMakeVisible (button);
  60901. resized();
  60902. if (currentPage == 0)
  60903. setCurrentPage (title);
  60904. }
  60905. void PreferencesPanel::addSettingsPage (const String& title,
  60906. const void* imageData,
  60907. const int imageDataSize)
  60908. {
  60909. DrawableImage icon, iconOver, iconDown;
  60910. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  60911. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  60912. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  60913. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  60914. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  60915. addSettingsPage (title, &icon, &iconOver, &iconDown);
  60916. }
  60917. class PrefsDialogWindow : public DialogWindow
  60918. {
  60919. public:
  60920. PrefsDialogWindow (const String& dialogtitle,
  60921. const Colour& backgroundColour)
  60922. : DialogWindow (dialogtitle, backgroundColour, true)
  60923. {
  60924. }
  60925. ~PrefsDialogWindow()
  60926. {
  60927. }
  60928. void closeButtonPressed()
  60929. {
  60930. exitModalState (0);
  60931. }
  60932. private:
  60933. PrefsDialogWindow (const PrefsDialogWindow&);
  60934. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  60935. };
  60936. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  60937. int dialogWidth,
  60938. int dialogHeight,
  60939. const Colour& backgroundColour)
  60940. {
  60941. setSize (dialogWidth, dialogHeight);
  60942. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  60943. dw.setContentComponent (this, true, true);
  60944. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  60945. dw.runModalLoop();
  60946. dw.setContentComponent (0, false, false);
  60947. }
  60948. void PreferencesPanel::resized()
  60949. {
  60950. int x = 0;
  60951. for (int i = 0; i < getNumChildComponents(); ++i)
  60952. {
  60953. Component* c = getChildComponent (i);
  60954. if (dynamic_cast <DrawableButton*> (c) == 0)
  60955. {
  60956. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  60957. }
  60958. else
  60959. {
  60960. c->setBounds (x, 0, buttonSize, buttonSize);
  60961. x += buttonSize;
  60962. }
  60963. }
  60964. }
  60965. void PreferencesPanel::paint (Graphics& g)
  60966. {
  60967. g.setColour (Colours::grey);
  60968. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  60969. }
  60970. void PreferencesPanel::setCurrentPage (const String& pageName)
  60971. {
  60972. if (currentPageName != pageName)
  60973. {
  60974. currentPageName = pageName;
  60975. currentPage = 0;
  60976. currentPage = createComponentForPage (pageName);
  60977. if (currentPage != 0)
  60978. {
  60979. addAndMakeVisible (currentPage);
  60980. currentPage->toBack();
  60981. resized();
  60982. }
  60983. for (int i = 0; i < getNumChildComponents(); ++i)
  60984. {
  60985. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60986. if (db != 0 && db->getName() == pageName)
  60987. {
  60988. db->setToggleState (true, false);
  60989. break;
  60990. }
  60991. }
  60992. }
  60993. }
  60994. void PreferencesPanel::buttonClicked (Button*)
  60995. {
  60996. for (int i = 0; i < getNumChildComponents(); ++i)
  60997. {
  60998. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60999. if (db != 0 && db->getToggleState())
  61000. {
  61001. setCurrentPage (db->getName());
  61002. break;
  61003. }
  61004. }
  61005. }
  61006. END_JUCE_NAMESPACE
  61007. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61008. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61009. #if JUCE_WINDOWS || JUCE_LINUX
  61010. BEGIN_JUCE_NAMESPACE
  61011. SystemTrayIconComponent::SystemTrayIconComponent()
  61012. {
  61013. addToDesktop (0);
  61014. }
  61015. SystemTrayIconComponent::~SystemTrayIconComponent()
  61016. {
  61017. }
  61018. END_JUCE_NAMESPACE
  61019. #endif
  61020. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61021. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61022. BEGIN_JUCE_NAMESPACE
  61023. class AlertWindowTextEditor : public TextEditor
  61024. {
  61025. public:
  61026. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61027. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61028. {
  61029. setSelectAllWhenFocused (true);
  61030. }
  61031. ~AlertWindowTextEditor()
  61032. {
  61033. }
  61034. void returnPressed()
  61035. {
  61036. // pass these up the component hierarchy to be trigger the buttons
  61037. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61038. }
  61039. void escapePressed()
  61040. {
  61041. // pass these up the component hierarchy to be trigger the buttons
  61042. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61043. }
  61044. private:
  61045. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61046. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61047. static juce_wchar getDefaultPasswordChar() throw()
  61048. {
  61049. #if JUCE_LINUX
  61050. return 0x2022;
  61051. #else
  61052. return 0x25cf;
  61053. #endif
  61054. }
  61055. };
  61056. AlertWindow::AlertWindow (const String& title,
  61057. const String& message,
  61058. AlertIconType iconType,
  61059. Component* associatedComponent_)
  61060. : TopLevelWindow (title, true),
  61061. alertIconType (iconType),
  61062. associatedComponent (associatedComponent_)
  61063. {
  61064. if (message.isEmpty())
  61065. text = " "; // to force an update if the message is empty
  61066. setMessage (message);
  61067. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61068. {
  61069. Component* const c = Desktop::getInstance().getComponent (i);
  61070. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61071. {
  61072. setAlwaysOnTop (true);
  61073. break;
  61074. }
  61075. }
  61076. if (JUCEApplication::getInstance() == 0)
  61077. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61078. lookAndFeelChanged();
  61079. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61080. }
  61081. AlertWindow::~AlertWindow()
  61082. {
  61083. for (int i = customComps.size(); --i >= 0;)
  61084. removeChildComponent ((Component*) customComps[i]);
  61085. deleteAllChildren();
  61086. }
  61087. void AlertWindow::userTriedToCloseWindow()
  61088. {
  61089. exitModalState (0);
  61090. }
  61091. void AlertWindow::setMessage (const String& message)
  61092. {
  61093. const String newMessage (message.substring (0, 2048));
  61094. if (text != newMessage)
  61095. {
  61096. text = newMessage;
  61097. font.setHeight (15.0f);
  61098. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61099. textLayout.setText (getName() + "\n\n", titleFont);
  61100. textLayout.appendText (text, font);
  61101. updateLayout (true);
  61102. repaint();
  61103. }
  61104. }
  61105. void AlertWindow::buttonClicked (Button* button)
  61106. {
  61107. for (int i = 0; i < buttons.size(); i++)
  61108. {
  61109. TextButton* const c = (TextButton*) buttons[i];
  61110. if (button->getName() == c->getName())
  61111. {
  61112. if (c->getParentComponent() != 0)
  61113. c->getParentComponent()->exitModalState (c->getCommandID());
  61114. break;
  61115. }
  61116. }
  61117. }
  61118. void AlertWindow::addButton (const String& name,
  61119. const int returnValue,
  61120. const KeyPress& shortcutKey1,
  61121. const KeyPress& shortcutKey2)
  61122. {
  61123. TextButton* const b = new TextButton (name, String::empty);
  61124. b->setWantsKeyboardFocus (true);
  61125. b->setMouseClickGrabsKeyboardFocus (false);
  61126. b->setCommandToTrigger (0, returnValue, false);
  61127. b->addShortcut (shortcutKey1);
  61128. b->addShortcut (shortcutKey2);
  61129. b->addButtonListener (this);
  61130. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61131. addAndMakeVisible (b, 0);
  61132. buttons.add (b);
  61133. updateLayout (false);
  61134. }
  61135. int AlertWindow::getNumButtons() const
  61136. {
  61137. return buttons.size();
  61138. }
  61139. void AlertWindow::triggerButtonClick (const String& buttonName)
  61140. {
  61141. for (int i = buttons.size(); --i >= 0;)
  61142. {
  61143. TextButton* const b = (TextButton*) buttons[i];
  61144. if (buttonName == b->getName())
  61145. {
  61146. b->triggerClick();
  61147. break;
  61148. }
  61149. }
  61150. }
  61151. void AlertWindow::addTextEditor (const String& name,
  61152. const String& initialContents,
  61153. const String& onScreenLabel,
  61154. const bool isPasswordBox)
  61155. {
  61156. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61157. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61158. tc->setFont (font);
  61159. tc->setText (initialContents);
  61160. tc->setCaretPosition (initialContents.length());
  61161. addAndMakeVisible (tc);
  61162. textBoxes.add (tc);
  61163. allComps.add (tc);
  61164. textboxNames.add (onScreenLabel);
  61165. updateLayout (false);
  61166. }
  61167. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61168. {
  61169. for (int i = textBoxes.size(); --i >= 0;)
  61170. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61171. return ((TextEditor*)textBoxes[i])->getText();
  61172. return String::empty;
  61173. }
  61174. void AlertWindow::addComboBox (const String& name,
  61175. const StringArray& items,
  61176. const String& onScreenLabel)
  61177. {
  61178. ComboBox* const cb = new ComboBox (name);
  61179. for (int i = 0; i < items.size(); ++i)
  61180. cb->addItem (items[i], i + 1);
  61181. addAndMakeVisible (cb);
  61182. cb->setSelectedItemIndex (0);
  61183. comboBoxes.add (cb);
  61184. allComps.add (cb);
  61185. comboBoxNames.add (onScreenLabel);
  61186. updateLayout (false);
  61187. }
  61188. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61189. {
  61190. for (int i = comboBoxes.size(); --i >= 0;)
  61191. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61192. return (ComboBox*) comboBoxes[i];
  61193. return 0;
  61194. }
  61195. class AlertTextComp : public TextEditor
  61196. {
  61197. public:
  61198. AlertTextComp (const String& message,
  61199. const Font& font)
  61200. {
  61201. setReadOnly (true);
  61202. setMultiLine (true, true);
  61203. setCaretVisible (false);
  61204. setScrollbarsShown (true);
  61205. lookAndFeelChanged();
  61206. setWantsKeyboardFocus (false);
  61207. setFont (font);
  61208. setText (message, false);
  61209. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61210. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61211. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61212. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61213. }
  61214. ~AlertTextComp()
  61215. {
  61216. }
  61217. int getPreferredWidth() const throw() { return bestWidth; }
  61218. void updateLayout (const int width)
  61219. {
  61220. TextLayout text;
  61221. text.appendText (getText(), getFont());
  61222. text.layout (width - 8, Justification::topLeft, true);
  61223. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61224. }
  61225. private:
  61226. int bestWidth;
  61227. AlertTextComp (const AlertTextComp&);
  61228. AlertTextComp& operator= (const AlertTextComp&);
  61229. };
  61230. void AlertWindow::addTextBlock (const String& textBlock)
  61231. {
  61232. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61233. textBlocks.add (c);
  61234. allComps.add (c);
  61235. addAndMakeVisible (c);
  61236. updateLayout (false);
  61237. }
  61238. void AlertWindow::addProgressBarComponent (double& progressValue)
  61239. {
  61240. ProgressBar* const pb = new ProgressBar (progressValue);
  61241. progressBars.add (pb);
  61242. allComps.add (pb);
  61243. addAndMakeVisible (pb);
  61244. updateLayout (false);
  61245. }
  61246. void AlertWindow::addCustomComponent (Component* const component)
  61247. {
  61248. customComps.add (component);
  61249. allComps.add (component);
  61250. addAndMakeVisible (component);
  61251. updateLayout (false);
  61252. }
  61253. int AlertWindow::getNumCustomComponents() const
  61254. {
  61255. return customComps.size();
  61256. }
  61257. Component* AlertWindow::getCustomComponent (const int index) const
  61258. {
  61259. return (Component*) customComps [index];
  61260. }
  61261. Component* AlertWindow::removeCustomComponent (const int index)
  61262. {
  61263. Component* const c = getCustomComponent (index);
  61264. if (c != 0)
  61265. {
  61266. customComps.removeValue (c);
  61267. allComps.removeValue (c);
  61268. removeChildComponent (c);
  61269. updateLayout (false);
  61270. }
  61271. return c;
  61272. }
  61273. void AlertWindow::paint (Graphics& g)
  61274. {
  61275. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61276. g.setColour (findColour (textColourId));
  61277. g.setFont (getLookAndFeel().getAlertWindowFont());
  61278. int i;
  61279. for (i = textBoxes.size(); --i >= 0;)
  61280. {
  61281. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61282. g.drawFittedText (textboxNames[i],
  61283. te->getX(), te->getY() - 14,
  61284. te->getWidth(), 14,
  61285. Justification::centredLeft, 1);
  61286. }
  61287. for (i = comboBoxNames.size(); --i >= 0;)
  61288. {
  61289. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61290. g.drawFittedText (comboBoxNames[i],
  61291. cb->getX(), cb->getY() - 14,
  61292. cb->getWidth(), 14,
  61293. Justification::centredLeft, 1);
  61294. }
  61295. for (i = customComps.size(); --i >= 0;)
  61296. {
  61297. const Component* const c = (Component*) customComps[i];
  61298. g.drawFittedText (c->getName(),
  61299. c->getX(), c->getY() - 14,
  61300. c->getWidth(), 14,
  61301. Justification::centredLeft, 1);
  61302. }
  61303. }
  61304. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61305. {
  61306. const int titleH = 24;
  61307. const int iconWidth = 80;
  61308. const int wid = jmax (font.getStringWidth (text),
  61309. font.getStringWidth (getName()));
  61310. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61311. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61312. const int edgeGap = 10;
  61313. const int labelHeight = 18;
  61314. int iconSpace;
  61315. if (alertIconType == NoIcon)
  61316. {
  61317. textLayout.layout (w, Justification::horizontallyCentred, true);
  61318. iconSpace = 0;
  61319. }
  61320. else
  61321. {
  61322. textLayout.layout (w, Justification::left, true);
  61323. iconSpace = iconWidth;
  61324. }
  61325. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61326. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61327. const int textLayoutH = textLayout.getHeight();
  61328. const int textBottom = 16 + titleH + textLayoutH;
  61329. int h = textBottom;
  61330. int buttonW = 40;
  61331. int i;
  61332. for (i = 0; i < buttons.size(); ++i)
  61333. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61334. w = jmax (buttonW, w);
  61335. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61336. if (buttons.size() > 0)
  61337. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61338. for (i = customComps.size(); --i >= 0;)
  61339. {
  61340. Component* c = (Component*) customComps[i];
  61341. w = jmax (w, (c->getWidth() * 100) / 80);
  61342. h += 10 + c->getHeight();
  61343. if (c->getName().isNotEmpty())
  61344. h += labelHeight;
  61345. }
  61346. for (i = textBlocks.size(); --i >= 0;)
  61347. {
  61348. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61349. w = jmax (w, ac->getPreferredWidth());
  61350. }
  61351. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61352. for (i = textBlocks.size(); --i >= 0;)
  61353. {
  61354. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61355. ac->updateLayout ((int) (w * 0.8f));
  61356. h += ac->getHeight() + 10;
  61357. }
  61358. h = jmin (getParentHeight() - 50, h);
  61359. if (onlyIncreaseSize)
  61360. {
  61361. w = jmax (w, getWidth());
  61362. h = jmax (h, getHeight());
  61363. }
  61364. if (! isVisible())
  61365. {
  61366. centreAroundComponent (associatedComponent, w, h);
  61367. }
  61368. else
  61369. {
  61370. const int cx = getX() + getWidth() / 2;
  61371. const int cy = getY() + getHeight() / 2;
  61372. setBounds (cx - w / 2,
  61373. cy - h / 2,
  61374. w, h);
  61375. }
  61376. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61377. const int spacer = 16;
  61378. int totalWidth = -spacer;
  61379. for (i = buttons.size(); --i >= 0;)
  61380. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61381. int x = (w - totalWidth) / 2;
  61382. int y = (int) (getHeight() * 0.95f);
  61383. for (i = 0; i < buttons.size(); ++i)
  61384. {
  61385. TextButton* const c = (TextButton*) buttons[i];
  61386. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61387. c->setTopLeftPosition (x, ny);
  61388. if (ny < y)
  61389. y = ny;
  61390. x += c->getWidth() + spacer;
  61391. c->toFront (false);
  61392. }
  61393. y = textBottom;
  61394. for (i = 0; i < allComps.size(); ++i)
  61395. {
  61396. Component* const c = (Component*) allComps[i];
  61397. h = 22;
  61398. const int comboIndex = comboBoxes.indexOf (c);
  61399. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61400. y += labelHeight;
  61401. const int tbIndex = textBoxes.indexOf (c);
  61402. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61403. y += labelHeight;
  61404. if (customComps.contains (c))
  61405. {
  61406. if (c->getName().isNotEmpty())
  61407. y += labelHeight;
  61408. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61409. h = c->getHeight();
  61410. }
  61411. else if (textBlocks.contains (c))
  61412. {
  61413. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61414. h = c->getHeight();
  61415. }
  61416. else
  61417. {
  61418. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61419. }
  61420. y += h + 10;
  61421. }
  61422. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61423. }
  61424. bool AlertWindow::containsAnyExtraComponents() const
  61425. {
  61426. return textBoxes.size()
  61427. + comboBoxes.size()
  61428. + progressBars.size()
  61429. + customComps.size() > 0;
  61430. }
  61431. void AlertWindow::mouseDown (const MouseEvent&)
  61432. {
  61433. dragger.startDraggingComponent (this, &constrainer);
  61434. }
  61435. void AlertWindow::mouseDrag (const MouseEvent& e)
  61436. {
  61437. dragger.dragComponent (this, e);
  61438. }
  61439. bool AlertWindow::keyPressed (const KeyPress& key)
  61440. {
  61441. for (int i = buttons.size(); --i >= 0;)
  61442. {
  61443. TextButton* const b = (TextButton*) buttons[i];
  61444. if (b->isRegisteredForShortcut (key))
  61445. {
  61446. b->triggerClick();
  61447. return true;
  61448. }
  61449. }
  61450. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61451. {
  61452. exitModalState (0);
  61453. return true;
  61454. }
  61455. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61456. {
  61457. ((TextButton*) buttons.getFirst())->triggerClick();
  61458. return true;
  61459. }
  61460. return false;
  61461. }
  61462. void AlertWindow::lookAndFeelChanged()
  61463. {
  61464. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61465. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61466. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61467. }
  61468. int AlertWindow::getDesktopWindowStyleFlags() const
  61469. {
  61470. return getLookAndFeel().getAlertBoxWindowFlags();
  61471. }
  61472. struct AlertWindowInfo
  61473. {
  61474. String title, message, button1, button2, button3;
  61475. AlertWindow::AlertIconType iconType;
  61476. int numButtons;
  61477. Component::SafePointer<Component> associatedComponent;
  61478. int run() const
  61479. {
  61480. return (int) (pointer_sized_int)
  61481. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61482. }
  61483. private:
  61484. int show() const
  61485. {
  61486. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61487. : LookAndFeel::getDefaultLookAndFeel();
  61488. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61489. iconType, numButtons, associatedComponent));
  61490. jassert (alertBox != 0); // you have to return one of these!
  61491. return alertBox->runModalLoop();
  61492. }
  61493. static void* showCallback (void* userData)
  61494. {
  61495. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61496. }
  61497. };
  61498. void AlertWindow::showMessageBox (AlertIconType iconType,
  61499. const String& title,
  61500. const String& message,
  61501. const String& buttonText,
  61502. Component* associatedComponent)
  61503. {
  61504. AlertWindowInfo info;
  61505. info.title = title;
  61506. info.message = message;
  61507. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61508. info.iconType = iconType;
  61509. info.numButtons = 1;
  61510. info.associatedComponent = associatedComponent;
  61511. info.run();
  61512. }
  61513. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61514. const String& title,
  61515. const String& message,
  61516. const String& button1Text,
  61517. const String& button2Text,
  61518. Component* associatedComponent)
  61519. {
  61520. AlertWindowInfo info;
  61521. info.title = title;
  61522. info.message = message;
  61523. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61524. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61525. info.iconType = iconType;
  61526. info.numButtons = 2;
  61527. info.associatedComponent = associatedComponent;
  61528. return info.run() != 0;
  61529. }
  61530. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61531. const String& title,
  61532. const String& message,
  61533. const String& button1Text,
  61534. const String& button2Text,
  61535. const String& button3Text,
  61536. Component* associatedComponent)
  61537. {
  61538. AlertWindowInfo info;
  61539. info.title = title;
  61540. info.message = message;
  61541. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61542. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61543. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61544. info.iconType = iconType;
  61545. info.numButtons = 3;
  61546. info.associatedComponent = associatedComponent;
  61547. return info.run();
  61548. }
  61549. END_JUCE_NAMESPACE
  61550. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61551. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61552. BEGIN_JUCE_NAMESPACE
  61553. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61554. static Array <ComponentPeer*> heavyweightPeers;
  61555. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61556. : component (component_),
  61557. styleFlags (styleFlags_),
  61558. lastPaintTime (0),
  61559. constrainer (0),
  61560. lastDragAndDropCompUnderMouse (0),
  61561. fakeMouseMessageSent (false),
  61562. isWindowMinimised (false)
  61563. {
  61564. heavyweightPeers.add (this);
  61565. }
  61566. ComponentPeer::~ComponentPeer()
  61567. {
  61568. heavyweightPeers.removeValue (this);
  61569. Desktop::getInstance().triggerFocusCallback();
  61570. }
  61571. int ComponentPeer::getNumPeers() throw()
  61572. {
  61573. return heavyweightPeers.size();
  61574. }
  61575. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61576. {
  61577. return heavyweightPeers [index];
  61578. }
  61579. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61580. {
  61581. for (int i = heavyweightPeers.size(); --i >= 0;)
  61582. {
  61583. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61584. if (peer->getComponent() == component)
  61585. return peer;
  61586. }
  61587. return 0;
  61588. }
  61589. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61590. {
  61591. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61592. }
  61593. void ComponentPeer::updateCurrentModifiers() throw()
  61594. {
  61595. ModifierKeys::updateCurrentModifiers();
  61596. }
  61597. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61598. {
  61599. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61600. jassert (mouse != 0); // not enough sources!
  61601. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61602. }
  61603. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61604. {
  61605. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61606. jassert (mouse != 0); // not enough sources!
  61607. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61608. }
  61609. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61610. {
  61611. Graphics g (&contextToPaintTo);
  61612. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61613. g.saveState();
  61614. #endif
  61615. JUCE_TRY
  61616. {
  61617. component->paintEntireComponent (g);
  61618. }
  61619. JUCE_CATCH_EXCEPTION
  61620. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61621. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61622. // clearly when things are being repainted.
  61623. {
  61624. g.restoreState();
  61625. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61626. (uint8) Random::getSystemRandom().nextInt (255),
  61627. (uint8) Random::getSystemRandom().nextInt (255),
  61628. (uint8) 0x50));
  61629. }
  61630. #endif
  61631. }
  61632. bool ComponentPeer::handleKeyPress (const int keyCode,
  61633. const juce_wchar textCharacter)
  61634. {
  61635. updateCurrentModifiers();
  61636. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61637. ? Component::getCurrentlyFocusedComponent()
  61638. : component;
  61639. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61640. {
  61641. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61642. if (currentModalComp != 0)
  61643. target = currentModalComp;
  61644. }
  61645. const KeyPress keyInfo (keyCode,
  61646. ModifierKeys::getCurrentModifiers().getRawFlags()
  61647. & ModifierKeys::allKeyboardModifiers,
  61648. textCharacter);
  61649. bool keyWasUsed = false;
  61650. while (target != 0)
  61651. {
  61652. const Component::SafePointer<Component> deletionChecker (target);
  61653. if (target->keyListeners_ != 0)
  61654. {
  61655. for (int i = target->keyListeners_->size(); --i >= 0;)
  61656. {
  61657. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  61658. if (keyWasUsed || deletionChecker == 0)
  61659. return keyWasUsed;
  61660. i = jmin (i, target->keyListeners_->size());
  61661. }
  61662. }
  61663. keyWasUsed = target->keyPressed (keyInfo);
  61664. if (keyWasUsed || deletionChecker == 0)
  61665. break;
  61666. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61667. {
  61668. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61669. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61670. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61671. break;
  61672. }
  61673. target = target->parentComponent_;
  61674. }
  61675. return keyWasUsed;
  61676. }
  61677. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61678. {
  61679. updateCurrentModifiers();
  61680. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61681. ? Component::getCurrentlyFocusedComponent()
  61682. : component;
  61683. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61684. {
  61685. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61686. if (currentModalComp != 0)
  61687. target = currentModalComp;
  61688. }
  61689. bool keyWasUsed = false;
  61690. while (target != 0)
  61691. {
  61692. const Component::SafePointer<Component> deletionChecker (target);
  61693. keyWasUsed = target->keyStateChanged (isKeyDown);
  61694. if (keyWasUsed || deletionChecker == 0)
  61695. break;
  61696. if (target->keyListeners_ != 0)
  61697. {
  61698. for (int i = target->keyListeners_->size(); --i >= 0;)
  61699. {
  61700. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  61701. if (keyWasUsed || deletionChecker == 0)
  61702. return keyWasUsed;
  61703. i = jmin (i, target->keyListeners_->size());
  61704. }
  61705. }
  61706. target = target->parentComponent_;
  61707. }
  61708. return keyWasUsed;
  61709. }
  61710. void ComponentPeer::handleModifierKeysChange()
  61711. {
  61712. updateCurrentModifiers();
  61713. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  61714. if (target == 0)
  61715. target = Component::getCurrentlyFocusedComponent();
  61716. if (target == 0)
  61717. target = component;
  61718. if (target != 0)
  61719. target->internalModifierKeysChanged();
  61720. }
  61721. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  61722. {
  61723. Component* const c = Component::getCurrentlyFocusedComponent();
  61724. if (component->isParentOf (c))
  61725. {
  61726. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  61727. if (ti != 0 && ti->isTextInputActive())
  61728. return ti;
  61729. }
  61730. return 0;
  61731. }
  61732. void ComponentPeer::handleBroughtToFront()
  61733. {
  61734. updateCurrentModifiers();
  61735. if (component != 0)
  61736. component->internalBroughtToFront();
  61737. }
  61738. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  61739. {
  61740. constrainer = newConstrainer;
  61741. }
  61742. void ComponentPeer::handleMovedOrResized()
  61743. {
  61744. jassert (component->isValidComponent());
  61745. updateCurrentModifiers();
  61746. const bool nowMinimised = isMinimised();
  61747. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  61748. {
  61749. const Component::SafePointer<Component> deletionChecker (component);
  61750. const Rectangle<int> newBounds (getBounds());
  61751. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  61752. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  61753. if (wasMoved || wasResized)
  61754. {
  61755. component->bounds_ = newBounds;
  61756. if (wasResized)
  61757. component->repaint();
  61758. component->sendMovedResizedMessages (wasMoved, wasResized);
  61759. if (deletionChecker == 0)
  61760. return;
  61761. }
  61762. }
  61763. if (isWindowMinimised != nowMinimised)
  61764. {
  61765. isWindowMinimised = nowMinimised;
  61766. component->minimisationStateChanged (nowMinimised);
  61767. component->sendVisibilityChangeMessage();
  61768. }
  61769. if (! isFullScreen())
  61770. lastNonFullscreenBounds = component->getBounds();
  61771. }
  61772. void ComponentPeer::handleFocusGain()
  61773. {
  61774. updateCurrentModifiers();
  61775. if (component->isParentOf (lastFocusedComponent))
  61776. {
  61777. Component::currentlyFocusedComponent = lastFocusedComponent;
  61778. Desktop::getInstance().triggerFocusCallback();
  61779. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  61780. }
  61781. else
  61782. {
  61783. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  61784. component->grabKeyboardFocus();
  61785. else
  61786. Component::bringModalComponentToFront();
  61787. }
  61788. }
  61789. void ComponentPeer::handleFocusLoss()
  61790. {
  61791. updateCurrentModifiers();
  61792. if (component->hasKeyboardFocus (true))
  61793. {
  61794. lastFocusedComponent = Component::currentlyFocusedComponent;
  61795. if (lastFocusedComponent != 0)
  61796. {
  61797. Component::currentlyFocusedComponent = 0;
  61798. Desktop::getInstance().triggerFocusCallback();
  61799. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  61800. }
  61801. }
  61802. }
  61803. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  61804. {
  61805. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  61806. ? static_cast <Component*> (lastFocusedComponent)
  61807. : component;
  61808. }
  61809. void ComponentPeer::handleScreenSizeChange()
  61810. {
  61811. updateCurrentModifiers();
  61812. component->parentSizeChanged();
  61813. handleMovedOrResized();
  61814. }
  61815. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  61816. {
  61817. lastNonFullscreenBounds = newBounds;
  61818. }
  61819. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  61820. {
  61821. return lastNonFullscreenBounds;
  61822. }
  61823. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  61824. const StringArray& files,
  61825. FileDragAndDropTarget* const lastOne)
  61826. {
  61827. while (c != 0)
  61828. {
  61829. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  61830. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  61831. return t;
  61832. c = c->getParentComponent();
  61833. }
  61834. return 0;
  61835. }
  61836. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  61837. {
  61838. updateCurrentModifiers();
  61839. FileDragAndDropTarget* lastTarget
  61840. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61841. FileDragAndDropTarget* newTarget = 0;
  61842. Component* const compUnderMouse = component->getComponentAt (position);
  61843. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  61844. {
  61845. lastDragAndDropCompUnderMouse = compUnderMouse;
  61846. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  61847. if (newTarget != lastTarget)
  61848. {
  61849. if (lastTarget != 0)
  61850. lastTarget->fileDragExit (files);
  61851. dragAndDropTargetComponent = 0;
  61852. if (newTarget != 0)
  61853. {
  61854. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  61855. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  61856. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  61857. }
  61858. }
  61859. }
  61860. else
  61861. {
  61862. newTarget = lastTarget;
  61863. }
  61864. if (newTarget != 0)
  61865. {
  61866. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  61867. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61868. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  61869. }
  61870. }
  61871. void ComponentPeer::handleFileDragExit (const StringArray& files)
  61872. {
  61873. handleFileDragMove (files, Point<int> (-1, -1));
  61874. jassert (dragAndDropTargetComponent == 0);
  61875. lastDragAndDropCompUnderMouse = 0;
  61876. }
  61877. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  61878. {
  61879. handleFileDragMove (files, position);
  61880. if (dragAndDropTargetComponent != 0)
  61881. {
  61882. FileDragAndDropTarget* const target
  61883. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61884. dragAndDropTargetComponent = 0;
  61885. lastDragAndDropCompUnderMouse = 0;
  61886. if (target != 0)
  61887. {
  61888. Component* const targetComp = dynamic_cast <Component*> (target);
  61889. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  61890. {
  61891. targetComp->internalModalInputAttempt();
  61892. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  61893. return;
  61894. }
  61895. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61896. target->filesDropped (files, pos.getX(), pos.getY());
  61897. }
  61898. }
  61899. }
  61900. void ComponentPeer::handleUserClosingWindow()
  61901. {
  61902. updateCurrentModifiers();
  61903. component->userTriedToCloseWindow();
  61904. }
  61905. void ComponentPeer::bringModalComponentToFront()
  61906. {
  61907. Component::bringModalComponentToFront();
  61908. }
  61909. void ComponentPeer::clearMaskedRegion()
  61910. {
  61911. maskedRegion.clear();
  61912. }
  61913. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  61914. {
  61915. maskedRegion.add (x, y, w, h);
  61916. }
  61917. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  61918. {
  61919. StringArray s;
  61920. s.add ("Software Renderer");
  61921. return s;
  61922. }
  61923. int ComponentPeer::getCurrentRenderingEngine() throw()
  61924. {
  61925. return 0;
  61926. }
  61927. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  61928. {
  61929. }
  61930. END_JUCE_NAMESPACE
  61931. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  61932. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  61933. BEGIN_JUCE_NAMESPACE
  61934. DialogWindow::DialogWindow (const String& name,
  61935. const Colour& backgroundColour_,
  61936. const bool escapeKeyTriggersCloseButton_,
  61937. const bool addToDesktop_)
  61938. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  61939. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  61940. {
  61941. }
  61942. DialogWindow::~DialogWindow()
  61943. {
  61944. }
  61945. void DialogWindow::resized()
  61946. {
  61947. DocumentWindow::resized();
  61948. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  61949. if (escapeKeyTriggersCloseButton
  61950. && getCloseButton() != 0
  61951. && ! getCloseButton()->isRegisteredForShortcut (esc))
  61952. {
  61953. getCloseButton()->addShortcut (esc);
  61954. }
  61955. }
  61956. class TempDialogWindow : public DialogWindow
  61957. {
  61958. public:
  61959. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  61960. : DialogWindow (title, colour, escapeCloses, true)
  61961. {
  61962. if (JUCEApplication::getInstance() == 0)
  61963. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61964. }
  61965. ~TempDialogWindow()
  61966. {
  61967. }
  61968. void closeButtonPressed()
  61969. {
  61970. setVisible (false);
  61971. }
  61972. private:
  61973. TempDialogWindow (const TempDialogWindow&);
  61974. TempDialogWindow& operator= (const TempDialogWindow&);
  61975. };
  61976. int DialogWindow::showModalDialog (const String& dialogTitle,
  61977. Component* contentComponent,
  61978. Component* componentToCentreAround,
  61979. const Colour& colour,
  61980. const bool escapeKeyTriggersCloseButton,
  61981. const bool shouldBeResizable,
  61982. const bool useBottomRightCornerResizer)
  61983. {
  61984. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  61985. dw.setContentComponent (contentComponent, true, true);
  61986. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  61987. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  61988. const int result = dw.runModalLoop();
  61989. dw.setContentComponent (0, false);
  61990. return result;
  61991. }
  61992. END_JUCE_NAMESPACE
  61993. /*** End of inlined file: juce_DialogWindow.cpp ***/
  61994. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  61995. BEGIN_JUCE_NAMESPACE
  61996. class DocumentWindow::ButtonListenerProxy : public ButtonListener
  61997. {
  61998. public:
  61999. ButtonListenerProxy (DocumentWindow& owner_)
  62000. : owner (owner_)
  62001. {
  62002. }
  62003. void buttonClicked (Button* button)
  62004. {
  62005. if (button == owner.getMinimiseButton())
  62006. owner.minimiseButtonPressed();
  62007. else if (button == owner.getMaximiseButton())
  62008. owner.maximiseButtonPressed();
  62009. else if (button == owner.getCloseButton())
  62010. owner.closeButtonPressed();
  62011. }
  62012. juce_UseDebuggingNewOperator
  62013. private:
  62014. DocumentWindow& owner;
  62015. ButtonListenerProxy (const ButtonListenerProxy&);
  62016. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  62017. };
  62018. DocumentWindow::DocumentWindow (const String& title,
  62019. const Colour& backgroundColour,
  62020. const int requiredButtons_,
  62021. const bool addToDesktop_)
  62022. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62023. titleBarHeight (26),
  62024. menuBarHeight (24),
  62025. requiredButtons (requiredButtons_),
  62026. #if JUCE_MAC
  62027. positionTitleBarButtonsOnLeft (true),
  62028. #else
  62029. positionTitleBarButtonsOnLeft (false),
  62030. #endif
  62031. drawTitleTextCentred (true),
  62032. menuBarModel (0)
  62033. {
  62034. setResizeLimits (128, 128, 32768, 32768);
  62035. lookAndFeelChanged();
  62036. }
  62037. DocumentWindow::~DocumentWindow()
  62038. {
  62039. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62040. titleBarButtons[i] = 0;
  62041. menuBar = 0;
  62042. }
  62043. void DocumentWindow::repaintTitleBar()
  62044. {
  62045. repaint (getTitleBarArea());
  62046. }
  62047. void DocumentWindow::setName (const String& newName)
  62048. {
  62049. if (newName != getName())
  62050. {
  62051. Component::setName (newName);
  62052. repaintTitleBar();
  62053. }
  62054. }
  62055. void DocumentWindow::setIcon (const Image& imageToUse)
  62056. {
  62057. titleBarIcon = imageToUse;
  62058. repaintTitleBar();
  62059. }
  62060. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62061. {
  62062. titleBarHeight = newHeight;
  62063. resized();
  62064. repaintTitleBar();
  62065. }
  62066. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62067. const bool positionTitleBarButtonsOnLeft_)
  62068. {
  62069. requiredButtons = requiredButtons_;
  62070. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62071. lookAndFeelChanged();
  62072. }
  62073. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62074. {
  62075. drawTitleTextCentred = textShouldBeCentred;
  62076. repaintTitleBar();
  62077. }
  62078. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62079. const int menuBarHeight_)
  62080. {
  62081. if (menuBarModel != menuBarModel_)
  62082. {
  62083. menuBar = 0;
  62084. menuBarModel = menuBarModel_;
  62085. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62086. : getLookAndFeel().getDefaultMenuBarHeight();
  62087. if (menuBarModel != 0)
  62088. {
  62089. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62090. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62091. menuBar->setEnabled (isActiveWindow());
  62092. }
  62093. resized();
  62094. }
  62095. }
  62096. void DocumentWindow::closeButtonPressed()
  62097. {
  62098. /* If you've got a close button, you have to override this method to get
  62099. rid of your window!
  62100. If the window is just a pop-up, you should override this method and make
  62101. it delete the window in whatever way is appropriate for your app. E.g. you
  62102. might just want to call "delete this".
  62103. If your app is centred around this window such that the whole app should quit when
  62104. the window is closed, then you will probably want to use this method as an opportunity
  62105. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62106. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62107. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62108. or closing it via the taskbar icon on Windows).
  62109. */
  62110. jassertfalse;
  62111. }
  62112. void DocumentWindow::minimiseButtonPressed()
  62113. {
  62114. setMinimised (true);
  62115. }
  62116. void DocumentWindow::maximiseButtonPressed()
  62117. {
  62118. setFullScreen (! isFullScreen());
  62119. }
  62120. void DocumentWindow::paint (Graphics& g)
  62121. {
  62122. ResizableWindow::paint (g);
  62123. if (resizableBorder == 0)
  62124. {
  62125. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62126. const BorderSize border (getBorderThickness());
  62127. g.fillRect (0, 0, getWidth(), border.getTop());
  62128. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62129. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62130. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62131. }
  62132. const Rectangle<int> titleBarArea (getTitleBarArea());
  62133. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62134. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62135. int titleSpaceX1 = 6;
  62136. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62137. for (int i = 0; i < 3; ++i)
  62138. {
  62139. if (titleBarButtons[i] != 0)
  62140. {
  62141. if (positionTitleBarButtonsOnLeft)
  62142. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62143. else
  62144. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62145. }
  62146. }
  62147. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62148. titleBarArea.getWidth(),
  62149. titleBarArea.getHeight(),
  62150. titleSpaceX1,
  62151. jmax (1, titleSpaceX2 - titleSpaceX1),
  62152. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62153. ! drawTitleTextCentred);
  62154. }
  62155. void DocumentWindow::resized()
  62156. {
  62157. ResizableWindow::resized();
  62158. if (titleBarButtons[1] != 0)
  62159. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62160. const Rectangle<int> titleBarArea (getTitleBarArea());
  62161. getLookAndFeel()
  62162. .positionDocumentWindowButtons (*this,
  62163. titleBarArea.getX(), titleBarArea.getY(),
  62164. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62165. titleBarButtons[0],
  62166. titleBarButtons[1],
  62167. titleBarButtons[2],
  62168. positionTitleBarButtonsOnLeft);
  62169. if (menuBar != 0)
  62170. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62171. titleBarArea.getWidth(), menuBarHeight);
  62172. }
  62173. const BorderSize DocumentWindow::getBorderThickness()
  62174. {
  62175. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62176. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62177. }
  62178. const BorderSize DocumentWindow::getContentComponentBorder()
  62179. {
  62180. BorderSize border (getBorderThickness());
  62181. border.setTop (border.getTop()
  62182. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62183. + (menuBar != 0 ? menuBarHeight : 0));
  62184. return border;
  62185. }
  62186. int DocumentWindow::getTitleBarHeight() const
  62187. {
  62188. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62189. }
  62190. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62191. {
  62192. const BorderSize border (getBorderThickness());
  62193. return Rectangle<int> (border.getLeft(), border.getTop(),
  62194. getWidth() - border.getLeftAndRight(),
  62195. getTitleBarHeight());
  62196. }
  62197. Button* DocumentWindow::getCloseButton() const throw()
  62198. {
  62199. return titleBarButtons[2];
  62200. }
  62201. Button* DocumentWindow::getMinimiseButton() const throw()
  62202. {
  62203. return titleBarButtons[0];
  62204. }
  62205. Button* DocumentWindow::getMaximiseButton() const throw()
  62206. {
  62207. return titleBarButtons[1];
  62208. }
  62209. int DocumentWindow::getDesktopWindowStyleFlags() const
  62210. {
  62211. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62212. if ((requiredButtons & minimiseButton) != 0)
  62213. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62214. if ((requiredButtons & maximiseButton) != 0)
  62215. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62216. if ((requiredButtons & closeButton) != 0)
  62217. styleFlags |= ComponentPeer::windowHasCloseButton;
  62218. return styleFlags;
  62219. }
  62220. void DocumentWindow::lookAndFeelChanged()
  62221. {
  62222. int i;
  62223. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62224. titleBarButtons[i] = 0;
  62225. if (! isUsingNativeTitleBar())
  62226. {
  62227. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62228. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62229. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62230. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62231. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62232. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62233. for (i = 0; i < 3; ++i)
  62234. {
  62235. if (titleBarButtons[i] != 0)
  62236. {
  62237. if (buttonListener == 0)
  62238. buttonListener = new ButtonListenerProxy (*this);
  62239. titleBarButtons[i]->addButtonListener (buttonListener);
  62240. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62241. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62242. Component::addAndMakeVisible (titleBarButtons[i]);
  62243. }
  62244. }
  62245. if (getCloseButton() != 0)
  62246. {
  62247. #if JUCE_MAC
  62248. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62249. #else
  62250. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62251. #endif
  62252. }
  62253. }
  62254. activeWindowStatusChanged();
  62255. ResizableWindow::lookAndFeelChanged();
  62256. }
  62257. void DocumentWindow::parentHierarchyChanged()
  62258. {
  62259. lookAndFeelChanged();
  62260. }
  62261. void DocumentWindow::activeWindowStatusChanged()
  62262. {
  62263. ResizableWindow::activeWindowStatusChanged();
  62264. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62265. if (titleBarButtons[i] != 0)
  62266. titleBarButtons[i]->setEnabled (isActiveWindow());
  62267. if (menuBar != 0)
  62268. menuBar->setEnabled (isActiveWindow());
  62269. }
  62270. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62271. {
  62272. if (getTitleBarArea().contains (e.x, e.y)
  62273. && getMaximiseButton() != 0)
  62274. {
  62275. getMaximiseButton()->triggerClick();
  62276. }
  62277. }
  62278. void DocumentWindow::userTriedToCloseWindow()
  62279. {
  62280. closeButtonPressed();
  62281. }
  62282. END_JUCE_NAMESPACE
  62283. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62284. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62285. BEGIN_JUCE_NAMESPACE
  62286. ResizableWindow::ResizableWindow (const String& name,
  62287. const bool addToDesktop_)
  62288. : TopLevelWindow (name, addToDesktop_),
  62289. resizeToFitContent (false),
  62290. fullscreen (false),
  62291. lastNonFullScreenPos (50, 50, 256, 256),
  62292. constrainer (0)
  62293. #if JUCE_DEBUG
  62294. , hasBeenResized (false)
  62295. #endif
  62296. {
  62297. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62298. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62299. if (addToDesktop_)
  62300. Component::addToDesktop (getDesktopWindowStyleFlags());
  62301. }
  62302. ResizableWindow::ResizableWindow (const String& name,
  62303. const Colour& backgroundColour_,
  62304. const bool addToDesktop_)
  62305. : TopLevelWindow (name, addToDesktop_),
  62306. resizeToFitContent (false),
  62307. fullscreen (false),
  62308. lastNonFullScreenPos (50, 50, 256, 256),
  62309. constrainer (0)
  62310. #if JUCE_DEBUG
  62311. , hasBeenResized (false)
  62312. #endif
  62313. {
  62314. setBackgroundColour (backgroundColour_);
  62315. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62316. if (addToDesktop_)
  62317. Component::addToDesktop (getDesktopWindowStyleFlags());
  62318. }
  62319. ResizableWindow::~ResizableWindow()
  62320. {
  62321. resizableCorner = 0;
  62322. resizableBorder = 0;
  62323. contentComponent = 0;
  62324. // have you been adding your own components directly to this window..? tut tut tut.
  62325. // Read the instructions for using a ResizableWindow!
  62326. jassert (getNumChildComponents() == 0);
  62327. }
  62328. int ResizableWindow::getDesktopWindowStyleFlags() const
  62329. {
  62330. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62331. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62332. styleFlags |= ComponentPeer::windowIsResizable;
  62333. return styleFlags;
  62334. }
  62335. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62336. const bool deleteOldOne,
  62337. const bool resizeToFit)
  62338. {
  62339. resizeToFitContent = resizeToFit;
  62340. if (newContentComponent != static_cast <Component*> (contentComponent))
  62341. {
  62342. if (! deleteOldOne)
  62343. removeChildComponent (contentComponent.release());
  62344. contentComponent = newContentComponent;
  62345. Component::addAndMakeVisible (contentComponent);
  62346. }
  62347. if (resizeToFit)
  62348. childBoundsChanged (contentComponent);
  62349. resized(); // must always be called to position the new content comp
  62350. }
  62351. void ResizableWindow::setContentComponentSize (int width, int height)
  62352. {
  62353. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62354. const BorderSize border (getContentComponentBorder());
  62355. setSize (width + border.getLeftAndRight(),
  62356. height + border.getTopAndBottom());
  62357. }
  62358. const BorderSize ResizableWindow::getBorderThickness()
  62359. {
  62360. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62361. }
  62362. const BorderSize ResizableWindow::getContentComponentBorder()
  62363. {
  62364. return getBorderThickness();
  62365. }
  62366. void ResizableWindow::moved()
  62367. {
  62368. updateLastPos();
  62369. }
  62370. void ResizableWindow::visibilityChanged()
  62371. {
  62372. TopLevelWindow::visibilityChanged();
  62373. updateLastPos();
  62374. }
  62375. void ResizableWindow::resized()
  62376. {
  62377. if (resizableBorder != 0)
  62378. {
  62379. resizableBorder->setVisible (! isFullScreen());
  62380. resizableBorder->setBorderThickness (getBorderThickness());
  62381. resizableBorder->setSize (getWidth(), getHeight());
  62382. resizableBorder->toBack();
  62383. }
  62384. if (resizableCorner != 0)
  62385. {
  62386. resizableCorner->setVisible (! isFullScreen());
  62387. const int resizerSize = 18;
  62388. resizableCorner->setBounds (getWidth() - resizerSize,
  62389. getHeight() - resizerSize,
  62390. resizerSize, resizerSize);
  62391. }
  62392. if (contentComponent != 0)
  62393. contentComponent->setBoundsInset (getContentComponentBorder());
  62394. updateLastPos();
  62395. #if JUCE_DEBUG
  62396. hasBeenResized = true;
  62397. #endif
  62398. }
  62399. void ResizableWindow::childBoundsChanged (Component* child)
  62400. {
  62401. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62402. {
  62403. // not going to look very good if this component has a zero size..
  62404. jassert (child->getWidth() > 0);
  62405. jassert (child->getHeight() > 0);
  62406. const BorderSize borders (getContentComponentBorder());
  62407. setSize (child->getWidth() + borders.getLeftAndRight(),
  62408. child->getHeight() + borders.getTopAndBottom());
  62409. }
  62410. }
  62411. void ResizableWindow::activeWindowStatusChanged()
  62412. {
  62413. const BorderSize borders (getContentComponentBorder());
  62414. repaint (0, 0, getWidth(), borders.getTop());
  62415. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  62416. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  62417. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  62418. }
  62419. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62420. const bool useBottomRightCornerResizer)
  62421. {
  62422. if (shouldBeResizable)
  62423. {
  62424. if (useBottomRightCornerResizer)
  62425. {
  62426. resizableBorder = 0;
  62427. if (resizableCorner == 0)
  62428. {
  62429. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62430. resizableCorner->setAlwaysOnTop (true);
  62431. }
  62432. }
  62433. else
  62434. {
  62435. resizableCorner = 0;
  62436. if (resizableBorder == 0)
  62437. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62438. }
  62439. }
  62440. else
  62441. {
  62442. resizableCorner = 0;
  62443. resizableBorder = 0;
  62444. }
  62445. if (isUsingNativeTitleBar())
  62446. recreateDesktopWindow();
  62447. childBoundsChanged (contentComponent);
  62448. resized();
  62449. }
  62450. bool ResizableWindow::isResizable() const throw()
  62451. {
  62452. return resizableCorner != 0
  62453. || resizableBorder != 0;
  62454. }
  62455. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62456. const int newMinimumHeight,
  62457. const int newMaximumWidth,
  62458. const int newMaximumHeight) throw()
  62459. {
  62460. // if you've set up a custom constrainer then these settings won't have any effect..
  62461. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62462. if (constrainer == 0)
  62463. setConstrainer (&defaultConstrainer);
  62464. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62465. newMaximumWidth, newMaximumHeight);
  62466. setBoundsConstrained (getBounds());
  62467. }
  62468. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62469. {
  62470. if (constrainer != newConstrainer)
  62471. {
  62472. constrainer = newConstrainer;
  62473. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62474. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62475. resizableCorner = 0;
  62476. resizableBorder = 0;
  62477. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62478. ComponentPeer* const peer = getPeer();
  62479. if (peer != 0)
  62480. peer->setConstrainer (newConstrainer);
  62481. }
  62482. }
  62483. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62484. {
  62485. if (constrainer != 0)
  62486. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62487. else
  62488. setBounds (bounds);
  62489. }
  62490. void ResizableWindow::paint (Graphics& g)
  62491. {
  62492. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62493. getBorderThickness(), *this);
  62494. if (! isFullScreen())
  62495. {
  62496. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62497. getBorderThickness(), *this);
  62498. }
  62499. #if JUCE_DEBUG
  62500. /* If this fails, then you've probably written a subclass with a resized()
  62501. callback but forgotten to make it call its parent class's resized() method.
  62502. It's important when you override methods like resized(), moved(),
  62503. etc., that you make sure the base class methods also get called.
  62504. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62505. because your content should all be inside the content component - and it's the
  62506. content component's resized() method that you should be using to do your
  62507. layout.
  62508. */
  62509. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62510. #endif
  62511. }
  62512. void ResizableWindow::lookAndFeelChanged()
  62513. {
  62514. resized();
  62515. if (isOnDesktop())
  62516. {
  62517. Component::addToDesktop (getDesktopWindowStyleFlags());
  62518. ComponentPeer* const peer = getPeer();
  62519. if (peer != 0)
  62520. peer->setConstrainer (constrainer);
  62521. }
  62522. }
  62523. const Colour ResizableWindow::getBackgroundColour() const throw()
  62524. {
  62525. return findColour (backgroundColourId, false);
  62526. }
  62527. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62528. {
  62529. Colour backgroundColour (newColour);
  62530. if (! Desktop::canUseSemiTransparentWindows())
  62531. backgroundColour = newColour.withAlpha (1.0f);
  62532. setColour (backgroundColourId, backgroundColour);
  62533. setOpaque (backgroundColour.isOpaque());
  62534. repaint();
  62535. }
  62536. bool ResizableWindow::isFullScreen() const
  62537. {
  62538. if (isOnDesktop())
  62539. {
  62540. ComponentPeer* const peer = getPeer();
  62541. return peer != 0 && peer->isFullScreen();
  62542. }
  62543. return fullscreen;
  62544. }
  62545. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62546. {
  62547. if (shouldBeFullScreen != isFullScreen())
  62548. {
  62549. updateLastPos();
  62550. fullscreen = shouldBeFullScreen;
  62551. if (isOnDesktop())
  62552. {
  62553. ComponentPeer* const peer = getPeer();
  62554. if (peer != 0)
  62555. {
  62556. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62557. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62558. peer->setFullScreen (shouldBeFullScreen);
  62559. if (! shouldBeFullScreen)
  62560. setBounds (lastPos);
  62561. }
  62562. else
  62563. {
  62564. jassertfalse;
  62565. }
  62566. }
  62567. else
  62568. {
  62569. if (shouldBeFullScreen)
  62570. setBounds (0, 0, getParentWidth(), getParentHeight());
  62571. else
  62572. setBounds (lastNonFullScreenPos);
  62573. }
  62574. resized();
  62575. }
  62576. }
  62577. bool ResizableWindow::isMinimised() const
  62578. {
  62579. ComponentPeer* const peer = getPeer();
  62580. return (peer != 0) && peer->isMinimised();
  62581. }
  62582. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62583. {
  62584. if (shouldMinimise != isMinimised())
  62585. {
  62586. ComponentPeer* const peer = getPeer();
  62587. if (peer != 0)
  62588. {
  62589. updateLastPos();
  62590. peer->setMinimised (shouldMinimise);
  62591. }
  62592. else
  62593. {
  62594. jassertfalse;
  62595. }
  62596. }
  62597. }
  62598. void ResizableWindow::updateLastPos()
  62599. {
  62600. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62601. {
  62602. lastNonFullScreenPos = getBounds();
  62603. }
  62604. }
  62605. void ResizableWindow::parentSizeChanged()
  62606. {
  62607. if (isFullScreen() && getParentComponent() != 0)
  62608. {
  62609. setBounds (0, 0, getParentWidth(), getParentHeight());
  62610. }
  62611. }
  62612. const String ResizableWindow::getWindowStateAsString()
  62613. {
  62614. updateLastPos();
  62615. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62616. }
  62617. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62618. {
  62619. StringArray tokens;
  62620. tokens.addTokens (s, false);
  62621. tokens.removeEmptyStrings();
  62622. tokens.trim();
  62623. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62624. const int firstCoord = fs ? 1 : 0;
  62625. if (tokens.size() != firstCoord + 4)
  62626. return false;
  62627. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62628. tokens[firstCoord + 1].getIntValue(),
  62629. tokens[firstCoord + 2].getIntValue(),
  62630. tokens[firstCoord + 3].getIntValue());
  62631. if (newPos.isEmpty())
  62632. return false;
  62633. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62634. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62635. if (peer != 0)
  62636. peer->getFrameSize().addTo (newPos);
  62637. if (! screen.contains (newPos))
  62638. {
  62639. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62640. jmin (newPos.getHeight(), screen.getHeight()));
  62641. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62642. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62643. }
  62644. if (peer != 0)
  62645. {
  62646. peer->getFrameSize().subtractFrom (newPos);
  62647. peer->setNonFullScreenBounds (newPos);
  62648. }
  62649. lastNonFullScreenPos = newPos;
  62650. setFullScreen (fs);
  62651. if (! fs)
  62652. setBoundsConstrained (newPos);
  62653. return true;
  62654. }
  62655. void ResizableWindow::mouseDown (const MouseEvent&)
  62656. {
  62657. if (! isFullScreen())
  62658. dragger.startDraggingComponent (this, constrainer);
  62659. }
  62660. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62661. {
  62662. if (! isFullScreen())
  62663. dragger.dragComponent (this, e);
  62664. }
  62665. #if JUCE_DEBUG
  62666. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62667. {
  62668. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62669. manages its child components automatically, and if you add your own it'll cause
  62670. trouble. Instead, use setContentComponent() to give it a component which
  62671. will be automatically resized and kept in the right place - then you can add
  62672. subcomponents to the content comp. See the notes for the ResizableWindow class
  62673. for more info.
  62674. If you really know what you're doing and want to avoid this assertion, just call
  62675. Component::addChildComponent directly.
  62676. */
  62677. jassertfalse;
  62678. Component::addChildComponent (child, zOrder);
  62679. }
  62680. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  62681. {
  62682. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62683. manages its child components automatically, and if you add your own it'll cause
  62684. trouble. Instead, use setContentComponent() to give it a component which
  62685. will be automatically resized and kept in the right place - then you can add
  62686. subcomponents to the content comp. See the notes for the ResizableWindow class
  62687. for more info.
  62688. If you really know what you're doing and want to avoid this assertion, just call
  62689. Component::addAndMakeVisible directly.
  62690. */
  62691. jassertfalse;
  62692. Component::addAndMakeVisible (child, zOrder);
  62693. }
  62694. #endif
  62695. END_JUCE_NAMESPACE
  62696. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  62697. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  62698. BEGIN_JUCE_NAMESPACE
  62699. SplashScreen::SplashScreen()
  62700. {
  62701. setOpaque (true);
  62702. }
  62703. SplashScreen::~SplashScreen()
  62704. {
  62705. }
  62706. void SplashScreen::show (const String& title,
  62707. const Image& backgroundImage_,
  62708. const int minimumTimeToDisplayFor,
  62709. const bool useDropShadow,
  62710. const bool removeOnMouseClick)
  62711. {
  62712. backgroundImage = backgroundImage_;
  62713. jassert (backgroundImage_.isValid());
  62714. if (backgroundImage_.isValid())
  62715. {
  62716. setOpaque (! backgroundImage_.hasAlphaChannel());
  62717. show (title,
  62718. backgroundImage_.getWidth(),
  62719. backgroundImage_.getHeight(),
  62720. minimumTimeToDisplayFor,
  62721. useDropShadow,
  62722. removeOnMouseClick);
  62723. }
  62724. }
  62725. void SplashScreen::show (const String& title,
  62726. const int width,
  62727. const int height,
  62728. const int minimumTimeToDisplayFor,
  62729. const bool useDropShadow,
  62730. const bool removeOnMouseClick)
  62731. {
  62732. setName (title);
  62733. setAlwaysOnTop (true);
  62734. setVisible (true);
  62735. centreWithSize (width, height);
  62736. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  62737. toFront (false);
  62738. MessageManager::getInstance()->runDispatchLoopUntil (300);
  62739. repaint();
  62740. originalClickCounter = removeOnMouseClick
  62741. ? Desktop::getMouseButtonClickCounter()
  62742. : std::numeric_limits<int>::max();
  62743. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  62744. startTimer (50);
  62745. }
  62746. void SplashScreen::paint (Graphics& g)
  62747. {
  62748. g.setOpacity (1.0f);
  62749. g.drawImage (backgroundImage,
  62750. 0, 0, getWidth(), getHeight(),
  62751. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  62752. }
  62753. void SplashScreen::timerCallback()
  62754. {
  62755. if (Time::getCurrentTime() > earliestTimeToDelete
  62756. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  62757. {
  62758. delete this;
  62759. }
  62760. }
  62761. END_JUCE_NAMESPACE
  62762. /*** End of inlined file: juce_SplashScreen.cpp ***/
  62763. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62764. BEGIN_JUCE_NAMESPACE
  62765. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  62766. const bool hasProgressBar,
  62767. const bool hasCancelButton,
  62768. const int timeOutMsWhenCancelling_,
  62769. const String& cancelButtonText)
  62770. : Thread ("Juce Progress Window"),
  62771. progress (0.0),
  62772. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  62773. {
  62774. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  62775. .createAlertWindow (title, String::empty, cancelButtonText,
  62776. String::empty, String::empty,
  62777. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  62778. if (hasProgressBar)
  62779. alertWindow->addProgressBarComponent (progress);
  62780. }
  62781. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  62782. {
  62783. stopThread (timeOutMsWhenCancelling);
  62784. }
  62785. bool ThreadWithProgressWindow::runThread (const int priority)
  62786. {
  62787. startThread (priority);
  62788. startTimer (100);
  62789. {
  62790. const ScopedLock sl (messageLock);
  62791. alertWindow->setMessage (message);
  62792. }
  62793. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  62794. stopThread (timeOutMsWhenCancelling);
  62795. alertWindow->setVisible (false);
  62796. return finishedNaturally;
  62797. }
  62798. void ThreadWithProgressWindow::setProgress (const double newProgress)
  62799. {
  62800. progress = newProgress;
  62801. }
  62802. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  62803. {
  62804. const ScopedLock sl (messageLock);
  62805. message = newStatusMessage;
  62806. }
  62807. void ThreadWithProgressWindow::timerCallback()
  62808. {
  62809. if (! isThreadRunning())
  62810. {
  62811. // thread has finished normally..
  62812. alertWindow->exitModalState (1);
  62813. alertWindow->setVisible (false);
  62814. }
  62815. else
  62816. {
  62817. const ScopedLock sl (messageLock);
  62818. alertWindow->setMessage (message);
  62819. }
  62820. }
  62821. END_JUCE_NAMESPACE
  62822. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62823. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  62824. BEGIN_JUCE_NAMESPACE
  62825. TooltipWindow::TooltipWindow (Component* const parentComponent,
  62826. const int millisecondsBeforeTipAppears_)
  62827. : Component ("tooltip"),
  62828. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  62829. mouseClicks (0),
  62830. lastHideTime (0),
  62831. lastComponentUnderMouse (0),
  62832. changedCompsSinceShown (true)
  62833. {
  62834. if (Desktop::getInstance().getMainMouseSource().canHover())
  62835. startTimer (123);
  62836. setAlwaysOnTop (true);
  62837. setOpaque (true);
  62838. if (parentComponent != 0)
  62839. parentComponent->addChildComponent (this);
  62840. }
  62841. TooltipWindow::~TooltipWindow()
  62842. {
  62843. hide();
  62844. }
  62845. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  62846. {
  62847. millisecondsBeforeTipAppears = newTimeMs;
  62848. }
  62849. void TooltipWindow::paint (Graphics& g)
  62850. {
  62851. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  62852. }
  62853. void TooltipWindow::mouseEnter (const MouseEvent&)
  62854. {
  62855. hide();
  62856. }
  62857. void TooltipWindow::showFor (const String& tip)
  62858. {
  62859. jassert (tip.isNotEmpty());
  62860. tipShowing = tip;
  62861. Point<int> mousePos (Desktop::getMousePosition());
  62862. if (getParentComponent() != 0)
  62863. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  62864. int x, y, w, h;
  62865. getLookAndFeel().getTooltipSize (tip, w, h);
  62866. if (mousePos.getX() > getParentWidth() / 2)
  62867. x = mousePos.getX() - (w + 12);
  62868. else
  62869. x = mousePos.getX() + 24;
  62870. if (mousePos.getY() > getParentHeight() / 2)
  62871. y = mousePos.getY() - (h + 6);
  62872. else
  62873. y = mousePos.getY() + 6;
  62874. setBounds (x, y, w, h);
  62875. setVisible (true);
  62876. if (getParentComponent() == 0)
  62877. {
  62878. addToDesktop (ComponentPeer::windowHasDropShadow
  62879. | ComponentPeer::windowIsTemporary
  62880. | ComponentPeer::windowIgnoresKeyPresses);
  62881. }
  62882. toFront (false);
  62883. }
  62884. const String TooltipWindow::getTipFor (Component* const c)
  62885. {
  62886. if (c != 0
  62887. && Process::isForegroundProcess()
  62888. && ! Component::isMouseButtonDownAnywhere())
  62889. {
  62890. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  62891. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  62892. return ttc->getTooltip();
  62893. }
  62894. return String::empty;
  62895. }
  62896. void TooltipWindow::hide()
  62897. {
  62898. tipShowing = String::empty;
  62899. removeFromDesktop();
  62900. setVisible (false);
  62901. }
  62902. void TooltipWindow::timerCallback()
  62903. {
  62904. const unsigned int now = Time::getApproximateMillisecondCounter();
  62905. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62906. const String newTip (getTipFor (newComp));
  62907. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  62908. lastComponentUnderMouse = newComp;
  62909. lastTipUnderMouse = newTip;
  62910. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  62911. const bool mouseWasClicked = clickCount > mouseClicks;
  62912. mouseClicks = clickCount;
  62913. const Point<int> mousePos (Desktop::getMousePosition());
  62914. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  62915. lastMousePos = mousePos;
  62916. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  62917. lastCompChangeTime = now;
  62918. if (isVisible() || now < lastHideTime + 500)
  62919. {
  62920. // if a tip is currently visible (or has just disappeared), update to a new one
  62921. // immediately if needed..
  62922. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  62923. {
  62924. if (isVisible())
  62925. {
  62926. lastHideTime = now;
  62927. hide();
  62928. }
  62929. }
  62930. else if (tipChanged)
  62931. {
  62932. showFor (newTip);
  62933. }
  62934. }
  62935. else
  62936. {
  62937. // if there isn't currently a tip, but one is needed, only let it
  62938. // appear after a timeout..
  62939. if (newTip.isNotEmpty()
  62940. && newTip != tipShowing
  62941. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  62942. {
  62943. showFor (newTip);
  62944. }
  62945. }
  62946. }
  62947. END_JUCE_NAMESPACE
  62948. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  62949. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  62950. BEGIN_JUCE_NAMESPACE
  62951. /** Keeps track of the active top level window.
  62952. */
  62953. class TopLevelWindowManager : public Timer,
  62954. public DeletedAtShutdown
  62955. {
  62956. public:
  62957. TopLevelWindowManager()
  62958. : currentActive (0)
  62959. {
  62960. }
  62961. ~TopLevelWindowManager()
  62962. {
  62963. clearSingletonInstance();
  62964. }
  62965. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  62966. void timerCallback()
  62967. {
  62968. startTimer (jmin (1731, getTimerInterval() * 2));
  62969. TopLevelWindow* active = 0;
  62970. if (Process::isForegroundProcess())
  62971. {
  62972. active = currentActive;
  62973. Component* const c = Component::getCurrentlyFocusedComponent();
  62974. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  62975. if (tlw == 0 && c != 0)
  62976. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  62977. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  62978. if (tlw != 0)
  62979. active = tlw;
  62980. }
  62981. if (active != currentActive)
  62982. {
  62983. currentActive = active;
  62984. for (int i = windows.size(); --i >= 0;)
  62985. {
  62986. TopLevelWindow* const tlw = windows.getUnchecked (i);
  62987. tlw->setWindowActive (isWindowActive (tlw));
  62988. i = jmin (i, windows.size() - 1);
  62989. }
  62990. Desktop::getInstance().triggerFocusCallback();
  62991. }
  62992. }
  62993. bool addWindow (TopLevelWindow* const w)
  62994. {
  62995. windows.add (w);
  62996. startTimer (10);
  62997. return isWindowActive (w);
  62998. }
  62999. void removeWindow (TopLevelWindow* const w)
  63000. {
  63001. startTimer (10);
  63002. if (currentActive == w)
  63003. currentActive = 0;
  63004. windows.removeValue (w);
  63005. if (windows.size() == 0)
  63006. deleteInstance();
  63007. }
  63008. Array <TopLevelWindow*> windows;
  63009. private:
  63010. TopLevelWindow* currentActive;
  63011. bool isWindowActive (TopLevelWindow* const tlw) const
  63012. {
  63013. return (tlw == currentActive
  63014. || tlw->isParentOf (currentActive)
  63015. || tlw->hasKeyboardFocus (true))
  63016. && tlw->isShowing();
  63017. }
  63018. TopLevelWindowManager (const TopLevelWindowManager&);
  63019. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  63020. };
  63021. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63022. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63023. {
  63024. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63025. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63026. }
  63027. TopLevelWindow::TopLevelWindow (const String& name,
  63028. const bool addToDesktop_)
  63029. : Component (name),
  63030. useDropShadow (true),
  63031. useNativeTitleBar (false),
  63032. windowIsActive_ (false)
  63033. {
  63034. setOpaque (true);
  63035. if (addToDesktop_)
  63036. Component::addToDesktop (getDesktopWindowStyleFlags());
  63037. else
  63038. setDropShadowEnabled (true);
  63039. setWantsKeyboardFocus (true);
  63040. setBroughtToFrontOnMouseClick (true);
  63041. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63042. }
  63043. TopLevelWindow::~TopLevelWindow()
  63044. {
  63045. shadower = 0;
  63046. TopLevelWindowManager::getInstance()->removeWindow (this);
  63047. }
  63048. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63049. {
  63050. if (hasKeyboardFocus (true))
  63051. TopLevelWindowManager::getInstance()->timerCallback();
  63052. else
  63053. TopLevelWindowManager::getInstance()->startTimer (10);
  63054. }
  63055. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63056. {
  63057. if (windowIsActive_ != isNowActive)
  63058. {
  63059. windowIsActive_ = isNowActive;
  63060. activeWindowStatusChanged();
  63061. }
  63062. }
  63063. void TopLevelWindow::activeWindowStatusChanged()
  63064. {
  63065. }
  63066. void TopLevelWindow::parentHierarchyChanged()
  63067. {
  63068. setDropShadowEnabled (useDropShadow);
  63069. }
  63070. void TopLevelWindow::visibilityChanged()
  63071. {
  63072. if (isShowing())
  63073. toFront (true);
  63074. }
  63075. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63076. {
  63077. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63078. if (useDropShadow)
  63079. styleFlags |= ComponentPeer::windowHasDropShadow;
  63080. if (useNativeTitleBar)
  63081. styleFlags |= ComponentPeer::windowHasTitleBar;
  63082. return styleFlags;
  63083. }
  63084. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63085. {
  63086. useDropShadow = useShadow;
  63087. if (isOnDesktop())
  63088. {
  63089. shadower = 0;
  63090. Component::addToDesktop (getDesktopWindowStyleFlags());
  63091. }
  63092. else
  63093. {
  63094. if (useShadow && isOpaque())
  63095. {
  63096. if (shadower == 0)
  63097. {
  63098. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63099. if (shadower != 0)
  63100. shadower->setOwner (this);
  63101. }
  63102. }
  63103. else
  63104. {
  63105. shadower = 0;
  63106. }
  63107. }
  63108. }
  63109. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63110. {
  63111. if (useNativeTitleBar != useNativeTitleBar_)
  63112. {
  63113. useNativeTitleBar = useNativeTitleBar_;
  63114. recreateDesktopWindow();
  63115. sendLookAndFeelChange();
  63116. }
  63117. }
  63118. void TopLevelWindow::recreateDesktopWindow()
  63119. {
  63120. if (isOnDesktop())
  63121. {
  63122. Component::addToDesktop (getDesktopWindowStyleFlags());
  63123. toFront (true);
  63124. }
  63125. }
  63126. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63127. {
  63128. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63129. because this class needs to make sure its layout corresponds with settings like whether
  63130. it's got a native title bar or not.
  63131. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63132. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63133. method, then add or remove whatever flags are necessary from this value before returning it.
  63134. */
  63135. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63136. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63137. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63138. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63139. sendLookAndFeelChange();
  63140. }
  63141. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63142. {
  63143. if (c == 0)
  63144. c = TopLevelWindow::getActiveTopLevelWindow();
  63145. if (c == 0)
  63146. {
  63147. centreWithSize (width, height);
  63148. }
  63149. else
  63150. {
  63151. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63152. (c->getHeight() - height) / 2)));
  63153. Rectangle<int> parentArea (c->getParentMonitorArea());
  63154. if (getParentComponent() != 0)
  63155. {
  63156. p = getParentComponent()->globalPositionToRelative (p);
  63157. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63158. }
  63159. parentArea.reduce (12, 12);
  63160. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63161. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63162. width, height);
  63163. }
  63164. }
  63165. int TopLevelWindow::getNumTopLevelWindows() throw()
  63166. {
  63167. return TopLevelWindowManager::getInstance()->windows.size();
  63168. }
  63169. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63170. {
  63171. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63172. }
  63173. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63174. {
  63175. TopLevelWindow* best = 0;
  63176. int bestNumTWLParents = -1;
  63177. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63178. {
  63179. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63180. if (tlw->isActiveWindow())
  63181. {
  63182. int numTWLParents = 0;
  63183. const Component* c = tlw->getParentComponent();
  63184. while (c != 0)
  63185. {
  63186. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63187. ++numTWLParents;
  63188. c = c->getParentComponent();
  63189. }
  63190. if (bestNumTWLParents < numTWLParents)
  63191. {
  63192. best = tlw;
  63193. bestNumTWLParents = numTWLParents;
  63194. }
  63195. }
  63196. }
  63197. return best;
  63198. }
  63199. END_JUCE_NAMESPACE
  63200. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63201. #endif
  63202. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  63203. /*** Start of inlined file: juce_Colour.cpp ***/
  63204. BEGIN_JUCE_NAMESPACE
  63205. namespace ColourHelpers
  63206. {
  63207. static uint8 floatAlphaToInt (const float alpha) throw()
  63208. {
  63209. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  63210. }
  63211. static void convertHSBtoRGB (float h, float s, float v,
  63212. uint8& r, uint8& g, uint8& b) throw()
  63213. {
  63214. v = jlimit (0.0f, 1.0f, v);
  63215. v *= 255.0f;
  63216. const uint8 intV = (uint8) roundToInt (v);
  63217. if (s <= 0)
  63218. {
  63219. r = intV;
  63220. g = intV;
  63221. b = intV;
  63222. }
  63223. else
  63224. {
  63225. s = jmin (1.0f, s);
  63226. h = jlimit (0.0f, 1.0f, h);
  63227. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  63228. const float f = h - std::floor (h);
  63229. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  63230. const float y = v * (1.0f - s * f);
  63231. const float z = v * (1.0f - (s * (1.0f - f)));
  63232. if (h < 1.0f)
  63233. {
  63234. r = intV;
  63235. g = (uint8) roundToInt (z);
  63236. b = x;
  63237. }
  63238. else if (h < 2.0f)
  63239. {
  63240. r = (uint8) roundToInt (y);
  63241. g = intV;
  63242. b = x;
  63243. }
  63244. else if (h < 3.0f)
  63245. {
  63246. r = x;
  63247. g = intV;
  63248. b = (uint8) roundToInt (z);
  63249. }
  63250. else if (h < 4.0f)
  63251. {
  63252. r = x;
  63253. g = (uint8) roundToInt (y);
  63254. b = intV;
  63255. }
  63256. else if (h < 5.0f)
  63257. {
  63258. r = (uint8) roundToInt (z);
  63259. g = x;
  63260. b = intV;
  63261. }
  63262. else if (h < 6.0f)
  63263. {
  63264. r = intV;
  63265. g = x;
  63266. b = (uint8) roundToInt (y);
  63267. }
  63268. else
  63269. {
  63270. r = 0;
  63271. g = 0;
  63272. b = 0;
  63273. }
  63274. }
  63275. }
  63276. }
  63277. Colour::Colour() throw()
  63278. : argb (0)
  63279. {
  63280. }
  63281. Colour::Colour (const Colour& other) throw()
  63282. : argb (other.argb)
  63283. {
  63284. }
  63285. Colour& Colour::operator= (const Colour& other) throw()
  63286. {
  63287. argb = other.argb;
  63288. return *this;
  63289. }
  63290. bool Colour::operator== (const Colour& other) const throw()
  63291. {
  63292. return argb.getARGB() == other.argb.getARGB();
  63293. }
  63294. bool Colour::operator!= (const Colour& other) const throw()
  63295. {
  63296. return argb.getARGB() != other.argb.getARGB();
  63297. }
  63298. Colour::Colour (const uint32 argb_) throw()
  63299. : argb (argb_)
  63300. {
  63301. }
  63302. Colour::Colour (const uint8 red,
  63303. const uint8 green,
  63304. const uint8 blue) throw()
  63305. {
  63306. argb.setARGB (0xff, red, green, blue);
  63307. }
  63308. const Colour Colour::fromRGB (const uint8 red,
  63309. const uint8 green,
  63310. const uint8 blue) throw()
  63311. {
  63312. return Colour (red, green, blue);
  63313. }
  63314. Colour::Colour (const uint8 red,
  63315. const uint8 green,
  63316. const uint8 blue,
  63317. const uint8 alpha) throw()
  63318. {
  63319. argb.setARGB (alpha, red, green, blue);
  63320. }
  63321. const Colour Colour::fromRGBA (const uint8 red,
  63322. const uint8 green,
  63323. const uint8 blue,
  63324. const uint8 alpha) throw()
  63325. {
  63326. return Colour (red, green, blue, alpha);
  63327. }
  63328. Colour::Colour (const uint8 red,
  63329. const uint8 green,
  63330. const uint8 blue,
  63331. const float alpha) throw()
  63332. {
  63333. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  63334. }
  63335. const Colour Colour::fromRGBAFloat (const uint8 red,
  63336. const uint8 green,
  63337. const uint8 blue,
  63338. const float alpha) throw()
  63339. {
  63340. return Colour (red, green, blue, alpha);
  63341. }
  63342. Colour::Colour (const float hue,
  63343. const float saturation,
  63344. const float brightness,
  63345. const float alpha) throw()
  63346. {
  63347. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63348. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63349. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  63350. }
  63351. const Colour Colour::fromHSV (const float hue,
  63352. const float saturation,
  63353. const float brightness,
  63354. const float alpha) throw()
  63355. {
  63356. return Colour (hue, saturation, brightness, alpha);
  63357. }
  63358. Colour::Colour (const float hue,
  63359. const float saturation,
  63360. const float brightness,
  63361. const uint8 alpha) throw()
  63362. {
  63363. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63364. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63365. argb.setARGB (alpha, r, g, b);
  63366. }
  63367. Colour::~Colour() throw()
  63368. {
  63369. }
  63370. const PixelARGB Colour::getPixelARGB() const throw()
  63371. {
  63372. PixelARGB p (argb);
  63373. p.premultiply();
  63374. return p;
  63375. }
  63376. uint32 Colour::getARGB() const throw()
  63377. {
  63378. return argb.getARGB();
  63379. }
  63380. bool Colour::isTransparent() const throw()
  63381. {
  63382. return getAlpha() == 0;
  63383. }
  63384. bool Colour::isOpaque() const throw()
  63385. {
  63386. return getAlpha() == 0xff;
  63387. }
  63388. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  63389. {
  63390. PixelARGB newCol (argb);
  63391. newCol.setAlpha (newAlpha);
  63392. return Colour (newCol.getARGB());
  63393. }
  63394. const Colour Colour::withAlpha (const float newAlpha) const throw()
  63395. {
  63396. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  63397. PixelARGB newCol (argb);
  63398. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  63399. return Colour (newCol.getARGB());
  63400. }
  63401. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  63402. {
  63403. jassert (alphaMultiplier >= 0);
  63404. PixelARGB newCol (argb);
  63405. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  63406. return Colour (newCol.getARGB());
  63407. }
  63408. const Colour Colour::overlaidWith (const Colour& src) const throw()
  63409. {
  63410. const int destAlpha = getAlpha();
  63411. if (destAlpha > 0)
  63412. {
  63413. const int invA = 0xff - (int) src.getAlpha();
  63414. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  63415. if (resA > 0)
  63416. {
  63417. const int da = (invA * destAlpha) / resA;
  63418. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  63419. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  63420. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  63421. (uint8) resA);
  63422. }
  63423. return *this;
  63424. }
  63425. else
  63426. {
  63427. return src;
  63428. }
  63429. }
  63430. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  63431. {
  63432. if (proportionOfOther <= 0)
  63433. return *this;
  63434. if (proportionOfOther >= 1.0f)
  63435. return other;
  63436. PixelARGB c1 (getPixelARGB());
  63437. const PixelARGB c2 (other.getPixelARGB());
  63438. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  63439. c1.unpremultiply();
  63440. return Colour (c1.getARGB());
  63441. }
  63442. float Colour::getFloatRed() const throw()
  63443. {
  63444. return getRed() / 255.0f;
  63445. }
  63446. float Colour::getFloatGreen() const throw()
  63447. {
  63448. return getGreen() / 255.0f;
  63449. }
  63450. float Colour::getFloatBlue() const throw()
  63451. {
  63452. return getBlue() / 255.0f;
  63453. }
  63454. float Colour::getFloatAlpha() const throw()
  63455. {
  63456. return getAlpha() / 255.0f;
  63457. }
  63458. void Colour::getHSB (float& h, float& s, float& v) const throw()
  63459. {
  63460. const int r = getRed();
  63461. const int g = getGreen();
  63462. const int b = getBlue();
  63463. const int hi = jmax (r, g, b);
  63464. const int lo = jmin (r, g, b);
  63465. if (hi != 0)
  63466. {
  63467. s = (hi - lo) / (float) hi;
  63468. if (s != 0)
  63469. {
  63470. const float invDiff = 1.0f / (hi - lo);
  63471. const float red = (hi - r) * invDiff;
  63472. const float green = (hi - g) * invDiff;
  63473. const float blue = (hi - b) * invDiff;
  63474. if (r == hi)
  63475. h = blue - green;
  63476. else if (g == hi)
  63477. h = 2.0f + red - blue;
  63478. else
  63479. h = 4.0f + green - red;
  63480. h *= 1.0f / 6.0f;
  63481. if (h < 0)
  63482. ++h;
  63483. }
  63484. else
  63485. {
  63486. h = 0;
  63487. }
  63488. }
  63489. else
  63490. {
  63491. s = 0;
  63492. h = 0;
  63493. }
  63494. v = hi / 255.0f;
  63495. }
  63496. float Colour::getHue() const throw()
  63497. {
  63498. float h, s, b;
  63499. getHSB (h, s, b);
  63500. return h;
  63501. }
  63502. const Colour Colour::withHue (const float hue) const throw()
  63503. {
  63504. float h, s, b;
  63505. getHSB (h, s, b);
  63506. return Colour (hue, s, b, getAlpha());
  63507. }
  63508. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  63509. {
  63510. float h, s, b;
  63511. getHSB (h, s, b);
  63512. h += amountToRotate;
  63513. h -= std::floor (h);
  63514. return Colour (h, s, b, getAlpha());
  63515. }
  63516. float Colour::getSaturation() const throw()
  63517. {
  63518. float h, s, b;
  63519. getHSB (h, s, b);
  63520. return s;
  63521. }
  63522. const Colour Colour::withSaturation (const float saturation) const throw()
  63523. {
  63524. float h, s, b;
  63525. getHSB (h, s, b);
  63526. return Colour (h, saturation, b, getAlpha());
  63527. }
  63528. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  63529. {
  63530. float h, s, b;
  63531. getHSB (h, s, b);
  63532. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  63533. }
  63534. float Colour::getBrightness() const throw()
  63535. {
  63536. float h, s, b;
  63537. getHSB (h, s, b);
  63538. return b;
  63539. }
  63540. const Colour Colour::withBrightness (const float brightness) const throw()
  63541. {
  63542. float h, s, b;
  63543. getHSB (h, s, b);
  63544. return Colour (h, s, brightness, getAlpha());
  63545. }
  63546. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  63547. {
  63548. float h, s, b;
  63549. getHSB (h, s, b);
  63550. b *= amount;
  63551. if (b > 1.0f)
  63552. b = 1.0f;
  63553. return Colour (h, s, b, getAlpha());
  63554. }
  63555. const Colour Colour::brighter (float amount) const throw()
  63556. {
  63557. amount = 1.0f / (1.0f + amount);
  63558. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  63559. (uint8) (255 - (amount * (255 - getGreen()))),
  63560. (uint8) (255 - (amount * (255 - getBlue()))),
  63561. getAlpha());
  63562. }
  63563. const Colour Colour::darker (float amount) const throw()
  63564. {
  63565. amount = 1.0f / (1.0f + amount);
  63566. return Colour ((uint8) (amount * getRed()),
  63567. (uint8) (amount * getGreen()),
  63568. (uint8) (amount * getBlue()),
  63569. getAlpha());
  63570. }
  63571. const Colour Colour::greyLevel (const float brightness) throw()
  63572. {
  63573. const uint8 level
  63574. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  63575. return Colour (level, level, level);
  63576. }
  63577. const Colour Colour::contrasting (const float amount) const throw()
  63578. {
  63579. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  63580. ? Colours::black
  63581. : Colours::white).withAlpha (amount));
  63582. }
  63583. const Colour Colour::contrasting (const Colour& colour1,
  63584. const Colour& colour2) throw()
  63585. {
  63586. const float b1 = colour1.getBrightness();
  63587. const float b2 = colour2.getBrightness();
  63588. float best = 0.0f;
  63589. float bestDist = 0.0f;
  63590. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  63591. {
  63592. const float d1 = std::abs (i - b1);
  63593. const float d2 = std::abs (i - b2);
  63594. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  63595. if (dist > bestDist)
  63596. {
  63597. best = i;
  63598. bestDist = dist;
  63599. }
  63600. }
  63601. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  63602. .withBrightness (best);
  63603. }
  63604. const String Colour::toString() const
  63605. {
  63606. return String::toHexString ((int) argb.getARGB());
  63607. }
  63608. const Colour Colour::fromString (const String& encodedColourString)
  63609. {
  63610. return Colour ((uint32) encodedColourString.getHexValue32());
  63611. }
  63612. const String Colour::toDisplayString (const bool includeAlphaValue) const
  63613. {
  63614. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  63615. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  63616. .toUpperCase();
  63617. }
  63618. END_JUCE_NAMESPACE
  63619. /*** End of inlined file: juce_Colour.cpp ***/
  63620. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  63621. BEGIN_JUCE_NAMESPACE
  63622. ColourGradient::ColourGradient() throw()
  63623. {
  63624. #if JUCE_DEBUG
  63625. point1.setX (987654.0f);
  63626. #endif
  63627. }
  63628. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  63629. const Colour& colour2, const float x2_, const float y2_,
  63630. const bool isRadial_)
  63631. : point1 (x1_, y1_),
  63632. point2 (x2_, y2_),
  63633. isRadial (isRadial_)
  63634. {
  63635. colours.add (ColourPoint (0.0, colour1));
  63636. colours.add (ColourPoint (1.0, colour2));
  63637. }
  63638. ColourGradient::~ColourGradient()
  63639. {
  63640. }
  63641. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  63642. {
  63643. return point1 == other.point1 && point2 == other.point2
  63644. && isRadial == other.isRadial
  63645. && colours == other.colours;
  63646. }
  63647. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  63648. {
  63649. return ! operator== (other);
  63650. }
  63651. void ColourGradient::clearColours()
  63652. {
  63653. colours.clear();
  63654. }
  63655. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  63656. {
  63657. // must be within the two end-points
  63658. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  63659. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  63660. int i;
  63661. for (i = 0; i < colours.size(); ++i)
  63662. if (colours.getReference(i).position > pos)
  63663. break;
  63664. colours.insert (i, ColourPoint (pos, colour));
  63665. return i;
  63666. }
  63667. void ColourGradient::removeColour (int index)
  63668. {
  63669. jassert (index > 0 && index < colours.size() - 1);
  63670. colours.remove (index);
  63671. }
  63672. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  63673. {
  63674. for (int i = 0; i < colours.size(); ++i)
  63675. {
  63676. Colour& c = colours.getReference(i).colour;
  63677. c = c.withMultipliedAlpha (multiplier);
  63678. }
  63679. }
  63680. int ColourGradient::getNumColours() const throw()
  63681. {
  63682. return colours.size();
  63683. }
  63684. double ColourGradient::getColourPosition (const int index) const throw()
  63685. {
  63686. if (((unsigned int) index) < (unsigned int) colours.size())
  63687. return colours.getReference (index).position;
  63688. return 0;
  63689. }
  63690. const Colour ColourGradient::getColour (const int index) const throw()
  63691. {
  63692. if (((unsigned int) index) < (unsigned int) colours.size())
  63693. return colours.getReference (index).colour;
  63694. return Colour();
  63695. }
  63696. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  63697. {
  63698. if (((unsigned int) index) < (unsigned int) colours.size())
  63699. colours.getReference (index).colour = newColour;
  63700. }
  63701. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  63702. {
  63703. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  63704. if (position <= 0 || colours.size() <= 1)
  63705. return colours.getReference(0).colour;
  63706. int i = colours.size() - 1;
  63707. while (position < colours.getReference(i).position)
  63708. --i;
  63709. const ColourPoint& p1 = colours.getReference (i);
  63710. if (i >= colours.size() - 1)
  63711. return p1.colour;
  63712. const ColourPoint& p2 = colours.getReference (i + 1);
  63713. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  63714. }
  63715. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  63716. {
  63717. #if JUCE_DEBUG
  63718. // trying to use the object without setting its co-ordinates? Have a careful read of
  63719. // the comments for the constructors.
  63720. jassert (point1.getX() != 987654.0f);
  63721. #endif
  63722. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  63723. 3 * (int) point1.transformedBy (transform)
  63724. .getDistanceFrom (point2.transformedBy (transform)));
  63725. lookupTable.malloc (numEntries);
  63726. if (colours.size() >= 2)
  63727. {
  63728. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  63729. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  63730. int index = 0;
  63731. for (int j = 1; j < colours.size(); ++j)
  63732. {
  63733. const ColourPoint& p = colours.getReference (j);
  63734. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  63735. const PixelARGB pix2 (p.colour.getPixelARGB());
  63736. for (int i = 0; i < numToDo; ++i)
  63737. {
  63738. jassert (index >= 0 && index < numEntries);
  63739. lookupTable[index] = pix1;
  63740. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  63741. ++index;
  63742. }
  63743. pix1 = pix2;
  63744. }
  63745. while (index < numEntries)
  63746. lookupTable [index++] = pix1;
  63747. }
  63748. else
  63749. {
  63750. jassertfalse; // no colours specified!
  63751. }
  63752. return numEntries;
  63753. }
  63754. bool ColourGradient::isOpaque() const throw()
  63755. {
  63756. for (int i = 0; i < colours.size(); ++i)
  63757. if (! colours.getReference(i).colour.isOpaque())
  63758. return false;
  63759. return true;
  63760. }
  63761. bool ColourGradient::isInvisible() const throw()
  63762. {
  63763. for (int i = 0; i < colours.size(); ++i)
  63764. if (! colours.getReference(i).colour.isTransparent())
  63765. return false;
  63766. return true;
  63767. }
  63768. END_JUCE_NAMESPACE
  63769. /*** End of inlined file: juce_ColourGradient.cpp ***/
  63770. /*** Start of inlined file: juce_Colours.cpp ***/
  63771. BEGIN_JUCE_NAMESPACE
  63772. const Colour Colours::transparentBlack (0);
  63773. const Colour Colours::transparentWhite (0x00ffffff);
  63774. const Colour Colours::aliceblue (0xfff0f8ff);
  63775. const Colour Colours::antiquewhite (0xfffaebd7);
  63776. const Colour Colours::aqua (0xff00ffff);
  63777. const Colour Colours::aquamarine (0xff7fffd4);
  63778. const Colour Colours::azure (0xfff0ffff);
  63779. const Colour Colours::beige (0xfff5f5dc);
  63780. const Colour Colours::bisque (0xffffe4c4);
  63781. const Colour Colours::black (0xff000000);
  63782. const Colour Colours::blanchedalmond (0xffffebcd);
  63783. const Colour Colours::blue (0xff0000ff);
  63784. const Colour Colours::blueviolet (0xff8a2be2);
  63785. const Colour Colours::brown (0xffa52a2a);
  63786. const Colour Colours::burlywood (0xffdeb887);
  63787. const Colour Colours::cadetblue (0xff5f9ea0);
  63788. const Colour Colours::chartreuse (0xff7fff00);
  63789. const Colour Colours::chocolate (0xffd2691e);
  63790. const Colour Colours::coral (0xffff7f50);
  63791. const Colour Colours::cornflowerblue (0xff6495ed);
  63792. const Colour Colours::cornsilk (0xfffff8dc);
  63793. const Colour Colours::crimson (0xffdc143c);
  63794. const Colour Colours::cyan (0xff00ffff);
  63795. const Colour Colours::darkblue (0xff00008b);
  63796. const Colour Colours::darkcyan (0xff008b8b);
  63797. const Colour Colours::darkgoldenrod (0xffb8860b);
  63798. const Colour Colours::darkgrey (0xff555555);
  63799. const Colour Colours::darkgreen (0xff006400);
  63800. const Colour Colours::darkkhaki (0xffbdb76b);
  63801. const Colour Colours::darkmagenta (0xff8b008b);
  63802. const Colour Colours::darkolivegreen (0xff556b2f);
  63803. const Colour Colours::darkorange (0xffff8c00);
  63804. const Colour Colours::darkorchid (0xff9932cc);
  63805. const Colour Colours::darkred (0xff8b0000);
  63806. const Colour Colours::darksalmon (0xffe9967a);
  63807. const Colour Colours::darkseagreen (0xff8fbc8f);
  63808. const Colour Colours::darkslateblue (0xff483d8b);
  63809. const Colour Colours::darkslategrey (0xff2f4f4f);
  63810. const Colour Colours::darkturquoise (0xff00ced1);
  63811. const Colour Colours::darkviolet (0xff9400d3);
  63812. const Colour Colours::deeppink (0xffff1493);
  63813. const Colour Colours::deepskyblue (0xff00bfff);
  63814. const Colour Colours::dimgrey (0xff696969);
  63815. const Colour Colours::dodgerblue (0xff1e90ff);
  63816. const Colour Colours::firebrick (0xffb22222);
  63817. const Colour Colours::floralwhite (0xfffffaf0);
  63818. const Colour Colours::forestgreen (0xff228b22);
  63819. const Colour Colours::fuchsia (0xffff00ff);
  63820. const Colour Colours::gainsboro (0xffdcdcdc);
  63821. const Colour Colours::gold (0xffffd700);
  63822. const Colour Colours::goldenrod (0xffdaa520);
  63823. const Colour Colours::grey (0xff808080);
  63824. const Colour Colours::green (0xff008000);
  63825. const Colour Colours::greenyellow (0xffadff2f);
  63826. const Colour Colours::honeydew (0xfff0fff0);
  63827. const Colour Colours::hotpink (0xffff69b4);
  63828. const Colour Colours::indianred (0xffcd5c5c);
  63829. const Colour Colours::indigo (0xff4b0082);
  63830. const Colour Colours::ivory (0xfffffff0);
  63831. const Colour Colours::khaki (0xfff0e68c);
  63832. const Colour Colours::lavender (0xffe6e6fa);
  63833. const Colour Colours::lavenderblush (0xfffff0f5);
  63834. const Colour Colours::lemonchiffon (0xfffffacd);
  63835. const Colour Colours::lightblue (0xffadd8e6);
  63836. const Colour Colours::lightcoral (0xfff08080);
  63837. const Colour Colours::lightcyan (0xffe0ffff);
  63838. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  63839. const Colour Colours::lightgreen (0xff90ee90);
  63840. const Colour Colours::lightgrey (0xffd3d3d3);
  63841. const Colour Colours::lightpink (0xffffb6c1);
  63842. const Colour Colours::lightsalmon (0xffffa07a);
  63843. const Colour Colours::lightseagreen (0xff20b2aa);
  63844. const Colour Colours::lightskyblue (0xff87cefa);
  63845. const Colour Colours::lightslategrey (0xff778899);
  63846. const Colour Colours::lightsteelblue (0xffb0c4de);
  63847. const Colour Colours::lightyellow (0xffffffe0);
  63848. const Colour Colours::lime (0xff00ff00);
  63849. const Colour Colours::limegreen (0xff32cd32);
  63850. const Colour Colours::linen (0xfffaf0e6);
  63851. const Colour Colours::magenta (0xffff00ff);
  63852. const Colour Colours::maroon (0xff800000);
  63853. const Colour Colours::mediumaquamarine (0xff66cdaa);
  63854. const Colour Colours::mediumblue (0xff0000cd);
  63855. const Colour Colours::mediumorchid (0xffba55d3);
  63856. const Colour Colours::mediumpurple (0xff9370db);
  63857. const Colour Colours::mediumseagreen (0xff3cb371);
  63858. const Colour Colours::mediumslateblue (0xff7b68ee);
  63859. const Colour Colours::mediumspringgreen (0xff00fa9a);
  63860. const Colour Colours::mediumturquoise (0xff48d1cc);
  63861. const Colour Colours::mediumvioletred (0xffc71585);
  63862. const Colour Colours::midnightblue (0xff191970);
  63863. const Colour Colours::mintcream (0xfff5fffa);
  63864. const Colour Colours::mistyrose (0xffffe4e1);
  63865. const Colour Colours::navajowhite (0xffffdead);
  63866. const Colour Colours::navy (0xff000080);
  63867. const Colour Colours::oldlace (0xfffdf5e6);
  63868. const Colour Colours::olive (0xff808000);
  63869. const Colour Colours::olivedrab (0xff6b8e23);
  63870. const Colour Colours::orange (0xffffa500);
  63871. const Colour Colours::orangered (0xffff4500);
  63872. const Colour Colours::orchid (0xffda70d6);
  63873. const Colour Colours::palegoldenrod (0xffeee8aa);
  63874. const Colour Colours::palegreen (0xff98fb98);
  63875. const Colour Colours::paleturquoise (0xffafeeee);
  63876. const Colour Colours::palevioletred (0xffdb7093);
  63877. const Colour Colours::papayawhip (0xffffefd5);
  63878. const Colour Colours::peachpuff (0xffffdab9);
  63879. const Colour Colours::peru (0xffcd853f);
  63880. const Colour Colours::pink (0xffffc0cb);
  63881. const Colour Colours::plum (0xffdda0dd);
  63882. const Colour Colours::powderblue (0xffb0e0e6);
  63883. const Colour Colours::purple (0xff800080);
  63884. const Colour Colours::red (0xffff0000);
  63885. const Colour Colours::rosybrown (0xffbc8f8f);
  63886. const Colour Colours::royalblue (0xff4169e1);
  63887. const Colour Colours::saddlebrown (0xff8b4513);
  63888. const Colour Colours::salmon (0xfffa8072);
  63889. const Colour Colours::sandybrown (0xfff4a460);
  63890. const Colour Colours::seagreen (0xff2e8b57);
  63891. const Colour Colours::seashell (0xfffff5ee);
  63892. const Colour Colours::sienna (0xffa0522d);
  63893. const Colour Colours::silver (0xffc0c0c0);
  63894. const Colour Colours::skyblue (0xff87ceeb);
  63895. const Colour Colours::slateblue (0xff6a5acd);
  63896. const Colour Colours::slategrey (0xff708090);
  63897. const Colour Colours::snow (0xfffffafa);
  63898. const Colour Colours::springgreen (0xff00ff7f);
  63899. const Colour Colours::steelblue (0xff4682b4);
  63900. const Colour Colours::tan (0xffd2b48c);
  63901. const Colour Colours::teal (0xff008080);
  63902. const Colour Colours::thistle (0xffd8bfd8);
  63903. const Colour Colours::tomato (0xffff6347);
  63904. const Colour Colours::turquoise (0xff40e0d0);
  63905. const Colour Colours::violet (0xffee82ee);
  63906. const Colour Colours::wheat (0xfff5deb3);
  63907. const Colour Colours::white (0xffffffff);
  63908. const Colour Colours::whitesmoke (0xfff5f5f5);
  63909. const Colour Colours::yellow (0xffffff00);
  63910. const Colour Colours::yellowgreen (0xff9acd32);
  63911. const Colour Colours::findColourForName (const String& colourName,
  63912. const Colour& defaultColour)
  63913. {
  63914. static const int presets[] =
  63915. {
  63916. // (first value is the string's hashcode, second is ARGB)
  63917. 0x05978fff, 0xff000000, /* black */
  63918. 0x06bdcc29, 0xffffffff, /* white */
  63919. 0x002e305a, 0xff0000ff, /* blue */
  63920. 0x00308adf, 0xff808080, /* grey */
  63921. 0x05e0cf03, 0xff008000, /* green */
  63922. 0x0001b891, 0xffff0000, /* red */
  63923. 0xd43c6474, 0xffffff00, /* yellow */
  63924. 0x620886da, 0xfff0f8ff, /* aliceblue */
  63925. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  63926. 0x002dcebc, 0xff00ffff, /* aqua */
  63927. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  63928. 0x0590228f, 0xfff0ffff, /* azure */
  63929. 0x05947fe4, 0xfff5f5dc, /* beige */
  63930. 0xad388e35, 0xffffe4c4, /* bisque */
  63931. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  63932. 0x39129959, 0xff8a2be2, /* blueviolet */
  63933. 0x059a8136, 0xffa52a2a, /* brown */
  63934. 0x89cea8f9, 0xffdeb887, /* burlywood */
  63935. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  63936. 0x6b748956, 0xff7fff00, /* chartreuse */
  63937. 0x2903623c, 0xffd2691e, /* chocolate */
  63938. 0x05a74431, 0xffff7f50, /* coral */
  63939. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  63940. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  63941. 0x3d8c4edf, 0xffdc143c, /* crimson */
  63942. 0x002ed323, 0xff00ffff, /* cyan */
  63943. 0x67cc74d0, 0xff00008b, /* darkblue */
  63944. 0x67cd1799, 0xff008b8b, /* darkcyan */
  63945. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  63946. 0x67cecf55, 0xff555555, /* darkgrey */
  63947. 0x920b194d, 0xff006400, /* darkgreen */
  63948. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  63949. 0x5c293873, 0xff8b008b, /* darkmagenta */
  63950. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  63951. 0xbcfd2524, 0xffff8c00, /* darkorange */
  63952. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  63953. 0x55ee0d5b, 0xff8b0000, /* darkred */
  63954. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  63955. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  63956. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  63957. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  63958. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  63959. 0xc8769375, 0xff9400d3, /* darkviolet */
  63960. 0x25832862, 0xffff1493, /* deeppink */
  63961. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  63962. 0x634c8b67, 0xff696969, /* dimgrey */
  63963. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  63964. 0xef19e3cb, 0xffb22222, /* firebrick */
  63965. 0xb852b195, 0xfffffaf0, /* floralwhite */
  63966. 0xd086fd06, 0xff228b22, /* forestgreen */
  63967. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  63968. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  63969. 0x00308060, 0xffffd700, /* gold */
  63970. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  63971. 0xbab8a537, 0xffadff2f, /* greenyellow */
  63972. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  63973. 0x41892743, 0xffff69b4, /* hotpink */
  63974. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  63975. 0xb969fed2, 0xff4b0082, /* indigo */
  63976. 0x05fef6a9, 0xfffffff0, /* ivory */
  63977. 0x06149302, 0xfff0e68c, /* khaki */
  63978. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  63979. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  63980. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  63981. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  63982. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  63983. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  63984. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  63985. 0xf40157ad, 0xff90ee90, /* lightgreen */
  63986. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  63987. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  63988. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  63989. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  63990. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  63991. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  63992. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  63993. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  63994. 0x0032afd5, 0xff00ff00, /* lime */
  63995. 0x607bbc4e, 0xff32cd32, /* limegreen */
  63996. 0x06234efa, 0xfffaf0e6, /* linen */
  63997. 0x316858a9, 0xffff00ff, /* magenta */
  63998. 0xbf8ca470, 0xff800000, /* maroon */
  63999. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  64000. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  64001. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  64002. 0x07556b71, 0xff9370db, /* mediumpurple */
  64003. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  64004. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  64005. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  64006. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  64007. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  64008. 0x168eb32a, 0xff191970, /* midnightblue */
  64009. 0x4306b960, 0xfff5fffa, /* mintcream */
  64010. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  64011. 0xe97218a6, 0xffffdead, /* navajowhite */
  64012. 0x00337bb6, 0xff000080, /* navy */
  64013. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  64014. 0x064ee1db, 0xff808000, /* olive */
  64015. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  64016. 0xc3de262e, 0xffffa500, /* orange */
  64017. 0x58bebba3, 0xffff4500, /* orangered */
  64018. 0xc3def8a3, 0xffda70d6, /* orchid */
  64019. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  64020. 0x3d9dd619, 0xff98fb98, /* palegreen */
  64021. 0x74022737, 0xffafeeee, /* paleturquoise */
  64022. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  64023. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  64024. 0x93e1b776, 0xffffdab9, /* peachpuff */
  64025. 0x003472f8, 0xffcd853f, /* peru */
  64026. 0x00348176, 0xffffc0cb, /* pink */
  64027. 0x00348d94, 0xffdda0dd, /* plum */
  64028. 0xd036be93, 0xffb0e0e6, /* powderblue */
  64029. 0xc5c507bc, 0xff800080, /* purple */
  64030. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  64031. 0xbd9413e1, 0xff4169e1, /* royalblue */
  64032. 0xf456044f, 0xff8b4513, /* saddlebrown */
  64033. 0xc9c6f66e, 0xfffa8072, /* salmon */
  64034. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  64035. 0x34636c14, 0xff2e8b57, /* seagreen */
  64036. 0x3507fb41, 0xfffff5ee, /* seashell */
  64037. 0xca348772, 0xffa0522d, /* sienna */
  64038. 0xca37d30d, 0xffc0c0c0, /* silver */
  64039. 0x80da74fb, 0xff87ceeb, /* skyblue */
  64040. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  64041. 0x44ab37f8, 0xff708090, /* slategrey */
  64042. 0x0035f183, 0xfffffafa, /* snow */
  64043. 0xd5440d16, 0xff00ff7f, /* springgreen */
  64044. 0x3e1524a5, 0xff4682b4, /* steelblue */
  64045. 0x0001bfa1, 0xffd2b48c, /* tan */
  64046. 0x0036425c, 0xff008080, /* teal */
  64047. 0xafc8858f, 0xffd8bfd8, /* thistle */
  64048. 0xcc41600a, 0xffff6347, /* tomato */
  64049. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  64050. 0xcf57947f, 0xffee82ee, /* violet */
  64051. 0x06bdbae7, 0xfff5deb3, /* wheat */
  64052. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  64053. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  64054. };
  64055. const int hash = colourName.trim().toLowerCase().hashCode();
  64056. for (int i = 0; i < numElementsInArray (presets); i += 2)
  64057. if (presets [i] == hash)
  64058. return Colour (presets [i + 1]);
  64059. return defaultColour;
  64060. }
  64061. END_JUCE_NAMESPACE
  64062. /*** End of inlined file: juce_Colours.cpp ***/
  64063. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  64064. BEGIN_JUCE_NAMESPACE
  64065. const int juce_edgeTableDefaultEdgesPerLine = 32;
  64066. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  64067. const Path& path, const AffineTransform& transform)
  64068. : bounds (bounds_),
  64069. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64070. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64071. needToCheckEmptinesss (true)
  64072. {
  64073. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  64074. int* t = table;
  64075. for (int i = bounds.getHeight(); --i >= 0;)
  64076. {
  64077. *t = 0;
  64078. t += lineStrideElements;
  64079. }
  64080. const int topLimit = bounds.getY() << 8;
  64081. const int heightLimit = bounds.getHeight() << 8;
  64082. const int leftLimit = bounds.getX() << 8;
  64083. const int rightLimit = bounds.getRight() << 8;
  64084. PathFlatteningIterator iter (path, transform);
  64085. while (iter.next())
  64086. {
  64087. int y1 = roundToInt (iter.y1 * 256.0f);
  64088. int y2 = roundToInt (iter.y2 * 256.0f);
  64089. if (y1 != y2)
  64090. {
  64091. y1 -= topLimit;
  64092. y2 -= topLimit;
  64093. const int startY = y1;
  64094. int direction = -1;
  64095. if (y1 > y2)
  64096. {
  64097. swapVariables (y1, y2);
  64098. direction = 1;
  64099. }
  64100. if (y1 < 0)
  64101. y1 = 0;
  64102. if (y2 > heightLimit)
  64103. y2 = heightLimit;
  64104. if (y1 < y2)
  64105. {
  64106. const double startX = 256.0f * iter.x1;
  64107. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  64108. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  64109. do
  64110. {
  64111. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  64112. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  64113. if (x < leftLimit)
  64114. x = leftLimit;
  64115. else if (x >= rightLimit)
  64116. x = rightLimit - 1;
  64117. addEdgePoint (x, y1 >> 8, direction * step);
  64118. y1 += step;
  64119. }
  64120. while (y1 < y2);
  64121. }
  64122. }
  64123. }
  64124. sanitiseLevels (path.isUsingNonZeroWinding());
  64125. }
  64126. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  64127. : bounds (rectangleToAdd),
  64128. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64129. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64130. needToCheckEmptinesss (true)
  64131. {
  64132. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64133. table[0] = 0;
  64134. const int x1 = rectangleToAdd.getX() << 8;
  64135. const int x2 = rectangleToAdd.getRight() << 8;
  64136. int* t = table;
  64137. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  64138. {
  64139. t[0] = 2;
  64140. t[1] = x1;
  64141. t[2] = 255;
  64142. t[3] = x2;
  64143. t[4] = 0;
  64144. t += lineStrideElements;
  64145. }
  64146. }
  64147. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  64148. : bounds (rectanglesToAdd.getBounds()),
  64149. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64150. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64151. needToCheckEmptinesss (true)
  64152. {
  64153. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64154. int* t = table;
  64155. for (int i = bounds.getHeight(); --i >= 0;)
  64156. {
  64157. *t = 0;
  64158. t += lineStrideElements;
  64159. }
  64160. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  64161. {
  64162. const Rectangle<int>* const r = iter.getRectangle();
  64163. const int x1 = r->getX() << 8;
  64164. const int x2 = r->getRight() << 8;
  64165. int y = r->getY() - bounds.getY();
  64166. for (int j = r->getHeight(); --j >= 0;)
  64167. {
  64168. addEdgePoint (x1, y, 255);
  64169. addEdgePoint (x2, y, -255);
  64170. ++y;
  64171. }
  64172. }
  64173. sanitiseLevels (true);
  64174. }
  64175. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  64176. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  64177. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  64178. 2 + (int) rectangleToAdd.getWidth(),
  64179. 2 + (int) rectangleToAdd.getHeight())),
  64180. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64181. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64182. needToCheckEmptinesss (true)
  64183. {
  64184. jassert (! rectangleToAdd.isEmpty());
  64185. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64186. table[0] = 0;
  64187. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  64188. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  64189. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  64190. jassert (y1 < 256);
  64191. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  64192. if (x2 <= x1 || y2 <= y1)
  64193. {
  64194. bounds.setHeight (0);
  64195. return;
  64196. }
  64197. int lineY = 0;
  64198. int* t = table;
  64199. if ((y1 >> 8) == (y2 >> 8))
  64200. {
  64201. t[0] = 2;
  64202. t[1] = x1;
  64203. t[2] = y2 - y1;
  64204. t[3] = x2;
  64205. t[4] = 0;
  64206. ++lineY;
  64207. t += lineStrideElements;
  64208. }
  64209. else
  64210. {
  64211. t[0] = 2;
  64212. t[1] = x1;
  64213. t[2] = 255 - (y1 & 255);
  64214. t[3] = x2;
  64215. t[4] = 0;
  64216. ++lineY;
  64217. t += lineStrideElements;
  64218. while (lineY < (y2 >> 8))
  64219. {
  64220. t[0] = 2;
  64221. t[1] = x1;
  64222. t[2] = 255;
  64223. t[3] = x2;
  64224. t[4] = 0;
  64225. ++lineY;
  64226. t += lineStrideElements;
  64227. }
  64228. jassert (lineY < bounds.getHeight());
  64229. t[0] = 2;
  64230. t[1] = x1;
  64231. t[2] = y2 & 255;
  64232. t[3] = x2;
  64233. t[4] = 0;
  64234. ++lineY;
  64235. t += lineStrideElements;
  64236. }
  64237. while (lineY < bounds.getHeight())
  64238. {
  64239. t[0] = 0;
  64240. t += lineStrideElements;
  64241. ++lineY;
  64242. }
  64243. }
  64244. EdgeTable::EdgeTable (const EdgeTable& other)
  64245. {
  64246. operator= (other);
  64247. }
  64248. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  64249. {
  64250. bounds = other.bounds;
  64251. maxEdgesPerLine = other.maxEdgesPerLine;
  64252. lineStrideElements = other.lineStrideElements;
  64253. needToCheckEmptinesss = other.needToCheckEmptinesss;
  64254. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64255. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  64256. return *this;
  64257. }
  64258. EdgeTable::~EdgeTable()
  64259. {
  64260. }
  64261. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  64262. {
  64263. while (--numLines >= 0)
  64264. {
  64265. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  64266. src += srcLineStride;
  64267. dest += destLineStride;
  64268. }
  64269. }
  64270. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  64271. {
  64272. // Convert the table from relative windings to absolute levels..
  64273. int* lineStart = table;
  64274. for (int i = bounds.getHeight(); --i >= 0;)
  64275. {
  64276. int* line = lineStart;
  64277. lineStart += lineStrideElements;
  64278. int num = *line;
  64279. if (num == 0)
  64280. continue;
  64281. int level = 0;
  64282. if (useNonZeroWinding)
  64283. {
  64284. while (--num > 0)
  64285. {
  64286. line += 2;
  64287. level += *line;
  64288. int corrected = abs (level);
  64289. if (corrected >> 8)
  64290. corrected = 255;
  64291. *line = corrected;
  64292. }
  64293. }
  64294. else
  64295. {
  64296. while (--num > 0)
  64297. {
  64298. line += 2;
  64299. level += *line;
  64300. int corrected = abs (level);
  64301. if (corrected >> 8)
  64302. {
  64303. corrected &= 511;
  64304. if (corrected >> 8)
  64305. corrected = 511 - corrected;
  64306. }
  64307. *line = corrected;
  64308. }
  64309. }
  64310. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  64311. }
  64312. }
  64313. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  64314. {
  64315. if (newNumEdgesPerLine != maxEdgesPerLine)
  64316. {
  64317. maxEdgesPerLine = newNumEdgesPerLine;
  64318. jassert (bounds.getHeight() > 0);
  64319. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  64320. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  64321. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  64322. table.swapWith (newTable);
  64323. lineStrideElements = newLineStrideElements;
  64324. }
  64325. }
  64326. void EdgeTable::optimiseTable() throw()
  64327. {
  64328. int maxLineElements = 0;
  64329. for (int i = bounds.getHeight(); --i >= 0;)
  64330. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  64331. remapTableForNumEdges (maxLineElements);
  64332. }
  64333. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  64334. {
  64335. jassert (y >= 0 && y < bounds.getHeight());
  64336. int* line = table + lineStrideElements * y;
  64337. const int numPoints = line[0];
  64338. int n = numPoints << 1;
  64339. if (n > 0)
  64340. {
  64341. while (n > 0)
  64342. {
  64343. const int cx = line [n - 1];
  64344. if (cx <= x)
  64345. {
  64346. if (cx == x)
  64347. {
  64348. line [n] += winding;
  64349. return;
  64350. }
  64351. break;
  64352. }
  64353. n -= 2;
  64354. }
  64355. if (numPoints >= maxEdgesPerLine)
  64356. {
  64357. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64358. jassert (numPoints < maxEdgesPerLine);
  64359. line = table + lineStrideElements * y;
  64360. }
  64361. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  64362. }
  64363. line [n + 1] = x;
  64364. line [n + 2] = winding;
  64365. line[0]++;
  64366. }
  64367. void EdgeTable::translate (float dx, const int dy) throw()
  64368. {
  64369. bounds.translate ((int) std::floor (dx), dy);
  64370. int* lineStart = table;
  64371. const int intDx = (int) (dx * 256.0f);
  64372. for (int i = bounds.getHeight(); --i >= 0;)
  64373. {
  64374. int* line = lineStart;
  64375. lineStart += lineStrideElements;
  64376. int num = *line++;
  64377. while (--num >= 0)
  64378. {
  64379. *line += intDx;
  64380. line += 2;
  64381. }
  64382. }
  64383. }
  64384. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  64385. {
  64386. jassert (y >= 0 && y < bounds.getHeight());
  64387. int* dest = table + lineStrideElements * y;
  64388. if (dest[0] == 0)
  64389. return;
  64390. int otherNumPoints = *otherLine;
  64391. if (otherNumPoints == 0)
  64392. {
  64393. *dest = 0;
  64394. return;
  64395. }
  64396. const int right = bounds.getRight() << 8;
  64397. // optimise for the common case where our line lies entirely within a
  64398. // single pair of points, as happens when clipping to a simple rect.
  64399. if (otherNumPoints == 2 && otherLine[2] >= 255)
  64400. {
  64401. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  64402. return;
  64403. }
  64404. ++otherLine;
  64405. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  64406. int* temp = (int*) alloca (lineSizeBytes);
  64407. memcpy (temp, dest, lineSizeBytes);
  64408. const int* src1 = temp;
  64409. int srcNum1 = *src1++;
  64410. int x1 = *src1++;
  64411. const int* src2 = otherLine;
  64412. int srcNum2 = otherNumPoints;
  64413. int x2 = *src2++;
  64414. int destIndex = 0, destTotal = 0;
  64415. int level1 = 0, level2 = 0;
  64416. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  64417. while (srcNum1 > 0 && srcNum2 > 0)
  64418. {
  64419. int nextX;
  64420. if (x1 < x2)
  64421. {
  64422. nextX = x1;
  64423. level1 = *src1++;
  64424. x1 = *src1++;
  64425. --srcNum1;
  64426. }
  64427. else if (x1 == x2)
  64428. {
  64429. nextX = x1;
  64430. level1 = *src1++;
  64431. level2 = *src2++;
  64432. x1 = *src1++;
  64433. x2 = *src2++;
  64434. --srcNum1;
  64435. --srcNum2;
  64436. }
  64437. else
  64438. {
  64439. nextX = x2;
  64440. level2 = *src2++;
  64441. x2 = *src2++;
  64442. --srcNum2;
  64443. }
  64444. if (nextX > lastX)
  64445. {
  64446. if (nextX >= right)
  64447. break;
  64448. lastX = nextX;
  64449. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  64450. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  64451. if (nextLevel != lastLevel)
  64452. {
  64453. if (destTotal >= maxEdgesPerLine)
  64454. {
  64455. dest[0] = destTotal;
  64456. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64457. dest = table + lineStrideElements * y;
  64458. }
  64459. ++destTotal;
  64460. lastLevel = nextLevel;
  64461. dest[++destIndex] = nextX;
  64462. dest[++destIndex] = nextLevel;
  64463. }
  64464. }
  64465. }
  64466. if (lastLevel > 0)
  64467. {
  64468. if (destTotal >= maxEdgesPerLine)
  64469. {
  64470. dest[0] = destTotal;
  64471. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64472. dest = table + lineStrideElements * y;
  64473. }
  64474. ++destTotal;
  64475. dest[++destIndex] = right;
  64476. dest[++destIndex] = 0;
  64477. }
  64478. dest[0] = destTotal;
  64479. #if JUCE_DEBUG
  64480. int last = std::numeric_limits<int>::min();
  64481. for (int i = 0; i < dest[0]; ++i)
  64482. {
  64483. jassert (dest[i * 2 + 1] > last);
  64484. last = dest[i * 2 + 1];
  64485. }
  64486. jassert (dest [dest[0] * 2] == 0);
  64487. #endif
  64488. }
  64489. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  64490. {
  64491. int* lastItem = dest + (dest[0] * 2 - 1);
  64492. if (x2 < lastItem[0])
  64493. {
  64494. if (x2 <= dest[1])
  64495. {
  64496. dest[0] = 0;
  64497. return;
  64498. }
  64499. while (x2 < lastItem[-2])
  64500. {
  64501. --(dest[0]);
  64502. lastItem -= 2;
  64503. }
  64504. lastItem[0] = x2;
  64505. lastItem[1] = 0;
  64506. }
  64507. if (x1 > dest[1])
  64508. {
  64509. while (lastItem[0] > x1)
  64510. lastItem -= 2;
  64511. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  64512. if (itemsRemoved > 0)
  64513. {
  64514. dest[0] -= itemsRemoved;
  64515. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  64516. }
  64517. dest[1] = x1;
  64518. }
  64519. }
  64520. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  64521. {
  64522. const Rectangle<int> clipped (r.getIntersection (bounds));
  64523. if (clipped.isEmpty())
  64524. {
  64525. needToCheckEmptinesss = false;
  64526. bounds.setHeight (0);
  64527. }
  64528. else
  64529. {
  64530. const int top = clipped.getY() - bounds.getY();
  64531. const int bottom = clipped.getBottom() - bounds.getY();
  64532. if (bottom < bounds.getHeight())
  64533. bounds.setHeight (bottom);
  64534. if (clipped.getRight() < bounds.getRight())
  64535. bounds.setRight (clipped.getRight());
  64536. for (int i = top; --i >= 0;)
  64537. table [lineStrideElements * i] = 0;
  64538. if (clipped.getX() > bounds.getX())
  64539. {
  64540. const int x1 = clipped.getX() << 8;
  64541. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  64542. int* line = table + lineStrideElements * top;
  64543. for (int i = bottom - top; --i >= 0;)
  64544. {
  64545. if (line[0] != 0)
  64546. clipEdgeTableLineToRange (line, x1, x2);
  64547. line += lineStrideElements;
  64548. }
  64549. }
  64550. needToCheckEmptinesss = true;
  64551. }
  64552. }
  64553. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  64554. {
  64555. const Rectangle<int> clipped (r.getIntersection (bounds));
  64556. if (! clipped.isEmpty())
  64557. {
  64558. const int top = clipped.getY() - bounds.getY();
  64559. const int bottom = clipped.getBottom() - bounds.getY();
  64560. //XXX optimise here by shortening the table if it fills top or bottom
  64561. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  64562. clipped.getX() << 8, 0,
  64563. clipped.getRight() << 8, 255,
  64564. std::numeric_limits<int>::max(), 0 };
  64565. for (int i = top; i < bottom; ++i)
  64566. intersectWithEdgeTableLine (i, rectLine);
  64567. needToCheckEmptinesss = true;
  64568. }
  64569. }
  64570. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  64571. {
  64572. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  64573. if (clipped.isEmpty())
  64574. {
  64575. needToCheckEmptinesss = false;
  64576. bounds.setHeight (0);
  64577. }
  64578. else
  64579. {
  64580. const int top = clipped.getY() - bounds.getY();
  64581. const int bottom = clipped.getBottom() - bounds.getY();
  64582. if (bottom < bounds.getHeight())
  64583. bounds.setHeight (bottom);
  64584. if (clipped.getRight() < bounds.getRight())
  64585. bounds.setRight (clipped.getRight());
  64586. int i = 0;
  64587. for (i = top; --i >= 0;)
  64588. table [lineStrideElements * i] = 0;
  64589. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  64590. for (i = top; i < bottom; ++i)
  64591. {
  64592. intersectWithEdgeTableLine (i, otherLine);
  64593. otherLine += other.lineStrideElements;
  64594. }
  64595. needToCheckEmptinesss = true;
  64596. }
  64597. }
  64598. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  64599. {
  64600. y -= bounds.getY();
  64601. if (y < 0 || y >= bounds.getHeight())
  64602. return;
  64603. needToCheckEmptinesss = true;
  64604. if (numPixels <= 0)
  64605. {
  64606. table [lineStrideElements * y] = 0;
  64607. return;
  64608. }
  64609. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  64610. int destIndex = 0, lastLevel = 0;
  64611. while (--numPixels >= 0)
  64612. {
  64613. const int alpha = *mask;
  64614. mask += maskStride;
  64615. if (alpha != lastLevel)
  64616. {
  64617. tempLine[++destIndex] = (x << 8);
  64618. tempLine[++destIndex] = alpha;
  64619. lastLevel = alpha;
  64620. }
  64621. ++x;
  64622. }
  64623. if (lastLevel > 0)
  64624. {
  64625. tempLine[++destIndex] = (x << 8);
  64626. tempLine[++destIndex] = 0;
  64627. }
  64628. tempLine[0] = destIndex >> 1;
  64629. intersectWithEdgeTableLine (y, tempLine);
  64630. }
  64631. bool EdgeTable::isEmpty() throw()
  64632. {
  64633. if (needToCheckEmptinesss)
  64634. {
  64635. needToCheckEmptinesss = false;
  64636. int* t = table;
  64637. for (int i = bounds.getHeight(); --i >= 0;)
  64638. {
  64639. if (t[0] > 1)
  64640. return false;
  64641. t += lineStrideElements;
  64642. }
  64643. bounds.setHeight (0);
  64644. }
  64645. return bounds.getHeight() == 0;
  64646. }
  64647. END_JUCE_NAMESPACE
  64648. /*** End of inlined file: juce_EdgeTable.cpp ***/
  64649. /*** Start of inlined file: juce_FillType.cpp ***/
  64650. BEGIN_JUCE_NAMESPACE
  64651. FillType::FillType() throw()
  64652. : colour (0xff000000), image (0)
  64653. {
  64654. }
  64655. FillType::FillType (const Colour& colour_) throw()
  64656. : colour (colour_), image (0)
  64657. {
  64658. }
  64659. FillType::FillType (const ColourGradient& gradient_)
  64660. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  64661. {
  64662. }
  64663. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  64664. : colour (0xff000000), image (image_), transform (transform_)
  64665. {
  64666. }
  64667. FillType::FillType (const FillType& other)
  64668. : colour (other.colour),
  64669. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  64670. image (other.image), transform (other.transform)
  64671. {
  64672. }
  64673. FillType& FillType::operator= (const FillType& other)
  64674. {
  64675. if (this != &other)
  64676. {
  64677. colour = other.colour;
  64678. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  64679. image = other.image;
  64680. transform = other.transform;
  64681. }
  64682. return *this;
  64683. }
  64684. FillType::~FillType() throw()
  64685. {
  64686. }
  64687. bool FillType::operator== (const FillType& other) const
  64688. {
  64689. return colour == other.colour && image == other.image
  64690. && (gradient == other.gradient
  64691. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  64692. }
  64693. bool FillType::operator!= (const FillType& other) const
  64694. {
  64695. return ! operator== (other);
  64696. }
  64697. void FillType::setColour (const Colour& newColour) throw()
  64698. {
  64699. gradient = 0;
  64700. image = Image();
  64701. colour = newColour;
  64702. }
  64703. void FillType::setGradient (const ColourGradient& newGradient)
  64704. {
  64705. if (gradient != 0)
  64706. {
  64707. *gradient = newGradient;
  64708. }
  64709. else
  64710. {
  64711. image = Image();
  64712. gradient = new ColourGradient (newGradient);
  64713. colour = Colours::black;
  64714. }
  64715. }
  64716. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  64717. {
  64718. gradient = 0;
  64719. image = image_;
  64720. transform = transform_;
  64721. colour = Colours::black;
  64722. }
  64723. void FillType::setOpacity (const float newOpacity) throw()
  64724. {
  64725. colour = colour.withAlpha (newOpacity);
  64726. }
  64727. bool FillType::isInvisible() const throw()
  64728. {
  64729. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  64730. }
  64731. END_JUCE_NAMESPACE
  64732. /*** End of inlined file: juce_FillType.cpp ***/
  64733. /*** Start of inlined file: juce_Graphics.cpp ***/
  64734. BEGIN_JUCE_NAMESPACE
  64735. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  64736. template <typename Type>
  64737. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  64738. {
  64739. const int maxVal = 0x3fffffff;
  64740. return (int) x >= -maxVal && (int) x <= maxVal
  64741. && (int) y >= -maxVal && (int) y <= maxVal
  64742. && (int) w >= -maxVal && (int) w <= maxVal
  64743. && (int) h >= -maxVal && (int) h <= maxVal;
  64744. }
  64745. LowLevelGraphicsContext::LowLevelGraphicsContext()
  64746. {
  64747. }
  64748. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  64749. {
  64750. }
  64751. Graphics::Graphics (const Image& imageToDrawOnto)
  64752. : context (imageToDrawOnto.createLowLevelContext()),
  64753. contextToDelete (context),
  64754. saveStatePending (false)
  64755. {
  64756. }
  64757. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  64758. : context (internalContext),
  64759. saveStatePending (false)
  64760. {
  64761. }
  64762. Graphics::~Graphics()
  64763. {
  64764. }
  64765. void Graphics::resetToDefaultState()
  64766. {
  64767. saveStateIfPending();
  64768. context->setFill (FillType());
  64769. context->setFont (Font());
  64770. context->setInterpolationQuality (defaultQuality);
  64771. }
  64772. bool Graphics::isVectorDevice() const
  64773. {
  64774. return context->isVectorDevice();
  64775. }
  64776. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  64777. {
  64778. saveStateIfPending();
  64779. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  64780. }
  64781. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  64782. {
  64783. saveStateIfPending();
  64784. return context->clipToRectangleList (clipRegion);
  64785. }
  64786. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  64787. {
  64788. saveStateIfPending();
  64789. context->clipToPath (path, transform);
  64790. return ! context->isClipEmpty();
  64791. }
  64792. bool Graphics::reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion, const AffineTransform& transform)
  64793. {
  64794. saveStateIfPending();
  64795. context->clipToImageAlpha (image, sourceClipRegion, transform);
  64796. return ! context->isClipEmpty();
  64797. }
  64798. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  64799. {
  64800. saveStateIfPending();
  64801. context->excludeClipRectangle (rectangleToExclude);
  64802. }
  64803. bool Graphics::isClipEmpty() const
  64804. {
  64805. return context->isClipEmpty();
  64806. }
  64807. const Rectangle<int> Graphics::getClipBounds() const
  64808. {
  64809. return context->getClipBounds();
  64810. }
  64811. void Graphics::saveState()
  64812. {
  64813. saveStateIfPending();
  64814. saveStatePending = true;
  64815. }
  64816. void Graphics::restoreState()
  64817. {
  64818. if (saveStatePending)
  64819. saveStatePending = false;
  64820. else
  64821. context->restoreState();
  64822. }
  64823. void Graphics::saveStateIfPending()
  64824. {
  64825. if (saveStatePending)
  64826. {
  64827. saveStatePending = false;
  64828. context->saveState();
  64829. }
  64830. }
  64831. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  64832. {
  64833. saveStateIfPending();
  64834. context->setOrigin (newOriginX, newOriginY);
  64835. }
  64836. bool Graphics::clipRegionIntersects (const int x, const int y, const int w, const int h) const
  64837. {
  64838. return context->clipRegionIntersects (Rectangle<int> (x, y, w, h));
  64839. }
  64840. void Graphics::setColour (const Colour& newColour)
  64841. {
  64842. saveStateIfPending();
  64843. context->setFill (newColour);
  64844. }
  64845. void Graphics::setOpacity (const float newOpacity)
  64846. {
  64847. saveStateIfPending();
  64848. context->setOpacity (newOpacity);
  64849. }
  64850. void Graphics::setGradientFill (const ColourGradient& gradient)
  64851. {
  64852. setFillType (gradient);
  64853. }
  64854. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  64855. {
  64856. saveStateIfPending();
  64857. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  64858. context->setOpacity (opacity);
  64859. }
  64860. void Graphics::setFillType (const FillType& newFill)
  64861. {
  64862. saveStateIfPending();
  64863. context->setFill (newFill);
  64864. }
  64865. void Graphics::setFont (const Font& newFont)
  64866. {
  64867. saveStateIfPending();
  64868. context->setFont (newFont);
  64869. }
  64870. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  64871. {
  64872. saveStateIfPending();
  64873. Font f (context->getFont());
  64874. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  64875. context->setFont (f);
  64876. }
  64877. const Font Graphics::getCurrentFont() const
  64878. {
  64879. return context->getFont();
  64880. }
  64881. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  64882. {
  64883. if (text.isNotEmpty()
  64884. && startX < context->getClipBounds().getRight())
  64885. {
  64886. GlyphArrangement arr;
  64887. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  64888. arr.draw (*this);
  64889. }
  64890. }
  64891. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  64892. {
  64893. if (text.isNotEmpty())
  64894. {
  64895. GlyphArrangement arr;
  64896. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  64897. arr.draw (*this, transform);
  64898. }
  64899. }
  64900. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  64901. {
  64902. if (text.isNotEmpty()
  64903. && startX < context->getClipBounds().getRight())
  64904. {
  64905. GlyphArrangement arr;
  64906. arr.addJustifiedText (context->getFont(), text,
  64907. (float) startX, (float) baselineY, (float) maximumLineWidth,
  64908. Justification::left);
  64909. arr.draw (*this);
  64910. }
  64911. }
  64912. void Graphics::drawText (const String& text,
  64913. const int x, const int y, const int width, const int height,
  64914. const Justification& justificationType,
  64915. const bool useEllipsesIfTooBig) const
  64916. {
  64917. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  64918. {
  64919. GlyphArrangement arr;
  64920. arr.addCurtailedLineOfText (context->getFont(), text,
  64921. 0.0f, 0.0f, (float) width,
  64922. useEllipsesIfTooBig);
  64923. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  64924. (float) x, (float) y, (float) width, (float) height,
  64925. justificationType);
  64926. arr.draw (*this);
  64927. }
  64928. }
  64929. void Graphics::drawFittedText (const String& text,
  64930. const int x, const int y, const int width, const int height,
  64931. const Justification& justification,
  64932. const int maximumNumberOfLines,
  64933. const float minimumHorizontalScale) const
  64934. {
  64935. if (text.isNotEmpty()
  64936. && width > 0 && height > 0
  64937. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  64938. {
  64939. GlyphArrangement arr;
  64940. arr.addFittedText (context->getFont(), text,
  64941. (float) x, (float) y, (float) width, (float) height,
  64942. justification,
  64943. maximumNumberOfLines,
  64944. minimumHorizontalScale);
  64945. arr.draw (*this);
  64946. }
  64947. }
  64948. void Graphics::fillRect (int x, int y, int width, int height) const
  64949. {
  64950. // passing in a silly number can cause maths problems in rendering!
  64951. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64952. context->fillRect (Rectangle<int> (x, y, width, height), false);
  64953. }
  64954. void Graphics::fillRect (const Rectangle<int>& r) const
  64955. {
  64956. context->fillRect (r, false);
  64957. }
  64958. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  64959. {
  64960. // passing in a silly number can cause maths problems in rendering!
  64961. jassert (areCoordsSensibleNumbers (x, y, width, height));
  64962. Path p;
  64963. p.addRectangle (x, y, width, height);
  64964. fillPath (p);
  64965. }
  64966. void Graphics::setPixel (int x, int y) const
  64967. {
  64968. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  64969. }
  64970. void Graphics::fillAll() const
  64971. {
  64972. fillRect (context->getClipBounds());
  64973. }
  64974. void Graphics::fillAll (const Colour& colourToUse) const
  64975. {
  64976. if (! colourToUse.isTransparent())
  64977. {
  64978. const Rectangle<int> clip (context->getClipBounds());
  64979. context->saveState();
  64980. context->setFill (colourToUse);
  64981. context->fillRect (clip, false);
  64982. context->restoreState();
  64983. }
  64984. }
  64985. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  64986. {
  64987. if ((! context->isClipEmpty()) && ! path.isEmpty())
  64988. context->fillPath (path, transform);
  64989. }
  64990. void Graphics::strokePath (const Path& path,
  64991. const PathStrokeType& strokeType,
  64992. const AffineTransform& transform) const
  64993. {
  64994. Path stroke;
  64995. strokeType.createStrokedPath (stroke, path, transform);
  64996. fillPath (stroke);
  64997. }
  64998. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  64999. const int lineThickness) const
  65000. {
  65001. // passing in a silly number can cause maths problems in rendering!
  65002. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65003. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  65004. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  65005. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  65006. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  65007. }
  65008. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  65009. {
  65010. // passing in a silly number can cause maths problems in rendering!
  65011. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65012. Path p;
  65013. p.addRectangle (x, y, width, lineThickness);
  65014. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  65015. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  65016. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  65017. fillPath (p);
  65018. }
  65019. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  65020. {
  65021. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  65022. }
  65023. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  65024. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  65025. const bool useGradient, const bool sharpEdgeOnOutside) const
  65026. {
  65027. // passing in a silly number can cause maths problems in rendering!
  65028. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65029. if (clipRegionIntersects (x, y, width, height))
  65030. {
  65031. context->saveState();
  65032. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  65033. const float ramp = oldOpacity / bevelThickness;
  65034. for (int i = bevelThickness; --i >= 0;)
  65035. {
  65036. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  65037. : oldOpacity;
  65038. context->setFill (topLeftColour.withMultipliedAlpha (op));
  65039. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  65040. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  65041. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  65042. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  65043. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  65044. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  65045. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  65046. }
  65047. context->restoreState();
  65048. }
  65049. }
  65050. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  65051. {
  65052. // passing in a silly number can cause maths problems in rendering!
  65053. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65054. Path p;
  65055. p.addEllipse (x, y, width, height);
  65056. fillPath (p);
  65057. }
  65058. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  65059. const float lineThickness) const
  65060. {
  65061. // passing in a silly number can cause maths problems in rendering!
  65062. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65063. Path p;
  65064. p.addEllipse (x, y, width, height);
  65065. strokePath (p, PathStrokeType (lineThickness));
  65066. }
  65067. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  65068. {
  65069. // passing in a silly number can cause maths problems in rendering!
  65070. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65071. Path p;
  65072. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65073. fillPath (p);
  65074. }
  65075. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  65076. {
  65077. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  65078. }
  65079. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  65080. const float cornerSize, const float lineThickness) const
  65081. {
  65082. // passing in a silly number can cause maths problems in rendering!
  65083. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65084. Path p;
  65085. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65086. strokePath (p, PathStrokeType (lineThickness));
  65087. }
  65088. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  65089. {
  65090. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  65091. }
  65092. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  65093. {
  65094. Path p;
  65095. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  65096. fillPath (p);
  65097. }
  65098. void Graphics::fillCheckerBoard (int x, int y, int width, int height,
  65099. const int checkWidth, const int checkHeight,
  65100. const Colour& colour1, const Colour& colour2) const
  65101. {
  65102. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  65103. if (checkWidth > 0 && checkHeight > 0)
  65104. {
  65105. context->saveState();
  65106. if (colour1 == colour2)
  65107. {
  65108. context->setFill (colour1);
  65109. context->fillRect (Rectangle<int> (x, y, width, height), false);
  65110. }
  65111. else
  65112. {
  65113. const Rectangle<int> clip (context->getClipBounds());
  65114. const int right = jmin (x + width, clip.getRight());
  65115. const int bottom = jmin (y + height, clip.getBottom());
  65116. int cy = 0;
  65117. while (y < bottom)
  65118. {
  65119. int cx = cy;
  65120. for (int xx = x; xx < right; xx += checkWidth)
  65121. {
  65122. context->setFill (((cx++ & 1) == 0) ? colour1 : colour2);
  65123. context->fillRect (Rectangle<int> (xx, y, jmin (checkWidth, right - xx), jmin (checkHeight, bottom - y)),
  65124. false);
  65125. }
  65126. ++cy;
  65127. y += checkHeight;
  65128. }
  65129. }
  65130. context->restoreState();
  65131. }
  65132. }
  65133. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  65134. {
  65135. context->drawVerticalLine (x, top, bottom);
  65136. }
  65137. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  65138. {
  65139. context->drawHorizontalLine (y, left, right);
  65140. }
  65141. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  65142. {
  65143. context->drawLine (Line<float> (x1, y1, x2, y2));
  65144. }
  65145. void Graphics::drawLine (const float startX, const float startY,
  65146. const float endX, const float endY,
  65147. const float lineThickness) const
  65148. {
  65149. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  65150. }
  65151. void Graphics::drawLine (const Line<float>& line) const
  65152. {
  65153. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  65154. }
  65155. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  65156. {
  65157. Path p;
  65158. p.addLineSegment (line, lineThickness);
  65159. fillPath (p);
  65160. }
  65161. void Graphics::drawDashedLine (const float startX, const float startY,
  65162. const float endX, const float endY,
  65163. const float* const dashLengths,
  65164. const int numDashLengths,
  65165. const float lineThickness) const
  65166. {
  65167. const double dx = endX - startX;
  65168. const double dy = endY - startY;
  65169. const double totalLen = juce_hypot (dx, dy);
  65170. if (totalLen >= 0.5)
  65171. {
  65172. const double onePixAlpha = 1.0 / totalLen;
  65173. double alpha = 0.0;
  65174. float x = startX;
  65175. float y = startY;
  65176. int n = 0;
  65177. while (alpha < 1.0f)
  65178. {
  65179. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  65180. n = n % numDashLengths;
  65181. const float oldX = x;
  65182. const float oldY = y;
  65183. x = (float) (startX + dx * alpha);
  65184. y = (float) (startY + dy * alpha);
  65185. if ((n & 1) != 0)
  65186. {
  65187. if (lineThickness != 1.0f)
  65188. drawLine (oldX, oldY, x, y, lineThickness);
  65189. else
  65190. drawLine (oldX, oldY, x, y);
  65191. }
  65192. }
  65193. }
  65194. }
  65195. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  65196. {
  65197. saveStateIfPending();
  65198. context->setInterpolationQuality (newQuality);
  65199. }
  65200. void Graphics::drawImageAt (const Image& imageToDraw,
  65201. const int topLeftX, const int topLeftY,
  65202. const bool fillAlphaChannelWithCurrentBrush) const
  65203. {
  65204. const int imageW = imageToDraw.getWidth();
  65205. const int imageH = imageToDraw.getHeight();
  65206. drawImage (imageToDraw,
  65207. topLeftX, topLeftY, imageW, imageH,
  65208. 0, 0, imageW, imageH,
  65209. fillAlphaChannelWithCurrentBrush);
  65210. }
  65211. void Graphics::drawImageWithin (const Image& imageToDraw,
  65212. const int destX, const int destY,
  65213. const int destW, const int destH,
  65214. const RectanglePlacement& placementWithinTarget,
  65215. const bool fillAlphaChannelWithCurrentBrush) const
  65216. {
  65217. // passing in a silly number can cause maths problems in rendering!
  65218. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  65219. if (imageToDraw.isValid())
  65220. {
  65221. const int imageW = imageToDraw.getWidth();
  65222. const int imageH = imageToDraw.getHeight();
  65223. if (imageW > 0 && imageH > 0)
  65224. {
  65225. double newX = 0.0, newY = 0.0;
  65226. double newW = imageW;
  65227. double newH = imageH;
  65228. placementWithinTarget.applyTo (newX, newY, newW, newH,
  65229. destX, destY, destW, destH);
  65230. if (newW > 0 && newH > 0)
  65231. {
  65232. drawImage (imageToDraw,
  65233. roundToInt (newX), roundToInt (newY),
  65234. roundToInt (newW), roundToInt (newH),
  65235. 0, 0, imageW, imageH,
  65236. fillAlphaChannelWithCurrentBrush);
  65237. }
  65238. }
  65239. }
  65240. }
  65241. void Graphics::drawImage (const Image& imageToDraw,
  65242. int dx, int dy, int dw, int dh,
  65243. int sx, int sy, int sw, int sh,
  65244. const bool fillAlphaChannelWithCurrentBrush) const
  65245. {
  65246. // passing in a silly number can cause maths problems in rendering!
  65247. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  65248. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  65249. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  65250. {
  65251. drawImageTransformed (imageToDraw, Rectangle<int> (sx, sy, sw, sh),
  65252. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  65253. .translated ((float) dx, (float) dy),
  65254. fillAlphaChannelWithCurrentBrush);
  65255. }
  65256. }
  65257. void Graphics::drawImageTransformed (const Image& imageToDraw,
  65258. const Rectangle<int>& imageSubRegion,
  65259. const AffineTransform& transform,
  65260. const bool fillAlphaChannelWithCurrentBrush) const
  65261. {
  65262. if (imageToDraw.isValid() && ! context->isClipEmpty())
  65263. {
  65264. const Rectangle<int> srcClip (imageSubRegion.getIntersection (imageToDraw.getBounds()));
  65265. if (fillAlphaChannelWithCurrentBrush)
  65266. {
  65267. context->saveState();
  65268. context->clipToImageAlpha (imageToDraw, srcClip, transform);
  65269. fillAll();
  65270. context->restoreState();
  65271. }
  65272. else
  65273. {
  65274. context->drawImage (imageToDraw, srcClip, transform, false);
  65275. }
  65276. }
  65277. }
  65278. END_JUCE_NAMESPACE
  65279. /*** End of inlined file: juce_Graphics.cpp ***/
  65280. /*** Start of inlined file: juce_Justification.cpp ***/
  65281. BEGIN_JUCE_NAMESPACE
  65282. Justification::Justification (const Justification& other) throw()
  65283. : flags (other.flags)
  65284. {
  65285. }
  65286. Justification& Justification::operator= (const Justification& other) throw()
  65287. {
  65288. flags = other.flags;
  65289. return *this;
  65290. }
  65291. int Justification::getOnlyVerticalFlags() const throw()
  65292. {
  65293. return flags & (top | bottom | verticallyCentred);
  65294. }
  65295. int Justification::getOnlyHorizontalFlags() const throw()
  65296. {
  65297. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  65298. }
  65299. void Justification::applyToRectangle (int& x, int& y,
  65300. const int w, const int h,
  65301. const int spaceX, const int spaceY,
  65302. const int spaceW, const int spaceH) const throw()
  65303. {
  65304. if ((flags & horizontallyCentred) != 0)
  65305. x = spaceX + ((spaceW - w) >> 1);
  65306. else if ((flags & right) != 0)
  65307. x = spaceX + spaceW - w;
  65308. else
  65309. x = spaceX;
  65310. if ((flags & verticallyCentred) != 0)
  65311. y = spaceY + ((spaceH - h) >> 1);
  65312. else if ((flags & bottom) != 0)
  65313. y = spaceY + spaceH - h;
  65314. else
  65315. y = spaceY;
  65316. }
  65317. END_JUCE_NAMESPACE
  65318. /*** End of inlined file: juce_Justification.cpp ***/
  65319. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65320. BEGIN_JUCE_NAMESPACE
  65321. // this will throw an assertion if you try to draw something that's not
  65322. // possible in postscript
  65323. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  65324. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  65325. #define notPossibleInPostscriptAssert jassertfalse
  65326. #else
  65327. #define notPossibleInPostscriptAssert
  65328. #endif
  65329. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  65330. const String& documentTitle,
  65331. const int totalWidth_,
  65332. const int totalHeight_)
  65333. : out (resultingPostScript),
  65334. totalWidth (totalWidth_),
  65335. totalHeight (totalHeight_),
  65336. needToClip (true)
  65337. {
  65338. stateStack.add (new SavedState());
  65339. stateStack.getLast()->clip = Rectangle<int> (0, 0, totalWidth_, totalHeight_);
  65340. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  65341. out << "%!PS-Adobe-3.0 EPSF-3.0"
  65342. "\n%%BoundingBox: 0 0 600 824"
  65343. "\n%%Pages: 0"
  65344. "\n%%Creator: Raw Material Software JUCE"
  65345. "\n%%Title: " << documentTitle <<
  65346. "\n%%CreationDate: none"
  65347. "\n%%LanguageLevel: 2"
  65348. "\n%%EndComments"
  65349. "\n%%BeginProlog"
  65350. "\n%%BeginResource: JRes"
  65351. "\n/bd {bind def} bind def"
  65352. "\n/c {setrgbcolor} bd"
  65353. "\n/m {moveto} bd"
  65354. "\n/l {lineto} bd"
  65355. "\n/rl {rlineto} bd"
  65356. "\n/ct {curveto} bd"
  65357. "\n/cp {closepath} bd"
  65358. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  65359. "\n/doclip {initclip newpath} bd"
  65360. "\n/endclip {clip newpath} bd"
  65361. "\n%%EndResource"
  65362. "\n%%EndProlog"
  65363. "\n%%BeginSetup"
  65364. "\n%%EndSetup"
  65365. "\n%%Page: 1 1"
  65366. "\n%%BeginPageSetup"
  65367. "\n%%EndPageSetup\n\n"
  65368. << "40 800 translate\n"
  65369. << scale << ' ' << scale << " scale\n\n";
  65370. }
  65371. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  65372. {
  65373. }
  65374. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  65375. {
  65376. return true;
  65377. }
  65378. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  65379. {
  65380. if (x != 0 || y != 0)
  65381. {
  65382. stateStack.getLast()->xOffset += x;
  65383. stateStack.getLast()->yOffset += y;
  65384. needToClip = true;
  65385. }
  65386. }
  65387. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  65388. {
  65389. needToClip = true;
  65390. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65391. }
  65392. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  65393. {
  65394. needToClip = true;
  65395. return stateStack.getLast()->clip.clipTo (clipRegion);
  65396. }
  65397. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  65398. {
  65399. needToClip = true;
  65400. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65401. }
  65402. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  65403. {
  65404. writeClip();
  65405. Path p (path);
  65406. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65407. writePath (p);
  65408. out << "clip\n";
  65409. }
  65410. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const Rectangle<int>& /*srcClip*/, const AffineTransform& /*transform*/)
  65411. {
  65412. needToClip = true;
  65413. jassertfalse; // xxx
  65414. }
  65415. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  65416. {
  65417. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65418. }
  65419. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  65420. {
  65421. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  65422. -stateStack.getLast()->yOffset);
  65423. }
  65424. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  65425. {
  65426. return stateStack.getLast()->clip.isEmpty();
  65427. }
  65428. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  65429. : xOffset (0),
  65430. yOffset (0)
  65431. {
  65432. }
  65433. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  65434. {
  65435. }
  65436. void LowLevelGraphicsPostScriptRenderer::saveState()
  65437. {
  65438. stateStack.add (new SavedState (*stateStack.getLast()));
  65439. }
  65440. void LowLevelGraphicsPostScriptRenderer::restoreState()
  65441. {
  65442. jassert (stateStack.size() > 0);
  65443. if (stateStack.size() > 0)
  65444. stateStack.removeLast();
  65445. }
  65446. void LowLevelGraphicsPostScriptRenderer::writeClip()
  65447. {
  65448. if (needToClip)
  65449. {
  65450. needToClip = false;
  65451. out << "doclip ";
  65452. int itemsOnLine = 0;
  65453. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  65454. {
  65455. if (++itemsOnLine == 6)
  65456. {
  65457. itemsOnLine = 0;
  65458. out << '\n';
  65459. }
  65460. const Rectangle<int>& r = *i.getRectangle();
  65461. out << r.getX() << ' ' << -r.getY() << ' '
  65462. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  65463. }
  65464. out << "endclip\n";
  65465. }
  65466. }
  65467. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  65468. {
  65469. Colour c (Colours::white.overlaidWith (colour));
  65470. if (lastColour != c)
  65471. {
  65472. lastColour = c;
  65473. out << String (c.getFloatRed(), 3) << ' '
  65474. << String (c.getFloatGreen(), 3) << ' '
  65475. << String (c.getFloatBlue(), 3) << " c\n";
  65476. }
  65477. }
  65478. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  65479. {
  65480. out << String (x, 2) << ' '
  65481. << String (-y, 2) << ' ';
  65482. }
  65483. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  65484. {
  65485. out << "newpath ";
  65486. float lastX = 0.0f;
  65487. float lastY = 0.0f;
  65488. int itemsOnLine = 0;
  65489. Path::Iterator i (path);
  65490. while (i.next())
  65491. {
  65492. if (++itemsOnLine == 4)
  65493. {
  65494. itemsOnLine = 0;
  65495. out << '\n';
  65496. }
  65497. switch (i.elementType)
  65498. {
  65499. case Path::Iterator::startNewSubPath:
  65500. writeXY (i.x1, i.y1);
  65501. lastX = i.x1;
  65502. lastY = i.y1;
  65503. out << "m ";
  65504. break;
  65505. case Path::Iterator::lineTo:
  65506. writeXY (i.x1, i.y1);
  65507. lastX = i.x1;
  65508. lastY = i.y1;
  65509. out << "l ";
  65510. break;
  65511. case Path::Iterator::quadraticTo:
  65512. {
  65513. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  65514. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  65515. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  65516. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  65517. writeXY (cp1x, cp1y);
  65518. writeXY (cp2x, cp2y);
  65519. writeXY (i.x2, i.y2);
  65520. out << "ct ";
  65521. lastX = i.x2;
  65522. lastY = i.y2;
  65523. }
  65524. break;
  65525. case Path::Iterator::cubicTo:
  65526. writeXY (i.x1, i.y1);
  65527. writeXY (i.x2, i.y2);
  65528. writeXY (i.x3, i.y3);
  65529. out << "ct ";
  65530. lastX = i.x3;
  65531. lastY = i.y3;
  65532. break;
  65533. case Path::Iterator::closePath:
  65534. out << "cp ";
  65535. break;
  65536. default:
  65537. jassertfalse;
  65538. break;
  65539. }
  65540. }
  65541. out << '\n';
  65542. }
  65543. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  65544. {
  65545. out << "[ "
  65546. << trans.mat00 << ' '
  65547. << trans.mat10 << ' '
  65548. << trans.mat01 << ' '
  65549. << trans.mat11 << ' '
  65550. << trans.mat02 << ' '
  65551. << trans.mat12 << " ] concat ";
  65552. }
  65553. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  65554. {
  65555. stateStack.getLast()->fillType = fillType;
  65556. }
  65557. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  65558. {
  65559. }
  65560. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  65561. {
  65562. }
  65563. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  65564. {
  65565. if (stateStack.getLast()->fillType.isColour())
  65566. {
  65567. writeClip();
  65568. writeColour (stateStack.getLast()->fillType.colour);
  65569. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65570. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  65571. }
  65572. else
  65573. {
  65574. Path p;
  65575. p.addRectangle (r);
  65576. fillPath (p, AffineTransform::identity);
  65577. }
  65578. }
  65579. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  65580. {
  65581. if (stateStack.getLast()->fillType.isColour())
  65582. {
  65583. writeClip();
  65584. Path p (path);
  65585. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  65586. (float) stateStack.getLast()->yOffset));
  65587. writePath (p);
  65588. writeColour (stateStack.getLast()->fillType.colour);
  65589. out << "fill\n";
  65590. }
  65591. else if (stateStack.getLast()->fillType.isGradient())
  65592. {
  65593. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  65594. // postscript can't do semi-transparent ones.
  65595. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  65596. writeClip();
  65597. out << "gsave ";
  65598. {
  65599. Path p (path);
  65600. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65601. writePath (p);
  65602. out << "clip\n";
  65603. }
  65604. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  65605. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  65606. // time-being, this just fills it with the average colour..
  65607. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  65608. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  65609. out << "grestore\n";
  65610. }
  65611. }
  65612. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  65613. const int sx, const int sy,
  65614. const int maxW, const int maxH) const
  65615. {
  65616. out << "{<\n";
  65617. const int w = jmin (maxW, im.getWidth());
  65618. const int h = jmin (maxH, im.getHeight());
  65619. int charsOnLine = 0;
  65620. const Image::BitmapData srcData (im, 0, 0, w, h);
  65621. Colour pixel;
  65622. for (int y = h; --y >= 0;)
  65623. {
  65624. for (int x = 0; x < w; ++x)
  65625. {
  65626. const uint8* pixelData = srcData.getPixelPointer (x, y);
  65627. if (x >= sx && y >= sy)
  65628. {
  65629. if (im.isARGB())
  65630. {
  65631. PixelARGB p (*(const PixelARGB*) pixelData);
  65632. p.unpremultiply();
  65633. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  65634. }
  65635. else if (im.isRGB())
  65636. {
  65637. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  65638. }
  65639. else
  65640. {
  65641. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  65642. }
  65643. }
  65644. else
  65645. {
  65646. pixel = Colours::transparentWhite;
  65647. }
  65648. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  65649. out << String::toHexString (pixelValues, 3, 0);
  65650. charsOnLine += 3;
  65651. if (charsOnLine > 100)
  65652. {
  65653. out << '\n';
  65654. charsOnLine = 0;
  65655. }
  65656. }
  65657. }
  65658. out << "\n>}\n";
  65659. }
  65660. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  65661. const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  65662. {
  65663. const int w = jmin (sourceImage.getWidth(), srcClip.getRight());
  65664. const int h = jmin (sourceImage.getHeight(), srcClip.getBottom());
  65665. writeClip();
  65666. out << "gsave ";
  65667. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  65668. .scaled (1.0f, -1.0f));
  65669. RectangleList imageClip;
  65670. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  65671. imageClip.clipTo (srcClip);
  65672. out << "newpath ";
  65673. int itemsOnLine = 0;
  65674. for (RectangleList::Iterator i (imageClip); i.next();)
  65675. {
  65676. if (++itemsOnLine == 6)
  65677. {
  65678. out << '\n';
  65679. itemsOnLine = 0;
  65680. }
  65681. const Rectangle<int>& r = *i.getRectangle();
  65682. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  65683. }
  65684. out << " clip newpath\n";
  65685. out << w << ' ' << h << " scale\n";
  65686. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  65687. writeImage (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  65688. out << "false 3 colorimage grestore\n";
  65689. needToClip = true;
  65690. }
  65691. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  65692. {
  65693. Path p;
  65694. p.addLineSegment (line, 1.0f);
  65695. fillPath (p, AffineTransform::identity);
  65696. }
  65697. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  65698. {
  65699. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  65700. }
  65701. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  65702. {
  65703. drawLine (Line<float> (left, (float) y, right, (float) y));
  65704. }
  65705. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  65706. {
  65707. stateStack.getLast()->font = newFont;
  65708. }
  65709. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  65710. {
  65711. return stateStack.getLast()->font;
  65712. }
  65713. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  65714. {
  65715. Path p;
  65716. Font& font = stateStack.getLast()->font;
  65717. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  65718. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  65719. }
  65720. END_JUCE_NAMESPACE
  65721. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65722. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  65723. BEGIN_JUCE_NAMESPACE
  65724. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  65725. #define JUCE_USE_SSE_INSTRUCTIONS 1
  65726. #endif
  65727. #if JUCE_MSVC
  65728. #pragma warning (push)
  65729. #pragma warning (disable: 4127) // "expression is constant" warning
  65730. #if JUCE_DEBUG
  65731. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  65732. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  65733. #endif
  65734. #endif
  65735. namespace SoftwareRendererClasses
  65736. {
  65737. template <class PixelType, bool replaceExisting = false>
  65738. class SolidColourEdgeTableRenderer
  65739. {
  65740. public:
  65741. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  65742. : data (data_),
  65743. sourceColour (colour)
  65744. {
  65745. if (sizeof (PixelType) == 3)
  65746. {
  65747. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  65748. && sourceColour.getGreen() == sourceColour.getBlue();
  65749. filler[0].set (sourceColour);
  65750. filler[1].set (sourceColour);
  65751. filler[2].set (sourceColour);
  65752. filler[3].set (sourceColour);
  65753. }
  65754. }
  65755. forcedinline void setEdgeTableYPos (const int y) throw()
  65756. {
  65757. linePixels = (PixelType*) data.getLinePointer (y);
  65758. }
  65759. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65760. {
  65761. if (replaceExisting)
  65762. linePixels[x].set (sourceColour);
  65763. else
  65764. linePixels[x].blend (sourceColour, alphaLevel);
  65765. }
  65766. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  65767. {
  65768. if (replaceExisting)
  65769. linePixels[x].set (sourceColour);
  65770. else
  65771. linePixels[x].blend (sourceColour);
  65772. }
  65773. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  65774. {
  65775. PixelARGB p (sourceColour);
  65776. p.multiplyAlpha (alphaLevel);
  65777. PixelType* dest = linePixels + x;
  65778. if (replaceExisting || p.getAlpha() >= 0xff)
  65779. replaceLine (dest, p, width);
  65780. else
  65781. blendLine (dest, p, width);
  65782. }
  65783. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  65784. {
  65785. PixelType* dest = linePixels + x;
  65786. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  65787. replaceLine (dest, sourceColour, width);
  65788. else
  65789. blendLine (dest, sourceColour, width);
  65790. }
  65791. private:
  65792. const Image::BitmapData& data;
  65793. PixelType* linePixels;
  65794. PixelARGB sourceColour;
  65795. PixelRGB filler [4];
  65796. bool areRGBComponentsEqual;
  65797. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  65798. {
  65799. do
  65800. {
  65801. dest->blend (colour);
  65802. ++dest;
  65803. } while (--width > 0);
  65804. }
  65805. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  65806. {
  65807. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  65808. {
  65809. memset (dest, colour.getRed(), width * 3);
  65810. }
  65811. else
  65812. {
  65813. if (width >> 5)
  65814. {
  65815. const int* const intFiller = (const int*) filler;
  65816. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  65817. {
  65818. dest->set (colour);
  65819. ++dest;
  65820. --width;
  65821. }
  65822. while (width > 4)
  65823. {
  65824. ((int*) dest) [0] = intFiller[0];
  65825. ((int*) dest) [1] = intFiller[1];
  65826. ((int*) dest) [2] = intFiller[2];
  65827. dest = (PixelRGB*) (((uint8*) dest) + 12);
  65828. width -= 4;
  65829. }
  65830. }
  65831. while (--width >= 0)
  65832. {
  65833. dest->set (colour);
  65834. ++dest;
  65835. }
  65836. }
  65837. }
  65838. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  65839. {
  65840. memset (dest, colour.getAlpha(), width);
  65841. }
  65842. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  65843. {
  65844. do
  65845. {
  65846. dest->set (colour);
  65847. ++dest;
  65848. } while (--width > 0);
  65849. }
  65850. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  65851. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  65852. };
  65853. class LinearGradientPixelGenerator
  65854. {
  65855. public:
  65856. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  65857. : lookupTable (lookupTable_), numEntries (numEntries_)
  65858. {
  65859. jassert (numEntries_ >= 0);
  65860. Point<float> p1 (gradient.point1);
  65861. Point<float> p2 (gradient.point2);
  65862. if (! transform.isIdentity())
  65863. {
  65864. const Line<float> l (p2, p1);
  65865. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  65866. p1.applyTransform (transform);
  65867. p2.applyTransform (transform);
  65868. p3.applyTransform (transform);
  65869. const Line<float> l2 (p2, p3);
  65870. p2 = l2.getPointAlongLineProportionally (l2.findNearestPointTo (p1));
  65871. }
  65872. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  65873. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  65874. if (vertical)
  65875. {
  65876. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  65877. start = roundToInt (p1.getY() * scale);
  65878. }
  65879. else if (horizontal)
  65880. {
  65881. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  65882. start = roundToInt (p1.getX() * scale);
  65883. }
  65884. else
  65885. {
  65886. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  65887. yTerm = p1.getY() - p1.getX() / grad;
  65888. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  65889. grad *= scale;
  65890. }
  65891. }
  65892. forcedinline void setY (const int y) throw()
  65893. {
  65894. if (vertical)
  65895. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  65896. else if (! horizontal)
  65897. start = roundToInt ((y - yTerm) * grad);
  65898. }
  65899. inline const PixelARGB getPixel (const int x) const throw()
  65900. {
  65901. return vertical ? linePix
  65902. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  65903. }
  65904. private:
  65905. const PixelARGB* const lookupTable;
  65906. const int numEntries;
  65907. PixelARGB linePix;
  65908. int start, scale;
  65909. double grad, yTerm;
  65910. bool vertical, horizontal;
  65911. enum { numScaleBits = 12 };
  65912. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  65913. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  65914. };
  65915. class RadialGradientPixelGenerator
  65916. {
  65917. public:
  65918. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  65919. const PixelARGB* const lookupTable_, const int numEntries_)
  65920. : lookupTable (lookupTable_),
  65921. numEntries (numEntries_),
  65922. gx1 (gradient.point1.getX()),
  65923. gy1 (gradient.point1.getY())
  65924. {
  65925. jassert (numEntries_ >= 0);
  65926. const Point<float> diff (gradient.point1 - gradient.point2);
  65927. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  65928. invScale = numEntries / std::sqrt (maxDist);
  65929. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  65930. }
  65931. forcedinline void setY (const int y) throw()
  65932. {
  65933. dy = y - gy1;
  65934. dy *= dy;
  65935. }
  65936. inline const PixelARGB getPixel (const int px) const throw()
  65937. {
  65938. double x = px - gx1;
  65939. x *= x;
  65940. x += dy;
  65941. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  65942. }
  65943. protected:
  65944. const PixelARGB* const lookupTable;
  65945. const int numEntries;
  65946. const double gx1, gy1;
  65947. double maxDist, invScale, dy;
  65948. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  65949. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  65950. };
  65951. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  65952. {
  65953. public:
  65954. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  65955. const PixelARGB* const lookupTable_, const int numEntries_)
  65956. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  65957. inverseTransform (transform.inverted())
  65958. {
  65959. tM10 = inverseTransform.mat10;
  65960. tM00 = inverseTransform.mat00;
  65961. }
  65962. forcedinline void setY (const int y) throw()
  65963. {
  65964. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  65965. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  65966. }
  65967. inline const PixelARGB getPixel (const int px) const throw()
  65968. {
  65969. double x = px;
  65970. const double y = tM10 * x + lineYM11;
  65971. x = tM00 * x + lineYM01;
  65972. x *= x;
  65973. x += y * y;
  65974. if (x >= maxDist)
  65975. return lookupTable [numEntries];
  65976. else
  65977. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  65978. }
  65979. private:
  65980. double tM10, tM00, lineYM01, lineYM11;
  65981. const AffineTransform inverseTransform;
  65982. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  65983. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  65984. };
  65985. template <class PixelType, class GradientType>
  65986. class GradientEdgeTableRenderer : public GradientType
  65987. {
  65988. public:
  65989. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  65990. const PixelARGB* const lookupTable_, const int numEntries_)
  65991. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  65992. destData (destData_)
  65993. {
  65994. }
  65995. forcedinline void setEdgeTableYPos (const int y) throw()
  65996. {
  65997. linePixels = (PixelType*) destData.getLinePointer (y);
  65998. GradientType::setY (y);
  65999. }
  66000. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66001. {
  66002. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  66003. }
  66004. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66005. {
  66006. linePixels[x].blend (GradientType::getPixel (x));
  66007. }
  66008. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  66009. {
  66010. PixelType* dest = linePixels + x;
  66011. if (alphaLevel < 0xff)
  66012. {
  66013. do
  66014. {
  66015. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  66016. } while (--width > 0);
  66017. }
  66018. else
  66019. {
  66020. do
  66021. {
  66022. (dest++)->blend (GradientType::getPixel (x++));
  66023. } while (--width > 0);
  66024. }
  66025. }
  66026. void handleEdgeTableLineFull (int x, int width) const throw()
  66027. {
  66028. PixelType* dest = linePixels + x;
  66029. do
  66030. {
  66031. (dest++)->blend (GradientType::getPixel (x++));
  66032. } while (--width > 0);
  66033. }
  66034. private:
  66035. const Image::BitmapData& destData;
  66036. PixelType* linePixels;
  66037. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  66038. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  66039. };
  66040. static forcedinline int safeModulo (int n, const int divisor) throw()
  66041. {
  66042. jassert (divisor > 0);
  66043. n %= divisor;
  66044. return (n < 0) ? (n + divisor) : n;
  66045. }
  66046. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66047. class ImageFillEdgeTableRenderer
  66048. {
  66049. public:
  66050. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66051. const Image::BitmapData& srcData_,
  66052. const int extraAlpha_,
  66053. const int x, const int y)
  66054. : destData (destData_),
  66055. srcData (srcData_),
  66056. extraAlpha (extraAlpha_ + 1),
  66057. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  66058. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  66059. {
  66060. }
  66061. forcedinline void setEdgeTableYPos (int y) throw()
  66062. {
  66063. linePixels = (DestPixelType*) destData.getLinePointer (y);
  66064. y -= yOffset;
  66065. if (repeatPattern)
  66066. {
  66067. jassert (y >= 0);
  66068. y %= srcData.height;
  66069. }
  66070. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  66071. }
  66072. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  66073. {
  66074. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66075. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  66076. }
  66077. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66078. {
  66079. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  66080. }
  66081. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  66082. {
  66083. DestPixelType* dest = linePixels + x;
  66084. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66085. x -= xOffset;
  66086. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66087. if (alphaLevel < 0xfe)
  66088. {
  66089. do
  66090. {
  66091. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  66092. } while (--width > 0);
  66093. }
  66094. else
  66095. {
  66096. if (repeatPattern)
  66097. {
  66098. do
  66099. {
  66100. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66101. } while (--width > 0);
  66102. }
  66103. else
  66104. {
  66105. copyRow (dest, sourceLineStart + x, width);
  66106. }
  66107. }
  66108. }
  66109. void handleEdgeTableLineFull (int x, int width) const throw()
  66110. {
  66111. DestPixelType* dest = linePixels + x;
  66112. x -= xOffset;
  66113. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66114. if (extraAlpha < 0xfe)
  66115. {
  66116. do
  66117. {
  66118. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  66119. } while (--width > 0);
  66120. }
  66121. else
  66122. {
  66123. if (repeatPattern)
  66124. {
  66125. do
  66126. {
  66127. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66128. } while (--width > 0);
  66129. }
  66130. else
  66131. {
  66132. copyRow (dest, sourceLineStart + x, width);
  66133. }
  66134. }
  66135. }
  66136. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  66137. {
  66138. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  66139. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  66140. uint8* mask = (uint8*) (s + x - xOffset);
  66141. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  66142. mask += PixelARGB::indexA;
  66143. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  66144. }
  66145. private:
  66146. const Image::BitmapData& destData;
  66147. const Image::BitmapData& srcData;
  66148. const int extraAlpha, xOffset, yOffset;
  66149. DestPixelType* linePixels;
  66150. SrcPixelType* sourceLineStart;
  66151. template <class PixelType1, class PixelType2>
  66152. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  66153. {
  66154. do
  66155. {
  66156. dest++ ->blend (*src++);
  66157. } while (--width > 0);
  66158. }
  66159. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  66160. {
  66161. memcpy (dest, src, width * sizeof (PixelRGB));
  66162. }
  66163. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  66164. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  66165. };
  66166. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66167. class TransformedImageFillEdgeTableRenderer
  66168. {
  66169. public:
  66170. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66171. const Image::BitmapData& srcData_,
  66172. const AffineTransform& transform,
  66173. const int extraAlpha_,
  66174. const bool betterQuality_)
  66175. : interpolator (transform),
  66176. destData (destData_),
  66177. srcData (srcData_),
  66178. extraAlpha (extraAlpha_ + 1),
  66179. betterQuality (betterQuality_),
  66180. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  66181. pixelOffsetInt (betterQuality_ ? -128 : 0),
  66182. maxX (srcData_.width - 1),
  66183. maxY (srcData_.height - 1),
  66184. scratchSize (2048)
  66185. {
  66186. scratchBuffer.malloc (scratchSize);
  66187. }
  66188. ~TransformedImageFillEdgeTableRenderer()
  66189. {
  66190. }
  66191. forcedinline void setEdgeTableYPos (const int newY) throw()
  66192. {
  66193. y = newY;
  66194. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  66195. }
  66196. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  66197. {
  66198. alphaLevel *= extraAlpha;
  66199. alphaLevel >>= 8;
  66200. SrcPixelType p;
  66201. generate (&p, x, 1);
  66202. linePixels[x].blend (p, alphaLevel);
  66203. }
  66204. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  66205. {
  66206. SrcPixelType p;
  66207. generate (&p, x, 1);
  66208. linePixels[x].blend (p, extraAlpha);
  66209. }
  66210. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  66211. {
  66212. if (width > scratchSize)
  66213. {
  66214. scratchSize = width;
  66215. scratchBuffer.malloc (scratchSize);
  66216. }
  66217. SrcPixelType* span = scratchBuffer;
  66218. generate (span, x, width);
  66219. DestPixelType* dest = linePixels + x;
  66220. alphaLevel *= extraAlpha;
  66221. alphaLevel >>= 8;
  66222. if (alphaLevel < 0xfe)
  66223. {
  66224. do
  66225. {
  66226. dest++ ->blend (*span++, alphaLevel);
  66227. } while (--width > 0);
  66228. }
  66229. else
  66230. {
  66231. do
  66232. {
  66233. dest++ ->blend (*span++);
  66234. } while (--width > 0);
  66235. }
  66236. }
  66237. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  66238. {
  66239. handleEdgeTableLine (x, width, 255);
  66240. }
  66241. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  66242. {
  66243. if (width > scratchSize)
  66244. {
  66245. scratchSize = width;
  66246. scratchBuffer.malloc (scratchSize);
  66247. }
  66248. y = y_;
  66249. generate (scratchBuffer, x, width);
  66250. et.clipLineToMask (x, y_,
  66251. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  66252. sizeof (SrcPixelType), width);
  66253. }
  66254. private:
  66255. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  66256. {
  66257. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66258. do
  66259. {
  66260. int hiResX, hiResY;
  66261. this->interpolator.next (hiResX, hiResY);
  66262. hiResX += pixelOffsetInt;
  66263. hiResY += pixelOffsetInt;
  66264. int loResX = hiResX >> 8;
  66265. int loResY = hiResY >> 8;
  66266. if (repeatPattern)
  66267. {
  66268. loResX = safeModulo (loResX, srcData.width);
  66269. loResY = safeModulo (loResY, srcData.height);
  66270. }
  66271. if (betterQuality
  66272. && ((unsigned int) loResX) < (unsigned int) maxX
  66273. && ((unsigned int) loResY) < (unsigned int) maxY)
  66274. {
  66275. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  66276. hiResX &= 255;
  66277. hiResY &= 255;
  66278. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66279. uint32 weight = (256 - hiResX) * (256 - hiResY);
  66280. c[0] += weight * src[0];
  66281. c[1] += weight * src[1];
  66282. c[2] += weight * src[2];
  66283. c[3] += weight * src[3];
  66284. weight = hiResX * (256 - hiResY);
  66285. c[0] += weight * src[4];
  66286. c[1] += weight * src[5];
  66287. c[2] += weight * src[6];
  66288. c[3] += weight * src[7];
  66289. src += this->srcData.lineStride;
  66290. weight = (256 - hiResX) * hiResY;
  66291. c[0] += weight * src[0];
  66292. c[1] += weight * src[1];
  66293. c[2] += weight * src[2];
  66294. c[3] += weight * src[3];
  66295. weight = hiResX * hiResY;
  66296. c[0] += weight * src[4];
  66297. c[1] += weight * src[5];
  66298. c[2] += weight * src[6];
  66299. c[3] += weight * src[7];
  66300. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  66301. (uint8) (c[PixelARGB::indexR] >> 16),
  66302. (uint8) (c[PixelARGB::indexG] >> 16),
  66303. (uint8) (c[PixelARGB::indexB] >> 16));
  66304. }
  66305. else
  66306. {
  66307. if (! repeatPattern)
  66308. {
  66309. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66310. if (loResX < 0) loResX = 0;
  66311. if (loResY < 0) loResY = 0;
  66312. if (loResX > maxX) loResX = maxX;
  66313. if (loResY > maxY) loResY = maxY;
  66314. }
  66315. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  66316. }
  66317. ++dest;
  66318. } while (--numPixels > 0);
  66319. }
  66320. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  66321. {
  66322. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66323. do
  66324. {
  66325. int hiResX, hiResY;
  66326. this->interpolator.next (hiResX, hiResY);
  66327. hiResX += pixelOffsetInt;
  66328. hiResY += pixelOffsetInt;
  66329. int loResX = hiResX >> 8;
  66330. int loResY = hiResY >> 8;
  66331. if (repeatPattern)
  66332. {
  66333. loResX = safeModulo (loResX, srcData.width);
  66334. loResY = safeModulo (loResY, srcData.height);
  66335. }
  66336. if (betterQuality
  66337. && ((unsigned int) loResX) < (unsigned int) maxX
  66338. && ((unsigned int) loResY) < (unsigned int) maxY)
  66339. {
  66340. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  66341. hiResX &= 255;
  66342. hiResY &= 255;
  66343. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66344. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  66345. c[0] += weight * src[0];
  66346. c[1] += weight * src[1];
  66347. c[2] += weight * src[2];
  66348. weight = hiResX * (256 - hiResY);
  66349. c[0] += weight * src[3];
  66350. c[1] += weight * src[4];
  66351. c[2] += weight * src[5];
  66352. src += this->srcData.lineStride;
  66353. weight = (256 - hiResX) * hiResY;
  66354. c[0] += weight * src[0];
  66355. c[1] += weight * src[1];
  66356. c[2] += weight * src[2];
  66357. weight = hiResX * hiResY;
  66358. c[0] += weight * src[3];
  66359. c[1] += weight * src[4];
  66360. c[2] += weight * src[5];
  66361. dest->setARGB ((uint8) 255,
  66362. (uint8) (c[PixelRGB::indexR] >> 16),
  66363. (uint8) (c[PixelRGB::indexG] >> 16),
  66364. (uint8) (c[PixelRGB::indexB] >> 16));
  66365. }
  66366. else
  66367. {
  66368. if (! repeatPattern)
  66369. {
  66370. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66371. if (loResX < 0) loResX = 0;
  66372. if (loResY < 0) loResY = 0;
  66373. if (loResX > maxX) loResX = maxX;
  66374. if (loResY > maxY) loResY = maxY;
  66375. }
  66376. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  66377. }
  66378. ++dest;
  66379. } while (--numPixels > 0);
  66380. }
  66381. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  66382. {
  66383. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66384. do
  66385. {
  66386. int hiResX, hiResY;
  66387. this->interpolator.next (hiResX, hiResY);
  66388. hiResX += pixelOffsetInt;
  66389. hiResY += pixelOffsetInt;
  66390. int loResX = hiResX >> 8;
  66391. int loResY = hiResY >> 8;
  66392. if (repeatPattern)
  66393. {
  66394. loResX = safeModulo (loResX, srcData.width);
  66395. loResY = safeModulo (loResY, srcData.height);
  66396. }
  66397. if (betterQuality
  66398. && ((unsigned int) loResX) < (unsigned int) maxX
  66399. && ((unsigned int) loResY) < (unsigned int) maxY)
  66400. {
  66401. hiResX &= 255;
  66402. hiResY &= 255;
  66403. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66404. uint32 c = 256 * 128;
  66405. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  66406. c += src[1] * (hiResX * (256 - hiResY));
  66407. src += this->srcData.lineStride;
  66408. c += src[0] * ((256 - hiResX) * hiResY);
  66409. c += src[1] * (hiResX * hiResY);
  66410. *((uint8*) dest) = (uint8) c;
  66411. }
  66412. else
  66413. {
  66414. if (! repeatPattern)
  66415. {
  66416. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66417. if (loResX < 0) loResX = 0;
  66418. if (loResY < 0) loResY = 0;
  66419. if (loResX > maxX) loResX = maxX;
  66420. if (loResY > maxY) loResY = maxY;
  66421. }
  66422. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  66423. }
  66424. ++dest;
  66425. } while (--numPixels > 0);
  66426. }
  66427. class TransformedImageSpanInterpolator
  66428. {
  66429. public:
  66430. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  66431. : inverseTransform (transform.inverted())
  66432. {}
  66433. void setStartOfLine (float x, float y, const int numPixels) throw()
  66434. {
  66435. float x1 = x, y1 = y;
  66436. inverseTransform.transformPoint (x1, y1);
  66437. x += numPixels;
  66438. inverseTransform.transformPoint (x, y);
  66439. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  66440. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  66441. }
  66442. void next (int& x, int& y) throw()
  66443. {
  66444. x = xBresenham.n;
  66445. xBresenham.stepToNext();
  66446. y = yBresenham.n;
  66447. yBresenham.stepToNext();
  66448. }
  66449. private:
  66450. class BresenhamInterpolator
  66451. {
  66452. public:
  66453. BresenhamInterpolator() throw() {}
  66454. void set (const int n1, const int n2, const int numSteps_) throw()
  66455. {
  66456. numSteps = jmax (1, numSteps_);
  66457. step = (n2 - n1) / numSteps;
  66458. remainder = modulo = (n2 - n1) % numSteps;
  66459. n = n1;
  66460. if (modulo <= 0)
  66461. {
  66462. modulo += numSteps;
  66463. remainder += numSteps;
  66464. --step;
  66465. }
  66466. modulo -= numSteps;
  66467. }
  66468. forcedinline void stepToNext() throw()
  66469. {
  66470. modulo += remainder;
  66471. n += step;
  66472. if (modulo > 0)
  66473. {
  66474. modulo -= numSteps;
  66475. ++n;
  66476. }
  66477. }
  66478. int n;
  66479. private:
  66480. int numSteps, step, modulo, remainder;
  66481. };
  66482. const AffineTransform inverseTransform;
  66483. BresenhamInterpolator xBresenham, yBresenham;
  66484. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  66485. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  66486. };
  66487. TransformedImageSpanInterpolator interpolator;
  66488. const Image::BitmapData& destData;
  66489. const Image::BitmapData& srcData;
  66490. const int extraAlpha;
  66491. const bool betterQuality;
  66492. const float pixelOffset;
  66493. const int pixelOffsetInt, maxX, maxY;
  66494. int y;
  66495. DestPixelType* linePixels;
  66496. HeapBlock <SrcPixelType> scratchBuffer;
  66497. int scratchSize;
  66498. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  66499. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  66500. };
  66501. class ClipRegionBase : public ReferenceCountedObject
  66502. {
  66503. public:
  66504. ClipRegionBase() {}
  66505. virtual ~ClipRegionBase() {}
  66506. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  66507. virtual const Ptr clone() const = 0;
  66508. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  66509. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  66510. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  66511. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  66512. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  66513. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  66514. virtual const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t, const bool betterQuality) = 0;
  66515. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  66516. virtual const Rectangle<int> getClipBounds() const = 0;
  66517. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  66518. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  66519. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  66520. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  66521. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  66522. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  66523. protected:
  66524. template <class Iterator>
  66525. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  66526. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  66527. {
  66528. switch (destData.pixelFormat)
  66529. {
  66530. case Image::ARGB:
  66531. switch (srcData.pixelFormat)
  66532. {
  66533. case Image::ARGB:
  66534. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66535. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66536. break;
  66537. case Image::RGB:
  66538. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66539. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66540. break;
  66541. default:
  66542. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66543. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66544. break;
  66545. }
  66546. break;
  66547. case Image::RGB:
  66548. switch (srcData.pixelFormat)
  66549. {
  66550. case Image::ARGB:
  66551. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66552. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66553. break;
  66554. case Image::RGB:
  66555. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66556. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66557. break;
  66558. default:
  66559. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66560. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66561. break;
  66562. }
  66563. break;
  66564. default:
  66565. switch (srcData.pixelFormat)
  66566. {
  66567. case Image::ARGB:
  66568. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66569. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66570. break;
  66571. case Image::RGB:
  66572. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66573. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66574. break;
  66575. default:
  66576. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66577. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66578. break;
  66579. }
  66580. break;
  66581. }
  66582. }
  66583. template <class Iterator>
  66584. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  66585. {
  66586. switch (destData.pixelFormat)
  66587. {
  66588. case Image::ARGB:
  66589. switch (srcData.pixelFormat)
  66590. {
  66591. case Image::ARGB:
  66592. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66593. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66594. break;
  66595. case Image::RGB:
  66596. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66597. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66598. break;
  66599. default:
  66600. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66601. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66602. break;
  66603. }
  66604. break;
  66605. case Image::RGB:
  66606. switch (srcData.pixelFormat)
  66607. {
  66608. case Image::ARGB:
  66609. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66610. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66611. break;
  66612. case Image::RGB:
  66613. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66614. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66615. break;
  66616. default:
  66617. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66618. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66619. break;
  66620. }
  66621. break;
  66622. default:
  66623. switch (srcData.pixelFormat)
  66624. {
  66625. case Image::ARGB:
  66626. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66627. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66628. break;
  66629. case Image::RGB:
  66630. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66631. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66632. break;
  66633. default:
  66634. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66635. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66636. break;
  66637. }
  66638. break;
  66639. }
  66640. }
  66641. template <class Iterator, class DestPixelType>
  66642. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  66643. {
  66644. jassert (destData.pixelStride == sizeof (DestPixelType));
  66645. if (replaceContents)
  66646. {
  66647. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  66648. iter.iterate (r);
  66649. }
  66650. else
  66651. {
  66652. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  66653. iter.iterate (r);
  66654. }
  66655. }
  66656. template <class Iterator, class DestPixelType>
  66657. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  66658. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  66659. {
  66660. jassert (destData.pixelStride == sizeof (DestPixelType));
  66661. if (g.isRadial)
  66662. {
  66663. if (isIdentity)
  66664. {
  66665. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66666. iter.iterate (renderer);
  66667. }
  66668. else
  66669. {
  66670. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66671. iter.iterate (renderer);
  66672. }
  66673. }
  66674. else
  66675. {
  66676. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66677. iter.iterate (renderer);
  66678. }
  66679. }
  66680. };
  66681. class ClipRegion_EdgeTable : public ClipRegionBase
  66682. {
  66683. public:
  66684. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  66685. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  66686. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  66687. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  66688. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  66689. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  66690. ~ClipRegion_EdgeTable() {}
  66691. const Ptr clone() const
  66692. {
  66693. return new ClipRegion_EdgeTable (*this);
  66694. }
  66695. const Ptr applyClipTo (const Ptr& target) const
  66696. {
  66697. return target->clipToEdgeTable (edgeTable);
  66698. }
  66699. const Ptr clipToRectangle (const Rectangle<int>& r)
  66700. {
  66701. edgeTable.clipToRectangle (r);
  66702. return edgeTable.isEmpty() ? 0 : this;
  66703. }
  66704. const Ptr clipToRectangleList (const RectangleList& r)
  66705. {
  66706. RectangleList inverse (edgeTable.getMaximumBounds());
  66707. if (inverse.subtract (r))
  66708. for (RectangleList::Iterator iter (inverse); iter.next();)
  66709. edgeTable.excludeRectangle (*iter.getRectangle());
  66710. return edgeTable.isEmpty() ? 0 : this;
  66711. }
  66712. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  66713. {
  66714. edgeTable.excludeRectangle (r);
  66715. return edgeTable.isEmpty() ? 0 : this;
  66716. }
  66717. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  66718. {
  66719. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  66720. edgeTable.clipToEdgeTable (et);
  66721. return edgeTable.isEmpty() ? 0 : this;
  66722. }
  66723. const Ptr clipToEdgeTable (const EdgeTable& et)
  66724. {
  66725. edgeTable.clipToEdgeTable (et);
  66726. return edgeTable.isEmpty() ? 0 : this;
  66727. }
  66728. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  66729. {
  66730. const Image::BitmapData srcData (image, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66731. if (transform.isOnlyTranslation())
  66732. {
  66733. // If our translation doesn't involve any distortion, just use a simple blit..
  66734. const int tx = (int) (transform.getTranslationX() * 256.0f);
  66735. const int ty = (int) (transform.getTranslationY() * 256.0f);
  66736. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  66737. {
  66738. const int imageX = ((tx + 128) >> 8);
  66739. const int imageY = ((ty + 128) >> 8);
  66740. if (image.getFormat() == Image::ARGB)
  66741. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  66742. else
  66743. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  66744. return edgeTable.isEmpty() ? 0 : this;
  66745. }
  66746. }
  66747. if (transform.isSingularity())
  66748. return 0;
  66749. {
  66750. Path p;
  66751. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  66752. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  66753. edgeTable.clipToEdgeTable (et2);
  66754. }
  66755. if (! edgeTable.isEmpty())
  66756. {
  66757. if (image.getFormat() == Image::ARGB)
  66758. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  66759. else
  66760. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  66761. }
  66762. return edgeTable.isEmpty() ? 0 : this;
  66763. }
  66764. bool clipRegionIntersects (const Rectangle<int>& r) const
  66765. {
  66766. return edgeTable.getMaximumBounds().intersects (r);
  66767. }
  66768. const Rectangle<int> getClipBounds() const
  66769. {
  66770. return edgeTable.getMaximumBounds();
  66771. }
  66772. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  66773. {
  66774. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  66775. const Rectangle<int> clipped (totalClip.getIntersection (area));
  66776. if (! clipped.isEmpty())
  66777. {
  66778. ClipRegion_EdgeTable et (clipped);
  66779. et.edgeTable.clipToEdgeTable (edgeTable);
  66780. et.fillAllWithColour (destData, colour, replaceContents);
  66781. }
  66782. }
  66783. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  66784. {
  66785. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  66786. const Rectangle<float> clipped (totalClip.getIntersection (area));
  66787. if (! clipped.isEmpty())
  66788. {
  66789. ClipRegion_EdgeTable et (clipped);
  66790. et.edgeTable.clipToEdgeTable (edgeTable);
  66791. et.fillAllWithColour (destData, colour, false);
  66792. }
  66793. }
  66794. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  66795. {
  66796. switch (destData.pixelFormat)
  66797. {
  66798. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  66799. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  66800. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  66801. }
  66802. }
  66803. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  66804. {
  66805. HeapBlock <PixelARGB> lookupTable;
  66806. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  66807. jassert (numLookupEntries > 0);
  66808. switch (destData.pixelFormat)
  66809. {
  66810. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  66811. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  66812. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  66813. }
  66814. }
  66815. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  66816. {
  66817. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  66818. }
  66819. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  66820. {
  66821. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  66822. }
  66823. EdgeTable edgeTable;
  66824. private:
  66825. template <class SrcPixelType>
  66826. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  66827. {
  66828. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  66829. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  66830. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  66831. edgeTable.getMaximumBounds().getWidth());
  66832. }
  66833. template <class SrcPixelType>
  66834. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  66835. {
  66836. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  66837. edgeTable.clipToRectangle (r);
  66838. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  66839. for (int y = 0; y < r.getHeight(); ++y)
  66840. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  66841. }
  66842. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  66843. };
  66844. class ClipRegion_RectangleList : public ClipRegionBase
  66845. {
  66846. public:
  66847. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  66848. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  66849. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  66850. ~ClipRegion_RectangleList() {}
  66851. const Ptr clone() const
  66852. {
  66853. return new ClipRegion_RectangleList (*this);
  66854. }
  66855. const Ptr applyClipTo (const Ptr& target) const
  66856. {
  66857. return target->clipToRectangleList (clip);
  66858. }
  66859. const Ptr clipToRectangle (const Rectangle<int>& r)
  66860. {
  66861. clip.clipTo (r);
  66862. return clip.isEmpty() ? 0 : this;
  66863. }
  66864. const Ptr clipToRectangleList (const RectangleList& r)
  66865. {
  66866. clip.clipTo (r);
  66867. return clip.isEmpty() ? 0 : this;
  66868. }
  66869. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  66870. {
  66871. clip.subtract (r);
  66872. return clip.isEmpty() ? 0 : this;
  66873. }
  66874. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  66875. {
  66876. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  66877. }
  66878. const Ptr clipToEdgeTable (const EdgeTable& et)
  66879. {
  66880. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  66881. }
  66882. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  66883. {
  66884. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, srcClip, transform, betterQuality);
  66885. }
  66886. bool clipRegionIntersects (const Rectangle<int>& r) const
  66887. {
  66888. return clip.intersects (r);
  66889. }
  66890. const Rectangle<int> getClipBounds() const
  66891. {
  66892. return clip.getBounds();
  66893. }
  66894. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  66895. {
  66896. SubRectangleIterator iter (clip, area);
  66897. switch (destData.pixelFormat)
  66898. {
  66899. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  66900. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  66901. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  66902. }
  66903. }
  66904. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  66905. {
  66906. SubRectangleIteratorFloat iter (clip, area);
  66907. switch (destData.pixelFormat)
  66908. {
  66909. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  66910. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  66911. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  66912. }
  66913. }
  66914. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  66915. {
  66916. switch (destData.pixelFormat)
  66917. {
  66918. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  66919. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  66920. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  66921. }
  66922. }
  66923. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  66924. {
  66925. HeapBlock <PixelARGB> lookupTable;
  66926. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  66927. jassert (numLookupEntries > 0);
  66928. switch (destData.pixelFormat)
  66929. {
  66930. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  66931. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  66932. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  66933. }
  66934. }
  66935. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  66936. {
  66937. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  66938. }
  66939. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  66940. {
  66941. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  66942. }
  66943. RectangleList clip;
  66944. template <class Renderer>
  66945. void iterate (Renderer& r) const throw()
  66946. {
  66947. RectangleList::Iterator iter (clip);
  66948. while (iter.next())
  66949. {
  66950. const Rectangle<int> rect (*iter.getRectangle());
  66951. const int x = rect.getX();
  66952. const int w = rect.getWidth();
  66953. jassert (w > 0);
  66954. const int bottom = rect.getBottom();
  66955. for (int y = rect.getY(); y < bottom; ++y)
  66956. {
  66957. r.setEdgeTableYPos (y);
  66958. r.handleEdgeTableLineFull (x, w);
  66959. }
  66960. }
  66961. }
  66962. private:
  66963. class SubRectangleIterator
  66964. {
  66965. public:
  66966. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  66967. : clip (clip_), area (area_)
  66968. {
  66969. }
  66970. template <class Renderer>
  66971. void iterate (Renderer& r) const throw()
  66972. {
  66973. RectangleList::Iterator iter (clip);
  66974. while (iter.next())
  66975. {
  66976. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  66977. if (! rect.isEmpty())
  66978. {
  66979. const int x = rect.getX();
  66980. const int w = rect.getWidth();
  66981. const int bottom = rect.getBottom();
  66982. for (int y = rect.getY(); y < bottom; ++y)
  66983. {
  66984. r.setEdgeTableYPos (y);
  66985. r.handleEdgeTableLineFull (x, w);
  66986. }
  66987. }
  66988. }
  66989. }
  66990. private:
  66991. const RectangleList& clip;
  66992. const Rectangle<int> area;
  66993. SubRectangleIterator (const SubRectangleIterator&);
  66994. SubRectangleIterator& operator= (const SubRectangleIterator&);
  66995. };
  66996. class SubRectangleIteratorFloat
  66997. {
  66998. public:
  66999. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  67000. : clip (clip_), area (area_)
  67001. {
  67002. }
  67003. template <class Renderer>
  67004. void iterate (Renderer& r) const throw()
  67005. {
  67006. int left = roundToInt (area.getX() * 256.0f);
  67007. int top = roundToInt (area.getY() * 256.0f);
  67008. int right = roundToInt (area.getRight() * 256.0f);
  67009. int bottom = roundToInt (area.getBottom() * 256.0f);
  67010. int totalTop, totalLeft, totalBottom, totalRight;
  67011. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  67012. if ((top >> 8) == (bottom >> 8))
  67013. {
  67014. topAlpha = bottom - top;
  67015. bottomAlpha = 0;
  67016. totalTop = top >> 8;
  67017. totalBottom = bottom = top = totalTop + 1;
  67018. }
  67019. else
  67020. {
  67021. if ((top & 255) == 0)
  67022. {
  67023. topAlpha = 0;
  67024. top = totalTop = (top >> 8);
  67025. }
  67026. else
  67027. {
  67028. topAlpha = 255 - (top & 255);
  67029. totalTop = (top >> 8);
  67030. top = totalTop + 1;
  67031. }
  67032. bottomAlpha = bottom & 255;
  67033. bottom >>= 8;
  67034. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  67035. }
  67036. if ((left >> 8) == (right >> 8))
  67037. {
  67038. leftAlpha = right - left;
  67039. rightAlpha = 0;
  67040. totalLeft = (left >> 8);
  67041. totalRight = right = left = totalLeft + 1;
  67042. }
  67043. else
  67044. {
  67045. if ((left & 255) == 0)
  67046. {
  67047. leftAlpha = 0;
  67048. left = totalLeft = (left >> 8);
  67049. }
  67050. else
  67051. {
  67052. leftAlpha = 255 - (left & 255);
  67053. totalLeft = (left >> 8);
  67054. left = totalLeft + 1;
  67055. }
  67056. rightAlpha = right & 255;
  67057. right >>= 8;
  67058. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  67059. }
  67060. RectangleList::Iterator iter (clip);
  67061. while (iter.next())
  67062. {
  67063. const int clipLeft = iter.getRectangle()->getX();
  67064. const int clipRight = iter.getRectangle()->getRight();
  67065. const int clipTop = iter.getRectangle()->getY();
  67066. const int clipBottom = iter.getRectangle()->getBottom();
  67067. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  67068. {
  67069. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  67070. {
  67071. if (topAlpha != 0 && totalTop >= clipTop)
  67072. {
  67073. r.setEdgeTableYPos (totalTop);
  67074. r.handleEdgeTablePixel (left, topAlpha);
  67075. }
  67076. const int endY = jmin (bottom, clipBottom);
  67077. for (int y = jmax (clipTop, top); y < endY; ++y)
  67078. {
  67079. r.setEdgeTableYPos (y);
  67080. r.handleEdgeTablePixelFull (left);
  67081. }
  67082. if (bottomAlpha != 0 && bottom < clipBottom)
  67083. {
  67084. r.setEdgeTableYPos (bottom);
  67085. r.handleEdgeTablePixel (left, bottomAlpha);
  67086. }
  67087. }
  67088. else
  67089. {
  67090. const int clippedLeft = jmax (left, clipLeft);
  67091. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  67092. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  67093. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  67094. if (topAlpha != 0 && totalTop >= clipTop)
  67095. {
  67096. r.setEdgeTableYPos (totalTop);
  67097. if (doLeftAlpha)
  67098. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  67099. if (clippedWidth > 0)
  67100. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  67101. if (doRightAlpha)
  67102. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  67103. }
  67104. const int endY = jmin (bottom, clipBottom);
  67105. for (int y = jmax (clipTop, top); y < endY; ++y)
  67106. {
  67107. r.setEdgeTableYPos (y);
  67108. if (doLeftAlpha)
  67109. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  67110. if (clippedWidth > 0)
  67111. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  67112. if (doRightAlpha)
  67113. r.handleEdgeTablePixel (right, rightAlpha);
  67114. }
  67115. if (bottomAlpha != 0 && bottom < clipBottom)
  67116. {
  67117. r.setEdgeTableYPos (bottom);
  67118. if (doLeftAlpha)
  67119. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  67120. if (clippedWidth > 0)
  67121. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  67122. if (doRightAlpha)
  67123. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  67124. }
  67125. }
  67126. }
  67127. }
  67128. }
  67129. private:
  67130. const RectangleList& clip;
  67131. const Rectangle<float>& area;
  67132. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  67133. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  67134. };
  67135. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  67136. };
  67137. }
  67138. class LowLevelGraphicsSoftwareRenderer::SavedState
  67139. {
  67140. public:
  67141. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  67142. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67143. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67144. {
  67145. }
  67146. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  67147. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67148. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67149. {
  67150. }
  67151. SavedState (const SavedState& other)
  67152. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  67153. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  67154. {
  67155. }
  67156. ~SavedState()
  67157. {
  67158. }
  67159. void setOrigin (const int x, const int y) throw()
  67160. {
  67161. xOffset += x;
  67162. yOffset += y;
  67163. }
  67164. bool clipToRectangle (const Rectangle<int>& r)
  67165. {
  67166. if (clip != 0)
  67167. {
  67168. cloneClipIfMultiplyReferenced();
  67169. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  67170. }
  67171. return clip != 0;
  67172. }
  67173. bool clipToRectangleList (const RectangleList& r)
  67174. {
  67175. if (clip != 0)
  67176. {
  67177. cloneClipIfMultiplyReferenced();
  67178. RectangleList offsetList (r);
  67179. offsetList.offsetAll (xOffset, yOffset);
  67180. clip = clip->clipToRectangleList (offsetList);
  67181. }
  67182. return clip != 0;
  67183. }
  67184. bool excludeClipRectangle (const Rectangle<int>& r)
  67185. {
  67186. if (clip != 0)
  67187. {
  67188. cloneClipIfMultiplyReferenced();
  67189. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  67190. }
  67191. return clip != 0;
  67192. }
  67193. void clipToPath (const Path& p, const AffineTransform& transform)
  67194. {
  67195. if (clip != 0)
  67196. {
  67197. cloneClipIfMultiplyReferenced();
  67198. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  67199. }
  67200. }
  67201. void clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t)
  67202. {
  67203. if (clip != 0)
  67204. {
  67205. if (image.hasAlphaChannel())
  67206. {
  67207. cloneClipIfMultiplyReferenced();
  67208. clip = clip->clipToImageAlpha (image, srcClip, t.translated ((float) xOffset, (float) yOffset),
  67209. interpolationQuality != Graphics::lowResamplingQuality);
  67210. }
  67211. else
  67212. {
  67213. Path p;
  67214. p.addRectangle (srcClip);
  67215. clipToPath (p, t);
  67216. }
  67217. }
  67218. }
  67219. bool clipRegionIntersects (const Rectangle<int>& r) const
  67220. {
  67221. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  67222. }
  67223. const Rectangle<int> getClipBounds() const
  67224. {
  67225. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  67226. }
  67227. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  67228. {
  67229. if (clip != 0)
  67230. {
  67231. if (fillType.isColour())
  67232. {
  67233. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67234. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  67235. }
  67236. else
  67237. {
  67238. const Rectangle<int> totalClip (clip->getClipBounds());
  67239. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  67240. if (! clipped.isEmpty())
  67241. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  67242. }
  67243. }
  67244. }
  67245. void fillRect (Image& image, const Rectangle<float>& r)
  67246. {
  67247. if (clip != 0)
  67248. {
  67249. if (fillType.isColour())
  67250. {
  67251. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67252. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  67253. }
  67254. else
  67255. {
  67256. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  67257. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  67258. if (! clipped.isEmpty())
  67259. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  67260. }
  67261. }
  67262. }
  67263. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  67264. {
  67265. if (clip != 0)
  67266. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  67267. }
  67268. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  67269. {
  67270. if (clip != 0)
  67271. {
  67272. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  67273. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  67274. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  67275. fillShape (image, shapeToFill, false);
  67276. }
  67277. }
  67278. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  67279. {
  67280. jassert (clip != 0);
  67281. shapeToFill = clip->applyClipTo (shapeToFill);
  67282. if (shapeToFill != 0)
  67283. {
  67284. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67285. if (fillType.isGradient())
  67286. {
  67287. jassert (! replaceContents); // that option is just for solid colours
  67288. ColourGradient g2 (*(fillType.gradient));
  67289. g2.multiplyOpacity (fillType.getOpacity());
  67290. g2.point1.addXY (-0.5f, -0.5f);
  67291. g2.point2.addXY (-0.5f, -0.5f);
  67292. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  67293. const bool isIdentity = transform.isOnlyTranslation();
  67294. if (isIdentity)
  67295. {
  67296. // If our translation doesn't involve any distortion, we can speed it up..
  67297. g2.point1.applyTransform (transform);
  67298. g2.point2.applyTransform (transform);
  67299. transform = AffineTransform::identity;
  67300. }
  67301. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  67302. }
  67303. else if (fillType.isTiledImage())
  67304. {
  67305. renderImage (image, fillType.image, fillType.image.getBounds(), fillType.transform, shapeToFill);
  67306. }
  67307. else
  67308. {
  67309. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  67310. }
  67311. }
  67312. }
  67313. void renderImage (Image& destImage, const Image& sourceImage, const Rectangle<int>& srcClip,
  67314. const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  67315. {
  67316. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  67317. const Image::BitmapData destData (destImage, 0, 0, destImage.getWidth(), destImage.getHeight(), true);
  67318. const Image::BitmapData srcData (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  67319. const int alpha = fillType.colour.getAlpha();
  67320. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  67321. if (transform.isOnlyTranslation())
  67322. {
  67323. // If our translation doesn't involve any distortion, just use a simple blit..
  67324. int tx = (int) (transform.getTranslationX() * 256.0f);
  67325. int ty = (int) (transform.getTranslationY() * 256.0f);
  67326. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67327. {
  67328. tx = ((tx + 128) >> 8);
  67329. ty = ((ty + 128) >> 8);
  67330. if (tiledFillClipRegion != 0)
  67331. {
  67332. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  67333. }
  67334. else
  67335. {
  67336. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, srcClip.getWidth(), srcClip.getHeight()).getIntersection (destImage.getBounds())));
  67337. c = clip->applyClipTo (c);
  67338. if (c != 0)
  67339. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  67340. }
  67341. return;
  67342. }
  67343. }
  67344. if (transform.isSingularity())
  67345. return;
  67346. if (tiledFillClipRegion != 0)
  67347. {
  67348. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  67349. }
  67350. else
  67351. {
  67352. Path p;
  67353. p.addRectangle (srcClip);
  67354. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  67355. c = c->clipToPath (p, transform);
  67356. if (c != 0)
  67357. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  67358. }
  67359. }
  67360. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  67361. int xOffset, yOffset;
  67362. Font font;
  67363. FillType fillType;
  67364. Graphics::ResamplingQuality interpolationQuality;
  67365. private:
  67366. void cloneClipIfMultiplyReferenced()
  67367. {
  67368. if (clip->getReferenceCount() > 1)
  67369. clip = clip->clone();
  67370. }
  67371. SavedState& operator= (const SavedState&);
  67372. };
  67373. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  67374. : image (image_)
  67375. {
  67376. currentState = new SavedState (image_.getBounds(), 0, 0);
  67377. }
  67378. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  67379. const RectangleList& initialClip)
  67380. : image (image_)
  67381. {
  67382. currentState = new SavedState (initialClip, xOffset, yOffset);
  67383. }
  67384. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  67385. {
  67386. }
  67387. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  67388. {
  67389. return false;
  67390. }
  67391. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  67392. {
  67393. currentState->setOrigin (x, y);
  67394. }
  67395. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  67396. {
  67397. return currentState->clipToRectangle (r);
  67398. }
  67399. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67400. {
  67401. return currentState->clipToRectangleList (clipRegion);
  67402. }
  67403. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67404. {
  67405. currentState->excludeClipRectangle (r);
  67406. }
  67407. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67408. {
  67409. currentState->clipToPath (path, transform);
  67410. }
  67411. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  67412. {
  67413. currentState->clipToImageAlpha (sourceImage, srcClip, transform);
  67414. }
  67415. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67416. {
  67417. return currentState->clipRegionIntersects (r);
  67418. }
  67419. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  67420. {
  67421. return currentState->getClipBounds();
  67422. }
  67423. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  67424. {
  67425. return currentState->clip == 0;
  67426. }
  67427. void LowLevelGraphicsSoftwareRenderer::saveState()
  67428. {
  67429. stateStack.add (new SavedState (*currentState));
  67430. }
  67431. void LowLevelGraphicsSoftwareRenderer::restoreState()
  67432. {
  67433. SavedState* const top = stateStack.getLast();
  67434. if (top != 0)
  67435. {
  67436. currentState = top;
  67437. stateStack.removeLast (1, false);
  67438. }
  67439. else
  67440. {
  67441. jassertfalse; // trying to pop with an empty stack!
  67442. }
  67443. }
  67444. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  67445. {
  67446. currentState->fillType = fillType;
  67447. }
  67448. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  67449. {
  67450. currentState->fillType.setOpacity (newOpacity);
  67451. }
  67452. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  67453. {
  67454. currentState->interpolationQuality = quality;
  67455. }
  67456. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  67457. {
  67458. currentState->fillRect (image, r, replaceExistingContents);
  67459. }
  67460. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  67461. {
  67462. currentState->fillPath (image, path, transform);
  67463. }
  67464. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  67465. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  67466. {
  67467. jassert (sourceImage.getBounds().contains (srcClip));
  67468. currentState->renderImage (image, sourceImage, srcClip, transform,
  67469. fillEntireClipAsTiles ? currentState->clip : 0);
  67470. }
  67471. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  67472. {
  67473. Path p;
  67474. p.addLineSegment (line, 1.0f);
  67475. fillPath (p, AffineTransform::identity);
  67476. }
  67477. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  67478. {
  67479. if (bottom > top)
  67480. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  67481. }
  67482. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  67483. {
  67484. if (right > left)
  67485. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  67486. }
  67487. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  67488. {
  67489. public:
  67490. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  67491. ~CachedGlyph() {}
  67492. void draw (SavedState& state, Image& image, const float x, const float y) const
  67493. {
  67494. if (edgeTable != 0)
  67495. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  67496. }
  67497. void generate (const Font& newFont, const int glyphNumber)
  67498. {
  67499. font = newFont;
  67500. glyph = glyphNumber;
  67501. edgeTable = 0;
  67502. Path glyphPath;
  67503. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  67504. if (! glyphPath.isEmpty())
  67505. {
  67506. const float fontHeight = font.getHeight();
  67507. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  67508. .translated (0.0f, -0.5f));
  67509. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  67510. glyphPath, transform);
  67511. }
  67512. }
  67513. int glyph, lastAccessCount;
  67514. Font font;
  67515. juce_UseDebuggingNewOperator
  67516. private:
  67517. ScopedPointer <EdgeTable> edgeTable;
  67518. CachedGlyph (const CachedGlyph&);
  67519. CachedGlyph& operator= (const CachedGlyph&);
  67520. };
  67521. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  67522. {
  67523. public:
  67524. GlyphCache()
  67525. : accessCounter (0), hits (0), misses (0)
  67526. {
  67527. for (int i = 120; --i >= 0;)
  67528. glyphs.add (new CachedGlyph());
  67529. }
  67530. ~GlyphCache()
  67531. {
  67532. clearSingletonInstance();
  67533. }
  67534. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  67535. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  67536. {
  67537. ++accessCounter;
  67538. int oldestCounter = std::numeric_limits<int>::max();
  67539. CachedGlyph* oldest = 0;
  67540. for (int i = glyphs.size(); --i >= 0;)
  67541. {
  67542. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  67543. if (glyph->glyph == glyphNumber && glyph->font == font)
  67544. {
  67545. ++hits;
  67546. glyph->lastAccessCount = accessCounter;
  67547. glyph->draw (state, image, x, y);
  67548. return;
  67549. }
  67550. if (glyph->lastAccessCount <= oldestCounter)
  67551. {
  67552. oldestCounter = glyph->lastAccessCount;
  67553. oldest = glyph;
  67554. }
  67555. }
  67556. if (hits + ++misses > (glyphs.size() << 4))
  67557. {
  67558. if (misses * 2 > hits)
  67559. {
  67560. for (int i = 32; --i >= 0;)
  67561. glyphs.add (new CachedGlyph());
  67562. }
  67563. hits = misses = 0;
  67564. oldest = glyphs.getLast();
  67565. }
  67566. jassert (oldest != 0);
  67567. oldest->lastAccessCount = accessCounter;
  67568. oldest->generate (font, glyphNumber);
  67569. oldest->draw (state, image, x, y);
  67570. }
  67571. juce_UseDebuggingNewOperator
  67572. private:
  67573. friend class OwnedArray <CachedGlyph>;
  67574. OwnedArray <CachedGlyph> glyphs;
  67575. int accessCounter, hits, misses;
  67576. GlyphCache (const GlyphCache&);
  67577. GlyphCache& operator= (const GlyphCache&);
  67578. };
  67579. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  67580. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  67581. {
  67582. currentState->font = newFont;
  67583. }
  67584. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  67585. {
  67586. return currentState->font;
  67587. }
  67588. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67589. {
  67590. Font& f = currentState->font;
  67591. if (transform.isOnlyTranslation())
  67592. {
  67593. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  67594. transform.getTranslationX(),
  67595. transform.getTranslationY());
  67596. }
  67597. else
  67598. {
  67599. Path p;
  67600. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67601. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  67602. }
  67603. }
  67604. #if JUCE_MSVC
  67605. #pragma warning (pop)
  67606. #if JUCE_DEBUG
  67607. #pragma optimize ("", on) // resets optimisations to the project defaults
  67608. #endif
  67609. #endif
  67610. END_JUCE_NAMESPACE
  67611. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67612. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  67613. BEGIN_JUCE_NAMESPACE
  67614. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  67615. : flags (other.flags)
  67616. {
  67617. }
  67618. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  67619. {
  67620. flags = other.flags;
  67621. return *this;
  67622. }
  67623. void RectanglePlacement::applyTo (double& x, double& y,
  67624. double& w, double& h,
  67625. const double dx, const double dy,
  67626. const double dw, const double dh) const throw()
  67627. {
  67628. if (w == 0 || h == 0)
  67629. return;
  67630. if ((flags & stretchToFit) != 0)
  67631. {
  67632. x = dx;
  67633. y = dy;
  67634. w = dw;
  67635. h = dh;
  67636. }
  67637. else
  67638. {
  67639. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  67640. : jmin (dw / w, dh / h);
  67641. if ((flags & onlyReduceInSize) != 0)
  67642. scale = jmin (scale, 1.0);
  67643. if ((flags & onlyIncreaseInSize) != 0)
  67644. scale = jmax (scale, 1.0);
  67645. w *= scale;
  67646. h *= scale;
  67647. if ((flags & xLeft) != 0)
  67648. x = dx;
  67649. else if ((flags & xRight) != 0)
  67650. x = dx + dw - w;
  67651. else
  67652. x = dx + (dw - w) * 0.5;
  67653. if ((flags & yTop) != 0)
  67654. y = dy;
  67655. else if ((flags & yBottom) != 0)
  67656. y = dy + dh - h;
  67657. else
  67658. y = dy + (dh - h) * 0.5;
  67659. }
  67660. }
  67661. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  67662. float w, float h,
  67663. const float dx, const float dy,
  67664. const float dw, const float dh) const throw()
  67665. {
  67666. if (w == 0 || h == 0)
  67667. return AffineTransform::identity;
  67668. const float scaleX = dw / w;
  67669. const float scaleY = dh / h;
  67670. if ((flags & stretchToFit) != 0)
  67671. return AffineTransform::translation (-x, -y)
  67672. .scaled (scaleX, scaleY)
  67673. .translated (dx, dy);
  67674. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  67675. : jmin (scaleX, scaleY);
  67676. if ((flags & onlyReduceInSize) != 0)
  67677. scale = jmin (scale, 1.0f);
  67678. if ((flags & onlyIncreaseInSize) != 0)
  67679. scale = jmax (scale, 1.0f);
  67680. w *= scale;
  67681. h *= scale;
  67682. float newX = dx;
  67683. if ((flags & xRight) != 0)
  67684. newX += dw - w; // right
  67685. else if ((flags & xLeft) == 0)
  67686. newX += (dw - w) / 2.0f; // centre
  67687. float newY = dy;
  67688. if ((flags & yBottom) != 0)
  67689. newY += dh - h; // bottom
  67690. else if ((flags & yTop) == 0)
  67691. newY += (dh - h) / 2.0f; // centre
  67692. return AffineTransform::translation (-x, -y)
  67693. .scaled (scale, scale)
  67694. .translated (newX, newY);
  67695. }
  67696. END_JUCE_NAMESPACE
  67697. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  67698. /*** Start of inlined file: juce_Drawable.cpp ***/
  67699. BEGIN_JUCE_NAMESPACE
  67700. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  67701. const AffineTransform& transform_,
  67702. const float opacity_) throw()
  67703. : g (g_),
  67704. transform (transform_),
  67705. opacity (opacity_)
  67706. {
  67707. }
  67708. Drawable::Drawable()
  67709. : parent (0)
  67710. {
  67711. }
  67712. Drawable::~Drawable()
  67713. {
  67714. }
  67715. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  67716. {
  67717. render (RenderingContext (g, transform, opacity));
  67718. }
  67719. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  67720. {
  67721. draw (g, opacity, AffineTransform::translation (x, y));
  67722. }
  67723. void Drawable::drawWithin (Graphics& g,
  67724. const int destX,
  67725. const int destY,
  67726. const int destW,
  67727. const int destH,
  67728. const RectanglePlacement& placement,
  67729. const float opacity) const
  67730. {
  67731. if (destW > 0 && destH > 0)
  67732. {
  67733. Rectangle<float> bounds (getBounds());
  67734. draw (g, opacity,
  67735. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  67736. (float) destX, (float) destY,
  67737. (float) destW, (float) destH));
  67738. }
  67739. }
  67740. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  67741. {
  67742. Drawable* result = 0;
  67743. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  67744. if (image.isValid())
  67745. {
  67746. DrawableImage* const di = new DrawableImage();
  67747. di->setImage (image);
  67748. result = di;
  67749. }
  67750. else
  67751. {
  67752. const String asString (String::createStringFromData (data, (int) numBytes));
  67753. XmlDocument doc (asString);
  67754. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  67755. if (outer != 0 && outer->hasTagName ("svg"))
  67756. {
  67757. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  67758. if (svg != 0)
  67759. result = Drawable::createFromSVG (*svg);
  67760. }
  67761. }
  67762. return result;
  67763. }
  67764. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  67765. {
  67766. MemoryBlock mb;
  67767. dataSource.readIntoMemoryBlock (mb);
  67768. return createFromImageData (mb.getData(), mb.getSize());
  67769. }
  67770. Drawable* Drawable::createFromImageFile (const File& file)
  67771. {
  67772. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  67773. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  67774. }
  67775. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  67776. {
  67777. return createChildFromValueTree (0, tree, imageProvider);
  67778. }
  67779. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  67780. {
  67781. const Identifier type (tree.getType());
  67782. Drawable* d = 0;
  67783. if (type == DrawablePath::valueTreeType)
  67784. d = new DrawablePath();
  67785. else if (type == DrawableComposite::valueTreeType)
  67786. d = new DrawableComposite();
  67787. else if (type == DrawableImage::valueTreeType)
  67788. d = new DrawableImage();
  67789. else if (type == DrawableText::valueTreeType)
  67790. d = new DrawableText();
  67791. if (d != 0)
  67792. {
  67793. d->parent = parent;
  67794. d->refreshFromValueTree (tree, imageProvider);
  67795. }
  67796. return d;
  67797. }
  67798. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  67799. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  67800. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  67801. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  67802. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  67803. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  67804. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  67805. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  67806. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  67807. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  67808. : state (state_)
  67809. {
  67810. }
  67811. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  67812. {
  67813. }
  67814. const String Drawable::ValueTreeWrapperBase::getID() const
  67815. {
  67816. return state [idProperty];
  67817. }
  67818. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  67819. {
  67820. if (newID.isEmpty())
  67821. state.removeProperty (idProperty, undoManager);
  67822. else
  67823. state.setProperty (idProperty, newID, undoManager);
  67824. }
  67825. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2,
  67826. RelativeCoordinate::NamedCoordinateFinder* const nameFinder, ImageProvider* imageProvider)
  67827. {
  67828. const String newType (v[type].toString());
  67829. if (newType == "solid")
  67830. {
  67831. const String colourString (v [colour].toString());
  67832. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  67833. : (uint32) colourString.getHexValue32()));
  67834. }
  67835. else if (newType == "gradient")
  67836. {
  67837. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]);
  67838. ColourGradient g;
  67839. if (gp1 != 0)
  67840. *gp1 = p1;
  67841. if (gp2 != 0)
  67842. *gp2 = p2;
  67843. g.point1 = p1.resolve (nameFinder);
  67844. g.point2 = p2.resolve (nameFinder);
  67845. g.isRadial = v[radial];
  67846. StringArray colourSteps;
  67847. colourSteps.addTokens (v[colours].toString(), false);
  67848. for (int i = 0; i < colourSteps.size() / 2; ++i)
  67849. g.addColour (colourSteps[i * 2].getDoubleValue(),
  67850. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  67851. return FillType (g);
  67852. }
  67853. else if (newType == "image")
  67854. {
  67855. Image im;
  67856. if (imageProvider != 0)
  67857. im = imageProvider->getImageForIdentifier (v[imageId]);
  67858. FillType f (im, AffineTransform::identity);
  67859. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  67860. return f;
  67861. }
  67862. jassertfalse;
  67863. return FillType();
  67864. }
  67865. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  67866. const RelativePoint* const gp1, const RelativePoint* const gp2,
  67867. ImageProvider* imageProvider, UndoManager* const undoManager)
  67868. {
  67869. if (fillType.isColour())
  67870. {
  67871. v.setProperty (type, "solid", undoManager);
  67872. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  67873. }
  67874. else if (fillType.isGradient())
  67875. {
  67876. v.setProperty (type, "gradient", undoManager);
  67877. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  67878. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  67879. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  67880. String s;
  67881. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  67882. s << ' ' << fillType.gradient->getColourPosition (i)
  67883. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  67884. v.setProperty (colours, s.trimStart(), undoManager);
  67885. }
  67886. else if (fillType.isTiledImage())
  67887. {
  67888. v.setProperty (type, "image", undoManager);
  67889. if (imageProvider != 0)
  67890. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  67891. if (fillType.getOpacity() < 1.0f)
  67892. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  67893. else
  67894. v.removeProperty (imageOpacity, undoManager);
  67895. }
  67896. else
  67897. {
  67898. jassertfalse;
  67899. }
  67900. }
  67901. END_JUCE_NAMESPACE
  67902. /*** End of inlined file: juce_Drawable.cpp ***/
  67903. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  67904. BEGIN_JUCE_NAMESPACE
  67905. DrawableComposite::DrawableComposite()
  67906. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  67907. {
  67908. setContentArea (RelativeRectangle (RelativeCoordinate (0.0, true),
  67909. RelativeCoordinate (100.0, true),
  67910. RelativeCoordinate (0.0, false),
  67911. RelativeCoordinate (100.0, false)));
  67912. }
  67913. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  67914. {
  67915. bounds = other.bounds;
  67916. for (int i = 0; i < other.drawables.size(); ++i)
  67917. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  67918. markersX.addCopiesOf (other.markersX);
  67919. markersY.addCopiesOf (other.markersY);
  67920. }
  67921. DrawableComposite::~DrawableComposite()
  67922. {
  67923. }
  67924. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  67925. {
  67926. if (drawable != 0)
  67927. {
  67928. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  67929. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  67930. drawables.insert (index, drawable);
  67931. drawable->parent = this;
  67932. }
  67933. }
  67934. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  67935. {
  67936. insertDrawable (drawable.createCopy(), index);
  67937. }
  67938. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  67939. {
  67940. drawables.remove (index, deleteDrawable);
  67941. }
  67942. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  67943. {
  67944. for (int i = drawables.size(); --i >= 0;)
  67945. if (drawables.getUnchecked(i)->getName() == name)
  67946. return drawables.getUnchecked(i);
  67947. return 0;
  67948. }
  67949. void DrawableComposite::bringToFront (const int index)
  67950. {
  67951. if (index >= 0 && index < drawables.size() - 1)
  67952. drawables.move (index, -1);
  67953. }
  67954. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  67955. {
  67956. bounds = newBoundingBox;
  67957. }
  67958. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  67959. : name (other.name), position (other.position)
  67960. {
  67961. }
  67962. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  67963. : name (name_), position (position_)
  67964. {
  67965. }
  67966. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  67967. {
  67968. return name != other.name || position != other.position;
  67969. }
  67970. const char* const DrawableComposite::contentLeftMarkerName ("left");
  67971. const char* const DrawableComposite::contentRightMarkerName ("right");
  67972. const char* const DrawableComposite::contentTopMarkerName ("top");
  67973. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  67974. const RelativeRectangle DrawableComposite::getContentArea() const
  67975. {
  67976. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  67977. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  67978. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  67979. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  67980. }
  67981. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  67982. {
  67983. setMarker (contentLeftMarkerName, true, newArea.left);
  67984. setMarker (contentRightMarkerName, true, newArea.right);
  67985. setMarker (contentTopMarkerName, false, newArea.top);
  67986. setMarker (contentBottomMarkerName, false, newArea.bottom);
  67987. }
  67988. void DrawableComposite::resetBoundingBoxToContentArea()
  67989. {
  67990. const RelativeRectangle content (getContentArea());
  67991. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  67992. RelativePoint (content.right, content.top),
  67993. RelativePoint (content.left, content.bottom)));
  67994. }
  67995. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  67996. {
  67997. return (xAxis ? markersX : markersY).size();
  67998. }
  67999. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  68000. {
  68001. return (xAxis ? markersX : markersY) [index];
  68002. }
  68003. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  68004. {
  68005. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  68006. for (int i = 0; i < markers.size(); ++i)
  68007. {
  68008. Marker* const m = markers.getUnchecked(i);
  68009. if (m->name == name)
  68010. {
  68011. if (m->position != position)
  68012. {
  68013. m->position = position;
  68014. invalidatePoints();
  68015. }
  68016. return;
  68017. }
  68018. }
  68019. (xAxis ? markersX : markersY).add (new Marker (name, position));
  68020. invalidatePoints();
  68021. }
  68022. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  68023. {
  68024. jassert (index >= 2);
  68025. if (index >= 2)
  68026. (xAxis ? markersX : markersY).remove (index);
  68027. }
  68028. const AffineTransform DrawableComposite::calculateTransform() const
  68029. {
  68030. Point<float> resolved[3];
  68031. bounds.resolveThreePoints (resolved, parent);
  68032. const Rectangle<float> content (getContentArea().resolve (parent));
  68033. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  68034. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  68035. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  68036. }
  68037. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  68038. {
  68039. if (drawables.size() > 0 && context.opacity > 0)
  68040. {
  68041. if (context.opacity >= 1.0f || drawables.size() == 1)
  68042. {
  68043. Drawable::RenderingContext contextCopy (context);
  68044. contextCopy.transform = calculateTransform().followedBy (context.transform);
  68045. for (int i = 0; i < drawables.size(); ++i)
  68046. drawables.getUnchecked(i)->render (contextCopy);
  68047. }
  68048. else
  68049. {
  68050. // To correctly render a whole composite layer with an overall transparency,
  68051. // we need to render everything opaquely into a temp buffer, then blend that
  68052. // with the target opacity...
  68053. const Rectangle<int> clipBounds (context.g.getClipBounds());
  68054. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  68055. {
  68056. Graphics tempG (tempImage);
  68057. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  68058. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  68059. render (tempContext);
  68060. }
  68061. context.g.setOpacity (context.opacity);
  68062. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  68063. }
  68064. }
  68065. }
  68066. const RelativeCoordinate DrawableComposite::findNamedCoordinate (const String& objectName, const String& edge) const
  68067. {
  68068. if (objectName == RelativeCoordinate::Strings::parent)
  68069. {
  68070. if (edge == RelativeCoordinate::Strings::right)
  68071. {
  68072. jassertfalse; // a Drawable doesn't have a fixed right-hand edge - use a marker instead if you need a point of reference.
  68073. return RelativeCoordinate (100.0, true);
  68074. }
  68075. if (edge == RelativeCoordinate::Strings::bottom)
  68076. {
  68077. jassertfalse; // a Drawable doesn't have a fixed bottom edge - use a marker instead if you need a point of reference.
  68078. return RelativeCoordinate (100.0, false);
  68079. }
  68080. }
  68081. int i;
  68082. for (i = 0; i < markersX.size(); ++i)
  68083. {
  68084. Marker* const m = markersX.getUnchecked(i);
  68085. if (m->name == objectName)
  68086. return m->position;
  68087. }
  68088. for (i = 0; i < markersY.size(); ++i)
  68089. {
  68090. Marker* const m = markersY.getUnchecked(i);
  68091. if (m->name == objectName)
  68092. return m->position;
  68093. }
  68094. return RelativeCoordinate();
  68095. }
  68096. const Rectangle<float> DrawableComposite::getUntransformedBounds() const
  68097. {
  68098. Rectangle<float> bounds;
  68099. int i;
  68100. for (i = 0; i < drawables.size(); ++i)
  68101. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  68102. if (markersX.size() > 0)
  68103. {
  68104. float minX = std::numeric_limits<float>::max();
  68105. float maxX = std::numeric_limits<float>::min();
  68106. for (i = markersX.size(); --i >= 0;)
  68107. {
  68108. const Marker* m = markersX.getUnchecked(i);
  68109. const float pos = (float) m->position.resolve (parent);
  68110. minX = jmin (minX, pos);
  68111. maxX = jmax (maxX, pos);
  68112. }
  68113. if (minX <= maxX)
  68114. {
  68115. if (bounds.getWidth() == 0)
  68116. {
  68117. bounds.setLeft (minX);
  68118. bounds.setWidth (maxX - minX);
  68119. }
  68120. else
  68121. {
  68122. bounds.setLeft (jmin (bounds.getX(), minX));
  68123. bounds.setRight (jmax (bounds.getRight(), maxX));
  68124. }
  68125. }
  68126. }
  68127. if (markersY.size() > 0)
  68128. {
  68129. float minY = std::numeric_limits<float>::max();
  68130. float maxY = std::numeric_limits<float>::min();
  68131. for (i = markersY.size(); --i >= 0;)
  68132. {
  68133. const Marker* m = markersY.getUnchecked(i);
  68134. const float pos = (float) m->position.resolve (parent);
  68135. minY = jmin (minY, pos);
  68136. maxY = jmax (maxY, pos);
  68137. }
  68138. if (minY <= maxY)
  68139. {
  68140. if (bounds.getHeight() == 0)
  68141. {
  68142. bounds.setTop (minY);
  68143. bounds.setHeight (maxY - minY);
  68144. }
  68145. else
  68146. {
  68147. bounds.setTop (jmin (bounds.getY(), minY));
  68148. bounds.setBottom (jmax (bounds.getBottom(), maxY));
  68149. }
  68150. }
  68151. }
  68152. return bounds;
  68153. }
  68154. const Rectangle<float> DrawableComposite::getBounds() const
  68155. {
  68156. return getUntransformedBounds().transformed (calculateTransform());
  68157. }
  68158. bool DrawableComposite::hitTest (float x, float y) const
  68159. {
  68160. calculateTransform().inverted().transformPoint (x, y);
  68161. for (int i = 0; i < drawables.size(); ++i)
  68162. if (drawables.getUnchecked(i)->hitTest (x, y))
  68163. return true;
  68164. return false;
  68165. }
  68166. Drawable* DrawableComposite::createCopy() const
  68167. {
  68168. return new DrawableComposite (*this);
  68169. }
  68170. void DrawableComposite::invalidatePoints()
  68171. {
  68172. for (int i = 0; i < drawables.size(); ++i)
  68173. drawables.getUnchecked(i)->invalidatePoints();
  68174. }
  68175. const Identifier DrawableComposite::valueTreeType ("Group");
  68176. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  68177. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  68178. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  68179. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  68180. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  68181. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  68182. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  68183. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  68184. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  68185. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68186. : ValueTreeWrapperBase (state_)
  68187. {
  68188. jassert (state.hasType (valueTreeType));
  68189. }
  68190. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  68191. {
  68192. return state.getChildWithName (childGroupTag);
  68193. }
  68194. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  68195. {
  68196. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  68197. }
  68198. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  68199. {
  68200. return getChildList().getNumChildren();
  68201. }
  68202. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  68203. {
  68204. return getChildList().getChild (index);
  68205. }
  68206. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  68207. {
  68208. if (getID() == objectId)
  68209. return state;
  68210. if (! recursive)
  68211. {
  68212. return getChildList().getChildWithProperty (idProperty, objectId);
  68213. }
  68214. else
  68215. {
  68216. const ValueTree childList (getChildList());
  68217. for (int i = getNumDrawables(); --i >= 0;)
  68218. {
  68219. const ValueTree& child = childList.getChild (i);
  68220. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  68221. return child;
  68222. if (child.hasType (DrawableComposite::valueTreeType))
  68223. {
  68224. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  68225. if (v.isValid())
  68226. return v;
  68227. }
  68228. }
  68229. return ValueTree::invalid;
  68230. }
  68231. }
  68232. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  68233. {
  68234. return getChildList().indexOf (item);
  68235. }
  68236. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  68237. {
  68238. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  68239. }
  68240. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  68241. {
  68242. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  68243. }
  68244. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  68245. {
  68246. getChildList().removeChild (child, undoManager);
  68247. }
  68248. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  68249. {
  68250. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  68251. state.getProperty (topRight, "100, 0"),
  68252. state.getProperty (bottomLeft, "0, 100"));
  68253. }
  68254. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  68255. {
  68256. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  68257. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  68258. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  68259. }
  68260. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  68261. {
  68262. const RelativeRectangle content (getContentArea());
  68263. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  68264. RelativePoint (content.right, content.top),
  68265. RelativePoint (content.left, content.bottom)), undoManager);
  68266. }
  68267. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  68268. {
  68269. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  68270. getMarker (true, getMarkerState (true, 1)).position,
  68271. getMarker (false, getMarkerState (false, 0)).position,
  68272. getMarker (false, getMarkerState (false, 1)).position);
  68273. }
  68274. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  68275. {
  68276. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  68277. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  68278. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  68279. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  68280. }
  68281. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  68282. {
  68283. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  68284. }
  68285. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  68286. {
  68287. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  68288. }
  68289. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  68290. {
  68291. return getMarkerList (xAxis).getNumChildren();
  68292. }
  68293. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  68294. {
  68295. return getMarkerList (xAxis).getChild (index);
  68296. }
  68297. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  68298. {
  68299. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  68300. }
  68301. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  68302. {
  68303. return state.isAChildOf (getMarkerList (xAxis));
  68304. }
  68305. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  68306. {
  68307. jassert (containsMarker (xAxis, state));
  68308. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString(), xAxis));
  68309. }
  68310. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  68311. {
  68312. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  68313. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  68314. if (marker.isValid())
  68315. {
  68316. marker.setProperty (posProperty, m.position.toString(), undoManager);
  68317. }
  68318. else
  68319. {
  68320. marker = ValueTree (markerTag);
  68321. marker.setProperty (nameProperty, m.name, 0);
  68322. marker.setProperty (posProperty, m.position.toString(), 0);
  68323. markerList.addChild (marker, -1, undoManager);
  68324. }
  68325. }
  68326. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  68327. {
  68328. if (state [nameProperty].toString() != contentLeftMarkerName
  68329. && state [nameProperty].toString() != contentRightMarkerName
  68330. && state [nameProperty].toString() != contentTopMarkerName
  68331. && state [nameProperty].toString() != contentBottomMarkerName)
  68332. return getMarkerList (xAxis).removeChild (state, undoManager);
  68333. }
  68334. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68335. {
  68336. Rectangle<float> damageRect;
  68337. const ValueTreeWrapper wrapper (tree);
  68338. setName (wrapper.getID());
  68339. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  68340. bool redrawAll = false;
  68341. if (bounds != newBounds)
  68342. {
  68343. redrawAll = true;
  68344. damageRect = getUntransformedBounds();
  68345. bounds = newBounds;
  68346. }
  68347. const int numMarkersX = wrapper.getNumMarkers (true);
  68348. const int numMarkersY = wrapper.getNumMarkers (false);
  68349. // Remove deleted markers...
  68350. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  68351. {
  68352. if (damageRect.isEmpty())
  68353. damageRect = getUntransformedBounds();
  68354. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  68355. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  68356. }
  68357. // Update markers and add new ones..
  68358. int i;
  68359. for (i = 0; i < numMarkersX; ++i)
  68360. {
  68361. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  68362. Marker* m = markersX[i];
  68363. if (m == 0 || newMarker != *m)
  68364. {
  68365. redrawAll = true;
  68366. if (damageRect.isEmpty())
  68367. damageRect = getUntransformedBounds();
  68368. if (m == 0)
  68369. markersX.add (new Marker (newMarker));
  68370. else
  68371. *m = newMarker;
  68372. }
  68373. }
  68374. for (i = 0; i < numMarkersY; ++i)
  68375. {
  68376. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  68377. Marker* m = markersY[i];
  68378. if (m == 0 || newMarker != *m)
  68379. {
  68380. redrawAll = true;
  68381. if (damageRect.isEmpty())
  68382. damageRect = getUntransformedBounds();
  68383. if (m == 0)
  68384. markersY.add (new Marker (newMarker));
  68385. else
  68386. *m = newMarker;
  68387. }
  68388. }
  68389. // Remove deleted drawables..
  68390. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  68391. {
  68392. Drawable* const d = drawables.getUnchecked(i);
  68393. damageRect = damageRect.getUnion (d->getBounds());
  68394. d->parent = 0;
  68395. drawables.remove (i);
  68396. }
  68397. // Update drawables and add new ones..
  68398. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  68399. {
  68400. const ValueTree newDrawable (wrapper.getDrawableState (i));
  68401. Drawable* d = drawables[i];
  68402. if (d != 0)
  68403. {
  68404. if (newDrawable.hasType (d->getValueTreeType()))
  68405. {
  68406. damageRect = damageRect.getUnion (d->refreshFromValueTree (newDrawable, imageProvider));
  68407. }
  68408. else
  68409. {
  68410. damageRect = damageRect.getUnion (d->getBounds());
  68411. d = createChildFromValueTree (this, newDrawable, imageProvider);
  68412. drawables.set (i, d);
  68413. damageRect = damageRect.getUnion (d->getBounds());
  68414. }
  68415. }
  68416. else
  68417. {
  68418. d = createChildFromValueTree (this, newDrawable, imageProvider);
  68419. drawables.set (i, d);
  68420. damageRect = damageRect.getUnion (d->getBounds());
  68421. }
  68422. }
  68423. if (redrawAll)
  68424. damageRect = damageRect.getUnion (getUntransformedBounds());
  68425. return damageRect.transformed (calculateTransform());
  68426. }
  68427. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  68428. {
  68429. ValueTree tree (valueTreeType);
  68430. ValueTreeWrapper v (tree);
  68431. v.setID (getName(), 0);
  68432. v.setBoundingBox (bounds, 0);
  68433. int i;
  68434. for (i = 0; i < drawables.size(); ++i)
  68435. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  68436. for (i = 0; i < markersX.size(); ++i)
  68437. v.setMarker (true, *markersX.getUnchecked(i), 0);
  68438. for (i = 0; i < markersY.size(); ++i)
  68439. v.setMarker (false, *markersY.getUnchecked(i), 0);
  68440. return tree;
  68441. }
  68442. END_JUCE_NAMESPACE
  68443. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  68444. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  68445. BEGIN_JUCE_NAMESPACE
  68446. DrawableImage::DrawableImage()
  68447. : image (0),
  68448. opacity (1.0f),
  68449. overlayColour (0x00000000)
  68450. {
  68451. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  68452. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  68453. }
  68454. DrawableImage::DrawableImage (const DrawableImage& other)
  68455. : image (other.image),
  68456. opacity (other.opacity),
  68457. overlayColour (other.overlayColour),
  68458. bounds (other.bounds)
  68459. {
  68460. }
  68461. DrawableImage::~DrawableImage()
  68462. {
  68463. }
  68464. void DrawableImage::setImage (const Image& imageToUse)
  68465. {
  68466. image = imageToUse;
  68467. if (image.isValid())
  68468. {
  68469. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  68470. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  68471. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  68472. }
  68473. }
  68474. void DrawableImage::setOpacity (const float newOpacity)
  68475. {
  68476. opacity = newOpacity;
  68477. }
  68478. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  68479. {
  68480. overlayColour = newOverlayColour;
  68481. }
  68482. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  68483. {
  68484. bounds = newBounds;
  68485. }
  68486. const AffineTransform DrawableImage::calculateTransform() const
  68487. {
  68488. if (image.isNull())
  68489. return AffineTransform::identity;
  68490. Point<float> resolved[3];
  68491. bounds.resolveThreePoints (resolved, parent);
  68492. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  68493. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  68494. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  68495. tr.getX(), tr.getY(),
  68496. bl.getX(), bl.getY());
  68497. }
  68498. void DrawableImage::render (const Drawable::RenderingContext& context) const
  68499. {
  68500. if (image.isValid())
  68501. {
  68502. const AffineTransform t (calculateTransform().followedBy (context.transform));
  68503. if (opacity > 0.0f && ! overlayColour.isOpaque())
  68504. {
  68505. context.g.setOpacity (context.opacity * opacity);
  68506. context.g.drawImageTransformed (image, image.getBounds(), t, false);
  68507. }
  68508. if (! overlayColour.isTransparent())
  68509. {
  68510. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  68511. context.g.drawImageTransformed (image, image.getBounds(), t, true);
  68512. }
  68513. }
  68514. }
  68515. const Rectangle<float> DrawableImage::getBounds() const
  68516. {
  68517. if (image.isNull())
  68518. return Rectangle<float>();
  68519. return bounds.getBounds (parent);
  68520. }
  68521. bool DrawableImage::hitTest (float x, float y) const
  68522. {
  68523. if (image.isNull())
  68524. return false;
  68525. calculateTransform().inverted().transformPoint (x, y);
  68526. const int ix = roundToInt (x);
  68527. const int iy = roundToInt (y);
  68528. return ix >= 0
  68529. && iy >= 0
  68530. && ix < image.getWidth()
  68531. && iy < image.getHeight()
  68532. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  68533. }
  68534. Drawable* DrawableImage::createCopy() const
  68535. {
  68536. return new DrawableImage (*this);
  68537. }
  68538. void DrawableImage::invalidatePoints()
  68539. {
  68540. }
  68541. const Identifier DrawableImage::valueTreeType ("Image");
  68542. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  68543. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  68544. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  68545. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  68546. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  68547. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  68548. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68549. : ValueTreeWrapperBase (state_)
  68550. {
  68551. jassert (state.hasType (valueTreeType));
  68552. }
  68553. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  68554. {
  68555. return state [image];
  68556. }
  68557. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  68558. {
  68559. return state.getPropertyAsValue (image, undoManager);
  68560. }
  68561. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  68562. {
  68563. state.setProperty (image, newIdentifier, undoManager);
  68564. }
  68565. float DrawableImage::ValueTreeWrapper::getOpacity() const
  68566. {
  68567. return (float) state.getProperty (opacity, 1.0);
  68568. }
  68569. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  68570. {
  68571. if (! state.hasProperty (opacity))
  68572. state.setProperty (opacity, 1.0, undoManager);
  68573. return state.getPropertyAsValue (opacity, undoManager);
  68574. }
  68575. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  68576. {
  68577. state.setProperty (opacity, newOpacity, undoManager);
  68578. }
  68579. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  68580. {
  68581. return Colour (state [overlay].toString().getHexValue32());
  68582. }
  68583. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  68584. {
  68585. if (newColour.isTransparent())
  68586. state.removeProperty (overlay, undoManager);
  68587. else
  68588. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  68589. }
  68590. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  68591. {
  68592. return state.getPropertyAsValue (overlay, undoManager);
  68593. }
  68594. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  68595. {
  68596. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  68597. state.getProperty (topRight, "100, 0"),
  68598. state.getProperty (bottomLeft, "0, 100"));
  68599. }
  68600. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  68601. {
  68602. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  68603. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  68604. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  68605. }
  68606. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68607. {
  68608. const ValueTreeWrapper controller (tree);
  68609. setName (controller.getID());
  68610. const float newOpacity = controller.getOpacity();
  68611. const Colour newOverlayColour (controller.getOverlayColour());
  68612. Image newImage;
  68613. const var imageIdentifier (controller.getImageIdentifier());
  68614. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  68615. if (imageProvider != 0)
  68616. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  68617. const RelativeParallelogram newBounds (controller.getBoundingBox());
  68618. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  68619. {
  68620. const Rectangle<float> damage (getBounds());
  68621. opacity = newOpacity;
  68622. overlayColour = newOverlayColour;
  68623. bounds = newBounds;
  68624. image = newImage;
  68625. return damage.getUnion (getBounds());
  68626. }
  68627. return Rectangle<float>();
  68628. }
  68629. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  68630. {
  68631. ValueTree tree (valueTreeType);
  68632. ValueTreeWrapper v (tree);
  68633. v.setID (getName(), 0);
  68634. v.setOpacity (opacity, 0);
  68635. v.setOverlayColour (overlayColour, 0);
  68636. v.setBoundingBox (bounds, 0);
  68637. if (image.isValid())
  68638. {
  68639. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  68640. if (imageProvider != 0)
  68641. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  68642. }
  68643. return tree;
  68644. }
  68645. END_JUCE_NAMESPACE
  68646. /*** End of inlined file: juce_DrawableImage.cpp ***/
  68647. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  68648. BEGIN_JUCE_NAMESPACE
  68649. DrawablePath::DrawablePath()
  68650. : mainFill (Colours::black),
  68651. strokeFill (Colours::transparentBlack),
  68652. strokeType (0.0f),
  68653. pathNeedsUpdating (true),
  68654. strokeNeedsUpdating (true)
  68655. {
  68656. }
  68657. DrawablePath::DrawablePath (const DrawablePath& other)
  68658. : mainFill (other.mainFill),
  68659. strokeFill (other.strokeFill),
  68660. strokeType (other.strokeType),
  68661. pathNeedsUpdating (true),
  68662. strokeNeedsUpdating (true)
  68663. {
  68664. if (other.relativePath != 0)
  68665. relativePath = new RelativePointPath (*other.relativePath);
  68666. else
  68667. path = other.path;
  68668. }
  68669. DrawablePath::~DrawablePath()
  68670. {
  68671. }
  68672. void DrawablePath::setPath (const Path& newPath)
  68673. {
  68674. path = newPath;
  68675. strokeNeedsUpdating = true;
  68676. }
  68677. void DrawablePath::setFill (const FillType& newFill)
  68678. {
  68679. mainFill = newFill;
  68680. }
  68681. void DrawablePath::setStrokeFill (const FillType& newFill)
  68682. {
  68683. strokeFill = newFill;
  68684. }
  68685. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  68686. {
  68687. strokeType = newStrokeType;
  68688. strokeNeedsUpdating = true;
  68689. }
  68690. void DrawablePath::setStrokeThickness (const float newThickness)
  68691. {
  68692. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  68693. }
  68694. void DrawablePath::updatePath() const
  68695. {
  68696. if (pathNeedsUpdating)
  68697. {
  68698. pathNeedsUpdating = false;
  68699. if (relativePath != 0)
  68700. {
  68701. path.clear();
  68702. relativePath->createPath (path, parent);
  68703. strokeNeedsUpdating = true;
  68704. }
  68705. }
  68706. }
  68707. void DrawablePath::updateStroke() const
  68708. {
  68709. if (strokeNeedsUpdating)
  68710. {
  68711. strokeNeedsUpdating = false;
  68712. updatePath();
  68713. stroke.clear();
  68714. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  68715. }
  68716. }
  68717. const Path& DrawablePath::getPath() const
  68718. {
  68719. updatePath();
  68720. return path;
  68721. }
  68722. const Path& DrawablePath::getStrokePath() const
  68723. {
  68724. updateStroke();
  68725. return stroke;
  68726. }
  68727. bool DrawablePath::isStrokeVisible() const throw()
  68728. {
  68729. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  68730. }
  68731. void DrawablePath::invalidatePoints()
  68732. {
  68733. pathNeedsUpdating = true;
  68734. strokeNeedsUpdating = true;
  68735. }
  68736. void DrawablePath::render (const Drawable::RenderingContext& context) const
  68737. {
  68738. {
  68739. FillType f (mainFill);
  68740. if (f.isGradient())
  68741. f.gradient->multiplyOpacity (context.opacity);
  68742. f.transform = f.transform.followedBy (context.transform);
  68743. context.g.setFillType (f);
  68744. context.g.fillPath (getPath(), context.transform);
  68745. }
  68746. if (isStrokeVisible())
  68747. {
  68748. FillType f (strokeFill);
  68749. if (f.isGradient())
  68750. f.gradient->multiplyOpacity (context.opacity);
  68751. f.transform = f.transform.followedBy (context.transform);
  68752. context.g.setFillType (f);
  68753. context.g.fillPath (getStrokePath(), context.transform);
  68754. }
  68755. }
  68756. const Rectangle<float> DrawablePath::getBounds() const
  68757. {
  68758. if (isStrokeVisible())
  68759. return getStrokePath().getBounds();
  68760. else
  68761. return getPath().getBounds();
  68762. }
  68763. bool DrawablePath::hitTest (float x, float y) const
  68764. {
  68765. return getPath().contains (x, y)
  68766. || (isStrokeVisible() && getStrokePath().contains (x, y));
  68767. }
  68768. Drawable* DrawablePath::createCopy() const
  68769. {
  68770. return new DrawablePath (*this);
  68771. }
  68772. const Identifier DrawablePath::valueTreeType ("Path");
  68773. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  68774. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  68775. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  68776. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  68777. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  68778. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  68779. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  68780. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  68781. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  68782. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  68783. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68784. : ValueTreeWrapperBase (state_)
  68785. {
  68786. jassert (state.hasType (valueTreeType));
  68787. }
  68788. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  68789. {
  68790. return state.getOrCreateChildWithName (path, 0);
  68791. }
  68792. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  68793. {
  68794. ValueTree v (state.getChildWithName (fill));
  68795. if (v.isValid())
  68796. return v;
  68797. setMainFill (Colours::black, 0, 0, 0, 0);
  68798. return getMainFillState();
  68799. }
  68800. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  68801. {
  68802. ValueTree v (state.getChildWithName (stroke));
  68803. if (v.isValid())
  68804. return v;
  68805. setStrokeFill (Colours::black, 0, 0, 0, 0);
  68806. return getStrokeFillState();
  68807. }
  68808. const FillType DrawablePath::ValueTreeWrapper::getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  68809. ImageProvider* imageProvider) const
  68810. {
  68811. return readFillType (state.getChildWithName (fill), 0, 0, nameFinder, imageProvider);
  68812. }
  68813. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  68814. const RelativePoint* gp2, ImageProvider* imageProvider, UndoManager* undoManager)
  68815. {
  68816. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  68817. writeFillType (v, newFill, gp1, gp2, imageProvider, undoManager);
  68818. }
  68819. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  68820. ImageProvider* imageProvider) const
  68821. {
  68822. return readFillType (state.getChildWithName (stroke), 0, 0, nameFinder, imageProvider);
  68823. }
  68824. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  68825. const RelativePoint* gp2, ImageProvider* imageProvider, UndoManager* undoManager)
  68826. {
  68827. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  68828. writeFillType (v, newFill, gp1, gp2, imageProvider, undoManager);
  68829. }
  68830. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  68831. {
  68832. const String jointStyleString (state [jointStyle].toString());
  68833. const String capStyleString (state [capStyle].toString());
  68834. return PathStrokeType (state [strokeWidth],
  68835. jointStyleString == "curved" ? PathStrokeType::curved
  68836. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  68837. : PathStrokeType::mitered),
  68838. capStyleString == "square" ? PathStrokeType::square
  68839. : (capStyleString == "round" ? PathStrokeType::rounded
  68840. : PathStrokeType::butt));
  68841. }
  68842. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  68843. {
  68844. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  68845. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  68846. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  68847. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  68848. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  68849. }
  68850. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  68851. {
  68852. return state [nonZeroWinding];
  68853. }
  68854. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  68855. {
  68856. state.setProperty (nonZeroWinding, b, undoManager);
  68857. }
  68858. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  68859. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  68860. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  68861. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  68862. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  68863. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  68864. : state (state_)
  68865. {
  68866. }
  68867. DrawablePath::ValueTreeWrapper::Element::~Element()
  68868. {
  68869. }
  68870. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  68871. {
  68872. return ValueTreeWrapper (state.getParent().getParent());
  68873. }
  68874. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  68875. {
  68876. const Identifier i (state.getType());
  68877. if (i == startSubPathElement || i == lineToElement) return 1;
  68878. if (i == quadraticToElement) return 2;
  68879. if (i == cubicToElement) return 3;
  68880. return 0;
  68881. }
  68882. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  68883. {
  68884. jassert (index >= 0 && index < getNumControlPoints());
  68885. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  68886. }
  68887. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  68888. {
  68889. jassert (index >= 0 && index < getNumControlPoints());
  68890. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  68891. }
  68892. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  68893. {
  68894. jassert (index >= 0 && index < getNumControlPoints());
  68895. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  68896. }
  68897. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  68898. {
  68899. const Identifier i (state.getType());
  68900. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  68901. if (i == quadraticToElement) return getControlPoint (1);
  68902. if (i == cubicToElement) return getControlPoint (2);
  68903. return RelativePoint();
  68904. }
  68905. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68906. {
  68907. Rectangle<float> damageRect;
  68908. ValueTreeWrapper v (tree);
  68909. setName (v.getID());
  68910. bool needsRedraw = false;
  68911. const FillType newFill (v.getMainFill (parent, imageProvider));
  68912. if (mainFill != newFill)
  68913. {
  68914. needsRedraw = true;
  68915. mainFill = newFill;
  68916. }
  68917. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  68918. if (strokeFill != newStrokeFill)
  68919. {
  68920. needsRedraw = true;
  68921. strokeFill = newStrokeFill;
  68922. }
  68923. const PathStrokeType newStroke (v.getStrokeType());
  68924. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  68925. Path newPath;
  68926. newRelativePath->createPath (newPath, parent);
  68927. if (! newRelativePath->containsAnyDynamicPoints())
  68928. newRelativePath = 0;
  68929. if (strokeType != newStroke || path != newPath)
  68930. {
  68931. damageRect = getBounds();
  68932. path.swapWithPath (newPath);
  68933. strokeNeedsUpdating = true;
  68934. strokeType = newStroke;
  68935. needsRedraw = true;
  68936. }
  68937. relativePath = newRelativePath.release();
  68938. if (needsRedraw)
  68939. damageRect = damageRect.getUnion (getBounds());
  68940. return damageRect;
  68941. }
  68942. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  68943. {
  68944. ValueTree tree (valueTreeType);
  68945. ValueTreeWrapper v (tree);
  68946. v.setID (getName(), 0);
  68947. v.setMainFill (mainFill, 0, 0, imageProvider, 0);
  68948. v.setStrokeFill (strokeFill, 0, 0, imageProvider, 0);
  68949. v.setStrokeType (strokeType, 0);
  68950. if (relativePath != 0)
  68951. {
  68952. relativePath->writeTo (tree, 0);
  68953. }
  68954. else
  68955. {
  68956. RelativePointPath rp (path);
  68957. rp.writeTo (tree, 0);
  68958. }
  68959. return tree;
  68960. }
  68961. END_JUCE_NAMESPACE
  68962. /*** End of inlined file: juce_DrawablePath.cpp ***/
  68963. /*** Start of inlined file: juce_DrawableText.cpp ***/
  68964. BEGIN_JUCE_NAMESPACE
  68965. DrawableText::DrawableText()
  68966. : colour (Colours::black),
  68967. justification (Justification::centredLeft)
  68968. {
  68969. setFont (Font (15.0f), true);
  68970. }
  68971. DrawableText::DrawableText (const DrawableText& other)
  68972. : text (other.text),
  68973. font (other.font),
  68974. colour (other.colour),
  68975. justification (other.justification),
  68976. bounds (other.bounds),
  68977. fontSizeControlPoint (other.fontSizeControlPoint)
  68978. {
  68979. }
  68980. DrawableText::~DrawableText()
  68981. {
  68982. }
  68983. void DrawableText::setText (const String& newText)
  68984. {
  68985. text = newText;
  68986. }
  68987. void DrawableText::setColour (const Colour& newColour)
  68988. {
  68989. colour = newColour;
  68990. }
  68991. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  68992. {
  68993. font = newFont;
  68994. if (applySizeAndScale)
  68995. {
  68996. Point<float> corners[3];
  68997. bounds.resolveThreePoints (corners, parent);
  68998. setFontSizeControlPoint (RelativePoint (bounds.getPointForInternalCoord (corners,
  68999. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  69000. }
  69001. }
  69002. void DrawableText::setJustification (const Justification& newJustification)
  69003. {
  69004. justification = newJustification;
  69005. }
  69006. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  69007. {
  69008. bounds = newBounds;
  69009. }
  69010. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  69011. {
  69012. fontSizeControlPoint = newPoint;
  69013. }
  69014. void DrawableText::render (const Drawable::RenderingContext& context) const
  69015. {
  69016. Point<float> points[3];
  69017. bounds.resolveThreePoints (points, parent);
  69018. const float w = Line<float> (points[0], points[1]).getLength();
  69019. const float h = Line<float> (points[0], points[2]).getLength();
  69020. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  69021. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  69022. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  69023. Font f (font);
  69024. f.setHeight (fontHeight);
  69025. f.setHorizontalScale (fontWidth / fontHeight);
  69026. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  69027. GlyphArrangement ga;
  69028. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  69029. ga.draw (context.g,
  69030. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  69031. w, 0, points[1].getX(), points[1].getY(),
  69032. 0, h, points[2].getX(), points[2].getY())
  69033. .followedBy (context.transform));
  69034. }
  69035. const Rectangle<float> DrawableText::getBounds() const
  69036. {
  69037. return bounds.getBounds (parent);
  69038. }
  69039. bool DrawableText::hitTest (float x, float y) const
  69040. {
  69041. Path p;
  69042. bounds.getPath (p, parent);
  69043. return p.contains (x, y);
  69044. }
  69045. Drawable* DrawableText::createCopy() const
  69046. {
  69047. return new DrawableText (*this);
  69048. }
  69049. void DrawableText::invalidatePoints()
  69050. {
  69051. }
  69052. const Identifier DrawableText::valueTreeType ("Text");
  69053. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  69054. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  69055. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  69056. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  69057. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  69058. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  69059. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69060. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  69061. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69062. : ValueTreeWrapperBase (state_)
  69063. {
  69064. jassert (state.hasType (valueTreeType));
  69065. }
  69066. const String DrawableText::ValueTreeWrapper::getText() const
  69067. {
  69068. return state [text].toString();
  69069. }
  69070. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  69071. {
  69072. state.setProperty (text, newText, undoManager);
  69073. }
  69074. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  69075. {
  69076. return state.getPropertyAsValue (text, undoManager);
  69077. }
  69078. const Colour DrawableText::ValueTreeWrapper::getColour() const
  69079. {
  69080. return Colour::fromString (state [colour].toString());
  69081. }
  69082. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  69083. {
  69084. state.setProperty (colour, newColour.toString(), undoManager);
  69085. }
  69086. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  69087. {
  69088. return Justification ((int) state [justification]);
  69089. }
  69090. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  69091. {
  69092. state.setProperty (justification, newJustification.getFlags(), undoManager);
  69093. }
  69094. const Font DrawableText::ValueTreeWrapper::getFont() const
  69095. {
  69096. return Font::fromString (state [font]);
  69097. }
  69098. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  69099. {
  69100. state.setProperty (font, newFont.toString(), undoManager);
  69101. }
  69102. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  69103. {
  69104. return state.getPropertyAsValue (font, undoManager);
  69105. }
  69106. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  69107. {
  69108. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  69109. }
  69110. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69111. {
  69112. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69113. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69114. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69115. }
  69116. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeAndScaleAnchor() const
  69117. {
  69118. return state [fontSizeAnchor].toString();
  69119. }
  69120. void DrawableText::ValueTreeWrapper::setFontSizeAndScaleAnchor (const RelativePoint& p, UndoManager* undoManager)
  69121. {
  69122. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  69123. }
  69124. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  69125. {
  69126. ValueTreeWrapper v (tree);
  69127. setName (v.getID());
  69128. const RelativeParallelogram newBounds (v.getBoundingBox());
  69129. const RelativePoint newFontPoint (v.getFontSizeAndScaleAnchor());
  69130. const Colour newColour (v.getColour());
  69131. const Justification newJustification (v.getJustification());
  69132. const String newText (v.getText());
  69133. const Font newFont (v.getFont());
  69134. if (text != newText || font != newFont || justification != newJustification
  69135. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  69136. {
  69137. const Rectangle<float> damage (getBounds());
  69138. setBoundingBox (newBounds);
  69139. setFontSizeControlPoint (newFontPoint);
  69140. setColour (newColour);
  69141. setFont (newFont, false);
  69142. setJustification (newJustification);
  69143. setText (newText);
  69144. return damage.getUnion (getBounds());
  69145. }
  69146. return Rectangle<float>();
  69147. }
  69148. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  69149. {
  69150. ValueTree tree (valueTreeType);
  69151. ValueTreeWrapper v (tree);
  69152. v.setID (getName(), 0);
  69153. v.setText (text, 0);
  69154. v.setFont (font, 0);
  69155. v.setJustification (justification, 0);
  69156. v.setColour (colour, 0);
  69157. v.setBoundingBox (bounds, 0);
  69158. v.setFontSizeAndScaleAnchor (fontSizeControlPoint, 0);
  69159. return tree;
  69160. }
  69161. END_JUCE_NAMESPACE
  69162. /*** End of inlined file: juce_DrawableText.cpp ***/
  69163. /*** Start of inlined file: juce_SVGParser.cpp ***/
  69164. BEGIN_JUCE_NAMESPACE
  69165. class SVGState
  69166. {
  69167. public:
  69168. SVGState (const XmlElement* const topLevel)
  69169. : topLevelXml (topLevel),
  69170. elementX (0), elementY (0),
  69171. width (512), height (512),
  69172. viewBoxW (0), viewBoxH (0)
  69173. {
  69174. }
  69175. ~SVGState()
  69176. {
  69177. }
  69178. Drawable* parseSVGElement (const XmlElement& xml)
  69179. {
  69180. if (! xml.hasTagName ("svg"))
  69181. return 0;
  69182. DrawableComposite* const drawable = new DrawableComposite();
  69183. drawable->setName (xml.getStringAttribute ("id"));
  69184. SVGState newState (*this);
  69185. if (xml.hasAttribute ("transform"))
  69186. newState.addTransform (xml);
  69187. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  69188. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  69189. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  69190. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  69191. if (xml.hasAttribute ("viewBox"))
  69192. {
  69193. const String viewParams (xml.getStringAttribute ("viewBox"));
  69194. int i = 0;
  69195. float vx, vy, vw, vh;
  69196. if (parseCoords (viewParams, vx, vy, i, true)
  69197. && parseCoords (viewParams, vw, vh, i, true)
  69198. && vw > 0
  69199. && vh > 0)
  69200. {
  69201. newState.viewBoxW = vw;
  69202. newState.viewBoxH = vh;
  69203. int placementFlags = 0;
  69204. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  69205. if (aspect.containsIgnoreCase ("none"))
  69206. {
  69207. placementFlags = RectanglePlacement::stretchToFit;
  69208. }
  69209. else
  69210. {
  69211. if (aspect.containsIgnoreCase ("slice"))
  69212. placementFlags |= RectanglePlacement::fillDestination;
  69213. if (aspect.containsIgnoreCase ("xMin"))
  69214. placementFlags |= RectanglePlacement::xLeft;
  69215. else if (aspect.containsIgnoreCase ("xMax"))
  69216. placementFlags |= RectanglePlacement::xRight;
  69217. else
  69218. placementFlags |= RectanglePlacement::xMid;
  69219. if (aspect.containsIgnoreCase ("yMin"))
  69220. placementFlags |= RectanglePlacement::yTop;
  69221. else if (aspect.containsIgnoreCase ("yMax"))
  69222. placementFlags |= RectanglePlacement::yBottom;
  69223. else
  69224. placementFlags |= RectanglePlacement::yMid;
  69225. }
  69226. const RectanglePlacement placement (placementFlags);
  69227. newState.transform
  69228. = placement.getTransformToFit (vx, vy, vw, vh,
  69229. 0.0f, 0.0f, newState.width, newState.height)
  69230. .followedBy (newState.transform);
  69231. }
  69232. }
  69233. else
  69234. {
  69235. if (viewBoxW == 0)
  69236. newState.viewBoxW = newState.width;
  69237. if (viewBoxH == 0)
  69238. newState.viewBoxH = newState.height;
  69239. }
  69240. newState.parseSubElements (xml, drawable);
  69241. const Rectangle<float> bounds (drawable->getBounds());
  69242. drawable->setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX(), true),
  69243. RelativeCoordinate (bounds.getRight(), true),
  69244. RelativeCoordinate (bounds.getY(), false),
  69245. RelativeCoordinate (bounds.getBottom(), false)));
  69246. drawable->resetBoundingBoxToContentArea();
  69247. return drawable;
  69248. }
  69249. private:
  69250. const XmlElement* const topLevelXml;
  69251. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  69252. AffineTransform transform;
  69253. String cssStyleText;
  69254. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  69255. {
  69256. forEachXmlChildElement (xml, e)
  69257. {
  69258. Drawable* d = 0;
  69259. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  69260. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  69261. else if (e->hasTagName ("path")) d = parsePath (*e);
  69262. else if (e->hasTagName ("rect")) d = parseRect (*e);
  69263. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  69264. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  69265. else if (e->hasTagName ("line")) d = parseLine (*e);
  69266. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  69267. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  69268. else if (e->hasTagName ("text")) d = parseText (*e);
  69269. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  69270. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  69271. parentDrawable->insertDrawable (d);
  69272. }
  69273. }
  69274. DrawableComposite* parseSwitch (const XmlElement& xml)
  69275. {
  69276. const XmlElement* const group = xml.getChildByName ("g");
  69277. if (group != 0)
  69278. return parseGroupElement (*group);
  69279. return 0;
  69280. }
  69281. DrawableComposite* parseGroupElement (const XmlElement& xml)
  69282. {
  69283. DrawableComposite* const drawable = new DrawableComposite();
  69284. drawable->setName (xml.getStringAttribute ("id"));
  69285. if (xml.hasAttribute ("transform"))
  69286. {
  69287. SVGState newState (*this);
  69288. newState.addTransform (xml);
  69289. newState.parseSubElements (xml, drawable);
  69290. }
  69291. else
  69292. {
  69293. parseSubElements (xml, drawable);
  69294. }
  69295. return drawable;
  69296. }
  69297. Drawable* parsePath (const XmlElement& xml) const
  69298. {
  69299. const String d (xml.getStringAttribute ("d").trimStart());
  69300. Path path;
  69301. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  69302. path.setUsingNonZeroWinding (false);
  69303. int index = 0;
  69304. float lastX = 0, lastY = 0;
  69305. float lastX2 = 0, lastY2 = 0;
  69306. juce_wchar lastCommandChar = 0;
  69307. bool isRelative = true;
  69308. bool carryOn = true;
  69309. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  69310. while (d[index] != 0)
  69311. {
  69312. float x, y, x2, y2, x3, y3;
  69313. if (validCommandChars.containsChar (d[index]))
  69314. {
  69315. lastCommandChar = d [index++];
  69316. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  69317. }
  69318. switch (lastCommandChar)
  69319. {
  69320. case 'M':
  69321. case 'm':
  69322. case 'L':
  69323. case 'l':
  69324. if (parseCoords (d, x, y, index, false))
  69325. {
  69326. if (isRelative)
  69327. {
  69328. x += lastX;
  69329. y += lastY;
  69330. }
  69331. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  69332. {
  69333. path.startNewSubPath (x, y);
  69334. lastCommandChar = 'l';
  69335. }
  69336. else
  69337. path.lineTo (x, y);
  69338. lastX2 = lastX;
  69339. lastY2 = lastY;
  69340. lastX = x;
  69341. lastY = y;
  69342. }
  69343. else
  69344. {
  69345. ++index;
  69346. }
  69347. break;
  69348. case 'H':
  69349. case 'h':
  69350. if (parseCoord (d, x, index, false, true))
  69351. {
  69352. if (isRelative)
  69353. x += lastX;
  69354. path.lineTo (x, lastY);
  69355. lastX2 = lastX;
  69356. lastX = x;
  69357. }
  69358. else
  69359. {
  69360. ++index;
  69361. }
  69362. break;
  69363. case 'V':
  69364. case 'v':
  69365. if (parseCoord (d, y, index, false, false))
  69366. {
  69367. if (isRelative)
  69368. y += lastY;
  69369. path.lineTo (lastX, y);
  69370. lastY2 = lastY;
  69371. lastY = y;
  69372. }
  69373. else
  69374. {
  69375. ++index;
  69376. }
  69377. break;
  69378. case 'C':
  69379. case 'c':
  69380. if (parseCoords (d, x, y, index, false)
  69381. && parseCoords (d, x2, y2, index, false)
  69382. && parseCoords (d, x3, y3, index, false))
  69383. {
  69384. if (isRelative)
  69385. {
  69386. x += lastX;
  69387. y += lastY;
  69388. x2 += lastX;
  69389. y2 += lastY;
  69390. x3 += lastX;
  69391. y3 += lastY;
  69392. }
  69393. path.cubicTo (x, y, x2, y2, x3, y3);
  69394. lastX2 = x2;
  69395. lastY2 = y2;
  69396. lastX = x3;
  69397. lastY = y3;
  69398. }
  69399. else
  69400. {
  69401. ++index;
  69402. }
  69403. break;
  69404. case 'S':
  69405. case 's':
  69406. if (parseCoords (d, x, y, index, false)
  69407. && parseCoords (d, x3, y3, index, false))
  69408. {
  69409. if (isRelative)
  69410. {
  69411. x += lastX;
  69412. y += lastY;
  69413. x3 += lastX;
  69414. y3 += lastY;
  69415. }
  69416. x2 = lastX + (lastX - lastX2);
  69417. y2 = lastY + (lastY - lastY2);
  69418. path.cubicTo (x2, y2, x, y, x3, y3);
  69419. lastX2 = x;
  69420. lastY2 = y;
  69421. lastX = x3;
  69422. lastY = y3;
  69423. }
  69424. else
  69425. {
  69426. ++index;
  69427. }
  69428. break;
  69429. case 'Q':
  69430. case 'q':
  69431. if (parseCoords (d, x, y, index, false)
  69432. && parseCoords (d, x2, y2, index, false))
  69433. {
  69434. if (isRelative)
  69435. {
  69436. x += lastX;
  69437. y += lastY;
  69438. x2 += lastX;
  69439. y2 += lastY;
  69440. }
  69441. path.quadraticTo (x, y, x2, y2);
  69442. lastX2 = x;
  69443. lastY2 = y;
  69444. lastX = x2;
  69445. lastY = y2;
  69446. }
  69447. else
  69448. {
  69449. ++index;
  69450. }
  69451. break;
  69452. case 'T':
  69453. case 't':
  69454. if (parseCoords (d, x, y, index, false))
  69455. {
  69456. if (isRelative)
  69457. {
  69458. x += lastX;
  69459. y += lastY;
  69460. }
  69461. x2 = lastX + (lastX - lastX2);
  69462. y2 = lastY + (lastY - lastY2);
  69463. path.quadraticTo (x2, y2, x, y);
  69464. lastX2 = x2;
  69465. lastY2 = y2;
  69466. lastX = x;
  69467. lastY = y;
  69468. }
  69469. else
  69470. {
  69471. ++index;
  69472. }
  69473. break;
  69474. case 'A':
  69475. case 'a':
  69476. if (parseCoords (d, x, y, index, false))
  69477. {
  69478. String num;
  69479. if (parseNextNumber (d, num, index, false))
  69480. {
  69481. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  69482. if (parseNextNumber (d, num, index, false))
  69483. {
  69484. const bool largeArc = num.getIntValue() != 0;
  69485. if (parseNextNumber (d, num, index, false))
  69486. {
  69487. const bool sweep = num.getIntValue() != 0;
  69488. if (parseCoords (d, x2, y2, index, false))
  69489. {
  69490. if (isRelative)
  69491. {
  69492. x2 += lastX;
  69493. y2 += lastY;
  69494. }
  69495. if (lastX != x2 || lastY != y2)
  69496. {
  69497. double centreX, centreY, startAngle, deltaAngle;
  69498. double rx = x, ry = y;
  69499. endpointToCentreParameters (lastX, lastY, x2, y2,
  69500. angle, largeArc, sweep,
  69501. rx, ry, centreX, centreY,
  69502. startAngle, deltaAngle);
  69503. path.addCentredArc ((float) centreX, (float) centreY,
  69504. (float) rx, (float) ry,
  69505. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  69506. false);
  69507. path.lineTo (x2, y2);
  69508. }
  69509. lastX2 = lastX;
  69510. lastY2 = lastY;
  69511. lastX = x2;
  69512. lastY = y2;
  69513. }
  69514. }
  69515. }
  69516. }
  69517. }
  69518. else
  69519. {
  69520. ++index;
  69521. }
  69522. break;
  69523. case 'Z':
  69524. case 'z':
  69525. path.closeSubPath();
  69526. while (CharacterFunctions::isWhitespace (d [index]))
  69527. ++index;
  69528. break;
  69529. default:
  69530. carryOn = false;
  69531. break;
  69532. }
  69533. if (! carryOn)
  69534. break;
  69535. }
  69536. return parseShape (xml, path);
  69537. }
  69538. Drawable* parseRect (const XmlElement& xml) const
  69539. {
  69540. Path rect;
  69541. const bool hasRX = xml.hasAttribute ("rx");
  69542. const bool hasRY = xml.hasAttribute ("ry");
  69543. if (hasRX || hasRY)
  69544. {
  69545. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  69546. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  69547. if (! hasRX)
  69548. rx = ry;
  69549. else if (! hasRY)
  69550. ry = rx;
  69551. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  69552. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  69553. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  69554. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  69555. rx, ry);
  69556. }
  69557. else
  69558. {
  69559. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  69560. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  69561. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  69562. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  69563. }
  69564. return parseShape (xml, rect);
  69565. }
  69566. Drawable* parseCircle (const XmlElement& xml) const
  69567. {
  69568. Path circle;
  69569. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  69570. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  69571. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  69572. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  69573. return parseShape (xml, circle);
  69574. }
  69575. Drawable* parseEllipse (const XmlElement& xml) const
  69576. {
  69577. Path ellipse;
  69578. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  69579. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  69580. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  69581. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  69582. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  69583. return parseShape (xml, ellipse);
  69584. }
  69585. Drawable* parseLine (const XmlElement& xml) const
  69586. {
  69587. Path line;
  69588. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  69589. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  69590. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  69591. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  69592. line.startNewSubPath (x1, y1);
  69593. line.lineTo (x2, y2);
  69594. return parseShape (xml, line);
  69595. }
  69596. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  69597. {
  69598. const String points (xml.getStringAttribute ("points"));
  69599. Path path;
  69600. int index = 0;
  69601. float x, y;
  69602. if (parseCoords (points, x, y, index, true))
  69603. {
  69604. float firstX = x;
  69605. float firstY = y;
  69606. float lastX = 0, lastY = 0;
  69607. path.startNewSubPath (x, y);
  69608. while (parseCoords (points, x, y, index, true))
  69609. {
  69610. lastX = x;
  69611. lastY = y;
  69612. path.lineTo (x, y);
  69613. }
  69614. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  69615. path.closeSubPath();
  69616. }
  69617. return parseShape (xml, path);
  69618. }
  69619. Drawable* parseShape (const XmlElement& xml, Path& path,
  69620. const bool shouldParseTransform = true) const
  69621. {
  69622. if (shouldParseTransform && xml.hasAttribute ("transform"))
  69623. {
  69624. SVGState newState (*this);
  69625. newState.addTransform (xml);
  69626. return newState.parseShape (xml, path, false);
  69627. }
  69628. DrawablePath* dp = new DrawablePath();
  69629. dp->setName (xml.getStringAttribute ("id"));
  69630. dp->setFill (Colours::transparentBlack);
  69631. path.applyTransform (transform);
  69632. dp->setPath (path);
  69633. Path::Iterator iter (path);
  69634. bool containsClosedSubPath = false;
  69635. while (iter.next())
  69636. {
  69637. if (iter.elementType == Path::Iterator::closePath)
  69638. {
  69639. containsClosedSubPath = true;
  69640. break;
  69641. }
  69642. }
  69643. dp->setFill (getPathFillType (path,
  69644. getStyleAttribute (&xml, "fill"),
  69645. getStyleAttribute (&xml, "fill-opacity"),
  69646. getStyleAttribute (&xml, "opacity"),
  69647. containsClosedSubPath ? Colours::black
  69648. : Colours::transparentBlack));
  69649. const String strokeType (getStyleAttribute (&xml, "stroke"));
  69650. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  69651. {
  69652. dp->setStrokeFill (getPathFillType (path, strokeType,
  69653. getStyleAttribute (&xml, "stroke-opacity"),
  69654. getStyleAttribute (&xml, "opacity"),
  69655. Colours::transparentBlack));
  69656. dp->setStrokeType (getStrokeFor (&xml));
  69657. }
  69658. return dp;
  69659. }
  69660. const XmlElement* findLinkedElement (const XmlElement* e) const
  69661. {
  69662. const String id (e->getStringAttribute ("xlink:href"));
  69663. if (! id.startsWithChar ('#'))
  69664. return 0;
  69665. return findElementForId (topLevelXml, id.substring (1));
  69666. }
  69667. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  69668. {
  69669. if (fillXml == 0)
  69670. return;
  69671. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  69672. {
  69673. int index = 0;
  69674. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  69675. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  69676. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  69677. double offset = e->getDoubleAttribute ("offset");
  69678. if (e->getStringAttribute ("offset").containsChar ('%'))
  69679. offset *= 0.01;
  69680. cg.addColour (jlimit (0.0, 1.0, offset), col);
  69681. }
  69682. }
  69683. const FillType getPathFillType (const Path& path,
  69684. const String& fill,
  69685. const String& fillOpacity,
  69686. const String& overallOpacity,
  69687. const Colour& defaultColour) const
  69688. {
  69689. float opacity = 1.0f;
  69690. if (overallOpacity.isNotEmpty())
  69691. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  69692. if (fillOpacity.isNotEmpty())
  69693. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  69694. if (fill.startsWithIgnoreCase ("url"))
  69695. {
  69696. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  69697. .upToLastOccurrenceOf (")", false, false).trim());
  69698. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  69699. if (fillXml != 0
  69700. && (fillXml->hasTagName ("linearGradient")
  69701. || fillXml->hasTagName ("radialGradient")))
  69702. {
  69703. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  69704. ColourGradient gradient;
  69705. addGradientStopsIn (gradient, inheritedFrom);
  69706. addGradientStopsIn (gradient, fillXml);
  69707. if (gradient.getNumColours() > 0)
  69708. {
  69709. gradient.addColour (0.0, gradient.getColour (0));
  69710. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  69711. }
  69712. else
  69713. {
  69714. gradient.addColour (0.0, Colours::black);
  69715. gradient.addColour (1.0, Colours::black);
  69716. }
  69717. if (overallOpacity.isNotEmpty())
  69718. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  69719. jassert (gradient.getNumColours() > 0);
  69720. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  69721. float gradientWidth = viewBoxW;
  69722. float gradientHeight = viewBoxH;
  69723. float dx = 0.0f;
  69724. float dy = 0.0f;
  69725. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  69726. if (! userSpace)
  69727. {
  69728. const Rectangle<float> bounds (path.getBounds());
  69729. dx = bounds.getX();
  69730. dy = bounds.getY();
  69731. gradientWidth = bounds.getWidth();
  69732. gradientHeight = bounds.getHeight();
  69733. }
  69734. if (gradient.isRadial)
  69735. {
  69736. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  69737. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  69738. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  69739. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  69740. //xxx (the fx, fy focal point isn't handled properly here..)
  69741. }
  69742. else
  69743. {
  69744. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  69745. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  69746. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  69747. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  69748. if (gradient.point1 == gradient.point2)
  69749. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  69750. }
  69751. FillType type (gradient);
  69752. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  69753. .followedBy (transform);
  69754. return type;
  69755. }
  69756. }
  69757. if (fill.equalsIgnoreCase ("none"))
  69758. return Colours::transparentBlack;
  69759. int i = 0;
  69760. const Colour colour (parseColour (fill, i, defaultColour));
  69761. return colour.withMultipliedAlpha (opacity);
  69762. }
  69763. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  69764. {
  69765. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  69766. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  69767. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  69768. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  69769. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  69770. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  69771. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  69772. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  69773. if (join.equalsIgnoreCase ("round"))
  69774. joinStyle = PathStrokeType::curved;
  69775. else if (join.equalsIgnoreCase ("bevel"))
  69776. joinStyle = PathStrokeType::beveled;
  69777. if (cap.equalsIgnoreCase ("round"))
  69778. capStyle = PathStrokeType::rounded;
  69779. else if (cap.equalsIgnoreCase ("square"))
  69780. capStyle = PathStrokeType::square;
  69781. float ox = 0.0f, oy = 0.0f;
  69782. transform.transformPoint (ox, oy);
  69783. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  69784. transform.transformPoint (x, y);
  69785. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  69786. joinStyle, capStyle);
  69787. }
  69788. Drawable* parseText (const XmlElement& xml)
  69789. {
  69790. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  69791. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  69792. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  69793. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  69794. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  69795. //xxx not done text yet!
  69796. forEachXmlChildElement (xml, e)
  69797. {
  69798. if (e->isTextElement())
  69799. {
  69800. const String text (e->getText());
  69801. Path path;
  69802. Drawable* s = parseShape (*e, path);
  69803. delete s;
  69804. }
  69805. else if (e->hasTagName ("tspan"))
  69806. {
  69807. Drawable* s = parseText (*e);
  69808. delete s;
  69809. }
  69810. }
  69811. return 0;
  69812. }
  69813. void addTransform (const XmlElement& xml)
  69814. {
  69815. transform = parseTransform (xml.getStringAttribute ("transform"))
  69816. .followedBy (transform);
  69817. }
  69818. bool parseCoord (const String& s, float& value, int& index,
  69819. const bool allowUnits, const bool isX) const
  69820. {
  69821. String number;
  69822. if (! parseNextNumber (s, number, index, allowUnits))
  69823. {
  69824. value = 0;
  69825. return false;
  69826. }
  69827. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  69828. return true;
  69829. }
  69830. bool parseCoords (const String& s, float& x, float& y,
  69831. int& index, const bool allowUnits) const
  69832. {
  69833. return parseCoord (s, x, index, allowUnits, true)
  69834. && parseCoord (s, y, index, allowUnits, false);
  69835. }
  69836. float getCoordLength (const String& s, const float sizeForProportions) const
  69837. {
  69838. float n = s.getFloatValue();
  69839. const int len = s.length();
  69840. if (len > 2)
  69841. {
  69842. const float dpi = 96.0f;
  69843. const juce_wchar n1 = s [len - 2];
  69844. const juce_wchar n2 = s [len - 1];
  69845. if (n1 == 'i' && n2 == 'n')
  69846. n *= dpi;
  69847. else if (n1 == 'm' && n2 == 'm')
  69848. n *= dpi / 25.4f;
  69849. else if (n1 == 'c' && n2 == 'm')
  69850. n *= dpi / 2.54f;
  69851. else if (n1 == 'p' && n2 == 'c')
  69852. n *= 15.0f;
  69853. else if (n2 == '%')
  69854. n *= 0.01f * sizeForProportions;
  69855. }
  69856. return n;
  69857. }
  69858. void getCoordList (Array <float>& coords, const String& list,
  69859. const bool allowUnits, const bool isX) const
  69860. {
  69861. int index = 0;
  69862. float value;
  69863. while (parseCoord (list, value, index, allowUnits, isX))
  69864. coords.add (value);
  69865. }
  69866. void parseCSSStyle (const XmlElement& xml)
  69867. {
  69868. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  69869. }
  69870. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  69871. const String& defaultValue = String::empty) const
  69872. {
  69873. if (xml->hasAttribute (attributeName))
  69874. return xml->getStringAttribute (attributeName, defaultValue);
  69875. const String styleAtt (xml->getStringAttribute ("style"));
  69876. if (styleAtt.isNotEmpty())
  69877. {
  69878. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  69879. if (value.isNotEmpty())
  69880. return value;
  69881. }
  69882. else if (xml->hasAttribute ("class"))
  69883. {
  69884. const String className ("." + xml->getStringAttribute ("class"));
  69885. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  69886. if (index < 0)
  69887. index = cssStyleText.indexOfIgnoreCase (className + "{");
  69888. if (index >= 0)
  69889. {
  69890. const int openBracket = cssStyleText.indexOfChar (index, '{');
  69891. if (openBracket > index)
  69892. {
  69893. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  69894. if (closeBracket > openBracket)
  69895. {
  69896. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  69897. if (value.isNotEmpty())
  69898. return value;
  69899. }
  69900. }
  69901. }
  69902. }
  69903. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  69904. if (xml != 0)
  69905. return getStyleAttribute (xml, attributeName, defaultValue);
  69906. return defaultValue;
  69907. }
  69908. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  69909. {
  69910. if (xml->hasAttribute (attributeName))
  69911. return xml->getStringAttribute (attributeName);
  69912. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  69913. if (xml != 0)
  69914. return getInheritedAttribute (xml, attributeName);
  69915. return String::empty;
  69916. }
  69917. static bool isIdentifierChar (const juce_wchar c)
  69918. {
  69919. return CharacterFunctions::isLetter (c) || c == '-';
  69920. }
  69921. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  69922. {
  69923. int i = 0;
  69924. for (;;)
  69925. {
  69926. i = list.indexOf (i, attributeName);
  69927. if (i < 0)
  69928. break;
  69929. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  69930. && ! isIdentifierChar (list [i + attributeName.length()]))
  69931. {
  69932. i = list.indexOfChar (i, ':');
  69933. if (i < 0)
  69934. break;
  69935. int end = list.indexOfChar (i, ';');
  69936. if (end < 0)
  69937. end = 0x7ffff;
  69938. return list.substring (i + 1, end).trim();
  69939. }
  69940. ++i;
  69941. }
  69942. return defaultValue;
  69943. }
  69944. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  69945. {
  69946. const juce_wchar* const s = source;
  69947. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  69948. ++index;
  69949. int start = index;
  69950. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  69951. ++index;
  69952. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  69953. ++index;
  69954. if ((s[index] == 'e' || s[index] == 'E')
  69955. && (CharacterFunctions::isDigit (s[index + 1])
  69956. || s[index + 1] == '-'
  69957. || s[index + 1] == '+'))
  69958. {
  69959. index += 2;
  69960. while (CharacterFunctions::isDigit (s[index]))
  69961. ++index;
  69962. }
  69963. if (allowUnits)
  69964. {
  69965. while (CharacterFunctions::isLetter (s[index]))
  69966. ++index;
  69967. }
  69968. if (index == start)
  69969. return false;
  69970. value = String (s + start, index - start);
  69971. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  69972. ++index;
  69973. return true;
  69974. }
  69975. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  69976. {
  69977. if (s [index] == '#')
  69978. {
  69979. uint32 hex [6];
  69980. zeromem (hex, sizeof (hex));
  69981. int numChars = 0;
  69982. for (int i = 6; --i >= 0;)
  69983. {
  69984. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  69985. if (hexValue >= 0)
  69986. hex [numChars++] = hexValue;
  69987. else
  69988. break;
  69989. }
  69990. if (numChars <= 3)
  69991. return Colour ((uint8) (hex [0] * 0x11),
  69992. (uint8) (hex [1] * 0x11),
  69993. (uint8) (hex [2] * 0x11));
  69994. else
  69995. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  69996. (uint8) ((hex [2] << 4) + hex [3]),
  69997. (uint8) ((hex [4] << 4) + hex [5]));
  69998. }
  69999. else if (s [index] == 'r'
  70000. && s [index + 1] == 'g'
  70001. && s [index + 2] == 'b')
  70002. {
  70003. const int openBracket = s.indexOfChar (index, '(');
  70004. const int closeBracket = s.indexOfChar (openBracket, ')');
  70005. if (openBracket >= 3 && closeBracket > openBracket)
  70006. {
  70007. index = closeBracket;
  70008. StringArray tokens;
  70009. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  70010. tokens.trim();
  70011. tokens.removeEmptyStrings();
  70012. if (tokens[0].containsChar ('%'))
  70013. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  70014. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  70015. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  70016. else
  70017. return Colour ((uint8) tokens[0].getIntValue(),
  70018. (uint8) tokens[1].getIntValue(),
  70019. (uint8) tokens[2].getIntValue());
  70020. }
  70021. }
  70022. return Colours::findColourForName (s, defaultColour);
  70023. }
  70024. static const AffineTransform parseTransform (String t)
  70025. {
  70026. AffineTransform result;
  70027. while (t.isNotEmpty())
  70028. {
  70029. StringArray tokens;
  70030. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  70031. .upToFirstOccurrenceOf (")", false, false),
  70032. ", ", String::empty);
  70033. tokens.removeEmptyStrings (true);
  70034. float numbers [6];
  70035. for (int i = 0; i < 6; ++i)
  70036. numbers[i] = tokens[i].getFloatValue();
  70037. AffineTransform trans;
  70038. if (t.startsWithIgnoreCase ("matrix"))
  70039. {
  70040. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  70041. numbers[1], numbers[3], numbers[5]);
  70042. }
  70043. else if (t.startsWithIgnoreCase ("translate"))
  70044. {
  70045. jassert (tokens.size() == 2);
  70046. trans = AffineTransform::translation (numbers[0], numbers[1]);
  70047. }
  70048. else if (t.startsWithIgnoreCase ("scale"))
  70049. {
  70050. if (tokens.size() == 1)
  70051. trans = AffineTransform::scale (numbers[0], numbers[0]);
  70052. else
  70053. trans = AffineTransform::scale (numbers[0], numbers[1]);
  70054. }
  70055. else if (t.startsWithIgnoreCase ("rotate"))
  70056. {
  70057. if (tokens.size() != 3)
  70058. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  70059. else
  70060. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  70061. numbers[1], numbers[2]);
  70062. }
  70063. else if (t.startsWithIgnoreCase ("skewX"))
  70064. {
  70065. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  70066. 0.0f, 1.0f, 0.0f);
  70067. }
  70068. else if (t.startsWithIgnoreCase ("skewY"))
  70069. {
  70070. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  70071. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  70072. }
  70073. result = trans.followedBy (result);
  70074. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  70075. }
  70076. return result;
  70077. }
  70078. static void endpointToCentreParameters (const double x1, const double y1,
  70079. const double x2, const double y2,
  70080. const double angle,
  70081. const bool largeArc, const bool sweep,
  70082. double& rx, double& ry,
  70083. double& centreX, double& centreY,
  70084. double& startAngle, double& deltaAngle)
  70085. {
  70086. const double midX = (x1 - x2) * 0.5;
  70087. const double midY = (y1 - y2) * 0.5;
  70088. const double cosAngle = cos (angle);
  70089. const double sinAngle = sin (angle);
  70090. const double xp = cosAngle * midX + sinAngle * midY;
  70091. const double yp = cosAngle * midY - sinAngle * midX;
  70092. const double xp2 = xp * xp;
  70093. const double yp2 = yp * yp;
  70094. double rx2 = rx * rx;
  70095. double ry2 = ry * ry;
  70096. const double s = (xp2 / rx2) + (yp2 / ry2);
  70097. double c;
  70098. if (s <= 1.0)
  70099. {
  70100. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  70101. / (( rx2 * yp2) + (ry2 * xp2))));
  70102. if (largeArc == sweep)
  70103. c = -c;
  70104. }
  70105. else
  70106. {
  70107. const double s2 = std::sqrt (s);
  70108. rx *= s2;
  70109. ry *= s2;
  70110. rx2 = rx * rx;
  70111. ry2 = ry * ry;
  70112. c = 0;
  70113. }
  70114. const double cpx = ((rx * yp) / ry) * c;
  70115. const double cpy = ((-ry * xp) / rx) * c;
  70116. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  70117. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  70118. const double ux = (xp - cpx) / rx;
  70119. const double uy = (yp - cpy) / ry;
  70120. const double vx = (-xp - cpx) / rx;
  70121. const double vy = (-yp - cpy) / ry;
  70122. const double length = juce_hypot (ux, uy);
  70123. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  70124. if (uy < 0)
  70125. startAngle = -startAngle;
  70126. startAngle += double_Pi * 0.5;
  70127. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  70128. / (length * juce_hypot (vx, vy))));
  70129. if ((ux * vy) - (uy * vx) < 0)
  70130. deltaAngle = -deltaAngle;
  70131. if (sweep)
  70132. {
  70133. if (deltaAngle < 0)
  70134. deltaAngle += double_Pi * 2.0;
  70135. }
  70136. else
  70137. {
  70138. if (deltaAngle > 0)
  70139. deltaAngle -= double_Pi * 2.0;
  70140. }
  70141. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  70142. }
  70143. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  70144. {
  70145. forEachXmlChildElement (*parent, e)
  70146. {
  70147. if (e->compareAttribute ("id", id))
  70148. return e;
  70149. const XmlElement* const found = findElementForId (e, id);
  70150. if (found != 0)
  70151. return found;
  70152. }
  70153. return 0;
  70154. }
  70155. SVGState& operator= (const SVGState&);
  70156. };
  70157. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  70158. {
  70159. SVGState state (&svgDocument);
  70160. return state.parseSVGElement (svgDocument);
  70161. }
  70162. END_JUCE_NAMESPACE
  70163. /*** End of inlined file: juce_SVGParser.cpp ***/
  70164. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  70165. BEGIN_JUCE_NAMESPACE
  70166. #if JUCE_MSVC && JUCE_DEBUG
  70167. #pragma optimize ("t", on)
  70168. #endif
  70169. DropShadowEffect::DropShadowEffect()
  70170. : offsetX (0),
  70171. offsetY (0),
  70172. radius (4),
  70173. opacity (0.6f)
  70174. {
  70175. }
  70176. DropShadowEffect::~DropShadowEffect()
  70177. {
  70178. }
  70179. void DropShadowEffect::setShadowProperties (const float newRadius,
  70180. const float newOpacity,
  70181. const int newShadowOffsetX,
  70182. const int newShadowOffsetY)
  70183. {
  70184. radius = jmax (1.1f, newRadius);
  70185. offsetX = newShadowOffsetX;
  70186. offsetY = newShadowOffsetY;
  70187. opacity = newOpacity;
  70188. }
  70189. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  70190. {
  70191. const int w = image.getWidth();
  70192. const int h = image.getHeight();
  70193. Image shadowImage (Image::SingleChannel, w, h, false);
  70194. const Image::BitmapData srcData (image, 0, 0, w, h);
  70195. const Image::BitmapData destData (shadowImage, 0, 0, w, h, true);
  70196. const int filter = roundToInt (63.0f / radius);
  70197. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  70198. for (int x = w; --x >= 0;)
  70199. {
  70200. int shadowAlpha = 0;
  70201. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  70202. uint8* shadowPix = destData.data + x;
  70203. for (int y = h; --y >= 0;)
  70204. {
  70205. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  70206. *shadowPix = (uint8) shadowAlpha;
  70207. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  70208. shadowPix += destData.lineStride;
  70209. }
  70210. }
  70211. for (int y = h; --y >= 0;)
  70212. {
  70213. int shadowAlpha = 0;
  70214. uint8* shadowPix = destData.getLinePointer (y);
  70215. for (int x = w; --x >= 0;)
  70216. {
  70217. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  70218. *shadowPix++ = (uint8) shadowAlpha;
  70219. }
  70220. }
  70221. g.setColour (Colours::black.withAlpha (opacity));
  70222. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  70223. g.setOpacity (1.0f);
  70224. g.drawImageAt (image, 0, 0);
  70225. }
  70226. #if JUCE_MSVC && JUCE_DEBUG
  70227. #pragma optimize ("", on) // resets optimisations to the project defaults
  70228. #endif
  70229. END_JUCE_NAMESPACE
  70230. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  70231. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  70232. BEGIN_JUCE_NAMESPACE
  70233. GlowEffect::GlowEffect()
  70234. : radius (2.0f),
  70235. colour (Colours::white)
  70236. {
  70237. }
  70238. GlowEffect::~GlowEffect()
  70239. {
  70240. }
  70241. void GlowEffect::setGlowProperties (const float newRadius,
  70242. const Colour& newColour)
  70243. {
  70244. radius = newRadius;
  70245. colour = newColour;
  70246. }
  70247. void GlowEffect::applyEffect (Image& image, Graphics& g)
  70248. {
  70249. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  70250. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  70251. blurKernel.createGaussianBlur (radius);
  70252. blurKernel.rescaleAllValues (radius);
  70253. blurKernel.applyToImage (temp, image, image.getBounds());
  70254. g.setColour (colour);
  70255. g.drawImageAt (temp, 0, 0, true);
  70256. g.setOpacity (1.0f);
  70257. g.drawImageAt (image, 0, 0, false);
  70258. }
  70259. END_JUCE_NAMESPACE
  70260. /*** End of inlined file: juce_GlowEffect.cpp ***/
  70261. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  70262. BEGIN_JUCE_NAMESPACE
  70263. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  70264. : opacity (opacity_)
  70265. {
  70266. }
  70267. ReduceOpacityEffect::~ReduceOpacityEffect()
  70268. {
  70269. }
  70270. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  70271. {
  70272. opacity = jlimit (0.0f, 1.0f, newOpacity);
  70273. }
  70274. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  70275. {
  70276. g.setOpacity (opacity);
  70277. g.drawImageAt (image, 0, 0);
  70278. }
  70279. END_JUCE_NAMESPACE
  70280. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  70281. /*** Start of inlined file: juce_Font.cpp ***/
  70282. BEGIN_JUCE_NAMESPACE
  70283. namespace FontValues
  70284. {
  70285. static float limitFontHeight (const float height) throw()
  70286. {
  70287. return jlimit (0.1f, 10000.0f, height);
  70288. }
  70289. static const float defaultFontHeight = 14.0f;
  70290. static String fallbackFont;
  70291. }
  70292. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  70293. const float kerning_, const float ascent_, const int styleFlags_,
  70294. Typeface* const typeface_) throw()
  70295. : typefaceName (typefaceName_),
  70296. height (height_),
  70297. horizontalScale (horizontalScale_),
  70298. kerning (kerning_),
  70299. ascent (ascent_),
  70300. styleFlags (styleFlags_),
  70301. typeface (typeface_)
  70302. {
  70303. }
  70304. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  70305. : typefaceName (other.typefaceName),
  70306. height (other.height),
  70307. horizontalScale (other.horizontalScale),
  70308. kerning (other.kerning),
  70309. ascent (other.ascent),
  70310. styleFlags (other.styleFlags),
  70311. typeface (other.typeface)
  70312. {
  70313. }
  70314. Font::Font() throw()
  70315. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  70316. 1.0f, 0, 0, Font::plain, 0))
  70317. {
  70318. }
  70319. Font::Font (const float fontHeight, const int styleFlags_) throw()
  70320. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  70321. 1.0f, 0, 0, styleFlags_, 0))
  70322. {
  70323. }
  70324. Font::Font (const String& typefaceName_,
  70325. const float fontHeight,
  70326. const int styleFlags_) throw()
  70327. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  70328. 1.0f, 0, 0, styleFlags_, 0))
  70329. {
  70330. }
  70331. Font::Font (const Font& other) throw()
  70332. : font (other.font)
  70333. {
  70334. }
  70335. Font& Font::operator= (const Font& other) throw()
  70336. {
  70337. font = other.font;
  70338. return *this;
  70339. }
  70340. Font::~Font() throw()
  70341. {
  70342. }
  70343. Font::Font (const Typeface::Ptr& typeface) throw()
  70344. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  70345. 1.0f, 0, 0, Font::plain, typeface))
  70346. {
  70347. }
  70348. bool Font::operator== (const Font& other) const throw()
  70349. {
  70350. return font == other.font
  70351. || (font->height == other.font->height
  70352. && font->styleFlags == other.font->styleFlags
  70353. && font->horizontalScale == other.font->horizontalScale
  70354. && font->kerning == other.font->kerning
  70355. && font->typefaceName == other.font->typefaceName);
  70356. }
  70357. bool Font::operator!= (const Font& other) const throw()
  70358. {
  70359. return ! operator== (other);
  70360. }
  70361. void Font::dupeInternalIfShared() throw()
  70362. {
  70363. if (font->getReferenceCount() > 1)
  70364. font = new SharedFontInternal (*font);
  70365. }
  70366. const String Font::getDefaultSansSerifFontName() throw()
  70367. {
  70368. static const String name ("<Sans-Serif>");
  70369. return name;
  70370. }
  70371. const String Font::getDefaultSerifFontName() throw()
  70372. {
  70373. static const String name ("<Serif>");
  70374. return name;
  70375. }
  70376. const String Font::getDefaultMonospacedFontName() throw()
  70377. {
  70378. static const String name ("<Monospaced>");
  70379. return name;
  70380. }
  70381. void Font::setTypefaceName (const String& faceName) throw()
  70382. {
  70383. if (faceName != font->typefaceName)
  70384. {
  70385. dupeInternalIfShared();
  70386. font->typefaceName = faceName;
  70387. font->typeface = 0;
  70388. font->ascent = 0;
  70389. }
  70390. }
  70391. const String Font::getFallbackFontName() throw()
  70392. {
  70393. return FontValues::fallbackFont;
  70394. }
  70395. void Font::setFallbackFontName (const String& name) throw()
  70396. {
  70397. FontValues::fallbackFont = name;
  70398. }
  70399. void Font::setHeight (float newHeight) throw()
  70400. {
  70401. newHeight = FontValues::limitFontHeight (newHeight);
  70402. if (font->height != newHeight)
  70403. {
  70404. dupeInternalIfShared();
  70405. font->height = newHeight;
  70406. }
  70407. }
  70408. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  70409. {
  70410. newHeight = FontValues::limitFontHeight (newHeight);
  70411. if (font->height != newHeight)
  70412. {
  70413. dupeInternalIfShared();
  70414. font->horizontalScale *= (font->height / newHeight);
  70415. font->height = newHeight;
  70416. }
  70417. }
  70418. void Font::setStyleFlags (const int newFlags) throw()
  70419. {
  70420. if (font->styleFlags != newFlags)
  70421. {
  70422. dupeInternalIfShared();
  70423. font->styleFlags = newFlags;
  70424. font->typeface = 0;
  70425. font->ascent = 0;
  70426. }
  70427. }
  70428. void Font::setSizeAndStyle (float newHeight,
  70429. const int newStyleFlags,
  70430. const float newHorizontalScale,
  70431. const float newKerningAmount) throw()
  70432. {
  70433. newHeight = FontValues::limitFontHeight (newHeight);
  70434. if (font->height != newHeight
  70435. || font->horizontalScale != newHorizontalScale
  70436. || font->kerning != newKerningAmount)
  70437. {
  70438. dupeInternalIfShared();
  70439. font->height = newHeight;
  70440. font->horizontalScale = newHorizontalScale;
  70441. font->kerning = newKerningAmount;
  70442. }
  70443. setStyleFlags (newStyleFlags);
  70444. }
  70445. void Font::setHorizontalScale (const float scaleFactor) throw()
  70446. {
  70447. dupeInternalIfShared();
  70448. font->horizontalScale = scaleFactor;
  70449. }
  70450. void Font::setExtraKerningFactor (const float extraKerning) throw()
  70451. {
  70452. dupeInternalIfShared();
  70453. font->kerning = extraKerning;
  70454. }
  70455. void Font::setBold (const bool shouldBeBold) throw()
  70456. {
  70457. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  70458. : (font->styleFlags & ~bold));
  70459. }
  70460. bool Font::isBold() const throw()
  70461. {
  70462. return (font->styleFlags & bold) != 0;
  70463. }
  70464. void Font::setItalic (const bool shouldBeItalic) throw()
  70465. {
  70466. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  70467. : (font->styleFlags & ~italic));
  70468. }
  70469. bool Font::isItalic() const throw()
  70470. {
  70471. return (font->styleFlags & italic) != 0;
  70472. }
  70473. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  70474. {
  70475. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  70476. : (font->styleFlags & ~underlined));
  70477. }
  70478. bool Font::isUnderlined() const throw()
  70479. {
  70480. return (font->styleFlags & underlined) != 0;
  70481. }
  70482. float Font::getAscent() const throw()
  70483. {
  70484. if (font->ascent == 0)
  70485. font->ascent = getTypeface()->getAscent();
  70486. return font->height * font->ascent;
  70487. }
  70488. float Font::getDescent() const throw()
  70489. {
  70490. return font->height - getAscent();
  70491. }
  70492. int Font::getStringWidth (const String& text) const throw()
  70493. {
  70494. return roundToInt (getStringWidthFloat (text));
  70495. }
  70496. float Font::getStringWidthFloat (const String& text) const throw()
  70497. {
  70498. float w = getTypeface()->getStringWidth (text);
  70499. if (font->kerning != 0)
  70500. w += font->kerning * text.length();
  70501. return w * font->height * font->horizontalScale;
  70502. }
  70503. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  70504. {
  70505. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  70506. const float scale = font->height * font->horizontalScale;
  70507. const int num = xOffsets.size();
  70508. if (num > 0)
  70509. {
  70510. float* const x = &(xOffsets.getReference(0));
  70511. if (font->kerning != 0)
  70512. {
  70513. for (int i = 0; i < num; ++i)
  70514. x[i] = (x[i] + i * font->kerning) * scale;
  70515. }
  70516. else
  70517. {
  70518. for (int i = 0; i < num; ++i)
  70519. x[i] *= scale;
  70520. }
  70521. }
  70522. }
  70523. void Font::findFonts (Array<Font>& destArray) throw()
  70524. {
  70525. const StringArray names (findAllTypefaceNames());
  70526. for (int i = 0; i < names.size(); ++i)
  70527. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  70528. }
  70529. const String Font::toString() const
  70530. {
  70531. String s (getTypefaceName());
  70532. if (s == getDefaultSansSerifFontName())
  70533. s = String::empty;
  70534. else
  70535. s += "; ";
  70536. s += String (getHeight(), 1);
  70537. if (isBold())
  70538. s += " bold";
  70539. if (isItalic())
  70540. s += " italic";
  70541. return s;
  70542. }
  70543. const Font Font::fromString (const String& fontDescription)
  70544. {
  70545. String name;
  70546. const int separator = fontDescription.indexOfChar (';');
  70547. if (separator > 0)
  70548. name = fontDescription.substring (0, separator).trim();
  70549. if (name.isEmpty())
  70550. name = getDefaultSansSerifFontName();
  70551. String sizeAndStyle (fontDescription.substring (separator + 1));
  70552. float height = sizeAndStyle.getFloatValue();
  70553. if (height <= 0)
  70554. height = 10.0f;
  70555. int flags = Font::plain;
  70556. if (sizeAndStyle.containsIgnoreCase ("bold"))
  70557. flags |= Font::bold;
  70558. if (sizeAndStyle.containsIgnoreCase ("italic"))
  70559. flags |= Font::italic;
  70560. return Font (name, height, flags);
  70561. }
  70562. class TypefaceCache : public DeletedAtShutdown
  70563. {
  70564. public:
  70565. TypefaceCache (int numToCache = 10) throw()
  70566. : counter (1)
  70567. {
  70568. while (--numToCache >= 0)
  70569. faces.add (new CachedFace());
  70570. }
  70571. ~TypefaceCache()
  70572. {
  70573. clearSingletonInstance();
  70574. }
  70575. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  70576. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  70577. {
  70578. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  70579. const String faceName (font.getTypefaceName());
  70580. int i;
  70581. for (i = faces.size(); --i >= 0;)
  70582. {
  70583. CachedFace* const face = faces.getUnchecked(i);
  70584. if (face->flags == flags
  70585. && face->typefaceName == faceName)
  70586. {
  70587. face->lastUsageCount = ++counter;
  70588. return face->typeFace;
  70589. }
  70590. }
  70591. int replaceIndex = 0;
  70592. int bestLastUsageCount = std::numeric_limits<int>::max();
  70593. for (i = faces.size(); --i >= 0;)
  70594. {
  70595. const int lu = faces.getUnchecked(i)->lastUsageCount;
  70596. if (bestLastUsageCount > lu)
  70597. {
  70598. bestLastUsageCount = lu;
  70599. replaceIndex = i;
  70600. }
  70601. }
  70602. CachedFace* const face = faces.getUnchecked (replaceIndex);
  70603. face->typefaceName = faceName;
  70604. face->flags = flags;
  70605. face->lastUsageCount = ++counter;
  70606. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  70607. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  70608. return face->typeFace;
  70609. }
  70610. juce_UseDebuggingNewOperator
  70611. private:
  70612. struct CachedFace
  70613. {
  70614. CachedFace() throw()
  70615. : lastUsageCount (0), flags (-1)
  70616. {
  70617. }
  70618. String typefaceName;
  70619. int lastUsageCount;
  70620. int flags;
  70621. Typeface::Ptr typeFace;
  70622. };
  70623. int counter;
  70624. OwnedArray <CachedFace> faces;
  70625. TypefaceCache (const TypefaceCache&);
  70626. TypefaceCache& operator= (const TypefaceCache&);
  70627. };
  70628. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  70629. Typeface* Font::getTypeface() const throw()
  70630. {
  70631. if (font->typeface == 0)
  70632. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  70633. return font->typeface;
  70634. }
  70635. END_JUCE_NAMESPACE
  70636. /*** End of inlined file: juce_Font.cpp ***/
  70637. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  70638. BEGIN_JUCE_NAMESPACE
  70639. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  70640. const juce_wchar character_, const int glyph_)
  70641. : x (x_),
  70642. y (y_),
  70643. w (w_),
  70644. font (font_),
  70645. character (character_),
  70646. glyph (glyph_)
  70647. {
  70648. }
  70649. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  70650. : x (other.x),
  70651. y (other.y),
  70652. w (other.w),
  70653. font (other.font),
  70654. character (other.character),
  70655. glyph (other.glyph)
  70656. {
  70657. }
  70658. void PositionedGlyph::draw (const Graphics& g) const
  70659. {
  70660. if (! isWhitespace())
  70661. {
  70662. g.getInternalContext()->setFont (font);
  70663. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  70664. }
  70665. }
  70666. void PositionedGlyph::draw (const Graphics& g,
  70667. const AffineTransform& transform) const
  70668. {
  70669. if (! isWhitespace())
  70670. {
  70671. g.getInternalContext()->setFont (font);
  70672. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  70673. .followedBy (transform));
  70674. }
  70675. }
  70676. void PositionedGlyph::createPath (Path& path) const
  70677. {
  70678. if (! isWhitespace())
  70679. {
  70680. Typeface* const t = font.getTypeface();
  70681. if (t != 0)
  70682. {
  70683. Path p;
  70684. t->getOutlineForGlyph (glyph, p);
  70685. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  70686. .translated (x, y));
  70687. }
  70688. }
  70689. }
  70690. bool PositionedGlyph::hitTest (float px, float py) const
  70691. {
  70692. if (getBounds().contains (px, py) && ! isWhitespace())
  70693. {
  70694. Typeface* const t = font.getTypeface();
  70695. if (t != 0)
  70696. {
  70697. Path p;
  70698. t->getOutlineForGlyph (glyph, p);
  70699. AffineTransform::translation (-x, -y)
  70700. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  70701. .transformPoint (px, py);
  70702. return p.contains (px, py);
  70703. }
  70704. }
  70705. return false;
  70706. }
  70707. void PositionedGlyph::moveBy (const float deltaX,
  70708. const float deltaY)
  70709. {
  70710. x += deltaX;
  70711. y += deltaY;
  70712. }
  70713. GlyphArrangement::GlyphArrangement()
  70714. {
  70715. glyphs.ensureStorageAllocated (128);
  70716. }
  70717. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  70718. {
  70719. addGlyphArrangement (other);
  70720. }
  70721. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  70722. {
  70723. if (this != &other)
  70724. {
  70725. clear();
  70726. addGlyphArrangement (other);
  70727. }
  70728. return *this;
  70729. }
  70730. GlyphArrangement::~GlyphArrangement()
  70731. {
  70732. }
  70733. void GlyphArrangement::clear()
  70734. {
  70735. glyphs.clear();
  70736. }
  70737. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  70738. {
  70739. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  70740. return *glyphs [index];
  70741. }
  70742. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  70743. {
  70744. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  70745. glyphs.addCopiesOf (other.glyphs);
  70746. }
  70747. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  70748. {
  70749. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  70750. }
  70751. void GlyphArrangement::addLineOfText (const Font& font,
  70752. const String& text,
  70753. const float xOffset,
  70754. const float yOffset)
  70755. {
  70756. addCurtailedLineOfText (font, text,
  70757. xOffset, yOffset,
  70758. 1.0e10f, false);
  70759. }
  70760. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  70761. const String& text,
  70762. float xOffset,
  70763. const float yOffset,
  70764. const float maxWidthPixels,
  70765. const bool useEllipsis)
  70766. {
  70767. if (text.isNotEmpty())
  70768. {
  70769. Array <int> newGlyphs;
  70770. Array <float> xOffsets;
  70771. font.getGlyphPositions (text, newGlyphs, xOffsets);
  70772. const int textLen = newGlyphs.size();
  70773. const juce_wchar* const unicodeText = text;
  70774. for (int i = 0; i < textLen; ++i)
  70775. {
  70776. const float thisX = xOffsets.getUnchecked (i);
  70777. const float nextX = xOffsets.getUnchecked (i + 1);
  70778. if (nextX > maxWidthPixels + 1.0f)
  70779. {
  70780. // curtail the string if it's too wide..
  70781. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  70782. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  70783. break;
  70784. }
  70785. else
  70786. {
  70787. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  70788. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  70789. }
  70790. }
  70791. }
  70792. }
  70793. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  70794. const int startIndex, int endIndex)
  70795. {
  70796. int numDeleted = 0;
  70797. if (glyphs.size() > 0)
  70798. {
  70799. Array<int> dotGlyphs;
  70800. Array<float> dotXs;
  70801. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  70802. const float dx = dotXs[1];
  70803. float xOffset = 0.0f, yOffset = 0.0f;
  70804. while (endIndex > startIndex)
  70805. {
  70806. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  70807. xOffset = pg->x;
  70808. yOffset = pg->y;
  70809. glyphs.remove (endIndex);
  70810. ++numDeleted;
  70811. if (xOffset + dx * 3 <= maxXPos)
  70812. break;
  70813. }
  70814. for (int i = 3; --i >= 0;)
  70815. {
  70816. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  70817. font, '.', dotGlyphs.getFirst()));
  70818. --numDeleted;
  70819. xOffset += dx;
  70820. if (xOffset > maxXPos)
  70821. break;
  70822. }
  70823. }
  70824. return numDeleted;
  70825. }
  70826. void GlyphArrangement::addJustifiedText (const Font& font,
  70827. const String& text,
  70828. float x, float y,
  70829. const float maxLineWidth,
  70830. const Justification& horizontalLayout)
  70831. {
  70832. int lineStartIndex = glyphs.size();
  70833. addLineOfText (font, text, x, y);
  70834. const float originalY = y;
  70835. while (lineStartIndex < glyphs.size())
  70836. {
  70837. int i = lineStartIndex;
  70838. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  70839. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  70840. ++i;
  70841. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  70842. int lastWordBreakIndex = -1;
  70843. while (i < glyphs.size())
  70844. {
  70845. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  70846. const juce_wchar c = pg->getCharacter();
  70847. if (c == '\r' || c == '\n')
  70848. {
  70849. ++i;
  70850. if (c == '\r' && i < glyphs.size()
  70851. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  70852. ++i;
  70853. break;
  70854. }
  70855. else if (pg->isWhitespace())
  70856. {
  70857. lastWordBreakIndex = i + 1;
  70858. }
  70859. else if (pg->getRight() - 0.0001f >= lineMaxX)
  70860. {
  70861. if (lastWordBreakIndex >= 0)
  70862. i = lastWordBreakIndex;
  70863. break;
  70864. }
  70865. ++i;
  70866. }
  70867. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  70868. float currentLineEndX = currentLineStartX;
  70869. for (int j = i; --j >= lineStartIndex;)
  70870. {
  70871. if (! glyphs.getUnchecked (j)->isWhitespace())
  70872. {
  70873. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  70874. break;
  70875. }
  70876. }
  70877. float deltaX = 0.0f;
  70878. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  70879. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  70880. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  70881. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  70882. else if (horizontalLayout.testFlags (Justification::right))
  70883. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  70884. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  70885. x + deltaX - currentLineStartX, y - originalY);
  70886. lineStartIndex = i;
  70887. y += font.getHeight();
  70888. }
  70889. }
  70890. void GlyphArrangement::addFittedText (const Font& f,
  70891. const String& text,
  70892. const float x, const float y,
  70893. const float width, const float height,
  70894. const Justification& layout,
  70895. int maximumLines,
  70896. const float minimumHorizontalScale)
  70897. {
  70898. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  70899. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  70900. if (text.containsAnyOf ("\r\n"))
  70901. {
  70902. GlyphArrangement ga;
  70903. ga.addJustifiedText (f, text, x, y, width, layout);
  70904. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  70905. float dy = y - bb.getY();
  70906. if (layout.testFlags (Justification::verticallyCentred))
  70907. dy += (height - bb.getHeight()) * 0.5f;
  70908. else if (layout.testFlags (Justification::bottom))
  70909. dy += height - bb.getHeight();
  70910. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  70911. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  70912. for (int i = 0; i < ga.glyphs.size(); ++i)
  70913. glyphs.add (ga.glyphs.getUnchecked (i));
  70914. ga.glyphs.clear (false);
  70915. return;
  70916. }
  70917. int startIndex = glyphs.size();
  70918. addLineOfText (f, text.trim(), x, y);
  70919. if (glyphs.size() > startIndex)
  70920. {
  70921. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  70922. - glyphs.getUnchecked (startIndex)->getLeft();
  70923. if (lineWidth <= 0)
  70924. return;
  70925. if (lineWidth * minimumHorizontalScale < width)
  70926. {
  70927. if (lineWidth > width)
  70928. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  70929. width / lineWidth);
  70930. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  70931. x, y, width, height, layout);
  70932. }
  70933. else if (maximumLines <= 1)
  70934. {
  70935. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  70936. x, y, width, height, f, layout, minimumHorizontalScale);
  70937. }
  70938. else
  70939. {
  70940. Font font (f);
  70941. String txt (text.trim());
  70942. const int length = txt.length();
  70943. const int originalStartIndex = startIndex;
  70944. int numLines = 1;
  70945. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  70946. maximumLines = 1;
  70947. maximumLines = jmin (maximumLines, length);
  70948. while (numLines < maximumLines)
  70949. {
  70950. ++numLines;
  70951. const float newFontHeight = height / (float) numLines;
  70952. if (newFontHeight < font.getHeight())
  70953. {
  70954. font.setHeight (jmax (8.0f, newFontHeight));
  70955. removeRangeOfGlyphs (startIndex, -1);
  70956. addLineOfText (font, txt, x, y);
  70957. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  70958. - glyphs.getUnchecked (startIndex)->getLeft();
  70959. }
  70960. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  70961. break;
  70962. }
  70963. if (numLines < 1)
  70964. numLines = 1;
  70965. float lineY = y;
  70966. float widthPerLine = lineWidth / numLines;
  70967. int lastLineStartIndex = 0;
  70968. for (int line = 0; line < numLines; ++line)
  70969. {
  70970. int i = startIndex;
  70971. lastLineStartIndex = i;
  70972. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  70973. if (line == numLines - 1)
  70974. {
  70975. widthPerLine = width;
  70976. i = glyphs.size();
  70977. }
  70978. else
  70979. {
  70980. while (i < glyphs.size())
  70981. {
  70982. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  70983. if (lineWidth > widthPerLine)
  70984. {
  70985. // got to a point where the line's too long, so skip forward to find a
  70986. // good place to break it..
  70987. const int searchStartIndex = i;
  70988. while (i < glyphs.size())
  70989. {
  70990. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  70991. {
  70992. if (glyphs.getUnchecked (i)->isWhitespace()
  70993. || glyphs.getUnchecked (i)->getCharacter() == '-')
  70994. {
  70995. ++i;
  70996. break;
  70997. }
  70998. }
  70999. else
  71000. {
  71001. // can't find a suitable break, so try looking backwards..
  71002. i = searchStartIndex;
  71003. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  71004. {
  71005. if (glyphs.getUnchecked (i - back)->isWhitespace()
  71006. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  71007. {
  71008. i -= back - 1;
  71009. break;
  71010. }
  71011. }
  71012. break;
  71013. }
  71014. ++i;
  71015. }
  71016. break;
  71017. }
  71018. ++i;
  71019. }
  71020. int wsStart = i;
  71021. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  71022. --wsStart;
  71023. int wsEnd = i;
  71024. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  71025. ++wsEnd;
  71026. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  71027. i = jmax (wsStart, startIndex + 1);
  71028. }
  71029. i -= fitLineIntoSpace (startIndex, i - startIndex,
  71030. x, lineY, width, font.getHeight(), font,
  71031. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  71032. minimumHorizontalScale);
  71033. startIndex = i;
  71034. lineY += font.getHeight();
  71035. if (startIndex >= glyphs.size())
  71036. break;
  71037. }
  71038. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  71039. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  71040. }
  71041. }
  71042. }
  71043. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  71044. const float dx, const float dy)
  71045. {
  71046. jassert (startIndex >= 0);
  71047. if (dx != 0.0f || dy != 0.0f)
  71048. {
  71049. if (num < 0 || startIndex + num > glyphs.size())
  71050. num = glyphs.size() - startIndex;
  71051. while (--num >= 0)
  71052. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  71053. }
  71054. }
  71055. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  71056. const Justification& justification, float minimumHorizontalScale)
  71057. {
  71058. int numDeleted = 0;
  71059. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  71060. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  71061. if (lineWidth > w)
  71062. {
  71063. if (minimumHorizontalScale < 1.0f)
  71064. {
  71065. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  71066. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  71067. }
  71068. if (lineWidth > w)
  71069. {
  71070. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  71071. numGlyphs -= numDeleted;
  71072. }
  71073. }
  71074. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  71075. return numDeleted;
  71076. }
  71077. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  71078. const float horizontalScaleFactor)
  71079. {
  71080. jassert (startIndex >= 0);
  71081. if (num < 0 || startIndex + num > glyphs.size())
  71082. num = glyphs.size() - startIndex;
  71083. if (num > 0)
  71084. {
  71085. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  71086. while (--num >= 0)
  71087. {
  71088. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  71089. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  71090. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  71091. pg->w *= horizontalScaleFactor;
  71092. }
  71093. }
  71094. }
  71095. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  71096. {
  71097. jassert (startIndex >= 0);
  71098. if (num < 0 || startIndex + num > glyphs.size())
  71099. num = glyphs.size() - startIndex;
  71100. Rectangle<float> result;
  71101. while (--num >= 0)
  71102. {
  71103. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  71104. if (includeWhitespace || ! pg->isWhitespace())
  71105. result = result.getUnion (pg->getBounds());
  71106. }
  71107. return result;
  71108. }
  71109. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  71110. const float x, const float y, const float width, const float height,
  71111. const Justification& justification)
  71112. {
  71113. jassert (num >= 0 && startIndex >= 0);
  71114. if (glyphs.size() > 0 && num > 0)
  71115. {
  71116. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  71117. | Justification::horizontallyCentred)));
  71118. float deltaX = 0.0f;
  71119. if (justification.testFlags (Justification::horizontallyJustified))
  71120. deltaX = x - bb.getX();
  71121. else if (justification.testFlags (Justification::horizontallyCentred))
  71122. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  71123. else if (justification.testFlags (Justification::right))
  71124. deltaX = (x + width) - bb.getRight();
  71125. else
  71126. deltaX = x - bb.getX();
  71127. float deltaY = 0.0f;
  71128. if (justification.testFlags (Justification::top))
  71129. deltaY = y - bb.getY();
  71130. else if (justification.testFlags (Justification::bottom))
  71131. deltaY = (y + height) - bb.getBottom();
  71132. else
  71133. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  71134. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  71135. if (justification.testFlags (Justification::horizontallyJustified))
  71136. {
  71137. int lineStart = 0;
  71138. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  71139. int i;
  71140. for (i = 0; i < num; ++i)
  71141. {
  71142. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  71143. if (glyphY != baseY)
  71144. {
  71145. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  71146. lineStart = i;
  71147. baseY = glyphY;
  71148. }
  71149. }
  71150. if (i > lineStart)
  71151. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  71152. }
  71153. }
  71154. }
  71155. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  71156. {
  71157. if (start + num < glyphs.size()
  71158. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  71159. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  71160. {
  71161. int numSpaces = 0;
  71162. int spacesAtEnd = 0;
  71163. for (int i = 0; i < num; ++i)
  71164. {
  71165. if (glyphs.getUnchecked (start + i)->isWhitespace())
  71166. {
  71167. ++spacesAtEnd;
  71168. ++numSpaces;
  71169. }
  71170. else
  71171. {
  71172. spacesAtEnd = 0;
  71173. }
  71174. }
  71175. numSpaces -= spacesAtEnd;
  71176. if (numSpaces > 0)
  71177. {
  71178. const float startX = glyphs.getUnchecked (start)->getLeft();
  71179. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  71180. const float extraPaddingBetweenWords
  71181. = (targetWidth - (endX - startX)) / (float) numSpaces;
  71182. float deltaX = 0.0f;
  71183. for (int i = 0; i < num; ++i)
  71184. {
  71185. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  71186. if (glyphs.getUnchecked (start + i)->isWhitespace())
  71187. deltaX += extraPaddingBetweenWords;
  71188. }
  71189. }
  71190. }
  71191. }
  71192. void GlyphArrangement::draw (const Graphics& g) const
  71193. {
  71194. for (int i = 0; i < glyphs.size(); ++i)
  71195. {
  71196. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  71197. if (pg->font.isUnderlined())
  71198. {
  71199. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  71200. float nextX = pg->x + pg->w;
  71201. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  71202. nextX = glyphs.getUnchecked (i + 1)->x;
  71203. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  71204. nextX - pg->x, lineThickness);
  71205. }
  71206. pg->draw (g);
  71207. }
  71208. }
  71209. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  71210. {
  71211. for (int i = 0; i < glyphs.size(); ++i)
  71212. {
  71213. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  71214. if (pg->font.isUnderlined())
  71215. {
  71216. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  71217. float nextX = pg->x + pg->w;
  71218. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  71219. nextX = glyphs.getUnchecked (i + 1)->x;
  71220. Path p;
  71221. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  71222. nextX, pg->y + lineThickness * 2.0f),
  71223. lineThickness);
  71224. g.fillPath (p, transform);
  71225. }
  71226. pg->draw (g, transform);
  71227. }
  71228. }
  71229. void GlyphArrangement::createPath (Path& path) const
  71230. {
  71231. for (int i = 0; i < glyphs.size(); ++i)
  71232. glyphs.getUnchecked (i)->createPath (path);
  71233. }
  71234. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  71235. {
  71236. for (int i = 0; i < glyphs.size(); ++i)
  71237. if (glyphs.getUnchecked (i)->hitTest (x, y))
  71238. return i;
  71239. return -1;
  71240. }
  71241. END_JUCE_NAMESPACE
  71242. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  71243. /*** Start of inlined file: juce_TextLayout.cpp ***/
  71244. BEGIN_JUCE_NAMESPACE
  71245. class TextLayout::Token
  71246. {
  71247. public:
  71248. String text;
  71249. Font font;
  71250. int x, y, w, h;
  71251. int line, lineHeight;
  71252. bool isWhitespace, isNewLine;
  71253. Token (const String& t,
  71254. const Font& f,
  71255. const bool isWhitespace_)
  71256. : text (t),
  71257. font (f),
  71258. x(0),
  71259. y(0),
  71260. isWhitespace (isWhitespace_)
  71261. {
  71262. w = font.getStringWidth (t);
  71263. h = roundToInt (f.getHeight());
  71264. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  71265. }
  71266. Token (const Token& other)
  71267. : text (other.text),
  71268. font (other.font),
  71269. x (other.x),
  71270. y (other.y),
  71271. w (other.w),
  71272. h (other.h),
  71273. line (other.line),
  71274. lineHeight (other.lineHeight),
  71275. isWhitespace (other.isWhitespace),
  71276. isNewLine (other.isNewLine)
  71277. {
  71278. }
  71279. ~Token()
  71280. {
  71281. }
  71282. void draw (Graphics& g,
  71283. const int xOffset,
  71284. const int yOffset)
  71285. {
  71286. if (! isWhitespace)
  71287. {
  71288. g.setFont (font);
  71289. g.drawSingleLineText (text.trimEnd(),
  71290. xOffset + x,
  71291. yOffset + y + (lineHeight - h)
  71292. + roundToInt (font.getAscent()));
  71293. }
  71294. }
  71295. juce_UseDebuggingNewOperator
  71296. };
  71297. TextLayout::TextLayout()
  71298. : totalLines (0)
  71299. {
  71300. tokens.ensureStorageAllocated (64);
  71301. }
  71302. TextLayout::TextLayout (const String& text, const Font& font)
  71303. : totalLines (0)
  71304. {
  71305. tokens.ensureStorageAllocated (64);
  71306. appendText (text, font);
  71307. }
  71308. TextLayout::TextLayout (const TextLayout& other)
  71309. : totalLines (0)
  71310. {
  71311. *this = other;
  71312. }
  71313. TextLayout& TextLayout::operator= (const TextLayout& other)
  71314. {
  71315. if (this != &other)
  71316. {
  71317. clear();
  71318. totalLines = other.totalLines;
  71319. tokens.addCopiesOf (other.tokens);
  71320. }
  71321. return *this;
  71322. }
  71323. TextLayout::~TextLayout()
  71324. {
  71325. clear();
  71326. }
  71327. void TextLayout::clear()
  71328. {
  71329. tokens.clear();
  71330. totalLines = 0;
  71331. }
  71332. void TextLayout::appendText (const String& text, const Font& font)
  71333. {
  71334. const juce_wchar* t = text;
  71335. String currentString;
  71336. int lastCharType = 0;
  71337. for (;;)
  71338. {
  71339. const juce_wchar c = *t++;
  71340. if (c == 0)
  71341. break;
  71342. int charType;
  71343. if (c == '\r' || c == '\n')
  71344. {
  71345. charType = 0;
  71346. }
  71347. else if (CharacterFunctions::isWhitespace (c))
  71348. {
  71349. charType = 2;
  71350. }
  71351. else
  71352. {
  71353. charType = 1;
  71354. }
  71355. if (charType == 0 || charType != lastCharType)
  71356. {
  71357. if (currentString.isNotEmpty())
  71358. {
  71359. tokens.add (new Token (currentString, font,
  71360. lastCharType == 2 || lastCharType == 0));
  71361. }
  71362. currentString = String::charToString (c);
  71363. if (c == '\r' && *t == '\n')
  71364. currentString += *t++;
  71365. }
  71366. else
  71367. {
  71368. currentString += c;
  71369. }
  71370. lastCharType = charType;
  71371. }
  71372. if (currentString.isNotEmpty())
  71373. tokens.add (new Token (currentString, font, lastCharType == 2));
  71374. }
  71375. void TextLayout::setText (const String& text, const Font& font)
  71376. {
  71377. clear();
  71378. appendText (text, font);
  71379. }
  71380. void TextLayout::layout (int maxWidth,
  71381. const Justification& justification,
  71382. const bool attemptToBalanceLineLengths)
  71383. {
  71384. if (attemptToBalanceLineLengths)
  71385. {
  71386. const int originalW = maxWidth;
  71387. int bestWidth = maxWidth;
  71388. float bestLineProportion = 0.0f;
  71389. while (maxWidth > originalW / 2)
  71390. {
  71391. layout (maxWidth, justification, false);
  71392. if (getNumLines() <= 1)
  71393. return;
  71394. const int lastLineW = getLineWidth (getNumLines() - 1);
  71395. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  71396. const float prop = lastLineW / (float) lastButOneLineW;
  71397. if (prop > 0.9f)
  71398. return;
  71399. if (prop > bestLineProportion)
  71400. {
  71401. bestLineProportion = prop;
  71402. bestWidth = maxWidth;
  71403. }
  71404. maxWidth -= 10;
  71405. }
  71406. layout (bestWidth, justification, false);
  71407. }
  71408. else
  71409. {
  71410. int x = 0;
  71411. int y = 0;
  71412. int h = 0;
  71413. totalLines = 0;
  71414. int i;
  71415. for (i = 0; i < tokens.size(); ++i)
  71416. {
  71417. Token* const t = tokens.getUnchecked(i);
  71418. t->x = x;
  71419. t->y = y;
  71420. t->line = totalLines;
  71421. x += t->w;
  71422. h = jmax (h, t->h);
  71423. const Token* nextTok = tokens [i + 1];
  71424. if (nextTok == 0)
  71425. break;
  71426. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  71427. {
  71428. // finished a line, so go back and update the heights of the things on it
  71429. for (int j = i; j >= 0; --j)
  71430. {
  71431. Token* const tok = tokens.getUnchecked(j);
  71432. if (tok->line == totalLines)
  71433. tok->lineHeight = h;
  71434. else
  71435. break;
  71436. }
  71437. x = 0;
  71438. y += h;
  71439. h = 0;
  71440. ++totalLines;
  71441. }
  71442. }
  71443. // finished a line, so go back and update the heights of the things on it
  71444. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  71445. {
  71446. Token* const t = tokens.getUnchecked(j);
  71447. if (t->line == totalLines)
  71448. t->lineHeight = h;
  71449. else
  71450. break;
  71451. }
  71452. ++totalLines;
  71453. if (! justification.testFlags (Justification::left))
  71454. {
  71455. int totalW = getWidth();
  71456. for (i = totalLines; --i >= 0;)
  71457. {
  71458. const int lineW = getLineWidth (i);
  71459. int dx = 0;
  71460. if (justification.testFlags (Justification::horizontallyCentred))
  71461. dx = (totalW - lineW) / 2;
  71462. else if (justification.testFlags (Justification::right))
  71463. dx = totalW - lineW;
  71464. for (int j = tokens.size(); --j >= 0;)
  71465. {
  71466. Token* const t = tokens.getUnchecked(j);
  71467. if (t->line == i)
  71468. t->x += dx;
  71469. }
  71470. }
  71471. }
  71472. }
  71473. }
  71474. int TextLayout::getLineWidth (const int lineNumber) const
  71475. {
  71476. int maxW = 0;
  71477. for (int i = tokens.size(); --i >= 0;)
  71478. {
  71479. const Token* const t = tokens.getUnchecked(i);
  71480. if (t->line == lineNumber && ! t->isWhitespace)
  71481. maxW = jmax (maxW, t->x + t->w);
  71482. }
  71483. return maxW;
  71484. }
  71485. int TextLayout::getWidth() const
  71486. {
  71487. int maxW = 0;
  71488. for (int i = tokens.size(); --i >= 0;)
  71489. {
  71490. const Token* const t = tokens.getUnchecked(i);
  71491. if (! t->isWhitespace)
  71492. maxW = jmax (maxW, t->x + t->w);
  71493. }
  71494. return maxW;
  71495. }
  71496. int TextLayout::getHeight() const
  71497. {
  71498. int maxH = 0;
  71499. for (int i = tokens.size(); --i >= 0;)
  71500. {
  71501. const Token* const t = tokens.getUnchecked(i);
  71502. if (! t->isWhitespace)
  71503. maxH = jmax (maxH, t->y + t->h);
  71504. }
  71505. return maxH;
  71506. }
  71507. void TextLayout::draw (Graphics& g,
  71508. const int xOffset,
  71509. const int yOffset) const
  71510. {
  71511. for (int i = tokens.size(); --i >= 0;)
  71512. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  71513. }
  71514. void TextLayout::drawWithin (Graphics& g,
  71515. int x, int y, int w, int h,
  71516. const Justification& justification) const
  71517. {
  71518. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  71519. x, y, w, h);
  71520. draw (g, x, y);
  71521. }
  71522. END_JUCE_NAMESPACE
  71523. /*** End of inlined file: juce_TextLayout.cpp ***/
  71524. /*** Start of inlined file: juce_Typeface.cpp ***/
  71525. BEGIN_JUCE_NAMESPACE
  71526. Typeface::Typeface (const String& name_) throw()
  71527. : name (name_)
  71528. {
  71529. }
  71530. Typeface::~Typeface()
  71531. {
  71532. }
  71533. class CustomTypeface::GlyphInfo
  71534. {
  71535. public:
  71536. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  71537. : character (character_), path (path_), width (width_)
  71538. {
  71539. }
  71540. ~GlyphInfo() throw()
  71541. {
  71542. }
  71543. struct KerningPair
  71544. {
  71545. juce_wchar character2;
  71546. float kerningAmount;
  71547. };
  71548. void addKerningPair (const juce_wchar subsequentCharacter,
  71549. const float extraKerningAmount) throw()
  71550. {
  71551. KerningPair kp;
  71552. kp.character2 = subsequentCharacter;
  71553. kp.kerningAmount = extraKerningAmount;
  71554. kerningPairs.add (kp);
  71555. }
  71556. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  71557. {
  71558. if (subsequentCharacter != 0)
  71559. {
  71560. for (int i = kerningPairs.size(); --i >= 0;)
  71561. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  71562. return width + kerningPairs.getReference(i).kerningAmount;
  71563. }
  71564. return width;
  71565. }
  71566. const juce_wchar character;
  71567. const Path path;
  71568. float width;
  71569. Array <KerningPair> kerningPairs;
  71570. juce_UseDebuggingNewOperator
  71571. private:
  71572. GlyphInfo (const GlyphInfo&);
  71573. GlyphInfo& operator= (const GlyphInfo&);
  71574. };
  71575. CustomTypeface::CustomTypeface()
  71576. : Typeface (String::empty)
  71577. {
  71578. clear();
  71579. }
  71580. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  71581. : Typeface (String::empty)
  71582. {
  71583. clear();
  71584. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  71585. BufferedInputStream in (&gzin, 32768, false);
  71586. name = in.readString();
  71587. isBold = in.readBool();
  71588. isItalic = in.readBool();
  71589. ascent = in.readFloat();
  71590. defaultCharacter = (juce_wchar) in.readShort();
  71591. int i, numChars = in.readInt();
  71592. for (i = 0; i < numChars; ++i)
  71593. {
  71594. const juce_wchar c = (juce_wchar) in.readShort();
  71595. const float width = in.readFloat();
  71596. Path p;
  71597. p.loadPathFromStream (in);
  71598. addGlyph (c, p, width);
  71599. }
  71600. const int numKerningPairs = in.readInt();
  71601. for (i = 0; i < numKerningPairs; ++i)
  71602. {
  71603. const juce_wchar char1 = (juce_wchar) in.readShort();
  71604. const juce_wchar char2 = (juce_wchar) in.readShort();
  71605. addKerningPair (char1, char2, in.readFloat());
  71606. }
  71607. }
  71608. CustomTypeface::~CustomTypeface()
  71609. {
  71610. }
  71611. void CustomTypeface::clear()
  71612. {
  71613. defaultCharacter = 0;
  71614. ascent = 1.0f;
  71615. isBold = isItalic = false;
  71616. zeromem (lookupTable, sizeof (lookupTable));
  71617. glyphs.clear();
  71618. }
  71619. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  71620. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  71621. {
  71622. name = name_;
  71623. defaultCharacter = defaultCharacter_;
  71624. ascent = ascent_;
  71625. isBold = isBold_;
  71626. isItalic = isItalic_;
  71627. }
  71628. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  71629. {
  71630. // Check that you're not trying to add the same character twice..
  71631. jassert (findGlyph (character, false) == 0);
  71632. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  71633. lookupTable [character] = (short) glyphs.size();
  71634. glyphs.add (new GlyphInfo (character, path, width));
  71635. }
  71636. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  71637. {
  71638. if (extraAmount != 0)
  71639. {
  71640. GlyphInfo* const g = findGlyph (char1, true);
  71641. jassert (g != 0); // can only add kerning pairs for characters that exist!
  71642. if (g != 0)
  71643. g->addKerningPair (char2, extraAmount);
  71644. }
  71645. }
  71646. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  71647. {
  71648. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  71649. return glyphs [(int) lookupTable [(int) character]];
  71650. for (int i = 0; i < glyphs.size(); ++i)
  71651. {
  71652. GlyphInfo* const g = glyphs.getUnchecked(i);
  71653. if (g->character == character)
  71654. return g;
  71655. }
  71656. if (loadIfNeeded && loadGlyphIfPossible (character))
  71657. return findGlyph (character, false);
  71658. return 0;
  71659. }
  71660. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  71661. {
  71662. GlyphInfo* glyph = findGlyph (character, true);
  71663. if (glyph == 0)
  71664. {
  71665. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  71666. glyph = findGlyph (L' ', true);
  71667. if (glyph == 0)
  71668. {
  71669. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  71670. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  71671. if (fallbackTypeface != 0 && fallbackTypeface != this)
  71672. {
  71673. //xxx
  71674. }
  71675. if (glyph == 0)
  71676. glyph = findGlyph (defaultCharacter, true);
  71677. }
  71678. }
  71679. return glyph;
  71680. }
  71681. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  71682. {
  71683. return false;
  71684. }
  71685. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  71686. {
  71687. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  71688. for (int i = 0; i < numCharacters; ++i)
  71689. {
  71690. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  71691. Array <int> glyphIndexes;
  71692. Array <float> offsets;
  71693. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  71694. const int glyphIndex = glyphIndexes.getFirst();
  71695. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  71696. {
  71697. const float glyphWidth = offsets[1];
  71698. Path p;
  71699. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  71700. addGlyph (c, p, glyphWidth);
  71701. for (int j = glyphs.size() - 1; --j >= 0;)
  71702. {
  71703. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  71704. glyphIndexes.clearQuick();
  71705. offsets.clearQuick();
  71706. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  71707. if (offsets.size() > 1)
  71708. addKerningPair (c, char2, offsets[1] - glyphWidth);
  71709. }
  71710. }
  71711. }
  71712. }
  71713. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  71714. {
  71715. GZIPCompressorOutputStream out (&outputStream);
  71716. out.writeString (name);
  71717. out.writeBool (isBold);
  71718. out.writeBool (isItalic);
  71719. out.writeFloat (ascent);
  71720. out.writeShort ((short) (unsigned short) defaultCharacter);
  71721. out.writeInt (glyphs.size());
  71722. int i, numKerningPairs = 0;
  71723. for (i = 0; i < glyphs.size(); ++i)
  71724. {
  71725. const GlyphInfo* const g = glyphs.getUnchecked (i);
  71726. out.writeShort ((short) (unsigned short) g->character);
  71727. out.writeFloat (g->width);
  71728. g->path.writePathToStream (out);
  71729. numKerningPairs += g->kerningPairs.size();
  71730. }
  71731. out.writeInt (numKerningPairs);
  71732. for (i = 0; i < glyphs.size(); ++i)
  71733. {
  71734. const GlyphInfo* const g = glyphs.getUnchecked (i);
  71735. for (int j = 0; j < g->kerningPairs.size(); ++j)
  71736. {
  71737. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  71738. out.writeShort ((short) (unsigned short) g->character);
  71739. out.writeShort ((short) (unsigned short) p.character2);
  71740. out.writeFloat (p.kerningAmount);
  71741. }
  71742. }
  71743. return true;
  71744. }
  71745. float CustomTypeface::getAscent() const
  71746. {
  71747. return ascent;
  71748. }
  71749. float CustomTypeface::getDescent() const
  71750. {
  71751. return 1.0f - ascent;
  71752. }
  71753. float CustomTypeface::getStringWidth (const String& text)
  71754. {
  71755. float x = 0;
  71756. const juce_wchar* t = text;
  71757. while (*t != 0)
  71758. {
  71759. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  71760. if (glyph != 0)
  71761. x += glyph->getHorizontalSpacing (*t);
  71762. }
  71763. return x;
  71764. }
  71765. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  71766. {
  71767. xOffsets.add (0);
  71768. float x = 0;
  71769. const juce_wchar* t = text;
  71770. while (*t != 0)
  71771. {
  71772. const juce_wchar c = *t++;
  71773. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  71774. if (glyph != 0)
  71775. {
  71776. x += glyph->getHorizontalSpacing (*t);
  71777. resultGlyphs.add ((int) glyph->character);
  71778. xOffsets.add (x);
  71779. }
  71780. }
  71781. }
  71782. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  71783. {
  71784. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  71785. if (glyph != 0)
  71786. {
  71787. path = glyph->path;
  71788. return true;
  71789. }
  71790. return false;
  71791. }
  71792. END_JUCE_NAMESPACE
  71793. /*** End of inlined file: juce_Typeface.cpp ***/
  71794. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  71795. BEGIN_JUCE_NAMESPACE
  71796. AffineTransform::AffineTransform() throw()
  71797. : mat00 (1.0f),
  71798. mat01 (0),
  71799. mat02 (0),
  71800. mat10 (0),
  71801. mat11 (1.0f),
  71802. mat12 (0)
  71803. {
  71804. }
  71805. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  71806. : mat00 (other.mat00),
  71807. mat01 (other.mat01),
  71808. mat02 (other.mat02),
  71809. mat10 (other.mat10),
  71810. mat11 (other.mat11),
  71811. mat12 (other.mat12)
  71812. {
  71813. }
  71814. AffineTransform::AffineTransform (const float mat00_,
  71815. const float mat01_,
  71816. const float mat02_,
  71817. const float mat10_,
  71818. const float mat11_,
  71819. const float mat12_) throw()
  71820. : mat00 (mat00_),
  71821. mat01 (mat01_),
  71822. mat02 (mat02_),
  71823. mat10 (mat10_),
  71824. mat11 (mat11_),
  71825. mat12 (mat12_)
  71826. {
  71827. }
  71828. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  71829. {
  71830. mat00 = other.mat00;
  71831. mat01 = other.mat01;
  71832. mat02 = other.mat02;
  71833. mat10 = other.mat10;
  71834. mat11 = other.mat11;
  71835. mat12 = other.mat12;
  71836. return *this;
  71837. }
  71838. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  71839. {
  71840. return mat00 == other.mat00
  71841. && mat01 == other.mat01
  71842. && mat02 == other.mat02
  71843. && mat10 == other.mat10
  71844. && mat11 == other.mat11
  71845. && mat12 == other.mat12;
  71846. }
  71847. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  71848. {
  71849. return ! operator== (other);
  71850. }
  71851. bool AffineTransform::isIdentity() const throw()
  71852. {
  71853. return (mat01 == 0)
  71854. && (mat02 == 0)
  71855. && (mat10 == 0)
  71856. && (mat12 == 0)
  71857. && (mat00 == 1.0f)
  71858. && (mat11 == 1.0f);
  71859. }
  71860. const AffineTransform AffineTransform::identity;
  71861. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  71862. {
  71863. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  71864. other.mat00 * mat01 + other.mat01 * mat11,
  71865. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  71866. other.mat10 * mat00 + other.mat11 * mat10,
  71867. other.mat10 * mat01 + other.mat11 * mat11,
  71868. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  71869. }
  71870. const AffineTransform AffineTransform::followedBy (const float omat00,
  71871. const float omat01,
  71872. const float omat02,
  71873. const float omat10,
  71874. const float omat11,
  71875. const float omat12) const throw()
  71876. {
  71877. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  71878. omat00 * mat01 + omat01 * mat11,
  71879. omat00 * mat02 + omat01 * mat12 + omat02,
  71880. omat10 * mat00 + omat11 * mat10,
  71881. omat10 * mat01 + omat11 * mat11,
  71882. omat10 * mat02 + omat11 * mat12 + omat12);
  71883. }
  71884. const AffineTransform AffineTransform::translated (const float dx,
  71885. const float dy) const throw()
  71886. {
  71887. return AffineTransform (mat00, mat01, mat02 + dx,
  71888. mat10, mat11, mat12 + dy);
  71889. }
  71890. const AffineTransform AffineTransform::translation (const float dx,
  71891. const float dy) throw()
  71892. {
  71893. return AffineTransform (1.0f, 0, dx,
  71894. 0, 1.0f, dy);
  71895. }
  71896. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  71897. {
  71898. const float cosRad = std::cos (rad);
  71899. const float sinRad = std::sin (rad);
  71900. return followedBy (cosRad, -sinRad, 0,
  71901. sinRad, cosRad, 0);
  71902. }
  71903. const AffineTransform AffineTransform::rotation (const float rad) throw()
  71904. {
  71905. const float cosRad = std::cos (rad);
  71906. const float sinRad = std::sin (rad);
  71907. return AffineTransform (cosRad, -sinRad, 0,
  71908. sinRad, cosRad, 0);
  71909. }
  71910. const AffineTransform AffineTransform::rotated (const float angle,
  71911. const float pivotX,
  71912. const float pivotY) const throw()
  71913. {
  71914. return translated (-pivotX, -pivotY)
  71915. .rotated (angle)
  71916. .translated (pivotX, pivotY);
  71917. }
  71918. const AffineTransform AffineTransform::rotation (const float angle,
  71919. const float pivotX,
  71920. const float pivotY) throw()
  71921. {
  71922. return translation (-pivotX, -pivotY)
  71923. .rotated (angle)
  71924. .translated (pivotX, pivotY);
  71925. }
  71926. const AffineTransform AffineTransform::scaled (const float factorX,
  71927. const float factorY) const throw()
  71928. {
  71929. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  71930. factorY * mat10, factorY * mat11, factorY * mat12);
  71931. }
  71932. const AffineTransform AffineTransform::scale (const float factorX,
  71933. const float factorY) throw()
  71934. {
  71935. return AffineTransform (factorX, 0, 0,
  71936. 0, factorY, 0);
  71937. }
  71938. const AffineTransform AffineTransform::sheared (const float shearX,
  71939. const float shearY) const throw()
  71940. {
  71941. return followedBy (1.0f, shearX, 0,
  71942. shearY, 1.0f, 0);
  71943. }
  71944. const AffineTransform AffineTransform::inverted() const throw()
  71945. {
  71946. double determinant = (mat00 * mat11 - mat10 * mat01);
  71947. if (determinant != 0.0)
  71948. {
  71949. determinant = 1.0 / determinant;
  71950. const float dst00 = (float) (mat11 * determinant);
  71951. const float dst10 = (float) (-mat10 * determinant);
  71952. const float dst01 = (float) (-mat01 * determinant);
  71953. const float dst11 = (float) (mat00 * determinant);
  71954. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  71955. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  71956. }
  71957. else
  71958. {
  71959. // singularity..
  71960. return *this;
  71961. }
  71962. }
  71963. bool AffineTransform::isSingularity() const throw()
  71964. {
  71965. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  71966. }
  71967. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  71968. const float x10, const float y10,
  71969. const float x01, const float y01) throw()
  71970. {
  71971. return AffineTransform (x10 - x00, x01 - x00, x00,
  71972. y10 - y00, y01 - y00, y00);
  71973. }
  71974. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  71975. const float sx2, const float sy2, const float tx2, const float ty2,
  71976. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  71977. {
  71978. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  71979. .inverted()
  71980. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  71981. }
  71982. bool AffineTransform::isOnlyTranslation() const throw()
  71983. {
  71984. return (mat01 == 0)
  71985. && (mat10 == 0)
  71986. && (mat00 == 1.0f)
  71987. && (mat11 == 1.0f);
  71988. }
  71989. void AffineTransform::transformPoint (float& x,
  71990. float& y) const throw()
  71991. {
  71992. const float oldX = x;
  71993. x = mat00 * oldX + mat01 * y + mat02;
  71994. y = mat10 * oldX + mat11 * y + mat12;
  71995. }
  71996. void AffineTransform::transformPoint (double& x,
  71997. double& y) const throw()
  71998. {
  71999. const double oldX = x;
  72000. x = mat00 * oldX + mat01 * y + mat02;
  72001. y = mat10 * oldX + mat11 * y + mat12;
  72002. }
  72003. END_JUCE_NAMESPACE
  72004. /*** End of inlined file: juce_AffineTransform.cpp ***/
  72005. /*** Start of inlined file: juce_BorderSize.cpp ***/
  72006. BEGIN_JUCE_NAMESPACE
  72007. BorderSize::BorderSize() throw()
  72008. : top (0),
  72009. left (0),
  72010. bottom (0),
  72011. right (0)
  72012. {
  72013. }
  72014. BorderSize::BorderSize (const BorderSize& other) throw()
  72015. : top (other.top),
  72016. left (other.left),
  72017. bottom (other.bottom),
  72018. right (other.right)
  72019. {
  72020. }
  72021. BorderSize::BorderSize (const int topGap,
  72022. const int leftGap,
  72023. const int bottomGap,
  72024. const int rightGap) throw()
  72025. : top (topGap),
  72026. left (leftGap),
  72027. bottom (bottomGap),
  72028. right (rightGap)
  72029. {
  72030. }
  72031. BorderSize::BorderSize (const int allGaps) throw()
  72032. : top (allGaps),
  72033. left (allGaps),
  72034. bottom (allGaps),
  72035. right (allGaps)
  72036. {
  72037. }
  72038. BorderSize::~BorderSize() throw()
  72039. {
  72040. }
  72041. void BorderSize::setTop (const int newTopGap) throw()
  72042. {
  72043. top = newTopGap;
  72044. }
  72045. void BorderSize::setLeft (const int newLeftGap) throw()
  72046. {
  72047. left = newLeftGap;
  72048. }
  72049. void BorderSize::setBottom (const int newBottomGap) throw()
  72050. {
  72051. bottom = newBottomGap;
  72052. }
  72053. void BorderSize::setRight (const int newRightGap) throw()
  72054. {
  72055. right = newRightGap;
  72056. }
  72057. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  72058. {
  72059. return Rectangle<int> (r.getX() + left,
  72060. r.getY() + top,
  72061. r.getWidth() - (left + right),
  72062. r.getHeight() - (top + bottom));
  72063. }
  72064. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  72065. {
  72066. r.setBounds (r.getX() + left,
  72067. r.getY() + top,
  72068. r.getWidth() - (left + right),
  72069. r.getHeight() - (top + bottom));
  72070. }
  72071. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  72072. {
  72073. return Rectangle<int> (r.getX() - left,
  72074. r.getY() - top,
  72075. r.getWidth() + (left + right),
  72076. r.getHeight() + (top + bottom));
  72077. }
  72078. void BorderSize::addTo (Rectangle<int>& r) const throw()
  72079. {
  72080. r.setBounds (r.getX() - left,
  72081. r.getY() - top,
  72082. r.getWidth() + (left + right),
  72083. r.getHeight() + (top + bottom));
  72084. }
  72085. bool BorderSize::operator== (const BorderSize& other) const throw()
  72086. {
  72087. return top == other.top
  72088. && left == other.left
  72089. && bottom == other.bottom
  72090. && right == other.right;
  72091. }
  72092. bool BorderSize::operator!= (const BorderSize& other) const throw()
  72093. {
  72094. return ! operator== (other);
  72095. }
  72096. END_JUCE_NAMESPACE
  72097. /*** End of inlined file: juce_BorderSize.cpp ***/
  72098. /*** Start of inlined file: juce_Path.cpp ***/
  72099. BEGIN_JUCE_NAMESPACE
  72100. // tests that some co-ords aren't NaNs
  72101. #define CHECK_COORDS_ARE_VALID(x, y) \
  72102. jassert (x == x && y == y);
  72103. namespace PathHelpers
  72104. {
  72105. static const float ellipseAngularIncrement = 0.05f;
  72106. static const String nextToken (const juce_wchar*& t)
  72107. {
  72108. while (CharacterFunctions::isWhitespace (*t))
  72109. ++t;
  72110. const juce_wchar* const start = t;
  72111. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  72112. ++t;
  72113. return String (start, (int) (t - start));
  72114. }
  72115. }
  72116. const float Path::lineMarker = 100001.0f;
  72117. const float Path::moveMarker = 100002.0f;
  72118. const float Path::quadMarker = 100003.0f;
  72119. const float Path::cubicMarker = 100004.0f;
  72120. const float Path::closeSubPathMarker = 100005.0f;
  72121. Path::Path()
  72122. : numElements (0),
  72123. pathXMin (0),
  72124. pathXMax (0),
  72125. pathYMin (0),
  72126. pathYMax (0),
  72127. useNonZeroWinding (true)
  72128. {
  72129. }
  72130. Path::~Path()
  72131. {
  72132. }
  72133. Path::Path (const Path& other)
  72134. : numElements (other.numElements),
  72135. pathXMin (other.pathXMin),
  72136. pathXMax (other.pathXMax),
  72137. pathYMin (other.pathYMin),
  72138. pathYMax (other.pathYMax),
  72139. useNonZeroWinding (other.useNonZeroWinding)
  72140. {
  72141. if (numElements > 0)
  72142. {
  72143. data.setAllocatedSize ((int) numElements);
  72144. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  72145. }
  72146. }
  72147. Path& Path::operator= (const Path& other)
  72148. {
  72149. if (this != &other)
  72150. {
  72151. data.ensureAllocatedSize ((int) other.numElements);
  72152. numElements = other.numElements;
  72153. pathXMin = other.pathXMin;
  72154. pathXMax = other.pathXMax;
  72155. pathYMin = other.pathYMin;
  72156. pathYMax = other.pathYMax;
  72157. useNonZeroWinding = other.useNonZeroWinding;
  72158. if (numElements > 0)
  72159. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  72160. }
  72161. return *this;
  72162. }
  72163. bool Path::operator== (const Path& other) const throw()
  72164. {
  72165. return ! operator!= (other);
  72166. }
  72167. bool Path::operator!= (const Path& other) const throw()
  72168. {
  72169. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  72170. return true;
  72171. for (size_t i = 0; i < numElements; ++i)
  72172. if (data.elements[i] != other.data.elements[i])
  72173. return true;
  72174. return false;
  72175. }
  72176. void Path::clear() throw()
  72177. {
  72178. numElements = 0;
  72179. pathXMin = 0;
  72180. pathYMin = 0;
  72181. pathYMax = 0;
  72182. pathXMax = 0;
  72183. }
  72184. void Path::swapWithPath (Path& other) throw()
  72185. {
  72186. data.swapWith (other.data);
  72187. swapVariables <size_t> (numElements, other.numElements);
  72188. swapVariables <float> (pathXMin, other.pathXMin);
  72189. swapVariables <float> (pathXMax, other.pathXMax);
  72190. swapVariables <float> (pathYMin, other.pathYMin);
  72191. swapVariables <float> (pathYMax, other.pathYMax);
  72192. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  72193. }
  72194. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  72195. {
  72196. useNonZeroWinding = isNonZero;
  72197. }
  72198. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  72199. const bool preserveProportions) throw()
  72200. {
  72201. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  72202. }
  72203. bool Path::isEmpty() const throw()
  72204. {
  72205. size_t i = 0;
  72206. while (i < numElements)
  72207. {
  72208. const float type = data.elements [i++];
  72209. if (type == moveMarker)
  72210. {
  72211. i += 2;
  72212. }
  72213. else if (type == lineMarker
  72214. || type == quadMarker
  72215. || type == cubicMarker)
  72216. {
  72217. return false;
  72218. }
  72219. }
  72220. return true;
  72221. }
  72222. const Rectangle<float> Path::getBounds() const throw()
  72223. {
  72224. return Rectangle<float> (pathXMin, pathYMin,
  72225. pathXMax - pathXMin,
  72226. pathYMax - pathYMin);
  72227. }
  72228. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  72229. {
  72230. return getBounds().transformed (transform);
  72231. }
  72232. void Path::startNewSubPath (const float x, const float y)
  72233. {
  72234. CHECK_COORDS_ARE_VALID (x, y);
  72235. if (numElements == 0)
  72236. {
  72237. pathXMin = pathXMax = x;
  72238. pathYMin = pathYMax = y;
  72239. }
  72240. else
  72241. {
  72242. pathXMin = jmin (pathXMin, x);
  72243. pathXMax = jmax (pathXMax, x);
  72244. pathYMin = jmin (pathYMin, y);
  72245. pathYMax = jmax (pathYMax, y);
  72246. }
  72247. data.ensureAllocatedSize ((int) numElements + 3);
  72248. data.elements [numElements++] = moveMarker;
  72249. data.elements [numElements++] = x;
  72250. data.elements [numElements++] = y;
  72251. }
  72252. void Path::startNewSubPath (const Point<float>& start)
  72253. {
  72254. startNewSubPath (start.getX(), start.getY());
  72255. }
  72256. void Path::lineTo (const float x, const float y)
  72257. {
  72258. CHECK_COORDS_ARE_VALID (x, y);
  72259. if (numElements == 0)
  72260. startNewSubPath (0, 0);
  72261. data.ensureAllocatedSize ((int) numElements + 3);
  72262. data.elements [numElements++] = lineMarker;
  72263. data.elements [numElements++] = x;
  72264. data.elements [numElements++] = y;
  72265. pathXMin = jmin (pathXMin, x);
  72266. pathXMax = jmax (pathXMax, x);
  72267. pathYMin = jmin (pathYMin, y);
  72268. pathYMax = jmax (pathYMax, y);
  72269. }
  72270. void Path::lineTo (const Point<float>& end)
  72271. {
  72272. lineTo (end.getX(), end.getY());
  72273. }
  72274. void Path::quadraticTo (const float x1, const float y1,
  72275. const float x2, const float y2)
  72276. {
  72277. CHECK_COORDS_ARE_VALID (x1, y1);
  72278. CHECK_COORDS_ARE_VALID (x2, y2);
  72279. if (numElements == 0)
  72280. startNewSubPath (0, 0);
  72281. data.ensureAllocatedSize ((int) numElements + 5);
  72282. data.elements [numElements++] = quadMarker;
  72283. data.elements [numElements++] = x1;
  72284. data.elements [numElements++] = y1;
  72285. data.elements [numElements++] = x2;
  72286. data.elements [numElements++] = y2;
  72287. pathXMin = jmin (pathXMin, x1, x2);
  72288. pathXMax = jmax (pathXMax, x1, x2);
  72289. pathYMin = jmin (pathYMin, y1, y2);
  72290. pathYMax = jmax (pathYMax, y1, y2);
  72291. }
  72292. void Path::quadraticTo (const Point<float>& controlPoint,
  72293. const Point<float>& endPoint)
  72294. {
  72295. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  72296. endPoint.getX(), endPoint.getY());
  72297. }
  72298. void Path::cubicTo (const float x1, const float y1,
  72299. const float x2, const float y2,
  72300. const float x3, const float y3)
  72301. {
  72302. CHECK_COORDS_ARE_VALID (x1, y1);
  72303. CHECK_COORDS_ARE_VALID (x2, y2);
  72304. CHECK_COORDS_ARE_VALID (x3, y3);
  72305. if (numElements == 0)
  72306. startNewSubPath (0, 0);
  72307. data.ensureAllocatedSize ((int) numElements + 7);
  72308. data.elements [numElements++] = cubicMarker;
  72309. data.elements [numElements++] = x1;
  72310. data.elements [numElements++] = y1;
  72311. data.elements [numElements++] = x2;
  72312. data.elements [numElements++] = y2;
  72313. data.elements [numElements++] = x3;
  72314. data.elements [numElements++] = y3;
  72315. pathXMin = jmin (pathXMin, x1, x2, x3);
  72316. pathXMax = jmax (pathXMax, x1, x2, x3);
  72317. pathYMin = jmin (pathYMin, y1, y2, y3);
  72318. pathYMax = jmax (pathYMax, y1, y2, y3);
  72319. }
  72320. void Path::cubicTo (const Point<float>& controlPoint1,
  72321. const Point<float>& controlPoint2,
  72322. const Point<float>& endPoint)
  72323. {
  72324. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  72325. controlPoint2.getX(), controlPoint2.getY(),
  72326. endPoint.getX(), endPoint.getY());
  72327. }
  72328. void Path::closeSubPath()
  72329. {
  72330. if (numElements > 0
  72331. && data.elements [numElements - 1] != closeSubPathMarker)
  72332. {
  72333. data.ensureAllocatedSize ((int) numElements + 1);
  72334. data.elements [numElements++] = closeSubPathMarker;
  72335. }
  72336. }
  72337. const Point<float> Path::getCurrentPosition() const
  72338. {
  72339. size_t i = numElements - 1;
  72340. if (i > 0 && data.elements[i] == closeSubPathMarker)
  72341. {
  72342. while (i >= 0)
  72343. {
  72344. if (data.elements[i] == moveMarker)
  72345. {
  72346. i += 2;
  72347. break;
  72348. }
  72349. --i;
  72350. }
  72351. }
  72352. if (i > 0)
  72353. return Point<float> (data.elements [i - 1], data.elements [i]);
  72354. return Point<float>();
  72355. }
  72356. void Path::addRectangle (const float x, const float y,
  72357. const float w, const float h)
  72358. {
  72359. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  72360. if (w < 0)
  72361. swapVariables (x1, x2);
  72362. if (h < 0)
  72363. swapVariables (y1, y2);
  72364. data.ensureAllocatedSize ((int) numElements + 13);
  72365. if (numElements == 0)
  72366. {
  72367. pathXMin = x1;
  72368. pathXMax = x2;
  72369. pathYMin = y1;
  72370. pathYMax = y2;
  72371. }
  72372. else
  72373. {
  72374. pathXMin = jmin (pathXMin, x1);
  72375. pathXMax = jmax (pathXMax, x2);
  72376. pathYMin = jmin (pathYMin, y1);
  72377. pathYMax = jmax (pathYMax, y2);
  72378. }
  72379. data.elements [numElements++] = moveMarker;
  72380. data.elements [numElements++] = x1;
  72381. data.elements [numElements++] = y2;
  72382. data.elements [numElements++] = lineMarker;
  72383. data.elements [numElements++] = x1;
  72384. data.elements [numElements++] = y1;
  72385. data.elements [numElements++] = lineMarker;
  72386. data.elements [numElements++] = x2;
  72387. data.elements [numElements++] = y1;
  72388. data.elements [numElements++] = lineMarker;
  72389. data.elements [numElements++] = x2;
  72390. data.elements [numElements++] = y2;
  72391. data.elements [numElements++] = closeSubPathMarker;
  72392. }
  72393. void Path::addRectangle (const Rectangle<int>& rectangle)
  72394. {
  72395. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  72396. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  72397. }
  72398. void Path::addRoundedRectangle (const float x, const float y,
  72399. const float w, const float h,
  72400. float csx,
  72401. float csy)
  72402. {
  72403. csx = jmin (csx, w * 0.5f);
  72404. csy = jmin (csy, h * 0.5f);
  72405. const float cs45x = csx * 0.45f;
  72406. const float cs45y = csy * 0.45f;
  72407. const float x2 = x + w;
  72408. const float y2 = y + h;
  72409. startNewSubPath (x + csx, y);
  72410. lineTo (x2 - csx, y);
  72411. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  72412. lineTo (x2, y2 - csy);
  72413. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  72414. lineTo (x + csx, y2);
  72415. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  72416. lineTo (x, y + csy);
  72417. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  72418. closeSubPath();
  72419. }
  72420. void Path::addRoundedRectangle (const float x, const float y,
  72421. const float w, const float h,
  72422. float cs)
  72423. {
  72424. addRoundedRectangle (x, y, w, h, cs, cs);
  72425. }
  72426. void Path::addTriangle (const float x1, const float y1,
  72427. const float x2, const float y2,
  72428. const float x3, const float y3)
  72429. {
  72430. startNewSubPath (x1, y1);
  72431. lineTo (x2, y2);
  72432. lineTo (x3, y3);
  72433. closeSubPath();
  72434. }
  72435. void Path::addQuadrilateral (const float x1, const float y1,
  72436. const float x2, const float y2,
  72437. const float x3, const float y3,
  72438. const float x4, const float y4)
  72439. {
  72440. startNewSubPath (x1, y1);
  72441. lineTo (x2, y2);
  72442. lineTo (x3, y3);
  72443. lineTo (x4, y4);
  72444. closeSubPath();
  72445. }
  72446. void Path::addEllipse (const float x, const float y,
  72447. const float w, const float h)
  72448. {
  72449. const float hw = w * 0.5f;
  72450. const float hw55 = hw * 0.55f;
  72451. const float hh = h * 0.5f;
  72452. const float hh45 = hh * 0.55f;
  72453. const float cx = x + hw;
  72454. const float cy = y + hh;
  72455. startNewSubPath (cx, cy - hh);
  72456. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  72457. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  72458. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  72459. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  72460. closeSubPath();
  72461. }
  72462. void Path::addArc (const float x, const float y,
  72463. const float w, const float h,
  72464. const float fromRadians,
  72465. const float toRadians,
  72466. const bool startAsNewSubPath)
  72467. {
  72468. const float radiusX = w / 2.0f;
  72469. const float radiusY = h / 2.0f;
  72470. addCentredArc (x + radiusX,
  72471. y + radiusY,
  72472. radiusX, radiusY,
  72473. 0.0f,
  72474. fromRadians, toRadians,
  72475. startAsNewSubPath);
  72476. }
  72477. void Path::addCentredArc (const float centreX, const float centreY,
  72478. const float radiusX, const float radiusY,
  72479. const float rotationOfEllipse,
  72480. const float fromRadians,
  72481. const float toRadians,
  72482. const bool startAsNewSubPath)
  72483. {
  72484. if (radiusX > 0.0f && radiusY > 0.0f)
  72485. {
  72486. const Point<float> centre (centreX, centreY);
  72487. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  72488. float angle = fromRadians;
  72489. if (startAsNewSubPath)
  72490. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72491. if (fromRadians < toRadians)
  72492. {
  72493. if (startAsNewSubPath)
  72494. angle += PathHelpers::ellipseAngularIncrement;
  72495. while (angle < toRadians)
  72496. {
  72497. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72498. angle += PathHelpers::ellipseAngularIncrement;
  72499. }
  72500. }
  72501. else
  72502. {
  72503. if (startAsNewSubPath)
  72504. angle -= PathHelpers::ellipseAngularIncrement;
  72505. while (angle > toRadians)
  72506. {
  72507. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72508. angle -= PathHelpers::ellipseAngularIncrement;
  72509. }
  72510. }
  72511. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  72512. }
  72513. }
  72514. void Path::addPieSegment (const float x, const float y,
  72515. const float width, const float height,
  72516. const float fromRadians,
  72517. const float toRadians,
  72518. const float innerCircleProportionalSize)
  72519. {
  72520. float radiusX = width * 0.5f;
  72521. float radiusY = height * 0.5f;
  72522. const Point<float> centre (x + radiusX, y + radiusY);
  72523. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  72524. addArc (x, y, width, height, fromRadians, toRadians);
  72525. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  72526. {
  72527. closeSubPath();
  72528. if (innerCircleProportionalSize > 0)
  72529. {
  72530. radiusX *= innerCircleProportionalSize;
  72531. radiusY *= innerCircleProportionalSize;
  72532. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  72533. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  72534. }
  72535. }
  72536. else
  72537. {
  72538. if (innerCircleProportionalSize > 0)
  72539. {
  72540. radiusX *= innerCircleProportionalSize;
  72541. radiusY *= innerCircleProportionalSize;
  72542. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  72543. }
  72544. else
  72545. {
  72546. lineTo (centre);
  72547. }
  72548. }
  72549. closeSubPath();
  72550. }
  72551. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  72552. {
  72553. const Line<float> reversed (line.reversed());
  72554. lineThickness *= 0.5f;
  72555. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  72556. lineTo (line.getPointAlongLine (0, -lineThickness));
  72557. lineTo (reversed.getPointAlongLine (0, lineThickness));
  72558. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  72559. closeSubPath();
  72560. }
  72561. void Path::addArrow (const Line<float>& line, float lineThickness,
  72562. float arrowheadWidth, float arrowheadLength)
  72563. {
  72564. const Line<float> reversed (line.reversed());
  72565. lineThickness *= 0.5f;
  72566. arrowheadWidth *= 0.5f;
  72567. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  72568. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  72569. lineTo (line.getPointAlongLine (0, -lineThickness));
  72570. lineTo (reversed.getPointAlongLine (0, lineThickness));
  72571. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  72572. lineTo (line.getEnd());
  72573. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  72574. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  72575. closeSubPath();
  72576. }
  72577. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  72578. const float radius, const float startAngle)
  72579. {
  72580. jassert (numberOfSides > 1); // this would be silly.
  72581. if (numberOfSides > 1)
  72582. {
  72583. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  72584. for (int i = 0; i < numberOfSides; ++i)
  72585. {
  72586. const float angle = startAngle + i * angleBetweenPoints;
  72587. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  72588. if (i == 0)
  72589. startNewSubPath (p);
  72590. else
  72591. lineTo (p);
  72592. }
  72593. closeSubPath();
  72594. }
  72595. }
  72596. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  72597. const float innerRadius, const float outerRadius, const float startAngle)
  72598. {
  72599. jassert (numberOfPoints > 1); // this would be silly.
  72600. if (numberOfPoints > 1)
  72601. {
  72602. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  72603. for (int i = 0; i < numberOfPoints; ++i)
  72604. {
  72605. const float angle = startAngle + i * angleBetweenPoints;
  72606. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  72607. if (i == 0)
  72608. startNewSubPath (p);
  72609. else
  72610. lineTo (p);
  72611. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  72612. }
  72613. closeSubPath();
  72614. }
  72615. }
  72616. void Path::addBubble (float x, float y,
  72617. float w, float h,
  72618. float cs,
  72619. float tipX,
  72620. float tipY,
  72621. int whichSide,
  72622. float arrowPos,
  72623. float arrowWidth)
  72624. {
  72625. if (w > 1.0f && h > 1.0f)
  72626. {
  72627. cs = jmin (cs, w * 0.5f, h * 0.5f);
  72628. const float cs2 = 2.0f * cs;
  72629. startNewSubPath (x + cs, y);
  72630. if (whichSide == 0)
  72631. {
  72632. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  72633. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  72634. lineTo (arrowX1, y);
  72635. lineTo (tipX, tipY);
  72636. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  72637. }
  72638. lineTo (x + w - cs, y);
  72639. if (cs > 0.0f)
  72640. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  72641. if (whichSide == 3)
  72642. {
  72643. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  72644. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  72645. lineTo (x + w, arrowY1);
  72646. lineTo (tipX, tipY);
  72647. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  72648. }
  72649. lineTo (x + w, y + h - cs);
  72650. if (cs > 0.0f)
  72651. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  72652. if (whichSide == 2)
  72653. {
  72654. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  72655. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  72656. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  72657. lineTo (tipX, tipY);
  72658. lineTo (arrowX1, y + h);
  72659. }
  72660. lineTo (x + cs, y + h);
  72661. if (cs > 0.0f)
  72662. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  72663. if (whichSide == 1)
  72664. {
  72665. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  72666. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  72667. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  72668. lineTo (tipX, tipY);
  72669. lineTo (x, arrowY1);
  72670. }
  72671. lineTo (x, y + cs);
  72672. if (cs > 0.0f)
  72673. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  72674. closeSubPath();
  72675. }
  72676. }
  72677. void Path::addPath (const Path& other)
  72678. {
  72679. size_t i = 0;
  72680. while (i < other.numElements)
  72681. {
  72682. const float type = other.data.elements [i++];
  72683. if (type == moveMarker)
  72684. {
  72685. startNewSubPath (other.data.elements [i],
  72686. other.data.elements [i + 1]);
  72687. i += 2;
  72688. }
  72689. else if (type == lineMarker)
  72690. {
  72691. lineTo (other.data.elements [i],
  72692. other.data.elements [i + 1]);
  72693. i += 2;
  72694. }
  72695. else if (type == quadMarker)
  72696. {
  72697. quadraticTo (other.data.elements [i],
  72698. other.data.elements [i + 1],
  72699. other.data.elements [i + 2],
  72700. other.data.elements [i + 3]);
  72701. i += 4;
  72702. }
  72703. else if (type == cubicMarker)
  72704. {
  72705. cubicTo (other.data.elements [i],
  72706. other.data.elements [i + 1],
  72707. other.data.elements [i + 2],
  72708. other.data.elements [i + 3],
  72709. other.data.elements [i + 4],
  72710. other.data.elements [i + 5]);
  72711. i += 6;
  72712. }
  72713. else if (type == closeSubPathMarker)
  72714. {
  72715. closeSubPath();
  72716. }
  72717. else
  72718. {
  72719. // something's gone wrong with the element list!
  72720. jassertfalse;
  72721. }
  72722. }
  72723. }
  72724. void Path::addPath (const Path& other,
  72725. const AffineTransform& transformToApply)
  72726. {
  72727. size_t i = 0;
  72728. while (i < other.numElements)
  72729. {
  72730. const float type = other.data.elements [i++];
  72731. if (type == closeSubPathMarker)
  72732. {
  72733. closeSubPath();
  72734. }
  72735. else
  72736. {
  72737. float x = other.data.elements [i++];
  72738. float y = other.data.elements [i++];
  72739. transformToApply.transformPoint (x, y);
  72740. if (type == moveMarker)
  72741. {
  72742. startNewSubPath (x, y);
  72743. }
  72744. else if (type == lineMarker)
  72745. {
  72746. lineTo (x, y);
  72747. }
  72748. else if (type == quadMarker)
  72749. {
  72750. float x2 = other.data.elements [i++];
  72751. float y2 = other.data.elements [i++];
  72752. transformToApply.transformPoint (x2, y2);
  72753. quadraticTo (x, y, x2, y2);
  72754. }
  72755. else if (type == cubicMarker)
  72756. {
  72757. float x2 = other.data.elements [i++];
  72758. float y2 = other.data.elements [i++];
  72759. float x3 = other.data.elements [i++];
  72760. float y3 = other.data.elements [i++];
  72761. transformToApply.transformPoint (x2, y2);
  72762. transformToApply.transformPoint (x3, y3);
  72763. cubicTo (x, y, x2, y2, x3, y3);
  72764. }
  72765. else
  72766. {
  72767. // something's gone wrong with the element list!
  72768. jassertfalse;
  72769. }
  72770. }
  72771. }
  72772. }
  72773. void Path::applyTransform (const AffineTransform& transform) throw()
  72774. {
  72775. size_t i = 0;
  72776. pathYMin = pathXMin = 0;
  72777. pathYMax = pathXMax = 0;
  72778. bool setMaxMin = false;
  72779. while (i < numElements)
  72780. {
  72781. const float type = data.elements [i++];
  72782. if (type == moveMarker)
  72783. {
  72784. transform.transformPoint (data.elements [i],
  72785. data.elements [i + 1]);
  72786. if (setMaxMin)
  72787. {
  72788. pathXMin = jmin (pathXMin, data.elements [i]);
  72789. pathXMax = jmax (pathXMax, data.elements [i]);
  72790. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  72791. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  72792. }
  72793. else
  72794. {
  72795. pathXMin = pathXMax = data.elements [i];
  72796. pathYMin = pathYMax = data.elements [i + 1];
  72797. setMaxMin = true;
  72798. }
  72799. i += 2;
  72800. }
  72801. else if (type == lineMarker)
  72802. {
  72803. transform.transformPoint (data.elements [i],
  72804. data.elements [i + 1]);
  72805. pathXMin = jmin (pathXMin, data.elements [i]);
  72806. pathXMax = jmax (pathXMax, data.elements [i]);
  72807. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  72808. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  72809. i += 2;
  72810. }
  72811. else if (type == quadMarker)
  72812. {
  72813. transform.transformPoint (data.elements [i],
  72814. data.elements [i + 1]);
  72815. transform.transformPoint (data.elements [i + 2],
  72816. data.elements [i + 3]);
  72817. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  72818. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  72819. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  72820. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  72821. i += 4;
  72822. }
  72823. else if (type == cubicMarker)
  72824. {
  72825. transform.transformPoint (data.elements [i],
  72826. data.elements [i + 1]);
  72827. transform.transformPoint (data.elements [i + 2],
  72828. data.elements [i + 3]);
  72829. transform.transformPoint (data.elements [i + 4],
  72830. data.elements [i + 5]);
  72831. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  72832. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  72833. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  72834. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  72835. i += 6;
  72836. }
  72837. }
  72838. }
  72839. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  72840. const float w, const float h,
  72841. const bool preserveProportions,
  72842. const Justification& justification) const
  72843. {
  72844. Rectangle<float> bounds (getBounds());
  72845. if (preserveProportions)
  72846. {
  72847. if (w <= 0 || h <= 0 || bounds.isEmpty())
  72848. return AffineTransform::identity;
  72849. float newW, newH;
  72850. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  72851. if (srcRatio > h / w)
  72852. {
  72853. newW = h / srcRatio;
  72854. newH = h;
  72855. }
  72856. else
  72857. {
  72858. newW = w;
  72859. newH = w * srcRatio;
  72860. }
  72861. float newXCentre = x;
  72862. float newYCentre = y;
  72863. if (justification.testFlags (Justification::left))
  72864. newXCentre += newW * 0.5f;
  72865. else if (justification.testFlags (Justification::right))
  72866. newXCentre += w - newW * 0.5f;
  72867. else
  72868. newXCentre += w * 0.5f;
  72869. if (justification.testFlags (Justification::top))
  72870. newYCentre += newH * 0.5f;
  72871. else if (justification.testFlags (Justification::bottom))
  72872. newYCentre += h - newH * 0.5f;
  72873. else
  72874. newYCentre += h * 0.5f;
  72875. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  72876. bounds.getHeight() * -0.5f - bounds.getY())
  72877. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  72878. .translated (newXCentre, newYCentre);
  72879. }
  72880. else
  72881. {
  72882. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  72883. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  72884. .translated (x, y);
  72885. }
  72886. }
  72887. bool Path::contains (const float x, const float y, const float tolerence) const
  72888. {
  72889. if (x <= pathXMin || x >= pathXMax
  72890. || y <= pathYMin || y >= pathYMax)
  72891. return false;
  72892. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  72893. int positiveCrossings = 0;
  72894. int negativeCrossings = 0;
  72895. while (i.next())
  72896. {
  72897. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  72898. {
  72899. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  72900. if (intersectX <= x)
  72901. {
  72902. if (i.y1 < i.y2)
  72903. ++positiveCrossings;
  72904. else
  72905. ++negativeCrossings;
  72906. }
  72907. }
  72908. }
  72909. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  72910. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  72911. }
  72912. bool Path::contains (const Point<float>& point, const float tolerence) const
  72913. {
  72914. return contains (point.getX(), point.getY(), tolerence);
  72915. }
  72916. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  72917. {
  72918. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  72919. Point<float> intersection;
  72920. while (i.next())
  72921. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  72922. return true;
  72923. return false;
  72924. }
  72925. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  72926. {
  72927. Line<float> result (line);
  72928. const bool startInside = contains (line.getStart());
  72929. const bool endInside = contains (line.getEnd());
  72930. if (startInside == endInside)
  72931. {
  72932. if (keepSectionOutsidePath == startInside)
  72933. result = Line<float>();
  72934. }
  72935. else
  72936. {
  72937. PathFlatteningIterator i (*this, AffineTransform::identity);
  72938. Point<float> intersection;
  72939. while (i.next())
  72940. {
  72941. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  72942. {
  72943. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  72944. result.setStart (intersection);
  72945. else
  72946. result.setEnd (intersection);
  72947. }
  72948. }
  72949. }
  72950. return result;
  72951. }
  72952. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  72953. {
  72954. if (cornerRadius <= 0.01f)
  72955. return *this;
  72956. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  72957. size_t n = 0;
  72958. bool lastWasLine = false, firstWasLine = false;
  72959. Path p;
  72960. while (n < numElements)
  72961. {
  72962. const float type = data.elements [n++];
  72963. if (type == moveMarker)
  72964. {
  72965. indexOfPathStart = p.numElements;
  72966. indexOfPathStartThis = n - 1;
  72967. const float x = data.elements [n++];
  72968. const float y = data.elements [n++];
  72969. p.startNewSubPath (x, y);
  72970. lastWasLine = false;
  72971. firstWasLine = (data.elements [n] == lineMarker);
  72972. }
  72973. else if (type == lineMarker || type == closeSubPathMarker)
  72974. {
  72975. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  72976. if (type == lineMarker)
  72977. {
  72978. endX = data.elements [n++];
  72979. endY = data.elements [n++];
  72980. if (n > 8)
  72981. {
  72982. startX = data.elements [n - 8];
  72983. startY = data.elements [n - 7];
  72984. joinX = data.elements [n - 5];
  72985. joinY = data.elements [n - 4];
  72986. }
  72987. }
  72988. else
  72989. {
  72990. endX = data.elements [indexOfPathStartThis + 1];
  72991. endY = data.elements [indexOfPathStartThis + 2];
  72992. if (n > 6)
  72993. {
  72994. startX = data.elements [n - 6];
  72995. startY = data.elements [n - 5];
  72996. joinX = data.elements [n - 3];
  72997. joinY = data.elements [n - 2];
  72998. }
  72999. }
  73000. if (lastWasLine)
  73001. {
  73002. const double len1 = juce_hypot (startX - joinX,
  73003. startY - joinY);
  73004. if (len1 > 0)
  73005. {
  73006. const double propNeeded = jmin (0.5, cornerRadius / len1);
  73007. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  73008. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  73009. }
  73010. const double len2 = juce_hypot (endX - joinX,
  73011. endY - joinY);
  73012. if (len2 > 0)
  73013. {
  73014. const double propNeeded = jmin (0.5, cornerRadius / len2);
  73015. p.quadraticTo (joinX, joinY,
  73016. (float) (joinX + (endX - joinX) * propNeeded),
  73017. (float) (joinY + (endY - joinY) * propNeeded));
  73018. }
  73019. p.lineTo (endX, endY);
  73020. }
  73021. else if (type == lineMarker)
  73022. {
  73023. p.lineTo (endX, endY);
  73024. lastWasLine = true;
  73025. }
  73026. if (type == closeSubPathMarker)
  73027. {
  73028. if (firstWasLine)
  73029. {
  73030. startX = data.elements [n - 3];
  73031. startY = data.elements [n - 2];
  73032. joinX = endX;
  73033. joinY = endY;
  73034. endX = data.elements [indexOfPathStartThis + 4];
  73035. endY = data.elements [indexOfPathStartThis + 5];
  73036. const double len1 = juce_hypot (startX - joinX,
  73037. startY - joinY);
  73038. if (len1 > 0)
  73039. {
  73040. const double propNeeded = jmin (0.5, cornerRadius / len1);
  73041. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  73042. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  73043. }
  73044. const double len2 = juce_hypot (endX - joinX,
  73045. endY - joinY);
  73046. if (len2 > 0)
  73047. {
  73048. const double propNeeded = jmin (0.5, cornerRadius / len2);
  73049. endX = (float) (joinX + (endX - joinX) * propNeeded);
  73050. endY = (float) (joinY + (endY - joinY) * propNeeded);
  73051. p.quadraticTo (joinX, joinY, endX, endY);
  73052. p.data.elements [indexOfPathStart + 1] = endX;
  73053. p.data.elements [indexOfPathStart + 2] = endY;
  73054. }
  73055. }
  73056. p.closeSubPath();
  73057. }
  73058. }
  73059. else if (type == quadMarker)
  73060. {
  73061. lastWasLine = false;
  73062. const float x1 = data.elements [n++];
  73063. const float y1 = data.elements [n++];
  73064. const float x2 = data.elements [n++];
  73065. const float y2 = data.elements [n++];
  73066. p.quadraticTo (x1, y1, x2, y2);
  73067. }
  73068. else if (type == cubicMarker)
  73069. {
  73070. lastWasLine = false;
  73071. const float x1 = data.elements [n++];
  73072. const float y1 = data.elements [n++];
  73073. const float x2 = data.elements [n++];
  73074. const float y2 = data.elements [n++];
  73075. const float x3 = data.elements [n++];
  73076. const float y3 = data.elements [n++];
  73077. p.cubicTo (x1, y1, x2, y2, x3, y3);
  73078. }
  73079. }
  73080. return p;
  73081. }
  73082. void Path::loadPathFromStream (InputStream& source)
  73083. {
  73084. while (! source.isExhausted())
  73085. {
  73086. switch (source.readByte())
  73087. {
  73088. case 'm':
  73089. {
  73090. const float x = source.readFloat();
  73091. const float y = source.readFloat();
  73092. startNewSubPath (x, y);
  73093. break;
  73094. }
  73095. case 'l':
  73096. {
  73097. const float x = source.readFloat();
  73098. const float y = source.readFloat();
  73099. lineTo (x, y);
  73100. break;
  73101. }
  73102. case 'q':
  73103. {
  73104. const float x1 = source.readFloat();
  73105. const float y1 = source.readFloat();
  73106. const float x2 = source.readFloat();
  73107. const float y2 = source.readFloat();
  73108. quadraticTo (x1, y1, x2, y2);
  73109. break;
  73110. }
  73111. case 'b':
  73112. {
  73113. const float x1 = source.readFloat();
  73114. const float y1 = source.readFloat();
  73115. const float x2 = source.readFloat();
  73116. const float y2 = source.readFloat();
  73117. const float x3 = source.readFloat();
  73118. const float y3 = source.readFloat();
  73119. cubicTo (x1, y1, x2, y2, x3, y3);
  73120. break;
  73121. }
  73122. case 'c':
  73123. closeSubPath();
  73124. break;
  73125. case 'n':
  73126. useNonZeroWinding = true;
  73127. break;
  73128. case 'z':
  73129. useNonZeroWinding = false;
  73130. break;
  73131. case 'e':
  73132. return; // end of path marker
  73133. default:
  73134. jassertfalse; // illegal char in the stream
  73135. break;
  73136. }
  73137. }
  73138. }
  73139. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  73140. {
  73141. MemoryInputStream in (pathData, numberOfBytes, false);
  73142. loadPathFromStream (in);
  73143. }
  73144. void Path::writePathToStream (OutputStream& dest) const
  73145. {
  73146. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  73147. size_t i = 0;
  73148. while (i < numElements)
  73149. {
  73150. const float type = data.elements [i++];
  73151. if (type == moveMarker)
  73152. {
  73153. dest.writeByte ('m');
  73154. dest.writeFloat (data.elements [i++]);
  73155. dest.writeFloat (data.elements [i++]);
  73156. }
  73157. else if (type == lineMarker)
  73158. {
  73159. dest.writeByte ('l');
  73160. dest.writeFloat (data.elements [i++]);
  73161. dest.writeFloat (data.elements [i++]);
  73162. }
  73163. else if (type == quadMarker)
  73164. {
  73165. dest.writeByte ('q');
  73166. dest.writeFloat (data.elements [i++]);
  73167. dest.writeFloat (data.elements [i++]);
  73168. dest.writeFloat (data.elements [i++]);
  73169. dest.writeFloat (data.elements [i++]);
  73170. }
  73171. else if (type == cubicMarker)
  73172. {
  73173. dest.writeByte ('b');
  73174. dest.writeFloat (data.elements [i++]);
  73175. dest.writeFloat (data.elements [i++]);
  73176. dest.writeFloat (data.elements [i++]);
  73177. dest.writeFloat (data.elements [i++]);
  73178. dest.writeFloat (data.elements [i++]);
  73179. dest.writeFloat (data.elements [i++]);
  73180. }
  73181. else if (type == closeSubPathMarker)
  73182. {
  73183. dest.writeByte ('c');
  73184. }
  73185. }
  73186. dest.writeByte ('e'); // marks the end-of-path
  73187. }
  73188. const String Path::toString() const
  73189. {
  73190. MemoryOutputStream s (2048, 2048);
  73191. if (! useNonZeroWinding)
  73192. s << 'a';
  73193. size_t i = 0;
  73194. float lastMarker = 0.0f;
  73195. while (i < numElements)
  73196. {
  73197. const float marker = data.elements [i++];
  73198. char markerChar = 0;
  73199. int numCoords = 0;
  73200. if (marker == moveMarker)
  73201. {
  73202. markerChar = 'm';
  73203. numCoords = 2;
  73204. }
  73205. else if (marker == lineMarker)
  73206. {
  73207. markerChar = 'l';
  73208. numCoords = 2;
  73209. }
  73210. else if (marker == quadMarker)
  73211. {
  73212. markerChar = 'q';
  73213. numCoords = 4;
  73214. }
  73215. else if (marker == cubicMarker)
  73216. {
  73217. markerChar = 'c';
  73218. numCoords = 6;
  73219. }
  73220. else
  73221. {
  73222. jassert (marker == closeSubPathMarker);
  73223. markerChar = 'z';
  73224. }
  73225. if (marker != lastMarker)
  73226. {
  73227. if (s.getDataSize() != 0)
  73228. s << ' ';
  73229. s << markerChar;
  73230. lastMarker = marker;
  73231. }
  73232. while (--numCoords >= 0 && i < numElements)
  73233. {
  73234. String coord (data.elements [i++], 3);
  73235. while (coord.endsWithChar ('0') && coord != "0")
  73236. coord = coord.dropLastCharacters (1);
  73237. if (coord.endsWithChar ('.'))
  73238. coord = coord.dropLastCharacters (1);
  73239. if (s.getDataSize() != 0)
  73240. s << ' ';
  73241. s << coord;
  73242. }
  73243. }
  73244. return s.toUTF8();
  73245. }
  73246. void Path::restoreFromString (const String& stringVersion)
  73247. {
  73248. clear();
  73249. setUsingNonZeroWinding (true);
  73250. const juce_wchar* t = stringVersion;
  73251. juce_wchar marker = 'm';
  73252. int numValues = 2;
  73253. float values [6];
  73254. for (;;)
  73255. {
  73256. const String token (PathHelpers::nextToken (t));
  73257. const juce_wchar firstChar = token[0];
  73258. int startNum = 0;
  73259. if (firstChar == 0)
  73260. break;
  73261. if (firstChar == 'm' || firstChar == 'l')
  73262. {
  73263. marker = firstChar;
  73264. numValues = 2;
  73265. }
  73266. else if (firstChar == 'q')
  73267. {
  73268. marker = firstChar;
  73269. numValues = 4;
  73270. }
  73271. else if (firstChar == 'c')
  73272. {
  73273. marker = firstChar;
  73274. numValues = 6;
  73275. }
  73276. else if (firstChar == 'z')
  73277. {
  73278. marker = firstChar;
  73279. numValues = 0;
  73280. }
  73281. else if (firstChar == 'a')
  73282. {
  73283. setUsingNonZeroWinding (false);
  73284. continue;
  73285. }
  73286. else
  73287. {
  73288. ++startNum;
  73289. values [0] = token.getFloatValue();
  73290. }
  73291. for (int i = startNum; i < numValues; ++i)
  73292. values [i] = PathHelpers::nextToken (t).getFloatValue();
  73293. switch (marker)
  73294. {
  73295. case 'm':
  73296. startNewSubPath (values[0], values[1]);
  73297. break;
  73298. case 'l':
  73299. lineTo (values[0], values[1]);
  73300. break;
  73301. case 'q':
  73302. quadraticTo (values[0], values[1],
  73303. values[2], values[3]);
  73304. break;
  73305. case 'c':
  73306. cubicTo (values[0], values[1],
  73307. values[2], values[3],
  73308. values[4], values[5]);
  73309. break;
  73310. case 'z':
  73311. closeSubPath();
  73312. break;
  73313. default:
  73314. jassertfalse; // illegal string format?
  73315. break;
  73316. }
  73317. }
  73318. }
  73319. Path::Iterator::Iterator (const Path& path_)
  73320. : path (path_),
  73321. index (0)
  73322. {
  73323. }
  73324. Path::Iterator::~Iterator()
  73325. {
  73326. }
  73327. bool Path::Iterator::next()
  73328. {
  73329. const float* const elements = path.data.elements;
  73330. if (index < path.numElements)
  73331. {
  73332. const float type = elements [index++];
  73333. if (type == moveMarker)
  73334. {
  73335. elementType = startNewSubPath;
  73336. x1 = elements [index++];
  73337. y1 = elements [index++];
  73338. }
  73339. else if (type == lineMarker)
  73340. {
  73341. elementType = lineTo;
  73342. x1 = elements [index++];
  73343. y1 = elements [index++];
  73344. }
  73345. else if (type == quadMarker)
  73346. {
  73347. elementType = quadraticTo;
  73348. x1 = elements [index++];
  73349. y1 = elements [index++];
  73350. x2 = elements [index++];
  73351. y2 = elements [index++];
  73352. }
  73353. else if (type == cubicMarker)
  73354. {
  73355. elementType = cubicTo;
  73356. x1 = elements [index++];
  73357. y1 = elements [index++];
  73358. x2 = elements [index++];
  73359. y2 = elements [index++];
  73360. x3 = elements [index++];
  73361. y3 = elements [index++];
  73362. }
  73363. else if (type == closeSubPathMarker)
  73364. {
  73365. elementType = closePath;
  73366. }
  73367. return true;
  73368. }
  73369. return false;
  73370. }
  73371. END_JUCE_NAMESPACE
  73372. /*** End of inlined file: juce_Path.cpp ***/
  73373. /*** Start of inlined file: juce_PathIterator.cpp ***/
  73374. BEGIN_JUCE_NAMESPACE
  73375. #if JUCE_MSVC && JUCE_DEBUG
  73376. #pragma optimize ("t", on)
  73377. #endif
  73378. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  73379. const AffineTransform& transform_,
  73380. float tolerence_)
  73381. : x2 (0),
  73382. y2 (0),
  73383. closesSubPath (false),
  73384. subPathIndex (-1),
  73385. path (path_),
  73386. transform (transform_),
  73387. points (path_.data.elements),
  73388. tolerence (tolerence_ * tolerence_),
  73389. subPathCloseX (0),
  73390. subPathCloseY (0),
  73391. isIdentityTransform (transform_.isIdentity()),
  73392. stackBase (32),
  73393. index (0),
  73394. stackSize (32)
  73395. {
  73396. stackPos = stackBase;
  73397. }
  73398. PathFlatteningIterator::~PathFlatteningIterator()
  73399. {
  73400. }
  73401. bool PathFlatteningIterator::next()
  73402. {
  73403. x1 = x2;
  73404. y1 = y2;
  73405. float x3 = 0;
  73406. float y3 = 0;
  73407. float x4 = 0;
  73408. float y4 = 0;
  73409. float type;
  73410. for (;;)
  73411. {
  73412. if (stackPos == stackBase)
  73413. {
  73414. if (index >= path.numElements)
  73415. {
  73416. return false;
  73417. }
  73418. else
  73419. {
  73420. type = points [index++];
  73421. if (type != Path::closeSubPathMarker)
  73422. {
  73423. x2 = points [index++];
  73424. y2 = points [index++];
  73425. if (! isIdentityTransform)
  73426. transform.transformPoint (x2, y2);
  73427. if (type == Path::quadMarker)
  73428. {
  73429. x3 = points [index++];
  73430. y3 = points [index++];
  73431. if (! isIdentityTransform)
  73432. transform.transformPoint (x3, y3);
  73433. }
  73434. else if (type == Path::cubicMarker)
  73435. {
  73436. x3 = points [index++];
  73437. y3 = points [index++];
  73438. x4 = points [index++];
  73439. y4 = points [index++];
  73440. if (! isIdentityTransform)
  73441. {
  73442. transform.transformPoint (x3, y3);
  73443. transform.transformPoint (x4, y4);
  73444. }
  73445. }
  73446. }
  73447. }
  73448. }
  73449. else
  73450. {
  73451. type = *--stackPos;
  73452. if (type != Path::closeSubPathMarker)
  73453. {
  73454. x2 = *--stackPos;
  73455. y2 = *--stackPos;
  73456. if (type == Path::quadMarker)
  73457. {
  73458. x3 = *--stackPos;
  73459. y3 = *--stackPos;
  73460. }
  73461. else if (type == Path::cubicMarker)
  73462. {
  73463. x3 = *--stackPos;
  73464. y3 = *--stackPos;
  73465. x4 = *--stackPos;
  73466. y4 = *--stackPos;
  73467. }
  73468. }
  73469. }
  73470. if (type == Path::lineMarker)
  73471. {
  73472. ++subPathIndex;
  73473. closesSubPath = (stackPos == stackBase)
  73474. && (index < path.numElements)
  73475. && (points [index] == Path::closeSubPathMarker)
  73476. && x2 == subPathCloseX
  73477. && y2 == subPathCloseY;
  73478. return true;
  73479. }
  73480. else if (type == Path::quadMarker)
  73481. {
  73482. const size_t offset = (size_t) (stackPos - stackBase);
  73483. if (offset >= stackSize - 10)
  73484. {
  73485. stackSize <<= 1;
  73486. stackBase.realloc (stackSize);
  73487. stackPos = stackBase + offset;
  73488. }
  73489. const float dx1 = x1 - x2;
  73490. const float dy1 = y1 - y2;
  73491. const float dx2 = x2 - x3;
  73492. const float dy2 = y2 - y3;
  73493. const float m1x = (x1 + x2) * 0.5f;
  73494. const float m1y = (y1 + y2) * 0.5f;
  73495. const float m2x = (x2 + x3) * 0.5f;
  73496. const float m2y = (y2 + y3) * 0.5f;
  73497. const float m3x = (m1x + m2x) * 0.5f;
  73498. const float m3y = (m1y + m2y) * 0.5f;
  73499. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  73500. {
  73501. *stackPos++ = y3;
  73502. *stackPos++ = x3;
  73503. *stackPos++ = m2y;
  73504. *stackPos++ = m2x;
  73505. *stackPos++ = Path::quadMarker;
  73506. *stackPos++ = m3y;
  73507. *stackPos++ = m3x;
  73508. *stackPos++ = m1y;
  73509. *stackPos++ = m1x;
  73510. *stackPos++ = Path::quadMarker;
  73511. }
  73512. else
  73513. {
  73514. *stackPos++ = y3;
  73515. *stackPos++ = x3;
  73516. *stackPos++ = Path::lineMarker;
  73517. *stackPos++ = m3y;
  73518. *stackPos++ = m3x;
  73519. *stackPos++ = Path::lineMarker;
  73520. }
  73521. jassert (stackPos < stackBase + stackSize);
  73522. }
  73523. else if (type == Path::cubicMarker)
  73524. {
  73525. const size_t offset = (size_t) (stackPos - stackBase);
  73526. if (offset >= stackSize - 16)
  73527. {
  73528. stackSize <<= 1;
  73529. stackBase.realloc (stackSize);
  73530. stackPos = stackBase + offset;
  73531. }
  73532. const float dx1 = x1 - x2;
  73533. const float dy1 = y1 - y2;
  73534. const float dx2 = x2 - x3;
  73535. const float dy2 = y2 - y3;
  73536. const float dx3 = x3 - x4;
  73537. const float dy3 = y3 - y4;
  73538. const float m1x = (x1 + x2) * 0.5f;
  73539. const float m1y = (y1 + y2) * 0.5f;
  73540. const float m2x = (x3 + x2) * 0.5f;
  73541. const float m2y = (y3 + y2) * 0.5f;
  73542. const float m3x = (x3 + x4) * 0.5f;
  73543. const float m3y = (y3 + y4) * 0.5f;
  73544. const float m4x = (m1x + m2x) * 0.5f;
  73545. const float m4y = (m1y + m2y) * 0.5f;
  73546. const float m5x = (m3x + m2x) * 0.5f;
  73547. const float m5y = (m3y + m2y) * 0.5f;
  73548. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  73549. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  73550. {
  73551. *stackPos++ = y4;
  73552. *stackPos++ = x4;
  73553. *stackPos++ = m3y;
  73554. *stackPos++ = m3x;
  73555. *stackPos++ = m5y;
  73556. *stackPos++ = m5x;
  73557. *stackPos++ = Path::cubicMarker;
  73558. *stackPos++ = (m4y + m5y) * 0.5f;
  73559. *stackPos++ = (m4x + m5x) * 0.5f;
  73560. *stackPos++ = m4y;
  73561. *stackPos++ = m4x;
  73562. *stackPos++ = m1y;
  73563. *stackPos++ = m1x;
  73564. *stackPos++ = Path::cubicMarker;
  73565. }
  73566. else
  73567. {
  73568. *stackPos++ = y4;
  73569. *stackPos++ = x4;
  73570. *stackPos++ = Path::lineMarker;
  73571. *stackPos++ = m5y;
  73572. *stackPos++ = m5x;
  73573. *stackPos++ = Path::lineMarker;
  73574. *stackPos++ = m4y;
  73575. *stackPos++ = m4x;
  73576. *stackPos++ = Path::lineMarker;
  73577. }
  73578. }
  73579. else if (type == Path::closeSubPathMarker)
  73580. {
  73581. if (x2 != subPathCloseX || y2 != subPathCloseY)
  73582. {
  73583. x1 = x2;
  73584. y1 = y2;
  73585. x2 = subPathCloseX;
  73586. y2 = subPathCloseY;
  73587. closesSubPath = true;
  73588. return true;
  73589. }
  73590. }
  73591. else
  73592. {
  73593. jassert (type == Path::moveMarker);
  73594. subPathIndex = -1;
  73595. subPathCloseX = x1 = x2;
  73596. subPathCloseY = y1 = y2;
  73597. }
  73598. }
  73599. }
  73600. #if JUCE_MSVC && JUCE_DEBUG
  73601. #pragma optimize ("", on) // resets optimisations to the project defaults
  73602. #endif
  73603. END_JUCE_NAMESPACE
  73604. /*** End of inlined file: juce_PathIterator.cpp ***/
  73605. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  73606. BEGIN_JUCE_NAMESPACE
  73607. PathStrokeType::PathStrokeType (const float strokeThickness,
  73608. const JointStyle jointStyle_,
  73609. const EndCapStyle endStyle_) throw()
  73610. : thickness (strokeThickness),
  73611. jointStyle (jointStyle_),
  73612. endStyle (endStyle_)
  73613. {
  73614. }
  73615. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  73616. : thickness (other.thickness),
  73617. jointStyle (other.jointStyle),
  73618. endStyle (other.endStyle)
  73619. {
  73620. }
  73621. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  73622. {
  73623. thickness = other.thickness;
  73624. jointStyle = other.jointStyle;
  73625. endStyle = other.endStyle;
  73626. return *this;
  73627. }
  73628. PathStrokeType::~PathStrokeType() throw()
  73629. {
  73630. }
  73631. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  73632. {
  73633. return thickness == other.thickness
  73634. && jointStyle == other.jointStyle
  73635. && endStyle == other.endStyle;
  73636. }
  73637. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  73638. {
  73639. return ! operator== (other);
  73640. }
  73641. namespace PathStrokeHelpers
  73642. {
  73643. static bool lineIntersection (const float x1, const float y1,
  73644. const float x2, const float y2,
  73645. const float x3, const float y3,
  73646. const float x4, const float y4,
  73647. float& intersectionX,
  73648. float& intersectionY,
  73649. float& distanceBeyondLine1EndSquared) throw()
  73650. {
  73651. if (x2 != x3 || y2 != y3)
  73652. {
  73653. const float dx1 = x2 - x1;
  73654. const float dy1 = y2 - y1;
  73655. const float dx2 = x4 - x3;
  73656. const float dy2 = y4 - y3;
  73657. const float divisor = dx1 * dy2 - dx2 * dy1;
  73658. if (divisor == 0)
  73659. {
  73660. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  73661. {
  73662. if (dy1 == 0 && dy2 != 0)
  73663. {
  73664. const float along = (y1 - y3) / dy2;
  73665. intersectionX = x3 + along * dx2;
  73666. intersectionY = y1;
  73667. distanceBeyondLine1EndSquared = intersectionX - x2;
  73668. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73669. if ((x2 > x1) == (intersectionX < x2))
  73670. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73671. return along >= 0 && along <= 1.0f;
  73672. }
  73673. else if (dy2 == 0 && dy1 != 0)
  73674. {
  73675. const float along = (y3 - y1) / dy1;
  73676. intersectionX = x1 + along * dx1;
  73677. intersectionY = y3;
  73678. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  73679. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73680. if (along < 1.0f)
  73681. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73682. return along >= 0 && along <= 1.0f;
  73683. }
  73684. else if (dx1 == 0 && dx2 != 0)
  73685. {
  73686. const float along = (x1 - x3) / dx2;
  73687. intersectionX = x1;
  73688. intersectionY = y3 + along * dy2;
  73689. distanceBeyondLine1EndSquared = intersectionY - y2;
  73690. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73691. if ((y2 > y1) == (intersectionY < y2))
  73692. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73693. return along >= 0 && along <= 1.0f;
  73694. }
  73695. else if (dx2 == 0 && dx1 != 0)
  73696. {
  73697. const float along = (x3 - x1) / dx1;
  73698. intersectionX = x3;
  73699. intersectionY = y1 + along * dy1;
  73700. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  73701. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73702. if (along < 1.0f)
  73703. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73704. return along >= 0 && along <= 1.0f;
  73705. }
  73706. }
  73707. intersectionX = 0.5f * (x2 + x3);
  73708. intersectionY = 0.5f * (y2 + y3);
  73709. distanceBeyondLine1EndSquared = 0.0f;
  73710. return false;
  73711. }
  73712. else
  73713. {
  73714. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  73715. intersectionX = x1 + along1 * dx1;
  73716. intersectionY = y1 + along1 * dy1;
  73717. if (along1 >= 0 && along1 <= 1.0f)
  73718. {
  73719. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  73720. if (along2 >= 0 && along2 <= divisor)
  73721. {
  73722. distanceBeyondLine1EndSquared = 0.0f;
  73723. return true;
  73724. }
  73725. }
  73726. distanceBeyondLine1EndSquared = along1 - 1.0f;
  73727. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73728. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  73729. if (along1 < 1.0f)
  73730. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73731. return false;
  73732. }
  73733. }
  73734. intersectionX = x2;
  73735. intersectionY = y2;
  73736. distanceBeyondLine1EndSquared = 0.0f;
  73737. return true;
  73738. }
  73739. static void addEdgeAndJoint (Path& destPath,
  73740. const PathStrokeType::JointStyle style,
  73741. const float maxMiterExtensionSquared, const float width,
  73742. const float x1, const float y1,
  73743. const float x2, const float y2,
  73744. const float x3, const float y3,
  73745. const float x4, const float y4,
  73746. const float midX, const float midY)
  73747. {
  73748. if (style == PathStrokeType::beveled
  73749. || (x3 == x4 && y3 == y4)
  73750. || (x1 == x2 && y1 == y2))
  73751. {
  73752. destPath.lineTo (x2, y2);
  73753. destPath.lineTo (x3, y3);
  73754. }
  73755. else
  73756. {
  73757. float jx, jy, distanceBeyondLine1EndSquared;
  73758. // if they intersect, use this point..
  73759. if (lineIntersection (x1, y1, x2, y2,
  73760. x3, y3, x4, y4,
  73761. jx, jy, distanceBeyondLine1EndSquared))
  73762. {
  73763. destPath.lineTo (jx, jy);
  73764. }
  73765. else
  73766. {
  73767. if (style == PathStrokeType::mitered)
  73768. {
  73769. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  73770. && distanceBeyondLine1EndSquared > 0.0f)
  73771. {
  73772. destPath.lineTo (jx, jy);
  73773. }
  73774. else
  73775. {
  73776. // the end sticks out too far, so just use a blunt joint
  73777. destPath.lineTo (x2, y2);
  73778. destPath.lineTo (x3, y3);
  73779. }
  73780. }
  73781. else
  73782. {
  73783. // curved joints
  73784. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  73785. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  73786. const float angleIncrement = 0.1f;
  73787. destPath.lineTo (x2, y2);
  73788. if (std::abs (angle1 - angle2) > angleIncrement)
  73789. {
  73790. if (angle2 > angle1 + float_Pi
  73791. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  73792. {
  73793. if (angle2 > angle1)
  73794. angle2 -= float_Pi * 2.0f;
  73795. jassert (angle1 <= angle2 + float_Pi);
  73796. angle1 -= angleIncrement;
  73797. while (angle1 > angle2)
  73798. {
  73799. destPath.lineTo (midX + width * std::sin (angle1),
  73800. midY + width * std::cos (angle1));
  73801. angle1 -= angleIncrement;
  73802. }
  73803. }
  73804. else
  73805. {
  73806. if (angle1 > angle2)
  73807. angle1 -= float_Pi * 2.0f;
  73808. jassert (angle1 >= angle2 - float_Pi);
  73809. angle1 += angleIncrement;
  73810. while (angle1 < angle2)
  73811. {
  73812. destPath.lineTo (midX + width * std::sin (angle1),
  73813. midY + width * std::cos (angle1));
  73814. angle1 += angleIncrement;
  73815. }
  73816. }
  73817. }
  73818. destPath.lineTo (x3, y3);
  73819. }
  73820. }
  73821. }
  73822. }
  73823. static void addLineEnd (Path& destPath,
  73824. const PathStrokeType::EndCapStyle style,
  73825. const float x1, const float y1,
  73826. const float x2, const float y2,
  73827. const float width)
  73828. {
  73829. if (style == PathStrokeType::butt)
  73830. {
  73831. destPath.lineTo (x2, y2);
  73832. }
  73833. else
  73834. {
  73835. float offx1, offy1, offx2, offy2;
  73836. float dx = x2 - x1;
  73837. float dy = y2 - y1;
  73838. const float len = juce_hypotf (dx, dy);
  73839. if (len == 0)
  73840. {
  73841. offx1 = offx2 = x1;
  73842. offy1 = offy2 = y1;
  73843. }
  73844. else
  73845. {
  73846. const float offset = width / len;
  73847. dx *= offset;
  73848. dy *= offset;
  73849. offx1 = x1 + dy;
  73850. offy1 = y1 - dx;
  73851. offx2 = x2 + dy;
  73852. offy2 = y2 - dx;
  73853. }
  73854. if (style == PathStrokeType::square)
  73855. {
  73856. // sqaure ends
  73857. destPath.lineTo (offx1, offy1);
  73858. destPath.lineTo (offx2, offy2);
  73859. destPath.lineTo (x2, y2);
  73860. }
  73861. else
  73862. {
  73863. // rounded ends
  73864. const float midx = (offx1 + offx2) * 0.5f;
  73865. const float midy = (offy1 + offy2) * 0.5f;
  73866. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  73867. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  73868. midx, midy);
  73869. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  73870. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  73871. x2, y2);
  73872. }
  73873. }
  73874. }
  73875. struct Arrowhead
  73876. {
  73877. float startWidth, startLength;
  73878. float endWidth, endLength;
  73879. };
  73880. static void addArrowhead (Path& destPath,
  73881. const float x1, const float y1,
  73882. const float x2, const float y2,
  73883. const float tipX, const float tipY,
  73884. const float width,
  73885. const float arrowheadWidth)
  73886. {
  73887. Line<float> line (x1, y1, x2, y2);
  73888. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  73889. destPath.lineTo (tipX, tipY);
  73890. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  73891. destPath.lineTo (x2, y2);
  73892. }
  73893. struct LineSection
  73894. {
  73895. float x1, y1, x2, y2; // original line
  73896. float lx1, ly1, lx2, ly2; // the left-hand stroke
  73897. float rx1, ry1, rx2, ry2; // the right-hand stroke
  73898. };
  73899. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  73900. {
  73901. while (amountAtEnd > 0 && subPath.size() > 0)
  73902. {
  73903. LineSection& l = subPath.getReference (subPath.size() - 1);
  73904. float dx = l.rx2 - l.rx1;
  73905. float dy = l.ry2 - l.ry1;
  73906. const float len = juce_hypotf (dx, dy);
  73907. if (len <= amountAtEnd && subPath.size() > 1)
  73908. {
  73909. LineSection& prev = subPath.getReference (subPath.size() - 2);
  73910. prev.x2 = l.x2;
  73911. prev.y2 = l.y2;
  73912. subPath.removeLast();
  73913. amountAtEnd -= len;
  73914. }
  73915. else
  73916. {
  73917. const float prop = jmin (0.9999f, amountAtEnd / len);
  73918. dx *= prop;
  73919. dy *= prop;
  73920. l.rx1 += dx;
  73921. l.ry1 += dy;
  73922. l.lx2 += dx;
  73923. l.ly2 += dy;
  73924. break;
  73925. }
  73926. }
  73927. while (amountAtStart > 0 && subPath.size() > 0)
  73928. {
  73929. LineSection& l = subPath.getReference (0);
  73930. float dx = l.rx2 - l.rx1;
  73931. float dy = l.ry2 - l.ry1;
  73932. const float len = juce_hypotf (dx, dy);
  73933. if (len <= amountAtStart && subPath.size() > 1)
  73934. {
  73935. LineSection& next = subPath.getReference (1);
  73936. next.x1 = l.x1;
  73937. next.y1 = l.y1;
  73938. subPath.remove (0);
  73939. amountAtStart -= len;
  73940. }
  73941. else
  73942. {
  73943. const float prop = jmin (0.9999f, amountAtStart / len);
  73944. dx *= prop;
  73945. dy *= prop;
  73946. l.rx2 -= dx;
  73947. l.ry2 -= dy;
  73948. l.lx1 -= dx;
  73949. l.ly1 -= dy;
  73950. break;
  73951. }
  73952. }
  73953. }
  73954. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  73955. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  73956. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  73957. const Arrowhead* const arrowhead)
  73958. {
  73959. jassert (subPath.size() > 0);
  73960. if (arrowhead != 0)
  73961. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  73962. const LineSection& firstLine = subPath.getReference (0);
  73963. float lastX1 = firstLine.lx1;
  73964. float lastY1 = firstLine.ly1;
  73965. float lastX2 = firstLine.lx2;
  73966. float lastY2 = firstLine.ly2;
  73967. if (isClosed)
  73968. {
  73969. destPath.startNewSubPath (lastX1, lastY1);
  73970. }
  73971. else
  73972. {
  73973. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  73974. if (arrowhead != 0)
  73975. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  73976. width, arrowhead->startWidth);
  73977. else
  73978. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  73979. }
  73980. int i;
  73981. for (i = 1; i < subPath.size(); ++i)
  73982. {
  73983. const LineSection& l = subPath.getReference (i);
  73984. addEdgeAndJoint (destPath, jointStyle,
  73985. maxMiterExtensionSquared, width,
  73986. lastX1, lastY1, lastX2, lastY2,
  73987. l.lx1, l.ly1, l.lx2, l.ly2,
  73988. l.x1, l.y1);
  73989. lastX1 = l.lx1;
  73990. lastY1 = l.ly1;
  73991. lastX2 = l.lx2;
  73992. lastY2 = l.ly2;
  73993. }
  73994. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  73995. if (isClosed)
  73996. {
  73997. const LineSection& l = subPath.getReference (0);
  73998. addEdgeAndJoint (destPath, jointStyle,
  73999. maxMiterExtensionSquared, width,
  74000. lastX1, lastY1, lastX2, lastY2,
  74001. l.lx1, l.ly1, l.lx2, l.ly2,
  74002. l.x1, l.y1);
  74003. destPath.closeSubPath();
  74004. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  74005. }
  74006. else
  74007. {
  74008. destPath.lineTo (lastX2, lastY2);
  74009. if (arrowhead != 0)
  74010. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  74011. width, arrowhead->endWidth);
  74012. else
  74013. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  74014. }
  74015. lastX1 = lastLine.rx1;
  74016. lastY1 = lastLine.ry1;
  74017. lastX2 = lastLine.rx2;
  74018. lastY2 = lastLine.ry2;
  74019. for (i = subPath.size() - 1; --i >= 0;)
  74020. {
  74021. const LineSection& l = subPath.getReference (i);
  74022. addEdgeAndJoint (destPath, jointStyle,
  74023. maxMiterExtensionSquared, width,
  74024. lastX1, lastY1, lastX2, lastY2,
  74025. l.rx1, l.ry1, l.rx2, l.ry2,
  74026. l.x2, l.y2);
  74027. lastX1 = l.rx1;
  74028. lastY1 = l.ry1;
  74029. lastX2 = l.rx2;
  74030. lastY2 = l.ry2;
  74031. }
  74032. if (isClosed)
  74033. {
  74034. addEdgeAndJoint (destPath, jointStyle,
  74035. maxMiterExtensionSquared, width,
  74036. lastX1, lastY1, lastX2, lastY2,
  74037. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  74038. lastLine.x2, lastLine.y2);
  74039. }
  74040. else
  74041. {
  74042. // do the last line
  74043. destPath.lineTo (lastX2, lastY2);
  74044. }
  74045. destPath.closeSubPath();
  74046. }
  74047. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  74048. const PathStrokeType::EndCapStyle endStyle,
  74049. Path& destPath, const Path& source,
  74050. const AffineTransform& transform,
  74051. const float extraAccuracy, const Arrowhead* const arrowhead)
  74052. {
  74053. if (thickness <= 0)
  74054. {
  74055. destPath.clear();
  74056. return;
  74057. }
  74058. const Path* sourcePath = &source;
  74059. Path temp;
  74060. if (sourcePath == &destPath)
  74061. {
  74062. destPath.swapWithPath (temp);
  74063. sourcePath = &temp;
  74064. }
  74065. else
  74066. {
  74067. destPath.clear();
  74068. }
  74069. destPath.setUsingNonZeroWinding (true);
  74070. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  74071. const float width = 0.5f * thickness;
  74072. // Iterate the path, creating a list of the
  74073. // left/right-hand lines along either side of it...
  74074. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  74075. Array <LineSection> subPath;
  74076. subPath.ensureStorageAllocated (512);
  74077. LineSection l;
  74078. l.x1 = 0;
  74079. l.y1 = 0;
  74080. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  74081. while (it.next())
  74082. {
  74083. if (it.subPathIndex == 0)
  74084. {
  74085. if (subPath.size() > 0)
  74086. {
  74087. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74088. subPath.clearQuick();
  74089. }
  74090. l.x1 = it.x1;
  74091. l.y1 = it.y1;
  74092. }
  74093. l.x2 = it.x2;
  74094. l.y2 = it.y2;
  74095. float dx = l.x2 - l.x1;
  74096. float dy = l.y2 - l.y1;
  74097. const float hypotSquared = dx*dx + dy*dy;
  74098. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  74099. {
  74100. const float len = std::sqrt (hypotSquared);
  74101. if (len == 0)
  74102. {
  74103. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  74104. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  74105. }
  74106. else
  74107. {
  74108. const float offset = width / len;
  74109. dx *= offset;
  74110. dy *= offset;
  74111. l.rx2 = l.x1 - dy;
  74112. l.ry2 = l.y1 + dx;
  74113. l.lx1 = l.x1 + dy;
  74114. l.ly1 = l.y1 - dx;
  74115. l.lx2 = l.x2 + dy;
  74116. l.ly2 = l.y2 - dx;
  74117. l.rx1 = l.x2 - dy;
  74118. l.ry1 = l.y2 + dx;
  74119. }
  74120. subPath.add (l);
  74121. if (it.closesSubPath)
  74122. {
  74123. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74124. subPath.clearQuick();
  74125. }
  74126. else
  74127. {
  74128. l.x1 = it.x2;
  74129. l.y1 = it.y2;
  74130. }
  74131. }
  74132. }
  74133. if (subPath.size() > 0)
  74134. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74135. }
  74136. }
  74137. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  74138. const AffineTransform& transform, const float extraAccuracy) const
  74139. {
  74140. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  74141. transform, extraAccuracy, 0);
  74142. }
  74143. void PathStrokeType::createDashedStroke (Path& destPath,
  74144. const Path& sourcePath,
  74145. const float* dashLengths,
  74146. int numDashLengths,
  74147. const AffineTransform& transform,
  74148. const float extraAccuracy) const
  74149. {
  74150. if (thickness <= 0)
  74151. return;
  74152. // this should really be an even number..
  74153. jassert ((numDashLengths & 1) == 0);
  74154. Path newDestPath;
  74155. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  74156. bool first = true;
  74157. int dashNum = 0;
  74158. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  74159. float dx = 0.0f, dy = 0.0f;
  74160. for (;;)
  74161. {
  74162. const bool isSolid = ((dashNum & 1) == 0);
  74163. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  74164. jassert (dashLen > 0); // must be a positive increment!
  74165. if (dashLen <= 0)
  74166. break;
  74167. pos += dashLen;
  74168. while (pos > lineEndPos)
  74169. {
  74170. if (! it.next())
  74171. {
  74172. if (isSolid && ! first)
  74173. newDestPath.lineTo (it.x2, it.y2);
  74174. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  74175. return;
  74176. }
  74177. if (isSolid && ! first)
  74178. newDestPath.lineTo (it.x1, it.y1);
  74179. else
  74180. newDestPath.startNewSubPath (it.x1, it.y1);
  74181. dx = it.x2 - it.x1;
  74182. dy = it.y2 - it.y1;
  74183. lineLen = juce_hypotf (dx, dy);
  74184. lineEndPos += lineLen;
  74185. first = it.closesSubPath;
  74186. }
  74187. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  74188. if (isSolid)
  74189. newDestPath.lineTo (it.x1 + dx * alpha,
  74190. it.y1 + dy * alpha);
  74191. else
  74192. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  74193. it.y1 + dy * alpha);
  74194. }
  74195. }
  74196. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  74197. const Path& sourcePath,
  74198. const float arrowheadStartWidth, const float arrowheadStartLength,
  74199. const float arrowheadEndWidth, const float arrowheadEndLength,
  74200. const AffineTransform& transform,
  74201. const float extraAccuracy) const
  74202. {
  74203. PathStrokeHelpers::Arrowhead head;
  74204. head.startWidth = arrowheadStartWidth;
  74205. head.startLength = arrowheadStartLength;
  74206. head.endWidth = arrowheadEndWidth;
  74207. head.endLength = arrowheadEndLength;
  74208. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  74209. destPath, sourcePath, transform, extraAccuracy, &head);
  74210. }
  74211. END_JUCE_NAMESPACE
  74212. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  74213. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  74214. BEGIN_JUCE_NAMESPACE
  74215. PositionedRectangle::PositionedRectangle() throw()
  74216. : x (0.0),
  74217. y (0.0),
  74218. w (0.0),
  74219. h (0.0),
  74220. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  74221. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  74222. wMode (absoluteSize),
  74223. hMode (absoluteSize)
  74224. {
  74225. }
  74226. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  74227. : x (other.x),
  74228. y (other.y),
  74229. w (other.w),
  74230. h (other.h),
  74231. xMode (other.xMode),
  74232. yMode (other.yMode),
  74233. wMode (other.wMode),
  74234. hMode (other.hMode)
  74235. {
  74236. }
  74237. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  74238. {
  74239. x = other.x;
  74240. y = other.y;
  74241. w = other.w;
  74242. h = other.h;
  74243. xMode = other.xMode;
  74244. yMode = other.yMode;
  74245. wMode = other.wMode;
  74246. hMode = other.hMode;
  74247. return *this;
  74248. }
  74249. PositionedRectangle::~PositionedRectangle() throw()
  74250. {
  74251. }
  74252. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  74253. {
  74254. return x == other.x
  74255. && y == other.y
  74256. && w == other.w
  74257. && h == other.h
  74258. && xMode == other.xMode
  74259. && yMode == other.yMode
  74260. && wMode == other.wMode
  74261. && hMode == other.hMode;
  74262. }
  74263. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  74264. {
  74265. return ! operator== (other);
  74266. }
  74267. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  74268. {
  74269. StringArray tokens;
  74270. tokens.addTokens (stringVersion, false);
  74271. decodePosString (tokens [0], xMode, x);
  74272. decodePosString (tokens [1], yMode, y);
  74273. decodeSizeString (tokens [2], wMode, w);
  74274. decodeSizeString (tokens [3], hMode, h);
  74275. }
  74276. const String PositionedRectangle::toString() const throw()
  74277. {
  74278. String s;
  74279. s.preallocateStorage (12);
  74280. addPosDescription (s, xMode, x);
  74281. s << ' ';
  74282. addPosDescription (s, yMode, y);
  74283. s << ' ';
  74284. addSizeDescription (s, wMode, w);
  74285. s << ' ';
  74286. addSizeDescription (s, hMode, h);
  74287. return s;
  74288. }
  74289. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  74290. {
  74291. jassert (! target.isEmpty());
  74292. double x_, y_, w_, h_;
  74293. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  74294. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  74295. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  74296. roundToInt (w_), roundToInt (h_));
  74297. }
  74298. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  74299. double& x_, double& y_,
  74300. double& w_, double& h_) const throw()
  74301. {
  74302. jassert (! target.isEmpty());
  74303. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  74304. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  74305. }
  74306. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  74307. {
  74308. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  74309. }
  74310. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  74311. const Rectangle<int>& target) throw()
  74312. {
  74313. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  74314. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  74315. }
  74316. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  74317. const double newW, const double newH,
  74318. const Rectangle<int>& target) throw()
  74319. {
  74320. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  74321. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  74322. }
  74323. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  74324. {
  74325. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  74326. updateFrom (comp.getBounds(), Rectangle<int>());
  74327. else
  74328. updateFrom (comp.getBounds(), Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  74329. }
  74330. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  74331. {
  74332. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  74333. }
  74334. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  74335. {
  74336. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  74337. | absoluteFromParentBottomRight
  74338. | absoluteFromParentCentre
  74339. | proportionOfParentSize));
  74340. }
  74341. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  74342. {
  74343. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  74344. }
  74345. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  74346. {
  74347. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  74348. | absoluteFromParentBottomRight
  74349. | absoluteFromParentCentre
  74350. | proportionOfParentSize));
  74351. }
  74352. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  74353. {
  74354. return (SizeMode) wMode;
  74355. }
  74356. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  74357. {
  74358. return (SizeMode) hMode;
  74359. }
  74360. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  74361. const PositionMode xMode_,
  74362. const AnchorPoint yAnchor,
  74363. const PositionMode yMode_,
  74364. const SizeMode widthMode,
  74365. const SizeMode heightMode,
  74366. const Rectangle<int>& target) throw()
  74367. {
  74368. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  74369. {
  74370. double tx, tw;
  74371. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  74372. xMode = (uint8) (xAnchor | xMode_);
  74373. wMode = (uint8) widthMode;
  74374. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  74375. }
  74376. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  74377. {
  74378. double ty, th;
  74379. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  74380. yMode = (uint8) (yAnchor | yMode_);
  74381. hMode = (uint8) heightMode;
  74382. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  74383. }
  74384. }
  74385. bool PositionedRectangle::isPositionAbsolute() const throw()
  74386. {
  74387. return xMode == absoluteFromParentTopLeft
  74388. && yMode == absoluteFromParentTopLeft
  74389. && wMode == absoluteSize
  74390. && hMode == absoluteSize;
  74391. }
  74392. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  74393. {
  74394. if ((mode & proportionOfParentSize) != 0)
  74395. {
  74396. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  74397. }
  74398. else
  74399. {
  74400. s << (roundToInt (value * 100.0) / 100.0);
  74401. if ((mode & absoluteFromParentBottomRight) != 0)
  74402. s << 'R';
  74403. else if ((mode & absoluteFromParentCentre) != 0)
  74404. s << 'C';
  74405. }
  74406. if ((mode & anchorAtRightOrBottom) != 0)
  74407. s << 'r';
  74408. else if ((mode & anchorAtCentre) != 0)
  74409. s << 'c';
  74410. }
  74411. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  74412. {
  74413. if (mode == proportionalSize)
  74414. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  74415. else if (mode == parentSizeMinusAbsolute)
  74416. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  74417. else
  74418. s << (roundToInt (value * 100.0) / 100.0);
  74419. }
  74420. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  74421. {
  74422. if (s.containsChar ('r'))
  74423. mode = anchorAtRightOrBottom;
  74424. else if (s.containsChar ('c'))
  74425. mode = anchorAtCentre;
  74426. else
  74427. mode = anchorAtLeftOrTop;
  74428. if (s.containsChar ('%'))
  74429. {
  74430. mode |= proportionOfParentSize;
  74431. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  74432. }
  74433. else
  74434. {
  74435. if (s.containsChar ('R'))
  74436. mode |= absoluteFromParentBottomRight;
  74437. else if (s.containsChar ('C'))
  74438. mode |= absoluteFromParentCentre;
  74439. else
  74440. mode |= absoluteFromParentTopLeft;
  74441. value = s.removeCharacters ("rcRC").getDoubleValue();
  74442. }
  74443. }
  74444. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  74445. {
  74446. if (s.containsChar ('%'))
  74447. {
  74448. mode = proportionalSize;
  74449. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  74450. }
  74451. else if (s.containsChar ('M'))
  74452. {
  74453. mode = parentSizeMinusAbsolute;
  74454. value = s.getDoubleValue();
  74455. }
  74456. else
  74457. {
  74458. mode = absoluteSize;
  74459. value = s.getDoubleValue();
  74460. }
  74461. }
  74462. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  74463. const double x_, const double w_,
  74464. const uint8 xMode_, const uint8 wMode_,
  74465. const int parentPos,
  74466. const int parentSize) const throw()
  74467. {
  74468. if (wMode_ == proportionalSize)
  74469. wOut = roundToInt (w_ * parentSize);
  74470. else if (wMode_ == parentSizeMinusAbsolute)
  74471. wOut = jmax (0, parentSize - roundToInt (w_));
  74472. else
  74473. wOut = roundToInt (w_);
  74474. if ((xMode_ & proportionOfParentSize) != 0)
  74475. xOut = parentPos + x_ * parentSize;
  74476. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  74477. xOut = (parentPos + parentSize) - x_;
  74478. else if ((xMode_ & absoluteFromParentCentre) != 0)
  74479. xOut = x_ + (parentPos + parentSize / 2);
  74480. else
  74481. xOut = x_ + parentPos;
  74482. if ((xMode_ & anchorAtRightOrBottom) != 0)
  74483. xOut -= wOut;
  74484. else if ((xMode_ & anchorAtCentre) != 0)
  74485. xOut -= wOut / 2;
  74486. }
  74487. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  74488. double x_, const double w_,
  74489. const uint8 xMode_, const uint8 wMode_,
  74490. const int parentPos,
  74491. const int parentSize) const throw()
  74492. {
  74493. if (wMode_ == proportionalSize)
  74494. {
  74495. if (parentSize > 0)
  74496. wOut = w_ / parentSize;
  74497. }
  74498. else if (wMode_ == parentSizeMinusAbsolute)
  74499. wOut = parentSize - w_;
  74500. else
  74501. wOut = w_;
  74502. if ((xMode_ & anchorAtRightOrBottom) != 0)
  74503. x_ += w_;
  74504. else if ((xMode_ & anchorAtCentre) != 0)
  74505. x_ += w_ / 2;
  74506. if ((xMode_ & proportionOfParentSize) != 0)
  74507. {
  74508. if (parentSize > 0)
  74509. xOut = (x_ - parentPos) / parentSize;
  74510. }
  74511. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  74512. xOut = (parentPos + parentSize) - x_;
  74513. else if ((xMode_ & absoluteFromParentCentre) != 0)
  74514. xOut = x_ - (parentPos + parentSize / 2);
  74515. else
  74516. xOut = x_ - parentPos;
  74517. }
  74518. END_JUCE_NAMESPACE
  74519. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  74520. /*** Start of inlined file: juce_RectangleList.cpp ***/
  74521. BEGIN_JUCE_NAMESPACE
  74522. RectangleList::RectangleList() throw()
  74523. {
  74524. }
  74525. RectangleList::RectangleList (const Rectangle<int>& rect)
  74526. {
  74527. if (! rect.isEmpty())
  74528. rects.add (rect);
  74529. }
  74530. RectangleList::RectangleList (const RectangleList& other)
  74531. : rects (other.rects)
  74532. {
  74533. }
  74534. RectangleList& RectangleList::operator= (const RectangleList& other)
  74535. {
  74536. rects = other.rects;
  74537. return *this;
  74538. }
  74539. RectangleList::~RectangleList()
  74540. {
  74541. }
  74542. void RectangleList::clear()
  74543. {
  74544. rects.clearQuick();
  74545. }
  74546. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  74547. {
  74548. if (((unsigned int) index) < (unsigned int) rects.size())
  74549. return rects.getReference (index);
  74550. return Rectangle<int>();
  74551. }
  74552. bool RectangleList::isEmpty() const throw()
  74553. {
  74554. return rects.size() == 0;
  74555. }
  74556. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  74557. : current (0),
  74558. owner (list),
  74559. index (list.rects.size())
  74560. {
  74561. }
  74562. RectangleList::Iterator::~Iterator()
  74563. {
  74564. }
  74565. bool RectangleList::Iterator::next() throw()
  74566. {
  74567. if (--index >= 0)
  74568. {
  74569. current = & (owner.rects.getReference (index));
  74570. return true;
  74571. }
  74572. return false;
  74573. }
  74574. void RectangleList::add (const Rectangle<int>& rect)
  74575. {
  74576. if (! rect.isEmpty())
  74577. {
  74578. if (rects.size() == 0)
  74579. {
  74580. rects.add (rect);
  74581. }
  74582. else
  74583. {
  74584. bool anyOverlaps = false;
  74585. int i;
  74586. for (i = rects.size(); --i >= 0;)
  74587. {
  74588. Rectangle<int>& ourRect = rects.getReference (i);
  74589. if (rect.intersects (ourRect))
  74590. {
  74591. if (rect.contains (ourRect))
  74592. rects.remove (i);
  74593. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  74594. anyOverlaps = true;
  74595. }
  74596. }
  74597. if (anyOverlaps && rects.size() > 0)
  74598. {
  74599. RectangleList r (rect);
  74600. for (i = rects.size(); --i >= 0;)
  74601. {
  74602. const Rectangle<int>& ourRect = rects.getReference (i);
  74603. if (rect.intersects (ourRect))
  74604. {
  74605. r.subtract (ourRect);
  74606. if (r.rects.size() == 0)
  74607. return;
  74608. }
  74609. }
  74610. for (i = r.getNumRectangles(); --i >= 0;)
  74611. rects.add (r.rects.getReference (i));
  74612. }
  74613. else
  74614. {
  74615. rects.add (rect);
  74616. }
  74617. }
  74618. }
  74619. }
  74620. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  74621. {
  74622. if (! rect.isEmpty())
  74623. rects.add (rect);
  74624. }
  74625. void RectangleList::add (const int x, const int y, const int w, const int h)
  74626. {
  74627. if (rects.size() == 0)
  74628. {
  74629. if (w > 0 && h > 0)
  74630. rects.add (Rectangle<int> (x, y, w, h));
  74631. }
  74632. else
  74633. {
  74634. add (Rectangle<int> (x, y, w, h));
  74635. }
  74636. }
  74637. void RectangleList::add (const RectangleList& other)
  74638. {
  74639. for (int i = 0; i < other.rects.size(); ++i)
  74640. add (other.rects.getReference (i));
  74641. }
  74642. void RectangleList::subtract (const Rectangle<int>& rect)
  74643. {
  74644. const int originalNumRects = rects.size();
  74645. if (originalNumRects > 0)
  74646. {
  74647. const int x1 = rect.x;
  74648. const int y1 = rect.y;
  74649. const int x2 = x1 + rect.w;
  74650. const int y2 = y1 + rect.h;
  74651. for (int i = getNumRectangles(); --i >= 0;)
  74652. {
  74653. Rectangle<int>& r = rects.getReference (i);
  74654. const int rx1 = r.x;
  74655. const int ry1 = r.y;
  74656. const int rx2 = rx1 + r.w;
  74657. const int ry2 = ry1 + r.h;
  74658. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  74659. {
  74660. if (x1 > rx1 && x1 < rx2)
  74661. {
  74662. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  74663. {
  74664. r.w = x1 - rx1;
  74665. }
  74666. else
  74667. {
  74668. r.x = x1;
  74669. r.w = rx2 - x1;
  74670. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  74671. i += 2;
  74672. }
  74673. }
  74674. else if (x2 > rx1 && x2 < rx2)
  74675. {
  74676. r.x = x2;
  74677. r.w = rx2 - x2;
  74678. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  74679. {
  74680. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  74681. i += 2;
  74682. }
  74683. }
  74684. else if (y1 > ry1 && y1 < ry2)
  74685. {
  74686. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  74687. {
  74688. r.h = y1 - ry1;
  74689. }
  74690. else
  74691. {
  74692. r.y = y1;
  74693. r.h = ry2 - y1;
  74694. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  74695. i += 2;
  74696. }
  74697. }
  74698. else if (y2 > ry1 && y2 < ry2)
  74699. {
  74700. r.y = y2;
  74701. r.h = ry2 - y2;
  74702. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  74703. {
  74704. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  74705. i += 2;
  74706. }
  74707. }
  74708. else
  74709. {
  74710. rects.remove (i);
  74711. }
  74712. }
  74713. }
  74714. }
  74715. }
  74716. bool RectangleList::subtract (const RectangleList& otherList)
  74717. {
  74718. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  74719. subtract (otherList.rects.getReference (i));
  74720. return rects.size() > 0;
  74721. }
  74722. bool RectangleList::clipTo (const Rectangle<int>& rect)
  74723. {
  74724. bool notEmpty = false;
  74725. if (rect.isEmpty())
  74726. {
  74727. clear();
  74728. }
  74729. else
  74730. {
  74731. for (int i = rects.size(); --i >= 0;)
  74732. {
  74733. Rectangle<int>& r = rects.getReference (i);
  74734. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  74735. rects.remove (i);
  74736. else
  74737. notEmpty = true;
  74738. }
  74739. }
  74740. return notEmpty;
  74741. }
  74742. bool RectangleList::clipTo (const RectangleList& other)
  74743. {
  74744. if (rects.size() == 0)
  74745. return false;
  74746. RectangleList result;
  74747. for (int j = 0; j < rects.size(); ++j)
  74748. {
  74749. const Rectangle<int>& rect = rects.getReference (j);
  74750. for (int i = other.rects.size(); --i >= 0;)
  74751. {
  74752. Rectangle<int> r (other.rects.getReference (i));
  74753. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  74754. result.rects.add (r);
  74755. }
  74756. }
  74757. swapWith (result);
  74758. return ! isEmpty();
  74759. }
  74760. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  74761. {
  74762. destRegion.clear();
  74763. if (! rect.isEmpty())
  74764. {
  74765. for (int i = rects.size(); --i >= 0;)
  74766. {
  74767. Rectangle<int> r (rects.getReference (i));
  74768. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  74769. destRegion.rects.add (r);
  74770. }
  74771. }
  74772. return destRegion.rects.size() > 0;
  74773. }
  74774. void RectangleList::swapWith (RectangleList& otherList) throw()
  74775. {
  74776. rects.swapWithArray (otherList.rects);
  74777. }
  74778. void RectangleList::consolidate()
  74779. {
  74780. int i;
  74781. for (i = 0; i < getNumRectangles() - 1; ++i)
  74782. {
  74783. Rectangle<int>& r = rects.getReference (i);
  74784. const int rx1 = r.x;
  74785. const int ry1 = r.y;
  74786. const int rx2 = rx1 + r.w;
  74787. const int ry2 = ry1 + r.h;
  74788. for (int j = rects.size(); --j > i;)
  74789. {
  74790. Rectangle<int>& r2 = rects.getReference (j);
  74791. const int jrx1 = r2.x;
  74792. const int jry1 = r2.y;
  74793. const int jrx2 = jrx1 + r2.w;
  74794. const int jry2 = jry1 + r2.h;
  74795. // if the vertical edges of any blocks are touching and their horizontals don't
  74796. // line up, split them horizontally..
  74797. if (jrx1 == rx2 || jrx2 == rx1)
  74798. {
  74799. if (jry1 > ry1 && jry1 < ry2)
  74800. {
  74801. r.h = jry1 - ry1;
  74802. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  74803. i = -1;
  74804. break;
  74805. }
  74806. if (jry2 > ry1 && jry2 < ry2)
  74807. {
  74808. r.h = jry2 - ry1;
  74809. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  74810. i = -1;
  74811. break;
  74812. }
  74813. else if (ry1 > jry1 && ry1 < jry2)
  74814. {
  74815. r2.h = ry1 - jry1;
  74816. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  74817. i = -1;
  74818. break;
  74819. }
  74820. else if (ry2 > jry1 && ry2 < jry2)
  74821. {
  74822. r2.h = ry2 - jry1;
  74823. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  74824. i = -1;
  74825. break;
  74826. }
  74827. }
  74828. }
  74829. }
  74830. for (i = 0; i < rects.size() - 1; ++i)
  74831. {
  74832. Rectangle<int>& r = rects.getReference (i);
  74833. for (int j = rects.size(); --j > i;)
  74834. {
  74835. if (r.enlargeIfAdjacent (rects.getReference (j)))
  74836. {
  74837. rects.remove (j);
  74838. i = -1;
  74839. break;
  74840. }
  74841. }
  74842. }
  74843. }
  74844. bool RectangleList::containsPoint (const int x, const int y) const throw()
  74845. {
  74846. for (int i = getNumRectangles(); --i >= 0;)
  74847. if (rects.getReference (i).contains (x, y))
  74848. return true;
  74849. return false;
  74850. }
  74851. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  74852. {
  74853. if (rects.size() > 1)
  74854. {
  74855. RectangleList r (rectangleToCheck);
  74856. for (int i = rects.size(); --i >= 0;)
  74857. {
  74858. r.subtract (rects.getReference (i));
  74859. if (r.rects.size() == 0)
  74860. return true;
  74861. }
  74862. }
  74863. else if (rects.size() > 0)
  74864. {
  74865. return rects.getReference (0).contains (rectangleToCheck);
  74866. }
  74867. return false;
  74868. }
  74869. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  74870. {
  74871. for (int i = rects.size(); --i >= 0;)
  74872. if (rects.getReference (i).intersects (rectangleToCheck))
  74873. return true;
  74874. return false;
  74875. }
  74876. bool RectangleList::intersects (const RectangleList& other) const throw()
  74877. {
  74878. for (int i = rects.size(); --i >= 0;)
  74879. if (other.intersectsRectangle (rects.getReference (i)))
  74880. return true;
  74881. return false;
  74882. }
  74883. const Rectangle<int> RectangleList::getBounds() const throw()
  74884. {
  74885. if (rects.size() <= 1)
  74886. {
  74887. if (rects.size() == 0)
  74888. return Rectangle<int>();
  74889. else
  74890. return rects.getReference (0);
  74891. }
  74892. else
  74893. {
  74894. const Rectangle<int>& r = rects.getReference (0);
  74895. int minX = r.x;
  74896. int minY = r.y;
  74897. int maxX = minX + r.w;
  74898. int maxY = minY + r.h;
  74899. for (int i = rects.size(); --i > 0;)
  74900. {
  74901. const Rectangle<int>& r2 = rects.getReference (i);
  74902. minX = jmin (minX, r2.x);
  74903. minY = jmin (minY, r2.y);
  74904. maxX = jmax (maxX, r2.getRight());
  74905. maxY = jmax (maxY, r2.getBottom());
  74906. }
  74907. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  74908. }
  74909. }
  74910. void RectangleList::offsetAll (const int dx, const int dy) throw()
  74911. {
  74912. for (int i = rects.size(); --i >= 0;)
  74913. {
  74914. Rectangle<int>& r = rects.getReference (i);
  74915. r.x += dx;
  74916. r.y += dy;
  74917. }
  74918. }
  74919. const Path RectangleList::toPath() const
  74920. {
  74921. Path p;
  74922. for (int i = rects.size(); --i >= 0;)
  74923. {
  74924. const Rectangle<int>& r = rects.getReference (i);
  74925. p.addRectangle ((float) r.x,
  74926. (float) r.y,
  74927. (float) r.w,
  74928. (float) r.h);
  74929. }
  74930. return p;
  74931. }
  74932. END_JUCE_NAMESPACE
  74933. /*** End of inlined file: juce_RectangleList.cpp ***/
  74934. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  74935. BEGIN_JUCE_NAMESPACE
  74936. namespace RelativeCoordinateHelpers
  74937. {
  74938. static bool isOrigin (const String& name)
  74939. {
  74940. return name.isEmpty()
  74941. || name == RelativeCoordinate::Strings::parentLeft
  74942. || name == RelativeCoordinate::Strings::parentTop;
  74943. }
  74944. static const String getOriginAnchorName (const bool isHorizontal) throw()
  74945. {
  74946. return isHorizontal ? RelativeCoordinate::Strings::parentLeft
  74947. : RelativeCoordinate::Strings::parentTop;
  74948. }
  74949. static const String getExtentAnchorName (const bool isHorizontal) throw()
  74950. {
  74951. return isHorizontal ? RelativeCoordinate::Strings::parentRight
  74952. : RelativeCoordinate::Strings::parentBottom;
  74953. }
  74954. static const String getObjectName (const String& fullName)
  74955. {
  74956. return fullName.upToFirstOccurrenceOf (".", false, false);
  74957. }
  74958. static const String getEdgeName (const String& fullName)
  74959. {
  74960. return fullName.fromFirstOccurrenceOf (".", false, false);
  74961. }
  74962. static const RelativeCoordinate findCoordinate (const String& name, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  74963. {
  74964. return nameFinder != 0 ? nameFinder->findNamedCoordinate (getObjectName (name), getEdgeName (name))
  74965. : RelativeCoordinate();
  74966. }
  74967. struct RecursionException : public std::runtime_error
  74968. {
  74969. RecursionException() : std::runtime_error ("Recursive RelativeCoordinate expression")
  74970. {
  74971. }
  74972. };
  74973. static void skipWhitespace (const String& s, int& i)
  74974. {
  74975. while (CharacterFunctions::isWhitespace (s[i]))
  74976. ++i;
  74977. }
  74978. static void skipComma (const String& s, int& i)
  74979. {
  74980. skipWhitespace (s, i);
  74981. if (s[i] == ',')
  74982. ++i;
  74983. }
  74984. static const String readAnchorName (const String& s, int& i)
  74985. {
  74986. skipWhitespace (s, i);
  74987. if (CharacterFunctions::isLetter (s[i]) || s[i] == '_')
  74988. {
  74989. int start = i;
  74990. while (CharacterFunctions::isLetterOrDigit (s[i]) || s[i] == '_' || s[i] == '.')
  74991. ++i;
  74992. return s.substring (start, i);
  74993. }
  74994. return String::empty;
  74995. }
  74996. static double readNumber (const String& s, int& i)
  74997. {
  74998. skipWhitespace (s, i);
  74999. int start = i;
  75000. if (CharacterFunctions::isDigit (s[i]) || s[i] == '.' || s[i] == '-')
  75001. ++i;
  75002. while (CharacterFunctions::isDigit (s[i]) || s[i] == '.')
  75003. ++i;
  75004. if ((s[i] == 'e' || s[i] == 'E')
  75005. && (CharacterFunctions::isDigit (s[i + 1])
  75006. || s[i + 1] == '-'
  75007. || s[i + 1] == '+'))
  75008. {
  75009. i += 2;
  75010. while (CharacterFunctions::isDigit (s[i]))
  75011. ++i;
  75012. }
  75013. const double value = s.substring (start, i).getDoubleValue();
  75014. while (CharacterFunctions::isWhitespace (s[i]) || s[i] == ',')
  75015. ++i;
  75016. return value;
  75017. }
  75018. static const RelativeCoordinate readNextCoordinate (const String& s, int& i, const bool isHorizontal)
  75019. {
  75020. String anchor1 (readAnchorName (s, i));
  75021. double value = 0;
  75022. if (anchor1.isNotEmpty())
  75023. {
  75024. skipWhitespace (s, i);
  75025. if (s[i] == '+')
  75026. value = readNumber (s, ++i);
  75027. else if (s[i] == '-')
  75028. value = -readNumber (s, ++i);
  75029. return RelativeCoordinate (value, anchor1);
  75030. }
  75031. else
  75032. {
  75033. value = readNumber (s, i);
  75034. skipWhitespace (s, i);
  75035. if (s[i] == '%')
  75036. {
  75037. value /= 100.0;
  75038. skipWhitespace (s, ++i);
  75039. String anchor2;
  75040. if (s[i] == '*')
  75041. {
  75042. anchor1 = readAnchorName (s, ++i);
  75043. if (anchor1.isEmpty())
  75044. anchor1 = getOriginAnchorName (isHorizontal);
  75045. skipWhitespace (s, i);
  75046. if (s[i] == '-' && s[i + 1] == '>')
  75047. {
  75048. i += 2;
  75049. anchor2 = readAnchorName (s, i);
  75050. }
  75051. else
  75052. {
  75053. anchor2 = anchor1;
  75054. anchor1 = getOriginAnchorName (isHorizontal);
  75055. }
  75056. }
  75057. else
  75058. {
  75059. anchor1 = getOriginAnchorName (isHorizontal);
  75060. anchor2 = getExtentAnchorName (isHorizontal);
  75061. }
  75062. return RelativeCoordinate (value, anchor1, anchor2);
  75063. }
  75064. return RelativeCoordinate (value, isHorizontal);
  75065. }
  75066. }
  75067. static const String limitedAccuracyString (const double n)
  75068. {
  75069. if (! (n < -0.001 || n > 0.001)) // to detect NaN and inf as well as for rounding
  75070. return "0";
  75071. return String (n, 3).trimCharactersAtEnd ("0").trimCharactersAtEnd (".");
  75072. }
  75073. }
  75074. const String RelativeCoordinate::Strings::parent ("parent");
  75075. const String RelativeCoordinate::Strings::left ("left");
  75076. const String RelativeCoordinate::Strings::right ("right");
  75077. const String RelativeCoordinate::Strings::top ("top");
  75078. const String RelativeCoordinate::Strings::bottom ("bottom");
  75079. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  75080. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  75081. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  75082. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  75083. RelativeCoordinate::RelativeCoordinate()
  75084. : value (0)
  75085. {
  75086. }
  75087. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin, const bool horizontal_)
  75088. : anchor1 (RelativeCoordinateHelpers::getOriginAnchorName (horizontal_)),
  75089. value (absoluteDistanceFromOrigin)
  75090. {
  75091. }
  75092. RelativeCoordinate::RelativeCoordinate (const double absoluteDistance, const String& source)
  75093. : anchor1 (source.trim()),
  75094. value (absoluteDistance)
  75095. {
  75096. jassert (anchor1.isNotEmpty());
  75097. }
  75098. RelativeCoordinate::RelativeCoordinate (const double relativeProportion, const String& pos1, const String& pos2)
  75099. : anchor1 (pos1.trim()),
  75100. anchor2 (pos2.trim()),
  75101. value (relativeProportion)
  75102. {
  75103. jassert (anchor1.isNotEmpty());
  75104. jassert (anchor2.isNotEmpty());
  75105. }
  75106. RelativeCoordinate::RelativeCoordinate (const String& s, const bool isHorizontal)
  75107. : value (0)
  75108. {
  75109. int i = 0;
  75110. *this = RelativeCoordinateHelpers::readNextCoordinate (s, i, isHorizontal);
  75111. }
  75112. RelativeCoordinate::~RelativeCoordinate()
  75113. {
  75114. }
  75115. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  75116. {
  75117. return value == other.value && anchor1 == other.anchor1 && anchor2 == other.anchor2;
  75118. }
  75119. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  75120. {
  75121. return ! operator== (other);
  75122. }
  75123. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate1() const
  75124. {
  75125. return RelativeCoordinate (0.0, anchor1);
  75126. }
  75127. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate2() const
  75128. {
  75129. return RelativeCoordinate (0.0, anchor2);
  75130. }
  75131. double RelativeCoordinate::resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter)
  75132. {
  75133. if (RelativeCoordinateHelpers::isOrigin (anchorName))
  75134. return 0.0;
  75135. return RelativeCoordinateHelpers::findCoordinate (anchorName, nameFinder).resolve (nameFinder, recursionCounter + 1);
  75136. }
  75137. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const
  75138. {
  75139. if (recursionCounter > 150)
  75140. {
  75141. jassertfalse
  75142. throw RelativeCoordinateHelpers::RecursionException();
  75143. }
  75144. const double pos1 = resolveAnchor (anchor1, nameFinder, recursionCounter);
  75145. return isProportional() ? pos1 + (resolveAnchor (anchor2, nameFinder, recursionCounter) - pos1) * value
  75146. : pos1 + value;
  75147. }
  75148. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder) const
  75149. {
  75150. try
  75151. {
  75152. return resolve (nameFinder, 0);
  75153. }
  75154. catch (RelativeCoordinateHelpers::RecursionException&)
  75155. {}
  75156. return 0.0;
  75157. }
  75158. bool RelativeCoordinate::isRecursive (const NamedCoordinateFinder* nameFinder) const
  75159. {
  75160. try
  75161. {
  75162. (void) resolve (nameFinder, 0);
  75163. }
  75164. catch (RelativeCoordinateHelpers::RecursionException&)
  75165. {
  75166. return true;
  75167. }
  75168. return false;
  75169. }
  75170. void RelativeCoordinate::moveToAbsolute (double newPos, const NamedCoordinateFinder* nameFinder)
  75171. {
  75172. try
  75173. {
  75174. const double pos1 = resolveAnchor (anchor1, nameFinder, 0);
  75175. if (isProportional())
  75176. {
  75177. const double size = resolveAnchor (anchor2, nameFinder, 0) - pos1;
  75178. if (size != 0)
  75179. value = (newPos - pos1) / size;
  75180. }
  75181. else
  75182. {
  75183. value = newPos - pos1;
  75184. }
  75185. }
  75186. catch (RelativeCoordinateHelpers::RecursionException&)
  75187. {}
  75188. }
  75189. void RelativeCoordinate::toggleProportionality (const NamedCoordinateFinder* nameFinder, bool isHorizontal)
  75190. {
  75191. const double oldValue = resolve (nameFinder);
  75192. anchor1 = RelativeCoordinateHelpers::getOriginAnchorName (isHorizontal);
  75193. anchor2 = isProportional() ? String::empty
  75194. : RelativeCoordinateHelpers::getExtentAnchorName (isHorizontal);
  75195. moveToAbsolute (oldValue, nameFinder);
  75196. }
  75197. bool RelativeCoordinate::references (const String& coordName, const NamedCoordinateFinder* nameFinder) const
  75198. {
  75199. using namespace RelativeCoordinateHelpers;
  75200. if (isOrigin (anchor1) && ! isProportional())
  75201. return isOrigin (coordName);
  75202. return anchor1 == coordName
  75203. || anchor2 == coordName
  75204. || findCoordinate (anchor1, nameFinder).references (coordName, nameFinder)
  75205. || (isProportional() && findCoordinate (anchor2, nameFinder).references (coordName, nameFinder));
  75206. }
  75207. bool RelativeCoordinate::isDynamic() const
  75208. {
  75209. return anchor2.isNotEmpty() || ! RelativeCoordinateHelpers::isOrigin (anchor1);
  75210. }
  75211. const String RelativeCoordinate::toString() const
  75212. {
  75213. using namespace RelativeCoordinateHelpers;
  75214. if (isProportional())
  75215. {
  75216. const String percent (limitedAccuracyString (value * 100.0));
  75217. if (isOrigin (anchor1))
  75218. {
  75219. if (anchor2 == "parent.right" || anchor2 == "parent.bottom")
  75220. return percent + "%";
  75221. else
  75222. return percent + "% * " + anchor2;
  75223. }
  75224. else
  75225. return percent + "% * " + anchor1 + " -> " + anchor2;
  75226. }
  75227. else
  75228. {
  75229. if (isOrigin (anchor1))
  75230. return limitedAccuracyString (value);
  75231. else if (value > 0)
  75232. return anchor1 + " + " + limitedAccuracyString (value);
  75233. else if (value < 0)
  75234. return anchor1 + " - " + limitedAccuracyString (-value);
  75235. else
  75236. return anchor1;
  75237. }
  75238. }
  75239. const double RelativeCoordinate::getEditableNumber() const
  75240. {
  75241. return isProportional() ? value * 100.0 : value;
  75242. }
  75243. void RelativeCoordinate::setEditableNumber (const double newValue)
  75244. {
  75245. value = isProportional() ? newValue / 100.0 : newValue;
  75246. }
  75247. void RelativeCoordinate::changeAnchor1 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  75248. {
  75249. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  75250. const double oldValue = resolve (nameFinder);
  75251. anchor1 = newAnchorName;
  75252. moveToAbsolute (oldValue, nameFinder);
  75253. }
  75254. void RelativeCoordinate::changeAnchor2 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  75255. {
  75256. jassert (isProportional());
  75257. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  75258. const double oldValue = resolve (nameFinder);
  75259. anchor2 = newAnchorName;
  75260. moveToAbsolute (oldValue, nameFinder);
  75261. }
  75262. void RelativeCoordinate::renameAnchorIfUsed (const String& oldName, const String& newName, const NamedCoordinateFinder* nameFinder)
  75263. {
  75264. using namespace RelativeCoordinateHelpers;
  75265. jassert (oldName.isNotEmpty());
  75266. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  75267. if (newName.isEmpty())
  75268. {
  75269. if (getObjectName (anchor1) == oldName
  75270. || getObjectName (anchor2) == oldName)
  75271. {
  75272. value = resolve (nameFinder);
  75273. anchor1 = String::empty;
  75274. anchor2 = String::empty;
  75275. }
  75276. }
  75277. else
  75278. {
  75279. if (getObjectName (anchor1) == oldName)
  75280. anchor1 = newName + "." + getEdgeName (anchor1);
  75281. if (getObjectName (anchor2) == oldName)
  75282. anchor2 = newName + "." + getEdgeName (anchor2);
  75283. }
  75284. }
  75285. RelativePoint::RelativePoint()
  75286. : x (0, true), y (0, false)
  75287. {
  75288. }
  75289. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  75290. : x (absolutePoint.getX(), true), y (absolutePoint.getY(), false)
  75291. {
  75292. }
  75293. RelativePoint::RelativePoint (const float x_, const float y_)
  75294. : x (x_, true), y (y_, false)
  75295. {
  75296. }
  75297. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  75298. : x (x_), y (y_)
  75299. {
  75300. }
  75301. RelativePoint::RelativePoint (const String& s)
  75302. {
  75303. int i = 0;
  75304. x = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75305. RelativeCoordinateHelpers::skipComma (s, i);
  75306. y = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75307. }
  75308. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  75309. {
  75310. return x == other.x && y == other.y;
  75311. }
  75312. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  75313. {
  75314. return ! operator== (other);
  75315. }
  75316. const Point<float> RelativePoint::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  75317. {
  75318. return Point<float> ((float) x.resolve (nameFinder),
  75319. (float) y.resolve (nameFinder));
  75320. }
  75321. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75322. {
  75323. x.moveToAbsolute (newPos.getX(), nameFinder);
  75324. y.moveToAbsolute (newPos.getY(), nameFinder);
  75325. }
  75326. const String RelativePoint::toString() const
  75327. {
  75328. return x.toString() + ", " + y.toString();
  75329. }
  75330. void RelativePoint::renameAnchorIfUsed (const String& oldName, const String& newName, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75331. {
  75332. x.renameAnchorIfUsed (oldName, newName, nameFinder);
  75333. y.renameAnchorIfUsed (oldName, newName, nameFinder);
  75334. }
  75335. bool RelativePoint::isDynamic() const
  75336. {
  75337. return x.isDynamic() || y.isDynamic();
  75338. }
  75339. RelativeRectangle::RelativeRectangle()
  75340. {
  75341. }
  75342. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  75343. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  75344. : left (left_), right (right_), top (top_), bottom (bottom_)
  75345. {
  75346. }
  75347. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  75348. : left (rect.getX(), true),
  75349. right (rect.getWidth(), componentName + "." + RelativeCoordinate::Strings::left),
  75350. top (rect.getY(), false),
  75351. bottom (rect.getHeight(), componentName + "." + RelativeCoordinate::Strings::top)
  75352. {
  75353. }
  75354. RelativeRectangle::RelativeRectangle (const String& s)
  75355. {
  75356. int i = 0;
  75357. left = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75358. RelativeCoordinateHelpers::skipComma (s, i);
  75359. top = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75360. RelativeCoordinateHelpers::skipComma (s, i);
  75361. right = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75362. RelativeCoordinateHelpers::skipComma (s, i);
  75363. bottom = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75364. }
  75365. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  75366. {
  75367. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  75368. }
  75369. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  75370. {
  75371. return ! operator== (other);
  75372. }
  75373. const Rectangle<float> RelativeRectangle::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  75374. {
  75375. const double l = left.resolve (nameFinder);
  75376. const double r = right.resolve (nameFinder);
  75377. const double t = top.resolve (nameFinder);
  75378. const double b = bottom.resolve (nameFinder);
  75379. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  75380. }
  75381. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75382. {
  75383. left.moveToAbsolute (newPos.getX(), nameFinder);
  75384. right.moveToAbsolute (newPos.getRight(), nameFinder);
  75385. top.moveToAbsolute (newPos.getY(), nameFinder);
  75386. bottom.moveToAbsolute (newPos.getBottom(), nameFinder);
  75387. }
  75388. const String RelativeRectangle::toString() const
  75389. {
  75390. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  75391. }
  75392. void RelativeRectangle::renameAnchorIfUsed (const String& oldName, const String& newName,
  75393. const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75394. {
  75395. left.renameAnchorIfUsed (oldName, newName, nameFinder);
  75396. right.renameAnchorIfUsed (oldName, newName, nameFinder);
  75397. top.renameAnchorIfUsed (oldName, newName, nameFinder);
  75398. bottom.renameAnchorIfUsed (oldName, newName, nameFinder);
  75399. }
  75400. RelativePointPath::RelativePointPath()
  75401. : usesNonZeroWinding (true),
  75402. containsDynamicPoints (false)
  75403. {
  75404. }
  75405. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  75406. : usesNonZeroWinding (true),
  75407. containsDynamicPoints (false)
  75408. {
  75409. ValueTree state (DrawablePath::valueTreeType);
  75410. other.writeTo (state, 0);
  75411. parse (state);
  75412. }
  75413. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  75414. : usesNonZeroWinding (true),
  75415. containsDynamicPoints (false)
  75416. {
  75417. parse (drawable);
  75418. }
  75419. RelativePointPath::RelativePointPath (const Path& path)
  75420. {
  75421. usesNonZeroWinding = path.isUsingNonZeroWinding();
  75422. Path::Iterator i (path);
  75423. while (i.next())
  75424. {
  75425. switch (i.elementType)
  75426. {
  75427. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  75428. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  75429. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  75430. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  75431. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  75432. default: jassertfalse; break;
  75433. }
  75434. }
  75435. }
  75436. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  75437. {
  75438. DrawablePath::ValueTreeWrapper wrapper (state);
  75439. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  75440. ValueTree pathTree (wrapper.getPathState());
  75441. pathTree.removeAllChildren (undoManager);
  75442. for (int i = 0; i < elements.size(); ++i)
  75443. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  75444. }
  75445. void RelativePointPath::parse (const ValueTree& state)
  75446. {
  75447. DrawablePath::ValueTreeWrapper wrapper (state);
  75448. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  75449. RelativePoint points[3];
  75450. const ValueTree pathTree (wrapper.getPathState());
  75451. const int num = pathTree.getNumChildren();
  75452. for (int i = 0; i < num; ++i)
  75453. {
  75454. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  75455. const int numCps = e.getNumControlPoints();
  75456. for (int j = 0; j < numCps; ++j)
  75457. {
  75458. points[j] = e.getControlPoint (j);
  75459. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  75460. }
  75461. const Identifier type (e.getType());
  75462. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  75463. elements.add (new StartSubPath (points[0]));
  75464. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  75465. elements.add (new CloseSubPath());
  75466. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  75467. elements.add (new LineTo (points[0]));
  75468. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  75469. elements.add (new QuadraticTo (points[0], points[1]));
  75470. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  75471. elements.add (new CubicTo (points[0], points[1], points[2]));
  75472. else
  75473. jassertfalse;
  75474. }
  75475. }
  75476. RelativePointPath::~RelativePointPath()
  75477. {
  75478. }
  75479. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  75480. {
  75481. elements.swapWithArray (other.elements);
  75482. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  75483. }
  75484. void RelativePointPath::createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder)
  75485. {
  75486. for (int i = 0; i < elements.size(); ++i)
  75487. elements.getUnchecked(i)->addToPath (path, coordFinder);
  75488. }
  75489. bool RelativePointPath::containsAnyDynamicPoints() const
  75490. {
  75491. return containsDynamicPoints;
  75492. }
  75493. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  75494. {
  75495. }
  75496. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  75497. : ElementBase (startSubPathElement), startPos (pos)
  75498. {
  75499. }
  75500. const ValueTree RelativePointPath::StartSubPath::createTree() const
  75501. {
  75502. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  75503. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  75504. return v;
  75505. }
  75506. void RelativePointPath::StartSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75507. {
  75508. path.startNewSubPath (startPos.resolve (coordFinder));
  75509. }
  75510. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  75511. {
  75512. numPoints = 1;
  75513. return &startPos;
  75514. }
  75515. RelativePointPath::CloseSubPath::CloseSubPath()
  75516. : ElementBase (closeSubPathElement)
  75517. {
  75518. }
  75519. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  75520. {
  75521. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  75522. }
  75523. void RelativePointPath::CloseSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder*) const
  75524. {
  75525. path.closeSubPath();
  75526. }
  75527. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  75528. {
  75529. numPoints = 0;
  75530. return 0;
  75531. }
  75532. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  75533. : ElementBase (lineToElement), endPoint (endPoint_)
  75534. {
  75535. }
  75536. const ValueTree RelativePointPath::LineTo::createTree() const
  75537. {
  75538. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  75539. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  75540. return v;
  75541. }
  75542. void RelativePointPath::LineTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75543. {
  75544. path.lineTo (endPoint.resolve (coordFinder));
  75545. }
  75546. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  75547. {
  75548. numPoints = 1;
  75549. return &endPoint;
  75550. }
  75551. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  75552. : ElementBase (quadraticToElement)
  75553. {
  75554. controlPoints[0] = controlPoint;
  75555. controlPoints[1] = endPoint;
  75556. }
  75557. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  75558. {
  75559. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  75560. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  75561. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  75562. return v;
  75563. }
  75564. void RelativePointPath::QuadraticTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75565. {
  75566. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  75567. controlPoints[1].resolve (coordFinder));
  75568. }
  75569. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  75570. {
  75571. numPoints = 2;
  75572. return controlPoints;
  75573. }
  75574. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  75575. : ElementBase (cubicToElement)
  75576. {
  75577. controlPoints[0] = controlPoint1;
  75578. controlPoints[1] = controlPoint2;
  75579. controlPoints[2] = endPoint;
  75580. }
  75581. const ValueTree RelativePointPath::CubicTo::createTree() const
  75582. {
  75583. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  75584. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  75585. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  75586. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  75587. return v;
  75588. }
  75589. void RelativePointPath::CubicTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75590. {
  75591. path.cubicTo (controlPoints[0].resolve (coordFinder),
  75592. controlPoints[1].resolve (coordFinder),
  75593. controlPoints[2].resolve (coordFinder));
  75594. }
  75595. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  75596. {
  75597. numPoints = 3;
  75598. return controlPoints;
  75599. }
  75600. RelativeParallelogram::RelativeParallelogram()
  75601. {
  75602. }
  75603. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  75604. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  75605. {
  75606. }
  75607. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  75608. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  75609. {
  75610. }
  75611. RelativeParallelogram::~RelativeParallelogram()
  75612. {
  75613. }
  75614. void RelativeParallelogram::resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75615. {
  75616. points[0] = topLeft.resolve (coordFinder);
  75617. points[1] = topRight.resolve (coordFinder);
  75618. points[2] = bottomLeft.resolve (coordFinder);
  75619. }
  75620. void RelativeParallelogram::resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75621. {
  75622. resolveThreePoints (points, coordFinder);
  75623. points[3] = points[1] + (points[2] - points[0]);
  75624. }
  75625. const Rectangle<float> RelativeParallelogram::getBounds (RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75626. {
  75627. Point<float> points[4];
  75628. resolveFourCorners (points, coordFinder);
  75629. return Rectangle<float>::findAreaContainingPoints (points, 4);
  75630. }
  75631. void RelativeParallelogram::getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75632. {
  75633. Point<float> points[4];
  75634. resolveFourCorners (points, coordFinder);
  75635. path.startNewSubPath (points[0]);
  75636. path.lineTo (points[1]);
  75637. path.lineTo (points[3]);
  75638. path.lineTo (points[2]);
  75639. path.closeSubPath();
  75640. }
  75641. const AffineTransform RelativeParallelogram::resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* const coordFinder)
  75642. {
  75643. Point<float> corners[3];
  75644. resolveThreePoints (corners, coordFinder);
  75645. const Line<float> top (corners[0], corners[1]);
  75646. const Line<float> left (corners[0], corners[2]);
  75647. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  75648. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  75649. topRight.moveToAbsolute (newTopRight, coordFinder);
  75650. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  75651. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  75652. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  75653. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  75654. }
  75655. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  75656. {
  75657. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  75658. }
  75659. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  75660. {
  75661. return ! operator== (other);
  75662. }
  75663. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  75664. {
  75665. const Point<float> tr (corners[1] - corners[0]);
  75666. const Point<float> bl (corners[2] - corners[0]);
  75667. target -= corners[0];
  75668. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  75669. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  75670. }
  75671. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  75672. {
  75673. return corners[0]
  75674. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  75675. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  75676. }
  75677. END_JUCE_NAMESPACE
  75678. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  75679. /*** Start of inlined file: juce_Image.cpp ***/
  75680. BEGIN_JUCE_NAMESPACE
  75681. static const int fullAlphaThreshold = 253;
  75682. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  75683. : format (format_), width (width_), height (height_)
  75684. {
  75685. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  75686. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  75687. }
  75688. Image::SharedImage::~SharedImage()
  75689. {
  75690. }
  75691. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  75692. {
  75693. return imageData + lineStride * y + pixelStride * x;
  75694. }
  75695. class SoftwareSharedImage : public Image::SharedImage
  75696. {
  75697. public:
  75698. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  75699. : Image::SharedImage (format_, width_, height_)
  75700. {
  75701. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  75702. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  75703. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  75704. imageData = imageDataAllocated;
  75705. }
  75706. ~SoftwareSharedImage()
  75707. {
  75708. }
  75709. Image::ImageType getType() const
  75710. {
  75711. return Image::SoftwareImage;
  75712. }
  75713. LowLevelGraphicsContext* createLowLevelContext()
  75714. {
  75715. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  75716. }
  75717. SharedImage* clone()
  75718. {
  75719. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  75720. memcpy (s->imageData, imageData, lineStride * height);
  75721. return s;
  75722. }
  75723. private:
  75724. HeapBlock<uint8> imageDataAllocated;
  75725. };
  75726. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  75727. {
  75728. return new SoftwareSharedImage (format, width, height, clearImage);
  75729. }
  75730. Image::Image()
  75731. {
  75732. }
  75733. Image::Image (SharedImage* const instance)
  75734. : image (instance)
  75735. {
  75736. }
  75737. Image::Image (const PixelFormat format,
  75738. const int width, const int height,
  75739. const bool clearImage, const ImageType type)
  75740. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  75741. : new SoftwareSharedImage (format, width, height, clearImage))
  75742. {
  75743. }
  75744. Image::Image (const Image& other)
  75745. : image (other.image)
  75746. {
  75747. }
  75748. Image& Image::operator= (const Image& other)
  75749. {
  75750. image = other.image;
  75751. return *this;
  75752. }
  75753. Image::~Image()
  75754. {
  75755. }
  75756. LowLevelGraphicsContext* Image::createLowLevelContext() const
  75757. {
  75758. return image == 0 ? 0 : image->createLowLevelContext();
  75759. }
  75760. void Image::duplicateIfShared()
  75761. {
  75762. if (image != 0 && image->getReferenceCount() > 1)
  75763. image = image->clone();
  75764. }
  75765. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  75766. {
  75767. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  75768. return *this;
  75769. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  75770. Graphics g (newImage);
  75771. g.setImageResamplingQuality (quality);
  75772. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  75773. return newImage;
  75774. }
  75775. const Image Image::convertedToFormat (PixelFormat newFormat) const
  75776. {
  75777. if (image == 0 || newFormat == image->format)
  75778. return *this;
  75779. Image newImage (newFormat, image->width, image->height, false, image->getType());
  75780. if (newFormat == SingleChannel)
  75781. {
  75782. if (! hasAlphaChannel())
  75783. {
  75784. newImage.clear (getBounds(), Colours::black);
  75785. }
  75786. else
  75787. {
  75788. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  75789. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  75790. for (int y = 0; y < image->height; ++y)
  75791. {
  75792. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  75793. uint8* dst = destData.getLinePointer (y);
  75794. for (int x = image->width; --x >= 0;)
  75795. {
  75796. *dst++ = src->getAlpha();
  75797. ++src;
  75798. }
  75799. }
  75800. }
  75801. }
  75802. else
  75803. {
  75804. if (hasAlphaChannel())
  75805. newImage.clear (getBounds());
  75806. Graphics g (newImage);
  75807. g.drawImageAt (*this, 0, 0);
  75808. }
  75809. return newImage;
  75810. }
  75811. const var Image::getTag() const
  75812. {
  75813. return image == 0 ? var::null : image->userTag;
  75814. }
  75815. void Image::setTag (const var& newTag)
  75816. {
  75817. if (image != 0)
  75818. image->userTag = newTag;
  75819. }
  75820. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  75821. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  75822. pixelFormat (image.getFormat()),
  75823. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  75824. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  75825. width (w),
  75826. height (h)
  75827. {
  75828. jassert (data != 0);
  75829. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  75830. }
  75831. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  75832. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  75833. pixelFormat (image.getFormat()),
  75834. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  75835. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  75836. width (w),
  75837. height (h)
  75838. {
  75839. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  75840. }
  75841. Image::BitmapData::~BitmapData()
  75842. {
  75843. }
  75844. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  75845. {
  75846. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  75847. const uint8* const pixel = getPixelPointer (x, y);
  75848. switch (pixelFormat)
  75849. {
  75850. case Image::ARGB:
  75851. {
  75852. PixelARGB p (*(const PixelARGB*) pixel);
  75853. p.unpremultiply();
  75854. return Colour (p.getARGB());
  75855. }
  75856. case Image::RGB:
  75857. return Colour (((const PixelRGB*) pixel)->getARGB());
  75858. case Image::SingleChannel:
  75859. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  75860. default:
  75861. jassertfalse;
  75862. break;
  75863. }
  75864. return Colour();
  75865. }
  75866. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  75867. {
  75868. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  75869. uint8* const pixel = getPixelPointer (x, y);
  75870. const PixelARGB col (colour.getPixelARGB());
  75871. switch (pixelFormat)
  75872. {
  75873. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  75874. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  75875. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  75876. default: jassertfalse; break;
  75877. }
  75878. }
  75879. void Image::setPixelData (int x, int y, int w, int h,
  75880. const uint8* const sourcePixelData, const int sourceLineStride)
  75881. {
  75882. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  75883. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  75884. {
  75885. const BitmapData dest (*this, x, y, w, h, true);
  75886. for (int i = 0; i < h; ++i)
  75887. {
  75888. memcpy (dest.getLinePointer(i),
  75889. sourcePixelData + sourceLineStride * i,
  75890. w * dest.pixelStride);
  75891. }
  75892. }
  75893. }
  75894. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  75895. {
  75896. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  75897. if (! clipped.isEmpty())
  75898. {
  75899. const PixelARGB col (colourToClearTo.getPixelARGB());
  75900. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  75901. uint8* dest = destData.data;
  75902. int dh = clipped.getHeight();
  75903. while (--dh >= 0)
  75904. {
  75905. uint8* line = dest;
  75906. dest += destData.lineStride;
  75907. if (isARGB())
  75908. {
  75909. for (int x = clipped.getWidth(); --x >= 0;)
  75910. {
  75911. ((PixelARGB*) line)->set (col);
  75912. line += destData.pixelStride;
  75913. }
  75914. }
  75915. else if (isRGB())
  75916. {
  75917. for (int x = clipped.getWidth(); --x >= 0;)
  75918. {
  75919. ((PixelRGB*) line)->set (col);
  75920. line += destData.pixelStride;
  75921. }
  75922. }
  75923. else
  75924. {
  75925. for (int x = clipped.getWidth(); --x >= 0;)
  75926. {
  75927. *line = col.getAlpha();
  75928. line += destData.pixelStride;
  75929. }
  75930. }
  75931. }
  75932. }
  75933. }
  75934. const Colour Image::getPixelAt (const int x, const int y) const
  75935. {
  75936. if (((unsigned int) x) < (unsigned int) getWidth()
  75937. && ((unsigned int) y) < (unsigned int) getHeight())
  75938. {
  75939. const BitmapData srcData (*this, x, y, 1, 1);
  75940. return srcData.getPixelColour (0, 0);
  75941. }
  75942. return Colour();
  75943. }
  75944. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  75945. {
  75946. if (((unsigned int) x) < (unsigned int) getWidth()
  75947. && ((unsigned int) y) < (unsigned int) getHeight())
  75948. {
  75949. const BitmapData destData (*this, x, y, 1, 1, true);
  75950. destData.setPixelColour (0, 0, colour);
  75951. }
  75952. }
  75953. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  75954. {
  75955. if (((unsigned int) x) < (unsigned int) getWidth()
  75956. && ((unsigned int) y) < (unsigned int) getHeight()
  75957. && hasAlphaChannel())
  75958. {
  75959. const BitmapData destData (*this, x, y, 1, 1, true);
  75960. if (isARGB())
  75961. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  75962. else
  75963. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  75964. }
  75965. }
  75966. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  75967. {
  75968. if (hasAlphaChannel())
  75969. {
  75970. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  75971. if (isARGB())
  75972. {
  75973. for (int y = 0; y < destData.height; ++y)
  75974. {
  75975. uint8* p = destData.getLinePointer (y);
  75976. for (int x = 0; x < destData.width; ++x)
  75977. {
  75978. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  75979. p += destData.pixelStride;
  75980. }
  75981. }
  75982. }
  75983. else
  75984. {
  75985. for (int y = 0; y < destData.height; ++y)
  75986. {
  75987. uint8* p = destData.getLinePointer (y);
  75988. for (int x = 0; x < destData.width; ++x)
  75989. {
  75990. *p = (uint8) (*p * amountToMultiplyBy);
  75991. p += destData.pixelStride;
  75992. }
  75993. }
  75994. }
  75995. }
  75996. else
  75997. {
  75998. jassertfalse; // can't do this without an alpha-channel!
  75999. }
  76000. }
  76001. void Image::desaturate()
  76002. {
  76003. if (isARGB() || isRGB())
  76004. {
  76005. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76006. if (isARGB())
  76007. {
  76008. for (int y = 0; y < destData.height; ++y)
  76009. {
  76010. uint8* p = destData.getLinePointer (y);
  76011. for (int x = 0; x < destData.width; ++x)
  76012. {
  76013. ((PixelARGB*) p)->desaturate();
  76014. p += destData.pixelStride;
  76015. }
  76016. }
  76017. }
  76018. else
  76019. {
  76020. for (int y = 0; y < destData.height; ++y)
  76021. {
  76022. uint8* p = destData.getLinePointer (y);
  76023. for (int x = 0; x < destData.width; ++x)
  76024. {
  76025. ((PixelRGB*) p)->desaturate();
  76026. p += destData.pixelStride;
  76027. }
  76028. }
  76029. }
  76030. }
  76031. }
  76032. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76033. {
  76034. if (hasAlphaChannel())
  76035. {
  76036. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76037. SparseSet<int> pixelsOnRow;
  76038. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76039. for (int y = 0; y < srcData.height; ++y)
  76040. {
  76041. pixelsOnRow.clear();
  76042. const uint8* lineData = srcData.getLinePointer (y);
  76043. if (isARGB())
  76044. {
  76045. for (int x = 0; x < srcData.width; ++x)
  76046. {
  76047. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76048. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76049. lineData += srcData.pixelStride;
  76050. }
  76051. }
  76052. else
  76053. {
  76054. for (int x = 0; x < srcData.width; ++x)
  76055. {
  76056. if (*lineData >= threshold)
  76057. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76058. lineData += srcData.pixelStride;
  76059. }
  76060. }
  76061. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76062. {
  76063. const Range<int> range (pixelsOnRow.getRange (i));
  76064. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76065. }
  76066. result.consolidate();
  76067. }
  76068. }
  76069. else
  76070. {
  76071. result.add (0, 0, getWidth(), getHeight());
  76072. }
  76073. }
  76074. void Image::moveImageSection (int dx, int dy,
  76075. int sx, int sy,
  76076. int w, int h)
  76077. {
  76078. if (dx < 0)
  76079. {
  76080. w += dx;
  76081. sx -= dx;
  76082. dx = 0;
  76083. }
  76084. if (dy < 0)
  76085. {
  76086. h += dy;
  76087. sy -= dy;
  76088. dy = 0;
  76089. }
  76090. if (sx < 0)
  76091. {
  76092. w += sx;
  76093. dx -= sx;
  76094. sx = 0;
  76095. }
  76096. if (sy < 0)
  76097. {
  76098. h += sy;
  76099. dy -= sy;
  76100. sy = 0;
  76101. }
  76102. const int minX = jmin (dx, sx);
  76103. const int minY = jmin (dy, sy);
  76104. w = jmin (w, getWidth() - jmax (sx, dx));
  76105. h = jmin (h, getHeight() - jmax (sy, dy));
  76106. if (w > 0 && h > 0)
  76107. {
  76108. const int maxX = jmax (dx, sx) + w;
  76109. const int maxY = jmax (dy, sy) + h;
  76110. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  76111. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  76112. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  76113. const int lineSize = destData.pixelStride * w;
  76114. if (dy > sy)
  76115. {
  76116. while (--h >= 0)
  76117. {
  76118. const int offset = h * destData.lineStride;
  76119. memmove (dst + offset, src + offset, lineSize);
  76120. }
  76121. }
  76122. else if (dst != src)
  76123. {
  76124. while (--h >= 0)
  76125. {
  76126. memmove (dst, src, lineSize);
  76127. dst += destData.lineStride;
  76128. src += destData.lineStride;
  76129. }
  76130. }
  76131. }
  76132. }
  76133. END_JUCE_NAMESPACE
  76134. /*** End of inlined file: juce_Image.cpp ***/
  76135. /*** Start of inlined file: juce_ImageCache.cpp ***/
  76136. BEGIN_JUCE_NAMESPACE
  76137. class ImageCache::Pimpl : public Timer,
  76138. public DeletedAtShutdown
  76139. {
  76140. public:
  76141. Pimpl()
  76142. : cacheTimeout (5000)
  76143. {
  76144. }
  76145. ~Pimpl()
  76146. {
  76147. clearSingletonInstance();
  76148. }
  76149. const Image getFromHashCode (const int64 hashCode)
  76150. {
  76151. const ScopedLock sl (lock);
  76152. for (int i = images.size(); --i >= 0;)
  76153. {
  76154. Item* const item = images.getUnchecked(i);
  76155. if (item->hashCode == hashCode)
  76156. return item->image;
  76157. }
  76158. return Image();
  76159. }
  76160. void addImageToCache (const Image& image, const int64 hashCode)
  76161. {
  76162. if (image.isValid())
  76163. {
  76164. if (! isTimerRunning())
  76165. startTimer (2000);
  76166. Item* const item = new Item();
  76167. item->hashCode = hashCode;
  76168. item->image = image;
  76169. item->lastUseTime = Time::getApproximateMillisecondCounter();
  76170. const ScopedLock sl (lock);
  76171. images.add (item);
  76172. }
  76173. }
  76174. void timerCallback()
  76175. {
  76176. const uint32 now = Time::getApproximateMillisecondCounter();
  76177. const ScopedLock sl (lock);
  76178. for (int i = images.size(); --i >= 0;)
  76179. {
  76180. Item* const item = images.getUnchecked(i);
  76181. if (item->image.getReferenceCount() <= 1)
  76182. {
  76183. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  76184. images.remove (i);
  76185. }
  76186. else
  76187. {
  76188. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  76189. }
  76190. }
  76191. if (images.size() == 0)
  76192. stopTimer();
  76193. }
  76194. struct Item
  76195. {
  76196. Image image;
  76197. int64 hashCode;
  76198. uint32 lastUseTime;
  76199. };
  76200. int cacheTimeout;
  76201. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  76202. private:
  76203. OwnedArray<Item> images;
  76204. CriticalSection lock;
  76205. Pimpl (const Pimpl&);
  76206. Pimpl& operator= (const Pimpl&);
  76207. };
  76208. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  76209. const Image ImageCache::getFromHashCode (const int64 hashCode)
  76210. {
  76211. if (Pimpl::getInstanceWithoutCreating() != 0)
  76212. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  76213. return Image();
  76214. }
  76215. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  76216. {
  76217. Pimpl::getInstance()->addImageToCache (image, hashCode);
  76218. }
  76219. const Image ImageCache::getFromFile (const File& file)
  76220. {
  76221. const int64 hashCode = file.hashCode64();
  76222. Image image (getFromHashCode (hashCode));
  76223. if (image.isNull())
  76224. {
  76225. image = ImageFileFormat::loadFrom (file);
  76226. addImageToCache (image, hashCode);
  76227. }
  76228. return image;
  76229. }
  76230. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  76231. {
  76232. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  76233. Image image (getFromHashCode (hashCode));
  76234. if (image.isNull())
  76235. {
  76236. image = ImageFileFormat::loadFrom (imageData, dataSize);
  76237. addImageToCache (image, hashCode);
  76238. }
  76239. return image;
  76240. }
  76241. void ImageCache::setCacheTimeout (const int millisecs)
  76242. {
  76243. Pimpl::getInstance()->cacheTimeout = millisecs;
  76244. }
  76245. END_JUCE_NAMESPACE
  76246. /*** End of inlined file: juce_ImageCache.cpp ***/
  76247. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76248. BEGIN_JUCE_NAMESPACE
  76249. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  76250. : values (size_ * size_),
  76251. size (size_)
  76252. {
  76253. clear();
  76254. }
  76255. ImageConvolutionKernel::~ImageConvolutionKernel()
  76256. {
  76257. }
  76258. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  76259. {
  76260. if (((unsigned int) x) < (unsigned int) size
  76261. && ((unsigned int) y) < (unsigned int) size)
  76262. {
  76263. return values [x + y * size];
  76264. }
  76265. else
  76266. {
  76267. jassertfalse;
  76268. return 0;
  76269. }
  76270. }
  76271. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  76272. {
  76273. if (((unsigned int) x) < (unsigned int) size
  76274. && ((unsigned int) y) < (unsigned int) size)
  76275. {
  76276. values [x + y * size] = value;
  76277. }
  76278. else
  76279. {
  76280. jassertfalse;
  76281. }
  76282. }
  76283. void ImageConvolutionKernel::clear()
  76284. {
  76285. for (int i = size * size; --i >= 0;)
  76286. values[i] = 0;
  76287. }
  76288. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  76289. {
  76290. double currentTotal = 0.0;
  76291. for (int i = size * size; --i >= 0;)
  76292. currentTotal += values[i];
  76293. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  76294. }
  76295. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  76296. {
  76297. for (int i = size * size; --i >= 0;)
  76298. values[i] *= multiplier;
  76299. }
  76300. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  76301. {
  76302. const double radiusFactor = -1.0 / (radius * radius * 2);
  76303. const int centre = size >> 1;
  76304. for (int y = size; --y >= 0;)
  76305. {
  76306. for (int x = size; --x >= 0;)
  76307. {
  76308. const int cx = x - centre;
  76309. const int cy = y - centre;
  76310. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  76311. }
  76312. }
  76313. setOverallSum (1.0f);
  76314. }
  76315. void ImageConvolutionKernel::applyToImage (Image& destImage,
  76316. const Image& sourceImage,
  76317. const Rectangle<int>& destinationArea) const
  76318. {
  76319. if (sourceImage == destImage)
  76320. {
  76321. destImage.duplicateIfShared();
  76322. }
  76323. else
  76324. {
  76325. if (sourceImage.getWidth() != destImage.getWidth()
  76326. || sourceImage.getHeight() != destImage.getHeight()
  76327. || sourceImage.getFormat() != destImage.getFormat())
  76328. {
  76329. jassertfalse;
  76330. return;
  76331. }
  76332. }
  76333. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  76334. if (area.isEmpty())
  76335. return;
  76336. const int right = area.getRight();
  76337. const int bottom = area.getBottom();
  76338. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  76339. uint8* line = destData.data;
  76340. const Image::BitmapData srcData (sourceImage, 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  76341. if (destData.pixelStride == 4)
  76342. {
  76343. for (int y = area.getY(); y < bottom; ++y)
  76344. {
  76345. uint8* dest = line;
  76346. line += destData.lineStride;
  76347. for (int x = area.getX(); x < right; ++x)
  76348. {
  76349. float c1 = 0;
  76350. float c2 = 0;
  76351. float c3 = 0;
  76352. float c4 = 0;
  76353. for (int yy = 0; yy < size; ++yy)
  76354. {
  76355. const int sy = y + yy - (size >> 1);
  76356. if (sy >= srcData.height)
  76357. break;
  76358. if (sy >= 0)
  76359. {
  76360. int sx = x - (size >> 1);
  76361. const uint8* src = srcData.getPixelPointer (sx, sy);
  76362. for (int xx = 0; xx < size; ++xx)
  76363. {
  76364. if (sx >= srcData.width)
  76365. break;
  76366. if (sx >= 0)
  76367. {
  76368. const float kernelMult = values [xx + yy * size];
  76369. c1 += kernelMult * *src++;
  76370. c2 += kernelMult * *src++;
  76371. c3 += kernelMult * *src++;
  76372. c4 += kernelMult * *src++;
  76373. }
  76374. else
  76375. {
  76376. src += 4;
  76377. }
  76378. ++sx;
  76379. }
  76380. }
  76381. }
  76382. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  76383. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  76384. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  76385. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  76386. }
  76387. }
  76388. }
  76389. else if (destData.pixelStride == 3)
  76390. {
  76391. for (int y = area.getY(); y < bottom; ++y)
  76392. {
  76393. uint8* dest = line;
  76394. line += destData.lineStride;
  76395. for (int x = area.getX(); x < right; ++x)
  76396. {
  76397. float c1 = 0;
  76398. float c2 = 0;
  76399. float c3 = 0;
  76400. for (int yy = 0; yy < size; ++yy)
  76401. {
  76402. const int sy = y + yy - (size >> 1);
  76403. if (sy >= srcData.height)
  76404. break;
  76405. if (sy >= 0)
  76406. {
  76407. int sx = x - (size >> 1);
  76408. const uint8* src = srcData.getPixelPointer (sx, sy);
  76409. for (int xx = 0; xx < size; ++xx)
  76410. {
  76411. if (sx >= srcData.width)
  76412. break;
  76413. if (sx >= 0)
  76414. {
  76415. const float kernelMult = values [xx + yy * size];
  76416. c1 += kernelMult * *src++;
  76417. c2 += kernelMult * *src++;
  76418. c3 += kernelMult * *src++;
  76419. }
  76420. else
  76421. {
  76422. src += 3;
  76423. }
  76424. ++sx;
  76425. }
  76426. }
  76427. }
  76428. *dest++ = (uint8) roundToInt (c1);
  76429. *dest++ = (uint8) roundToInt (c2);
  76430. *dest++ = (uint8) roundToInt (c3);
  76431. }
  76432. }
  76433. }
  76434. }
  76435. END_JUCE_NAMESPACE
  76436. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76437. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  76438. BEGIN_JUCE_NAMESPACE
  76439. /*** Start of inlined file: juce_GIFLoader.h ***/
  76440. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  76441. #define __JUCE_GIFLOADER_JUCEHEADER__
  76442. #ifndef DOXYGEN
  76443. /**
  76444. Used internally by ImageFileFormat - don't use this class directly in your
  76445. application.
  76446. @see ImageFileFormat
  76447. */
  76448. class GIFLoader
  76449. {
  76450. public:
  76451. GIFLoader (InputStream& in);
  76452. ~GIFLoader();
  76453. const Image& getImage() const { return image; }
  76454. private:
  76455. Image image;
  76456. InputStream& input;
  76457. uint8 buffer [300];
  76458. uint8 palette [256][4];
  76459. bool dataBlockIsZero, fresh, finished;
  76460. int currentBit, lastBit, lastByteIndex;
  76461. int codeSize, setCodeSize;
  76462. int maxCode, maxCodeSize;
  76463. int firstcode, oldcode;
  76464. int clearCode, end_code;
  76465. enum { maxGifCode = 1 << 12 };
  76466. int table [2] [maxGifCode];
  76467. int stack [2 * maxGifCode];
  76468. int *sp;
  76469. bool getSizeFromHeader (int& width, int& height);
  76470. bool readPalette (const int numCols);
  76471. int readDataBlock (unsigned char* dest);
  76472. int processExtension (int type, int& transparent);
  76473. int readLZWByte (bool initialise, int input_code_size);
  76474. int getCode (int code_size, bool initialise);
  76475. bool readImage (int width, int height, int interlace, int transparent);
  76476. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  76477. GIFLoader (const GIFLoader&);
  76478. GIFLoader& operator= (const GIFLoader&);
  76479. };
  76480. #endif // DOXYGEN
  76481. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  76482. /*** End of inlined file: juce_GIFLoader.h ***/
  76483. class GIFImageFormat : public ImageFileFormat
  76484. {
  76485. public:
  76486. GIFImageFormat() {}
  76487. ~GIFImageFormat() {}
  76488. const String getFormatName()
  76489. {
  76490. return "GIF";
  76491. }
  76492. bool canUnderstand (InputStream& in)
  76493. {
  76494. const int bytesNeeded = 4;
  76495. char header [bytesNeeded];
  76496. return (in.read (header, bytesNeeded) == bytesNeeded)
  76497. && header[0] == 'G'
  76498. && header[1] == 'I'
  76499. && header[2] == 'F';
  76500. }
  76501. const Image decodeImage (InputStream& in)
  76502. {
  76503. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  76504. return loader->getImage();
  76505. }
  76506. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  76507. {
  76508. return false;
  76509. }
  76510. };
  76511. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  76512. {
  76513. static PNGImageFormat png;
  76514. static JPEGImageFormat jpg;
  76515. static GIFImageFormat gif;
  76516. ImageFileFormat* formats[4];
  76517. int numFormats = 0;
  76518. formats [numFormats++] = &png;
  76519. formats [numFormats++] = &jpg;
  76520. formats [numFormats++] = &gif;
  76521. const int64 streamPos = input.getPosition();
  76522. for (int i = 0; i < numFormats; ++i)
  76523. {
  76524. const bool found = formats[i]->canUnderstand (input);
  76525. input.setPosition (streamPos);
  76526. if (found)
  76527. return formats[i];
  76528. }
  76529. return 0;
  76530. }
  76531. const Image ImageFileFormat::loadFrom (InputStream& input)
  76532. {
  76533. ImageFileFormat* const format = findImageFormatForStream (input);
  76534. if (format != 0)
  76535. return format->decodeImage (input);
  76536. return Image();
  76537. }
  76538. const Image ImageFileFormat::loadFrom (const File& file)
  76539. {
  76540. InputStream* const in = file.createInputStream();
  76541. if (in != 0)
  76542. {
  76543. BufferedInputStream b (in, 8192, true);
  76544. return loadFrom (b);
  76545. }
  76546. return Image();
  76547. }
  76548. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  76549. {
  76550. if (rawData != 0 && numBytes > 4)
  76551. {
  76552. MemoryInputStream stream (rawData, numBytes, false);
  76553. return loadFrom (stream);
  76554. }
  76555. return Image();
  76556. }
  76557. END_JUCE_NAMESPACE
  76558. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  76559. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  76560. BEGIN_JUCE_NAMESPACE
  76561. GIFLoader::GIFLoader (InputStream& in)
  76562. : image (0),
  76563. input (in),
  76564. dataBlockIsZero (false),
  76565. fresh (false),
  76566. finished (false)
  76567. {
  76568. currentBit = lastBit = lastByteIndex = 0;
  76569. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  76570. firstcode = oldcode = 0;
  76571. clearCode = end_code = 0;
  76572. int imageWidth, imageHeight;
  76573. int transparent = -1;
  76574. if (! getSizeFromHeader (imageWidth, imageHeight))
  76575. return;
  76576. if ((imageWidth <= 0) || (imageHeight <= 0))
  76577. return;
  76578. unsigned char buf [16];
  76579. if (in.read (buf, 3) != 3)
  76580. return;
  76581. int numColours = 2 << (buf[0] & 7);
  76582. if ((buf[0] & 0x80) != 0)
  76583. readPalette (numColours);
  76584. for (;;)
  76585. {
  76586. if (input.read (buf, 1) != 1)
  76587. break;
  76588. if (buf[0] == ';')
  76589. break;
  76590. if (buf[0] == '!')
  76591. {
  76592. if (input.read (buf, 1) != 1)
  76593. break;
  76594. if (processExtension (buf[0], transparent) < 0)
  76595. break;
  76596. continue;
  76597. }
  76598. if (buf[0] != ',')
  76599. continue;
  76600. if (input.read (buf, 9) != 9)
  76601. break;
  76602. imageWidth = makeWord (buf[4], buf[5]);
  76603. imageHeight = makeWord (buf[6], buf[7]);
  76604. numColours = 2 << (buf[8] & 7);
  76605. if ((buf[8] & 0x80) != 0)
  76606. if (! readPalette (numColours))
  76607. break;
  76608. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  76609. imageWidth, imageHeight, (transparent >= 0));
  76610. readImage (imageWidth, imageHeight,
  76611. (buf[8] & 0x40) != 0,
  76612. transparent);
  76613. break;
  76614. }
  76615. }
  76616. GIFLoader::~GIFLoader()
  76617. {
  76618. }
  76619. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  76620. {
  76621. char b[8];
  76622. if (input.read (b, 6) == 6)
  76623. {
  76624. if ((strncmp ("GIF87a", b, 6) == 0)
  76625. || (strncmp ("GIF89a", b, 6) == 0))
  76626. {
  76627. if (input.read (b, 4) == 4)
  76628. {
  76629. w = makeWord (b[0], b[1]);
  76630. h = makeWord (b[2], b[3]);
  76631. return true;
  76632. }
  76633. }
  76634. }
  76635. return false;
  76636. }
  76637. bool GIFLoader::readPalette (const int numCols)
  76638. {
  76639. unsigned char rgb[4];
  76640. for (int i = 0; i < numCols; ++i)
  76641. {
  76642. input.read (rgb, 3);
  76643. palette [i][0] = rgb[0];
  76644. palette [i][1] = rgb[1];
  76645. palette [i][2] = rgb[2];
  76646. palette [i][3] = 0xff;
  76647. }
  76648. return true;
  76649. }
  76650. int GIFLoader::readDataBlock (unsigned char* const dest)
  76651. {
  76652. unsigned char n;
  76653. if (input.read (&n, 1) == 1)
  76654. {
  76655. dataBlockIsZero = (n == 0);
  76656. if (dataBlockIsZero || (input.read (dest, n) == n))
  76657. return n;
  76658. }
  76659. return -1;
  76660. }
  76661. int GIFLoader::processExtension (const int type, int& transparent)
  76662. {
  76663. unsigned char b [300];
  76664. int n = 0;
  76665. if (type == 0xf9)
  76666. {
  76667. n = readDataBlock (b);
  76668. if (n < 0)
  76669. return 1;
  76670. if ((b[0] & 0x1) != 0)
  76671. transparent = b[3];
  76672. }
  76673. do
  76674. {
  76675. n = readDataBlock (b);
  76676. }
  76677. while (n > 0);
  76678. return n;
  76679. }
  76680. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  76681. {
  76682. if (initialise)
  76683. {
  76684. currentBit = 0;
  76685. lastBit = 0;
  76686. finished = false;
  76687. return 0;
  76688. }
  76689. if ((currentBit + codeSize_) >= lastBit)
  76690. {
  76691. if (finished)
  76692. return -1;
  76693. buffer[0] = buffer [lastByteIndex - 2];
  76694. buffer[1] = buffer [lastByteIndex - 1];
  76695. const int n = readDataBlock (&buffer[2]);
  76696. if (n == 0)
  76697. finished = true;
  76698. lastByteIndex = 2 + n;
  76699. currentBit = (currentBit - lastBit) + 16;
  76700. lastBit = (2 + n) * 8 ;
  76701. }
  76702. int result = 0;
  76703. int i = currentBit;
  76704. for (int j = 0; j < codeSize_; ++j)
  76705. {
  76706. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  76707. ++i;
  76708. }
  76709. currentBit += codeSize_;
  76710. return result;
  76711. }
  76712. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  76713. {
  76714. int code, incode, i;
  76715. if (initialise)
  76716. {
  76717. setCodeSize = inputCodeSize;
  76718. codeSize = setCodeSize + 1;
  76719. clearCode = 1 << setCodeSize;
  76720. end_code = clearCode + 1;
  76721. maxCodeSize = 2 * clearCode;
  76722. maxCode = clearCode + 2;
  76723. getCode (0, true);
  76724. fresh = true;
  76725. for (i = 0; i < clearCode; ++i)
  76726. {
  76727. table[0][i] = 0;
  76728. table[1][i] = i;
  76729. }
  76730. for (; i < maxGifCode; ++i)
  76731. {
  76732. table[0][i] = 0;
  76733. table[1][i] = 0;
  76734. }
  76735. sp = stack;
  76736. return 0;
  76737. }
  76738. else if (fresh)
  76739. {
  76740. fresh = false;
  76741. do
  76742. {
  76743. firstcode = oldcode
  76744. = getCode (codeSize, false);
  76745. }
  76746. while (firstcode == clearCode);
  76747. return firstcode;
  76748. }
  76749. if (sp > stack)
  76750. return *--sp;
  76751. while ((code = getCode (codeSize, false)) >= 0)
  76752. {
  76753. if (code == clearCode)
  76754. {
  76755. for (i = 0; i < clearCode; ++i)
  76756. {
  76757. table[0][i] = 0;
  76758. table[1][i] = i;
  76759. }
  76760. for (; i < maxGifCode; ++i)
  76761. {
  76762. table[0][i] = 0;
  76763. table[1][i] = 0;
  76764. }
  76765. codeSize = setCodeSize + 1;
  76766. maxCodeSize = 2 * clearCode;
  76767. maxCode = clearCode + 2;
  76768. sp = stack;
  76769. firstcode = oldcode = getCode (codeSize, false);
  76770. return firstcode;
  76771. }
  76772. else if (code == end_code)
  76773. {
  76774. if (dataBlockIsZero)
  76775. return -2;
  76776. unsigned char buf [260];
  76777. int n;
  76778. while ((n = readDataBlock (buf)) > 0)
  76779. {}
  76780. if (n != 0)
  76781. return -2;
  76782. }
  76783. incode = code;
  76784. if (code >= maxCode)
  76785. {
  76786. *sp++ = firstcode;
  76787. code = oldcode;
  76788. }
  76789. while (code >= clearCode)
  76790. {
  76791. *sp++ = table[1][code];
  76792. if (code == table[0][code])
  76793. return -2;
  76794. code = table[0][code];
  76795. }
  76796. *sp++ = firstcode = table[1][code];
  76797. if ((code = maxCode) < maxGifCode)
  76798. {
  76799. table[0][code] = oldcode;
  76800. table[1][code] = firstcode;
  76801. ++maxCode;
  76802. if ((maxCode >= maxCodeSize)
  76803. && (maxCodeSize < maxGifCode))
  76804. {
  76805. maxCodeSize <<= 1;
  76806. ++codeSize;
  76807. }
  76808. }
  76809. oldcode = incode;
  76810. if (sp > stack)
  76811. return *--sp;
  76812. }
  76813. return code;
  76814. }
  76815. bool GIFLoader::readImage (const int width, const int height,
  76816. const int interlace, const int transparent)
  76817. {
  76818. unsigned char c;
  76819. if (input.read (&c, 1) != 1
  76820. || readLZWByte (true, c) < 0)
  76821. return false;
  76822. if (transparent >= 0)
  76823. {
  76824. palette [transparent][0] = 0;
  76825. palette [transparent][1] = 0;
  76826. palette [transparent][2] = 0;
  76827. palette [transparent][3] = 0;
  76828. }
  76829. int index;
  76830. int xpos = 0, ypos = 0, pass = 0;
  76831. const Image::BitmapData destData (image, 0, 0, width, height, true);
  76832. uint8* p = destData.data;
  76833. const bool hasAlpha = image.hasAlphaChannel();
  76834. while ((index = readLZWByte (false, c)) >= 0)
  76835. {
  76836. const uint8* const paletteEntry = palette [index];
  76837. if (hasAlpha)
  76838. {
  76839. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  76840. paletteEntry[0],
  76841. paletteEntry[1],
  76842. paletteEntry[2]);
  76843. ((PixelARGB*) p)->premultiply();
  76844. }
  76845. else
  76846. {
  76847. ((PixelRGB*) p)->setARGB (0,
  76848. paletteEntry[0],
  76849. paletteEntry[1],
  76850. paletteEntry[2]);
  76851. }
  76852. p += destData.pixelStride;
  76853. ++xpos;
  76854. if (xpos == width)
  76855. {
  76856. xpos = 0;
  76857. if (interlace)
  76858. {
  76859. switch (pass)
  76860. {
  76861. case 0:
  76862. case 1: ypos += 8; break;
  76863. case 2: ypos += 4; break;
  76864. case 3: ypos += 2; break;
  76865. }
  76866. while (ypos >= height)
  76867. {
  76868. ++pass;
  76869. switch (pass)
  76870. {
  76871. case 1: ypos = 4; break;
  76872. case 2: ypos = 2; break;
  76873. case 3: ypos = 1; break;
  76874. default: return true;
  76875. }
  76876. }
  76877. }
  76878. else
  76879. {
  76880. ++ypos;
  76881. }
  76882. p = destData.getPixelPointer (xpos, ypos);
  76883. }
  76884. if (ypos >= height)
  76885. break;
  76886. }
  76887. return true;
  76888. }
  76889. END_JUCE_NAMESPACE
  76890. /*** End of inlined file: juce_GIFLoader.cpp ***/
  76891. #endif
  76892. //==============================================================================
  76893. // some files include lots of library code, so leave them to the end to avoid cluttering
  76894. // up the build for the clean files.
  76895. #if JUCE_BUILD_CORE
  76896. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  76897. namespace zlibNamespace
  76898. {
  76899. #if JUCE_INCLUDE_ZLIB_CODE
  76900. #undef OS_CODE
  76901. #undef fdopen
  76902. /*** Start of inlined file: zlib.h ***/
  76903. #ifndef ZLIB_H
  76904. #define ZLIB_H
  76905. /*** Start of inlined file: zconf.h ***/
  76906. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76907. #ifndef ZCONF_H
  76908. #define ZCONF_H
  76909. // *** Just a few hacks here to make it compile nicely with Juce..
  76910. #define Z_PREFIX 1
  76911. #undef __MACTYPES__
  76912. #ifdef _MSC_VER
  76913. #pragma warning (disable : 4131 4127 4244 4267)
  76914. #endif
  76915. /*
  76916. * If you *really* need a unique prefix for all types and library functions,
  76917. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  76918. */
  76919. #ifdef Z_PREFIX
  76920. # define deflateInit_ z_deflateInit_
  76921. # define deflate z_deflate
  76922. # define deflateEnd z_deflateEnd
  76923. # define inflateInit_ z_inflateInit_
  76924. # define inflate z_inflate
  76925. # define inflateEnd z_inflateEnd
  76926. # define inflatePrime z_inflatePrime
  76927. # define inflateGetHeader z_inflateGetHeader
  76928. # define adler32_combine z_adler32_combine
  76929. # define crc32_combine z_crc32_combine
  76930. # define deflateInit2_ z_deflateInit2_
  76931. # define deflateSetDictionary z_deflateSetDictionary
  76932. # define deflateCopy z_deflateCopy
  76933. # define deflateReset z_deflateReset
  76934. # define deflateParams z_deflateParams
  76935. # define deflateBound z_deflateBound
  76936. # define deflatePrime z_deflatePrime
  76937. # define inflateInit2_ z_inflateInit2_
  76938. # define inflateSetDictionary z_inflateSetDictionary
  76939. # define inflateSync z_inflateSync
  76940. # define inflateSyncPoint z_inflateSyncPoint
  76941. # define inflateCopy z_inflateCopy
  76942. # define inflateReset z_inflateReset
  76943. # define inflateBack z_inflateBack
  76944. # define inflateBackEnd z_inflateBackEnd
  76945. # define compress z_compress
  76946. # define compress2 z_compress2
  76947. # define compressBound z_compressBound
  76948. # define uncompress z_uncompress
  76949. # define adler32 z_adler32
  76950. # define crc32 z_crc32
  76951. # define get_crc_table z_get_crc_table
  76952. # define zError z_zError
  76953. # define alloc_func z_alloc_func
  76954. # define free_func z_free_func
  76955. # define in_func z_in_func
  76956. # define out_func z_out_func
  76957. # define Byte z_Byte
  76958. # define uInt z_uInt
  76959. # define uLong z_uLong
  76960. # define Bytef z_Bytef
  76961. # define charf z_charf
  76962. # define intf z_intf
  76963. # define uIntf z_uIntf
  76964. # define uLongf z_uLongf
  76965. # define voidpf z_voidpf
  76966. # define voidp z_voidp
  76967. #endif
  76968. #if defined(__MSDOS__) && !defined(MSDOS)
  76969. # define MSDOS
  76970. #endif
  76971. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  76972. # define OS2
  76973. #endif
  76974. #if defined(_WINDOWS) && !defined(WINDOWS)
  76975. # define WINDOWS
  76976. #endif
  76977. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  76978. # ifndef WIN32
  76979. # define WIN32
  76980. # endif
  76981. #endif
  76982. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  76983. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  76984. # ifndef SYS16BIT
  76985. # define SYS16BIT
  76986. # endif
  76987. # endif
  76988. #endif
  76989. /*
  76990. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  76991. * than 64k bytes at a time (needed on systems with 16-bit int).
  76992. */
  76993. #ifdef SYS16BIT
  76994. # define MAXSEG_64K
  76995. #endif
  76996. #ifdef MSDOS
  76997. # define UNALIGNED_OK
  76998. #endif
  76999. #ifdef __STDC_VERSION__
  77000. # ifndef STDC
  77001. # define STDC
  77002. # endif
  77003. # if __STDC_VERSION__ >= 199901L
  77004. # ifndef STDC99
  77005. # define STDC99
  77006. # endif
  77007. # endif
  77008. #endif
  77009. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77010. # define STDC
  77011. #endif
  77012. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77013. # define STDC
  77014. #endif
  77015. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77016. # define STDC
  77017. #endif
  77018. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77019. # define STDC
  77020. #endif
  77021. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77022. # define STDC
  77023. #endif
  77024. #ifndef STDC
  77025. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77026. # define const /* note: need a more gentle solution here */
  77027. # endif
  77028. #endif
  77029. /* Some Mac compilers merge all .h files incorrectly: */
  77030. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77031. # define NO_DUMMY_DECL
  77032. #endif
  77033. /* Maximum value for memLevel in deflateInit2 */
  77034. #ifndef MAX_MEM_LEVEL
  77035. # ifdef MAXSEG_64K
  77036. # define MAX_MEM_LEVEL 8
  77037. # else
  77038. # define MAX_MEM_LEVEL 9
  77039. # endif
  77040. #endif
  77041. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77042. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77043. * created by gzip. (Files created by minigzip can still be extracted by
  77044. * gzip.)
  77045. */
  77046. #ifndef MAX_WBITS
  77047. # define MAX_WBITS 15 /* 32K LZ77 window */
  77048. #endif
  77049. /* The memory requirements for deflate are (in bytes):
  77050. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77051. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77052. plus a few kilobytes for small objects. For example, if you want to reduce
  77053. the default memory requirements from 256K to 128K, compile with
  77054. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77055. Of course this will generally degrade compression (there's no free lunch).
  77056. The memory requirements for inflate are (in bytes) 1 << windowBits
  77057. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77058. for small objects.
  77059. */
  77060. /* Type declarations */
  77061. #ifndef OF /* function prototypes */
  77062. # ifdef STDC
  77063. # define OF(args) args
  77064. # else
  77065. # define OF(args) ()
  77066. # endif
  77067. #endif
  77068. /* The following definitions for FAR are needed only for MSDOS mixed
  77069. * model programming (small or medium model with some far allocations).
  77070. * This was tested only with MSC; for other MSDOS compilers you may have
  77071. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77072. * just define FAR to be empty.
  77073. */
  77074. #ifdef SYS16BIT
  77075. # if defined(M_I86SM) || defined(M_I86MM)
  77076. /* MSC small or medium model */
  77077. # define SMALL_MEDIUM
  77078. # ifdef _MSC_VER
  77079. # define FAR _far
  77080. # else
  77081. # define FAR far
  77082. # endif
  77083. # endif
  77084. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77085. /* Turbo C small or medium model */
  77086. # define SMALL_MEDIUM
  77087. # ifdef __BORLANDC__
  77088. # define FAR _far
  77089. # else
  77090. # define FAR far
  77091. # endif
  77092. # endif
  77093. #endif
  77094. #if defined(WINDOWS) || defined(WIN32)
  77095. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77096. * This is not mandatory, but it offers a little performance increase.
  77097. */
  77098. # ifdef ZLIB_DLL
  77099. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77100. # ifdef ZLIB_INTERNAL
  77101. # define ZEXTERN extern __declspec(dllexport)
  77102. # else
  77103. # define ZEXTERN extern __declspec(dllimport)
  77104. # endif
  77105. # endif
  77106. # endif /* ZLIB_DLL */
  77107. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  77108. * define ZLIB_WINAPI.
  77109. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  77110. */
  77111. # ifdef ZLIB_WINAPI
  77112. # ifdef FAR
  77113. # undef FAR
  77114. # endif
  77115. # include <windows.h>
  77116. /* No need for _export, use ZLIB.DEF instead. */
  77117. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  77118. # define ZEXPORT WINAPI
  77119. # ifdef WIN32
  77120. # define ZEXPORTVA WINAPIV
  77121. # else
  77122. # define ZEXPORTVA FAR CDECL
  77123. # endif
  77124. # endif
  77125. #endif
  77126. #if defined (__BEOS__)
  77127. # ifdef ZLIB_DLL
  77128. # ifdef ZLIB_INTERNAL
  77129. # define ZEXPORT __declspec(dllexport)
  77130. # define ZEXPORTVA __declspec(dllexport)
  77131. # else
  77132. # define ZEXPORT __declspec(dllimport)
  77133. # define ZEXPORTVA __declspec(dllimport)
  77134. # endif
  77135. # endif
  77136. #endif
  77137. #ifndef ZEXTERN
  77138. # define ZEXTERN extern
  77139. #endif
  77140. #ifndef ZEXPORT
  77141. # define ZEXPORT
  77142. #endif
  77143. #ifndef ZEXPORTVA
  77144. # define ZEXPORTVA
  77145. #endif
  77146. #ifndef FAR
  77147. # define FAR
  77148. #endif
  77149. #if !defined(__MACTYPES__)
  77150. typedef unsigned char Byte; /* 8 bits */
  77151. #endif
  77152. typedef unsigned int uInt; /* 16 bits or more */
  77153. typedef unsigned long uLong; /* 32 bits or more */
  77154. #ifdef SMALL_MEDIUM
  77155. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  77156. # define Bytef Byte FAR
  77157. #else
  77158. typedef Byte FAR Bytef;
  77159. #endif
  77160. typedef char FAR charf;
  77161. typedef int FAR intf;
  77162. typedef uInt FAR uIntf;
  77163. typedef uLong FAR uLongf;
  77164. #ifdef STDC
  77165. typedef void const *voidpc;
  77166. typedef void FAR *voidpf;
  77167. typedef void *voidp;
  77168. #else
  77169. typedef Byte const *voidpc;
  77170. typedef Byte FAR *voidpf;
  77171. typedef Byte *voidp;
  77172. #endif
  77173. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  77174. # include <sys/types.h> /* for off_t */
  77175. # include <unistd.h> /* for SEEK_* and off_t */
  77176. # ifdef VMS
  77177. # include <unixio.h> /* for off_t */
  77178. # endif
  77179. # define z_off_t off_t
  77180. #endif
  77181. #ifndef SEEK_SET
  77182. # define SEEK_SET 0 /* Seek from beginning of file. */
  77183. # define SEEK_CUR 1 /* Seek from current position. */
  77184. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  77185. #endif
  77186. #ifndef z_off_t
  77187. # define z_off_t long
  77188. #endif
  77189. #if defined(__OS400__)
  77190. # define NO_vsnprintf
  77191. #endif
  77192. #if defined(__MVS__)
  77193. # define NO_vsnprintf
  77194. # ifdef FAR
  77195. # undef FAR
  77196. # endif
  77197. #endif
  77198. /* MVS linker does not support external names larger than 8 bytes */
  77199. #if defined(__MVS__)
  77200. # pragma map(deflateInit_,"DEIN")
  77201. # pragma map(deflateInit2_,"DEIN2")
  77202. # pragma map(deflateEnd,"DEEND")
  77203. # pragma map(deflateBound,"DEBND")
  77204. # pragma map(inflateInit_,"ININ")
  77205. # pragma map(inflateInit2_,"ININ2")
  77206. # pragma map(inflateEnd,"INEND")
  77207. # pragma map(inflateSync,"INSY")
  77208. # pragma map(inflateSetDictionary,"INSEDI")
  77209. # pragma map(compressBound,"CMBND")
  77210. # pragma map(inflate_table,"INTABL")
  77211. # pragma map(inflate_fast,"INFA")
  77212. # pragma map(inflate_copyright,"INCOPY")
  77213. #endif
  77214. #endif /* ZCONF_H */
  77215. /*** End of inlined file: zconf.h ***/
  77216. #ifdef __cplusplus
  77217. extern "C" {
  77218. #endif
  77219. #define ZLIB_VERSION "1.2.3"
  77220. #define ZLIB_VERNUM 0x1230
  77221. /*
  77222. The 'zlib' compression library provides in-memory compression and
  77223. decompression functions, including integrity checks of the uncompressed
  77224. data. This version of the library supports only one compression method
  77225. (deflation) but other algorithms will be added later and will have the same
  77226. stream interface.
  77227. Compression can be done in a single step if the buffers are large
  77228. enough (for example if an input file is mmap'ed), or can be done by
  77229. repeated calls of the compression function. In the latter case, the
  77230. application must provide more input and/or consume the output
  77231. (providing more output space) before each call.
  77232. The compressed data format used by default by the in-memory functions is
  77233. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  77234. around a deflate stream, which is itself documented in RFC 1951.
  77235. The library also supports reading and writing files in gzip (.gz) format
  77236. with an interface similar to that of stdio using the functions that start
  77237. with "gz". The gzip format is different from the zlib format. gzip is a
  77238. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  77239. This library can optionally read and write gzip streams in memory as well.
  77240. The zlib format was designed to be compact and fast for use in memory
  77241. and on communications channels. The gzip format was designed for single-
  77242. file compression on file systems, has a larger header than zlib to maintain
  77243. directory information, and uses a different, slower check method than zlib.
  77244. The library does not install any signal handler. The decoder checks
  77245. the consistency of the compressed data, so the library should never
  77246. crash even in case of corrupted input.
  77247. */
  77248. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  77249. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  77250. struct internal_state;
  77251. typedef struct z_stream_s {
  77252. Bytef *next_in; /* next input byte */
  77253. uInt avail_in; /* number of bytes available at next_in */
  77254. uLong total_in; /* total nb of input bytes read so far */
  77255. Bytef *next_out; /* next output byte should be put there */
  77256. uInt avail_out; /* remaining free space at next_out */
  77257. uLong total_out; /* total nb of bytes output so far */
  77258. char *msg; /* last error message, NULL if no error */
  77259. struct internal_state FAR *state; /* not visible by applications */
  77260. alloc_func zalloc; /* used to allocate the internal state */
  77261. free_func zfree; /* used to free the internal state */
  77262. voidpf opaque; /* private data object passed to zalloc and zfree */
  77263. int data_type; /* best guess about the data type: binary or text */
  77264. uLong adler; /* adler32 value of the uncompressed data */
  77265. uLong reserved; /* reserved for future use */
  77266. } z_stream;
  77267. typedef z_stream FAR *z_streamp;
  77268. /*
  77269. gzip header information passed to and from zlib routines. See RFC 1952
  77270. for more details on the meanings of these fields.
  77271. */
  77272. typedef struct gz_header_s {
  77273. int text; /* true if compressed data believed to be text */
  77274. uLong time; /* modification time */
  77275. int xflags; /* extra flags (not used when writing a gzip file) */
  77276. int os; /* operating system */
  77277. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  77278. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  77279. uInt extra_max; /* space at extra (only when reading header) */
  77280. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  77281. uInt name_max; /* space at name (only when reading header) */
  77282. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  77283. uInt comm_max; /* space at comment (only when reading header) */
  77284. int hcrc; /* true if there was or will be a header crc */
  77285. int done; /* true when done reading gzip header (not used
  77286. when writing a gzip file) */
  77287. } gz_header;
  77288. typedef gz_header FAR *gz_headerp;
  77289. /*
  77290. The application must update next_in and avail_in when avail_in has
  77291. dropped to zero. It must update next_out and avail_out when avail_out
  77292. has dropped to zero. The application must initialize zalloc, zfree and
  77293. opaque before calling the init function. All other fields are set by the
  77294. compression library and must not be updated by the application.
  77295. The opaque value provided by the application will be passed as the first
  77296. parameter for calls of zalloc and zfree. This can be useful for custom
  77297. memory management. The compression library attaches no meaning to the
  77298. opaque value.
  77299. zalloc must return Z_NULL if there is not enough memory for the object.
  77300. If zlib is used in a multi-threaded application, zalloc and zfree must be
  77301. thread safe.
  77302. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  77303. exactly 65536 bytes, but will not be required to allocate more than this
  77304. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  77305. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  77306. have their offset normalized to zero. The default allocation function
  77307. provided by this library ensures this (see zutil.c). To reduce memory
  77308. requirements and avoid any allocation of 64K objects, at the expense of
  77309. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  77310. The fields total_in and total_out can be used for statistics or
  77311. progress reports. After compression, total_in holds the total size of
  77312. the uncompressed data and may be saved for use in the decompressor
  77313. (particularly if the decompressor wants to decompress everything in
  77314. a single step).
  77315. */
  77316. /* constants */
  77317. #define Z_NO_FLUSH 0
  77318. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  77319. #define Z_SYNC_FLUSH 2
  77320. #define Z_FULL_FLUSH 3
  77321. #define Z_FINISH 4
  77322. #define Z_BLOCK 5
  77323. /* Allowed flush values; see deflate() and inflate() below for details */
  77324. #define Z_OK 0
  77325. #define Z_STREAM_END 1
  77326. #define Z_NEED_DICT 2
  77327. #define Z_ERRNO (-1)
  77328. #define Z_STREAM_ERROR (-2)
  77329. #define Z_DATA_ERROR (-3)
  77330. #define Z_MEM_ERROR (-4)
  77331. #define Z_BUF_ERROR (-5)
  77332. #define Z_VERSION_ERROR (-6)
  77333. /* Return codes for the compression/decompression functions. Negative
  77334. * values are errors, positive values are used for special but normal events.
  77335. */
  77336. #define Z_NO_COMPRESSION 0
  77337. #define Z_BEST_SPEED 1
  77338. #define Z_BEST_COMPRESSION 9
  77339. #define Z_DEFAULT_COMPRESSION (-1)
  77340. /* compression levels */
  77341. #define Z_FILTERED 1
  77342. #define Z_HUFFMAN_ONLY 2
  77343. #define Z_RLE 3
  77344. #define Z_FIXED 4
  77345. #define Z_DEFAULT_STRATEGY 0
  77346. /* compression strategy; see deflateInit2() below for details */
  77347. #define Z_BINARY 0
  77348. #define Z_TEXT 1
  77349. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  77350. #define Z_UNKNOWN 2
  77351. /* Possible values of the data_type field (though see inflate()) */
  77352. #define Z_DEFLATED 8
  77353. /* The deflate compression method (the only one supported in this version) */
  77354. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  77355. #define zlib_version zlibVersion()
  77356. /* for compatibility with versions < 1.0.2 */
  77357. /* basic functions */
  77358. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  77359. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  77360. If the first character differs, the library code actually used is
  77361. not compatible with the zlib.h header file used by the application.
  77362. This check is automatically made by deflateInit and inflateInit.
  77363. */
  77364. /*
  77365. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  77366. Initializes the internal stream state for compression. The fields
  77367. zalloc, zfree and opaque must be initialized before by the caller.
  77368. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  77369. use default allocation functions.
  77370. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  77371. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  77372. all (the input data is simply copied a block at a time).
  77373. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  77374. compression (currently equivalent to level 6).
  77375. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  77376. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  77377. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  77378. with the version assumed by the caller (ZLIB_VERSION).
  77379. msg is set to null if there is no error message. deflateInit does not
  77380. perform any compression: this will be done by deflate().
  77381. */
  77382. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  77383. /*
  77384. deflate compresses as much data as possible, and stops when the input
  77385. buffer becomes empty or the output buffer becomes full. It may introduce some
  77386. output latency (reading input without producing any output) except when
  77387. forced to flush.
  77388. The detailed semantics are as follows. deflate performs one or both of the
  77389. following actions:
  77390. - Compress more input starting at next_in and update next_in and avail_in
  77391. accordingly. If not all input can be processed (because there is not
  77392. enough room in the output buffer), next_in and avail_in are updated and
  77393. processing will resume at this point for the next call of deflate().
  77394. - Provide more output starting at next_out and update next_out and avail_out
  77395. accordingly. This action is forced if the parameter flush is non zero.
  77396. Forcing flush frequently degrades the compression ratio, so this parameter
  77397. should be set only when necessary (in interactive applications).
  77398. Some output may be provided even if flush is not set.
  77399. Before the call of deflate(), the application should ensure that at least
  77400. one of the actions is possible, by providing more input and/or consuming
  77401. more output, and updating avail_in or avail_out accordingly; avail_out
  77402. should never be zero before the call. The application can consume the
  77403. compressed output when it wants, for example when the output buffer is full
  77404. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  77405. and with zero avail_out, it must be called again after making room in the
  77406. output buffer because there might be more output pending.
  77407. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  77408. decide how much data to accumualte before producing output, in order to
  77409. maximize compression.
  77410. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  77411. flushed to the output buffer and the output is aligned on a byte boundary, so
  77412. that the decompressor can get all input data available so far. (In particular
  77413. avail_in is zero after the call if enough output space has been provided
  77414. before the call.) Flushing may degrade compression for some compression
  77415. algorithms and so it should be used only when necessary.
  77416. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  77417. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  77418. restart from this point if previous compressed data has been damaged or if
  77419. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  77420. compression.
  77421. If deflate returns with avail_out == 0, this function must be called again
  77422. with the same value of the flush parameter and more output space (updated
  77423. avail_out), until the flush is complete (deflate returns with non-zero
  77424. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  77425. avail_out is greater than six to avoid repeated flush markers due to
  77426. avail_out == 0 on return.
  77427. If the parameter flush is set to Z_FINISH, pending input is processed,
  77428. pending output is flushed and deflate returns with Z_STREAM_END if there
  77429. was enough output space; if deflate returns with Z_OK, this function must be
  77430. called again with Z_FINISH and more output space (updated avail_out) but no
  77431. more input data, until it returns with Z_STREAM_END or an error. After
  77432. deflate has returned Z_STREAM_END, the only possible operations on the
  77433. stream are deflateReset or deflateEnd.
  77434. Z_FINISH can be used immediately after deflateInit if all the compression
  77435. is to be done in a single step. In this case, avail_out must be at least
  77436. the value returned by deflateBound (see below). If deflate does not return
  77437. Z_STREAM_END, then it must be called again as described above.
  77438. deflate() sets strm->adler to the adler32 checksum of all input read
  77439. so far (that is, total_in bytes).
  77440. deflate() may update strm->data_type if it can make a good guess about
  77441. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  77442. binary. This field is only for information purposes and does not affect
  77443. the compression algorithm in any manner.
  77444. deflate() returns Z_OK if some progress has been made (more input
  77445. processed or more output produced), Z_STREAM_END if all input has been
  77446. consumed and all output has been produced (only when flush is set to
  77447. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  77448. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  77449. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  77450. fatal, and deflate() can be called again with more input and more output
  77451. space to continue compressing.
  77452. */
  77453. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  77454. /*
  77455. All dynamically allocated data structures for this stream are freed.
  77456. This function discards any unprocessed input and does not flush any
  77457. pending output.
  77458. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  77459. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  77460. prematurely (some input or output was discarded). In the error case,
  77461. msg may be set but then points to a static string (which must not be
  77462. deallocated).
  77463. */
  77464. /*
  77465. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  77466. Initializes the internal stream state for decompression. The fields
  77467. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  77468. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  77469. value depends on the compression method), inflateInit determines the
  77470. compression method from the zlib header and allocates all data structures
  77471. accordingly; otherwise the allocation will be deferred to the first call of
  77472. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  77473. use default allocation functions.
  77474. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77475. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  77476. version assumed by the caller. msg is set to null if there is no error
  77477. message. inflateInit does not perform any decompression apart from reading
  77478. the zlib header if present: this will be done by inflate(). (So next_in and
  77479. avail_in may be modified, but next_out and avail_out are unchanged.)
  77480. */
  77481. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  77482. /*
  77483. inflate decompresses as much data as possible, and stops when the input
  77484. buffer becomes empty or the output buffer becomes full. It may introduce
  77485. some output latency (reading input without producing any output) except when
  77486. forced to flush.
  77487. The detailed semantics are as follows. inflate performs one or both of the
  77488. following actions:
  77489. - Decompress more input starting at next_in and update next_in and avail_in
  77490. accordingly. If not all input can be processed (because there is not
  77491. enough room in the output buffer), next_in is updated and processing
  77492. will resume at this point for the next call of inflate().
  77493. - Provide more output starting at next_out and update next_out and avail_out
  77494. accordingly. inflate() provides as much output as possible, until there
  77495. is no more input data or no more space in the output buffer (see below
  77496. about the flush parameter).
  77497. Before the call of inflate(), the application should ensure that at least
  77498. one of the actions is possible, by providing more input and/or consuming
  77499. more output, and updating the next_* and avail_* values accordingly.
  77500. The application can consume the uncompressed output when it wants, for
  77501. example when the output buffer is full (avail_out == 0), or after each
  77502. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  77503. must be called again after making room in the output buffer because there
  77504. might be more output pending.
  77505. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  77506. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  77507. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  77508. if and when it gets to the next deflate block boundary. When decoding the
  77509. zlib or gzip format, this will cause inflate() to return immediately after
  77510. the header and before the first block. When doing a raw inflate, inflate()
  77511. will go ahead and process the first block, and will return when it gets to
  77512. the end of that block, or when it runs out of data.
  77513. The Z_BLOCK option assists in appending to or combining deflate streams.
  77514. Also to assist in this, on return inflate() will set strm->data_type to the
  77515. number of unused bits in the last byte taken from strm->next_in, plus 64
  77516. if inflate() is currently decoding the last block in the deflate stream,
  77517. plus 128 if inflate() returned immediately after decoding an end-of-block
  77518. code or decoding the complete header up to just before the first byte of the
  77519. deflate stream. The end-of-block will not be indicated until all of the
  77520. uncompressed data from that block has been written to strm->next_out. The
  77521. number of unused bits may in general be greater than seven, except when
  77522. bit 7 of data_type is set, in which case the number of unused bits will be
  77523. less than eight.
  77524. inflate() should normally be called until it returns Z_STREAM_END or an
  77525. error. However if all decompression is to be performed in a single step
  77526. (a single call of inflate), the parameter flush should be set to
  77527. Z_FINISH. In this case all pending input is processed and all pending
  77528. output is flushed; avail_out must be large enough to hold all the
  77529. uncompressed data. (The size of the uncompressed data may have been saved
  77530. by the compressor for this purpose.) The next operation on this stream must
  77531. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  77532. is never required, but can be used to inform inflate that a faster approach
  77533. may be used for the single inflate() call.
  77534. In this implementation, inflate() always flushes as much output as
  77535. possible to the output buffer, and always uses the faster approach on the
  77536. first call. So the only effect of the flush parameter in this implementation
  77537. is on the return value of inflate(), as noted below, or when it returns early
  77538. because Z_BLOCK is used.
  77539. If a preset dictionary is needed after this call (see inflateSetDictionary
  77540. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  77541. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  77542. strm->adler to the adler32 checksum of all output produced so far (that is,
  77543. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  77544. below. At the end of the stream, inflate() checks that its computed adler32
  77545. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  77546. only if the checksum is correct.
  77547. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  77548. deflate data. The header type is detected automatically. Any information
  77549. contained in the gzip header is not retained, so applications that need that
  77550. information should instead use raw inflate, see inflateInit2() below, or
  77551. inflateBack() and perform their own processing of the gzip header and
  77552. trailer.
  77553. inflate() returns Z_OK if some progress has been made (more input processed
  77554. or more output produced), Z_STREAM_END if the end of the compressed data has
  77555. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  77556. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  77557. corrupted (input stream not conforming to the zlib format or incorrect check
  77558. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  77559. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  77560. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  77561. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  77562. inflate() can be called again with more input and more output space to
  77563. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  77564. call inflateSync() to look for a good compression block if a partial recovery
  77565. of the data is desired.
  77566. */
  77567. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  77568. /*
  77569. All dynamically allocated data structures for this stream are freed.
  77570. This function discards any unprocessed input and does not flush any
  77571. pending output.
  77572. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  77573. was inconsistent. In the error case, msg may be set but then points to a
  77574. static string (which must not be deallocated).
  77575. */
  77576. /* Advanced functions */
  77577. /*
  77578. The following functions are needed only in some special applications.
  77579. */
  77580. /*
  77581. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  77582. int level,
  77583. int method,
  77584. int windowBits,
  77585. int memLevel,
  77586. int strategy));
  77587. This is another version of deflateInit with more compression options. The
  77588. fields next_in, zalloc, zfree and opaque must be initialized before by
  77589. the caller.
  77590. The method parameter is the compression method. It must be Z_DEFLATED in
  77591. this version of the library.
  77592. The windowBits parameter is the base two logarithm of the window size
  77593. (the size of the history buffer). It should be in the range 8..15 for this
  77594. version of the library. Larger values of this parameter result in better
  77595. compression at the expense of memory usage. The default value is 15 if
  77596. deflateInit is used instead.
  77597. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  77598. determines the window size. deflate() will then generate raw deflate data
  77599. with no zlib header or trailer, and will not compute an adler32 check value.
  77600. windowBits can also be greater than 15 for optional gzip encoding. Add
  77601. 16 to windowBits to write a simple gzip header and trailer around the
  77602. compressed data instead of a zlib wrapper. The gzip header will have no
  77603. file name, no extra data, no comment, no modification time (set to zero),
  77604. no header crc, and the operating system will be set to 255 (unknown). If a
  77605. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  77606. The memLevel parameter specifies how much memory should be allocated
  77607. for the internal compression state. memLevel=1 uses minimum memory but
  77608. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  77609. for optimal speed. The default value is 8. See zconf.h for total memory
  77610. usage as a function of windowBits and memLevel.
  77611. The strategy parameter is used to tune the compression algorithm. Use the
  77612. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  77613. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  77614. string match), or Z_RLE to limit match distances to one (run-length
  77615. encoding). Filtered data consists mostly of small values with a somewhat
  77616. random distribution. In this case, the compression algorithm is tuned to
  77617. compress them better. The effect of Z_FILTERED is to force more Huffman
  77618. coding and less string matching; it is somewhat intermediate between
  77619. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  77620. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  77621. parameter only affects the compression ratio but not the correctness of the
  77622. compressed output even if it is not set appropriately. Z_FIXED prevents the
  77623. use of dynamic Huffman codes, allowing for a simpler decoder for special
  77624. applications.
  77625. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77626. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  77627. method). msg is set to null if there is no error message. deflateInit2 does
  77628. not perform any compression: this will be done by deflate().
  77629. */
  77630. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  77631. const Bytef *dictionary,
  77632. uInt dictLength));
  77633. /*
  77634. Initializes the compression dictionary from the given byte sequence
  77635. without producing any compressed output. This function must be called
  77636. immediately after deflateInit, deflateInit2 or deflateReset, before any
  77637. call of deflate. The compressor and decompressor must use exactly the same
  77638. dictionary (see inflateSetDictionary).
  77639. The dictionary should consist of strings (byte sequences) that are likely
  77640. to be encountered later in the data to be compressed, with the most commonly
  77641. used strings preferably put towards the end of the dictionary. Using a
  77642. dictionary is most useful when the data to be compressed is short and can be
  77643. predicted with good accuracy; the data can then be compressed better than
  77644. with the default empty dictionary.
  77645. Depending on the size of the compression data structures selected by
  77646. deflateInit or deflateInit2, a part of the dictionary may in effect be
  77647. discarded, for example if the dictionary is larger than the window size in
  77648. deflate or deflate2. Thus the strings most likely to be useful should be
  77649. put at the end of the dictionary, not at the front. In addition, the
  77650. current implementation of deflate will use at most the window size minus
  77651. 262 bytes of the provided dictionary.
  77652. Upon return of this function, strm->adler is set to the adler32 value
  77653. of the dictionary; the decompressor may later use this value to determine
  77654. which dictionary has been used by the compressor. (The adler32 value
  77655. applies to the whole dictionary even if only a subset of the dictionary is
  77656. actually used by the compressor.) If a raw deflate was requested, then the
  77657. adler32 value is not computed and strm->adler is not set.
  77658. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  77659. parameter is invalid (such as NULL dictionary) or the stream state is
  77660. inconsistent (for example if deflate has already been called for this stream
  77661. or if the compression method is bsort). deflateSetDictionary does not
  77662. perform any compression: this will be done by deflate().
  77663. */
  77664. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  77665. z_streamp source));
  77666. /*
  77667. Sets the destination stream as a complete copy of the source stream.
  77668. This function can be useful when several compression strategies will be
  77669. tried, for example when there are several ways of pre-processing the input
  77670. data with a filter. The streams that will be discarded should then be freed
  77671. by calling deflateEnd. Note that deflateCopy duplicates the internal
  77672. compression state which can be quite large, so this strategy is slow and
  77673. can consume lots of memory.
  77674. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  77675. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  77676. (such as zalloc being NULL). msg is left unchanged in both source and
  77677. destination.
  77678. */
  77679. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  77680. /*
  77681. This function is equivalent to deflateEnd followed by deflateInit,
  77682. but does not free and reallocate all the internal compression state.
  77683. The stream will keep the same compression level and any other attributes
  77684. that may have been set by deflateInit2.
  77685. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  77686. stream state was inconsistent (such as zalloc or state being NULL).
  77687. */
  77688. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  77689. int level,
  77690. int strategy));
  77691. /*
  77692. Dynamically update the compression level and compression strategy. The
  77693. interpretation of level and strategy is as in deflateInit2. This can be
  77694. used to switch between compression and straight copy of the input data, or
  77695. to switch to a different kind of input data requiring a different
  77696. strategy. If the compression level is changed, the input available so far
  77697. is compressed with the old level (and may be flushed); the new level will
  77698. take effect only at the next call of deflate().
  77699. Before the call of deflateParams, the stream state must be set as for
  77700. a call of deflate(), since the currently available input may have to
  77701. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  77702. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  77703. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  77704. if strm->avail_out was zero.
  77705. */
  77706. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  77707. int good_length,
  77708. int max_lazy,
  77709. int nice_length,
  77710. int max_chain));
  77711. /*
  77712. Fine tune deflate's internal compression parameters. This should only be
  77713. used by someone who understands the algorithm used by zlib's deflate for
  77714. searching for the best matching string, and even then only by the most
  77715. fanatic optimizer trying to squeeze out the last compressed bit for their
  77716. specific input data. Read the deflate.c source code for the meaning of the
  77717. max_lazy, good_length, nice_length, and max_chain parameters.
  77718. deflateTune() can be called after deflateInit() or deflateInit2(), and
  77719. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  77720. */
  77721. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  77722. uLong sourceLen));
  77723. /*
  77724. deflateBound() returns an upper bound on the compressed size after
  77725. deflation of sourceLen bytes. It must be called after deflateInit()
  77726. or deflateInit2(). This would be used to allocate an output buffer
  77727. for deflation in a single pass, and so would be called before deflate().
  77728. */
  77729. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  77730. int bits,
  77731. int value));
  77732. /*
  77733. deflatePrime() inserts bits in the deflate output stream. The intent
  77734. is that this function is used to start off the deflate output with the
  77735. bits leftover from a previous deflate stream when appending to it. As such,
  77736. this function can only be used for raw deflate, and must be used before the
  77737. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  77738. less than or equal to 16, and that many of the least significant bits of
  77739. value will be inserted in the output.
  77740. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  77741. stream state was inconsistent.
  77742. */
  77743. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  77744. gz_headerp head));
  77745. /*
  77746. deflateSetHeader() provides gzip header information for when a gzip
  77747. stream is requested by deflateInit2(). deflateSetHeader() may be called
  77748. after deflateInit2() or deflateReset() and before the first call of
  77749. deflate(). The text, time, os, extra field, name, and comment information
  77750. in the provided gz_header structure are written to the gzip header (xflag is
  77751. ignored -- the extra flags are set according to the compression level). The
  77752. caller must assure that, if not Z_NULL, name and comment are terminated with
  77753. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  77754. available there. If hcrc is true, a gzip header crc is included. Note that
  77755. the current versions of the command-line version of gzip (up through version
  77756. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  77757. gzip file" and give up.
  77758. If deflateSetHeader is not used, the default gzip header has text false,
  77759. the time set to zero, and os set to 255, with no extra, name, or comment
  77760. fields. The gzip header is returned to the default state by deflateReset().
  77761. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  77762. stream state was inconsistent.
  77763. */
  77764. /*
  77765. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  77766. int windowBits));
  77767. This is another version of inflateInit with an extra parameter. The
  77768. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  77769. before by the caller.
  77770. The windowBits parameter is the base two logarithm of the maximum window
  77771. size (the size of the history buffer). It should be in the range 8..15 for
  77772. this version of the library. The default value is 15 if inflateInit is used
  77773. instead. windowBits must be greater than or equal to the windowBits value
  77774. provided to deflateInit2() while compressing, or it must be equal to 15 if
  77775. deflateInit2() was not used. If a compressed stream with a larger window
  77776. size is given as input, inflate() will return with the error code
  77777. Z_DATA_ERROR instead of trying to allocate a larger window.
  77778. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  77779. determines the window size. inflate() will then process raw deflate data,
  77780. not looking for a zlib or gzip header, not generating a check value, and not
  77781. looking for any check values for comparison at the end of the stream. This
  77782. is for use with other formats that use the deflate compressed data format
  77783. such as zip. Those formats provide their own check values. If a custom
  77784. format is developed using the raw deflate format for compressed data, it is
  77785. recommended that a check value such as an adler32 or a crc32 be applied to
  77786. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  77787. most applications, the zlib format should be used as is. Note that comments
  77788. above on the use in deflateInit2() applies to the magnitude of windowBits.
  77789. windowBits can also be greater than 15 for optional gzip decoding. Add
  77790. 32 to windowBits to enable zlib and gzip decoding with automatic header
  77791. detection, or add 16 to decode only the gzip format (the zlib format will
  77792. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  77793. a crc32 instead of an adler32.
  77794. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77795. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  77796. is set to null if there is no error message. inflateInit2 does not perform
  77797. any decompression apart from reading the zlib header if present: this will
  77798. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  77799. and avail_out are unchanged.)
  77800. */
  77801. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  77802. const Bytef *dictionary,
  77803. uInt dictLength));
  77804. /*
  77805. Initializes the decompression dictionary from the given uncompressed byte
  77806. sequence. This function must be called immediately after a call of inflate,
  77807. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  77808. can be determined from the adler32 value returned by that call of inflate.
  77809. The compressor and decompressor must use exactly the same dictionary (see
  77810. deflateSetDictionary). For raw inflate, this function can be called
  77811. immediately after inflateInit2() or inflateReset() and before any call of
  77812. inflate() to set the dictionary. The application must insure that the
  77813. dictionary that was used for compression is provided.
  77814. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  77815. parameter is invalid (such as NULL dictionary) or the stream state is
  77816. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  77817. expected one (incorrect adler32 value). inflateSetDictionary does not
  77818. perform any decompression: this will be done by subsequent calls of
  77819. inflate().
  77820. */
  77821. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  77822. /*
  77823. Skips invalid compressed data until a full flush point (see above the
  77824. description of deflate with Z_FULL_FLUSH) can be found, or until all
  77825. available input is skipped. No output is provided.
  77826. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  77827. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  77828. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  77829. case, the application may save the current current value of total_in which
  77830. indicates where valid compressed data was found. In the error case, the
  77831. application may repeatedly call inflateSync, providing more input each time,
  77832. until success or end of the input data.
  77833. */
  77834. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  77835. z_streamp source));
  77836. /*
  77837. Sets the destination stream as a complete copy of the source stream.
  77838. This function can be useful when randomly accessing a large stream. The
  77839. first pass through the stream can periodically record the inflate state,
  77840. allowing restarting inflate at those points when randomly accessing the
  77841. stream.
  77842. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  77843. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  77844. (such as zalloc being NULL). msg is left unchanged in both source and
  77845. destination.
  77846. */
  77847. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  77848. /*
  77849. This function is equivalent to inflateEnd followed by inflateInit,
  77850. but does not free and reallocate all the internal decompression state.
  77851. The stream will keep attributes that may have been set by inflateInit2.
  77852. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  77853. stream state was inconsistent (such as zalloc or state being NULL).
  77854. */
  77855. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  77856. int bits,
  77857. int value));
  77858. /*
  77859. This function inserts bits in the inflate input stream. The intent is
  77860. that this function is used to start inflating at a bit position in the
  77861. middle of a byte. The provided bits will be used before any bytes are used
  77862. from next_in. This function should only be used with raw inflate, and
  77863. should be used before the first inflate() call after inflateInit2() or
  77864. inflateReset(). bits must be less than or equal to 16, and that many of the
  77865. least significant bits of value will be inserted in the input.
  77866. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  77867. stream state was inconsistent.
  77868. */
  77869. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  77870. gz_headerp head));
  77871. /*
  77872. inflateGetHeader() requests that gzip header information be stored in the
  77873. provided gz_header structure. inflateGetHeader() may be called after
  77874. inflateInit2() or inflateReset(), and before the first call of inflate().
  77875. As inflate() processes the gzip stream, head->done is zero until the header
  77876. is completed, at which time head->done is set to one. If a zlib stream is
  77877. being decoded, then head->done is set to -1 to indicate that there will be
  77878. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  77879. force inflate() to return immediately after header processing is complete
  77880. and before any actual data is decompressed.
  77881. The text, time, xflags, and os fields are filled in with the gzip header
  77882. contents. hcrc is set to true if there is a header CRC. (The header CRC
  77883. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  77884. contains the maximum number of bytes to write to extra. Once done is true,
  77885. extra_len contains the actual extra field length, and extra contains the
  77886. extra field, or that field truncated if extra_max is less than extra_len.
  77887. If name is not Z_NULL, then up to name_max characters are written there,
  77888. terminated with a zero unless the length is greater than name_max. If
  77889. comment is not Z_NULL, then up to comm_max characters are written there,
  77890. terminated with a zero unless the length is greater than comm_max. When
  77891. any of extra, name, or comment are not Z_NULL and the respective field is
  77892. not present in the header, then that field is set to Z_NULL to signal its
  77893. absence. This allows the use of deflateSetHeader() with the returned
  77894. structure to duplicate the header. However if those fields are set to
  77895. allocated memory, then the application will need to save those pointers
  77896. elsewhere so that they can be eventually freed.
  77897. If inflateGetHeader is not used, then the header information is simply
  77898. discarded. The header is always checked for validity, including the header
  77899. CRC if present. inflateReset() will reset the process to discard the header
  77900. information. The application would need to call inflateGetHeader() again to
  77901. retrieve the header from the next gzip stream.
  77902. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  77903. stream state was inconsistent.
  77904. */
  77905. /*
  77906. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  77907. unsigned char FAR *window));
  77908. Initialize the internal stream state for decompression using inflateBack()
  77909. calls. The fields zalloc, zfree and opaque in strm must be initialized
  77910. before the call. If zalloc and zfree are Z_NULL, then the default library-
  77911. derived memory allocation routines are used. windowBits is the base two
  77912. logarithm of the window size, in the range 8..15. window is a caller
  77913. supplied buffer of that size. Except for special applications where it is
  77914. assured that deflate was used with small window sizes, windowBits must be 15
  77915. and a 32K byte window must be supplied to be able to decompress general
  77916. deflate streams.
  77917. See inflateBack() for the usage of these routines.
  77918. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  77919. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  77920. be allocated, or Z_VERSION_ERROR if the version of the library does not
  77921. match the version of the header file.
  77922. */
  77923. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  77924. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  77925. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  77926. in_func in, void FAR *in_desc,
  77927. out_func out, void FAR *out_desc));
  77928. /*
  77929. inflateBack() does a raw inflate with a single call using a call-back
  77930. interface for input and output. This is more efficient than inflate() for
  77931. file i/o applications in that it avoids copying between the output and the
  77932. sliding window by simply making the window itself the output buffer. This
  77933. function trusts the application to not change the output buffer passed by
  77934. the output function, at least until inflateBack() returns.
  77935. inflateBackInit() must be called first to allocate the internal state
  77936. and to initialize the state with the user-provided window buffer.
  77937. inflateBack() may then be used multiple times to inflate a complete, raw
  77938. deflate stream with each call. inflateBackEnd() is then called to free
  77939. the allocated state.
  77940. A raw deflate stream is one with no zlib or gzip header or trailer.
  77941. This routine would normally be used in a utility that reads zip or gzip
  77942. files and writes out uncompressed files. The utility would decode the
  77943. header and process the trailer on its own, hence this routine expects
  77944. only the raw deflate stream to decompress. This is different from the
  77945. normal behavior of inflate(), which expects either a zlib or gzip header and
  77946. trailer around the deflate stream.
  77947. inflateBack() uses two subroutines supplied by the caller that are then
  77948. called by inflateBack() for input and output. inflateBack() calls those
  77949. routines until it reads a complete deflate stream and writes out all of the
  77950. uncompressed data, or until it encounters an error. The function's
  77951. parameters and return types are defined above in the in_func and out_func
  77952. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  77953. number of bytes of provided input, and a pointer to that input in buf. If
  77954. there is no input available, in() must return zero--buf is ignored in that
  77955. case--and inflateBack() will return a buffer error. inflateBack() will call
  77956. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  77957. should return zero on success, or non-zero on failure. If out() returns
  77958. non-zero, inflateBack() will return with an error. Neither in() nor out()
  77959. are permitted to change the contents of the window provided to
  77960. inflateBackInit(), which is also the buffer that out() uses to write from.
  77961. The length written by out() will be at most the window size. Any non-zero
  77962. amount of input may be provided by in().
  77963. For convenience, inflateBack() can be provided input on the first call by
  77964. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  77965. in() will be called. Therefore strm->next_in must be initialized before
  77966. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  77967. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  77968. must also be initialized, and then if strm->avail_in is not zero, input will
  77969. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  77970. The in_desc and out_desc parameters of inflateBack() is passed as the
  77971. first parameter of in() and out() respectively when they are called. These
  77972. descriptors can be optionally used to pass any information that the caller-
  77973. supplied in() and out() functions need to do their job.
  77974. On return, inflateBack() will set strm->next_in and strm->avail_in to
  77975. pass back any unused input that was provided by the last in() call. The
  77976. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  77977. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  77978. error in the deflate stream (in which case strm->msg is set to indicate the
  77979. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  77980. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  77981. distinguished using strm->next_in which will be Z_NULL only if in() returned
  77982. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  77983. out() returning non-zero. (in() will always be called before out(), so
  77984. strm->next_in is assured to be defined if out() returns non-zero.) Note
  77985. that inflateBack() cannot return Z_OK.
  77986. */
  77987. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  77988. /*
  77989. All memory allocated by inflateBackInit() is freed.
  77990. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  77991. state was inconsistent.
  77992. */
  77993. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  77994. /* Return flags indicating compile-time options.
  77995. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  77996. 1.0: size of uInt
  77997. 3.2: size of uLong
  77998. 5.4: size of voidpf (pointer)
  77999. 7.6: size of z_off_t
  78000. Compiler, assembler, and debug options:
  78001. 8: DEBUG
  78002. 9: ASMV or ASMINF -- use ASM code
  78003. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78004. 11: 0 (reserved)
  78005. One-time table building (smaller code, but not thread-safe if true):
  78006. 12: BUILDFIXED -- build static block decoding tables when needed
  78007. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78008. 14,15: 0 (reserved)
  78009. Library content (indicates missing functionality):
  78010. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78011. deflate code when not needed)
  78012. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78013. and decode gzip streams (to avoid linking crc code)
  78014. 18-19: 0 (reserved)
  78015. Operation variations (changes in library functionality):
  78016. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78017. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78018. 22,23: 0 (reserved)
  78019. The sprintf variant used by gzprintf (zero is best):
  78020. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78021. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78022. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78023. Remainder:
  78024. 27-31: 0 (reserved)
  78025. */
  78026. /* utility functions */
  78027. /*
  78028. The following utility functions are implemented on top of the
  78029. basic stream-oriented functions. To simplify the interface, some
  78030. default options are assumed (compression level and memory usage,
  78031. standard memory allocation functions). The source code of these
  78032. utility functions can easily be modified if you need special options.
  78033. */
  78034. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78035. const Bytef *source, uLong sourceLen));
  78036. /*
  78037. Compresses the source buffer into the destination buffer. sourceLen is
  78038. the byte length of the source buffer. Upon entry, destLen is the total
  78039. size of the destination buffer, which must be at least the value returned
  78040. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78041. compressed buffer.
  78042. This function can be used to compress a whole file at once if the
  78043. input file is mmap'ed.
  78044. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78045. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78046. buffer.
  78047. */
  78048. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78049. const Bytef *source, uLong sourceLen,
  78050. int level));
  78051. /*
  78052. Compresses the source buffer into the destination buffer. The level
  78053. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78054. length of the source buffer. Upon entry, destLen is the total size of the
  78055. destination buffer, which must be at least the value returned by
  78056. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78057. compressed buffer.
  78058. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78059. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78060. Z_STREAM_ERROR if the level parameter is invalid.
  78061. */
  78062. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78063. /*
  78064. compressBound() returns an upper bound on the compressed size after
  78065. compress() or compress2() on sourceLen bytes. It would be used before
  78066. a compress() or compress2() call to allocate the destination buffer.
  78067. */
  78068. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78069. const Bytef *source, uLong sourceLen));
  78070. /*
  78071. Decompresses the source buffer into the destination buffer. sourceLen is
  78072. the byte length of the source buffer. Upon entry, destLen is the total
  78073. size of the destination buffer, which must be large enough to hold the
  78074. entire uncompressed data. (The size of the uncompressed data must have
  78075. been saved previously by the compressor and transmitted to the decompressor
  78076. by some mechanism outside the scope of this compression library.)
  78077. Upon exit, destLen is the actual size of the compressed buffer.
  78078. This function can be used to decompress a whole file at once if the
  78079. input file is mmap'ed.
  78080. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78081. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78082. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78083. */
  78084. typedef voidp gzFile;
  78085. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78086. /*
  78087. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78088. is as in fopen ("rb" or "wb") but can also include a compression level
  78089. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78090. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78091. as in "wb1R". (See the description of deflateInit2 for more information
  78092. about the strategy parameter.)
  78093. gzopen can be used to read a file which is not in gzip format; in this
  78094. case gzread will directly read from the file without decompression.
  78095. gzopen returns NULL if the file could not be opened or if there was
  78096. insufficient memory to allocate the (de)compression state; errno
  78097. can be checked to distinguish the two cases (if errno is zero, the
  78098. zlib error is Z_MEM_ERROR). */
  78099. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78100. /*
  78101. gzdopen() associates a gzFile with the file descriptor fd. File
  78102. descriptors are obtained from calls like open, dup, creat, pipe or
  78103. fileno (in the file has been previously opened with fopen).
  78104. The mode parameter is as in gzopen.
  78105. The next call of gzclose on the returned gzFile will also close the
  78106. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  78107. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  78108. gzdopen returns NULL if there was insufficient memory to allocate
  78109. the (de)compression state.
  78110. */
  78111. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  78112. /*
  78113. Dynamically update the compression level or strategy. See the description
  78114. of deflateInit2 for the meaning of these parameters.
  78115. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  78116. opened for writing.
  78117. */
  78118. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  78119. /*
  78120. Reads the given number of uncompressed bytes from the compressed file.
  78121. If the input file was not in gzip format, gzread copies the given number
  78122. of bytes into the buffer.
  78123. gzread returns the number of uncompressed bytes actually read (0 for
  78124. end of file, -1 for error). */
  78125. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  78126. voidpc buf, unsigned len));
  78127. /*
  78128. Writes the given number of uncompressed bytes into the compressed file.
  78129. gzwrite returns the number of uncompressed bytes actually written
  78130. (0 in case of error).
  78131. */
  78132. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  78133. /*
  78134. Converts, formats, and writes the args to the compressed file under
  78135. control of the format string, as in fprintf. gzprintf returns the number of
  78136. uncompressed bytes actually written (0 in case of error). The number of
  78137. uncompressed bytes written is limited to 4095. The caller should assure that
  78138. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  78139. return an error (0) with nothing written. In this case, there may also be a
  78140. buffer overflow with unpredictable consequences, which is possible only if
  78141. zlib was compiled with the insecure functions sprintf() or vsprintf()
  78142. because the secure snprintf() or vsnprintf() functions were not available.
  78143. */
  78144. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  78145. /*
  78146. Writes the given null-terminated string to the compressed file, excluding
  78147. the terminating null character.
  78148. gzputs returns the number of characters written, or -1 in case of error.
  78149. */
  78150. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  78151. /*
  78152. Reads bytes from the compressed file until len-1 characters are read, or
  78153. a newline character is read and transferred to buf, or an end-of-file
  78154. condition is encountered. The string is then terminated with a null
  78155. character.
  78156. gzgets returns buf, or Z_NULL in case of error.
  78157. */
  78158. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  78159. /*
  78160. Writes c, converted to an unsigned char, into the compressed file.
  78161. gzputc returns the value that was written, or -1 in case of error.
  78162. */
  78163. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  78164. /*
  78165. Reads one byte from the compressed file. gzgetc returns this byte
  78166. or -1 in case of end of file or error.
  78167. */
  78168. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  78169. /*
  78170. Push one character back onto the stream to be read again later.
  78171. Only one character of push-back is allowed. gzungetc() returns the
  78172. character pushed, or -1 on failure. gzungetc() will fail if a
  78173. character has been pushed but not read yet, or if c is -1. The pushed
  78174. character will be discarded if the stream is repositioned with gzseek()
  78175. or gzrewind().
  78176. */
  78177. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  78178. /*
  78179. Flushes all pending output into the compressed file. The parameter
  78180. flush is as in the deflate() function. The return value is the zlib
  78181. error number (see function gzerror below). gzflush returns Z_OK if
  78182. the flush parameter is Z_FINISH and all output could be flushed.
  78183. gzflush should be called only when strictly necessary because it can
  78184. degrade compression.
  78185. */
  78186. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  78187. z_off_t offset, int whence));
  78188. /*
  78189. Sets the starting position for the next gzread or gzwrite on the
  78190. given compressed file. The offset represents a number of bytes in the
  78191. uncompressed data stream. The whence parameter is defined as in lseek(2);
  78192. the value SEEK_END is not supported.
  78193. If the file is opened for reading, this function is emulated but can be
  78194. extremely slow. If the file is opened for writing, only forward seeks are
  78195. supported; gzseek then compresses a sequence of zeroes up to the new
  78196. starting position.
  78197. gzseek returns the resulting offset location as measured in bytes from
  78198. the beginning of the uncompressed stream, or -1 in case of error, in
  78199. particular if the file is opened for writing and the new starting position
  78200. would be before the current position.
  78201. */
  78202. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  78203. /*
  78204. Rewinds the given file. This function is supported only for reading.
  78205. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  78206. */
  78207. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  78208. /*
  78209. Returns the starting position for the next gzread or gzwrite on the
  78210. given compressed file. This position represents a number of bytes in the
  78211. uncompressed data stream.
  78212. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  78213. */
  78214. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  78215. /*
  78216. Returns 1 when EOF has previously been detected reading the given
  78217. input stream, otherwise zero.
  78218. */
  78219. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  78220. /*
  78221. Returns 1 if file is being read directly without decompression, otherwise
  78222. zero.
  78223. */
  78224. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  78225. /*
  78226. Flushes all pending output if necessary, closes the compressed file
  78227. and deallocates all the (de)compression state. The return value is the zlib
  78228. error number (see function gzerror below).
  78229. */
  78230. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  78231. /*
  78232. Returns the error message for the last error which occurred on the
  78233. given compressed file. errnum is set to zlib error number. If an
  78234. error occurred in the file system and not in the compression library,
  78235. errnum is set to Z_ERRNO and the application may consult errno
  78236. to get the exact error code.
  78237. */
  78238. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  78239. /*
  78240. Clears the error and end-of-file flags for file. This is analogous to the
  78241. clearerr() function in stdio. This is useful for continuing to read a gzip
  78242. file that is being written concurrently.
  78243. */
  78244. /* checksum functions */
  78245. /*
  78246. These functions are not related to compression but are exported
  78247. anyway because they might be useful in applications using the
  78248. compression library.
  78249. */
  78250. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  78251. /*
  78252. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  78253. return the updated checksum. If buf is NULL, this function returns
  78254. the required initial value for the checksum.
  78255. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  78256. much faster. Usage example:
  78257. uLong adler = adler32(0L, Z_NULL, 0);
  78258. while (read_buffer(buffer, length) != EOF) {
  78259. adler = adler32(adler, buffer, length);
  78260. }
  78261. if (adler != original_adler) error();
  78262. */
  78263. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  78264. z_off_t len2));
  78265. /*
  78266. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  78267. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  78268. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  78269. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  78270. */
  78271. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  78272. /*
  78273. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  78274. updated CRC-32. If buf is NULL, this function returns the required initial
  78275. value for the for the crc. Pre- and post-conditioning (one's complement) is
  78276. performed within this function so it shouldn't be done by the application.
  78277. Usage example:
  78278. uLong crc = crc32(0L, Z_NULL, 0);
  78279. while (read_buffer(buffer, length) != EOF) {
  78280. crc = crc32(crc, buffer, length);
  78281. }
  78282. if (crc != original_crc) error();
  78283. */
  78284. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  78285. /*
  78286. Combine two CRC-32 check values into one. For two sequences of bytes,
  78287. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  78288. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  78289. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  78290. len2.
  78291. */
  78292. /* various hacks, don't look :) */
  78293. /* deflateInit and inflateInit are macros to allow checking the zlib version
  78294. * and the compiler's view of z_stream:
  78295. */
  78296. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  78297. const char *version, int stream_size));
  78298. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  78299. const char *version, int stream_size));
  78300. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  78301. int windowBits, int memLevel,
  78302. int strategy, const char *version,
  78303. int stream_size));
  78304. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  78305. const char *version, int stream_size));
  78306. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  78307. unsigned char FAR *window,
  78308. const char *version,
  78309. int stream_size));
  78310. #define deflateInit(strm, level) \
  78311. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  78312. #define inflateInit(strm) \
  78313. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  78314. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  78315. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  78316. (strategy), ZLIB_VERSION, sizeof(z_stream))
  78317. #define inflateInit2(strm, windowBits) \
  78318. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  78319. #define inflateBackInit(strm, windowBits, window) \
  78320. inflateBackInit_((strm), (windowBits), (window), \
  78321. ZLIB_VERSION, sizeof(z_stream))
  78322. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  78323. struct internal_state {int dummy;}; /* hack for buggy compilers */
  78324. #endif
  78325. ZEXTERN const char * ZEXPORT zError OF((int));
  78326. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  78327. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  78328. #ifdef __cplusplus
  78329. }
  78330. #endif
  78331. #endif /* ZLIB_H */
  78332. /*** End of inlined file: zlib.h ***/
  78333. #undef OS_CODE
  78334. #else
  78335. #include <zlib.h>
  78336. #endif
  78337. }
  78338. BEGIN_JUCE_NAMESPACE
  78339. // internal helper object that holds the zlib structures so they don't have to be
  78340. // included publicly.
  78341. class GZIPCompressorHelper
  78342. {
  78343. public:
  78344. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  78345. : data (0),
  78346. dataSize (0),
  78347. compLevel (compressionLevel),
  78348. strategy (0),
  78349. setParams (true),
  78350. streamIsValid (false),
  78351. finished (false),
  78352. shouldFinish (false)
  78353. {
  78354. using namespace zlibNamespace;
  78355. zerostruct (stream);
  78356. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  78357. nowrap ? -MAX_WBITS : MAX_WBITS,
  78358. 8, strategy) == Z_OK);
  78359. }
  78360. ~GZIPCompressorHelper()
  78361. {
  78362. using namespace zlibNamespace;
  78363. if (streamIsValid)
  78364. deflateEnd (&stream);
  78365. }
  78366. bool needsInput() const throw()
  78367. {
  78368. return dataSize <= 0;
  78369. }
  78370. void setInput (const uint8* const newData, const int size) throw()
  78371. {
  78372. data = newData;
  78373. dataSize = size;
  78374. }
  78375. int doNextBlock (uint8* const dest, const int destSize) throw()
  78376. {
  78377. using namespace zlibNamespace;
  78378. if (streamIsValid)
  78379. {
  78380. stream.next_in = const_cast <uint8*> (data);
  78381. stream.next_out = dest;
  78382. stream.avail_in = dataSize;
  78383. stream.avail_out = destSize;
  78384. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  78385. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  78386. setParams = false;
  78387. switch (result)
  78388. {
  78389. case Z_STREAM_END:
  78390. finished = true;
  78391. // Deliberate fall-through..
  78392. case Z_OK:
  78393. data += dataSize - stream.avail_in;
  78394. dataSize = stream.avail_in;
  78395. return destSize - stream.avail_out;
  78396. default:
  78397. break;
  78398. }
  78399. }
  78400. return 0;
  78401. }
  78402. private:
  78403. zlibNamespace::z_stream stream;
  78404. const uint8* data;
  78405. int dataSize, compLevel, strategy;
  78406. bool setParams, streamIsValid;
  78407. public:
  78408. bool finished, shouldFinish;
  78409. };
  78410. const int gzipCompBufferSize = 32768;
  78411. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  78412. int compressionLevel,
  78413. const bool deleteDestStream,
  78414. const bool noWrap)
  78415. : destStream (destStream_),
  78416. streamToDelete (deleteDestStream ? destStream_ : 0),
  78417. buffer (gzipCompBufferSize)
  78418. {
  78419. if (compressionLevel < 1 || compressionLevel > 9)
  78420. compressionLevel = -1;
  78421. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  78422. }
  78423. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  78424. {
  78425. flush();
  78426. }
  78427. void GZIPCompressorOutputStream::flush()
  78428. {
  78429. if (! helper->finished)
  78430. {
  78431. helper->shouldFinish = true;
  78432. while (! helper->finished)
  78433. doNextBlock();
  78434. }
  78435. destStream->flush();
  78436. }
  78437. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  78438. {
  78439. if (! helper->finished)
  78440. {
  78441. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  78442. while (! helper->needsInput())
  78443. {
  78444. if (! doNextBlock())
  78445. return false;
  78446. }
  78447. }
  78448. return true;
  78449. }
  78450. bool GZIPCompressorOutputStream::doNextBlock()
  78451. {
  78452. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  78453. if (len > 0)
  78454. return destStream->write (buffer, len);
  78455. else
  78456. return true;
  78457. }
  78458. int64 GZIPCompressorOutputStream::getPosition()
  78459. {
  78460. return destStream->getPosition();
  78461. }
  78462. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  78463. {
  78464. jassertfalse; // can't do it!
  78465. return false;
  78466. }
  78467. END_JUCE_NAMESPACE
  78468. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78469. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  78470. #if JUCE_MSVC
  78471. #pragma warning (push)
  78472. #pragma warning (disable: 4309 4305)
  78473. #endif
  78474. namespace zlibNamespace
  78475. {
  78476. #if JUCE_INCLUDE_ZLIB_CODE
  78477. extern "C"
  78478. {
  78479. #undef OS_CODE
  78480. #undef fdopen
  78481. #define ZLIB_INTERNAL
  78482. #define NO_DUMMY_DECL
  78483. /*** Start of inlined file: adler32.c ***/
  78484. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78485. #define ZLIB_INTERNAL
  78486. #define BASE 65521UL /* largest prime smaller than 65536 */
  78487. #define NMAX 5552
  78488. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  78489. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  78490. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  78491. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  78492. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  78493. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  78494. /* use NO_DIVIDE if your processor does not do division in hardware */
  78495. #ifdef NO_DIVIDE
  78496. # define MOD(a) \
  78497. do { \
  78498. if (a >= (BASE << 16)) a -= (BASE << 16); \
  78499. if (a >= (BASE << 15)) a -= (BASE << 15); \
  78500. if (a >= (BASE << 14)) a -= (BASE << 14); \
  78501. if (a >= (BASE << 13)) a -= (BASE << 13); \
  78502. if (a >= (BASE << 12)) a -= (BASE << 12); \
  78503. if (a >= (BASE << 11)) a -= (BASE << 11); \
  78504. if (a >= (BASE << 10)) a -= (BASE << 10); \
  78505. if (a >= (BASE << 9)) a -= (BASE << 9); \
  78506. if (a >= (BASE << 8)) a -= (BASE << 8); \
  78507. if (a >= (BASE << 7)) a -= (BASE << 7); \
  78508. if (a >= (BASE << 6)) a -= (BASE << 6); \
  78509. if (a >= (BASE << 5)) a -= (BASE << 5); \
  78510. if (a >= (BASE << 4)) a -= (BASE << 4); \
  78511. if (a >= (BASE << 3)) a -= (BASE << 3); \
  78512. if (a >= (BASE << 2)) a -= (BASE << 2); \
  78513. if (a >= (BASE << 1)) a -= (BASE << 1); \
  78514. if (a >= BASE) a -= BASE; \
  78515. } while (0)
  78516. # define MOD4(a) \
  78517. do { \
  78518. if (a >= (BASE << 4)) a -= (BASE << 4); \
  78519. if (a >= (BASE << 3)) a -= (BASE << 3); \
  78520. if (a >= (BASE << 2)) a -= (BASE << 2); \
  78521. if (a >= (BASE << 1)) a -= (BASE << 1); \
  78522. if (a >= BASE) a -= BASE; \
  78523. } while (0)
  78524. #else
  78525. # define MOD(a) a %= BASE
  78526. # define MOD4(a) a %= BASE
  78527. #endif
  78528. /* ========================================================================= */
  78529. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  78530. {
  78531. unsigned long sum2;
  78532. unsigned n;
  78533. /* split Adler-32 into component sums */
  78534. sum2 = (adler >> 16) & 0xffff;
  78535. adler &= 0xffff;
  78536. /* in case user likes doing a byte at a time, keep it fast */
  78537. if (len == 1) {
  78538. adler += buf[0];
  78539. if (adler >= BASE)
  78540. adler -= BASE;
  78541. sum2 += adler;
  78542. if (sum2 >= BASE)
  78543. sum2 -= BASE;
  78544. return adler | (sum2 << 16);
  78545. }
  78546. /* initial Adler-32 value (deferred check for len == 1 speed) */
  78547. if (buf == Z_NULL)
  78548. return 1L;
  78549. /* in case short lengths are provided, keep it somewhat fast */
  78550. if (len < 16) {
  78551. while (len--) {
  78552. adler += *buf++;
  78553. sum2 += adler;
  78554. }
  78555. if (adler >= BASE)
  78556. adler -= BASE;
  78557. MOD4(sum2); /* only added so many BASE's */
  78558. return adler | (sum2 << 16);
  78559. }
  78560. /* do length NMAX blocks -- requires just one modulo operation */
  78561. while (len >= NMAX) {
  78562. len -= NMAX;
  78563. n = NMAX / 16; /* NMAX is divisible by 16 */
  78564. do {
  78565. DO16(buf); /* 16 sums unrolled */
  78566. buf += 16;
  78567. } while (--n);
  78568. MOD(adler);
  78569. MOD(sum2);
  78570. }
  78571. /* do remaining bytes (less than NMAX, still just one modulo) */
  78572. if (len) { /* avoid modulos if none remaining */
  78573. while (len >= 16) {
  78574. len -= 16;
  78575. DO16(buf);
  78576. buf += 16;
  78577. }
  78578. while (len--) {
  78579. adler += *buf++;
  78580. sum2 += adler;
  78581. }
  78582. MOD(adler);
  78583. MOD(sum2);
  78584. }
  78585. /* return recombined sums */
  78586. return adler | (sum2 << 16);
  78587. }
  78588. /* ========================================================================= */
  78589. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  78590. {
  78591. unsigned long sum1;
  78592. unsigned long sum2;
  78593. unsigned rem;
  78594. /* the derivation of this formula is left as an exercise for the reader */
  78595. rem = (unsigned)(len2 % BASE);
  78596. sum1 = adler1 & 0xffff;
  78597. sum2 = rem * sum1;
  78598. MOD(sum2);
  78599. sum1 += (adler2 & 0xffff) + BASE - 1;
  78600. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  78601. if (sum1 > BASE) sum1 -= BASE;
  78602. if (sum1 > BASE) sum1 -= BASE;
  78603. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  78604. if (sum2 > BASE) sum2 -= BASE;
  78605. return sum1 | (sum2 << 16);
  78606. }
  78607. /*** End of inlined file: adler32.c ***/
  78608. /*** Start of inlined file: compress.c ***/
  78609. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78610. #define ZLIB_INTERNAL
  78611. /* ===========================================================================
  78612. Compresses the source buffer into the destination buffer. The level
  78613. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78614. length of the source buffer. Upon entry, destLen is the total size of the
  78615. destination buffer, which must be at least 0.1% larger than sourceLen plus
  78616. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  78617. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78618. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78619. Z_STREAM_ERROR if the level parameter is invalid.
  78620. */
  78621. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  78622. uLong sourceLen, int level)
  78623. {
  78624. z_stream stream;
  78625. int err;
  78626. stream.next_in = (Bytef*)source;
  78627. stream.avail_in = (uInt)sourceLen;
  78628. #ifdef MAXSEG_64K
  78629. /* Check for source > 64K on 16-bit machine: */
  78630. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  78631. #endif
  78632. stream.next_out = dest;
  78633. stream.avail_out = (uInt)*destLen;
  78634. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  78635. stream.zalloc = (alloc_func)0;
  78636. stream.zfree = (free_func)0;
  78637. stream.opaque = (voidpf)0;
  78638. err = deflateInit(&stream, level);
  78639. if (err != Z_OK) return err;
  78640. err = deflate(&stream, Z_FINISH);
  78641. if (err != Z_STREAM_END) {
  78642. deflateEnd(&stream);
  78643. return err == Z_OK ? Z_BUF_ERROR : err;
  78644. }
  78645. *destLen = stream.total_out;
  78646. err = deflateEnd(&stream);
  78647. return err;
  78648. }
  78649. /* ===========================================================================
  78650. */
  78651. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  78652. {
  78653. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  78654. }
  78655. /* ===========================================================================
  78656. If the default memLevel or windowBits for deflateInit() is changed, then
  78657. this function needs to be updated.
  78658. */
  78659. uLong ZEXPORT compressBound (uLong sourceLen)
  78660. {
  78661. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  78662. }
  78663. /*** End of inlined file: compress.c ***/
  78664. #undef DO1
  78665. #undef DO8
  78666. /*** Start of inlined file: crc32.c ***/
  78667. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78668. /*
  78669. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  78670. protection on the static variables used to control the first-use generation
  78671. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  78672. first call get_crc_table() to initialize the tables before allowing more than
  78673. one thread to use crc32().
  78674. */
  78675. #ifdef MAKECRCH
  78676. # include <stdio.h>
  78677. # ifndef DYNAMIC_CRC_TABLE
  78678. # define DYNAMIC_CRC_TABLE
  78679. # endif /* !DYNAMIC_CRC_TABLE */
  78680. #endif /* MAKECRCH */
  78681. /*** Start of inlined file: zutil.h ***/
  78682. /* WARNING: this file should *not* be used by applications. It is
  78683. part of the implementation of the compression library and is
  78684. subject to change. Applications should only use zlib.h.
  78685. */
  78686. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78687. #ifndef ZUTIL_H
  78688. #define ZUTIL_H
  78689. #define ZLIB_INTERNAL
  78690. #ifdef STDC
  78691. # ifndef _WIN32_WCE
  78692. # include <stddef.h>
  78693. # endif
  78694. # include <string.h>
  78695. # include <stdlib.h>
  78696. #endif
  78697. #ifdef NO_ERRNO_H
  78698. # ifdef _WIN32_WCE
  78699. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  78700. * errno. We define it as a global variable to simplify porting.
  78701. * Its value is always 0 and should not be used. We rename it to
  78702. * avoid conflict with other libraries that use the same workaround.
  78703. */
  78704. # define errno z_errno
  78705. # endif
  78706. extern int errno;
  78707. #else
  78708. # ifndef _WIN32_WCE
  78709. # include <errno.h>
  78710. # endif
  78711. #endif
  78712. #ifndef local
  78713. # define local static
  78714. #endif
  78715. /* compile with -Dlocal if your debugger can't find static symbols */
  78716. typedef unsigned char uch;
  78717. typedef uch FAR uchf;
  78718. typedef unsigned short ush;
  78719. typedef ush FAR ushf;
  78720. typedef unsigned long ulg;
  78721. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  78722. /* (size given to avoid silly warnings with Visual C++) */
  78723. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  78724. #define ERR_RETURN(strm,err) \
  78725. return (strm->msg = (char*)ERR_MSG(err), (err))
  78726. /* To be used only when the state is known to be valid */
  78727. /* common constants */
  78728. #ifndef DEF_WBITS
  78729. # define DEF_WBITS MAX_WBITS
  78730. #endif
  78731. /* default windowBits for decompression. MAX_WBITS is for compression only */
  78732. #if MAX_MEM_LEVEL >= 8
  78733. # define DEF_MEM_LEVEL 8
  78734. #else
  78735. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  78736. #endif
  78737. /* default memLevel */
  78738. #define STORED_BLOCK 0
  78739. #define STATIC_TREES 1
  78740. #define DYN_TREES 2
  78741. /* The three kinds of block type */
  78742. #define MIN_MATCH 3
  78743. #define MAX_MATCH 258
  78744. /* The minimum and maximum match lengths */
  78745. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  78746. /* target dependencies */
  78747. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  78748. # define OS_CODE 0x00
  78749. # if defined(__TURBOC__) || defined(__BORLANDC__)
  78750. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  78751. /* Allow compilation with ANSI keywords only enabled */
  78752. void _Cdecl farfree( void *block );
  78753. void *_Cdecl farmalloc( unsigned long nbytes );
  78754. # else
  78755. # include <alloc.h>
  78756. # endif
  78757. # else /* MSC or DJGPP */
  78758. # include <malloc.h>
  78759. # endif
  78760. #endif
  78761. #ifdef AMIGA
  78762. # define OS_CODE 0x01
  78763. #endif
  78764. #if defined(VAXC) || defined(VMS)
  78765. # define OS_CODE 0x02
  78766. # define F_OPEN(name, mode) \
  78767. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  78768. #endif
  78769. #if defined(ATARI) || defined(atarist)
  78770. # define OS_CODE 0x05
  78771. #endif
  78772. #ifdef OS2
  78773. # define OS_CODE 0x06
  78774. # ifdef M_I86
  78775. #include <malloc.h>
  78776. # endif
  78777. #endif
  78778. #if defined(MACOS) || TARGET_OS_MAC
  78779. # define OS_CODE 0x07
  78780. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  78781. # include <unix.h> /* for fdopen */
  78782. # else
  78783. # ifndef fdopen
  78784. # define fdopen(fd,mode) NULL /* No fdopen() */
  78785. # endif
  78786. # endif
  78787. #endif
  78788. #ifdef TOPS20
  78789. # define OS_CODE 0x0a
  78790. #endif
  78791. #ifdef WIN32
  78792. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  78793. # define OS_CODE 0x0b
  78794. # endif
  78795. #endif
  78796. #ifdef __50SERIES /* Prime/PRIMOS */
  78797. # define OS_CODE 0x0f
  78798. #endif
  78799. #if defined(_BEOS_) || defined(RISCOS)
  78800. # define fdopen(fd,mode) NULL /* No fdopen() */
  78801. #endif
  78802. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  78803. # if defined(_WIN32_WCE)
  78804. # define fdopen(fd,mode) NULL /* No fdopen() */
  78805. # ifndef _PTRDIFF_T_DEFINED
  78806. typedef int ptrdiff_t;
  78807. # define _PTRDIFF_T_DEFINED
  78808. # endif
  78809. # else
  78810. # define fdopen(fd,type) _fdopen(fd,type)
  78811. # endif
  78812. #endif
  78813. /* common defaults */
  78814. #ifndef OS_CODE
  78815. # define OS_CODE 0x03 /* assume Unix */
  78816. #endif
  78817. #ifndef F_OPEN
  78818. # define F_OPEN(name, mode) fopen((name), (mode))
  78819. #endif
  78820. /* functions */
  78821. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  78822. # ifndef HAVE_VSNPRINTF
  78823. # define HAVE_VSNPRINTF
  78824. # endif
  78825. #endif
  78826. #if defined(__CYGWIN__)
  78827. # ifndef HAVE_VSNPRINTF
  78828. # define HAVE_VSNPRINTF
  78829. # endif
  78830. #endif
  78831. #ifndef HAVE_VSNPRINTF
  78832. # ifdef MSDOS
  78833. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  78834. but for now we just assume it doesn't. */
  78835. # define NO_vsnprintf
  78836. # endif
  78837. # ifdef __TURBOC__
  78838. # define NO_vsnprintf
  78839. # endif
  78840. # ifdef WIN32
  78841. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  78842. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  78843. # define vsnprintf _vsnprintf
  78844. # endif
  78845. # endif
  78846. # ifdef __SASC
  78847. # define NO_vsnprintf
  78848. # endif
  78849. #endif
  78850. #ifdef VMS
  78851. # define NO_vsnprintf
  78852. #endif
  78853. #if defined(pyr)
  78854. # define NO_MEMCPY
  78855. #endif
  78856. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  78857. /* Use our own functions for small and medium model with MSC <= 5.0.
  78858. * You may have to use the same strategy for Borland C (untested).
  78859. * The __SC__ check is for Symantec.
  78860. */
  78861. # define NO_MEMCPY
  78862. #endif
  78863. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  78864. # define HAVE_MEMCPY
  78865. #endif
  78866. #ifdef HAVE_MEMCPY
  78867. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  78868. # define zmemcpy _fmemcpy
  78869. # define zmemcmp _fmemcmp
  78870. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  78871. # else
  78872. # define zmemcpy memcpy
  78873. # define zmemcmp memcmp
  78874. # define zmemzero(dest, len) memset(dest, 0, len)
  78875. # endif
  78876. #else
  78877. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  78878. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  78879. extern void zmemzero OF((Bytef* dest, uInt len));
  78880. #endif
  78881. /* Diagnostic functions */
  78882. #ifdef DEBUG
  78883. # include <stdio.h>
  78884. extern int z_verbose;
  78885. extern void z_error OF((const char *m));
  78886. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  78887. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  78888. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  78889. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  78890. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  78891. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  78892. #else
  78893. # define Assert(cond,msg)
  78894. # define Trace(x)
  78895. # define Tracev(x)
  78896. # define Tracevv(x)
  78897. # define Tracec(c,x)
  78898. # define Tracecv(c,x)
  78899. #endif
  78900. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  78901. void zcfree OF((voidpf opaque, voidpf ptr));
  78902. #define ZALLOC(strm, items, size) \
  78903. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  78904. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  78905. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  78906. #endif /* ZUTIL_H */
  78907. /*** End of inlined file: zutil.h ***/
  78908. /* for STDC and FAR definitions */
  78909. #define local static
  78910. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  78911. #ifndef NOBYFOUR
  78912. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  78913. # include <limits.h>
  78914. # define BYFOUR
  78915. # if (UINT_MAX == 0xffffffffUL)
  78916. typedef unsigned int u4;
  78917. # else
  78918. # if (ULONG_MAX == 0xffffffffUL)
  78919. typedef unsigned long u4;
  78920. # else
  78921. # if (USHRT_MAX == 0xffffffffUL)
  78922. typedef unsigned short u4;
  78923. # else
  78924. # undef BYFOUR /* can't find a four-byte integer type! */
  78925. # endif
  78926. # endif
  78927. # endif
  78928. # endif /* STDC */
  78929. #endif /* !NOBYFOUR */
  78930. /* Definitions for doing the crc four data bytes at a time. */
  78931. #ifdef BYFOUR
  78932. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  78933. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  78934. local unsigned long crc32_little OF((unsigned long,
  78935. const unsigned char FAR *, unsigned));
  78936. local unsigned long crc32_big OF((unsigned long,
  78937. const unsigned char FAR *, unsigned));
  78938. # define TBLS 8
  78939. #else
  78940. # define TBLS 1
  78941. #endif /* BYFOUR */
  78942. /* Local functions for crc concatenation */
  78943. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  78944. unsigned long vec));
  78945. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  78946. #ifdef DYNAMIC_CRC_TABLE
  78947. local volatile int crc_table_empty = 1;
  78948. local unsigned long FAR crc_table[TBLS][256];
  78949. local void make_crc_table OF((void));
  78950. #ifdef MAKECRCH
  78951. local void write_table OF((FILE *, const unsigned long FAR *));
  78952. #endif /* MAKECRCH */
  78953. /*
  78954. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  78955. x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
  78956. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  78957. with the lowest powers in the most significant bit. Then adding polynomials
  78958. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  78959. one. If we call the above polynomial p, and represent a byte as the
  78960. polynomial q, also with the lowest power in the most significant bit (so the
  78961. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  78962. where a mod b means the remainder after dividing a by b.
  78963. This calculation is done using the shift-register method of multiplying and
  78964. taking the remainder. The register is initialized to zero, and for each
  78965. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  78966. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  78967. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  78968. out is a one). We start with the highest power (least significant bit) of
  78969. q and repeat for all eight bits of q.
  78970. The first table is simply the CRC of all possible eight bit values. This is
  78971. all the information needed to generate CRCs on data a byte at a time for all
  78972. combinations of CRC register values and incoming bytes. The remaining tables
  78973. allow for word-at-a-time CRC calculation for both big-endian and little-
  78974. endian machines, where a word is four bytes.
  78975. */
  78976. local void make_crc_table()
  78977. {
  78978. unsigned long c;
  78979. int n, k;
  78980. unsigned long poly; /* polynomial exclusive-or pattern */
  78981. /* terms of polynomial defining this crc (except x^32): */
  78982. static volatile int first = 1; /* flag to limit concurrent making */
  78983. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  78984. /* See if another task is already doing this (not thread-safe, but better
  78985. than nothing -- significantly reduces duration of vulnerability in
  78986. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  78987. if (first) {
  78988. first = 0;
  78989. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  78990. poly = 0UL;
  78991. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  78992. poly |= 1UL << (31 - p[n]);
  78993. /* generate a crc for every 8-bit value */
  78994. for (n = 0; n < 256; n++) {
  78995. c = (unsigned long)n;
  78996. for (k = 0; k < 8; k++)
  78997. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  78998. crc_table[0][n] = c;
  78999. }
  79000. #ifdef BYFOUR
  79001. /* generate crc for each value followed by one, two, and three zeros,
  79002. and then the byte reversal of those as well as the first table */
  79003. for (n = 0; n < 256; n++) {
  79004. c = crc_table[0][n];
  79005. crc_table[4][n] = REV(c);
  79006. for (k = 1; k < 4; k++) {
  79007. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79008. crc_table[k][n] = c;
  79009. crc_table[k + 4][n] = REV(c);
  79010. }
  79011. }
  79012. #endif /* BYFOUR */
  79013. crc_table_empty = 0;
  79014. }
  79015. else { /* not first */
  79016. /* wait for the other guy to finish (not efficient, but rare) */
  79017. while (crc_table_empty)
  79018. ;
  79019. }
  79020. #ifdef MAKECRCH
  79021. /* write out CRC tables to crc32.h */
  79022. {
  79023. FILE *out;
  79024. out = fopen("crc32.h", "w");
  79025. if (out == NULL) return;
  79026. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79027. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79028. fprintf(out, "local const unsigned long FAR ");
  79029. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79030. write_table(out, crc_table[0]);
  79031. # ifdef BYFOUR
  79032. fprintf(out, "#ifdef BYFOUR\n");
  79033. for (k = 1; k < 8; k++) {
  79034. fprintf(out, " },\n {\n");
  79035. write_table(out, crc_table[k]);
  79036. }
  79037. fprintf(out, "#endif\n");
  79038. # endif /* BYFOUR */
  79039. fprintf(out, " }\n};\n");
  79040. fclose(out);
  79041. }
  79042. #endif /* MAKECRCH */
  79043. }
  79044. #ifdef MAKECRCH
  79045. local void write_table(out, table)
  79046. FILE *out;
  79047. const unsigned long FAR *table;
  79048. {
  79049. int n;
  79050. for (n = 0; n < 256; n++)
  79051. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79052. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79053. }
  79054. #endif /* MAKECRCH */
  79055. #else /* !DYNAMIC_CRC_TABLE */
  79056. /* ========================================================================
  79057. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79058. */
  79059. /*** Start of inlined file: crc32.h ***/
  79060. local const unsigned long FAR crc_table[TBLS][256] =
  79061. {
  79062. {
  79063. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79064. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79065. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79066. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79067. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79068. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79069. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79070. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79071. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79072. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79073. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79074. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79075. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79076. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79077. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79078. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79079. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79080. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79081. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79082. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79083. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79084. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79085. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79086. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79087. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79088. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79089. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79090. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79091. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79092. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79093. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79094. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79095. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79096. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79097. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79098. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79099. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79100. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79101. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79102. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79103. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79104. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79105. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79106. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79107. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79108. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79109. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79110. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79111. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79112. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79113. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  79114. 0x2d02ef8dUL
  79115. #ifdef BYFOUR
  79116. },
  79117. {
  79118. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  79119. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  79120. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  79121. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  79122. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  79123. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  79124. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  79125. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  79126. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  79127. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  79128. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  79129. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  79130. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  79131. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  79132. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  79133. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  79134. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  79135. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  79136. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  79137. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  79138. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  79139. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  79140. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  79141. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  79142. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  79143. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  79144. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  79145. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  79146. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  79147. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  79148. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  79149. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  79150. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  79151. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  79152. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  79153. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  79154. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  79155. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  79156. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  79157. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  79158. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  79159. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  79160. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  79161. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  79162. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  79163. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  79164. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  79165. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  79166. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  79167. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  79168. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  79169. 0x9324fd72UL
  79170. },
  79171. {
  79172. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  79173. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  79174. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  79175. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  79176. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  79177. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  79178. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  79179. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  79180. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  79181. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  79182. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  79183. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  79184. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  79185. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  79186. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  79187. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  79188. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  79189. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  79190. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  79191. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  79192. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  79193. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  79194. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  79195. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  79196. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  79197. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  79198. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  79199. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  79200. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  79201. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  79202. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  79203. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  79204. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  79205. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  79206. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  79207. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  79208. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  79209. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  79210. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  79211. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  79212. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  79213. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  79214. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  79215. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  79216. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  79217. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  79218. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  79219. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  79220. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  79221. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  79222. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  79223. 0xbe9834edUL
  79224. },
  79225. {
  79226. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  79227. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  79228. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  79229. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  79230. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  79231. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  79232. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  79233. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  79234. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  79235. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  79236. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  79237. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  79238. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  79239. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  79240. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  79241. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  79242. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  79243. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  79244. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  79245. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  79246. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  79247. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  79248. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  79249. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  79250. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  79251. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  79252. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  79253. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  79254. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  79255. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  79256. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  79257. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  79258. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  79259. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  79260. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  79261. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  79262. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  79263. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  79264. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  79265. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  79266. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  79267. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  79268. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  79269. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  79270. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  79271. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  79272. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  79273. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  79274. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  79275. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  79276. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  79277. 0xde0506f1UL
  79278. },
  79279. {
  79280. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  79281. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  79282. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  79283. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  79284. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  79285. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  79286. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  79287. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  79288. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  79289. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  79290. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  79291. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  79292. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  79293. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  79294. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  79295. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  79296. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  79297. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  79298. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  79299. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  79300. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  79301. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  79302. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  79303. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  79304. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  79305. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  79306. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  79307. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  79308. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  79309. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  79310. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  79311. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  79312. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  79313. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  79314. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  79315. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  79316. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  79317. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  79318. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  79319. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  79320. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  79321. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  79322. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  79323. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  79324. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  79325. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  79326. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  79327. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  79328. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  79329. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  79330. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  79331. 0x8def022dUL
  79332. },
  79333. {
  79334. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  79335. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  79336. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  79337. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  79338. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  79339. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  79340. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  79341. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  79342. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  79343. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  79344. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  79345. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  79346. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  79347. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  79348. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  79349. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  79350. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  79351. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  79352. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  79353. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  79354. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  79355. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  79356. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  79357. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  79358. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  79359. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  79360. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  79361. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  79362. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  79363. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  79364. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  79365. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  79366. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  79367. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  79368. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  79369. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  79370. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  79371. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  79372. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  79373. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  79374. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  79375. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  79376. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  79377. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  79378. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  79379. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  79380. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  79381. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  79382. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  79383. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  79384. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  79385. 0x72fd2493UL
  79386. },
  79387. {
  79388. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  79389. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  79390. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  79391. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  79392. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  79393. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  79394. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  79395. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  79396. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  79397. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  79398. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  79399. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  79400. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  79401. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  79402. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  79403. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  79404. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  79405. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  79406. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  79407. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  79408. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  79409. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  79410. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  79411. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  79412. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  79413. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  79414. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  79415. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  79416. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  79417. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  79418. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  79419. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  79420. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  79421. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  79422. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  79423. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  79424. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  79425. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  79426. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  79427. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  79428. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  79429. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  79430. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  79431. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  79432. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  79433. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  79434. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  79435. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  79436. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  79437. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  79438. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  79439. 0xed3498beUL
  79440. },
  79441. {
  79442. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  79443. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  79444. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  79445. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  79446. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  79447. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  79448. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  79449. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  79450. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  79451. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  79452. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  79453. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  79454. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  79455. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  79456. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  79457. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  79458. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  79459. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  79460. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  79461. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  79462. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  79463. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  79464. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  79465. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  79466. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  79467. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  79468. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  79469. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  79470. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  79471. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  79472. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  79473. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  79474. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  79475. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  79476. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  79477. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  79478. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  79479. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  79480. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  79481. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  79482. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  79483. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  79484. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  79485. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  79486. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  79487. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  79488. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  79489. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  79490. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  79491. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  79492. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  79493. 0xf10605deUL
  79494. #endif
  79495. }
  79496. };
  79497. /*** End of inlined file: crc32.h ***/
  79498. #endif /* DYNAMIC_CRC_TABLE */
  79499. /* =========================================================================
  79500. * This function can be used by asm versions of crc32()
  79501. */
  79502. const unsigned long FAR * ZEXPORT get_crc_table()
  79503. {
  79504. #ifdef DYNAMIC_CRC_TABLE
  79505. if (crc_table_empty)
  79506. make_crc_table();
  79507. #endif /* DYNAMIC_CRC_TABLE */
  79508. return (const unsigned long FAR *)crc_table;
  79509. }
  79510. /* ========================================================================= */
  79511. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  79512. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  79513. /* ========================================================================= */
  79514. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79515. {
  79516. if (buf == Z_NULL) return 0UL;
  79517. #ifdef DYNAMIC_CRC_TABLE
  79518. if (crc_table_empty)
  79519. make_crc_table();
  79520. #endif /* DYNAMIC_CRC_TABLE */
  79521. #ifdef BYFOUR
  79522. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  79523. u4 endian;
  79524. endian = 1;
  79525. if (*((unsigned char *)(&endian)))
  79526. return crc32_little(crc, buf, len);
  79527. else
  79528. return crc32_big(crc, buf, len);
  79529. }
  79530. #endif /* BYFOUR */
  79531. crc = crc ^ 0xffffffffUL;
  79532. while (len >= 8) {
  79533. DO8;
  79534. len -= 8;
  79535. }
  79536. if (len) do {
  79537. DO1;
  79538. } while (--len);
  79539. return crc ^ 0xffffffffUL;
  79540. }
  79541. #ifdef BYFOUR
  79542. /* ========================================================================= */
  79543. #define DOLIT4 c ^= *buf4++; \
  79544. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  79545. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  79546. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  79547. /* ========================================================================= */
  79548. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79549. {
  79550. register u4 c;
  79551. register const u4 FAR *buf4;
  79552. c = (u4)crc;
  79553. c = ~c;
  79554. while (len && ((ptrdiff_t)buf & 3)) {
  79555. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  79556. len--;
  79557. }
  79558. buf4 = (const u4 FAR *)(const void FAR *)buf;
  79559. while (len >= 32) {
  79560. DOLIT32;
  79561. len -= 32;
  79562. }
  79563. while (len >= 4) {
  79564. DOLIT4;
  79565. len -= 4;
  79566. }
  79567. buf = (const unsigned char FAR *)buf4;
  79568. if (len) do {
  79569. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  79570. } while (--len);
  79571. c = ~c;
  79572. return (unsigned long)c;
  79573. }
  79574. /* ========================================================================= */
  79575. #define DOBIG4 c ^= *++buf4; \
  79576. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  79577. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  79578. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  79579. /* ========================================================================= */
  79580. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79581. {
  79582. register u4 c;
  79583. register const u4 FAR *buf4;
  79584. c = REV((u4)crc);
  79585. c = ~c;
  79586. while (len && ((ptrdiff_t)buf & 3)) {
  79587. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  79588. len--;
  79589. }
  79590. buf4 = (const u4 FAR *)(const void FAR *)buf;
  79591. buf4--;
  79592. while (len >= 32) {
  79593. DOBIG32;
  79594. len -= 32;
  79595. }
  79596. while (len >= 4) {
  79597. DOBIG4;
  79598. len -= 4;
  79599. }
  79600. buf4++;
  79601. buf = (const unsigned char FAR *)buf4;
  79602. if (len) do {
  79603. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  79604. } while (--len);
  79605. c = ~c;
  79606. return (unsigned long)(REV(c));
  79607. }
  79608. #endif /* BYFOUR */
  79609. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  79610. /* ========================================================================= */
  79611. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  79612. {
  79613. unsigned long sum;
  79614. sum = 0;
  79615. while (vec) {
  79616. if (vec & 1)
  79617. sum ^= *mat;
  79618. vec >>= 1;
  79619. mat++;
  79620. }
  79621. return sum;
  79622. }
  79623. /* ========================================================================= */
  79624. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  79625. {
  79626. int n;
  79627. for (n = 0; n < GF2_DIM; n++)
  79628. square[n] = gf2_matrix_times(mat, mat[n]);
  79629. }
  79630. /* ========================================================================= */
  79631. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  79632. {
  79633. int n;
  79634. unsigned long row;
  79635. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  79636. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  79637. /* degenerate case */
  79638. if (len2 == 0)
  79639. return crc1;
  79640. /* put operator for one zero bit in odd */
  79641. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  79642. row = 1;
  79643. for (n = 1; n < GF2_DIM; n++) {
  79644. odd[n] = row;
  79645. row <<= 1;
  79646. }
  79647. /* put operator for two zero bits in even */
  79648. gf2_matrix_square(even, odd);
  79649. /* put operator for four zero bits in odd */
  79650. gf2_matrix_square(odd, even);
  79651. /* apply len2 zeros to crc1 (first square will put the operator for one
  79652. zero byte, eight zero bits, in even) */
  79653. do {
  79654. /* apply zeros operator for this bit of len2 */
  79655. gf2_matrix_square(even, odd);
  79656. if (len2 & 1)
  79657. crc1 = gf2_matrix_times(even, crc1);
  79658. len2 >>= 1;
  79659. /* if no more bits set, then done */
  79660. if (len2 == 0)
  79661. break;
  79662. /* another iteration of the loop with odd and even swapped */
  79663. gf2_matrix_square(odd, even);
  79664. if (len2 & 1)
  79665. crc1 = gf2_matrix_times(odd, crc1);
  79666. len2 >>= 1;
  79667. /* if no more bits set, then done */
  79668. } while (len2 != 0);
  79669. /* return combined crc */
  79670. crc1 ^= crc2;
  79671. return crc1;
  79672. }
  79673. /*** End of inlined file: crc32.c ***/
  79674. /*** Start of inlined file: deflate.c ***/
  79675. /*
  79676. * ALGORITHM
  79677. *
  79678. * The "deflation" process depends on being able to identify portions
  79679. * of the input text which are identical to earlier input (within a
  79680. * sliding window trailing behind the input currently being processed).
  79681. *
  79682. * The most straightforward technique turns out to be the fastest for
  79683. * most input files: try all possible matches and select the longest.
  79684. * The key feature of this algorithm is that insertions into the string
  79685. * dictionary are very simple and thus fast, and deletions are avoided
  79686. * completely. Insertions are performed at each input character, whereas
  79687. * string matches are performed only when the previous match ends. So it
  79688. * is preferable to spend more time in matches to allow very fast string
  79689. * insertions and avoid deletions. The matching algorithm for small
  79690. * strings is inspired from that of Rabin & Karp. A brute force approach
  79691. * is used to find longer strings when a small match has been found.
  79692. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  79693. * (by Leonid Broukhis).
  79694. * A previous version of this file used a more sophisticated algorithm
  79695. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  79696. * time, but has a larger average cost, uses more memory and is patented.
  79697. * However the F&G algorithm may be faster for some highly redundant
  79698. * files if the parameter max_chain_length (described below) is too large.
  79699. *
  79700. * ACKNOWLEDGEMENTS
  79701. *
  79702. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  79703. * I found it in 'freeze' written by Leonid Broukhis.
  79704. * Thanks to many people for bug reports and testing.
  79705. *
  79706. * REFERENCES
  79707. *
  79708. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  79709. * Available in http://www.ietf.org/rfc/rfc1951.txt
  79710. *
  79711. * A description of the Rabin and Karp algorithm is given in the book
  79712. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  79713. *
  79714. * Fiala,E.R., and Greene,D.H.
  79715. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  79716. *
  79717. */
  79718. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79719. /*** Start of inlined file: deflate.h ***/
  79720. /* WARNING: this file should *not* be used by applications. It is
  79721. part of the implementation of the compression library and is
  79722. subject to change. Applications should only use zlib.h.
  79723. */
  79724. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79725. #ifndef DEFLATE_H
  79726. #define DEFLATE_H
  79727. /* define NO_GZIP when compiling if you want to disable gzip header and
  79728. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  79729. the crc code when it is not needed. For shared libraries, gzip encoding
  79730. should be left enabled. */
  79731. #ifndef NO_GZIP
  79732. # define GZIP
  79733. #endif
  79734. #define NO_DUMMY_DECL
  79735. /* ===========================================================================
  79736. * Internal compression state.
  79737. */
  79738. #define LENGTH_CODES 29
  79739. /* number of length codes, not counting the special END_BLOCK code */
  79740. #define LITERALS 256
  79741. /* number of literal bytes 0..255 */
  79742. #define L_CODES (LITERALS+1+LENGTH_CODES)
  79743. /* number of Literal or Length codes, including the END_BLOCK code */
  79744. #define D_CODES 30
  79745. /* number of distance codes */
  79746. #define BL_CODES 19
  79747. /* number of codes used to transfer the bit lengths */
  79748. #define HEAP_SIZE (2*L_CODES+1)
  79749. /* maximum heap size */
  79750. #define MAX_BITS 15
  79751. /* All codes must not exceed MAX_BITS bits */
  79752. #define INIT_STATE 42
  79753. #define EXTRA_STATE 69
  79754. #define NAME_STATE 73
  79755. #define COMMENT_STATE 91
  79756. #define HCRC_STATE 103
  79757. #define BUSY_STATE 113
  79758. #define FINISH_STATE 666
  79759. /* Stream status */
  79760. /* Data structure describing a single value and its code string. */
  79761. typedef struct ct_data_s {
  79762. union {
  79763. ush freq; /* frequency count */
  79764. ush code; /* bit string */
  79765. } fc;
  79766. union {
  79767. ush dad; /* father node in Huffman tree */
  79768. ush len; /* length of bit string */
  79769. } dl;
  79770. } FAR ct_data;
  79771. #define Freq fc.freq
  79772. #define Code fc.code
  79773. #define Dad dl.dad
  79774. #define Len dl.len
  79775. typedef struct static_tree_desc_s static_tree_desc;
  79776. typedef struct tree_desc_s {
  79777. ct_data *dyn_tree; /* the dynamic tree */
  79778. int max_code; /* largest code with non zero frequency */
  79779. static_tree_desc *stat_desc; /* the corresponding static tree */
  79780. } FAR tree_desc;
  79781. typedef ush Pos;
  79782. typedef Pos FAR Posf;
  79783. typedef unsigned IPos;
  79784. /* A Pos is an index in the character window. We use short instead of int to
  79785. * save space in the various tables. IPos is used only for parameter passing.
  79786. */
  79787. typedef struct internal_state {
  79788. z_streamp strm; /* pointer back to this zlib stream */
  79789. int status; /* as the name implies */
  79790. Bytef *pending_buf; /* output still pending */
  79791. ulg pending_buf_size; /* size of pending_buf */
  79792. Bytef *pending_out; /* next pending byte to output to the stream */
  79793. uInt pending; /* nb of bytes in the pending buffer */
  79794. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  79795. gz_headerp gzhead; /* gzip header information to write */
  79796. uInt gzindex; /* where in extra, name, or comment */
  79797. Byte method; /* STORED (for zip only) or DEFLATED */
  79798. int last_flush; /* value of flush param for previous deflate call */
  79799. /* used by deflate.c: */
  79800. uInt w_size; /* LZ77 window size (32K by default) */
  79801. uInt w_bits; /* log2(w_size) (8..16) */
  79802. uInt w_mask; /* w_size - 1 */
  79803. Bytef *window;
  79804. /* Sliding window. Input bytes are read into the second half of the window,
  79805. * and move to the first half later to keep a dictionary of at least wSize
  79806. * bytes. With this organization, matches are limited to a distance of
  79807. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  79808. * performed with a length multiple of the block size. Also, it limits
  79809. * the window size to 64K, which is quite useful on MSDOS.
  79810. * To do: use the user input buffer as sliding window.
  79811. */
  79812. ulg window_size;
  79813. /* Actual size of window: 2*wSize, except when the user input buffer
  79814. * is directly used as sliding window.
  79815. */
  79816. Posf *prev;
  79817. /* Link to older string with same hash index. To limit the size of this
  79818. * array to 64K, this link is maintained only for the last 32K strings.
  79819. * An index in this array is thus a window index modulo 32K.
  79820. */
  79821. Posf *head; /* Heads of the hash chains or NIL. */
  79822. uInt ins_h; /* hash index of string to be inserted */
  79823. uInt hash_size; /* number of elements in hash table */
  79824. uInt hash_bits; /* log2(hash_size) */
  79825. uInt hash_mask; /* hash_size-1 */
  79826. uInt hash_shift;
  79827. /* Number of bits by which ins_h must be shifted at each input
  79828. * step. It must be such that after MIN_MATCH steps, the oldest
  79829. * byte no longer takes part in the hash key, that is:
  79830. * hash_shift * MIN_MATCH >= hash_bits
  79831. */
  79832. long block_start;
  79833. /* Window position at the beginning of the current output block. Gets
  79834. * negative when the window is moved backwards.
  79835. */
  79836. uInt match_length; /* length of best match */
  79837. IPos prev_match; /* previous match */
  79838. int match_available; /* set if previous match exists */
  79839. uInt strstart; /* start of string to insert */
  79840. uInt match_start; /* start of matching string */
  79841. uInt lookahead; /* number of valid bytes ahead in window */
  79842. uInt prev_length;
  79843. /* Length of the best match at previous step. Matches not greater than this
  79844. * are discarded. This is used in the lazy match evaluation.
  79845. */
  79846. uInt max_chain_length;
  79847. /* To speed up deflation, hash chains are never searched beyond this
  79848. * length. A higher limit improves compression ratio but degrades the
  79849. * speed.
  79850. */
  79851. uInt max_lazy_match;
  79852. /* Attempt to find a better match only when the current match is strictly
  79853. * smaller than this value. This mechanism is used only for compression
  79854. * levels >= 4.
  79855. */
  79856. # define max_insert_length max_lazy_match
  79857. /* Insert new strings in the hash table only if the match length is not
  79858. * greater than this length. This saves time but degrades compression.
  79859. * max_insert_length is used only for compression levels <= 3.
  79860. */
  79861. int level; /* compression level (1..9) */
  79862. int strategy; /* favor or force Huffman coding*/
  79863. uInt good_match;
  79864. /* Use a faster search when the previous match is longer than this */
  79865. int nice_match; /* Stop searching when current match exceeds this */
  79866. /* used by trees.c: */
  79867. /* Didn't use ct_data typedef below to supress compiler warning */
  79868. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  79869. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  79870. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  79871. struct tree_desc_s l_desc; /* desc. for literal tree */
  79872. struct tree_desc_s d_desc; /* desc. for distance tree */
  79873. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  79874. ush bl_count[MAX_BITS+1];
  79875. /* number of codes at each bit length for an optimal tree */
  79876. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  79877. int heap_len; /* number of elements in the heap */
  79878. int heap_max; /* element of largest frequency */
  79879. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  79880. * The same heap array is used to build all trees.
  79881. */
  79882. uch depth[2*L_CODES+1];
  79883. /* Depth of each subtree used as tie breaker for trees of equal frequency
  79884. */
  79885. uchf *l_buf; /* buffer for literals or lengths */
  79886. uInt lit_bufsize;
  79887. /* Size of match buffer for literals/lengths. There are 4 reasons for
  79888. * limiting lit_bufsize to 64K:
  79889. * - frequencies can be kept in 16 bit counters
  79890. * - if compression is not successful for the first block, all input
  79891. * data is still in the window so we can still emit a stored block even
  79892. * when input comes from standard input. (This can also be done for
  79893. * all blocks if lit_bufsize is not greater than 32K.)
  79894. * - if compression is not successful for a file smaller than 64K, we can
  79895. * even emit a stored file instead of a stored block (saving 5 bytes).
  79896. * This is applicable only for zip (not gzip or zlib).
  79897. * - creating new Huffman trees less frequently may not provide fast
  79898. * adaptation to changes in the input data statistics. (Take for
  79899. * example a binary file with poorly compressible code followed by
  79900. * a highly compressible string table.) Smaller buffer sizes give
  79901. * fast adaptation but have of course the overhead of transmitting
  79902. * trees more frequently.
  79903. * - I can't count above 4
  79904. */
  79905. uInt last_lit; /* running index in l_buf */
  79906. ushf *d_buf;
  79907. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  79908. * the same number of elements. To use different lengths, an extra flag
  79909. * array would be necessary.
  79910. */
  79911. ulg opt_len; /* bit length of current block with optimal trees */
  79912. ulg static_len; /* bit length of current block with static trees */
  79913. uInt matches; /* number of string matches in current block */
  79914. int last_eob_len; /* bit length of EOB code for last block */
  79915. #ifdef DEBUG
  79916. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  79917. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  79918. #endif
  79919. ush bi_buf;
  79920. /* Output buffer. bits are inserted starting at the bottom (least
  79921. * significant bits).
  79922. */
  79923. int bi_valid;
  79924. /* Number of valid bits in bi_buf. All bits above the last valid bit
  79925. * are always zero.
  79926. */
  79927. } FAR deflate_state;
  79928. /* Output a byte on the stream.
  79929. * IN assertion: there is enough room in pending_buf.
  79930. */
  79931. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  79932. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  79933. /* Minimum amount of lookahead, except at the end of the input file.
  79934. * See deflate.c for comments about the MIN_MATCH+1.
  79935. */
  79936. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  79937. /* In order to simplify the code, particularly on 16 bit machines, match
  79938. * distances are limited to MAX_DIST instead of WSIZE.
  79939. */
  79940. /* in trees.c */
  79941. void _tr_init OF((deflate_state *s));
  79942. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  79943. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  79944. int eof));
  79945. void _tr_align OF((deflate_state *s));
  79946. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  79947. int eof));
  79948. #define d_code(dist) \
  79949. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  79950. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  79951. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  79952. * used.
  79953. */
  79954. #ifndef DEBUG
  79955. /* Inline versions of _tr_tally for speed: */
  79956. #if defined(GEN_TREES_H) || !defined(STDC)
  79957. extern uch _length_code[];
  79958. extern uch _dist_code[];
  79959. #else
  79960. extern const uch _length_code[];
  79961. extern const uch _dist_code[];
  79962. #endif
  79963. # define _tr_tally_lit(s, c, flush) \
  79964. { uch cc = (c); \
  79965. s->d_buf[s->last_lit] = 0; \
  79966. s->l_buf[s->last_lit++] = cc; \
  79967. s->dyn_ltree[cc].Freq++; \
  79968. flush = (s->last_lit == s->lit_bufsize-1); \
  79969. }
  79970. # define _tr_tally_dist(s, distance, length, flush) \
  79971. { uch len = (length); \
  79972. ush dist = (distance); \
  79973. s->d_buf[s->last_lit] = dist; \
  79974. s->l_buf[s->last_lit++] = len; \
  79975. dist--; \
  79976. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  79977. s->dyn_dtree[d_code(dist)].Freq++; \
  79978. flush = (s->last_lit == s->lit_bufsize-1); \
  79979. }
  79980. #else
  79981. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  79982. # define _tr_tally_dist(s, distance, length, flush) \
  79983. flush = _tr_tally(s, distance, length)
  79984. #endif
  79985. #endif /* DEFLATE_H */
  79986. /*** End of inlined file: deflate.h ***/
  79987. const char deflate_copyright[] =
  79988. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  79989. /*
  79990. If you use the zlib library in a product, an acknowledgment is welcome
  79991. in the documentation of your product. If for some reason you cannot
  79992. include such an acknowledgment, I would appreciate that you keep this
  79993. copyright string in the executable of your product.
  79994. */
  79995. /* ===========================================================================
  79996. * Function prototypes.
  79997. */
  79998. typedef enum {
  79999. need_more, /* block not completed, need more input or more output */
  80000. block_done, /* block flush performed */
  80001. finish_started, /* finish started, need only more output at next deflate */
  80002. finish_done /* finish done, accept no more input or output */
  80003. } block_state;
  80004. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80005. /* Compression function. Returns the block state after the call. */
  80006. local void fill_window OF((deflate_state *s));
  80007. local block_state deflate_stored OF((deflate_state *s, int flush));
  80008. local block_state deflate_fast OF((deflate_state *s, int flush));
  80009. #ifndef FASTEST
  80010. local block_state deflate_slow OF((deflate_state *s, int flush));
  80011. #endif
  80012. local void lm_init OF((deflate_state *s));
  80013. local void putShortMSB OF((deflate_state *s, uInt b));
  80014. local void flush_pending OF((z_streamp strm));
  80015. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80016. #ifndef FASTEST
  80017. #ifdef ASMV
  80018. void match_init OF((void)); /* asm code initialization */
  80019. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80020. #else
  80021. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80022. #endif
  80023. #endif
  80024. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80025. #ifdef DEBUG
  80026. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80027. int length));
  80028. #endif
  80029. /* ===========================================================================
  80030. * Local data
  80031. */
  80032. #define NIL 0
  80033. /* Tail of hash chains */
  80034. #ifndef TOO_FAR
  80035. # define TOO_FAR 4096
  80036. #endif
  80037. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80038. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80039. /* Minimum amount of lookahead, except at the end of the input file.
  80040. * See deflate.c for comments about the MIN_MATCH+1.
  80041. */
  80042. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80043. * the desired pack level (0..9). The values given below have been tuned to
  80044. * exclude worst case performance for pathological files. Better values may be
  80045. * found for specific files.
  80046. */
  80047. typedef struct config_s {
  80048. ush good_length; /* reduce lazy search above this match length */
  80049. ush max_lazy; /* do not perform lazy search above this match length */
  80050. ush nice_length; /* quit search above this match length */
  80051. ush max_chain;
  80052. compress_func func;
  80053. } config;
  80054. #ifdef FASTEST
  80055. local const config configuration_table[2] = {
  80056. /* good lazy nice chain */
  80057. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80058. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80059. #else
  80060. local const config configuration_table[10] = {
  80061. /* good lazy nice chain */
  80062. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80063. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80064. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80065. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80066. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80067. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80068. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80069. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80070. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80071. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80072. #endif
  80073. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80074. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80075. * meaning.
  80076. */
  80077. #define EQUAL 0
  80078. /* result of memcmp for equal strings */
  80079. #ifndef NO_DUMMY_DECL
  80080. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80081. #endif
  80082. /* ===========================================================================
  80083. * Update a hash value with the given input byte
  80084. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80085. * input characters, so that a running hash key can be computed from the
  80086. * previous key instead of complete recalculation each time.
  80087. */
  80088. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80089. /* ===========================================================================
  80090. * Insert string str in the dictionary and set match_head to the previous head
  80091. * of the hash chain (the most recent string with same hash key). Return
  80092. * the previous length of the hash chain.
  80093. * If this file is compiled with -DFASTEST, the compression level is forced
  80094. * to 1, and no hash chains are maintained.
  80095. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80096. * input characters and the first MIN_MATCH bytes of str are valid
  80097. * (except for the last MIN_MATCH-1 bytes of the input file).
  80098. */
  80099. #ifdef FASTEST
  80100. #define INSERT_STRING(s, str, match_head) \
  80101. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80102. match_head = s->head[s->ins_h], \
  80103. s->head[s->ins_h] = (Pos)(str))
  80104. #else
  80105. #define INSERT_STRING(s, str, match_head) \
  80106. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80107. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80108. s->head[s->ins_h] = (Pos)(str))
  80109. #endif
  80110. /* ===========================================================================
  80111. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80112. * prev[] will be initialized on the fly.
  80113. */
  80114. #define CLEAR_HASH(s) \
  80115. s->head[s->hash_size-1] = NIL; \
  80116. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  80117. /* ========================================================================= */
  80118. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  80119. {
  80120. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  80121. Z_DEFAULT_STRATEGY, version, stream_size);
  80122. /* To do: ignore strm->next_in if we use it as window */
  80123. }
  80124. /* ========================================================================= */
  80125. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  80126. {
  80127. deflate_state *s;
  80128. int wrap = 1;
  80129. static const char my_version[] = ZLIB_VERSION;
  80130. ushf *overlay;
  80131. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  80132. * output size for (length,distance) codes is <= 24 bits.
  80133. */
  80134. if (version == Z_NULL || version[0] != my_version[0] ||
  80135. stream_size != sizeof(z_stream)) {
  80136. return Z_VERSION_ERROR;
  80137. }
  80138. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80139. strm->msg = Z_NULL;
  80140. if (strm->zalloc == (alloc_func)0) {
  80141. strm->zalloc = zcalloc;
  80142. strm->opaque = (voidpf)0;
  80143. }
  80144. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80145. #ifdef FASTEST
  80146. if (level != 0) level = 1;
  80147. #else
  80148. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80149. #endif
  80150. if (windowBits < 0) { /* suppress zlib wrapper */
  80151. wrap = 0;
  80152. windowBits = -windowBits;
  80153. }
  80154. #ifdef GZIP
  80155. else if (windowBits > 15) {
  80156. wrap = 2; /* write gzip wrapper instead */
  80157. windowBits -= 16;
  80158. }
  80159. #endif
  80160. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  80161. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  80162. strategy < 0 || strategy > Z_FIXED) {
  80163. return Z_STREAM_ERROR;
  80164. }
  80165. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  80166. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  80167. if (s == Z_NULL) return Z_MEM_ERROR;
  80168. strm->state = (struct internal_state FAR *)s;
  80169. s->strm = strm;
  80170. s->wrap = wrap;
  80171. s->gzhead = Z_NULL;
  80172. s->w_bits = windowBits;
  80173. s->w_size = 1 << s->w_bits;
  80174. s->w_mask = s->w_size - 1;
  80175. s->hash_bits = memLevel + 7;
  80176. s->hash_size = 1 << s->hash_bits;
  80177. s->hash_mask = s->hash_size - 1;
  80178. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  80179. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  80180. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  80181. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  80182. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  80183. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  80184. s->pending_buf = (uchf *) overlay;
  80185. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  80186. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  80187. s->pending_buf == Z_NULL) {
  80188. s->status = FINISH_STATE;
  80189. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  80190. deflateEnd (strm);
  80191. return Z_MEM_ERROR;
  80192. }
  80193. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  80194. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  80195. s->level = level;
  80196. s->strategy = strategy;
  80197. s->method = (Byte)method;
  80198. return deflateReset(strm);
  80199. }
  80200. /* ========================================================================= */
  80201. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  80202. {
  80203. deflate_state *s;
  80204. uInt length = dictLength;
  80205. uInt n;
  80206. IPos hash_head = 0;
  80207. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  80208. strm->state->wrap == 2 ||
  80209. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  80210. return Z_STREAM_ERROR;
  80211. s = strm->state;
  80212. if (s->wrap)
  80213. strm->adler = adler32(strm->adler, dictionary, dictLength);
  80214. if (length < MIN_MATCH) return Z_OK;
  80215. if (length > MAX_DIST(s)) {
  80216. length = MAX_DIST(s);
  80217. dictionary += dictLength - length; /* use the tail of the dictionary */
  80218. }
  80219. zmemcpy(s->window, dictionary, length);
  80220. s->strstart = length;
  80221. s->block_start = (long)length;
  80222. /* Insert all strings in the hash table (except for the last two bytes).
  80223. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  80224. * call of fill_window.
  80225. */
  80226. s->ins_h = s->window[0];
  80227. UPDATE_HASH(s, s->ins_h, s->window[1]);
  80228. for (n = 0; n <= length - MIN_MATCH; n++) {
  80229. INSERT_STRING(s, n, hash_head);
  80230. }
  80231. if (hash_head) hash_head = 0; /* to make compiler happy */
  80232. return Z_OK;
  80233. }
  80234. /* ========================================================================= */
  80235. int ZEXPORT deflateReset (z_streamp strm)
  80236. {
  80237. deflate_state *s;
  80238. if (strm == Z_NULL || strm->state == Z_NULL ||
  80239. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  80240. return Z_STREAM_ERROR;
  80241. }
  80242. strm->total_in = strm->total_out = 0;
  80243. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  80244. strm->data_type = Z_UNKNOWN;
  80245. s = (deflate_state *)strm->state;
  80246. s->pending = 0;
  80247. s->pending_out = s->pending_buf;
  80248. if (s->wrap < 0) {
  80249. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  80250. }
  80251. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  80252. strm->adler =
  80253. #ifdef GZIP
  80254. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  80255. #endif
  80256. adler32(0L, Z_NULL, 0);
  80257. s->last_flush = Z_NO_FLUSH;
  80258. _tr_init(s);
  80259. lm_init(s);
  80260. return Z_OK;
  80261. }
  80262. /* ========================================================================= */
  80263. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  80264. {
  80265. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80266. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  80267. strm->state->gzhead = head;
  80268. return Z_OK;
  80269. }
  80270. /* ========================================================================= */
  80271. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  80272. {
  80273. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80274. strm->state->bi_valid = bits;
  80275. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  80276. return Z_OK;
  80277. }
  80278. /* ========================================================================= */
  80279. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  80280. {
  80281. deflate_state *s;
  80282. compress_func func;
  80283. int err = Z_OK;
  80284. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80285. s = strm->state;
  80286. #ifdef FASTEST
  80287. if (level != 0) level = 1;
  80288. #else
  80289. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80290. #endif
  80291. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  80292. return Z_STREAM_ERROR;
  80293. }
  80294. func = configuration_table[s->level].func;
  80295. if (func != configuration_table[level].func && strm->total_in != 0) {
  80296. /* Flush the last buffer: */
  80297. err = deflate(strm, Z_PARTIAL_FLUSH);
  80298. }
  80299. if (s->level != level) {
  80300. s->level = level;
  80301. s->max_lazy_match = configuration_table[level].max_lazy;
  80302. s->good_match = configuration_table[level].good_length;
  80303. s->nice_match = configuration_table[level].nice_length;
  80304. s->max_chain_length = configuration_table[level].max_chain;
  80305. }
  80306. s->strategy = strategy;
  80307. return err;
  80308. }
  80309. /* ========================================================================= */
  80310. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  80311. {
  80312. deflate_state *s;
  80313. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80314. s = strm->state;
  80315. s->good_match = good_length;
  80316. s->max_lazy_match = max_lazy;
  80317. s->nice_match = nice_length;
  80318. s->max_chain_length = max_chain;
  80319. return Z_OK;
  80320. }
  80321. /* =========================================================================
  80322. * For the default windowBits of 15 and memLevel of 8, this function returns
  80323. * a close to exact, as well as small, upper bound on the compressed size.
  80324. * They are coded as constants here for a reason--if the #define's are
  80325. * changed, then this function needs to be changed as well. The return
  80326. * value for 15 and 8 only works for those exact settings.
  80327. *
  80328. * For any setting other than those defaults for windowBits and memLevel,
  80329. * the value returned is a conservative worst case for the maximum expansion
  80330. * resulting from using fixed blocks instead of stored blocks, which deflate
  80331. * can emit on compressed data for some combinations of the parameters.
  80332. *
  80333. * This function could be more sophisticated to provide closer upper bounds
  80334. * for every combination of windowBits and memLevel, as well as wrap.
  80335. * But even the conservative upper bound of about 14% expansion does not
  80336. * seem onerous for output buffer allocation.
  80337. */
  80338. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  80339. {
  80340. deflate_state *s;
  80341. uLong destLen;
  80342. /* conservative upper bound */
  80343. destLen = sourceLen +
  80344. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  80345. /* if can't get parameters, return conservative bound */
  80346. if (strm == Z_NULL || strm->state == Z_NULL)
  80347. return destLen;
  80348. /* if not default parameters, return conservative bound */
  80349. s = strm->state;
  80350. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  80351. return destLen;
  80352. /* default settings: return tight bound for that case */
  80353. return compressBound(sourceLen);
  80354. }
  80355. /* =========================================================================
  80356. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  80357. * IN assertion: the stream state is correct and there is enough room in
  80358. * pending_buf.
  80359. */
  80360. local void putShortMSB (deflate_state *s, uInt b)
  80361. {
  80362. put_byte(s, (Byte)(b >> 8));
  80363. put_byte(s, (Byte)(b & 0xff));
  80364. }
  80365. /* =========================================================================
  80366. * Flush as much pending output as possible. All deflate() output goes
  80367. * through this function so some applications may wish to modify it
  80368. * to avoid allocating a large strm->next_out buffer and copying into it.
  80369. * (See also read_buf()).
  80370. */
  80371. local void flush_pending (z_streamp strm)
  80372. {
  80373. unsigned len = strm->state->pending;
  80374. if (len > strm->avail_out) len = strm->avail_out;
  80375. if (len == 0) return;
  80376. zmemcpy(strm->next_out, strm->state->pending_out, len);
  80377. strm->next_out += len;
  80378. strm->state->pending_out += len;
  80379. strm->total_out += len;
  80380. strm->avail_out -= len;
  80381. strm->state->pending -= len;
  80382. if (strm->state->pending == 0) {
  80383. strm->state->pending_out = strm->state->pending_buf;
  80384. }
  80385. }
  80386. /* ========================================================================= */
  80387. int ZEXPORT deflate (z_streamp strm, int flush)
  80388. {
  80389. int old_flush; /* value of flush param for previous deflate call */
  80390. deflate_state *s;
  80391. if (strm == Z_NULL || strm->state == Z_NULL ||
  80392. flush > Z_FINISH || flush < 0) {
  80393. return Z_STREAM_ERROR;
  80394. }
  80395. s = strm->state;
  80396. if (strm->next_out == Z_NULL ||
  80397. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  80398. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  80399. ERR_RETURN(strm, Z_STREAM_ERROR);
  80400. }
  80401. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  80402. s->strm = strm; /* just in case */
  80403. old_flush = s->last_flush;
  80404. s->last_flush = flush;
  80405. /* Write the header */
  80406. if (s->status == INIT_STATE) {
  80407. #ifdef GZIP
  80408. if (s->wrap == 2) {
  80409. strm->adler = crc32(0L, Z_NULL, 0);
  80410. put_byte(s, 31);
  80411. put_byte(s, 139);
  80412. put_byte(s, 8);
  80413. if (s->gzhead == NULL) {
  80414. put_byte(s, 0);
  80415. put_byte(s, 0);
  80416. put_byte(s, 0);
  80417. put_byte(s, 0);
  80418. put_byte(s, 0);
  80419. put_byte(s, s->level == 9 ? 2 :
  80420. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  80421. 4 : 0));
  80422. put_byte(s, OS_CODE);
  80423. s->status = BUSY_STATE;
  80424. }
  80425. else {
  80426. put_byte(s, (s->gzhead->text ? 1 : 0) +
  80427. (s->gzhead->hcrc ? 2 : 0) +
  80428. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  80429. (s->gzhead->name == Z_NULL ? 0 : 8) +
  80430. (s->gzhead->comment == Z_NULL ? 0 : 16)
  80431. );
  80432. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  80433. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  80434. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  80435. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  80436. put_byte(s, s->level == 9 ? 2 :
  80437. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  80438. 4 : 0));
  80439. put_byte(s, s->gzhead->os & 0xff);
  80440. if (s->gzhead->extra != NULL) {
  80441. put_byte(s, s->gzhead->extra_len & 0xff);
  80442. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  80443. }
  80444. if (s->gzhead->hcrc)
  80445. strm->adler = crc32(strm->adler, s->pending_buf,
  80446. s->pending);
  80447. s->gzindex = 0;
  80448. s->status = EXTRA_STATE;
  80449. }
  80450. }
  80451. else
  80452. #endif
  80453. {
  80454. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  80455. uInt level_flags;
  80456. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  80457. level_flags = 0;
  80458. else if (s->level < 6)
  80459. level_flags = 1;
  80460. else if (s->level == 6)
  80461. level_flags = 2;
  80462. else
  80463. level_flags = 3;
  80464. header |= (level_flags << 6);
  80465. if (s->strstart != 0) header |= PRESET_DICT;
  80466. header += 31 - (header % 31);
  80467. s->status = BUSY_STATE;
  80468. putShortMSB(s, header);
  80469. /* Save the adler32 of the preset dictionary: */
  80470. if (s->strstart != 0) {
  80471. putShortMSB(s, (uInt)(strm->adler >> 16));
  80472. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  80473. }
  80474. strm->adler = adler32(0L, Z_NULL, 0);
  80475. }
  80476. }
  80477. #ifdef GZIP
  80478. if (s->status == EXTRA_STATE) {
  80479. if (s->gzhead->extra != NULL) {
  80480. uInt beg = s->pending; /* start of bytes to update crc */
  80481. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  80482. if (s->pending == s->pending_buf_size) {
  80483. if (s->gzhead->hcrc && s->pending > beg)
  80484. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80485. s->pending - beg);
  80486. flush_pending(strm);
  80487. beg = s->pending;
  80488. if (s->pending == s->pending_buf_size)
  80489. break;
  80490. }
  80491. put_byte(s, s->gzhead->extra[s->gzindex]);
  80492. s->gzindex++;
  80493. }
  80494. if (s->gzhead->hcrc && s->pending > beg)
  80495. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80496. s->pending - beg);
  80497. if (s->gzindex == s->gzhead->extra_len) {
  80498. s->gzindex = 0;
  80499. s->status = NAME_STATE;
  80500. }
  80501. }
  80502. else
  80503. s->status = NAME_STATE;
  80504. }
  80505. if (s->status == NAME_STATE) {
  80506. if (s->gzhead->name != NULL) {
  80507. uInt beg = s->pending; /* start of bytes to update crc */
  80508. int val;
  80509. do {
  80510. if (s->pending == s->pending_buf_size) {
  80511. if (s->gzhead->hcrc && s->pending > beg)
  80512. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80513. s->pending - beg);
  80514. flush_pending(strm);
  80515. beg = s->pending;
  80516. if (s->pending == s->pending_buf_size) {
  80517. val = 1;
  80518. break;
  80519. }
  80520. }
  80521. val = s->gzhead->name[s->gzindex++];
  80522. put_byte(s, val);
  80523. } while (val != 0);
  80524. if (s->gzhead->hcrc && s->pending > beg)
  80525. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80526. s->pending - beg);
  80527. if (val == 0) {
  80528. s->gzindex = 0;
  80529. s->status = COMMENT_STATE;
  80530. }
  80531. }
  80532. else
  80533. s->status = COMMENT_STATE;
  80534. }
  80535. if (s->status == COMMENT_STATE) {
  80536. if (s->gzhead->comment != NULL) {
  80537. uInt beg = s->pending; /* start of bytes to update crc */
  80538. int val;
  80539. do {
  80540. if (s->pending == s->pending_buf_size) {
  80541. if (s->gzhead->hcrc && s->pending > beg)
  80542. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80543. s->pending - beg);
  80544. flush_pending(strm);
  80545. beg = s->pending;
  80546. if (s->pending == s->pending_buf_size) {
  80547. val = 1;
  80548. break;
  80549. }
  80550. }
  80551. val = s->gzhead->comment[s->gzindex++];
  80552. put_byte(s, val);
  80553. } while (val != 0);
  80554. if (s->gzhead->hcrc && s->pending > beg)
  80555. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80556. s->pending - beg);
  80557. if (val == 0)
  80558. s->status = HCRC_STATE;
  80559. }
  80560. else
  80561. s->status = HCRC_STATE;
  80562. }
  80563. if (s->status == HCRC_STATE) {
  80564. if (s->gzhead->hcrc) {
  80565. if (s->pending + 2 > s->pending_buf_size)
  80566. flush_pending(strm);
  80567. if (s->pending + 2 <= s->pending_buf_size) {
  80568. put_byte(s, (Byte)(strm->adler & 0xff));
  80569. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  80570. strm->adler = crc32(0L, Z_NULL, 0);
  80571. s->status = BUSY_STATE;
  80572. }
  80573. }
  80574. else
  80575. s->status = BUSY_STATE;
  80576. }
  80577. #endif
  80578. /* Flush as much pending output as possible */
  80579. if (s->pending != 0) {
  80580. flush_pending(strm);
  80581. if (strm->avail_out == 0) {
  80582. /* Since avail_out is 0, deflate will be called again with
  80583. * more output space, but possibly with both pending and
  80584. * avail_in equal to zero. There won't be anything to do,
  80585. * but this is not an error situation so make sure we
  80586. * return OK instead of BUF_ERROR at next call of deflate:
  80587. */
  80588. s->last_flush = -1;
  80589. return Z_OK;
  80590. }
  80591. /* Make sure there is something to do and avoid duplicate consecutive
  80592. * flushes. For repeated and useless calls with Z_FINISH, we keep
  80593. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  80594. */
  80595. } else if (strm->avail_in == 0 && flush <= old_flush &&
  80596. flush != Z_FINISH) {
  80597. ERR_RETURN(strm, Z_BUF_ERROR);
  80598. }
  80599. /* User must not provide more input after the first FINISH: */
  80600. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  80601. ERR_RETURN(strm, Z_BUF_ERROR);
  80602. }
  80603. /* Start a new block or continue the current one.
  80604. */
  80605. if (strm->avail_in != 0 || s->lookahead != 0 ||
  80606. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  80607. block_state bstate;
  80608. bstate = (*(configuration_table[s->level].func))(s, flush);
  80609. if (bstate == finish_started || bstate == finish_done) {
  80610. s->status = FINISH_STATE;
  80611. }
  80612. if (bstate == need_more || bstate == finish_started) {
  80613. if (strm->avail_out == 0) {
  80614. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  80615. }
  80616. return Z_OK;
  80617. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  80618. * of deflate should use the same flush parameter to make sure
  80619. * that the flush is complete. So we don't have to output an
  80620. * empty block here, this will be done at next call. This also
  80621. * ensures that for a very small output buffer, we emit at most
  80622. * one empty block.
  80623. */
  80624. }
  80625. if (bstate == block_done) {
  80626. if (flush == Z_PARTIAL_FLUSH) {
  80627. _tr_align(s);
  80628. } else { /* FULL_FLUSH or SYNC_FLUSH */
  80629. _tr_stored_block(s, (char*)0, 0L, 0);
  80630. /* For a full flush, this empty block will be recognized
  80631. * as a special marker by inflate_sync().
  80632. */
  80633. if (flush == Z_FULL_FLUSH) {
  80634. CLEAR_HASH(s); /* forget history */
  80635. }
  80636. }
  80637. flush_pending(strm);
  80638. if (strm->avail_out == 0) {
  80639. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  80640. return Z_OK;
  80641. }
  80642. }
  80643. }
  80644. Assert(strm->avail_out > 0, "bug2");
  80645. if (flush != Z_FINISH) return Z_OK;
  80646. if (s->wrap <= 0) return Z_STREAM_END;
  80647. /* Write the trailer */
  80648. #ifdef GZIP
  80649. if (s->wrap == 2) {
  80650. put_byte(s, (Byte)(strm->adler & 0xff));
  80651. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  80652. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  80653. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  80654. put_byte(s, (Byte)(strm->total_in & 0xff));
  80655. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  80656. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  80657. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  80658. }
  80659. else
  80660. #endif
  80661. {
  80662. putShortMSB(s, (uInt)(strm->adler >> 16));
  80663. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  80664. }
  80665. flush_pending(strm);
  80666. /* If avail_out is zero, the application will call deflate again
  80667. * to flush the rest.
  80668. */
  80669. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  80670. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  80671. }
  80672. /* ========================================================================= */
  80673. int ZEXPORT deflateEnd (z_streamp strm)
  80674. {
  80675. int status;
  80676. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80677. status = strm->state->status;
  80678. if (status != INIT_STATE &&
  80679. status != EXTRA_STATE &&
  80680. status != NAME_STATE &&
  80681. status != COMMENT_STATE &&
  80682. status != HCRC_STATE &&
  80683. status != BUSY_STATE &&
  80684. status != FINISH_STATE) {
  80685. return Z_STREAM_ERROR;
  80686. }
  80687. /* Deallocate in reverse order of allocations: */
  80688. TRY_FREE(strm, strm->state->pending_buf);
  80689. TRY_FREE(strm, strm->state->head);
  80690. TRY_FREE(strm, strm->state->prev);
  80691. TRY_FREE(strm, strm->state->window);
  80692. ZFREE(strm, strm->state);
  80693. strm->state = Z_NULL;
  80694. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  80695. }
  80696. /* =========================================================================
  80697. * Copy the source state to the destination state.
  80698. * To simplify the source, this is not supported for 16-bit MSDOS (which
  80699. * doesn't have enough memory anyway to duplicate compression states).
  80700. */
  80701. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  80702. {
  80703. #ifdef MAXSEG_64K
  80704. return Z_STREAM_ERROR;
  80705. #else
  80706. deflate_state *ds;
  80707. deflate_state *ss;
  80708. ushf *overlay;
  80709. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  80710. return Z_STREAM_ERROR;
  80711. }
  80712. ss = source->state;
  80713. zmemcpy(dest, source, sizeof(z_stream));
  80714. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  80715. if (ds == Z_NULL) return Z_MEM_ERROR;
  80716. dest->state = (struct internal_state FAR *) ds;
  80717. zmemcpy(ds, ss, sizeof(deflate_state));
  80718. ds->strm = dest;
  80719. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  80720. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  80721. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  80722. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  80723. ds->pending_buf = (uchf *) overlay;
  80724. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  80725. ds->pending_buf == Z_NULL) {
  80726. deflateEnd (dest);
  80727. return Z_MEM_ERROR;
  80728. }
  80729. /* following zmemcpy do not work for 16-bit MSDOS */
  80730. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  80731. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  80732. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  80733. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  80734. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  80735. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  80736. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  80737. ds->l_desc.dyn_tree = ds->dyn_ltree;
  80738. ds->d_desc.dyn_tree = ds->dyn_dtree;
  80739. ds->bl_desc.dyn_tree = ds->bl_tree;
  80740. return Z_OK;
  80741. #endif /* MAXSEG_64K */
  80742. }
  80743. /* ===========================================================================
  80744. * Read a new buffer from the current input stream, update the adler32
  80745. * and total number of bytes read. All deflate() input goes through
  80746. * this function so some applications may wish to modify it to avoid
  80747. * allocating a large strm->next_in buffer and copying from it.
  80748. * (See also flush_pending()).
  80749. */
  80750. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  80751. {
  80752. unsigned len = strm->avail_in;
  80753. if (len > size) len = size;
  80754. if (len == 0) return 0;
  80755. strm->avail_in -= len;
  80756. if (strm->state->wrap == 1) {
  80757. strm->adler = adler32(strm->adler, strm->next_in, len);
  80758. }
  80759. #ifdef GZIP
  80760. else if (strm->state->wrap == 2) {
  80761. strm->adler = crc32(strm->adler, strm->next_in, len);
  80762. }
  80763. #endif
  80764. zmemcpy(buf, strm->next_in, len);
  80765. strm->next_in += len;
  80766. strm->total_in += len;
  80767. return (int)len;
  80768. }
  80769. /* ===========================================================================
  80770. * Initialize the "longest match" routines for a new zlib stream
  80771. */
  80772. local void lm_init (deflate_state *s)
  80773. {
  80774. s->window_size = (ulg)2L*s->w_size;
  80775. CLEAR_HASH(s);
  80776. /* Set the default configuration parameters:
  80777. */
  80778. s->max_lazy_match = configuration_table[s->level].max_lazy;
  80779. s->good_match = configuration_table[s->level].good_length;
  80780. s->nice_match = configuration_table[s->level].nice_length;
  80781. s->max_chain_length = configuration_table[s->level].max_chain;
  80782. s->strstart = 0;
  80783. s->block_start = 0L;
  80784. s->lookahead = 0;
  80785. s->match_length = s->prev_length = MIN_MATCH-1;
  80786. s->match_available = 0;
  80787. s->ins_h = 0;
  80788. #ifndef FASTEST
  80789. #ifdef ASMV
  80790. match_init(); /* initialize the asm code */
  80791. #endif
  80792. #endif
  80793. }
  80794. #ifndef FASTEST
  80795. /* ===========================================================================
  80796. * Set match_start to the longest match starting at the given string and
  80797. * return its length. Matches shorter or equal to prev_length are discarded,
  80798. * in which case the result is equal to prev_length and match_start is
  80799. * garbage.
  80800. * IN assertions: cur_match is the head of the hash chain for the current
  80801. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  80802. * OUT assertion: the match length is not greater than s->lookahead.
  80803. */
  80804. #ifndef ASMV
  80805. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  80806. * match.S. The code will be functionally equivalent.
  80807. */
  80808. local uInt longest_match(deflate_state *s, IPos cur_match)
  80809. {
  80810. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  80811. register Bytef *scan = s->window + s->strstart; /* current string */
  80812. register Bytef *match; /* matched string */
  80813. register int len; /* length of current match */
  80814. int best_len = s->prev_length; /* best match length so far */
  80815. int nice_match = s->nice_match; /* stop if match long enough */
  80816. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  80817. s->strstart - (IPos)MAX_DIST(s) : NIL;
  80818. /* Stop when cur_match becomes <= limit. To simplify the code,
  80819. * we prevent matches with the string of window index 0.
  80820. */
  80821. Posf *prev = s->prev;
  80822. uInt wmask = s->w_mask;
  80823. #ifdef UNALIGNED_OK
  80824. /* Compare two bytes at a time. Note: this is not always beneficial.
  80825. * Try with and without -DUNALIGNED_OK to check.
  80826. */
  80827. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  80828. register ush scan_start = *(ushf*)scan;
  80829. register ush scan_end = *(ushf*)(scan+best_len-1);
  80830. #else
  80831. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  80832. register Byte scan_end1 = scan[best_len-1];
  80833. register Byte scan_end = scan[best_len];
  80834. #endif
  80835. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  80836. * It is easy to get rid of this optimization if necessary.
  80837. */
  80838. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  80839. /* Do not waste too much time if we already have a good match: */
  80840. if (s->prev_length >= s->good_match) {
  80841. chain_length >>= 2;
  80842. }
  80843. /* Do not look for matches beyond the end of the input. This is necessary
  80844. * to make deflate deterministic.
  80845. */
  80846. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  80847. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  80848. do {
  80849. Assert(cur_match < s->strstart, "no future");
  80850. match = s->window + cur_match;
  80851. /* Skip to next match if the match length cannot increase
  80852. * or if the match length is less than 2. Note that the checks below
  80853. * for insufficient lookahead only occur occasionally for performance
  80854. * reasons. Therefore uninitialized memory will be accessed, and
  80855. * conditional jumps will be made that depend on those values.
  80856. * However the length of the match is limited to the lookahead, so
  80857. * the output of deflate is not affected by the uninitialized values.
  80858. */
  80859. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  80860. /* This code assumes sizeof(unsigned short) == 2. Do not use
  80861. * UNALIGNED_OK if your compiler uses a different size.
  80862. */
  80863. if (*(ushf*)(match+best_len-1) != scan_end ||
  80864. *(ushf*)match != scan_start) continue;
  80865. /* It is not necessary to compare scan[2] and match[2] since they are
  80866. * always equal when the other bytes match, given that the hash keys
  80867. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  80868. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  80869. * lookahead only every 4th comparison; the 128th check will be made
  80870. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  80871. * necessary to put more guard bytes at the end of the window, or
  80872. * to check more often for insufficient lookahead.
  80873. */
  80874. Assert(scan[2] == match[2], "scan[2]?");
  80875. scan++, match++;
  80876. do {
  80877. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  80878. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  80879. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  80880. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  80881. scan < strend);
  80882. /* The funny "do {}" generates better code on most compilers */
  80883. /* Here, scan <= window+strstart+257 */
  80884. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  80885. if (*scan == *match) scan++;
  80886. len = (MAX_MATCH - 1) - (int)(strend-scan);
  80887. scan = strend - (MAX_MATCH-1);
  80888. #else /* UNALIGNED_OK */
  80889. if (match[best_len] != scan_end ||
  80890. match[best_len-1] != scan_end1 ||
  80891. *match != *scan ||
  80892. *++match != scan[1]) continue;
  80893. /* The check at best_len-1 can be removed because it will be made
  80894. * again later. (This heuristic is not always a win.)
  80895. * It is not necessary to compare scan[2] and match[2] since they
  80896. * are always equal when the other bytes match, given that
  80897. * the hash keys are equal and that HASH_BITS >= 8.
  80898. */
  80899. scan += 2, match++;
  80900. Assert(*scan == *match, "match[2]?");
  80901. /* We check for insufficient lookahead only every 8th comparison;
  80902. * the 256th check will be made at strstart+258.
  80903. */
  80904. do {
  80905. } while (*++scan == *++match && *++scan == *++match &&
  80906. *++scan == *++match && *++scan == *++match &&
  80907. *++scan == *++match && *++scan == *++match &&
  80908. *++scan == *++match && *++scan == *++match &&
  80909. scan < strend);
  80910. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  80911. len = MAX_MATCH - (int)(strend - scan);
  80912. scan = strend - MAX_MATCH;
  80913. #endif /* UNALIGNED_OK */
  80914. if (len > best_len) {
  80915. s->match_start = cur_match;
  80916. best_len = len;
  80917. if (len >= nice_match) break;
  80918. #ifdef UNALIGNED_OK
  80919. scan_end = *(ushf*)(scan+best_len-1);
  80920. #else
  80921. scan_end1 = scan[best_len-1];
  80922. scan_end = scan[best_len];
  80923. #endif
  80924. }
  80925. } while ((cur_match = prev[cur_match & wmask]) > limit
  80926. && --chain_length != 0);
  80927. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  80928. return s->lookahead;
  80929. }
  80930. #endif /* ASMV */
  80931. #endif /* FASTEST */
  80932. /* ---------------------------------------------------------------------------
  80933. * Optimized version for level == 1 or strategy == Z_RLE only
  80934. */
  80935. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  80936. {
  80937. register Bytef *scan = s->window + s->strstart; /* current string */
  80938. register Bytef *match; /* matched string */
  80939. register int len; /* length of current match */
  80940. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  80941. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  80942. * It is easy to get rid of this optimization if necessary.
  80943. */
  80944. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  80945. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  80946. Assert(cur_match < s->strstart, "no future");
  80947. match = s->window + cur_match;
  80948. /* Return failure if the match length is less than 2:
  80949. */
  80950. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  80951. /* The check at best_len-1 can be removed because it will be made
  80952. * again later. (This heuristic is not always a win.)
  80953. * It is not necessary to compare scan[2] and match[2] since they
  80954. * are always equal when the other bytes match, given that
  80955. * the hash keys are equal and that HASH_BITS >= 8.
  80956. */
  80957. scan += 2, match += 2;
  80958. Assert(*scan == *match, "match[2]?");
  80959. /* We check for insufficient lookahead only every 8th comparison;
  80960. * the 256th check will be made at strstart+258.
  80961. */
  80962. do {
  80963. } while (*++scan == *++match && *++scan == *++match &&
  80964. *++scan == *++match && *++scan == *++match &&
  80965. *++scan == *++match && *++scan == *++match &&
  80966. *++scan == *++match && *++scan == *++match &&
  80967. scan < strend);
  80968. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  80969. len = MAX_MATCH - (int)(strend - scan);
  80970. if (len < MIN_MATCH) return MIN_MATCH - 1;
  80971. s->match_start = cur_match;
  80972. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  80973. }
  80974. #ifdef DEBUG
  80975. /* ===========================================================================
  80976. * Check that the match at match_start is indeed a match.
  80977. */
  80978. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  80979. {
  80980. /* check that the match is indeed a match */
  80981. if (zmemcmp(s->window + match,
  80982. s->window + start, length) != EQUAL) {
  80983. fprintf(stderr, " start %u, match %u, length %d\n",
  80984. start, match, length);
  80985. do {
  80986. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  80987. } while (--length != 0);
  80988. z_error("invalid match");
  80989. }
  80990. if (z_verbose > 1) {
  80991. fprintf(stderr,"\\[%d,%d]", start-match, length);
  80992. do { putc(s->window[start++], stderr); } while (--length != 0);
  80993. }
  80994. }
  80995. #else
  80996. # define check_match(s, start, match, length)
  80997. #endif /* DEBUG */
  80998. /* ===========================================================================
  80999. * Fill the window when the lookahead becomes insufficient.
  81000. * Updates strstart and lookahead.
  81001. *
  81002. * IN assertion: lookahead < MIN_LOOKAHEAD
  81003. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81004. * At least one byte has been read, or avail_in == 0; reads are
  81005. * performed for at least two bytes (required for the zip translate_eol
  81006. * option -- not supported here).
  81007. */
  81008. local void fill_window (deflate_state *s)
  81009. {
  81010. register unsigned n, m;
  81011. register Posf *p;
  81012. unsigned more; /* Amount of free space at the end of the window. */
  81013. uInt wsize = s->w_size;
  81014. do {
  81015. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81016. /* Deal with !@#$% 64K limit: */
  81017. if (sizeof(int) <= 2) {
  81018. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81019. more = wsize;
  81020. } else if (more == (unsigned)(-1)) {
  81021. /* Very unlikely, but possible on 16 bit machine if
  81022. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81023. */
  81024. more--;
  81025. }
  81026. }
  81027. /* If the window is almost full and there is insufficient lookahead,
  81028. * move the upper half to the lower one to make room in the upper half.
  81029. */
  81030. if (s->strstart >= wsize+MAX_DIST(s)) {
  81031. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81032. s->match_start -= wsize;
  81033. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81034. s->block_start -= (long) wsize;
  81035. /* Slide the hash table (could be avoided with 32 bit values
  81036. at the expense of memory usage). We slide even when level == 0
  81037. to keep the hash table consistent if we switch back to level > 0
  81038. later. (Using level 0 permanently is not an optimal usage of
  81039. zlib, so we don't care about this pathological case.)
  81040. */
  81041. /* %%% avoid this when Z_RLE */
  81042. n = s->hash_size;
  81043. p = &s->head[n];
  81044. do {
  81045. m = *--p;
  81046. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81047. } while (--n);
  81048. n = wsize;
  81049. #ifndef FASTEST
  81050. p = &s->prev[n];
  81051. do {
  81052. m = *--p;
  81053. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81054. /* If n is not on any hash chain, prev[n] is garbage but
  81055. * its value will never be used.
  81056. */
  81057. } while (--n);
  81058. #endif
  81059. more += wsize;
  81060. }
  81061. if (s->strm->avail_in == 0) return;
  81062. /* If there was no sliding:
  81063. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81064. * more == window_size - lookahead - strstart
  81065. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81066. * => more >= window_size - 2*WSIZE + 2
  81067. * In the BIG_MEM or MMAP case (not yet supported),
  81068. * window_size == input_size + MIN_LOOKAHEAD &&
  81069. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81070. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81071. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81072. */
  81073. Assert(more >= 2, "more < 2");
  81074. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81075. s->lookahead += n;
  81076. /* Initialize the hash value now that we have some input: */
  81077. if (s->lookahead >= MIN_MATCH) {
  81078. s->ins_h = s->window[s->strstart];
  81079. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81080. #if MIN_MATCH != 3
  81081. Call UPDATE_HASH() MIN_MATCH-3 more times
  81082. #endif
  81083. }
  81084. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81085. * but this is not important since only literal bytes will be emitted.
  81086. */
  81087. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81088. }
  81089. /* ===========================================================================
  81090. * Flush the current block, with given end-of-file flag.
  81091. * IN assertion: strstart is set to the end of the current match.
  81092. */
  81093. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81094. _tr_flush_block(s, (s->block_start >= 0L ? \
  81095. (charf *)&s->window[(unsigned)s->block_start] : \
  81096. (charf *)Z_NULL), \
  81097. (ulg)((long)s->strstart - s->block_start), \
  81098. (eof)); \
  81099. s->block_start = s->strstart; \
  81100. flush_pending(s->strm); \
  81101. Tracev((stderr,"[FLUSH]")); \
  81102. }
  81103. /* Same but force premature exit if necessary. */
  81104. #define FLUSH_BLOCK(s, eof) { \
  81105. FLUSH_BLOCK_ONLY(s, eof); \
  81106. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81107. }
  81108. /* ===========================================================================
  81109. * Copy without compression as much as possible from the input stream, return
  81110. * the current block state.
  81111. * This function does not insert new strings in the dictionary since
  81112. * uncompressible data is probably not useful. This function is used
  81113. * only for the level=0 compression option.
  81114. * NOTE: this function should be optimized to avoid extra copying from
  81115. * window to pending_buf.
  81116. */
  81117. local block_state deflate_stored(deflate_state *s, int flush)
  81118. {
  81119. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  81120. * to pending_buf_size, and each stored block has a 5 byte header:
  81121. */
  81122. ulg max_block_size = 0xffff;
  81123. ulg max_start;
  81124. if (max_block_size > s->pending_buf_size - 5) {
  81125. max_block_size = s->pending_buf_size - 5;
  81126. }
  81127. /* Copy as much as possible from input to output: */
  81128. for (;;) {
  81129. /* Fill the window as much as possible: */
  81130. if (s->lookahead <= 1) {
  81131. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  81132. s->block_start >= (long)s->w_size, "slide too late");
  81133. fill_window(s);
  81134. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  81135. if (s->lookahead == 0) break; /* flush the current block */
  81136. }
  81137. Assert(s->block_start >= 0L, "block gone");
  81138. s->strstart += s->lookahead;
  81139. s->lookahead = 0;
  81140. /* Emit a stored block if pending_buf will be full: */
  81141. max_start = s->block_start + max_block_size;
  81142. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  81143. /* strstart == 0 is possible when wraparound on 16-bit machine */
  81144. s->lookahead = (uInt)(s->strstart - max_start);
  81145. s->strstart = (uInt)max_start;
  81146. FLUSH_BLOCK(s, 0);
  81147. }
  81148. /* Flush if we may have to slide, otherwise block_start may become
  81149. * negative and the data will be gone:
  81150. */
  81151. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  81152. FLUSH_BLOCK(s, 0);
  81153. }
  81154. }
  81155. FLUSH_BLOCK(s, flush == Z_FINISH);
  81156. return flush == Z_FINISH ? finish_done : block_done;
  81157. }
  81158. /* ===========================================================================
  81159. * Compress as much as possible from the input stream, return the current
  81160. * block state.
  81161. * This function does not perform lazy evaluation of matches and inserts
  81162. * new strings in the dictionary only for unmatched strings or for short
  81163. * matches. It is used only for the fast compression options.
  81164. */
  81165. local block_state deflate_fast(deflate_state *s, int flush)
  81166. {
  81167. IPos hash_head = NIL; /* head of the hash chain */
  81168. int bflush; /* set if current block must be flushed */
  81169. for (;;) {
  81170. /* Make sure that we always have enough lookahead, except
  81171. * at the end of the input file. We need MAX_MATCH bytes
  81172. * for the next match, plus MIN_MATCH bytes to insert the
  81173. * string following the next match.
  81174. */
  81175. if (s->lookahead < MIN_LOOKAHEAD) {
  81176. fill_window(s);
  81177. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81178. return need_more;
  81179. }
  81180. if (s->lookahead == 0) break; /* flush the current block */
  81181. }
  81182. /* Insert the string window[strstart .. strstart+2] in the
  81183. * dictionary, and set hash_head to the head of the hash chain:
  81184. */
  81185. if (s->lookahead >= MIN_MATCH) {
  81186. INSERT_STRING(s, s->strstart, hash_head);
  81187. }
  81188. /* Find the longest match, discarding those <= prev_length.
  81189. * At this point we have always match_length < MIN_MATCH
  81190. */
  81191. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  81192. /* To simplify the code, we prevent matches with the string
  81193. * of window index 0 (in particular we have to avoid a match
  81194. * of the string with itself at the start of the input file).
  81195. */
  81196. #ifdef FASTEST
  81197. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  81198. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  81199. s->match_length = longest_match_fast (s, hash_head);
  81200. }
  81201. #else
  81202. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81203. s->match_length = longest_match (s, hash_head);
  81204. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81205. s->match_length = longest_match_fast (s, hash_head);
  81206. }
  81207. #endif
  81208. /* longest_match() or longest_match_fast() sets match_start */
  81209. }
  81210. if (s->match_length >= MIN_MATCH) {
  81211. check_match(s, s->strstart, s->match_start, s->match_length);
  81212. _tr_tally_dist(s, s->strstart - s->match_start,
  81213. s->match_length - MIN_MATCH, bflush);
  81214. s->lookahead -= s->match_length;
  81215. /* Insert new strings in the hash table only if the match length
  81216. * is not too large. This saves time but degrades compression.
  81217. */
  81218. #ifndef FASTEST
  81219. if (s->match_length <= s->max_insert_length &&
  81220. s->lookahead >= MIN_MATCH) {
  81221. s->match_length--; /* string at strstart already in table */
  81222. do {
  81223. s->strstart++;
  81224. INSERT_STRING(s, s->strstart, hash_head);
  81225. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  81226. * always MIN_MATCH bytes ahead.
  81227. */
  81228. } while (--s->match_length != 0);
  81229. s->strstart++;
  81230. } else
  81231. #endif
  81232. {
  81233. s->strstart += s->match_length;
  81234. s->match_length = 0;
  81235. s->ins_h = s->window[s->strstart];
  81236. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81237. #if MIN_MATCH != 3
  81238. Call UPDATE_HASH() MIN_MATCH-3 more times
  81239. #endif
  81240. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  81241. * matter since it will be recomputed at next deflate call.
  81242. */
  81243. }
  81244. } else {
  81245. /* No match, output a literal byte */
  81246. Tracevv((stderr,"%c", s->window[s->strstart]));
  81247. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81248. s->lookahead--;
  81249. s->strstart++;
  81250. }
  81251. if (bflush) FLUSH_BLOCK(s, 0);
  81252. }
  81253. FLUSH_BLOCK(s, flush == Z_FINISH);
  81254. return flush == Z_FINISH ? finish_done : block_done;
  81255. }
  81256. #ifndef FASTEST
  81257. /* ===========================================================================
  81258. * Same as above, but achieves better compression. We use a lazy
  81259. * evaluation for matches: a match is finally adopted only if there is
  81260. * no better match at the next window position.
  81261. */
  81262. local block_state deflate_slow(deflate_state *s, int flush)
  81263. {
  81264. IPos hash_head = NIL; /* head of hash chain */
  81265. int bflush; /* set if current block must be flushed */
  81266. /* Process the input block. */
  81267. for (;;) {
  81268. /* Make sure that we always have enough lookahead, except
  81269. * at the end of the input file. We need MAX_MATCH bytes
  81270. * for the next match, plus MIN_MATCH bytes to insert the
  81271. * string following the next match.
  81272. */
  81273. if (s->lookahead < MIN_LOOKAHEAD) {
  81274. fill_window(s);
  81275. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81276. return need_more;
  81277. }
  81278. if (s->lookahead == 0) break; /* flush the current block */
  81279. }
  81280. /* Insert the string window[strstart .. strstart+2] in the
  81281. * dictionary, and set hash_head to the head of the hash chain:
  81282. */
  81283. if (s->lookahead >= MIN_MATCH) {
  81284. INSERT_STRING(s, s->strstart, hash_head);
  81285. }
  81286. /* Find the longest match, discarding those <= prev_length.
  81287. */
  81288. s->prev_length = s->match_length, s->prev_match = s->match_start;
  81289. s->match_length = MIN_MATCH-1;
  81290. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  81291. s->strstart - hash_head <= MAX_DIST(s)) {
  81292. /* To simplify the code, we prevent matches with the string
  81293. * of window index 0 (in particular we have to avoid a match
  81294. * of the string with itself at the start of the input file).
  81295. */
  81296. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81297. s->match_length = longest_match (s, hash_head);
  81298. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81299. s->match_length = longest_match_fast (s, hash_head);
  81300. }
  81301. /* longest_match() or longest_match_fast() sets match_start */
  81302. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  81303. #if TOO_FAR <= 32767
  81304. || (s->match_length == MIN_MATCH &&
  81305. s->strstart - s->match_start > TOO_FAR)
  81306. #endif
  81307. )) {
  81308. /* If prev_match is also MIN_MATCH, match_start is garbage
  81309. * but we will ignore the current match anyway.
  81310. */
  81311. s->match_length = MIN_MATCH-1;
  81312. }
  81313. }
  81314. /* If there was a match at the previous step and the current
  81315. * match is not better, output the previous match:
  81316. */
  81317. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  81318. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  81319. /* Do not insert strings in hash table beyond this. */
  81320. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  81321. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  81322. s->prev_length - MIN_MATCH, bflush);
  81323. /* Insert in hash table all strings up to the end of the match.
  81324. * strstart-1 and strstart are already inserted. If there is not
  81325. * enough lookahead, the last two strings are not inserted in
  81326. * the hash table.
  81327. */
  81328. s->lookahead -= s->prev_length-1;
  81329. s->prev_length -= 2;
  81330. do {
  81331. if (++s->strstart <= max_insert) {
  81332. INSERT_STRING(s, s->strstart, hash_head);
  81333. }
  81334. } while (--s->prev_length != 0);
  81335. s->match_available = 0;
  81336. s->match_length = MIN_MATCH-1;
  81337. s->strstart++;
  81338. if (bflush) FLUSH_BLOCK(s, 0);
  81339. } else if (s->match_available) {
  81340. /* If there was no match at the previous position, output a
  81341. * single literal. If there was a match but the current match
  81342. * is longer, truncate the previous match to a single literal.
  81343. */
  81344. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81345. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81346. if (bflush) {
  81347. FLUSH_BLOCK_ONLY(s, 0);
  81348. }
  81349. s->strstart++;
  81350. s->lookahead--;
  81351. if (s->strm->avail_out == 0) return need_more;
  81352. } else {
  81353. /* There is no previous match to compare with, wait for
  81354. * the next step to decide.
  81355. */
  81356. s->match_available = 1;
  81357. s->strstart++;
  81358. s->lookahead--;
  81359. }
  81360. }
  81361. Assert (flush != Z_NO_FLUSH, "no flush?");
  81362. if (s->match_available) {
  81363. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81364. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81365. s->match_available = 0;
  81366. }
  81367. FLUSH_BLOCK(s, flush == Z_FINISH);
  81368. return flush == Z_FINISH ? finish_done : block_done;
  81369. }
  81370. #endif /* FASTEST */
  81371. #if 0
  81372. /* ===========================================================================
  81373. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  81374. * one. Do not maintain a hash table. (It will be regenerated if this run of
  81375. * deflate switches away from Z_RLE.)
  81376. */
  81377. local block_state deflate_rle(s, flush)
  81378. deflate_state *s;
  81379. int flush;
  81380. {
  81381. int bflush; /* set if current block must be flushed */
  81382. uInt run; /* length of run */
  81383. uInt max; /* maximum length of run */
  81384. uInt prev; /* byte at distance one to match */
  81385. Bytef *scan; /* scan for end of run */
  81386. for (;;) {
  81387. /* Make sure that we always have enough lookahead, except
  81388. * at the end of the input file. We need MAX_MATCH bytes
  81389. * for the longest encodable run.
  81390. */
  81391. if (s->lookahead < MAX_MATCH) {
  81392. fill_window(s);
  81393. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  81394. return need_more;
  81395. }
  81396. if (s->lookahead == 0) break; /* flush the current block */
  81397. }
  81398. /* See how many times the previous byte repeats */
  81399. run = 0;
  81400. if (s->strstart > 0) { /* if there is a previous byte, that is */
  81401. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  81402. scan = s->window + s->strstart - 1;
  81403. prev = *scan++;
  81404. do {
  81405. if (*scan++ != prev)
  81406. break;
  81407. } while (++run < max);
  81408. }
  81409. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  81410. if (run >= MIN_MATCH) {
  81411. check_match(s, s->strstart, s->strstart - 1, run);
  81412. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  81413. s->lookahead -= run;
  81414. s->strstart += run;
  81415. } else {
  81416. /* No match, output a literal byte */
  81417. Tracevv((stderr,"%c", s->window[s->strstart]));
  81418. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81419. s->lookahead--;
  81420. s->strstart++;
  81421. }
  81422. if (bflush) FLUSH_BLOCK(s, 0);
  81423. }
  81424. FLUSH_BLOCK(s, flush == Z_FINISH);
  81425. return flush == Z_FINISH ? finish_done : block_done;
  81426. }
  81427. #endif
  81428. /*** End of inlined file: deflate.c ***/
  81429. /*** Start of inlined file: inffast.c ***/
  81430. /*** Start of inlined file: inftrees.h ***/
  81431. /* WARNING: this file should *not* be used by applications. It is
  81432. part of the implementation of the compression library and is
  81433. subject to change. Applications should only use zlib.h.
  81434. */
  81435. #ifndef _INFTREES_H_
  81436. #define _INFTREES_H_
  81437. /* Structure for decoding tables. Each entry provides either the
  81438. information needed to do the operation requested by the code that
  81439. indexed that table entry, or it provides a pointer to another
  81440. table that indexes more bits of the code. op indicates whether
  81441. the entry is a pointer to another table, a literal, a length or
  81442. distance, an end-of-block, or an invalid code. For a table
  81443. pointer, the low four bits of op is the number of index bits of
  81444. that table. For a length or distance, the low four bits of op
  81445. is the number of extra bits to get after the code. bits is
  81446. the number of bits in this code or part of the code to drop off
  81447. of the bit buffer. val is the actual byte to output in the case
  81448. of a literal, the base length or distance, or the offset from
  81449. the current table to the next table. Each entry is four bytes. */
  81450. typedef struct {
  81451. unsigned char op; /* operation, extra bits, table bits */
  81452. unsigned char bits; /* bits in this part of the code */
  81453. unsigned short val; /* offset in table or code value */
  81454. } code;
  81455. /* op values as set by inflate_table():
  81456. 00000000 - literal
  81457. 0000tttt - table link, tttt != 0 is the number of table index bits
  81458. 0001eeee - length or distance, eeee is the number of extra bits
  81459. 01100000 - end of block
  81460. 01000000 - invalid code
  81461. */
  81462. /* Maximum size of dynamic tree. The maximum found in a long but non-
  81463. exhaustive search was 1444 code structures (852 for length/literals
  81464. and 592 for distances, the latter actually the result of an
  81465. exhaustive search). The true maximum is not known, but the value
  81466. below is more than safe. */
  81467. #define ENOUGH 2048
  81468. #define MAXD 592
  81469. /* Type of code to build for inftable() */
  81470. typedef enum {
  81471. CODES,
  81472. LENS,
  81473. DISTS
  81474. } codetype;
  81475. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  81476. unsigned codes, code FAR * FAR *table,
  81477. unsigned FAR *bits, unsigned short FAR *work));
  81478. #endif
  81479. /*** End of inlined file: inftrees.h ***/
  81480. /*** Start of inlined file: inflate.h ***/
  81481. /* WARNING: this file should *not* be used by applications. It is
  81482. part of the implementation of the compression library and is
  81483. subject to change. Applications should only use zlib.h.
  81484. */
  81485. #ifndef _INFLATE_H_
  81486. #define _INFLATE_H_
  81487. /* define NO_GZIP when compiling if you want to disable gzip header and
  81488. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  81489. the crc code when it is not needed. For shared libraries, gzip decoding
  81490. should be left enabled. */
  81491. #ifndef NO_GZIP
  81492. # define GUNZIP
  81493. #endif
  81494. /* Possible inflate modes between inflate() calls */
  81495. typedef enum {
  81496. HEAD, /* i: waiting for magic header */
  81497. FLAGS, /* i: waiting for method and flags (gzip) */
  81498. TIME, /* i: waiting for modification time (gzip) */
  81499. OS, /* i: waiting for extra flags and operating system (gzip) */
  81500. EXLEN, /* i: waiting for extra length (gzip) */
  81501. EXTRA, /* i: waiting for extra bytes (gzip) */
  81502. NAME, /* i: waiting for end of file name (gzip) */
  81503. COMMENT, /* i: waiting for end of comment (gzip) */
  81504. HCRC, /* i: waiting for header crc (gzip) */
  81505. DICTID, /* i: waiting for dictionary check value */
  81506. DICT, /* waiting for inflateSetDictionary() call */
  81507. TYPE, /* i: waiting for type bits, including last-flag bit */
  81508. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  81509. STORED, /* i: waiting for stored size (length and complement) */
  81510. COPY, /* i/o: waiting for input or output to copy stored block */
  81511. TABLE, /* i: waiting for dynamic block table lengths */
  81512. LENLENS, /* i: waiting for code length code lengths */
  81513. CODELENS, /* i: waiting for length/lit and distance code lengths */
  81514. LEN, /* i: waiting for length/lit code */
  81515. LENEXT, /* i: waiting for length extra bits */
  81516. DIST, /* i: waiting for distance code */
  81517. DISTEXT, /* i: waiting for distance extra bits */
  81518. MATCH, /* o: waiting for output space to copy string */
  81519. LIT, /* o: waiting for output space to write literal */
  81520. CHECK, /* i: waiting for 32-bit check value */
  81521. LENGTH, /* i: waiting for 32-bit length (gzip) */
  81522. DONE, /* finished check, done -- remain here until reset */
  81523. BAD, /* got a data error -- remain here until reset */
  81524. MEM, /* got an inflate() memory error -- remain here until reset */
  81525. SYNC /* looking for synchronization bytes to restart inflate() */
  81526. } inflate_mode;
  81527. /*
  81528. State transitions between above modes -
  81529. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  81530. Process header:
  81531. HEAD -> (gzip) or (zlib)
  81532. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  81533. NAME -> COMMENT -> HCRC -> TYPE
  81534. (zlib) -> DICTID or TYPE
  81535. DICTID -> DICT -> TYPE
  81536. Read deflate blocks:
  81537. TYPE -> STORED or TABLE or LEN or CHECK
  81538. STORED -> COPY -> TYPE
  81539. TABLE -> LENLENS -> CODELENS -> LEN
  81540. Read deflate codes:
  81541. LEN -> LENEXT or LIT or TYPE
  81542. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  81543. LIT -> LEN
  81544. Process trailer:
  81545. CHECK -> LENGTH -> DONE
  81546. */
  81547. /* state maintained between inflate() calls. Approximately 7K bytes. */
  81548. struct inflate_state {
  81549. inflate_mode mode; /* current inflate mode */
  81550. int last; /* true if processing last block */
  81551. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81552. int havedict; /* true if dictionary provided */
  81553. int flags; /* gzip header method and flags (0 if zlib) */
  81554. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  81555. unsigned long check; /* protected copy of check value */
  81556. unsigned long total; /* protected copy of output count */
  81557. gz_headerp head; /* where to save gzip header information */
  81558. /* sliding window */
  81559. unsigned wbits; /* log base 2 of requested window size */
  81560. unsigned wsize; /* window size or zero if not using window */
  81561. unsigned whave; /* valid bytes in the window */
  81562. unsigned write; /* window write index */
  81563. unsigned char FAR *window; /* allocated sliding window, if needed */
  81564. /* bit accumulator */
  81565. unsigned long hold; /* input bit accumulator */
  81566. unsigned bits; /* number of bits in "in" */
  81567. /* for string and stored block copying */
  81568. unsigned length; /* literal or length of data to copy */
  81569. unsigned offset; /* distance back to copy string from */
  81570. /* for table and code decoding */
  81571. unsigned extra; /* extra bits needed */
  81572. /* fixed and dynamic code tables */
  81573. code const FAR *lencode; /* starting table for length/literal codes */
  81574. code const FAR *distcode; /* starting table for distance codes */
  81575. unsigned lenbits; /* index bits for lencode */
  81576. unsigned distbits; /* index bits for distcode */
  81577. /* dynamic table building */
  81578. unsigned ncode; /* number of code length code lengths */
  81579. unsigned nlen; /* number of length code lengths */
  81580. unsigned ndist; /* number of distance code lengths */
  81581. unsigned have; /* number of code lengths in lens[] */
  81582. code FAR *next; /* next available space in codes[] */
  81583. unsigned short lens[320]; /* temporary storage for code lengths */
  81584. unsigned short work[288]; /* work area for code table building */
  81585. code codes[ENOUGH]; /* space for code tables */
  81586. };
  81587. #endif
  81588. /*** End of inlined file: inflate.h ***/
  81589. /*** Start of inlined file: inffast.h ***/
  81590. /* WARNING: this file should *not* be used by applications. It is
  81591. part of the implementation of the compression library and is
  81592. subject to change. Applications should only use zlib.h.
  81593. */
  81594. void inflate_fast OF((z_streamp strm, unsigned start));
  81595. /*** End of inlined file: inffast.h ***/
  81596. #ifndef ASMINF
  81597. /* Allow machine dependent optimization for post-increment or pre-increment.
  81598. Based on testing to date,
  81599. Pre-increment preferred for:
  81600. - PowerPC G3 (Adler)
  81601. - MIPS R5000 (Randers-Pehrson)
  81602. Post-increment preferred for:
  81603. - none
  81604. No measurable difference:
  81605. - Pentium III (Anderson)
  81606. - M68060 (Nikl)
  81607. */
  81608. #ifdef POSTINC
  81609. # define OFF 0
  81610. # define PUP(a) *(a)++
  81611. #else
  81612. # define OFF 1
  81613. # define PUP(a) *++(a)
  81614. #endif
  81615. /*
  81616. Decode literal, length, and distance codes and write out the resulting
  81617. literal and match bytes until either not enough input or output is
  81618. available, an end-of-block is encountered, or a data error is encountered.
  81619. When large enough input and output buffers are supplied to inflate(), for
  81620. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  81621. inflate execution time is spent in this routine.
  81622. Entry assumptions:
  81623. state->mode == LEN
  81624. strm->avail_in >= 6
  81625. strm->avail_out >= 258
  81626. start >= strm->avail_out
  81627. state->bits < 8
  81628. On return, state->mode is one of:
  81629. LEN -- ran out of enough output space or enough available input
  81630. TYPE -- reached end of block code, inflate() to interpret next block
  81631. BAD -- error in block data
  81632. Notes:
  81633. - The maximum input bits used by a length/distance pair is 15 bits for the
  81634. length code, 5 bits for the length extra, 15 bits for the distance code,
  81635. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  81636. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  81637. checking for available input while decoding.
  81638. - The maximum bytes that a single length/distance pair can output is 258
  81639. bytes, which is the maximum length that can be coded. inflate_fast()
  81640. requires strm->avail_out >= 258 for each loop to avoid checking for
  81641. output space.
  81642. */
  81643. void inflate_fast (z_streamp strm, unsigned start)
  81644. {
  81645. struct inflate_state FAR *state;
  81646. unsigned char FAR *in; /* local strm->next_in */
  81647. unsigned char FAR *last; /* while in < last, enough input available */
  81648. unsigned char FAR *out; /* local strm->next_out */
  81649. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  81650. unsigned char FAR *end; /* while out < end, enough space available */
  81651. #ifdef INFLATE_STRICT
  81652. unsigned dmax; /* maximum distance from zlib header */
  81653. #endif
  81654. unsigned wsize; /* window size or zero if not using window */
  81655. unsigned whave; /* valid bytes in the window */
  81656. unsigned write; /* window write index */
  81657. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  81658. unsigned long hold; /* local strm->hold */
  81659. unsigned bits; /* local strm->bits */
  81660. code const FAR *lcode; /* local strm->lencode */
  81661. code const FAR *dcode; /* local strm->distcode */
  81662. unsigned lmask; /* mask for first level of length codes */
  81663. unsigned dmask; /* mask for first level of distance codes */
  81664. code thisx; /* retrieved table entry */
  81665. unsigned op; /* code bits, operation, extra bits, or */
  81666. /* window position, window bytes to copy */
  81667. unsigned len; /* match length, unused bytes */
  81668. unsigned dist; /* match distance */
  81669. unsigned char FAR *from; /* where to copy match from */
  81670. /* copy state to local variables */
  81671. state = (struct inflate_state FAR *)strm->state;
  81672. in = strm->next_in - OFF;
  81673. last = in + (strm->avail_in - 5);
  81674. out = strm->next_out - OFF;
  81675. beg = out - (start - strm->avail_out);
  81676. end = out + (strm->avail_out - 257);
  81677. #ifdef INFLATE_STRICT
  81678. dmax = state->dmax;
  81679. #endif
  81680. wsize = state->wsize;
  81681. whave = state->whave;
  81682. write = state->write;
  81683. window = state->window;
  81684. hold = state->hold;
  81685. bits = state->bits;
  81686. lcode = state->lencode;
  81687. dcode = state->distcode;
  81688. lmask = (1U << state->lenbits) - 1;
  81689. dmask = (1U << state->distbits) - 1;
  81690. /* decode literals and length/distances until end-of-block or not enough
  81691. input data or output space */
  81692. do {
  81693. if (bits < 15) {
  81694. hold += (unsigned long)(PUP(in)) << bits;
  81695. bits += 8;
  81696. hold += (unsigned long)(PUP(in)) << bits;
  81697. bits += 8;
  81698. }
  81699. thisx = lcode[hold & lmask];
  81700. dolen:
  81701. op = (unsigned)(thisx.bits);
  81702. hold >>= op;
  81703. bits -= op;
  81704. op = (unsigned)(thisx.op);
  81705. if (op == 0) { /* literal */
  81706. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  81707. "inflate: literal '%c'\n" :
  81708. "inflate: literal 0x%02x\n", thisx.val));
  81709. PUP(out) = (unsigned char)(thisx.val);
  81710. }
  81711. else if (op & 16) { /* length base */
  81712. len = (unsigned)(thisx.val);
  81713. op &= 15; /* number of extra bits */
  81714. if (op) {
  81715. if (bits < op) {
  81716. hold += (unsigned long)(PUP(in)) << bits;
  81717. bits += 8;
  81718. }
  81719. len += (unsigned)hold & ((1U << op) - 1);
  81720. hold >>= op;
  81721. bits -= op;
  81722. }
  81723. Tracevv((stderr, "inflate: length %u\n", len));
  81724. if (bits < 15) {
  81725. hold += (unsigned long)(PUP(in)) << bits;
  81726. bits += 8;
  81727. hold += (unsigned long)(PUP(in)) << bits;
  81728. bits += 8;
  81729. }
  81730. thisx = dcode[hold & dmask];
  81731. dodist:
  81732. op = (unsigned)(thisx.bits);
  81733. hold >>= op;
  81734. bits -= op;
  81735. op = (unsigned)(thisx.op);
  81736. if (op & 16) { /* distance base */
  81737. dist = (unsigned)(thisx.val);
  81738. op &= 15; /* number of extra bits */
  81739. if (bits < op) {
  81740. hold += (unsigned long)(PUP(in)) << bits;
  81741. bits += 8;
  81742. if (bits < op) {
  81743. hold += (unsigned long)(PUP(in)) << bits;
  81744. bits += 8;
  81745. }
  81746. }
  81747. dist += (unsigned)hold & ((1U << op) - 1);
  81748. #ifdef INFLATE_STRICT
  81749. if (dist > dmax) {
  81750. strm->msg = (char *)"invalid distance too far back";
  81751. state->mode = BAD;
  81752. break;
  81753. }
  81754. #endif
  81755. hold >>= op;
  81756. bits -= op;
  81757. Tracevv((stderr, "inflate: distance %u\n", dist));
  81758. op = (unsigned)(out - beg); /* max distance in output */
  81759. if (dist > op) { /* see if copy from window */
  81760. op = dist - op; /* distance back in window */
  81761. if (op > whave) {
  81762. strm->msg = (char *)"invalid distance too far back";
  81763. state->mode = BAD;
  81764. break;
  81765. }
  81766. from = window - OFF;
  81767. if (write == 0) { /* very common case */
  81768. from += wsize - op;
  81769. if (op < len) { /* some from window */
  81770. len -= op;
  81771. do {
  81772. PUP(out) = PUP(from);
  81773. } while (--op);
  81774. from = out - dist; /* rest from output */
  81775. }
  81776. }
  81777. else if (write < op) { /* wrap around window */
  81778. from += wsize + write - op;
  81779. op -= write;
  81780. if (op < len) { /* some from end of window */
  81781. len -= op;
  81782. do {
  81783. PUP(out) = PUP(from);
  81784. } while (--op);
  81785. from = window - OFF;
  81786. if (write < len) { /* some from start of window */
  81787. op = write;
  81788. len -= op;
  81789. do {
  81790. PUP(out) = PUP(from);
  81791. } while (--op);
  81792. from = out - dist; /* rest from output */
  81793. }
  81794. }
  81795. }
  81796. else { /* contiguous in window */
  81797. from += write - op;
  81798. if (op < len) { /* some from window */
  81799. len -= op;
  81800. do {
  81801. PUP(out) = PUP(from);
  81802. } while (--op);
  81803. from = out - dist; /* rest from output */
  81804. }
  81805. }
  81806. while (len > 2) {
  81807. PUP(out) = PUP(from);
  81808. PUP(out) = PUP(from);
  81809. PUP(out) = PUP(from);
  81810. len -= 3;
  81811. }
  81812. if (len) {
  81813. PUP(out) = PUP(from);
  81814. if (len > 1)
  81815. PUP(out) = PUP(from);
  81816. }
  81817. }
  81818. else {
  81819. from = out - dist; /* copy direct from output */
  81820. do { /* minimum length is three */
  81821. PUP(out) = PUP(from);
  81822. PUP(out) = PUP(from);
  81823. PUP(out) = PUP(from);
  81824. len -= 3;
  81825. } while (len > 2);
  81826. if (len) {
  81827. PUP(out) = PUP(from);
  81828. if (len > 1)
  81829. PUP(out) = PUP(from);
  81830. }
  81831. }
  81832. }
  81833. else if ((op & 64) == 0) { /* 2nd level distance code */
  81834. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  81835. goto dodist;
  81836. }
  81837. else {
  81838. strm->msg = (char *)"invalid distance code";
  81839. state->mode = BAD;
  81840. break;
  81841. }
  81842. }
  81843. else if ((op & 64) == 0) { /* 2nd level length code */
  81844. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  81845. goto dolen;
  81846. }
  81847. else if (op & 32) { /* end-of-block */
  81848. Tracevv((stderr, "inflate: end of block\n"));
  81849. state->mode = TYPE;
  81850. break;
  81851. }
  81852. else {
  81853. strm->msg = (char *)"invalid literal/length code";
  81854. state->mode = BAD;
  81855. break;
  81856. }
  81857. } while (in < last && out < end);
  81858. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  81859. len = bits >> 3;
  81860. in -= len;
  81861. bits -= len << 3;
  81862. hold &= (1U << bits) - 1;
  81863. /* update state and return */
  81864. strm->next_in = in + OFF;
  81865. strm->next_out = out + OFF;
  81866. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  81867. strm->avail_out = (unsigned)(out < end ?
  81868. 257 + (end - out) : 257 - (out - end));
  81869. state->hold = hold;
  81870. state->bits = bits;
  81871. return;
  81872. }
  81873. /*
  81874. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  81875. - Using bit fields for code structure
  81876. - Different op definition to avoid & for extra bits (do & for table bits)
  81877. - Three separate decoding do-loops for direct, window, and write == 0
  81878. - Special case for distance > 1 copies to do overlapped load and store copy
  81879. - Explicit branch predictions (based on measured branch probabilities)
  81880. - Deferring match copy and interspersed it with decoding subsequent codes
  81881. - Swapping literal/length else
  81882. - Swapping window/direct else
  81883. - Larger unrolled copy loops (three is about right)
  81884. - Moving len -= 3 statement into middle of loop
  81885. */
  81886. #endif /* !ASMINF */
  81887. /*** End of inlined file: inffast.c ***/
  81888. #undef PULLBYTE
  81889. #undef LOAD
  81890. #undef RESTORE
  81891. #undef INITBITS
  81892. #undef NEEDBITS
  81893. #undef DROPBITS
  81894. #undef BYTEBITS
  81895. /*** Start of inlined file: inflate.c ***/
  81896. /*
  81897. * Change history:
  81898. *
  81899. * 1.2.beta0 24 Nov 2002
  81900. * - First version -- complete rewrite of inflate to simplify code, avoid
  81901. * creation of window when not needed, minimize use of window when it is
  81902. * needed, make inffast.c even faster, implement gzip decoding, and to
  81903. * improve code readability and style over the previous zlib inflate code
  81904. *
  81905. * 1.2.beta1 25 Nov 2002
  81906. * - Use pointers for available input and output checking in inffast.c
  81907. * - Remove input and output counters in inffast.c
  81908. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  81909. * - Remove unnecessary second byte pull from length extra in inffast.c
  81910. * - Unroll direct copy to three copies per loop in inffast.c
  81911. *
  81912. * 1.2.beta2 4 Dec 2002
  81913. * - Change external routine names to reduce potential conflicts
  81914. * - Correct filename to inffixed.h for fixed tables in inflate.c
  81915. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  81916. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  81917. * to avoid negation problem on Alphas (64 bit) in inflate.c
  81918. *
  81919. * 1.2.beta3 22 Dec 2002
  81920. * - Add comments on state->bits assertion in inffast.c
  81921. * - Add comments on op field in inftrees.h
  81922. * - Fix bug in reuse of allocated window after inflateReset()
  81923. * - Remove bit fields--back to byte structure for speed
  81924. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  81925. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  81926. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  81927. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  81928. * - Use local copies of stream next and avail values, as well as local bit
  81929. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  81930. *
  81931. * 1.2.beta4 1 Jan 2003
  81932. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  81933. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  81934. * - Add comments in inffast.c to introduce the inflate_fast() routine
  81935. * - Rearrange window copies in inflate_fast() for speed and simplification
  81936. * - Unroll last copy for window match in inflate_fast()
  81937. * - Use local copies of window variables in inflate_fast() for speed
  81938. * - Pull out common write == 0 case for speed in inflate_fast()
  81939. * - Make op and len in inflate_fast() unsigned for consistency
  81940. * - Add FAR to lcode and dcode declarations in inflate_fast()
  81941. * - Simplified bad distance check in inflate_fast()
  81942. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  81943. * source file infback.c to provide a call-back interface to inflate for
  81944. * programs like gzip and unzip -- uses window as output buffer to avoid
  81945. * window copying
  81946. *
  81947. * 1.2.beta5 1 Jan 2003
  81948. * - Improved inflateBack() interface to allow the caller to provide initial
  81949. * input in strm.
  81950. * - Fixed stored blocks bug in inflateBack()
  81951. *
  81952. * 1.2.beta6 4 Jan 2003
  81953. * - Added comments in inffast.c on effectiveness of POSTINC
  81954. * - Typecasting all around to reduce compiler warnings
  81955. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  81956. * make compilers happy
  81957. * - Changed type of window in inflateBackInit() to unsigned char *
  81958. *
  81959. * 1.2.beta7 27 Jan 2003
  81960. * - Changed many types to unsigned or unsigned short to avoid warnings
  81961. * - Added inflateCopy() function
  81962. *
  81963. * 1.2.0 9 Mar 2003
  81964. * - Changed inflateBack() interface to provide separate opaque descriptors
  81965. * for the in() and out() functions
  81966. * - Changed inflateBack() argument and in_func typedef to swap the length
  81967. * and buffer address return values for the input function
  81968. * - Check next_in and next_out for Z_NULL on entry to inflate()
  81969. *
  81970. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  81971. */
  81972. /*** Start of inlined file: inffast.h ***/
  81973. /* WARNING: this file should *not* be used by applications. It is
  81974. part of the implementation of the compression library and is
  81975. subject to change. Applications should only use zlib.h.
  81976. */
  81977. void inflate_fast OF((z_streamp strm, unsigned start));
  81978. /*** End of inlined file: inffast.h ***/
  81979. #ifdef MAKEFIXED
  81980. # ifndef BUILDFIXED
  81981. # define BUILDFIXED
  81982. # endif
  81983. #endif
  81984. /* function prototypes */
  81985. local void fixedtables OF((struct inflate_state FAR *state));
  81986. local int updatewindow OF((z_streamp strm, unsigned out));
  81987. #ifdef BUILDFIXED
  81988. void makefixed OF((void));
  81989. #endif
  81990. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  81991. unsigned len));
  81992. int ZEXPORT inflateReset (z_streamp strm)
  81993. {
  81994. struct inflate_state FAR *state;
  81995. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81996. state = (struct inflate_state FAR *)strm->state;
  81997. strm->total_in = strm->total_out = state->total = 0;
  81998. strm->msg = Z_NULL;
  81999. strm->adler = 1; /* to support ill-conceived Java test suite */
  82000. state->mode = HEAD;
  82001. state->last = 0;
  82002. state->havedict = 0;
  82003. state->dmax = 32768U;
  82004. state->head = Z_NULL;
  82005. state->wsize = 0;
  82006. state->whave = 0;
  82007. state->write = 0;
  82008. state->hold = 0;
  82009. state->bits = 0;
  82010. state->lencode = state->distcode = state->next = state->codes;
  82011. Tracev((stderr, "inflate: reset\n"));
  82012. return Z_OK;
  82013. }
  82014. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82015. {
  82016. struct inflate_state FAR *state;
  82017. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82018. state = (struct inflate_state FAR *)strm->state;
  82019. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82020. value &= (1L << bits) - 1;
  82021. state->hold += value << state->bits;
  82022. state->bits += bits;
  82023. return Z_OK;
  82024. }
  82025. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82026. {
  82027. struct inflate_state FAR *state;
  82028. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82029. stream_size != (int)(sizeof(z_stream)))
  82030. return Z_VERSION_ERROR;
  82031. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82032. strm->msg = Z_NULL; /* in case we return an error */
  82033. if (strm->zalloc == (alloc_func)0) {
  82034. strm->zalloc = zcalloc;
  82035. strm->opaque = (voidpf)0;
  82036. }
  82037. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82038. state = (struct inflate_state FAR *)
  82039. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82040. if (state == Z_NULL) return Z_MEM_ERROR;
  82041. Tracev((stderr, "inflate: allocated\n"));
  82042. strm->state = (struct internal_state FAR *)state;
  82043. if (windowBits < 0) {
  82044. state->wrap = 0;
  82045. windowBits = -windowBits;
  82046. }
  82047. else {
  82048. state->wrap = (windowBits >> 4) + 1;
  82049. #ifdef GUNZIP
  82050. if (windowBits < 48) windowBits &= 15;
  82051. #endif
  82052. }
  82053. if (windowBits < 8 || windowBits > 15) {
  82054. ZFREE(strm, state);
  82055. strm->state = Z_NULL;
  82056. return Z_STREAM_ERROR;
  82057. }
  82058. state->wbits = (unsigned)windowBits;
  82059. state->window = Z_NULL;
  82060. return inflateReset(strm);
  82061. }
  82062. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82063. {
  82064. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82065. }
  82066. /*
  82067. Return state with length and distance decoding tables and index sizes set to
  82068. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82069. If BUILDFIXED is defined, then instead this routine builds the tables the
  82070. first time it's called, and returns those tables the first time and
  82071. thereafter. This reduces the size of the code by about 2K bytes, in
  82072. exchange for a little execution time. However, BUILDFIXED should not be
  82073. used for threaded applications, since the rewriting of the tables and virgin
  82074. may not be thread-safe.
  82075. */
  82076. local void fixedtables (struct inflate_state FAR *state)
  82077. {
  82078. #ifdef BUILDFIXED
  82079. static int virgin = 1;
  82080. static code *lenfix, *distfix;
  82081. static code fixed[544];
  82082. /* build fixed huffman tables if first call (may not be thread safe) */
  82083. if (virgin) {
  82084. unsigned sym, bits;
  82085. static code *next;
  82086. /* literal/length table */
  82087. sym = 0;
  82088. while (sym < 144) state->lens[sym++] = 8;
  82089. while (sym < 256) state->lens[sym++] = 9;
  82090. while (sym < 280) state->lens[sym++] = 7;
  82091. while (sym < 288) state->lens[sym++] = 8;
  82092. next = fixed;
  82093. lenfix = next;
  82094. bits = 9;
  82095. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82096. /* distance table */
  82097. sym = 0;
  82098. while (sym < 32) state->lens[sym++] = 5;
  82099. distfix = next;
  82100. bits = 5;
  82101. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82102. /* do this just once */
  82103. virgin = 0;
  82104. }
  82105. #else /* !BUILDFIXED */
  82106. /*** Start of inlined file: inffixed.h ***/
  82107. /* WARNING: this file should *not* be used by applications. It
  82108. is part of the implementation of the compression library and
  82109. is subject to change. Applications should only use zlib.h.
  82110. */
  82111. static const code lenfix[512] = {
  82112. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82113. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  82114. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  82115. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  82116. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  82117. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  82118. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  82119. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  82120. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  82121. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  82122. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  82123. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  82124. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  82125. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  82126. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  82127. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  82128. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  82129. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  82130. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  82131. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  82132. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  82133. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  82134. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  82135. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  82136. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  82137. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  82138. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  82139. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  82140. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  82141. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  82142. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  82143. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  82144. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  82145. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  82146. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  82147. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  82148. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  82149. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  82150. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  82151. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  82152. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  82153. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  82154. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  82155. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  82156. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  82157. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  82158. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  82159. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  82160. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  82161. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  82162. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  82163. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  82164. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  82165. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  82166. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  82167. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  82168. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  82169. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  82170. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  82171. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  82172. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  82173. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  82174. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  82175. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  82176. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  82177. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  82178. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  82179. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  82180. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  82181. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  82182. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  82183. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  82184. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  82185. {0,9,255}
  82186. };
  82187. static const code distfix[32] = {
  82188. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  82189. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  82190. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  82191. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  82192. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  82193. {22,5,193},{64,5,0}
  82194. };
  82195. /*** End of inlined file: inffixed.h ***/
  82196. #endif /* BUILDFIXED */
  82197. state->lencode = lenfix;
  82198. state->lenbits = 9;
  82199. state->distcode = distfix;
  82200. state->distbits = 5;
  82201. }
  82202. #ifdef MAKEFIXED
  82203. #include <stdio.h>
  82204. /*
  82205. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  82206. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  82207. those tables to stdout, which would be piped to inffixed.h. A small program
  82208. can simply call makefixed to do this:
  82209. void makefixed(void);
  82210. int main(void)
  82211. {
  82212. makefixed();
  82213. return 0;
  82214. }
  82215. Then that can be linked with zlib built with MAKEFIXED defined and run:
  82216. a.out > inffixed.h
  82217. */
  82218. void makefixed()
  82219. {
  82220. unsigned low, size;
  82221. struct inflate_state state;
  82222. fixedtables(&state);
  82223. puts(" /* inffixed.h -- table for decoding fixed codes");
  82224. puts(" * Generated automatically by makefixed().");
  82225. puts(" */");
  82226. puts("");
  82227. puts(" /* WARNING: this file should *not* be used by applications.");
  82228. puts(" It is part of the implementation of this library and is");
  82229. puts(" subject to change. Applications should only use zlib.h.");
  82230. puts(" */");
  82231. puts("");
  82232. size = 1U << 9;
  82233. printf(" static const code lenfix[%u] = {", size);
  82234. low = 0;
  82235. for (;;) {
  82236. if ((low % 7) == 0) printf("\n ");
  82237. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  82238. state.lencode[low].val);
  82239. if (++low == size) break;
  82240. putchar(',');
  82241. }
  82242. puts("\n };");
  82243. size = 1U << 5;
  82244. printf("\n static const code distfix[%u] = {", size);
  82245. low = 0;
  82246. for (;;) {
  82247. if ((low % 6) == 0) printf("\n ");
  82248. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  82249. state.distcode[low].val);
  82250. if (++low == size) break;
  82251. putchar(',');
  82252. }
  82253. puts("\n };");
  82254. }
  82255. #endif /* MAKEFIXED */
  82256. /*
  82257. Update the window with the last wsize (normally 32K) bytes written before
  82258. returning. If window does not exist yet, create it. This is only called
  82259. when a window is already in use, or when output has been written during this
  82260. inflate call, but the end of the deflate stream has not been reached yet.
  82261. It is also called to create a window for dictionary data when a dictionary
  82262. is loaded.
  82263. Providing output buffers larger than 32K to inflate() should provide a speed
  82264. advantage, since only the last 32K of output is copied to the sliding window
  82265. upon return from inflate(), and since all distances after the first 32K of
  82266. output will fall in the output data, making match copies simpler and faster.
  82267. The advantage may be dependent on the size of the processor's data caches.
  82268. */
  82269. local int updatewindow (z_streamp strm, unsigned out)
  82270. {
  82271. struct inflate_state FAR *state;
  82272. unsigned copy, dist;
  82273. state = (struct inflate_state FAR *)strm->state;
  82274. /* if it hasn't been done already, allocate space for the window */
  82275. if (state->window == Z_NULL) {
  82276. state->window = (unsigned char FAR *)
  82277. ZALLOC(strm, 1U << state->wbits,
  82278. sizeof(unsigned char));
  82279. if (state->window == Z_NULL) return 1;
  82280. }
  82281. /* if window not in use yet, initialize */
  82282. if (state->wsize == 0) {
  82283. state->wsize = 1U << state->wbits;
  82284. state->write = 0;
  82285. state->whave = 0;
  82286. }
  82287. /* copy state->wsize or less output bytes into the circular window */
  82288. copy = out - strm->avail_out;
  82289. if (copy >= state->wsize) {
  82290. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  82291. state->write = 0;
  82292. state->whave = state->wsize;
  82293. }
  82294. else {
  82295. dist = state->wsize - state->write;
  82296. if (dist > copy) dist = copy;
  82297. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  82298. copy -= dist;
  82299. if (copy) {
  82300. zmemcpy(state->window, strm->next_out - copy, copy);
  82301. state->write = copy;
  82302. state->whave = state->wsize;
  82303. }
  82304. else {
  82305. state->write += dist;
  82306. if (state->write == state->wsize) state->write = 0;
  82307. if (state->whave < state->wsize) state->whave += dist;
  82308. }
  82309. }
  82310. return 0;
  82311. }
  82312. /* Macros for inflate(): */
  82313. /* check function to use adler32() for zlib or crc32() for gzip */
  82314. #ifdef GUNZIP
  82315. # define UPDATE(check, buf, len) \
  82316. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  82317. #else
  82318. # define UPDATE(check, buf, len) adler32(check, buf, len)
  82319. #endif
  82320. /* check macros for header crc */
  82321. #ifdef GUNZIP
  82322. # define CRC2(check, word) \
  82323. do { \
  82324. hbuf[0] = (unsigned char)(word); \
  82325. hbuf[1] = (unsigned char)((word) >> 8); \
  82326. check = crc32(check, hbuf, 2); \
  82327. } while (0)
  82328. # define CRC4(check, word) \
  82329. do { \
  82330. hbuf[0] = (unsigned char)(word); \
  82331. hbuf[1] = (unsigned char)((word) >> 8); \
  82332. hbuf[2] = (unsigned char)((word) >> 16); \
  82333. hbuf[3] = (unsigned char)((word) >> 24); \
  82334. check = crc32(check, hbuf, 4); \
  82335. } while (0)
  82336. #endif
  82337. /* Load registers with state in inflate() for speed */
  82338. #define LOAD() \
  82339. do { \
  82340. put = strm->next_out; \
  82341. left = strm->avail_out; \
  82342. next = strm->next_in; \
  82343. have = strm->avail_in; \
  82344. hold = state->hold; \
  82345. bits = state->bits; \
  82346. } while (0)
  82347. /* Restore state from registers in inflate() */
  82348. #define RESTORE() \
  82349. do { \
  82350. strm->next_out = put; \
  82351. strm->avail_out = left; \
  82352. strm->next_in = next; \
  82353. strm->avail_in = have; \
  82354. state->hold = hold; \
  82355. state->bits = bits; \
  82356. } while (0)
  82357. /* Clear the input bit accumulator */
  82358. #define INITBITS() \
  82359. do { \
  82360. hold = 0; \
  82361. bits = 0; \
  82362. } while (0)
  82363. /* Get a byte of input into the bit accumulator, or return from inflate()
  82364. if there is no input available. */
  82365. #define PULLBYTE() \
  82366. do { \
  82367. if (have == 0) goto inf_leave; \
  82368. have--; \
  82369. hold += (unsigned long)(*next++) << bits; \
  82370. bits += 8; \
  82371. } while (0)
  82372. /* Assure that there are at least n bits in the bit accumulator. If there is
  82373. not enough available input to do that, then return from inflate(). */
  82374. #define NEEDBITS(n) \
  82375. do { \
  82376. while (bits < (unsigned)(n)) \
  82377. PULLBYTE(); \
  82378. } while (0)
  82379. /* Return the low n bits of the bit accumulator (n < 16) */
  82380. #define BITS(n) \
  82381. ((unsigned)hold & ((1U << (n)) - 1))
  82382. /* Remove n bits from the bit accumulator */
  82383. #define DROPBITS(n) \
  82384. do { \
  82385. hold >>= (n); \
  82386. bits -= (unsigned)(n); \
  82387. } while (0)
  82388. /* Remove zero to seven bits as needed to go to a byte boundary */
  82389. #define BYTEBITS() \
  82390. do { \
  82391. hold >>= bits & 7; \
  82392. bits -= bits & 7; \
  82393. } while (0)
  82394. /* Reverse the bytes in a 32-bit value */
  82395. #define REVERSE(q) \
  82396. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  82397. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  82398. /*
  82399. inflate() uses a state machine to process as much input data and generate as
  82400. much output data as possible before returning. The state machine is
  82401. structured roughly as follows:
  82402. for (;;) switch (state) {
  82403. ...
  82404. case STATEn:
  82405. if (not enough input data or output space to make progress)
  82406. return;
  82407. ... make progress ...
  82408. state = STATEm;
  82409. break;
  82410. ...
  82411. }
  82412. so when inflate() is called again, the same case is attempted again, and
  82413. if the appropriate resources are provided, the machine proceeds to the
  82414. next state. The NEEDBITS() macro is usually the way the state evaluates
  82415. whether it can proceed or should return. NEEDBITS() does the return if
  82416. the requested bits are not available. The typical use of the BITS macros
  82417. is:
  82418. NEEDBITS(n);
  82419. ... do something with BITS(n) ...
  82420. DROPBITS(n);
  82421. where NEEDBITS(n) either returns from inflate() if there isn't enough
  82422. input left to load n bits into the accumulator, or it continues. BITS(n)
  82423. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  82424. the low n bits off the accumulator. INITBITS() clears the accumulator
  82425. and sets the number of available bits to zero. BYTEBITS() discards just
  82426. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  82427. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  82428. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  82429. if there is no input available. The decoding of variable length codes uses
  82430. PULLBYTE() directly in order to pull just enough bytes to decode the next
  82431. code, and no more.
  82432. Some states loop until they get enough input, making sure that enough
  82433. state information is maintained to continue the loop where it left off
  82434. if NEEDBITS() returns in the loop. For example, want, need, and keep
  82435. would all have to actually be part of the saved state in case NEEDBITS()
  82436. returns:
  82437. case STATEw:
  82438. while (want < need) {
  82439. NEEDBITS(n);
  82440. keep[want++] = BITS(n);
  82441. DROPBITS(n);
  82442. }
  82443. state = STATEx;
  82444. case STATEx:
  82445. As shown above, if the next state is also the next case, then the break
  82446. is omitted.
  82447. A state may also return if there is not enough output space available to
  82448. complete that state. Those states are copying stored data, writing a
  82449. literal byte, and copying a matching string.
  82450. When returning, a "goto inf_leave" is used to update the total counters,
  82451. update the check value, and determine whether any progress has been made
  82452. during that inflate() call in order to return the proper return code.
  82453. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  82454. When there is a window, goto inf_leave will update the window with the last
  82455. output written. If a goto inf_leave occurs in the middle of decompression
  82456. and there is no window currently, goto inf_leave will create one and copy
  82457. output to the window for the next call of inflate().
  82458. In this implementation, the flush parameter of inflate() only affects the
  82459. return code (per zlib.h). inflate() always writes as much as possible to
  82460. strm->next_out, given the space available and the provided input--the effect
  82461. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  82462. the allocation of and copying into a sliding window until necessary, which
  82463. provides the effect documented in zlib.h for Z_FINISH when the entire input
  82464. stream available. So the only thing the flush parameter actually does is:
  82465. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  82466. will return Z_BUF_ERROR if it has not reached the end of the stream.
  82467. */
  82468. int ZEXPORT inflate (z_streamp strm, int flush)
  82469. {
  82470. struct inflate_state FAR *state;
  82471. unsigned char FAR *next; /* next input */
  82472. unsigned char FAR *put; /* next output */
  82473. unsigned have, left; /* available input and output */
  82474. unsigned long hold; /* bit buffer */
  82475. unsigned bits; /* bits in bit buffer */
  82476. unsigned in, out; /* save starting available input and output */
  82477. unsigned copy; /* number of stored or match bytes to copy */
  82478. unsigned char FAR *from; /* where to copy match bytes from */
  82479. code thisx; /* current decoding table entry */
  82480. code last; /* parent table entry */
  82481. unsigned len; /* length to copy for repeats, bits to drop */
  82482. int ret; /* return code */
  82483. #ifdef GUNZIP
  82484. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  82485. #endif
  82486. static const unsigned short order[19] = /* permutation of code lengths */
  82487. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  82488. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  82489. (strm->next_in == Z_NULL && strm->avail_in != 0))
  82490. return Z_STREAM_ERROR;
  82491. state = (struct inflate_state FAR *)strm->state;
  82492. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  82493. LOAD();
  82494. in = have;
  82495. out = left;
  82496. ret = Z_OK;
  82497. for (;;)
  82498. switch (state->mode) {
  82499. case HEAD:
  82500. if (state->wrap == 0) {
  82501. state->mode = TYPEDO;
  82502. break;
  82503. }
  82504. NEEDBITS(16);
  82505. #ifdef GUNZIP
  82506. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  82507. state->check = crc32(0L, Z_NULL, 0);
  82508. CRC2(state->check, hold);
  82509. INITBITS();
  82510. state->mode = FLAGS;
  82511. break;
  82512. }
  82513. state->flags = 0; /* expect zlib header */
  82514. if (state->head != Z_NULL)
  82515. state->head->done = -1;
  82516. if (!(state->wrap & 1) || /* check if zlib header allowed */
  82517. #else
  82518. if (
  82519. #endif
  82520. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  82521. strm->msg = (char *)"incorrect header check";
  82522. state->mode = BAD;
  82523. break;
  82524. }
  82525. if (BITS(4) != Z_DEFLATED) {
  82526. strm->msg = (char *)"unknown compression method";
  82527. state->mode = BAD;
  82528. break;
  82529. }
  82530. DROPBITS(4);
  82531. len = BITS(4) + 8;
  82532. if (len > state->wbits) {
  82533. strm->msg = (char *)"invalid window size";
  82534. state->mode = BAD;
  82535. break;
  82536. }
  82537. state->dmax = 1U << len;
  82538. Tracev((stderr, "inflate: zlib header ok\n"));
  82539. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  82540. state->mode = hold & 0x200 ? DICTID : TYPE;
  82541. INITBITS();
  82542. break;
  82543. #ifdef GUNZIP
  82544. case FLAGS:
  82545. NEEDBITS(16);
  82546. state->flags = (int)(hold);
  82547. if ((state->flags & 0xff) != Z_DEFLATED) {
  82548. strm->msg = (char *)"unknown compression method";
  82549. state->mode = BAD;
  82550. break;
  82551. }
  82552. if (state->flags & 0xe000) {
  82553. strm->msg = (char *)"unknown header flags set";
  82554. state->mode = BAD;
  82555. break;
  82556. }
  82557. if (state->head != Z_NULL)
  82558. state->head->text = (int)((hold >> 8) & 1);
  82559. if (state->flags & 0x0200) CRC2(state->check, hold);
  82560. INITBITS();
  82561. state->mode = TIME;
  82562. case TIME:
  82563. NEEDBITS(32);
  82564. if (state->head != Z_NULL)
  82565. state->head->time = hold;
  82566. if (state->flags & 0x0200) CRC4(state->check, hold);
  82567. INITBITS();
  82568. state->mode = OS;
  82569. case OS:
  82570. NEEDBITS(16);
  82571. if (state->head != Z_NULL) {
  82572. state->head->xflags = (int)(hold & 0xff);
  82573. state->head->os = (int)(hold >> 8);
  82574. }
  82575. if (state->flags & 0x0200) CRC2(state->check, hold);
  82576. INITBITS();
  82577. state->mode = EXLEN;
  82578. case EXLEN:
  82579. if (state->flags & 0x0400) {
  82580. NEEDBITS(16);
  82581. state->length = (unsigned)(hold);
  82582. if (state->head != Z_NULL)
  82583. state->head->extra_len = (unsigned)hold;
  82584. if (state->flags & 0x0200) CRC2(state->check, hold);
  82585. INITBITS();
  82586. }
  82587. else if (state->head != Z_NULL)
  82588. state->head->extra = Z_NULL;
  82589. state->mode = EXTRA;
  82590. case EXTRA:
  82591. if (state->flags & 0x0400) {
  82592. copy = state->length;
  82593. if (copy > have) copy = have;
  82594. if (copy) {
  82595. if (state->head != Z_NULL &&
  82596. state->head->extra != Z_NULL) {
  82597. len = state->head->extra_len - state->length;
  82598. zmemcpy(state->head->extra + len, next,
  82599. len + copy > state->head->extra_max ?
  82600. state->head->extra_max - len : copy);
  82601. }
  82602. if (state->flags & 0x0200)
  82603. state->check = crc32(state->check, next, copy);
  82604. have -= copy;
  82605. next += copy;
  82606. state->length -= copy;
  82607. }
  82608. if (state->length) goto inf_leave;
  82609. }
  82610. state->length = 0;
  82611. state->mode = NAME;
  82612. case NAME:
  82613. if (state->flags & 0x0800) {
  82614. if (have == 0) goto inf_leave;
  82615. copy = 0;
  82616. do {
  82617. len = (unsigned)(next[copy++]);
  82618. if (state->head != Z_NULL &&
  82619. state->head->name != Z_NULL &&
  82620. state->length < state->head->name_max)
  82621. state->head->name[state->length++] = len;
  82622. } while (len && copy < have);
  82623. if (state->flags & 0x0200)
  82624. state->check = crc32(state->check, next, copy);
  82625. have -= copy;
  82626. next += copy;
  82627. if (len) goto inf_leave;
  82628. }
  82629. else if (state->head != Z_NULL)
  82630. state->head->name = Z_NULL;
  82631. state->length = 0;
  82632. state->mode = COMMENT;
  82633. case COMMENT:
  82634. if (state->flags & 0x1000) {
  82635. if (have == 0) goto inf_leave;
  82636. copy = 0;
  82637. do {
  82638. len = (unsigned)(next[copy++]);
  82639. if (state->head != Z_NULL &&
  82640. state->head->comment != Z_NULL &&
  82641. state->length < state->head->comm_max)
  82642. state->head->comment[state->length++] = len;
  82643. } while (len && copy < have);
  82644. if (state->flags & 0x0200)
  82645. state->check = crc32(state->check, next, copy);
  82646. have -= copy;
  82647. next += copy;
  82648. if (len) goto inf_leave;
  82649. }
  82650. else if (state->head != Z_NULL)
  82651. state->head->comment = Z_NULL;
  82652. state->mode = HCRC;
  82653. case HCRC:
  82654. if (state->flags & 0x0200) {
  82655. NEEDBITS(16);
  82656. if (hold != (state->check & 0xffff)) {
  82657. strm->msg = (char *)"header crc mismatch";
  82658. state->mode = BAD;
  82659. break;
  82660. }
  82661. INITBITS();
  82662. }
  82663. if (state->head != Z_NULL) {
  82664. state->head->hcrc = (int)((state->flags >> 9) & 1);
  82665. state->head->done = 1;
  82666. }
  82667. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  82668. state->mode = TYPE;
  82669. break;
  82670. #endif
  82671. case DICTID:
  82672. NEEDBITS(32);
  82673. strm->adler = state->check = REVERSE(hold);
  82674. INITBITS();
  82675. state->mode = DICT;
  82676. case DICT:
  82677. if (state->havedict == 0) {
  82678. RESTORE();
  82679. return Z_NEED_DICT;
  82680. }
  82681. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  82682. state->mode = TYPE;
  82683. case TYPE:
  82684. if (flush == Z_BLOCK) goto inf_leave;
  82685. case TYPEDO:
  82686. if (state->last) {
  82687. BYTEBITS();
  82688. state->mode = CHECK;
  82689. break;
  82690. }
  82691. NEEDBITS(3);
  82692. state->last = BITS(1);
  82693. DROPBITS(1);
  82694. switch (BITS(2)) {
  82695. case 0: /* stored block */
  82696. Tracev((stderr, "inflate: stored block%s\n",
  82697. state->last ? " (last)" : ""));
  82698. state->mode = STORED;
  82699. break;
  82700. case 1: /* fixed block */
  82701. fixedtables(state);
  82702. Tracev((stderr, "inflate: fixed codes block%s\n",
  82703. state->last ? " (last)" : ""));
  82704. state->mode = LEN; /* decode codes */
  82705. break;
  82706. case 2: /* dynamic block */
  82707. Tracev((stderr, "inflate: dynamic codes block%s\n",
  82708. state->last ? " (last)" : ""));
  82709. state->mode = TABLE;
  82710. break;
  82711. case 3:
  82712. strm->msg = (char *)"invalid block type";
  82713. state->mode = BAD;
  82714. }
  82715. DROPBITS(2);
  82716. break;
  82717. case STORED:
  82718. BYTEBITS(); /* go to byte boundary */
  82719. NEEDBITS(32);
  82720. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  82721. strm->msg = (char *)"invalid stored block lengths";
  82722. state->mode = BAD;
  82723. break;
  82724. }
  82725. state->length = (unsigned)hold & 0xffff;
  82726. Tracev((stderr, "inflate: stored length %u\n",
  82727. state->length));
  82728. INITBITS();
  82729. state->mode = COPY;
  82730. case COPY:
  82731. copy = state->length;
  82732. if (copy) {
  82733. if (copy > have) copy = have;
  82734. if (copy > left) copy = left;
  82735. if (copy == 0) goto inf_leave;
  82736. zmemcpy(put, next, copy);
  82737. have -= copy;
  82738. next += copy;
  82739. left -= copy;
  82740. put += copy;
  82741. state->length -= copy;
  82742. break;
  82743. }
  82744. Tracev((stderr, "inflate: stored end\n"));
  82745. state->mode = TYPE;
  82746. break;
  82747. case TABLE:
  82748. NEEDBITS(14);
  82749. state->nlen = BITS(5) + 257;
  82750. DROPBITS(5);
  82751. state->ndist = BITS(5) + 1;
  82752. DROPBITS(5);
  82753. state->ncode = BITS(4) + 4;
  82754. DROPBITS(4);
  82755. #ifndef PKZIP_BUG_WORKAROUND
  82756. if (state->nlen > 286 || state->ndist > 30) {
  82757. strm->msg = (char *)"too many length or distance symbols";
  82758. state->mode = BAD;
  82759. break;
  82760. }
  82761. #endif
  82762. Tracev((stderr, "inflate: table sizes ok\n"));
  82763. state->have = 0;
  82764. state->mode = LENLENS;
  82765. case LENLENS:
  82766. while (state->have < state->ncode) {
  82767. NEEDBITS(3);
  82768. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  82769. DROPBITS(3);
  82770. }
  82771. while (state->have < 19)
  82772. state->lens[order[state->have++]] = 0;
  82773. state->next = state->codes;
  82774. state->lencode = (code const FAR *)(state->next);
  82775. state->lenbits = 7;
  82776. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  82777. &(state->lenbits), state->work);
  82778. if (ret) {
  82779. strm->msg = (char *)"invalid code lengths set";
  82780. state->mode = BAD;
  82781. break;
  82782. }
  82783. Tracev((stderr, "inflate: code lengths ok\n"));
  82784. state->have = 0;
  82785. state->mode = CODELENS;
  82786. case CODELENS:
  82787. while (state->have < state->nlen + state->ndist) {
  82788. for (;;) {
  82789. thisx = state->lencode[BITS(state->lenbits)];
  82790. if ((unsigned)(thisx.bits) <= bits) break;
  82791. PULLBYTE();
  82792. }
  82793. if (thisx.val < 16) {
  82794. NEEDBITS(thisx.bits);
  82795. DROPBITS(thisx.bits);
  82796. state->lens[state->have++] = thisx.val;
  82797. }
  82798. else {
  82799. if (thisx.val == 16) {
  82800. NEEDBITS(thisx.bits + 2);
  82801. DROPBITS(thisx.bits);
  82802. if (state->have == 0) {
  82803. strm->msg = (char *)"invalid bit length repeat";
  82804. state->mode = BAD;
  82805. break;
  82806. }
  82807. len = state->lens[state->have - 1];
  82808. copy = 3 + BITS(2);
  82809. DROPBITS(2);
  82810. }
  82811. else if (thisx.val == 17) {
  82812. NEEDBITS(thisx.bits + 3);
  82813. DROPBITS(thisx.bits);
  82814. len = 0;
  82815. copy = 3 + BITS(3);
  82816. DROPBITS(3);
  82817. }
  82818. else {
  82819. NEEDBITS(thisx.bits + 7);
  82820. DROPBITS(thisx.bits);
  82821. len = 0;
  82822. copy = 11 + BITS(7);
  82823. DROPBITS(7);
  82824. }
  82825. if (state->have + copy > state->nlen + state->ndist) {
  82826. strm->msg = (char *)"invalid bit length repeat";
  82827. state->mode = BAD;
  82828. break;
  82829. }
  82830. while (copy--)
  82831. state->lens[state->have++] = (unsigned short)len;
  82832. }
  82833. }
  82834. /* handle error breaks in while */
  82835. if (state->mode == BAD) break;
  82836. /* build code tables */
  82837. state->next = state->codes;
  82838. state->lencode = (code const FAR *)(state->next);
  82839. state->lenbits = 9;
  82840. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  82841. &(state->lenbits), state->work);
  82842. if (ret) {
  82843. strm->msg = (char *)"invalid literal/lengths set";
  82844. state->mode = BAD;
  82845. break;
  82846. }
  82847. state->distcode = (code const FAR *)(state->next);
  82848. state->distbits = 6;
  82849. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  82850. &(state->next), &(state->distbits), state->work);
  82851. if (ret) {
  82852. strm->msg = (char *)"invalid distances set";
  82853. state->mode = BAD;
  82854. break;
  82855. }
  82856. Tracev((stderr, "inflate: codes ok\n"));
  82857. state->mode = LEN;
  82858. case LEN:
  82859. if (have >= 6 && left >= 258) {
  82860. RESTORE();
  82861. inflate_fast(strm, out);
  82862. LOAD();
  82863. break;
  82864. }
  82865. for (;;) {
  82866. thisx = state->lencode[BITS(state->lenbits)];
  82867. if ((unsigned)(thisx.bits) <= bits) break;
  82868. PULLBYTE();
  82869. }
  82870. if (thisx.op && (thisx.op & 0xf0) == 0) {
  82871. last = thisx;
  82872. for (;;) {
  82873. thisx = state->lencode[last.val +
  82874. (BITS(last.bits + last.op) >> last.bits)];
  82875. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  82876. PULLBYTE();
  82877. }
  82878. DROPBITS(last.bits);
  82879. }
  82880. DROPBITS(thisx.bits);
  82881. state->length = (unsigned)thisx.val;
  82882. if ((int)(thisx.op) == 0) {
  82883. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82884. "inflate: literal '%c'\n" :
  82885. "inflate: literal 0x%02x\n", thisx.val));
  82886. state->mode = LIT;
  82887. break;
  82888. }
  82889. if (thisx.op & 32) {
  82890. Tracevv((stderr, "inflate: end of block\n"));
  82891. state->mode = TYPE;
  82892. break;
  82893. }
  82894. if (thisx.op & 64) {
  82895. strm->msg = (char *)"invalid literal/length code";
  82896. state->mode = BAD;
  82897. break;
  82898. }
  82899. state->extra = (unsigned)(thisx.op) & 15;
  82900. state->mode = LENEXT;
  82901. case LENEXT:
  82902. if (state->extra) {
  82903. NEEDBITS(state->extra);
  82904. state->length += BITS(state->extra);
  82905. DROPBITS(state->extra);
  82906. }
  82907. Tracevv((stderr, "inflate: length %u\n", state->length));
  82908. state->mode = DIST;
  82909. case DIST:
  82910. for (;;) {
  82911. thisx = state->distcode[BITS(state->distbits)];
  82912. if ((unsigned)(thisx.bits) <= bits) break;
  82913. PULLBYTE();
  82914. }
  82915. if ((thisx.op & 0xf0) == 0) {
  82916. last = thisx;
  82917. for (;;) {
  82918. thisx = state->distcode[last.val +
  82919. (BITS(last.bits + last.op) >> last.bits)];
  82920. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  82921. PULLBYTE();
  82922. }
  82923. DROPBITS(last.bits);
  82924. }
  82925. DROPBITS(thisx.bits);
  82926. if (thisx.op & 64) {
  82927. strm->msg = (char *)"invalid distance code";
  82928. state->mode = BAD;
  82929. break;
  82930. }
  82931. state->offset = (unsigned)thisx.val;
  82932. state->extra = (unsigned)(thisx.op) & 15;
  82933. state->mode = DISTEXT;
  82934. case DISTEXT:
  82935. if (state->extra) {
  82936. NEEDBITS(state->extra);
  82937. state->offset += BITS(state->extra);
  82938. DROPBITS(state->extra);
  82939. }
  82940. #ifdef INFLATE_STRICT
  82941. if (state->offset > state->dmax) {
  82942. strm->msg = (char *)"invalid distance too far back";
  82943. state->mode = BAD;
  82944. break;
  82945. }
  82946. #endif
  82947. if (state->offset > state->whave + out - left) {
  82948. strm->msg = (char *)"invalid distance too far back";
  82949. state->mode = BAD;
  82950. break;
  82951. }
  82952. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  82953. state->mode = MATCH;
  82954. case MATCH:
  82955. if (left == 0) goto inf_leave;
  82956. copy = out - left;
  82957. if (state->offset > copy) { /* copy from window */
  82958. copy = state->offset - copy;
  82959. if (copy > state->write) {
  82960. copy -= state->write;
  82961. from = state->window + (state->wsize - copy);
  82962. }
  82963. else
  82964. from = state->window + (state->write - copy);
  82965. if (copy > state->length) copy = state->length;
  82966. }
  82967. else { /* copy from output */
  82968. from = put - state->offset;
  82969. copy = state->length;
  82970. }
  82971. if (copy > left) copy = left;
  82972. left -= copy;
  82973. state->length -= copy;
  82974. do {
  82975. *put++ = *from++;
  82976. } while (--copy);
  82977. if (state->length == 0) state->mode = LEN;
  82978. break;
  82979. case LIT:
  82980. if (left == 0) goto inf_leave;
  82981. *put++ = (unsigned char)(state->length);
  82982. left--;
  82983. state->mode = LEN;
  82984. break;
  82985. case CHECK:
  82986. if (state->wrap) {
  82987. NEEDBITS(32);
  82988. out -= left;
  82989. strm->total_out += out;
  82990. state->total += out;
  82991. if (out)
  82992. strm->adler = state->check =
  82993. UPDATE(state->check, put - out, out);
  82994. out = left;
  82995. if ((
  82996. #ifdef GUNZIP
  82997. state->flags ? hold :
  82998. #endif
  82999. REVERSE(hold)) != state->check) {
  83000. strm->msg = (char *)"incorrect data check";
  83001. state->mode = BAD;
  83002. break;
  83003. }
  83004. INITBITS();
  83005. Tracev((stderr, "inflate: check matches trailer\n"));
  83006. }
  83007. #ifdef GUNZIP
  83008. state->mode = LENGTH;
  83009. case LENGTH:
  83010. if (state->wrap && state->flags) {
  83011. NEEDBITS(32);
  83012. if (hold != (state->total & 0xffffffffUL)) {
  83013. strm->msg = (char *)"incorrect length check";
  83014. state->mode = BAD;
  83015. break;
  83016. }
  83017. INITBITS();
  83018. Tracev((stderr, "inflate: length matches trailer\n"));
  83019. }
  83020. #endif
  83021. state->mode = DONE;
  83022. case DONE:
  83023. ret = Z_STREAM_END;
  83024. goto inf_leave;
  83025. case BAD:
  83026. ret = Z_DATA_ERROR;
  83027. goto inf_leave;
  83028. case MEM:
  83029. return Z_MEM_ERROR;
  83030. case SYNC:
  83031. default:
  83032. return Z_STREAM_ERROR;
  83033. }
  83034. /*
  83035. Return from inflate(), updating the total counts and the check value.
  83036. If there was no progress during the inflate() call, return a buffer
  83037. error. Call updatewindow() to create and/or update the window state.
  83038. Note: a memory error from inflate() is non-recoverable.
  83039. */
  83040. inf_leave:
  83041. RESTORE();
  83042. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83043. if (updatewindow(strm, out)) {
  83044. state->mode = MEM;
  83045. return Z_MEM_ERROR;
  83046. }
  83047. in -= strm->avail_in;
  83048. out -= strm->avail_out;
  83049. strm->total_in += in;
  83050. strm->total_out += out;
  83051. state->total += out;
  83052. if (state->wrap && out)
  83053. strm->adler = state->check =
  83054. UPDATE(state->check, strm->next_out - out, out);
  83055. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83056. (state->mode == TYPE ? 128 : 0);
  83057. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83058. ret = Z_BUF_ERROR;
  83059. return ret;
  83060. }
  83061. int ZEXPORT inflateEnd (z_streamp strm)
  83062. {
  83063. struct inflate_state FAR *state;
  83064. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83065. return Z_STREAM_ERROR;
  83066. state = (struct inflate_state FAR *)strm->state;
  83067. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83068. ZFREE(strm, strm->state);
  83069. strm->state = Z_NULL;
  83070. Tracev((stderr, "inflate: end\n"));
  83071. return Z_OK;
  83072. }
  83073. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83074. {
  83075. struct inflate_state FAR *state;
  83076. unsigned long id_;
  83077. /* check state */
  83078. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83079. state = (struct inflate_state FAR *)strm->state;
  83080. if (state->wrap != 0 && state->mode != DICT)
  83081. return Z_STREAM_ERROR;
  83082. /* check for correct dictionary id */
  83083. if (state->mode == DICT) {
  83084. id_ = adler32(0L, Z_NULL, 0);
  83085. id_ = adler32(id_, dictionary, dictLength);
  83086. if (id_ != state->check)
  83087. return Z_DATA_ERROR;
  83088. }
  83089. /* copy dictionary to window */
  83090. if (updatewindow(strm, strm->avail_out)) {
  83091. state->mode = MEM;
  83092. return Z_MEM_ERROR;
  83093. }
  83094. if (dictLength > state->wsize) {
  83095. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83096. state->wsize);
  83097. state->whave = state->wsize;
  83098. }
  83099. else {
  83100. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83101. dictLength);
  83102. state->whave = dictLength;
  83103. }
  83104. state->havedict = 1;
  83105. Tracev((stderr, "inflate: dictionary set\n"));
  83106. return Z_OK;
  83107. }
  83108. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83109. {
  83110. struct inflate_state FAR *state;
  83111. /* check state */
  83112. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83113. state = (struct inflate_state FAR *)strm->state;
  83114. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  83115. /* save header structure */
  83116. state->head = head;
  83117. head->done = 0;
  83118. return Z_OK;
  83119. }
  83120. /*
  83121. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  83122. or when out of input. When called, *have is the number of pattern bytes
  83123. found in order so far, in 0..3. On return *have is updated to the new
  83124. state. If on return *have equals four, then the pattern was found and the
  83125. return value is how many bytes were read including the last byte of the
  83126. pattern. If *have is less than four, then the pattern has not been found
  83127. yet and the return value is len. In the latter case, syncsearch() can be
  83128. called again with more data and the *have state. *have is initialized to
  83129. zero for the first call.
  83130. */
  83131. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  83132. {
  83133. unsigned got;
  83134. unsigned next;
  83135. got = *have;
  83136. next = 0;
  83137. while (next < len && got < 4) {
  83138. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  83139. got++;
  83140. else if (buf[next])
  83141. got = 0;
  83142. else
  83143. got = 4 - got;
  83144. next++;
  83145. }
  83146. *have = got;
  83147. return next;
  83148. }
  83149. int ZEXPORT inflateSync (z_streamp strm)
  83150. {
  83151. unsigned len; /* number of bytes to look at or looked at */
  83152. unsigned long in, out; /* temporary to save total_in and total_out */
  83153. unsigned char buf[4]; /* to restore bit buffer to byte string */
  83154. struct inflate_state FAR *state;
  83155. /* check parameters */
  83156. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83157. state = (struct inflate_state FAR *)strm->state;
  83158. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  83159. /* if first time, start search in bit buffer */
  83160. if (state->mode != SYNC) {
  83161. state->mode = SYNC;
  83162. state->hold <<= state->bits & 7;
  83163. state->bits -= state->bits & 7;
  83164. len = 0;
  83165. while (state->bits >= 8) {
  83166. buf[len++] = (unsigned char)(state->hold);
  83167. state->hold >>= 8;
  83168. state->bits -= 8;
  83169. }
  83170. state->have = 0;
  83171. syncsearch(&(state->have), buf, len);
  83172. }
  83173. /* search available input */
  83174. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  83175. strm->avail_in -= len;
  83176. strm->next_in += len;
  83177. strm->total_in += len;
  83178. /* return no joy or set up to restart inflate() on a new block */
  83179. if (state->have != 4) return Z_DATA_ERROR;
  83180. in = strm->total_in; out = strm->total_out;
  83181. inflateReset(strm);
  83182. strm->total_in = in; strm->total_out = out;
  83183. state->mode = TYPE;
  83184. return Z_OK;
  83185. }
  83186. /*
  83187. Returns true if inflate is currently at the end of a block generated by
  83188. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  83189. implementation to provide an additional safety check. PPP uses
  83190. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  83191. block. When decompressing, PPP checks that at the end of input packet,
  83192. inflate is waiting for these length bytes.
  83193. */
  83194. int ZEXPORT inflateSyncPoint (z_streamp strm)
  83195. {
  83196. struct inflate_state FAR *state;
  83197. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83198. state = (struct inflate_state FAR *)strm->state;
  83199. return state->mode == STORED && state->bits == 0;
  83200. }
  83201. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  83202. {
  83203. struct inflate_state FAR *state;
  83204. struct inflate_state FAR *copy;
  83205. unsigned char FAR *window;
  83206. unsigned wsize;
  83207. /* check input */
  83208. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  83209. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  83210. return Z_STREAM_ERROR;
  83211. state = (struct inflate_state FAR *)source->state;
  83212. /* allocate space */
  83213. copy = (struct inflate_state FAR *)
  83214. ZALLOC(source, 1, sizeof(struct inflate_state));
  83215. if (copy == Z_NULL) return Z_MEM_ERROR;
  83216. window = Z_NULL;
  83217. if (state->window != Z_NULL) {
  83218. window = (unsigned char FAR *)
  83219. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  83220. if (window == Z_NULL) {
  83221. ZFREE(source, copy);
  83222. return Z_MEM_ERROR;
  83223. }
  83224. }
  83225. /* copy state */
  83226. zmemcpy(dest, source, sizeof(z_stream));
  83227. zmemcpy(copy, state, sizeof(struct inflate_state));
  83228. if (state->lencode >= state->codes &&
  83229. state->lencode <= state->codes + ENOUGH - 1) {
  83230. copy->lencode = copy->codes + (state->lencode - state->codes);
  83231. copy->distcode = copy->codes + (state->distcode - state->codes);
  83232. }
  83233. copy->next = copy->codes + (state->next - state->codes);
  83234. if (window != Z_NULL) {
  83235. wsize = 1U << state->wbits;
  83236. zmemcpy(window, state->window, wsize);
  83237. }
  83238. copy->window = window;
  83239. dest->state = (struct internal_state FAR *)copy;
  83240. return Z_OK;
  83241. }
  83242. /*** End of inlined file: inflate.c ***/
  83243. /*** Start of inlined file: inftrees.c ***/
  83244. #define MAXBITS 15
  83245. const char inflate_copyright[] =
  83246. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  83247. /*
  83248. If you use the zlib library in a product, an acknowledgment is welcome
  83249. in the documentation of your product. If for some reason you cannot
  83250. include such an acknowledgment, I would appreciate that you keep this
  83251. copyright string in the executable of your product.
  83252. */
  83253. /*
  83254. Build a set of tables to decode the provided canonical Huffman code.
  83255. The code lengths are lens[0..codes-1]. The result starts at *table,
  83256. whose indices are 0..2^bits-1. work is a writable array of at least
  83257. lens shorts, which is used as a work area. type is the type of code
  83258. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  83259. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  83260. on return points to the next available entry's address. bits is the
  83261. requested root table index bits, and on return it is the actual root
  83262. table index bits. It will differ if the request is greater than the
  83263. longest code or if it is less than the shortest code.
  83264. */
  83265. int inflate_table (codetype type,
  83266. unsigned short FAR *lens,
  83267. unsigned codes,
  83268. code FAR * FAR *table,
  83269. unsigned FAR *bits,
  83270. unsigned short FAR *work)
  83271. {
  83272. unsigned len; /* a code's length in bits */
  83273. unsigned sym; /* index of code symbols */
  83274. unsigned min, max; /* minimum and maximum code lengths */
  83275. unsigned root; /* number of index bits for root table */
  83276. unsigned curr; /* number of index bits for current table */
  83277. unsigned drop; /* code bits to drop for sub-table */
  83278. int left; /* number of prefix codes available */
  83279. unsigned used; /* code entries in table used */
  83280. unsigned huff; /* Huffman code */
  83281. unsigned incr; /* for incrementing code, index */
  83282. unsigned fill; /* index for replicating entries */
  83283. unsigned low; /* low bits for current root entry */
  83284. unsigned mask; /* mask for low root bits */
  83285. code thisx; /* table entry for duplication */
  83286. code FAR *next; /* next available space in table */
  83287. const unsigned short FAR *base; /* base value table to use */
  83288. const unsigned short FAR *extra; /* extra bits table to use */
  83289. int end; /* use base and extra for symbol > end */
  83290. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  83291. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  83292. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  83293. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  83294. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  83295. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  83296. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  83297. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  83298. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  83299. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  83300. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  83301. 8193, 12289, 16385, 24577, 0, 0};
  83302. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  83303. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  83304. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  83305. 28, 28, 29, 29, 64, 64};
  83306. /*
  83307. Process a set of code lengths to create a canonical Huffman code. The
  83308. code lengths are lens[0..codes-1]. Each length corresponds to the
  83309. symbols 0..codes-1. The Huffman code is generated by first sorting the
  83310. symbols by length from short to long, and retaining the symbol order
  83311. for codes with equal lengths. Then the code starts with all zero bits
  83312. for the first code of the shortest length, and the codes are integer
  83313. increments for the same length, and zeros are appended as the length
  83314. increases. For the deflate format, these bits are stored backwards
  83315. from their more natural integer increment ordering, and so when the
  83316. decoding tables are built in the large loop below, the integer codes
  83317. are incremented backwards.
  83318. This routine assumes, but does not check, that all of the entries in
  83319. lens[] are in the range 0..MAXBITS. The caller must assure this.
  83320. 1..MAXBITS is interpreted as that code length. zero means that that
  83321. symbol does not occur in this code.
  83322. The codes are sorted by computing a count of codes for each length,
  83323. creating from that a table of starting indices for each length in the
  83324. sorted table, and then entering the symbols in order in the sorted
  83325. table. The sorted table is work[], with that space being provided by
  83326. the caller.
  83327. The length counts are used for other purposes as well, i.e. finding
  83328. the minimum and maximum length codes, determining if there are any
  83329. codes at all, checking for a valid set of lengths, and looking ahead
  83330. at length counts to determine sub-table sizes when building the
  83331. decoding tables.
  83332. */
  83333. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  83334. for (len = 0; len <= MAXBITS; len++)
  83335. count[len] = 0;
  83336. for (sym = 0; sym < codes; sym++)
  83337. count[lens[sym]]++;
  83338. /* bound code lengths, force root to be within code lengths */
  83339. root = *bits;
  83340. for (max = MAXBITS; max >= 1; max--)
  83341. if (count[max] != 0) break;
  83342. if (root > max) root = max;
  83343. if (max == 0) { /* no symbols to code at all */
  83344. thisx.op = (unsigned char)64; /* invalid code marker */
  83345. thisx.bits = (unsigned char)1;
  83346. thisx.val = (unsigned short)0;
  83347. *(*table)++ = thisx; /* make a table to force an error */
  83348. *(*table)++ = thisx;
  83349. *bits = 1;
  83350. return 0; /* no symbols, but wait for decoding to report error */
  83351. }
  83352. for (min = 1; min <= MAXBITS; min++)
  83353. if (count[min] != 0) break;
  83354. if (root < min) root = min;
  83355. /* check for an over-subscribed or incomplete set of lengths */
  83356. left = 1;
  83357. for (len = 1; len <= MAXBITS; len++) {
  83358. left <<= 1;
  83359. left -= count[len];
  83360. if (left < 0) return -1; /* over-subscribed */
  83361. }
  83362. if (left > 0 && (type == CODES || max != 1))
  83363. return -1; /* incomplete set */
  83364. /* generate offsets into symbol table for each length for sorting */
  83365. offs[1] = 0;
  83366. for (len = 1; len < MAXBITS; len++)
  83367. offs[len + 1] = offs[len] + count[len];
  83368. /* sort symbols by length, by symbol order within each length */
  83369. for (sym = 0; sym < codes; sym++)
  83370. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  83371. /*
  83372. Create and fill in decoding tables. In this loop, the table being
  83373. filled is at next and has curr index bits. The code being used is huff
  83374. with length len. That code is converted to an index by dropping drop
  83375. bits off of the bottom. For codes where len is less than drop + curr,
  83376. those top drop + curr - len bits are incremented through all values to
  83377. fill the table with replicated entries.
  83378. root is the number of index bits for the root table. When len exceeds
  83379. root, sub-tables are created pointed to by the root entry with an index
  83380. of the low root bits of huff. This is saved in low to check for when a
  83381. new sub-table should be started. drop is zero when the root table is
  83382. being filled, and drop is root when sub-tables are being filled.
  83383. When a new sub-table is needed, it is necessary to look ahead in the
  83384. code lengths to determine what size sub-table is needed. The length
  83385. counts are used for this, and so count[] is decremented as codes are
  83386. entered in the tables.
  83387. used keeps track of how many table entries have been allocated from the
  83388. provided *table space. It is checked when a LENS table is being made
  83389. against the space in *table, ENOUGH, minus the maximum space needed by
  83390. the worst case distance code, MAXD. This should never happen, but the
  83391. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  83392. This assumes that when type == LENS, bits == 9.
  83393. sym increments through all symbols, and the loop terminates when
  83394. all codes of length max, i.e. all codes, have been processed. This
  83395. routine permits incomplete codes, so another loop after this one fills
  83396. in the rest of the decoding tables with invalid code markers.
  83397. */
  83398. /* set up for code type */
  83399. switch (type) {
  83400. case CODES:
  83401. base = extra = work; /* dummy value--not used */
  83402. end = 19;
  83403. break;
  83404. case LENS:
  83405. base = lbase;
  83406. base -= 257;
  83407. extra = lext;
  83408. extra -= 257;
  83409. end = 256;
  83410. break;
  83411. default: /* DISTS */
  83412. base = dbase;
  83413. extra = dext;
  83414. end = -1;
  83415. }
  83416. /* initialize state for loop */
  83417. huff = 0; /* starting code */
  83418. sym = 0; /* starting code symbol */
  83419. len = min; /* starting code length */
  83420. next = *table; /* current table to fill in */
  83421. curr = root; /* current table index bits */
  83422. drop = 0; /* current bits to drop from code for index */
  83423. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  83424. used = 1U << root; /* use root table entries */
  83425. mask = used - 1; /* mask for comparing low */
  83426. /* check available table space */
  83427. if (type == LENS && used >= ENOUGH - MAXD)
  83428. return 1;
  83429. /* process all codes and make table entries */
  83430. for (;;) {
  83431. /* create table entry */
  83432. thisx.bits = (unsigned char)(len - drop);
  83433. if ((int)(work[sym]) < end) {
  83434. thisx.op = (unsigned char)0;
  83435. thisx.val = work[sym];
  83436. }
  83437. else if ((int)(work[sym]) > end) {
  83438. thisx.op = (unsigned char)(extra[work[sym]]);
  83439. thisx.val = base[work[sym]];
  83440. }
  83441. else {
  83442. thisx.op = (unsigned char)(32 + 64); /* end of block */
  83443. thisx.val = 0;
  83444. }
  83445. /* replicate for those indices with low len bits equal to huff */
  83446. incr = 1U << (len - drop);
  83447. fill = 1U << curr;
  83448. min = fill; /* save offset to next table */
  83449. do {
  83450. fill -= incr;
  83451. next[(huff >> drop) + fill] = thisx;
  83452. } while (fill != 0);
  83453. /* backwards increment the len-bit code huff */
  83454. incr = 1U << (len - 1);
  83455. while (huff & incr)
  83456. incr >>= 1;
  83457. if (incr != 0) {
  83458. huff &= incr - 1;
  83459. huff += incr;
  83460. }
  83461. else
  83462. huff = 0;
  83463. /* go to next symbol, update count, len */
  83464. sym++;
  83465. if (--(count[len]) == 0) {
  83466. if (len == max) break;
  83467. len = lens[work[sym]];
  83468. }
  83469. /* create new sub-table if needed */
  83470. if (len > root && (huff & mask) != low) {
  83471. /* if first time, transition to sub-tables */
  83472. if (drop == 0)
  83473. drop = root;
  83474. /* increment past last table */
  83475. next += min; /* here min is 1 << curr */
  83476. /* determine length of next table */
  83477. curr = len - drop;
  83478. left = (int)(1 << curr);
  83479. while (curr + drop < max) {
  83480. left -= count[curr + drop];
  83481. if (left <= 0) break;
  83482. curr++;
  83483. left <<= 1;
  83484. }
  83485. /* check for enough space */
  83486. used += 1U << curr;
  83487. if (type == LENS && used >= ENOUGH - MAXD)
  83488. return 1;
  83489. /* point entry in root table to sub-table */
  83490. low = huff & mask;
  83491. (*table)[low].op = (unsigned char)curr;
  83492. (*table)[low].bits = (unsigned char)root;
  83493. (*table)[low].val = (unsigned short)(next - *table);
  83494. }
  83495. }
  83496. /*
  83497. Fill in rest of table for incomplete codes. This loop is similar to the
  83498. loop above in incrementing huff for table indices. It is assumed that
  83499. len is equal to curr + drop, so there is no loop needed to increment
  83500. through high index bits. When the current sub-table is filled, the loop
  83501. drops back to the root table to fill in any remaining entries there.
  83502. */
  83503. thisx.op = (unsigned char)64; /* invalid code marker */
  83504. thisx.bits = (unsigned char)(len - drop);
  83505. thisx.val = (unsigned short)0;
  83506. while (huff != 0) {
  83507. /* when done with sub-table, drop back to root table */
  83508. if (drop != 0 && (huff & mask) != low) {
  83509. drop = 0;
  83510. len = root;
  83511. next = *table;
  83512. thisx.bits = (unsigned char)len;
  83513. }
  83514. /* put invalid code marker in table */
  83515. next[huff >> drop] = thisx;
  83516. /* backwards increment the len-bit code huff */
  83517. incr = 1U << (len - 1);
  83518. while (huff & incr)
  83519. incr >>= 1;
  83520. if (incr != 0) {
  83521. huff &= incr - 1;
  83522. huff += incr;
  83523. }
  83524. else
  83525. huff = 0;
  83526. }
  83527. /* set return parameters */
  83528. *table += used;
  83529. *bits = root;
  83530. return 0;
  83531. }
  83532. /*** End of inlined file: inftrees.c ***/
  83533. /*** Start of inlined file: trees.c ***/
  83534. /*
  83535. * ALGORITHM
  83536. *
  83537. * The "deflation" process uses several Huffman trees. The more
  83538. * common source values are represented by shorter bit sequences.
  83539. *
  83540. * Each code tree is stored in a compressed form which is itself
  83541. * a Huffman encoding of the lengths of all the code strings (in
  83542. * ascending order by source values). The actual code strings are
  83543. * reconstructed from the lengths in the inflate process, as described
  83544. * in the deflate specification.
  83545. *
  83546. * REFERENCES
  83547. *
  83548. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  83549. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  83550. *
  83551. * Storer, James A.
  83552. * Data Compression: Methods and Theory, pp. 49-50.
  83553. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  83554. *
  83555. * Sedgewick, R.
  83556. * Algorithms, p290.
  83557. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  83558. */
  83559. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  83560. /* #define GEN_TREES_H */
  83561. #ifdef DEBUG
  83562. # include <ctype.h>
  83563. #endif
  83564. /* ===========================================================================
  83565. * Constants
  83566. */
  83567. #define MAX_BL_BITS 7
  83568. /* Bit length codes must not exceed MAX_BL_BITS bits */
  83569. #define END_BLOCK 256
  83570. /* end of block literal code */
  83571. #define REP_3_6 16
  83572. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  83573. #define REPZ_3_10 17
  83574. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  83575. #define REPZ_11_138 18
  83576. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  83577. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  83578. = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
  83579. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  83580. = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  83581. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  83582. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  83583. local const uch bl_order[BL_CODES]
  83584. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  83585. /* The lengths of the bit length codes are sent in order of decreasing
  83586. * probability, to avoid transmitting the lengths for unused bit length codes.
  83587. */
  83588. #define Buf_size (8 * 2*sizeof(char))
  83589. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  83590. * more than 16 bits on some systems.)
  83591. */
  83592. /* ===========================================================================
  83593. * Local data. These are initialized only once.
  83594. */
  83595. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  83596. #if defined(GEN_TREES_H) || !defined(STDC)
  83597. /* non ANSI compilers may not accept trees.h */
  83598. local ct_data static_ltree[L_CODES+2];
  83599. /* The static literal tree. Since the bit lengths are imposed, there is no
  83600. * need for the L_CODES extra codes used during heap construction. However
  83601. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  83602. * below).
  83603. */
  83604. local ct_data static_dtree[D_CODES];
  83605. /* The static distance tree. (Actually a trivial tree since all codes use
  83606. * 5 bits.)
  83607. */
  83608. uch _dist_code[DIST_CODE_LEN];
  83609. /* Distance codes. The first 256 values correspond to the distances
  83610. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  83611. * the 15 bit distances.
  83612. */
  83613. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  83614. /* length code for each normalized match length (0 == MIN_MATCH) */
  83615. local int base_length[LENGTH_CODES];
  83616. /* First normalized length for each code (0 = MIN_MATCH) */
  83617. local int base_dist[D_CODES];
  83618. /* First normalized distance for each code (0 = distance of 1) */
  83619. #else
  83620. /*** Start of inlined file: trees.h ***/
  83621. local const ct_data static_ltree[L_CODES+2] = {
  83622. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  83623. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  83624. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  83625. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  83626. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  83627. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  83628. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  83629. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  83630. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  83631. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  83632. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  83633. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  83634. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  83635. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  83636. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  83637. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  83638. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  83639. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  83640. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  83641. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  83642. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  83643. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  83644. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  83645. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  83646. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  83647. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  83648. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  83649. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  83650. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  83651. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  83652. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  83653. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  83654. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  83655. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  83656. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  83657. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  83658. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  83659. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  83660. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  83661. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  83662. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  83663. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  83664. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  83665. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  83666. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  83667. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  83668. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  83669. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  83670. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  83671. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  83672. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  83673. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  83674. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  83675. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  83676. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  83677. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  83678. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  83679. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  83680. };
  83681. local const ct_data static_dtree[D_CODES] = {
  83682. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  83683. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  83684. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  83685. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  83686. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  83687. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  83688. };
  83689. const uch _dist_code[DIST_CODE_LEN] = {
  83690. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  83691. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  83692. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  83693. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  83694. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  83695. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  83696. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  83697. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  83698. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  83699. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  83700. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  83701. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  83702. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  83703. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  83704. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  83705. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  83706. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  83707. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  83708. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  83709. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  83710. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  83711. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  83712. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  83713. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  83714. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  83715. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  83716. };
  83717. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  83718. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  83719. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  83720. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  83721. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  83722. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  83723. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  83724. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  83725. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  83726. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  83727. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  83728. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  83729. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  83730. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  83731. };
  83732. local const int base_length[LENGTH_CODES] = {
  83733. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  83734. 64, 80, 96, 112, 128, 160, 192, 224, 0
  83735. };
  83736. local const int base_dist[D_CODES] = {
  83737. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  83738. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  83739. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  83740. };
  83741. /*** End of inlined file: trees.h ***/
  83742. #endif /* GEN_TREES_H */
  83743. struct static_tree_desc_s {
  83744. const ct_data *static_tree; /* static tree or NULL */
  83745. const intf *extra_bits; /* extra bits for each code or NULL */
  83746. int extra_base; /* base index for extra_bits */
  83747. int elems; /* max number of elements in the tree */
  83748. int max_length; /* max bit length for the codes */
  83749. };
  83750. local static_tree_desc static_l_desc =
  83751. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  83752. local static_tree_desc static_d_desc =
  83753. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  83754. local static_tree_desc static_bl_desc =
  83755. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  83756. /* ===========================================================================
  83757. * Local (static) routines in this file.
  83758. */
  83759. local void tr_static_init OF((void));
  83760. local void init_block OF((deflate_state *s));
  83761. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  83762. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  83763. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  83764. local void build_tree OF((deflate_state *s, tree_desc *desc));
  83765. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  83766. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  83767. local int build_bl_tree OF((deflate_state *s));
  83768. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  83769. int blcodes));
  83770. local void compress_block OF((deflate_state *s, ct_data *ltree,
  83771. ct_data *dtree));
  83772. local void set_data_type OF((deflate_state *s));
  83773. local unsigned bi_reverse OF((unsigned value, int length));
  83774. local void bi_windup OF((deflate_state *s));
  83775. local void bi_flush OF((deflate_state *s));
  83776. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  83777. int header));
  83778. #ifdef GEN_TREES_H
  83779. local void gen_trees_header OF((void));
  83780. #endif
  83781. #ifndef DEBUG
  83782. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  83783. /* Send a code of the given tree. c and tree must not have side effects */
  83784. #else /* DEBUG */
  83785. # define send_code(s, c, tree) \
  83786. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  83787. send_bits(s, tree[c].Code, tree[c].Len); }
  83788. #endif
  83789. /* ===========================================================================
  83790. * Output a short LSB first on the stream.
  83791. * IN assertion: there is enough room in pendingBuf.
  83792. */
  83793. #define put_short(s, w) { \
  83794. put_byte(s, (uch)((w) & 0xff)); \
  83795. put_byte(s, (uch)((ush)(w) >> 8)); \
  83796. }
  83797. /* ===========================================================================
  83798. * Send a value on a given number of bits.
  83799. * IN assertion: length <= 16 and value fits in length bits.
  83800. */
  83801. #ifdef DEBUG
  83802. local void send_bits OF((deflate_state *s, int value, int length));
  83803. local void send_bits (deflate_state *s, int value, int length)
  83804. {
  83805. Tracevv((stderr," l %2d v %4x ", length, value));
  83806. Assert(length > 0 && length <= 15, "invalid length");
  83807. s->bits_sent += (ulg)length;
  83808. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  83809. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  83810. * unused bits in value.
  83811. */
  83812. if (s->bi_valid > (int)Buf_size - length) {
  83813. s->bi_buf |= (value << s->bi_valid);
  83814. put_short(s, s->bi_buf);
  83815. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  83816. s->bi_valid += length - Buf_size;
  83817. } else {
  83818. s->bi_buf |= value << s->bi_valid;
  83819. s->bi_valid += length;
  83820. }
  83821. }
  83822. #else /* !DEBUG */
  83823. #define send_bits(s, value, length) \
  83824. { int len = length;\
  83825. if (s->bi_valid > (int)Buf_size - len) {\
  83826. int val = value;\
  83827. s->bi_buf |= (val << s->bi_valid);\
  83828. put_short(s, s->bi_buf);\
  83829. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  83830. s->bi_valid += len - Buf_size;\
  83831. } else {\
  83832. s->bi_buf |= (value) << s->bi_valid;\
  83833. s->bi_valid += len;\
  83834. }\
  83835. }
  83836. #endif /* DEBUG */
  83837. /* the arguments must not have side effects */
  83838. /* ===========================================================================
  83839. * Initialize the various 'constant' tables.
  83840. */
  83841. local void tr_static_init()
  83842. {
  83843. #if defined(GEN_TREES_H) || !defined(STDC)
  83844. static int static_init_done = 0;
  83845. int n; /* iterates over tree elements */
  83846. int bits; /* bit counter */
  83847. int length; /* length value */
  83848. int code; /* code value */
  83849. int dist; /* distance index */
  83850. ush bl_count[MAX_BITS+1];
  83851. /* number of codes at each bit length for an optimal tree */
  83852. if (static_init_done) return;
  83853. /* For some embedded targets, global variables are not initialized: */
  83854. static_l_desc.static_tree = static_ltree;
  83855. static_l_desc.extra_bits = extra_lbits;
  83856. static_d_desc.static_tree = static_dtree;
  83857. static_d_desc.extra_bits = extra_dbits;
  83858. static_bl_desc.extra_bits = extra_blbits;
  83859. /* Initialize the mapping length (0..255) -> length code (0..28) */
  83860. length = 0;
  83861. for (code = 0; code < LENGTH_CODES-1; code++) {
  83862. base_length[code] = length;
  83863. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  83864. _length_code[length++] = (uch)code;
  83865. }
  83866. }
  83867. Assert (length == 256, "tr_static_init: length != 256");
  83868. /* Note that the length 255 (match length 258) can be represented
  83869. * in two different ways: code 284 + 5 bits or code 285, so we
  83870. * overwrite length_code[255] to use the best encoding:
  83871. */
  83872. _length_code[length-1] = (uch)code;
  83873. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  83874. dist = 0;
  83875. for (code = 0 ; code < 16; code++) {
  83876. base_dist[code] = dist;
  83877. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  83878. _dist_code[dist++] = (uch)code;
  83879. }
  83880. }
  83881. Assert (dist == 256, "tr_static_init: dist != 256");
  83882. dist >>= 7; /* from now on, all distances are divided by 128 */
  83883. for ( ; code < D_CODES; code++) {
  83884. base_dist[code] = dist << 7;
  83885. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  83886. _dist_code[256 + dist++] = (uch)code;
  83887. }
  83888. }
  83889. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  83890. /* Construct the codes of the static literal tree */
  83891. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  83892. n = 0;
  83893. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  83894. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  83895. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  83896. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  83897. /* Codes 286 and 287 do not exist, but we must include them in the
  83898. * tree construction to get a canonical Huffman tree (longest code
  83899. * all ones)
  83900. */
  83901. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  83902. /* The static distance tree is trivial: */
  83903. for (n = 0; n < D_CODES; n++) {
  83904. static_dtree[n].Len = 5;
  83905. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  83906. }
  83907. static_init_done = 1;
  83908. # ifdef GEN_TREES_H
  83909. gen_trees_header();
  83910. # endif
  83911. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  83912. }
  83913. /* ===========================================================================
  83914. * Genererate the file trees.h describing the static trees.
  83915. */
  83916. #ifdef GEN_TREES_H
  83917. # ifndef DEBUG
  83918. # include <stdio.h>
  83919. # endif
  83920. # define SEPARATOR(i, last, width) \
  83921. ((i) == (last)? "\n};\n\n" : \
  83922. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  83923. void gen_trees_header()
  83924. {
  83925. FILE *header = fopen("trees.h", "w");
  83926. int i;
  83927. Assert (header != NULL, "Can't open trees.h");
  83928. fprintf(header,
  83929. "/* header created automatically with -DGEN_TREES_H */\n\n");
  83930. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  83931. for (i = 0; i < L_CODES+2; i++) {
  83932. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  83933. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  83934. }
  83935. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  83936. for (i = 0; i < D_CODES; i++) {
  83937. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  83938. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  83939. }
  83940. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  83941. for (i = 0; i < DIST_CODE_LEN; i++) {
  83942. fprintf(header, "%2u%s", _dist_code[i],
  83943. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  83944. }
  83945. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  83946. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  83947. fprintf(header, "%2u%s", _length_code[i],
  83948. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  83949. }
  83950. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  83951. for (i = 0; i < LENGTH_CODES; i++) {
  83952. fprintf(header, "%1u%s", base_length[i],
  83953. SEPARATOR(i, LENGTH_CODES-1, 20));
  83954. }
  83955. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  83956. for (i = 0; i < D_CODES; i++) {
  83957. fprintf(header, "%5u%s", base_dist[i],
  83958. SEPARATOR(i, D_CODES-1, 10));
  83959. }
  83960. fclose(header);
  83961. }
  83962. #endif /* GEN_TREES_H */
  83963. /* ===========================================================================
  83964. * Initialize the tree data structures for a new zlib stream.
  83965. */
  83966. void _tr_init(deflate_state *s)
  83967. {
  83968. tr_static_init();
  83969. s->l_desc.dyn_tree = s->dyn_ltree;
  83970. s->l_desc.stat_desc = &static_l_desc;
  83971. s->d_desc.dyn_tree = s->dyn_dtree;
  83972. s->d_desc.stat_desc = &static_d_desc;
  83973. s->bl_desc.dyn_tree = s->bl_tree;
  83974. s->bl_desc.stat_desc = &static_bl_desc;
  83975. s->bi_buf = 0;
  83976. s->bi_valid = 0;
  83977. s->last_eob_len = 8; /* enough lookahead for inflate */
  83978. #ifdef DEBUG
  83979. s->compressed_len = 0L;
  83980. s->bits_sent = 0L;
  83981. #endif
  83982. /* Initialize the first block of the first file: */
  83983. init_block(s);
  83984. }
  83985. /* ===========================================================================
  83986. * Initialize a new block.
  83987. */
  83988. local void init_block (deflate_state *s)
  83989. {
  83990. int n; /* iterates over tree elements */
  83991. /* Initialize the trees. */
  83992. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  83993. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  83994. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  83995. s->dyn_ltree[END_BLOCK].Freq = 1;
  83996. s->opt_len = s->static_len = 0L;
  83997. s->last_lit = s->matches = 0;
  83998. }
  83999. #define SMALLEST 1
  84000. /* Index within the heap array of least frequent node in the Huffman tree */
  84001. /* ===========================================================================
  84002. * Remove the smallest element from the heap and recreate the heap with
  84003. * one less element. Updates heap and heap_len.
  84004. */
  84005. #define pqremove(s, tree, top) \
  84006. {\
  84007. top = s->heap[SMALLEST]; \
  84008. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84009. pqdownheap(s, tree, SMALLEST); \
  84010. }
  84011. /* ===========================================================================
  84012. * Compares to subtrees, using the tree depth as tie breaker when
  84013. * the subtrees have equal frequency. This minimizes the worst case length.
  84014. */
  84015. #define smaller(tree, n, m, depth) \
  84016. (tree[n].Freq < tree[m].Freq || \
  84017. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84018. /* ===========================================================================
  84019. * Restore the heap property by moving down the tree starting at node k,
  84020. * exchanging a node with the smallest of its two sons if necessary, stopping
  84021. * when the heap property is re-established (each father smaller than its
  84022. * two sons).
  84023. */
  84024. local void pqdownheap (deflate_state *s,
  84025. ct_data *tree, /* the tree to restore */
  84026. int k) /* node to move down */
  84027. {
  84028. int v = s->heap[k];
  84029. int j = k << 1; /* left son of k */
  84030. while (j <= s->heap_len) {
  84031. /* Set j to the smallest of the two sons: */
  84032. if (j < s->heap_len &&
  84033. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84034. j++;
  84035. }
  84036. /* Exit if v is smaller than both sons */
  84037. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84038. /* Exchange v with the smallest son */
  84039. s->heap[k] = s->heap[j]; k = j;
  84040. /* And continue down the tree, setting j to the left son of k */
  84041. j <<= 1;
  84042. }
  84043. s->heap[k] = v;
  84044. }
  84045. /* ===========================================================================
  84046. * Compute the optimal bit lengths for a tree and update the total bit length
  84047. * for the current block.
  84048. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84049. * above are the tree nodes sorted by increasing frequency.
  84050. * OUT assertions: the field len is set to the optimal bit length, the
  84051. * array bl_count contains the frequencies for each bit length.
  84052. * The length opt_len is updated; static_len is also updated if stree is
  84053. * not null.
  84054. */
  84055. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84056. {
  84057. ct_data *tree = desc->dyn_tree;
  84058. int max_code = desc->max_code;
  84059. const ct_data *stree = desc->stat_desc->static_tree;
  84060. const intf *extra = desc->stat_desc->extra_bits;
  84061. int base = desc->stat_desc->extra_base;
  84062. int max_length = desc->stat_desc->max_length;
  84063. int h; /* heap index */
  84064. int n, m; /* iterate over the tree elements */
  84065. int bits; /* bit length */
  84066. int xbits; /* extra bits */
  84067. ush f; /* frequency */
  84068. int overflow = 0; /* number of elements with bit length too large */
  84069. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84070. /* In a first pass, compute the optimal bit lengths (which may
  84071. * overflow in the case of the bit length tree).
  84072. */
  84073. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84074. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84075. n = s->heap[h];
  84076. bits = tree[tree[n].Dad].Len + 1;
  84077. if (bits > max_length) bits = max_length, overflow++;
  84078. tree[n].Len = (ush)bits;
  84079. /* We overwrite tree[n].Dad which is no longer needed */
  84080. if (n > max_code) continue; /* not a leaf node */
  84081. s->bl_count[bits]++;
  84082. xbits = 0;
  84083. if (n >= base) xbits = extra[n-base];
  84084. f = tree[n].Freq;
  84085. s->opt_len += (ulg)f * (bits + xbits);
  84086. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84087. }
  84088. if (overflow == 0) return;
  84089. Trace((stderr,"\nbit length overflow\n"));
  84090. /* This happens for example on obj2 and pic of the Calgary corpus */
  84091. /* Find the first bit length which could increase: */
  84092. do {
  84093. bits = max_length-1;
  84094. while (s->bl_count[bits] == 0) bits--;
  84095. s->bl_count[bits]--; /* move one leaf down the tree */
  84096. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84097. s->bl_count[max_length]--;
  84098. /* The brother of the overflow item also moves one step up,
  84099. * but this does not affect bl_count[max_length]
  84100. */
  84101. overflow -= 2;
  84102. } while (overflow > 0);
  84103. /* Now recompute all bit lengths, scanning in increasing frequency.
  84104. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84105. * lengths instead of fixing only the wrong ones. This idea is taken
  84106. * from 'ar' written by Haruhiko Okumura.)
  84107. */
  84108. for (bits = max_length; bits != 0; bits--) {
  84109. n = s->bl_count[bits];
  84110. while (n != 0) {
  84111. m = s->heap[--h];
  84112. if (m > max_code) continue;
  84113. if ((unsigned) tree[m].Len != (unsigned) bits) {
  84114. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  84115. s->opt_len += ((long)bits - (long)tree[m].Len)
  84116. *(long)tree[m].Freq;
  84117. tree[m].Len = (ush)bits;
  84118. }
  84119. n--;
  84120. }
  84121. }
  84122. }
  84123. /* ===========================================================================
  84124. * Generate the codes for a given tree and bit counts (which need not be
  84125. * optimal).
  84126. * IN assertion: the array bl_count contains the bit length statistics for
  84127. * the given tree and the field len is set for all tree elements.
  84128. * OUT assertion: the field code is set for all tree elements of non
  84129. * zero code length.
  84130. */
  84131. local void gen_codes (ct_data *tree, /* the tree to decorate */
  84132. int max_code, /* largest code with non zero frequency */
  84133. ushf *bl_count) /* number of codes at each bit length */
  84134. {
  84135. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  84136. ush code = 0; /* running code value */
  84137. int bits; /* bit index */
  84138. int n; /* code index */
  84139. /* The distribution counts are first used to generate the code values
  84140. * without bit reversal.
  84141. */
  84142. for (bits = 1; bits <= MAX_BITS; bits++) {
  84143. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  84144. }
  84145. /* Check that the bit counts in bl_count are consistent. The last code
  84146. * must be all ones.
  84147. */
  84148. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  84149. "inconsistent bit counts");
  84150. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  84151. for (n = 0; n <= max_code; n++) {
  84152. int len = tree[n].Len;
  84153. if (len == 0) continue;
  84154. /* Now reverse the bits */
  84155. tree[n].Code = bi_reverse(next_code[len]++, len);
  84156. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  84157. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  84158. }
  84159. }
  84160. /* ===========================================================================
  84161. * Construct one Huffman tree and assigns the code bit strings and lengths.
  84162. * Update the total bit length for the current block.
  84163. * IN assertion: the field freq is set for all tree elements.
  84164. * OUT assertions: the fields len and code are set to the optimal bit length
  84165. * and corresponding code. The length opt_len is updated; static_len is
  84166. * also updated if stree is not null. The field max_code is set.
  84167. */
  84168. local void build_tree (deflate_state *s,
  84169. tree_desc *desc) /* the tree descriptor */
  84170. {
  84171. ct_data *tree = desc->dyn_tree;
  84172. const ct_data *stree = desc->stat_desc->static_tree;
  84173. int elems = desc->stat_desc->elems;
  84174. int n, m; /* iterate over heap elements */
  84175. int max_code = -1; /* largest code with non zero frequency */
  84176. int node; /* new node being created */
  84177. /* Construct the initial heap, with least frequent element in
  84178. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  84179. * heap[0] is not used.
  84180. */
  84181. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  84182. for (n = 0; n < elems; n++) {
  84183. if (tree[n].Freq != 0) {
  84184. s->heap[++(s->heap_len)] = max_code = n;
  84185. s->depth[n] = 0;
  84186. } else {
  84187. tree[n].Len = 0;
  84188. }
  84189. }
  84190. /* The pkzip format requires that at least one distance code exists,
  84191. * and that at least one bit should be sent even if there is only one
  84192. * possible code. So to avoid special checks later on we force at least
  84193. * two codes of non zero frequency.
  84194. */
  84195. while (s->heap_len < 2) {
  84196. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  84197. tree[node].Freq = 1;
  84198. s->depth[node] = 0;
  84199. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  84200. /* node is 0 or 1 so it does not have extra bits */
  84201. }
  84202. desc->max_code = max_code;
  84203. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  84204. * establish sub-heaps of increasing lengths:
  84205. */
  84206. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  84207. /* Construct the Huffman tree by repeatedly combining the least two
  84208. * frequent nodes.
  84209. */
  84210. node = elems; /* next internal node of the tree */
  84211. do {
  84212. pqremove(s, tree, n); /* n = node of least frequency */
  84213. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  84214. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  84215. s->heap[--(s->heap_max)] = m;
  84216. /* Create a new node father of n and m */
  84217. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  84218. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  84219. s->depth[n] : s->depth[m]) + 1);
  84220. tree[n].Dad = tree[m].Dad = (ush)node;
  84221. #ifdef DUMP_BL_TREE
  84222. if (tree == s->bl_tree) {
  84223. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  84224. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  84225. }
  84226. #endif
  84227. /* and insert the new node in the heap */
  84228. s->heap[SMALLEST] = node++;
  84229. pqdownheap(s, tree, SMALLEST);
  84230. } while (s->heap_len >= 2);
  84231. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  84232. /* At this point, the fields freq and dad are set. We can now
  84233. * generate the bit lengths.
  84234. */
  84235. gen_bitlen(s, (tree_desc *)desc);
  84236. /* The field len is now set, we can generate the bit codes */
  84237. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  84238. }
  84239. /* ===========================================================================
  84240. * Scan a literal or distance tree to determine the frequencies of the codes
  84241. * in the bit length tree.
  84242. */
  84243. local void scan_tree (deflate_state *s,
  84244. ct_data *tree, /* the tree to be scanned */
  84245. int max_code) /* and its largest code of non zero frequency */
  84246. {
  84247. int n; /* iterates over all tree elements */
  84248. int prevlen = -1; /* last emitted length */
  84249. int curlen; /* length of current code */
  84250. int nextlen = tree[0].Len; /* length of next code */
  84251. int count = 0; /* repeat count of the current code */
  84252. int max_count = 7; /* max repeat count */
  84253. int min_count = 4; /* min repeat count */
  84254. if (nextlen == 0) max_count = 138, min_count = 3;
  84255. tree[max_code+1].Len = (ush)0xffff; /* guard */
  84256. for (n = 0; n <= max_code; n++) {
  84257. curlen = nextlen; nextlen = tree[n+1].Len;
  84258. if (++count < max_count && curlen == nextlen) {
  84259. continue;
  84260. } else if (count < min_count) {
  84261. s->bl_tree[curlen].Freq += count;
  84262. } else if (curlen != 0) {
  84263. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  84264. s->bl_tree[REP_3_6].Freq++;
  84265. } else if (count <= 10) {
  84266. s->bl_tree[REPZ_3_10].Freq++;
  84267. } else {
  84268. s->bl_tree[REPZ_11_138].Freq++;
  84269. }
  84270. count = 0; prevlen = curlen;
  84271. if (nextlen == 0) {
  84272. max_count = 138, min_count = 3;
  84273. } else if (curlen == nextlen) {
  84274. max_count = 6, min_count = 3;
  84275. } else {
  84276. max_count = 7, min_count = 4;
  84277. }
  84278. }
  84279. }
  84280. /* ===========================================================================
  84281. * Send a literal or distance tree in compressed form, using the codes in
  84282. * bl_tree.
  84283. */
  84284. local void send_tree (deflate_state *s,
  84285. ct_data *tree, /* the tree to be scanned */
  84286. int max_code) /* and its largest code of non zero frequency */
  84287. {
  84288. int n; /* iterates over all tree elements */
  84289. int prevlen = -1; /* last emitted length */
  84290. int curlen; /* length of current code */
  84291. int nextlen = tree[0].Len; /* length of next code */
  84292. int count = 0; /* repeat count of the current code */
  84293. int max_count = 7; /* max repeat count */
  84294. int min_count = 4; /* min repeat count */
  84295. /* tree[max_code+1].Len = -1; */ /* guard already set */
  84296. if (nextlen == 0) max_count = 138, min_count = 3;
  84297. for (n = 0; n <= max_code; n++) {
  84298. curlen = nextlen; nextlen = tree[n+1].Len;
  84299. if (++count < max_count && curlen == nextlen) {
  84300. continue;
  84301. } else if (count < min_count) {
  84302. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  84303. } else if (curlen != 0) {
  84304. if (curlen != prevlen) {
  84305. send_code(s, curlen, s->bl_tree); count--;
  84306. }
  84307. Assert(count >= 3 && count <= 6, " 3_6?");
  84308. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  84309. } else if (count <= 10) {
  84310. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  84311. } else {
  84312. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  84313. }
  84314. count = 0; prevlen = curlen;
  84315. if (nextlen == 0) {
  84316. max_count = 138, min_count = 3;
  84317. } else if (curlen == nextlen) {
  84318. max_count = 6, min_count = 3;
  84319. } else {
  84320. max_count = 7, min_count = 4;
  84321. }
  84322. }
  84323. }
  84324. /* ===========================================================================
  84325. * Construct the Huffman tree for the bit lengths and return the index in
  84326. * bl_order of the last bit length code to send.
  84327. */
  84328. local int build_bl_tree (deflate_state *s)
  84329. {
  84330. int max_blindex; /* index of last bit length code of non zero freq */
  84331. /* Determine the bit length frequencies for literal and distance trees */
  84332. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  84333. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  84334. /* Build the bit length tree: */
  84335. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  84336. /* opt_len now includes the length of the tree representations, except
  84337. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  84338. */
  84339. /* Determine the number of bit length codes to send. The pkzip format
  84340. * requires that at least 4 bit length codes be sent. (appnote.txt says
  84341. * 3 but the actual value used is 4.)
  84342. */
  84343. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  84344. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  84345. }
  84346. /* Update opt_len to include the bit length tree and counts */
  84347. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  84348. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  84349. s->opt_len, s->static_len));
  84350. return max_blindex;
  84351. }
  84352. /* ===========================================================================
  84353. * Send the header for a block using dynamic Huffman trees: the counts, the
  84354. * lengths of the bit length codes, the literal tree and the distance tree.
  84355. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  84356. */
  84357. local void send_all_trees (deflate_state *s,
  84358. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  84359. {
  84360. int rank; /* index in bl_order */
  84361. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  84362. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  84363. "too many codes");
  84364. Tracev((stderr, "\nbl counts: "));
  84365. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  84366. send_bits(s, dcodes-1, 5);
  84367. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  84368. for (rank = 0; rank < blcodes; rank++) {
  84369. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  84370. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  84371. }
  84372. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  84373. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  84374. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  84375. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  84376. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  84377. }
  84378. /* ===========================================================================
  84379. * Send a stored block
  84380. */
  84381. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  84382. {
  84383. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  84384. #ifdef DEBUG
  84385. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  84386. s->compressed_len += (stored_len + 4) << 3;
  84387. #endif
  84388. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  84389. }
  84390. /* ===========================================================================
  84391. * Send one empty static block to give enough lookahead for inflate.
  84392. * This takes 10 bits, of which 7 may remain in the bit buffer.
  84393. * The current inflate code requires 9 bits of lookahead. If the
  84394. * last two codes for the previous block (real code plus EOB) were coded
  84395. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  84396. * the last real code. In this case we send two empty static blocks instead
  84397. * of one. (There are no problems if the previous block is stored or fixed.)
  84398. * To simplify the code, we assume the worst case of last real code encoded
  84399. * on one bit only.
  84400. */
  84401. void _tr_align (deflate_state *s)
  84402. {
  84403. send_bits(s, STATIC_TREES<<1, 3);
  84404. send_code(s, END_BLOCK, static_ltree);
  84405. #ifdef DEBUG
  84406. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  84407. #endif
  84408. bi_flush(s);
  84409. /* Of the 10 bits for the empty block, we have already sent
  84410. * (10 - bi_valid) bits. The lookahead for the last real code (before
  84411. * the EOB of the previous block) was thus at least one plus the length
  84412. * of the EOB plus what we have just sent of the empty static block.
  84413. */
  84414. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  84415. send_bits(s, STATIC_TREES<<1, 3);
  84416. send_code(s, END_BLOCK, static_ltree);
  84417. #ifdef DEBUG
  84418. s->compressed_len += 10L;
  84419. #endif
  84420. bi_flush(s);
  84421. }
  84422. s->last_eob_len = 7;
  84423. }
  84424. /* ===========================================================================
  84425. * Determine the best encoding for the current block: dynamic trees, static
  84426. * trees or store, and output the encoded block to the zip file.
  84427. */
  84428. void _tr_flush_block (deflate_state *s,
  84429. charf *buf, /* input block, or NULL if too old */
  84430. ulg stored_len, /* length of input block */
  84431. int eof) /* true if this is the last block for a file */
  84432. {
  84433. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  84434. int max_blindex = 0; /* index of last bit length code of non zero freq */
  84435. /* Build the Huffman trees unless a stored block is forced */
  84436. if (s->level > 0) {
  84437. /* Check if the file is binary or text */
  84438. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  84439. set_data_type(s);
  84440. /* Construct the literal and distance trees */
  84441. build_tree(s, (tree_desc *)(&(s->l_desc)));
  84442. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  84443. s->static_len));
  84444. build_tree(s, (tree_desc *)(&(s->d_desc)));
  84445. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  84446. s->static_len));
  84447. /* At this point, opt_len and static_len are the total bit lengths of
  84448. * the compressed block data, excluding the tree representations.
  84449. */
  84450. /* Build the bit length tree for the above two trees, and get the index
  84451. * in bl_order of the last bit length code to send.
  84452. */
  84453. max_blindex = build_bl_tree(s);
  84454. /* Determine the best encoding. Compute the block lengths in bytes. */
  84455. opt_lenb = (s->opt_len+3+7)>>3;
  84456. static_lenb = (s->static_len+3+7)>>3;
  84457. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  84458. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  84459. s->last_lit));
  84460. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  84461. } else {
  84462. Assert(buf != (char*)0, "lost buf");
  84463. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  84464. }
  84465. #ifdef FORCE_STORED
  84466. if (buf != (char*)0) { /* force stored block */
  84467. #else
  84468. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  84469. /* 4: two words for the lengths */
  84470. #endif
  84471. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  84472. * Otherwise we can't have processed more than WSIZE input bytes since
  84473. * the last block flush, because compression would have been
  84474. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  84475. * transform a block into a stored block.
  84476. */
  84477. _tr_stored_block(s, buf, stored_len, eof);
  84478. #ifdef FORCE_STATIC
  84479. } else if (static_lenb >= 0) { /* force static trees */
  84480. #else
  84481. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  84482. #endif
  84483. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  84484. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  84485. #ifdef DEBUG
  84486. s->compressed_len += 3 + s->static_len;
  84487. #endif
  84488. } else {
  84489. send_bits(s, (DYN_TREES<<1)+eof, 3);
  84490. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  84491. max_blindex+1);
  84492. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  84493. #ifdef DEBUG
  84494. s->compressed_len += 3 + s->opt_len;
  84495. #endif
  84496. }
  84497. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  84498. /* The above check is made mod 2^32, for files larger than 512 MB
  84499. * and uLong implemented on 32 bits.
  84500. */
  84501. init_block(s);
  84502. if (eof) {
  84503. bi_windup(s);
  84504. #ifdef DEBUG
  84505. s->compressed_len += 7; /* align on byte boundary */
  84506. #endif
  84507. }
  84508. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  84509. s->compressed_len-7*eof));
  84510. }
  84511. /* ===========================================================================
  84512. * Save the match info and tally the frequency counts. Return true if
  84513. * the current block must be flushed.
  84514. */
  84515. int _tr_tally (deflate_state *s,
  84516. unsigned dist, /* distance of matched string */
  84517. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  84518. {
  84519. s->d_buf[s->last_lit] = (ush)dist;
  84520. s->l_buf[s->last_lit++] = (uch)lc;
  84521. if (dist == 0) {
  84522. /* lc is the unmatched char */
  84523. s->dyn_ltree[lc].Freq++;
  84524. } else {
  84525. s->matches++;
  84526. /* Here, lc is the match length - MIN_MATCH */
  84527. dist--; /* dist = match distance - 1 */
  84528. Assert((ush)dist < (ush)MAX_DIST(s) &&
  84529. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  84530. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  84531. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  84532. s->dyn_dtree[d_code(dist)].Freq++;
  84533. }
  84534. #ifdef TRUNCATE_BLOCK
  84535. /* Try to guess if it is profitable to stop the current block here */
  84536. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  84537. /* Compute an upper bound for the compressed length */
  84538. ulg out_length = (ulg)s->last_lit*8L;
  84539. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  84540. int dcode;
  84541. for (dcode = 0; dcode < D_CODES; dcode++) {
  84542. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  84543. (5L+extra_dbits[dcode]);
  84544. }
  84545. out_length >>= 3;
  84546. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  84547. s->last_lit, in_length, out_length,
  84548. 100L - out_length*100L/in_length));
  84549. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  84550. }
  84551. #endif
  84552. return (s->last_lit == s->lit_bufsize-1);
  84553. /* We avoid equality with lit_bufsize because of wraparound at 64K
  84554. * on 16 bit machines and because stored blocks are restricted to
  84555. * 64K-1 bytes.
  84556. */
  84557. }
  84558. /* ===========================================================================
  84559. * Send the block data compressed using the given Huffman trees
  84560. */
  84561. local void compress_block (deflate_state *s,
  84562. ct_data *ltree, /* literal tree */
  84563. ct_data *dtree) /* distance tree */
  84564. {
  84565. unsigned dist; /* distance of matched string */
  84566. int lc; /* match length or unmatched char (if dist == 0) */
  84567. unsigned lx = 0; /* running index in l_buf */
  84568. unsigned code; /* the code to send */
  84569. int extra; /* number of extra bits to send */
  84570. if (s->last_lit != 0) do {
  84571. dist = s->d_buf[lx];
  84572. lc = s->l_buf[lx++];
  84573. if (dist == 0) {
  84574. send_code(s, lc, ltree); /* send a literal byte */
  84575. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  84576. } else {
  84577. /* Here, lc is the match length - MIN_MATCH */
  84578. code = _length_code[lc];
  84579. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  84580. extra = extra_lbits[code];
  84581. if (extra != 0) {
  84582. lc -= base_length[code];
  84583. send_bits(s, lc, extra); /* send the extra length bits */
  84584. }
  84585. dist--; /* dist is now the match distance - 1 */
  84586. code = d_code(dist);
  84587. Assert (code < D_CODES, "bad d_code");
  84588. send_code(s, code, dtree); /* send the distance code */
  84589. extra = extra_dbits[code];
  84590. if (extra != 0) {
  84591. dist -= base_dist[code];
  84592. send_bits(s, dist, extra); /* send the extra distance bits */
  84593. }
  84594. } /* literal or match pair ? */
  84595. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  84596. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  84597. "pendingBuf overflow");
  84598. } while (lx < s->last_lit);
  84599. send_code(s, END_BLOCK, ltree);
  84600. s->last_eob_len = ltree[END_BLOCK].Len;
  84601. }
  84602. /* ===========================================================================
  84603. * Set the data type to BINARY or TEXT, using a crude approximation:
  84604. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  84605. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  84606. * IN assertion: the fields Freq of dyn_ltree are set.
  84607. */
  84608. local void set_data_type (deflate_state *s)
  84609. {
  84610. int n;
  84611. for (n = 0; n < 9; n++)
  84612. if (s->dyn_ltree[n].Freq != 0)
  84613. break;
  84614. if (n == 9)
  84615. for (n = 14; n < 32; n++)
  84616. if (s->dyn_ltree[n].Freq != 0)
  84617. break;
  84618. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  84619. }
  84620. /* ===========================================================================
  84621. * Reverse the first len bits of a code, using straightforward code (a faster
  84622. * method would use a table)
  84623. * IN assertion: 1 <= len <= 15
  84624. */
  84625. local unsigned bi_reverse (unsigned code, int len)
  84626. {
  84627. register unsigned res = 0;
  84628. do {
  84629. res |= code & 1;
  84630. code >>= 1, res <<= 1;
  84631. } while (--len > 0);
  84632. return res >> 1;
  84633. }
  84634. /* ===========================================================================
  84635. * Flush the bit buffer, keeping at most 7 bits in it.
  84636. */
  84637. local void bi_flush (deflate_state *s)
  84638. {
  84639. if (s->bi_valid == 16) {
  84640. put_short(s, s->bi_buf);
  84641. s->bi_buf = 0;
  84642. s->bi_valid = 0;
  84643. } else if (s->bi_valid >= 8) {
  84644. put_byte(s, (Byte)s->bi_buf);
  84645. s->bi_buf >>= 8;
  84646. s->bi_valid -= 8;
  84647. }
  84648. }
  84649. /* ===========================================================================
  84650. * Flush the bit buffer and align the output on a byte boundary
  84651. */
  84652. local void bi_windup (deflate_state *s)
  84653. {
  84654. if (s->bi_valid > 8) {
  84655. put_short(s, s->bi_buf);
  84656. } else if (s->bi_valid > 0) {
  84657. put_byte(s, (Byte)s->bi_buf);
  84658. }
  84659. s->bi_buf = 0;
  84660. s->bi_valid = 0;
  84661. #ifdef DEBUG
  84662. s->bits_sent = (s->bits_sent+7) & ~7;
  84663. #endif
  84664. }
  84665. /* ===========================================================================
  84666. * Copy a stored block, storing first the length and its
  84667. * one's complement if requested.
  84668. */
  84669. local void copy_block(deflate_state *s,
  84670. charf *buf, /* the input data */
  84671. unsigned len, /* its length */
  84672. int header) /* true if block header must be written */
  84673. {
  84674. bi_windup(s); /* align on byte boundary */
  84675. s->last_eob_len = 8; /* enough lookahead for inflate */
  84676. if (header) {
  84677. put_short(s, (ush)len);
  84678. put_short(s, (ush)~len);
  84679. #ifdef DEBUG
  84680. s->bits_sent += 2*16;
  84681. #endif
  84682. }
  84683. #ifdef DEBUG
  84684. s->bits_sent += (ulg)len<<3;
  84685. #endif
  84686. while (len--) {
  84687. put_byte(s, *buf++);
  84688. }
  84689. }
  84690. /*** End of inlined file: trees.c ***/
  84691. /*** Start of inlined file: zutil.c ***/
  84692. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84693. #ifndef NO_DUMMY_DECL
  84694. struct internal_state {int dummy;}; /* for buggy compilers */
  84695. #endif
  84696. const char * const z_errmsg[10] = {
  84697. "need dictionary", /* Z_NEED_DICT 2 */
  84698. "stream end", /* Z_STREAM_END 1 */
  84699. "", /* Z_OK 0 */
  84700. "file error", /* Z_ERRNO (-1) */
  84701. "stream error", /* Z_STREAM_ERROR (-2) */
  84702. "data error", /* Z_DATA_ERROR (-3) */
  84703. "insufficient memory", /* Z_MEM_ERROR (-4) */
  84704. "buffer error", /* Z_BUF_ERROR (-5) */
  84705. "incompatible version",/* Z_VERSION_ERROR (-6) */
  84706. ""};
  84707. /*const char * ZEXPORT zlibVersion()
  84708. {
  84709. return ZLIB_VERSION;
  84710. }
  84711. uLong ZEXPORT zlibCompileFlags()
  84712. {
  84713. uLong flags;
  84714. flags = 0;
  84715. switch (sizeof(uInt)) {
  84716. case 2: break;
  84717. case 4: flags += 1; break;
  84718. case 8: flags += 2; break;
  84719. default: flags += 3;
  84720. }
  84721. switch (sizeof(uLong)) {
  84722. case 2: break;
  84723. case 4: flags += 1 << 2; break;
  84724. case 8: flags += 2 << 2; break;
  84725. default: flags += 3 << 2;
  84726. }
  84727. switch (sizeof(voidpf)) {
  84728. case 2: break;
  84729. case 4: flags += 1 << 4; break;
  84730. case 8: flags += 2 << 4; break;
  84731. default: flags += 3 << 4;
  84732. }
  84733. switch (sizeof(z_off_t)) {
  84734. case 2: break;
  84735. case 4: flags += 1 << 6; break;
  84736. case 8: flags += 2 << 6; break;
  84737. default: flags += 3 << 6;
  84738. }
  84739. #ifdef DEBUG
  84740. flags += 1 << 8;
  84741. #endif
  84742. #if defined(ASMV) || defined(ASMINF)
  84743. flags += 1 << 9;
  84744. #endif
  84745. #ifdef ZLIB_WINAPI
  84746. flags += 1 << 10;
  84747. #endif
  84748. #ifdef BUILDFIXED
  84749. flags += 1 << 12;
  84750. #endif
  84751. #ifdef DYNAMIC_CRC_TABLE
  84752. flags += 1 << 13;
  84753. #endif
  84754. #ifdef NO_GZCOMPRESS
  84755. flags += 1L << 16;
  84756. #endif
  84757. #ifdef NO_GZIP
  84758. flags += 1L << 17;
  84759. #endif
  84760. #ifdef PKZIP_BUG_WORKAROUND
  84761. flags += 1L << 20;
  84762. #endif
  84763. #ifdef FASTEST
  84764. flags += 1L << 21;
  84765. #endif
  84766. #ifdef STDC
  84767. # ifdef NO_vsnprintf
  84768. flags += 1L << 25;
  84769. # ifdef HAS_vsprintf_void
  84770. flags += 1L << 26;
  84771. # endif
  84772. # else
  84773. # ifdef HAS_vsnprintf_void
  84774. flags += 1L << 26;
  84775. # endif
  84776. # endif
  84777. #else
  84778. flags += 1L << 24;
  84779. # ifdef NO_snprintf
  84780. flags += 1L << 25;
  84781. # ifdef HAS_sprintf_void
  84782. flags += 1L << 26;
  84783. # endif
  84784. # else
  84785. # ifdef HAS_snprintf_void
  84786. flags += 1L << 26;
  84787. # endif
  84788. # endif
  84789. #endif
  84790. return flags;
  84791. }*/
  84792. #ifdef DEBUG
  84793. # ifndef verbose
  84794. # define verbose 0
  84795. # endif
  84796. int z_verbose = verbose;
  84797. void z_error (const char *m)
  84798. {
  84799. fprintf(stderr, "%s\n", m);
  84800. exit(1);
  84801. }
  84802. #endif
  84803. /* exported to allow conversion of error code to string for compress() and
  84804. * uncompress()
  84805. */
  84806. const char * ZEXPORT zError(int err)
  84807. {
  84808. return ERR_MSG(err);
  84809. }
  84810. #if defined(_WIN32_WCE)
  84811. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  84812. * errno. We define it as a global variable to simplify porting.
  84813. * Its value is always 0 and should not be used.
  84814. */
  84815. int errno = 0;
  84816. #endif
  84817. #ifndef HAVE_MEMCPY
  84818. void zmemcpy(dest, source, len)
  84819. Bytef* dest;
  84820. const Bytef* source;
  84821. uInt len;
  84822. {
  84823. if (len == 0) return;
  84824. do {
  84825. *dest++ = *source++; /* ??? to be unrolled */
  84826. } while (--len != 0);
  84827. }
  84828. int zmemcmp(s1, s2, len)
  84829. const Bytef* s1;
  84830. const Bytef* s2;
  84831. uInt len;
  84832. {
  84833. uInt j;
  84834. for (j = 0; j < len; j++) {
  84835. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  84836. }
  84837. return 0;
  84838. }
  84839. void zmemzero(dest, len)
  84840. Bytef* dest;
  84841. uInt len;
  84842. {
  84843. if (len == 0) return;
  84844. do {
  84845. *dest++ = 0; /* ??? to be unrolled */
  84846. } while (--len != 0);
  84847. }
  84848. #endif
  84849. #ifdef SYS16BIT
  84850. #ifdef __TURBOC__
  84851. /* Turbo C in 16-bit mode */
  84852. # define MY_ZCALLOC
  84853. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  84854. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  84855. * must fix the pointer. Warning: the pointer must be put back to its
  84856. * original form in order to free it, use zcfree().
  84857. */
  84858. #define MAX_PTR 10
  84859. /* 10*64K = 640K */
  84860. local int next_ptr = 0;
  84861. typedef struct ptr_table_s {
  84862. voidpf org_ptr;
  84863. voidpf new_ptr;
  84864. } ptr_table;
  84865. local ptr_table table[MAX_PTR];
  84866. /* This table is used to remember the original form of pointers
  84867. * to large buffers (64K). Such pointers are normalized with a zero offset.
  84868. * Since MSDOS is not a preemptive multitasking OS, this table is not
  84869. * protected from concurrent access. This hack doesn't work anyway on
  84870. * a protected system like OS/2. Use Microsoft C instead.
  84871. */
  84872. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  84873. {
  84874. voidpf buf = opaque; /* just to make some compilers happy */
  84875. ulg bsize = (ulg)items*size;
  84876. /* If we allocate less than 65520 bytes, we assume that farmalloc
  84877. * will return a usable pointer which doesn't have to be normalized.
  84878. */
  84879. if (bsize < 65520L) {
  84880. buf = farmalloc(bsize);
  84881. if (*(ush*)&buf != 0) return buf;
  84882. } else {
  84883. buf = farmalloc(bsize + 16L);
  84884. }
  84885. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  84886. table[next_ptr].org_ptr = buf;
  84887. /* Normalize the pointer to seg:0 */
  84888. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  84889. *(ush*)&buf = 0;
  84890. table[next_ptr++].new_ptr = buf;
  84891. return buf;
  84892. }
  84893. void zcfree (voidpf opaque, voidpf ptr)
  84894. {
  84895. int n;
  84896. if (*(ush*)&ptr != 0) { /* object < 64K */
  84897. farfree(ptr);
  84898. return;
  84899. }
  84900. /* Find the original pointer */
  84901. for (n = 0; n < next_ptr; n++) {
  84902. if (ptr != table[n].new_ptr) continue;
  84903. farfree(table[n].org_ptr);
  84904. while (++n < next_ptr) {
  84905. table[n-1] = table[n];
  84906. }
  84907. next_ptr--;
  84908. return;
  84909. }
  84910. ptr = opaque; /* just to make some compilers happy */
  84911. Assert(0, "zcfree: ptr not found");
  84912. }
  84913. #endif /* __TURBOC__ */
  84914. #ifdef M_I86
  84915. /* Microsoft C in 16-bit mode */
  84916. # define MY_ZCALLOC
  84917. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  84918. # define _halloc halloc
  84919. # define _hfree hfree
  84920. #endif
  84921. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  84922. {
  84923. if (opaque) opaque = 0; /* to make compiler happy */
  84924. return _halloc((long)items, size);
  84925. }
  84926. void zcfree (voidpf opaque, voidpf ptr)
  84927. {
  84928. if (opaque) opaque = 0; /* to make compiler happy */
  84929. _hfree(ptr);
  84930. }
  84931. #endif /* M_I86 */
  84932. #endif /* SYS16BIT */
  84933. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  84934. #ifndef STDC
  84935. extern voidp malloc OF((uInt size));
  84936. extern voidp calloc OF((uInt items, uInt size));
  84937. extern void free OF((voidpf ptr));
  84938. #endif
  84939. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  84940. {
  84941. if (opaque) items += size - size; /* make compiler happy */
  84942. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  84943. (voidpf)calloc(items, size);
  84944. }
  84945. void zcfree (voidpf opaque, voidpf ptr)
  84946. {
  84947. free(ptr);
  84948. if (opaque) return; /* make compiler happy */
  84949. }
  84950. #endif /* MY_ZCALLOC */
  84951. /*** End of inlined file: zutil.c ***/
  84952. #undef Byte
  84953. }
  84954. #else
  84955. #include <zlib.h>
  84956. #endif
  84957. }
  84958. #if JUCE_MSVC
  84959. #pragma warning (pop)
  84960. #endif
  84961. BEGIN_JUCE_NAMESPACE
  84962. // internal helper object that holds the zlib structures so they don't have to be
  84963. // included publicly.
  84964. class GZIPDecompressHelper
  84965. {
  84966. public:
  84967. GZIPDecompressHelper (const bool noWrap)
  84968. : finished (true),
  84969. needsDictionary (false),
  84970. error (true),
  84971. streamIsValid (false),
  84972. data (0),
  84973. dataSize (0)
  84974. {
  84975. using namespace zlibNamespace;
  84976. zerostruct (stream);
  84977. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  84978. finished = error = ! streamIsValid;
  84979. }
  84980. ~GZIPDecompressHelper()
  84981. {
  84982. using namespace zlibNamespace;
  84983. if (streamIsValid)
  84984. inflateEnd (&stream);
  84985. }
  84986. bool needsInput() const throw() { return dataSize <= 0; }
  84987. void setInput (uint8* const data_, const int size) throw()
  84988. {
  84989. data = data_;
  84990. dataSize = size;
  84991. }
  84992. int doNextBlock (uint8* const dest, const int destSize)
  84993. {
  84994. using namespace zlibNamespace;
  84995. if (streamIsValid && data != 0 && ! finished)
  84996. {
  84997. stream.next_in = data;
  84998. stream.next_out = dest;
  84999. stream.avail_in = dataSize;
  85000. stream.avail_out = destSize;
  85001. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85002. {
  85003. case Z_STREAM_END:
  85004. finished = true;
  85005. // deliberate fall-through
  85006. case Z_OK:
  85007. data += dataSize - stream.avail_in;
  85008. dataSize = stream.avail_in;
  85009. return destSize - stream.avail_out;
  85010. case Z_NEED_DICT:
  85011. needsDictionary = true;
  85012. data += dataSize - stream.avail_in;
  85013. dataSize = stream.avail_in;
  85014. break;
  85015. case Z_DATA_ERROR:
  85016. case Z_MEM_ERROR:
  85017. error = true;
  85018. default:
  85019. break;
  85020. }
  85021. }
  85022. return 0;
  85023. }
  85024. bool finished, needsDictionary, error, streamIsValid;
  85025. private:
  85026. zlibNamespace::z_stream stream;
  85027. uint8* data;
  85028. int dataSize;
  85029. GZIPDecompressHelper (const GZIPDecompressHelper&);
  85030. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  85031. };
  85032. const int gzipDecompBufferSize = 32768;
  85033. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85034. const bool deleteSourceWhenDestroyed,
  85035. const bool noWrap_,
  85036. const int64 uncompressedStreamLength_)
  85037. : sourceStream (sourceStream_),
  85038. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85039. uncompressedStreamLength (uncompressedStreamLength_),
  85040. noWrap (noWrap_),
  85041. isEof (false),
  85042. activeBufferSize (0),
  85043. originalSourcePos (sourceStream_->getPosition()),
  85044. currentPos (0),
  85045. buffer (gzipDecompBufferSize),
  85046. helper (new GZIPDecompressHelper (noWrap_))
  85047. {
  85048. }
  85049. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85050. {
  85051. }
  85052. int64 GZIPDecompressorInputStream::getTotalLength()
  85053. {
  85054. return uncompressedStreamLength;
  85055. }
  85056. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85057. {
  85058. if ((howMany > 0) && ! isEof)
  85059. {
  85060. jassert (destBuffer != 0);
  85061. if (destBuffer != 0)
  85062. {
  85063. int numRead = 0;
  85064. uint8* d = static_cast <uint8*> (destBuffer);
  85065. while (! helper->error)
  85066. {
  85067. const int n = helper->doNextBlock (d, howMany);
  85068. currentPos += n;
  85069. if (n == 0)
  85070. {
  85071. if (helper->finished || helper->needsDictionary)
  85072. {
  85073. isEof = true;
  85074. return numRead;
  85075. }
  85076. if (helper->needsInput())
  85077. {
  85078. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  85079. if (activeBufferSize > 0)
  85080. {
  85081. helper->setInput (buffer, activeBufferSize);
  85082. }
  85083. else
  85084. {
  85085. isEof = true;
  85086. return numRead;
  85087. }
  85088. }
  85089. }
  85090. else
  85091. {
  85092. numRead += n;
  85093. howMany -= n;
  85094. d += n;
  85095. if (howMany <= 0)
  85096. return numRead;
  85097. }
  85098. }
  85099. }
  85100. }
  85101. return 0;
  85102. }
  85103. bool GZIPDecompressorInputStream::isExhausted()
  85104. {
  85105. return helper->error || isEof;
  85106. }
  85107. int64 GZIPDecompressorInputStream::getPosition()
  85108. {
  85109. return currentPos;
  85110. }
  85111. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  85112. {
  85113. if (newPos < currentPos)
  85114. {
  85115. // to go backwards, reset the stream and start again..
  85116. isEof = false;
  85117. activeBufferSize = 0;
  85118. currentPos = 0;
  85119. helper = new GZIPDecompressHelper (noWrap);
  85120. sourceStream->setPosition (originalSourcePos);
  85121. }
  85122. skipNextBytes (newPos - currentPos);
  85123. return true;
  85124. }
  85125. END_JUCE_NAMESPACE
  85126. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  85127. #endif
  85128. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  85129. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  85130. #if JUCE_USE_FLAC
  85131. #if JUCE_WINDOWS
  85132. #include <windows.h>
  85133. #endif
  85134. namespace FlacNamespace
  85135. {
  85136. #if JUCE_INCLUDE_FLAC_CODE
  85137. #if JUCE_MSVC
  85138. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  85139. #endif
  85140. #define FLAC__NO_DLL 1
  85141. #if ! defined (SIZE_MAX)
  85142. #define SIZE_MAX 0xffffffff
  85143. #endif
  85144. #define __STDC_LIMIT_MACROS 1
  85145. /*** Start of inlined file: all.h ***/
  85146. #ifndef FLAC__ALL_H
  85147. #define FLAC__ALL_H
  85148. /*** Start of inlined file: export.h ***/
  85149. #ifndef FLAC__EXPORT_H
  85150. #define FLAC__EXPORT_H
  85151. /** \file include/FLAC/export.h
  85152. *
  85153. * \brief
  85154. * This module contains #defines and symbols for exporting function
  85155. * calls, and providing version information and compiled-in features.
  85156. *
  85157. * See the \link flac_export export \endlink module.
  85158. */
  85159. /** \defgroup flac_export FLAC/export.h: export symbols
  85160. * \ingroup flac
  85161. *
  85162. * \brief
  85163. * This module contains #defines and symbols for exporting function
  85164. * calls, and providing version information and compiled-in features.
  85165. *
  85166. * If you are compiling with MSVC and will link to the static library
  85167. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  85168. * make sure the symbols are exported properly.
  85169. *
  85170. * \{
  85171. */
  85172. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  85173. #define FLAC_API
  85174. #else
  85175. #ifdef FLAC_API_EXPORTS
  85176. #define FLAC_API _declspec(dllexport)
  85177. #else
  85178. #define FLAC_API _declspec(dllimport)
  85179. #endif
  85180. #endif
  85181. /** These #defines will mirror the libtool-based library version number, see
  85182. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  85183. */
  85184. #define FLAC_API_VERSION_CURRENT 10
  85185. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  85186. #define FLAC_API_VERSION_AGE 2 /**< see above */
  85187. #ifdef __cplusplus
  85188. extern "C" {
  85189. #endif
  85190. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  85191. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  85192. #ifdef __cplusplus
  85193. }
  85194. #endif
  85195. /* \} */
  85196. #endif
  85197. /*** End of inlined file: export.h ***/
  85198. /*** Start of inlined file: assert.h ***/
  85199. #ifndef FLAC__ASSERT_H
  85200. #define FLAC__ASSERT_H
  85201. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  85202. #ifdef DEBUG
  85203. #include <assert.h>
  85204. #define FLAC__ASSERT(x) assert(x)
  85205. #define FLAC__ASSERT_DECLARATION(x) x
  85206. #else
  85207. #define FLAC__ASSERT(x)
  85208. #define FLAC__ASSERT_DECLARATION(x)
  85209. #endif
  85210. #endif
  85211. /*** End of inlined file: assert.h ***/
  85212. /*** Start of inlined file: callback.h ***/
  85213. #ifndef FLAC__CALLBACK_H
  85214. #define FLAC__CALLBACK_H
  85215. /*** Start of inlined file: ordinals.h ***/
  85216. #ifndef FLAC__ORDINALS_H
  85217. #define FLAC__ORDINALS_H
  85218. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  85219. #include <inttypes.h>
  85220. #endif
  85221. typedef signed char FLAC__int8;
  85222. typedef unsigned char FLAC__uint8;
  85223. #if defined(_MSC_VER) || defined(__BORLANDC__)
  85224. typedef __int16 FLAC__int16;
  85225. typedef __int32 FLAC__int32;
  85226. typedef __int64 FLAC__int64;
  85227. typedef unsigned __int16 FLAC__uint16;
  85228. typedef unsigned __int32 FLAC__uint32;
  85229. typedef unsigned __int64 FLAC__uint64;
  85230. #elif defined(__EMX__)
  85231. typedef short FLAC__int16;
  85232. typedef long FLAC__int32;
  85233. typedef long long FLAC__int64;
  85234. typedef unsigned short FLAC__uint16;
  85235. typedef unsigned long FLAC__uint32;
  85236. typedef unsigned long long FLAC__uint64;
  85237. #else
  85238. typedef int16_t FLAC__int16;
  85239. typedef int32_t FLAC__int32;
  85240. typedef int64_t FLAC__int64;
  85241. typedef uint16_t FLAC__uint16;
  85242. typedef uint32_t FLAC__uint32;
  85243. typedef uint64_t FLAC__uint64;
  85244. #endif
  85245. typedef int FLAC__bool;
  85246. typedef FLAC__uint8 FLAC__byte;
  85247. #ifdef true
  85248. #undef true
  85249. #endif
  85250. #ifdef false
  85251. #undef false
  85252. #endif
  85253. #ifndef __cplusplus
  85254. #define true 1
  85255. #define false 0
  85256. #endif
  85257. #endif
  85258. /*** End of inlined file: ordinals.h ***/
  85259. #include <stdlib.h> /* for size_t */
  85260. /** \file include/FLAC/callback.h
  85261. *
  85262. * \brief
  85263. * This module defines the structures for describing I/O callbacks
  85264. * to the other FLAC interfaces.
  85265. *
  85266. * See the detailed documentation for callbacks in the
  85267. * \link flac_callbacks callbacks \endlink module.
  85268. */
  85269. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  85270. * \ingroup flac
  85271. *
  85272. * \brief
  85273. * This module defines the structures for describing I/O callbacks
  85274. * to the other FLAC interfaces.
  85275. *
  85276. * The purpose of the I/O callback functions is to create a common way
  85277. * for the metadata interfaces to handle I/O.
  85278. *
  85279. * Originally the metadata interfaces required filenames as the way of
  85280. * specifying FLAC files to operate on. This is problematic in some
  85281. * environments so there is an additional option to specify a set of
  85282. * callbacks for doing I/O on the FLAC file, instead of the filename.
  85283. *
  85284. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  85285. * opaque structure for a data source.
  85286. *
  85287. * The callback function prototypes are similar (but not identical) to the
  85288. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  85289. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  85290. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  85291. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  85292. * is required. \warning You generally CANNOT directly use fseek or ftell
  85293. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  85294. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  85295. * large files. You will have to find an equivalent function (e.g. ftello),
  85296. * or write a wrapper. The same is true for feof() since this is usually
  85297. * implemented as a macro, not as a function whose address can be taken.
  85298. *
  85299. * \{
  85300. */
  85301. #ifdef __cplusplus
  85302. extern "C" {
  85303. #endif
  85304. /** This is the opaque handle type used by the callbacks. Typically
  85305. * this is a \c FILE* or address of a file descriptor.
  85306. */
  85307. typedef void* FLAC__IOHandle;
  85308. /** Signature for the read callback.
  85309. * The signature and semantics match POSIX fread() implementations
  85310. * and can generally be used interchangeably.
  85311. *
  85312. * \param ptr The address of the read buffer.
  85313. * \param size The size of the records to be read.
  85314. * \param nmemb The number of records to be read.
  85315. * \param handle The handle to the data source.
  85316. * \retval size_t
  85317. * The number of records read.
  85318. */
  85319. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85320. /** Signature for the write callback.
  85321. * The signature and semantics match POSIX fwrite() implementations
  85322. * and can generally be used interchangeably.
  85323. *
  85324. * \param ptr The address of the write buffer.
  85325. * \param size The size of the records to be written.
  85326. * \param nmemb The number of records to be written.
  85327. * \param handle The handle to the data source.
  85328. * \retval size_t
  85329. * The number of records written.
  85330. */
  85331. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85332. /** Signature for the seek callback.
  85333. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  85334. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  85335. * and 32-bits wide.
  85336. *
  85337. * \param handle The handle to the data source.
  85338. * \param offset The new position, relative to \a whence
  85339. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  85340. * \retval int
  85341. * \c 0 on success, \c -1 on error.
  85342. */
  85343. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  85344. /** Signature for the tell callback.
  85345. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  85346. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  85347. * and 32-bits wide.
  85348. *
  85349. * \param handle The handle to the data source.
  85350. * \retval FLAC__int64
  85351. * The current position on success, \c -1 on error.
  85352. */
  85353. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  85354. /** Signature for the EOF callback.
  85355. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  85356. * on many systems, feof() is a macro, so in this case a wrapper function
  85357. * must be provided instead.
  85358. *
  85359. * \param handle The handle to the data source.
  85360. * \retval int
  85361. * \c 0 if not at end of file, nonzero if at end of file.
  85362. */
  85363. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  85364. /** Signature for the close callback.
  85365. * The signature and semantics match POSIX fclose() implementations
  85366. * and can generally be used interchangeably.
  85367. *
  85368. * \param handle The handle to the data source.
  85369. * \retval int
  85370. * \c 0 on success, \c EOF on error.
  85371. */
  85372. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  85373. /** A structure for holding a set of callbacks.
  85374. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  85375. * describe which of the callbacks are required. The ones that are not
  85376. * required may be set to NULL.
  85377. *
  85378. * If the seek requirement for an interface is optional, you can signify that
  85379. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  85380. */
  85381. typedef struct {
  85382. FLAC__IOCallback_Read read;
  85383. FLAC__IOCallback_Write write;
  85384. FLAC__IOCallback_Seek seek;
  85385. FLAC__IOCallback_Tell tell;
  85386. FLAC__IOCallback_Eof eof;
  85387. FLAC__IOCallback_Close close;
  85388. } FLAC__IOCallbacks;
  85389. /* \} */
  85390. #ifdef __cplusplus
  85391. }
  85392. #endif
  85393. #endif
  85394. /*** End of inlined file: callback.h ***/
  85395. /*** Start of inlined file: format.h ***/
  85396. #ifndef FLAC__FORMAT_H
  85397. #define FLAC__FORMAT_H
  85398. #ifdef __cplusplus
  85399. extern "C" {
  85400. #endif
  85401. /** \file include/FLAC/format.h
  85402. *
  85403. * \brief
  85404. * This module contains structure definitions for the representation
  85405. * of FLAC format components in memory. These are the basic
  85406. * structures used by the rest of the interfaces.
  85407. *
  85408. * See the detailed documentation in the
  85409. * \link flac_format format \endlink module.
  85410. */
  85411. /** \defgroup flac_format FLAC/format.h: format components
  85412. * \ingroup flac
  85413. *
  85414. * \brief
  85415. * This module contains structure definitions for the representation
  85416. * of FLAC format components in memory. These are the basic
  85417. * structures used by the rest of the interfaces.
  85418. *
  85419. * First, you should be familiar with the
  85420. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  85421. * follow directly from the specification. As a user of libFLAC, the
  85422. * interesting parts really are the structures that describe the frame
  85423. * header and metadata blocks.
  85424. *
  85425. * The format structures here are very primitive, designed to store
  85426. * information in an efficient way. Reading information from the
  85427. * structures is easy but creating or modifying them directly is
  85428. * more complex. For the most part, as a user of a library, editing
  85429. * is not necessary; however, for metadata blocks it is, so there are
  85430. * convenience functions provided in the \link flac_metadata metadata
  85431. * module \endlink to simplify the manipulation of metadata blocks.
  85432. *
  85433. * \note
  85434. * It's not the best convention, but symbols ending in _LEN are in bits
  85435. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  85436. * global variables because they are usually used when declaring byte
  85437. * arrays and some compilers require compile-time knowledge of array
  85438. * sizes when declared on the stack.
  85439. *
  85440. * \{
  85441. */
  85442. /*
  85443. Most of the values described in this file are defined by the FLAC
  85444. format specification. There is nothing to tune here.
  85445. */
  85446. /** The largest legal metadata type code. */
  85447. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  85448. /** The minimum block size, in samples, permitted by the format. */
  85449. #define FLAC__MIN_BLOCK_SIZE (16u)
  85450. /** The maximum block size, in samples, permitted by the format. */
  85451. #define FLAC__MAX_BLOCK_SIZE (65535u)
  85452. /** The maximum block size, in samples, permitted by the FLAC subset for
  85453. * sample rates up to 48kHz. */
  85454. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  85455. /** The maximum number of channels permitted by the format. */
  85456. #define FLAC__MAX_CHANNELS (8u)
  85457. /** The minimum sample resolution permitted by the format. */
  85458. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  85459. /** The maximum sample resolution permitted by the format. */
  85460. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  85461. /** The maximum sample resolution permitted by libFLAC.
  85462. *
  85463. * \warning
  85464. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  85465. * the reference encoder/decoder is currently limited to 24 bits because
  85466. * of prevalent 32-bit math, so make sure and use this value when
  85467. * appropriate.
  85468. */
  85469. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  85470. /** The maximum sample rate permitted by the format. The value is
  85471. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  85472. * as to why.
  85473. */
  85474. #define FLAC__MAX_SAMPLE_RATE (655350u)
  85475. /** The maximum LPC order permitted by the format. */
  85476. #define FLAC__MAX_LPC_ORDER (32u)
  85477. /** The maximum LPC order permitted by the FLAC subset for sample rates
  85478. * up to 48kHz. */
  85479. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  85480. /** The minimum quantized linear predictor coefficient precision
  85481. * permitted by the format.
  85482. */
  85483. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  85484. /** The maximum quantized linear predictor coefficient precision
  85485. * permitted by the format.
  85486. */
  85487. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  85488. /** The maximum order of the fixed predictors permitted by the format. */
  85489. #define FLAC__MAX_FIXED_ORDER (4u)
  85490. /** The maximum Rice partition order permitted by the format. */
  85491. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  85492. /** The maximum Rice partition order permitted by the FLAC Subset. */
  85493. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  85494. /** The version string of the release, stamped onto the libraries and binaries.
  85495. *
  85496. * \note
  85497. * This does not correspond to the shared library version number, which
  85498. * is used to determine binary compatibility.
  85499. */
  85500. extern FLAC_API const char *FLAC__VERSION_STRING;
  85501. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  85502. * This is a NUL-terminated ASCII string; when inserted into the
  85503. * VORBIS_COMMENT the trailing null is stripped.
  85504. */
  85505. extern FLAC_API const char *FLAC__VENDOR_STRING;
  85506. /** The byte string representation of the beginning of a FLAC stream. */
  85507. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  85508. /** The 32-bit integer big-endian representation of the beginning of
  85509. * a FLAC stream.
  85510. */
  85511. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  85512. /** The length of the FLAC signature in bits. */
  85513. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  85514. /** The length of the FLAC signature in bytes. */
  85515. #define FLAC__STREAM_SYNC_LENGTH (4u)
  85516. /*****************************************************************************
  85517. *
  85518. * Subframe structures
  85519. *
  85520. *****************************************************************************/
  85521. /*****************************************************************************/
  85522. /** An enumeration of the available entropy coding methods. */
  85523. typedef enum {
  85524. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  85525. /**< Residual is coded by partitioning into contexts, each with it's own
  85526. * 4-bit Rice parameter. */
  85527. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  85528. /**< Residual is coded by partitioning into contexts, each with it's own
  85529. * 5-bit Rice parameter. */
  85530. } FLAC__EntropyCodingMethodType;
  85531. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  85532. *
  85533. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  85534. * give the string equivalent. The contents should not be modified.
  85535. */
  85536. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  85537. /** Contents of a Rice partitioned residual
  85538. */
  85539. typedef struct {
  85540. unsigned *parameters;
  85541. /**< The Rice parameters for each context. */
  85542. unsigned *raw_bits;
  85543. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  85544. * partitions and zero for unescaped partitions.
  85545. */
  85546. unsigned capacity_by_order;
  85547. /**< The capacity of the \a parameters and \a raw_bits arrays
  85548. * specified as an order, i.e. the number of array elements
  85549. * allocated is 2 ^ \a capacity_by_order.
  85550. */
  85551. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  85552. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  85553. */
  85554. typedef struct {
  85555. unsigned order;
  85556. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  85557. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  85558. /**< The context's Rice parameters and/or raw bits. */
  85559. } FLAC__EntropyCodingMethod_PartitionedRice;
  85560. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  85561. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  85562. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  85563. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  85564. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  85565. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  85566. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  85567. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  85568. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  85569. */
  85570. typedef struct {
  85571. FLAC__EntropyCodingMethodType type;
  85572. union {
  85573. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  85574. } data;
  85575. } FLAC__EntropyCodingMethod;
  85576. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  85577. /*****************************************************************************/
  85578. /** An enumeration of the available subframe types. */
  85579. typedef enum {
  85580. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  85581. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  85582. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  85583. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  85584. } FLAC__SubframeType;
  85585. /** Maps a FLAC__SubframeType to a C string.
  85586. *
  85587. * Using a FLAC__SubframeType as the index to this array will
  85588. * give the string equivalent. The contents should not be modified.
  85589. */
  85590. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  85591. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  85592. */
  85593. typedef struct {
  85594. FLAC__int32 value; /**< The constant signal value. */
  85595. } FLAC__Subframe_Constant;
  85596. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  85597. */
  85598. typedef struct {
  85599. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  85600. } FLAC__Subframe_Verbatim;
  85601. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  85602. */
  85603. typedef struct {
  85604. FLAC__EntropyCodingMethod entropy_coding_method;
  85605. /**< The residual coding method. */
  85606. unsigned order;
  85607. /**< The polynomial order. */
  85608. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  85609. /**< Warmup samples to prime the predictor, length == order. */
  85610. const FLAC__int32 *residual;
  85611. /**< The residual signal, length == (blocksize minus order) samples. */
  85612. } FLAC__Subframe_Fixed;
  85613. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  85614. */
  85615. typedef struct {
  85616. FLAC__EntropyCodingMethod entropy_coding_method;
  85617. /**< The residual coding method. */
  85618. unsigned order;
  85619. /**< The FIR order. */
  85620. unsigned qlp_coeff_precision;
  85621. /**< Quantized FIR filter coefficient precision in bits. */
  85622. int quantization_level;
  85623. /**< The qlp coeff shift needed. */
  85624. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  85625. /**< FIR filter coefficients. */
  85626. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  85627. /**< Warmup samples to prime the predictor, length == order. */
  85628. const FLAC__int32 *residual;
  85629. /**< The residual signal, length == (blocksize minus order) samples. */
  85630. } FLAC__Subframe_LPC;
  85631. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  85632. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  85633. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  85634. */
  85635. typedef struct {
  85636. FLAC__SubframeType type;
  85637. union {
  85638. FLAC__Subframe_Constant constant;
  85639. FLAC__Subframe_Fixed fixed;
  85640. FLAC__Subframe_LPC lpc;
  85641. FLAC__Subframe_Verbatim verbatim;
  85642. } data;
  85643. unsigned wasted_bits;
  85644. } FLAC__Subframe;
  85645. /** == 1 (bit)
  85646. *
  85647. * This used to be a zero-padding bit (hence the name
  85648. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  85649. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  85650. * to mean something else.
  85651. */
  85652. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  85653. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  85654. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  85655. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  85656. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  85657. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  85658. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  85659. /*****************************************************************************/
  85660. /*****************************************************************************
  85661. *
  85662. * Frame structures
  85663. *
  85664. *****************************************************************************/
  85665. /** An enumeration of the available channel assignments. */
  85666. typedef enum {
  85667. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  85668. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  85669. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  85670. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  85671. } FLAC__ChannelAssignment;
  85672. /** Maps a FLAC__ChannelAssignment to a C string.
  85673. *
  85674. * Using a FLAC__ChannelAssignment as the index to this array will
  85675. * give the string equivalent. The contents should not be modified.
  85676. */
  85677. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  85678. /** An enumeration of the possible frame numbering methods. */
  85679. typedef enum {
  85680. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  85681. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  85682. } FLAC__FrameNumberType;
  85683. /** Maps a FLAC__FrameNumberType to a C string.
  85684. *
  85685. * Using a FLAC__FrameNumberType as the index to this array will
  85686. * give the string equivalent. The contents should not be modified.
  85687. */
  85688. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  85689. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  85690. */
  85691. typedef struct {
  85692. unsigned blocksize;
  85693. /**< The number of samples per subframe. */
  85694. unsigned sample_rate;
  85695. /**< The sample rate in Hz. */
  85696. unsigned channels;
  85697. /**< The number of channels (== number of subframes). */
  85698. FLAC__ChannelAssignment channel_assignment;
  85699. /**< The channel assignment for the frame. */
  85700. unsigned bits_per_sample;
  85701. /**< The sample resolution. */
  85702. FLAC__FrameNumberType number_type;
  85703. /**< The numbering scheme used for the frame. As a convenience, the
  85704. * decoder will always convert a frame number to a sample number because
  85705. * the rules are complex. */
  85706. union {
  85707. FLAC__uint32 frame_number;
  85708. FLAC__uint64 sample_number;
  85709. } number;
  85710. /**< The frame number or sample number of first sample in frame;
  85711. * use the \a number_type value to determine which to use. */
  85712. FLAC__uint8 crc;
  85713. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  85714. * of the raw frame header bytes, meaning everything before the CRC byte
  85715. * including the sync code.
  85716. */
  85717. } FLAC__FrameHeader;
  85718. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  85719. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  85720. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  85721. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  85722. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  85723. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  85724. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  85725. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  85726. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  85727. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  85728. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  85729. */
  85730. typedef struct {
  85731. FLAC__uint16 crc;
  85732. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  85733. * 0) of the bytes before the crc, back to and including the frame header
  85734. * sync code.
  85735. */
  85736. } FLAC__FrameFooter;
  85737. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  85738. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  85739. */
  85740. typedef struct {
  85741. FLAC__FrameHeader header;
  85742. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  85743. FLAC__FrameFooter footer;
  85744. } FLAC__Frame;
  85745. /*****************************************************************************/
  85746. /*****************************************************************************
  85747. *
  85748. * Meta-data structures
  85749. *
  85750. *****************************************************************************/
  85751. /** An enumeration of the available metadata block types. */
  85752. typedef enum {
  85753. FLAC__METADATA_TYPE_STREAMINFO = 0,
  85754. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  85755. FLAC__METADATA_TYPE_PADDING = 1,
  85756. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  85757. FLAC__METADATA_TYPE_APPLICATION = 2,
  85758. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  85759. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  85760. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  85761. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  85762. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  85763. FLAC__METADATA_TYPE_CUESHEET = 5,
  85764. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  85765. FLAC__METADATA_TYPE_PICTURE = 6,
  85766. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  85767. FLAC__METADATA_TYPE_UNDEFINED = 7
  85768. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  85769. } FLAC__MetadataType;
  85770. /** Maps a FLAC__MetadataType to a C string.
  85771. *
  85772. * Using a FLAC__MetadataType as the index to this array will
  85773. * give the string equivalent. The contents should not be modified.
  85774. */
  85775. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  85776. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  85777. */
  85778. typedef struct {
  85779. unsigned min_blocksize, max_blocksize;
  85780. unsigned min_framesize, max_framesize;
  85781. unsigned sample_rate;
  85782. unsigned channels;
  85783. unsigned bits_per_sample;
  85784. FLAC__uint64 total_samples;
  85785. FLAC__byte md5sum[16];
  85786. } FLAC__StreamMetadata_StreamInfo;
  85787. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  85788. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  85789. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  85790. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  85791. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  85792. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  85793. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  85794. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  85795. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  85796. /** The total stream length of the STREAMINFO block in bytes. */
  85797. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  85798. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  85799. */
  85800. typedef struct {
  85801. int dummy;
  85802. /**< Conceptually this is an empty struct since we don't store the
  85803. * padding bytes. Empty structs are not allowed by some C compilers,
  85804. * hence the dummy.
  85805. */
  85806. } FLAC__StreamMetadata_Padding;
  85807. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  85808. */
  85809. typedef struct {
  85810. FLAC__byte id[4];
  85811. FLAC__byte *data;
  85812. } FLAC__StreamMetadata_Application;
  85813. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  85814. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  85815. */
  85816. typedef struct {
  85817. FLAC__uint64 sample_number;
  85818. /**< The sample number of the target frame. */
  85819. FLAC__uint64 stream_offset;
  85820. /**< The offset, in bytes, of the target frame with respect to
  85821. * beginning of the first frame. */
  85822. unsigned frame_samples;
  85823. /**< The number of samples in the target frame. */
  85824. } FLAC__StreamMetadata_SeekPoint;
  85825. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  85826. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  85827. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  85828. /** The total stream length of a seek point in bytes. */
  85829. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  85830. /** The value used in the \a sample_number field of
  85831. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  85832. * point (== 0xffffffffffffffff).
  85833. */
  85834. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  85835. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  85836. *
  85837. * \note From the format specification:
  85838. * - The seek points must be sorted by ascending sample number.
  85839. * - Each seek point's sample number must be the first sample of the
  85840. * target frame.
  85841. * - Each seek point's sample number must be unique within the table.
  85842. * - Existence of a SEEKTABLE block implies a correct setting of
  85843. * total_samples in the stream_info block.
  85844. * - Behavior is undefined when more than one SEEKTABLE block is
  85845. * present in a stream.
  85846. */
  85847. typedef struct {
  85848. unsigned num_points;
  85849. FLAC__StreamMetadata_SeekPoint *points;
  85850. } FLAC__StreamMetadata_SeekTable;
  85851. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  85852. *
  85853. * For convenience, the APIs maintain a trailing NUL character at the end of
  85854. * \a entry which is not counted toward \a length, i.e.
  85855. * \code strlen(entry) == length \endcode
  85856. */
  85857. typedef struct {
  85858. FLAC__uint32 length;
  85859. FLAC__byte *entry;
  85860. } FLAC__StreamMetadata_VorbisComment_Entry;
  85861. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  85862. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  85863. */
  85864. typedef struct {
  85865. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  85866. FLAC__uint32 num_comments;
  85867. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  85868. } FLAC__StreamMetadata_VorbisComment;
  85869. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  85870. /** FLAC CUESHEET track index structure. (See the
  85871. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  85872. * the full description of each field.)
  85873. */
  85874. typedef struct {
  85875. FLAC__uint64 offset;
  85876. /**< Offset in samples, relative to the track offset, of the index
  85877. * point.
  85878. */
  85879. FLAC__byte number;
  85880. /**< The index point number. */
  85881. } FLAC__StreamMetadata_CueSheet_Index;
  85882. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  85883. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  85884. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  85885. /** FLAC CUESHEET track structure. (See the
  85886. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  85887. * the full description of each field.)
  85888. */
  85889. typedef struct {
  85890. FLAC__uint64 offset;
  85891. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  85892. FLAC__byte number;
  85893. /**< The track number. */
  85894. char isrc[13];
  85895. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  85896. unsigned type:1;
  85897. /**< The track type: 0 for audio, 1 for non-audio. */
  85898. unsigned pre_emphasis:1;
  85899. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  85900. FLAC__byte num_indices;
  85901. /**< The number of track index points. */
  85902. FLAC__StreamMetadata_CueSheet_Index *indices;
  85903. /**< NULL if num_indices == 0, else pointer to array of index points. */
  85904. } FLAC__StreamMetadata_CueSheet_Track;
  85905. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  85906. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  85907. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  85908. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  85909. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  85910. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  85911. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  85912. /** FLAC CUESHEET structure. (See the
  85913. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  85914. * for the full description of each field.)
  85915. */
  85916. typedef struct {
  85917. char media_catalog_number[129];
  85918. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  85919. * general, the media catalog number may be 0 to 128 bytes long; any
  85920. * unused characters should be right-padded with NUL characters.
  85921. */
  85922. FLAC__uint64 lead_in;
  85923. /**< The number of lead-in samples. */
  85924. FLAC__bool is_cd;
  85925. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  85926. unsigned num_tracks;
  85927. /**< The number of tracks. */
  85928. FLAC__StreamMetadata_CueSheet_Track *tracks;
  85929. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  85930. } FLAC__StreamMetadata_CueSheet;
  85931. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  85932. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  85933. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  85934. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  85935. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  85936. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  85937. typedef enum {
  85938. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  85939. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  85940. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  85941. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  85942. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  85943. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  85944. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  85945. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  85946. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  85947. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  85948. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  85949. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  85950. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  85951. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  85952. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  85953. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  85954. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  85955. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  85956. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  85957. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  85958. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  85959. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  85960. } FLAC__StreamMetadata_Picture_Type;
  85961. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  85962. *
  85963. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  85964. * will give the string equivalent. The contents should not be
  85965. * modified.
  85966. */
  85967. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  85968. /** FLAC PICTURE structure. (See the
  85969. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  85970. * for the full description of each field.)
  85971. */
  85972. typedef struct {
  85973. FLAC__StreamMetadata_Picture_Type type;
  85974. /**< The kind of picture stored. */
  85975. char *mime_type;
  85976. /**< Picture data's MIME type, in ASCII printable characters
  85977. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  85978. * use picture data of MIME type \c image/jpeg or \c image/png. A
  85979. * MIME type of '-->' is also allowed, in which case the picture
  85980. * data should be a complete URL. In file storage, the MIME type is
  85981. * stored as a 32-bit length followed by the ASCII string with no NUL
  85982. * terminator, but is converted to a plain C string in this structure
  85983. * for convenience.
  85984. */
  85985. FLAC__byte *description;
  85986. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  85987. * the description is stored as a 32-bit length followed by the UTF-8
  85988. * string with no NUL terminator, but is converted to a plain C string
  85989. * in this structure for convenience.
  85990. */
  85991. FLAC__uint32 width;
  85992. /**< Picture's width in pixels. */
  85993. FLAC__uint32 height;
  85994. /**< Picture's height in pixels. */
  85995. FLAC__uint32 depth;
  85996. /**< Picture's color depth in bits-per-pixel. */
  85997. FLAC__uint32 colors;
  85998. /**< For indexed palettes (like GIF), picture's number of colors (the
  85999. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86000. */
  86001. FLAC__uint32 data_length;
  86002. /**< Length of binary picture data in bytes. */
  86003. FLAC__byte *data;
  86004. /**< Binary picture data. */
  86005. } FLAC__StreamMetadata_Picture;
  86006. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86007. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86008. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86009. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86010. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86011. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86012. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86013. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86014. /** Structure that is used when a metadata block of unknown type is loaded.
  86015. * The contents are opaque. The structure is used only internally to
  86016. * correctly handle unknown metadata.
  86017. */
  86018. typedef struct {
  86019. FLAC__byte *data;
  86020. } FLAC__StreamMetadata_Unknown;
  86021. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86022. */
  86023. typedef struct {
  86024. FLAC__MetadataType type;
  86025. /**< The type of the metadata block; used determine which member of the
  86026. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86027. * then \a data.unknown must be used. */
  86028. FLAC__bool is_last;
  86029. /**< \c true if this metadata block is the last, else \a false */
  86030. unsigned length;
  86031. /**< Length, in bytes, of the block data as it appears in the stream. */
  86032. union {
  86033. FLAC__StreamMetadata_StreamInfo stream_info;
  86034. FLAC__StreamMetadata_Padding padding;
  86035. FLAC__StreamMetadata_Application application;
  86036. FLAC__StreamMetadata_SeekTable seek_table;
  86037. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86038. FLAC__StreamMetadata_CueSheet cue_sheet;
  86039. FLAC__StreamMetadata_Picture picture;
  86040. FLAC__StreamMetadata_Unknown unknown;
  86041. } data;
  86042. /**< Polymorphic block data; use the \a type value to determine which
  86043. * to use. */
  86044. } FLAC__StreamMetadata;
  86045. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86046. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86047. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86048. /** The total stream length of a metadata block header in bytes. */
  86049. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86050. /*****************************************************************************/
  86051. /*****************************************************************************
  86052. *
  86053. * Utility functions
  86054. *
  86055. *****************************************************************************/
  86056. /** Tests that a sample rate is valid for FLAC.
  86057. *
  86058. * \param sample_rate The sample rate to test for compliance.
  86059. * \retval FLAC__bool
  86060. * \c true if the given sample rate conforms to the specification, else
  86061. * \c false.
  86062. */
  86063. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86064. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86065. * for valid sample rates are slightly more complex since the rate has to
  86066. * be expressible completely in the frame header.
  86067. *
  86068. * \param sample_rate The sample rate to test for compliance.
  86069. * \retval FLAC__bool
  86070. * \c true if the given sample rate conforms to the specification for the
  86071. * subset, else \c false.
  86072. */
  86073. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86074. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86075. * comment specification.
  86076. *
  86077. * Vorbis comment names must be composed only of characters from
  86078. * [0x20-0x3C,0x3E-0x7D].
  86079. *
  86080. * \param name A NUL-terminated string to be checked.
  86081. * \assert
  86082. * \code name != NULL \endcode
  86083. * \retval FLAC__bool
  86084. * \c false if entry name is illegal, else \c true.
  86085. */
  86086. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86087. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86088. * comment specification.
  86089. *
  86090. * Vorbis comment values must be valid UTF-8 sequences.
  86091. *
  86092. * \param value A string to be checked.
  86093. * \param length A the length of \a value in bytes. May be
  86094. * \c (unsigned)(-1) to indicate that \a value is a plain
  86095. * UTF-8 NUL-terminated string.
  86096. * \assert
  86097. * \code value != NULL \endcode
  86098. * \retval FLAC__bool
  86099. * \c false if entry name is illegal, else \c true.
  86100. */
  86101. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86102. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86103. * comment specification.
  86104. *
  86105. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  86106. * 'value' must be legal according to
  86107. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  86108. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  86109. *
  86110. * \param entry An entry to be checked.
  86111. * \param length The length of \a entry in bytes.
  86112. * \assert
  86113. * \code value != NULL \endcode
  86114. * \retval FLAC__bool
  86115. * \c false if entry name is illegal, else \c true.
  86116. */
  86117. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  86118. /** Check a seek table to see if it conforms to the FLAC specification.
  86119. * See the format specification for limits on the contents of the
  86120. * seek table.
  86121. *
  86122. * \param seek_table A pointer to a seek table to be checked.
  86123. * \assert
  86124. * \code seek_table != NULL \endcode
  86125. * \retval FLAC__bool
  86126. * \c false if seek table is illegal, else \c true.
  86127. */
  86128. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  86129. /** Sort a seek table's seek points according to the format specification.
  86130. * This includes a "unique-ification" step to remove duplicates, i.e.
  86131. * seek points with identical \a sample_number values. Duplicate seek
  86132. * points are converted into placeholder points and sorted to the end of
  86133. * the table.
  86134. *
  86135. * \param seek_table A pointer to a seek table to be sorted.
  86136. * \assert
  86137. * \code seek_table != NULL \endcode
  86138. * \retval unsigned
  86139. * The number of duplicate seek points converted into placeholders.
  86140. */
  86141. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  86142. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86143. * See the format specification for limits on the contents of the
  86144. * cue sheet.
  86145. *
  86146. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  86147. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86148. * stringent requirements for a CD-DA (audio) disc.
  86149. * \param violation Address of a pointer to a string. If there is a
  86150. * violation, a pointer to a string explanation of the
  86151. * violation will be returned here. \a violation may be
  86152. * \c NULL if you don't need the returned string. Do not
  86153. * free the returned string; it will always point to static
  86154. * data.
  86155. * \assert
  86156. * \code cue_sheet != NULL \endcode
  86157. * \retval FLAC__bool
  86158. * \c false if cue sheet is illegal, else \c true.
  86159. */
  86160. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  86161. /** Check picture data to see if it conforms to the FLAC specification.
  86162. * See the format specification for limits on the contents of the
  86163. * PICTURE block.
  86164. *
  86165. * \param picture A pointer to existing picture data to be checked.
  86166. * \param violation Address of a pointer to a string. If there is a
  86167. * violation, a pointer to a string explanation of the
  86168. * violation will be returned here. \a violation may be
  86169. * \c NULL if you don't need the returned string. Do not
  86170. * free the returned string; it will always point to static
  86171. * data.
  86172. * \assert
  86173. * \code picture != NULL \endcode
  86174. * \retval FLAC__bool
  86175. * \c false if picture data is illegal, else \c true.
  86176. */
  86177. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  86178. /* \} */
  86179. #ifdef __cplusplus
  86180. }
  86181. #endif
  86182. #endif
  86183. /*** End of inlined file: format.h ***/
  86184. /*** Start of inlined file: metadata.h ***/
  86185. #ifndef FLAC__METADATA_H
  86186. #define FLAC__METADATA_H
  86187. #include <sys/types.h> /* for off_t */
  86188. /* --------------------------------------------------------------------
  86189. (For an example of how all these routines are used, see the source
  86190. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  86191. metaflac in src/metaflac/)
  86192. ------------------------------------------------------------------*/
  86193. /** \file include/FLAC/metadata.h
  86194. *
  86195. * \brief
  86196. * This module provides functions for creating and manipulating FLAC
  86197. * metadata blocks in memory, and three progressively more powerful
  86198. * interfaces for traversing and editing metadata in FLAC files.
  86199. *
  86200. * See the detailed documentation for each interface in the
  86201. * \link flac_metadata metadata \endlink module.
  86202. */
  86203. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  86204. * \ingroup flac
  86205. *
  86206. * \brief
  86207. * This module provides functions for creating and manipulating FLAC
  86208. * metadata blocks in memory, and three progressively more powerful
  86209. * interfaces for traversing and editing metadata in native FLAC files.
  86210. * Note that currently only the Chain interface (level 2) supports Ogg
  86211. * FLAC files, and it is read-only i.e. no writing back changed
  86212. * metadata to file.
  86213. *
  86214. * There are three metadata interfaces of increasing complexity:
  86215. *
  86216. * Level 0:
  86217. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  86218. * PICTURE blocks.
  86219. *
  86220. * Level 1:
  86221. * Read-write access to all metadata blocks. This level is write-
  86222. * efficient in most cases (more on this below), and uses less memory
  86223. * than level 2.
  86224. *
  86225. * Level 2:
  86226. * Read-write access to all metadata blocks. This level is write-
  86227. * efficient in all cases, but uses more memory since all metadata for
  86228. * the whole file is read into memory and manipulated before writing
  86229. * out again.
  86230. *
  86231. * What do we mean by efficient? Since FLAC metadata appears at the
  86232. * beginning of the file, when writing metadata back to a FLAC file
  86233. * it is possible to grow or shrink the metadata such that the entire
  86234. * file must be rewritten. However, if the size remains the same during
  86235. * changes or PADDING blocks are utilized, only the metadata needs to be
  86236. * overwritten, which is much faster.
  86237. *
  86238. * Efficient means the whole file is rewritten at most one time, and only
  86239. * when necessary. Level 1 is not efficient only in the case that you
  86240. * cause more than one metadata block to grow or shrink beyond what can
  86241. * be accomodated by padding. In this case you should probably use level
  86242. * 2, which allows you to edit all the metadata for a file in memory and
  86243. * write it out all at once.
  86244. *
  86245. * All levels know how to skip over and not disturb an ID3v2 tag at the
  86246. * front of the file.
  86247. *
  86248. * All levels access files via their filenames. In addition, level 2
  86249. * has additional alternative read and write functions that take an I/O
  86250. * handle and callbacks, for situations where access by filename is not
  86251. * possible.
  86252. *
  86253. * In addition to the three interfaces, this module defines functions for
  86254. * creating and manipulating various metadata objects in memory. As we see
  86255. * from the Format module, FLAC metadata blocks in memory are very primitive
  86256. * structures for storing information in an efficient way. Reading
  86257. * information from the structures is easy but creating or modifying them
  86258. * directly is more complex. The metadata object routines here facilitate
  86259. * this by taking care of the consistency and memory management drudgery.
  86260. *
  86261. * Unless you will be using the level 1 or 2 interfaces to modify existing
  86262. * metadata however, you will not probably not need these.
  86263. *
  86264. * From a dependency standpoint, none of the encoders or decoders require
  86265. * the metadata module. This is so that embedded users can strip out the
  86266. * metadata module from libFLAC to reduce the size and complexity.
  86267. */
  86268. #ifdef __cplusplus
  86269. extern "C" {
  86270. #endif
  86271. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  86272. * \ingroup flac_metadata
  86273. *
  86274. * \brief
  86275. * The level 0 interface consists of individual routines to read the
  86276. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  86277. * only a filename.
  86278. *
  86279. * They try to skip any ID3v2 tag at the head of the file.
  86280. *
  86281. * \{
  86282. */
  86283. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  86284. * will try to skip any ID3v2 tag at the head of the file.
  86285. *
  86286. * \param filename The path to the FLAC file to read.
  86287. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  86288. * FLAC__StreamMetadata is a simple structure with no
  86289. * memory allocation involved, you pass the address of
  86290. * an existing structure. It need not be initialized.
  86291. * \assert
  86292. * \code filename != NULL \endcode
  86293. * \code streaminfo != NULL \endcode
  86294. * \retval FLAC__bool
  86295. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  86296. * \c false if there was a memory allocation error, a file decoder error,
  86297. * or the file contained no STREAMINFO block. (A memory allocation error
  86298. * is possible because this function must set up a file decoder.)
  86299. */
  86300. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  86301. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  86302. * function will try to skip any ID3v2 tag at the head of the file.
  86303. *
  86304. * \param filename The path to the FLAC file to read.
  86305. * \param tags The address where the returned pointer will be
  86306. * stored. The \a tags object must be deleted by
  86307. * the caller using FLAC__metadata_object_delete().
  86308. * \assert
  86309. * \code filename != NULL \endcode
  86310. * \code tags != NULL \endcode
  86311. * \retval FLAC__bool
  86312. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  86313. * and \a *tags will be set to the address of the metadata structure.
  86314. * Returns \c false if there was a memory allocation error, a file
  86315. * decoder error, or the file contained no VORBIS_COMMENT block, and
  86316. * \a *tags will be set to \c NULL.
  86317. */
  86318. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  86319. /** Read the CUESHEET metadata block of the given FLAC file. This
  86320. * function will try to skip any ID3v2 tag at the head of the file.
  86321. *
  86322. * \param filename The path to the FLAC file to read.
  86323. * \param cuesheet The address where the returned pointer will be
  86324. * stored. The \a cuesheet object must be deleted by
  86325. * the caller using FLAC__metadata_object_delete().
  86326. * \assert
  86327. * \code filename != NULL \endcode
  86328. * \code cuesheet != NULL \endcode
  86329. * \retval FLAC__bool
  86330. * \c true if a valid CUESHEET block was read from \a filename,
  86331. * and \a *cuesheet will be set to the address of the metadata
  86332. * structure. Returns \c false if there was a memory allocation
  86333. * error, a file decoder error, or the file contained no CUESHEET
  86334. * block, and \a *cuesheet will be set to \c NULL.
  86335. */
  86336. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  86337. /** Read a PICTURE metadata block of the given FLAC file. This
  86338. * function will try to skip any ID3v2 tag at the head of the file.
  86339. * Since there can be more than one PICTURE block in a file, this
  86340. * function takes a number of parameters that act as constraints to
  86341. * the search. The PICTURE block with the largest area matching all
  86342. * the constraints will be returned, or \a *picture will be set to
  86343. * \c NULL if there was no such block.
  86344. *
  86345. * \param filename The path to the FLAC file to read.
  86346. * \param picture The address where the returned pointer will be
  86347. * stored. The \a picture object must be deleted by
  86348. * the caller using FLAC__metadata_object_delete().
  86349. * \param type The desired picture type. Use \c -1 to mean
  86350. * "any type".
  86351. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  86352. * string will be matched exactly. Use \c NULL to
  86353. * mean "any MIME type".
  86354. * \param description The desired description. The string will be
  86355. * matched exactly. Use \c NULL to mean "any
  86356. * description".
  86357. * \param max_width The maximum width in pixels desired. Use
  86358. * \c (unsigned)(-1) to mean "any width".
  86359. * \param max_height The maximum height in pixels desired. Use
  86360. * \c (unsigned)(-1) to mean "any height".
  86361. * \param max_depth The maximum color depth in bits-per-pixel desired.
  86362. * Use \c (unsigned)(-1) to mean "any depth".
  86363. * \param max_colors The maximum number of colors desired. Use
  86364. * \c (unsigned)(-1) to mean "any number of colors".
  86365. * \assert
  86366. * \code filename != NULL \endcode
  86367. * \code picture != NULL \endcode
  86368. * \retval FLAC__bool
  86369. * \c true if a valid PICTURE block was read from \a filename,
  86370. * and \a *picture will be set to the address of the metadata
  86371. * structure. Returns \c false if there was a memory allocation
  86372. * error, a file decoder error, or the file contained no PICTURE
  86373. * block, and \a *picture will be set to \c NULL.
  86374. */
  86375. FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors);
  86376. /* \} */
  86377. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  86378. * \ingroup flac_metadata
  86379. *
  86380. * \brief
  86381. * The level 1 interface provides read-write access to FLAC file metadata and
  86382. * operates directly on the FLAC file.
  86383. *
  86384. * The general usage of this interface is:
  86385. *
  86386. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  86387. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  86388. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  86389. * see if the file is writable, or only read access is allowed.
  86390. * - Use FLAC__metadata_simple_iterator_next() and
  86391. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  86392. * This is does not read the actual blocks themselves.
  86393. * FLAC__metadata_simple_iterator_next() is relatively fast.
  86394. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  86395. * forward from the front of the file.
  86396. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  86397. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  86398. * the current iterator position. The returned object is yours to modify
  86399. * and free.
  86400. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  86401. * back. You must have write permission to the original file. Make sure to
  86402. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  86403. * below.
  86404. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  86405. * Use the object creation functions from
  86406. * \link flac_metadata_object here \endlink to generate new objects.
  86407. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  86408. * currently referred to by the iterator, or replace it with padding.
  86409. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  86410. * finished.
  86411. *
  86412. * \note
  86413. * The FLAC file remains open the whole time between
  86414. * FLAC__metadata_simple_iterator_init() and
  86415. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  86416. * the file during this time.
  86417. *
  86418. * \note
  86419. * Do not modify the \a is_last, \a length, or \a type fields of returned
  86420. * FLAC__StreamMetadata objects. These are managed automatically.
  86421. *
  86422. * \note
  86423. * If any of the modification functions
  86424. * (FLAC__metadata_simple_iterator_set_block(),
  86425. * FLAC__metadata_simple_iterator_delete_block(),
  86426. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  86427. * you should delete the iterator as it may no longer be valid.
  86428. *
  86429. * \{
  86430. */
  86431. struct FLAC__Metadata_SimpleIterator;
  86432. /** The opaque structure definition for the level 1 iterator type.
  86433. * See the
  86434. * \link flac_metadata_level1 metadata level 1 module \endlink
  86435. * for a detailed description.
  86436. */
  86437. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  86438. /** Status type for FLAC__Metadata_SimpleIterator.
  86439. *
  86440. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  86441. */
  86442. typedef enum {
  86443. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  86444. /**< The iterator is in the normal OK state */
  86445. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  86446. /**< The data passed into a function violated the function's usage criteria */
  86447. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  86448. /**< The iterator could not open the target file */
  86449. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  86450. /**< The iterator could not find the FLAC signature at the start of the file */
  86451. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  86452. /**< The iterator tried to write to a file that was not writable */
  86453. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  86454. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  86455. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  86456. /**< The iterator encountered an error while reading the FLAC file */
  86457. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  86458. /**< The iterator encountered an error while seeking in the FLAC file */
  86459. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  86460. /**< The iterator encountered an error while writing the FLAC file */
  86461. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  86462. /**< The iterator encountered an error renaming the FLAC file */
  86463. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  86464. /**< The iterator encountered an error removing the temporary file */
  86465. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  86466. /**< Memory allocation failed */
  86467. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  86468. /**< The caller violated an assertion or an unexpected error occurred */
  86469. } FLAC__Metadata_SimpleIteratorStatus;
  86470. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  86471. *
  86472. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  86473. * will give the string equivalent. The contents should not be modified.
  86474. */
  86475. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  86476. /** Create a new iterator instance.
  86477. *
  86478. * \retval FLAC__Metadata_SimpleIterator*
  86479. * \c NULL if there was an error allocating memory, else the new instance.
  86480. */
  86481. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  86482. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  86483. *
  86484. * \param iterator A pointer to an existing iterator.
  86485. * \assert
  86486. * \code iterator != NULL \endcode
  86487. */
  86488. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  86489. /** Get the current status of the iterator. Call this after a function
  86490. * returns \c false to get the reason for the error. Also resets the status
  86491. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  86492. *
  86493. * \param iterator A pointer to an existing iterator.
  86494. * \assert
  86495. * \code iterator != NULL \endcode
  86496. * \retval FLAC__Metadata_SimpleIteratorStatus
  86497. * The current status of the iterator.
  86498. */
  86499. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  86500. /** Initialize the iterator to point to the first metadata block in the
  86501. * given FLAC file.
  86502. *
  86503. * \param iterator A pointer to an existing iterator.
  86504. * \param filename The path to the FLAC file.
  86505. * \param read_only If \c true, the FLAC file will be opened
  86506. * in read-only mode; if \c false, the FLAC
  86507. * file will be opened for edit even if no
  86508. * edits are performed.
  86509. * \param preserve_file_stats If \c true, the owner and modification
  86510. * time will be preserved even if the FLAC
  86511. * file is written to.
  86512. * \assert
  86513. * \code iterator != NULL \endcode
  86514. * \code filename != NULL \endcode
  86515. * \retval FLAC__bool
  86516. * \c false if a memory allocation error occurs, the file can't be
  86517. * opened, or another error occurs, else \c true.
  86518. */
  86519. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats);
  86520. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  86521. * FLAC__metadata_simple_iterator_set_block() and
  86522. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  86523. *
  86524. * \param iterator A pointer to an existing iterator.
  86525. * \assert
  86526. * \code iterator != NULL \endcode
  86527. * \retval FLAC__bool
  86528. * See above.
  86529. */
  86530. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  86531. /** Moves the iterator forward one metadata block, returning \c false if
  86532. * already at the end.
  86533. *
  86534. * \param iterator A pointer to an existing initialized iterator.
  86535. * \assert
  86536. * \code iterator != NULL \endcode
  86537. * \a iterator has been successfully initialized with
  86538. * FLAC__metadata_simple_iterator_init()
  86539. * \retval FLAC__bool
  86540. * \c false if already at the last metadata block of the chain, else
  86541. * \c true.
  86542. */
  86543. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  86544. /** Moves the iterator backward one metadata block, returning \c false if
  86545. * already at the beginning.
  86546. *
  86547. * \param iterator A pointer to an existing initialized iterator.
  86548. * \assert
  86549. * \code iterator != NULL \endcode
  86550. * \a iterator has been successfully initialized with
  86551. * FLAC__metadata_simple_iterator_init()
  86552. * \retval FLAC__bool
  86553. * \c false if already at the first metadata block of the chain, else
  86554. * \c true.
  86555. */
  86556. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  86557. /** Returns a flag telling if the current metadata block is the last.
  86558. *
  86559. * \param iterator A pointer to an existing initialized iterator.
  86560. * \assert
  86561. * \code iterator != NULL \endcode
  86562. * \a iterator has been successfully initialized with
  86563. * FLAC__metadata_simple_iterator_init()
  86564. * \retval FLAC__bool
  86565. * \c true if the current metadata block is the last in the file,
  86566. * else \c false.
  86567. */
  86568. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  86569. /** Get the offset of the metadata block at the current position. This
  86570. * avoids reading the actual block data which can save time for large
  86571. * blocks.
  86572. *
  86573. * \param iterator A pointer to an existing initialized iterator.
  86574. * \assert
  86575. * \code iterator != NULL \endcode
  86576. * \a iterator has been successfully initialized with
  86577. * FLAC__metadata_simple_iterator_init()
  86578. * \retval off_t
  86579. * The offset of the metadata block at the current iterator position.
  86580. * This is the byte offset relative to the beginning of the file of
  86581. * the current metadata block's header.
  86582. */
  86583. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  86584. /** Get the type of the metadata block at the current position. This
  86585. * avoids reading the actual block data which can save time for large
  86586. * blocks.
  86587. *
  86588. * \param iterator A pointer to an existing initialized iterator.
  86589. * \assert
  86590. * \code iterator != NULL \endcode
  86591. * \a iterator has been successfully initialized with
  86592. * FLAC__metadata_simple_iterator_init()
  86593. * \retval FLAC__MetadataType
  86594. * The type of the metadata block at the current iterator position.
  86595. */
  86596. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  86597. /** Get the length of the metadata block at the current position. This
  86598. * avoids reading the actual block data which can save time for large
  86599. * blocks.
  86600. *
  86601. * \param iterator A pointer to an existing initialized iterator.
  86602. * \assert
  86603. * \code iterator != NULL \endcode
  86604. * \a iterator has been successfully initialized with
  86605. * FLAC__metadata_simple_iterator_init()
  86606. * \retval unsigned
  86607. * The length of the metadata block at the current iterator position.
  86608. * The is same length as that in the
  86609. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  86610. * i.e. the length of the metadata body that follows the header.
  86611. */
  86612. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  86613. /** Get the application ID of the \c APPLICATION block at the current
  86614. * position. This avoids reading the actual block data which can save
  86615. * time for large blocks.
  86616. *
  86617. * \param iterator A pointer to an existing initialized iterator.
  86618. * \param id A pointer to a buffer of at least \c 4 bytes where
  86619. * the ID will be stored.
  86620. * \assert
  86621. * \code iterator != NULL \endcode
  86622. * \code id != NULL \endcode
  86623. * \a iterator has been successfully initialized with
  86624. * FLAC__metadata_simple_iterator_init()
  86625. * \retval FLAC__bool
  86626. * \c true if the ID was successfully read, else \c false, in which
  86627. * case you should check FLAC__metadata_simple_iterator_status() to
  86628. * find out why. If the status is
  86629. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  86630. * current metadata block is not an \c APPLICATION block. Otherwise
  86631. * if the status is
  86632. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  86633. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  86634. * occurred and the iterator can no longer be used.
  86635. */
  86636. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  86637. /** Get the metadata block at the current position. You can modify the
  86638. * block but must use FLAC__metadata_simple_iterator_set_block() to
  86639. * write it back to the FLAC file.
  86640. *
  86641. * You must call FLAC__metadata_object_delete() on the returned object
  86642. * when you are finished with it.
  86643. *
  86644. * \param iterator A pointer to an existing initialized iterator.
  86645. * \assert
  86646. * \code iterator != NULL \endcode
  86647. * \a iterator has been successfully initialized with
  86648. * FLAC__metadata_simple_iterator_init()
  86649. * \retval FLAC__StreamMetadata*
  86650. * The current metadata block, or \c NULL if there was a memory
  86651. * allocation error.
  86652. */
  86653. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  86654. /** Write a block back to the FLAC file. This function tries to be
  86655. * as efficient as possible; how the block is actually written is
  86656. * shown by the following:
  86657. *
  86658. * Existing block is a STREAMINFO block and the new block is a
  86659. * STREAMINFO block: the new block is written in place. Make sure
  86660. * you know what you're doing when changing the values of a
  86661. * STREAMINFO block.
  86662. *
  86663. * Existing block is a STREAMINFO block and the new block is a
  86664. * not a STREAMINFO block: this is an error since the first block
  86665. * must be a STREAMINFO block. Returns \c false without altering the
  86666. * file.
  86667. *
  86668. * Existing block is not a STREAMINFO block and the new block is a
  86669. * STREAMINFO block: this is an error since there may be only one
  86670. * STREAMINFO block. Returns \c false without altering the file.
  86671. *
  86672. * Existing block and new block are the same length: the existing
  86673. * block will be replaced by the new block, written in place.
  86674. *
  86675. * Existing block is longer than new block: if use_padding is \c true,
  86676. * the existing block will be overwritten in place with the new
  86677. * block followed by a PADDING block, if possible, to make the total
  86678. * size the same as the existing block. Remember that a padding
  86679. * block requires at least four bytes so if the difference in size
  86680. * between the new block and existing block is less than that, the
  86681. * entire file will have to be rewritten, using the new block's
  86682. * exact size. If use_padding is \c false, the entire file will be
  86683. * rewritten, replacing the existing block by the new block.
  86684. *
  86685. * Existing block is shorter than new block: if use_padding is \c true,
  86686. * the function will try and expand the new block into the following
  86687. * PADDING block, if it exists and doing so won't shrink the PADDING
  86688. * block to less than 4 bytes. If there is no following PADDING
  86689. * block, or it will shrink to less than 4 bytes, or use_padding is
  86690. * \c false, the entire file is rewritten, replacing the existing block
  86691. * with the new block. Note that in this case any following PADDING
  86692. * block is preserved as is.
  86693. *
  86694. * After writing the block, the iterator will remain in the same
  86695. * place, i.e. pointing to the new block.
  86696. *
  86697. * \param iterator A pointer to an existing initialized iterator.
  86698. * \param block The block to set.
  86699. * \param use_padding See above.
  86700. * \assert
  86701. * \code iterator != NULL \endcode
  86702. * \a iterator has been successfully initialized with
  86703. * FLAC__metadata_simple_iterator_init()
  86704. * \code block != NULL \endcode
  86705. * \retval FLAC__bool
  86706. * \c true if successful, else \c false.
  86707. */
  86708. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  86709. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  86710. * except that instead of writing over an existing block, it appends
  86711. * a block after the existing block. \a use_padding is again used to
  86712. * tell the function to try an expand into following padding in an
  86713. * attempt to avoid rewriting the entire file.
  86714. *
  86715. * This function will fail and return \c false if given a STREAMINFO
  86716. * block.
  86717. *
  86718. * After writing the block, the iterator will be pointing to the
  86719. * new block.
  86720. *
  86721. * \param iterator A pointer to an existing initialized iterator.
  86722. * \param block The block to set.
  86723. * \param use_padding See above.
  86724. * \assert
  86725. * \code iterator != NULL \endcode
  86726. * \a iterator has been successfully initialized with
  86727. * FLAC__metadata_simple_iterator_init()
  86728. * \code block != NULL \endcode
  86729. * \retval FLAC__bool
  86730. * \c true if successful, else \c false.
  86731. */
  86732. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  86733. /** Deletes the block at the current position. This will cause the
  86734. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  86735. * in which case the block will be replaced by an equal-sized PADDING
  86736. * block. The iterator will be left pointing to the block before the
  86737. * one just deleted.
  86738. *
  86739. * You may not delete the STREAMINFO block.
  86740. *
  86741. * \param iterator A pointer to an existing initialized iterator.
  86742. * \param use_padding See above.
  86743. * \assert
  86744. * \code iterator != NULL \endcode
  86745. * \a iterator has been successfully initialized with
  86746. * FLAC__metadata_simple_iterator_init()
  86747. * \retval FLAC__bool
  86748. * \c true if successful, else \c false.
  86749. */
  86750. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  86751. /* \} */
  86752. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  86753. * \ingroup flac_metadata
  86754. *
  86755. * \brief
  86756. * The level 2 interface provides read-write access to FLAC file metadata;
  86757. * all metadata is read into memory, operated on in memory, and then written
  86758. * to file, which is more efficient than level 1 when editing multiple blocks.
  86759. *
  86760. * Currently Ogg FLAC is supported for read only, via
  86761. * FLAC__metadata_chain_read_ogg() but a subsequent
  86762. * FLAC__metadata_chain_write() will fail.
  86763. *
  86764. * The general usage of this interface is:
  86765. *
  86766. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  86767. * linked list of FLAC metadata blocks.
  86768. * - Read all metadata into the the chain from a FLAC file using
  86769. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  86770. * check the status.
  86771. * - Optionally, consolidate the padding using
  86772. * FLAC__metadata_chain_merge_padding() or
  86773. * FLAC__metadata_chain_sort_padding().
  86774. * - Create a new iterator using FLAC__metadata_iterator_new()
  86775. * - Initialize the iterator to point to the first element in the chain
  86776. * using FLAC__metadata_iterator_init()
  86777. * - Traverse the chain using FLAC__metadata_iterator_next and
  86778. * FLAC__metadata_iterator_prev().
  86779. * - Get a block for reading or modification using
  86780. * FLAC__metadata_iterator_get_block(). The pointer to the object
  86781. * inside the chain is returned, so the block is yours to modify.
  86782. * Changes will be reflected in the FLAC file when you write the
  86783. * chain. You can also add and delete blocks (see functions below).
  86784. * - When done, write out the chain using FLAC__metadata_chain_write().
  86785. * Make sure to read the whole comment to the function below.
  86786. * - Delete the chain using FLAC__metadata_chain_delete().
  86787. *
  86788. * \note
  86789. * Even though the FLAC file is not open while the chain is being
  86790. * manipulated, you must not alter the file externally during
  86791. * this time. The chain assumes the FLAC file will not change
  86792. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  86793. * and FLAC__metadata_chain_write().
  86794. *
  86795. * \note
  86796. * Do not modify the is_last, length, or type fields of returned
  86797. * FLAC__StreamMetadata objects. These are managed automatically.
  86798. *
  86799. * \note
  86800. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  86801. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  86802. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  86803. * become owned by the chain and they will be deleted when the chain is
  86804. * deleted.
  86805. *
  86806. * \{
  86807. */
  86808. struct FLAC__Metadata_Chain;
  86809. /** The opaque structure definition for the level 2 chain type.
  86810. */
  86811. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  86812. struct FLAC__Metadata_Iterator;
  86813. /** The opaque structure definition for the level 2 iterator type.
  86814. */
  86815. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  86816. typedef enum {
  86817. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  86818. /**< The chain is in the normal OK state */
  86819. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  86820. /**< The data passed into a function violated the function's usage criteria */
  86821. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  86822. /**< The chain could not open the target file */
  86823. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  86824. /**< The chain could not find the FLAC signature at the start of the file */
  86825. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  86826. /**< The chain tried to write to a file that was not writable */
  86827. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  86828. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  86829. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  86830. /**< The chain encountered an error while reading the FLAC file */
  86831. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  86832. /**< The chain encountered an error while seeking in the FLAC file */
  86833. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  86834. /**< The chain encountered an error while writing the FLAC file */
  86835. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  86836. /**< The chain encountered an error renaming the FLAC file */
  86837. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  86838. /**< The chain encountered an error removing the temporary file */
  86839. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  86840. /**< Memory allocation failed */
  86841. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  86842. /**< The caller violated an assertion or an unexpected error occurred */
  86843. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  86844. /**< One or more of the required callbacks was NULL */
  86845. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  86846. /**< FLAC__metadata_chain_write() was called on a chain read by
  86847. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  86848. * or
  86849. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  86850. * was called on a chain read by
  86851. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  86852. * Matching read/write methods must always be used. */
  86853. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  86854. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  86855. * chain write requires a tempfile; use
  86856. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  86857. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  86858. * called when the chain write does not require a tempfile; use
  86859. * FLAC__metadata_chain_write_with_callbacks() instead.
  86860. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  86861. * before writing via callbacks. */
  86862. } FLAC__Metadata_ChainStatus;
  86863. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  86864. *
  86865. * Using a FLAC__Metadata_ChainStatus as the index to this array
  86866. * will give the string equivalent. The contents should not be modified.
  86867. */
  86868. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  86869. /*********** FLAC__Metadata_Chain ***********/
  86870. /** Create a new chain instance.
  86871. *
  86872. * \retval FLAC__Metadata_Chain*
  86873. * \c NULL if there was an error allocating memory, else the new instance.
  86874. */
  86875. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  86876. /** Free a chain instance. Deletes the object pointed to by \a chain.
  86877. *
  86878. * \param chain A pointer to an existing chain.
  86879. * \assert
  86880. * \code chain != NULL \endcode
  86881. */
  86882. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  86883. /** Get the current status of the chain. Call this after a function
  86884. * returns \c false to get the reason for the error. Also resets the
  86885. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  86886. *
  86887. * \param chain A pointer to an existing chain.
  86888. * \assert
  86889. * \code chain != NULL \endcode
  86890. * \retval FLAC__Metadata_ChainStatus
  86891. * The current status of the chain.
  86892. */
  86893. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  86894. /** Read all metadata from a FLAC file into the chain.
  86895. *
  86896. * \param chain A pointer to an existing chain.
  86897. * \param filename The path to the FLAC file to read.
  86898. * \assert
  86899. * \code chain != NULL \endcode
  86900. * \code filename != NULL \endcode
  86901. * \retval FLAC__bool
  86902. * \c true if a valid list of metadata blocks was read from
  86903. * \a filename, else \c false. On failure, check the status with
  86904. * FLAC__metadata_chain_status().
  86905. */
  86906. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  86907. /** Read all metadata from an Ogg FLAC file into the chain.
  86908. *
  86909. * \note Ogg FLAC metadata data writing is not supported yet and
  86910. * FLAC__metadata_chain_write() will fail.
  86911. *
  86912. * \param chain A pointer to an existing chain.
  86913. * \param filename The path to the Ogg FLAC file to read.
  86914. * \assert
  86915. * \code chain != NULL \endcode
  86916. * \code filename != NULL \endcode
  86917. * \retval FLAC__bool
  86918. * \c true if a valid list of metadata blocks was read from
  86919. * \a filename, else \c false. On failure, check the status with
  86920. * FLAC__metadata_chain_status().
  86921. */
  86922. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  86923. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  86924. *
  86925. * The \a handle need only be open for reading, but must be seekable.
  86926. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  86927. * for Windows).
  86928. *
  86929. * \param chain A pointer to an existing chain.
  86930. * \param handle The I/O handle of the FLAC stream to read. The
  86931. * handle will NOT be closed after the metadata is read;
  86932. * that is the duty of the caller.
  86933. * \param callbacks
  86934. * A set of callbacks to use for I/O. The mandatory
  86935. * callbacks are \a read, \a seek, and \a tell.
  86936. * \assert
  86937. * \code chain != NULL \endcode
  86938. * \retval FLAC__bool
  86939. * \c true if a valid list of metadata blocks was read from
  86940. * \a handle, else \c false. On failure, check the status with
  86941. * FLAC__metadata_chain_status().
  86942. */
  86943. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  86944. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  86945. *
  86946. * The \a handle need only be open for reading, but must be seekable.
  86947. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  86948. * for Windows).
  86949. *
  86950. * \note Ogg FLAC metadata data writing is not supported yet and
  86951. * FLAC__metadata_chain_write() will fail.
  86952. *
  86953. * \param chain A pointer to an existing chain.
  86954. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  86955. * handle will NOT be closed after the metadata is read;
  86956. * that is the duty of the caller.
  86957. * \param callbacks
  86958. * A set of callbacks to use for I/O. The mandatory
  86959. * callbacks are \a read, \a seek, and \a tell.
  86960. * \assert
  86961. * \code chain != NULL \endcode
  86962. * \retval FLAC__bool
  86963. * \c true if a valid list of metadata blocks was read from
  86964. * \a handle, else \c false. On failure, check the status with
  86965. * FLAC__metadata_chain_status().
  86966. */
  86967. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  86968. /** Checks if writing the given chain would require the use of a
  86969. * temporary file, or if it could be written in place.
  86970. *
  86971. * Under certain conditions, padding can be utilized so that writing
  86972. * edited metadata back to the FLAC file does not require rewriting the
  86973. * entire file. If rewriting is required, then a temporary workfile is
  86974. * required. When writing metadata using callbacks, you must check
  86975. * this function to know whether to call
  86976. * FLAC__metadata_chain_write_with_callbacks() or
  86977. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  86978. * writing with FLAC__metadata_chain_write(), the temporary file is
  86979. * handled internally.
  86980. *
  86981. * \param chain A pointer to an existing chain.
  86982. * \param use_padding
  86983. * Whether or not padding will be allowed to be used
  86984. * during the write. The value of \a use_padding given
  86985. * here must match the value later passed to
  86986. * FLAC__metadata_chain_write_with_callbacks() or
  86987. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  86988. * \assert
  86989. * \code chain != NULL \endcode
  86990. * \retval FLAC__bool
  86991. * \c true if writing the current chain would require a tempfile, or
  86992. * \c false if metadata can be written in place.
  86993. */
  86994. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  86995. /** Write all metadata out to the FLAC file. This function tries to be as
  86996. * efficient as possible; how the metadata is actually written is shown by
  86997. * the following:
  86998. *
  86999. * If the current chain is the same size as the existing metadata, the new
  87000. * data is written in place.
  87001. *
  87002. * If the current chain is longer than the existing metadata, and
  87003. * \a use_padding is \c true, and the last block is a PADDING block of
  87004. * sufficient length, the function will truncate the final padding block
  87005. * so that the overall size of the metadata is the same as the existing
  87006. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87007. * the above conditions are met, the entire FLAC file must be rewritten.
  87008. * If you want to use padding this way it is a good idea to call
  87009. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87010. * amount of padding to work with, unless you need to preserve ordering
  87011. * of the PADDING blocks for some reason.
  87012. *
  87013. * If the current chain is shorter than the existing metadata, and
  87014. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87015. * is extended to make the overall size the same as the existing data. If
  87016. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87017. * PADDING block is added to the end of the new data to make it the same
  87018. * size as the existing data (if possible, see the note to
  87019. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87020. * and the new data is written in place. If none of the above apply or
  87021. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87022. *
  87023. * If \a preserve_file_stats is \c true, the owner and modification time will
  87024. * be preserved even if the FLAC file is written.
  87025. *
  87026. * For this write function to be used, the chain must have been read with
  87027. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87028. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87029. *
  87030. * \param chain A pointer to an existing chain.
  87031. * \param use_padding See above.
  87032. * \param preserve_file_stats See above.
  87033. * \assert
  87034. * \code chain != NULL \endcode
  87035. * \retval FLAC__bool
  87036. * \c true if the write succeeded, else \c false. On failure,
  87037. * check the status with FLAC__metadata_chain_status().
  87038. */
  87039. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87040. /** Write all metadata out to a FLAC stream via callbacks.
  87041. *
  87042. * (See FLAC__metadata_chain_write() for the details on how padding is
  87043. * used to write metadata in place if possible.)
  87044. *
  87045. * The \a handle must be open for updating and be seekable. The
  87046. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87047. * for Windows).
  87048. *
  87049. * For this write function to be used, the chain must have been read with
  87050. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87051. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87052. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87053. * \c false.
  87054. *
  87055. * \param chain A pointer to an existing chain.
  87056. * \param use_padding See FLAC__metadata_chain_write()
  87057. * \param handle The I/O handle of the FLAC stream to write. The
  87058. * handle will NOT be closed after the metadata is
  87059. * written; that is the duty of the caller.
  87060. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87061. * callbacks are \a write and \a seek.
  87062. * \assert
  87063. * \code chain != NULL \endcode
  87064. * \retval FLAC__bool
  87065. * \c true if the write succeeded, else \c false. On failure,
  87066. * check the status with FLAC__metadata_chain_status().
  87067. */
  87068. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87069. /** Write all metadata out to a FLAC stream via callbacks.
  87070. *
  87071. * (See FLAC__metadata_chain_write() for the details on how padding is
  87072. * used to write metadata in place if possible.)
  87073. *
  87074. * This version of the write-with-callbacks function must be used when
  87075. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87076. * this function, you must supply an I/O handle corresponding to the
  87077. * FLAC file to edit, and a temporary handle to which the new FLAC
  87078. * file will be written. It is the caller's job to move this temporary
  87079. * FLAC file on top of the original FLAC file to complete the metadata
  87080. * edit.
  87081. *
  87082. * The \a handle must be open for reading and be seekable. The
  87083. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87084. * for Windows).
  87085. *
  87086. * The \a temp_handle must be open for writing. The
  87087. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87088. * for Windows). It should be an empty stream, or at least positioned
  87089. * at the start-of-file (in which case it is the caller's duty to
  87090. * truncate it on return).
  87091. *
  87092. * For this write function to be used, the chain must have been read with
  87093. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87094. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87095. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87096. * \c true.
  87097. *
  87098. * \param chain A pointer to an existing chain.
  87099. * \param use_padding See FLAC__metadata_chain_write()
  87100. * \param handle The I/O handle of the original FLAC stream to read.
  87101. * The handle will NOT be closed after the metadata is
  87102. * written; that is the duty of the caller.
  87103. * \param callbacks A set of callbacks to use for I/O on \a handle.
  87104. * The mandatory callbacks are \a read, \a seek, and
  87105. * \a eof.
  87106. * \param temp_handle The I/O handle of the FLAC stream to write. The
  87107. * handle will NOT be closed after the metadata is
  87108. * written; that is the duty of the caller.
  87109. * \param temp_callbacks
  87110. * A set of callbacks to use for I/O on temp_handle.
  87111. * The only mandatory callback is \a write.
  87112. * \assert
  87113. * \code chain != NULL \endcode
  87114. * \retval FLAC__bool
  87115. * \c true if the write succeeded, else \c false. On failure,
  87116. * check the status with FLAC__metadata_chain_status().
  87117. */
  87118. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks);
  87119. /** Merge adjacent PADDING blocks into a single block.
  87120. *
  87121. * \note This function does not write to the FLAC file, it only
  87122. * modifies the chain.
  87123. *
  87124. * \warning Any iterator on the current chain will become invalid after this
  87125. * call. You should delete the iterator and get a new one.
  87126. *
  87127. * \param chain A pointer to an existing chain.
  87128. * \assert
  87129. * \code chain != NULL \endcode
  87130. */
  87131. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  87132. /** This function will move all PADDING blocks to the end on the metadata,
  87133. * then merge them into a single block.
  87134. *
  87135. * \note This function does not write to the FLAC file, it only
  87136. * modifies the chain.
  87137. *
  87138. * \warning Any iterator on the current chain will become invalid after this
  87139. * call. You should delete the iterator and get a new one.
  87140. *
  87141. * \param chain A pointer to an existing chain.
  87142. * \assert
  87143. * \code chain != NULL \endcode
  87144. */
  87145. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  87146. /*********** FLAC__Metadata_Iterator ***********/
  87147. /** Create a new iterator instance.
  87148. *
  87149. * \retval FLAC__Metadata_Iterator*
  87150. * \c NULL if there was an error allocating memory, else the new instance.
  87151. */
  87152. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  87153. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87154. *
  87155. * \param iterator A pointer to an existing iterator.
  87156. * \assert
  87157. * \code iterator != NULL \endcode
  87158. */
  87159. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  87160. /** Initialize the iterator to point to the first metadata block in the
  87161. * given chain.
  87162. *
  87163. * \param iterator A pointer to an existing iterator.
  87164. * \param chain A pointer to an existing and initialized (read) chain.
  87165. * \assert
  87166. * \code iterator != NULL \endcode
  87167. * \code chain != NULL \endcode
  87168. */
  87169. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  87170. /** Moves the iterator forward one metadata block, returning \c false if
  87171. * already at the end.
  87172. *
  87173. * \param iterator A pointer to an existing initialized iterator.
  87174. * \assert
  87175. * \code iterator != NULL \endcode
  87176. * \a iterator has been successfully initialized with
  87177. * FLAC__metadata_iterator_init()
  87178. * \retval FLAC__bool
  87179. * \c false if already at the last metadata block of the chain, else
  87180. * \c true.
  87181. */
  87182. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  87183. /** Moves the iterator backward one metadata block, returning \c false if
  87184. * already at the beginning.
  87185. *
  87186. * \param iterator A pointer to an existing initialized iterator.
  87187. * \assert
  87188. * \code iterator != NULL \endcode
  87189. * \a iterator has been successfully initialized with
  87190. * FLAC__metadata_iterator_init()
  87191. * \retval FLAC__bool
  87192. * \c false if already at the first metadata block of the chain, else
  87193. * \c true.
  87194. */
  87195. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  87196. /** Get the type of the metadata block at the current position.
  87197. *
  87198. * \param iterator A pointer to an existing initialized iterator.
  87199. * \assert
  87200. * \code iterator != NULL \endcode
  87201. * \a iterator has been successfully initialized with
  87202. * FLAC__metadata_iterator_init()
  87203. * \retval FLAC__MetadataType
  87204. * The type of the metadata block at the current iterator position.
  87205. */
  87206. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  87207. /** Get the metadata block at the current position. You can modify
  87208. * the block in place but must write the chain before the changes
  87209. * are reflected to the FLAC file. You do not need to call
  87210. * FLAC__metadata_iterator_set_block() to reflect the changes;
  87211. * the pointer returned by FLAC__metadata_iterator_get_block()
  87212. * points directly into the chain.
  87213. *
  87214. * \warning
  87215. * Do not call FLAC__metadata_object_delete() on the returned object;
  87216. * to delete a block use FLAC__metadata_iterator_delete_block().
  87217. *
  87218. * \param iterator A pointer to an existing initialized iterator.
  87219. * \assert
  87220. * \code iterator != NULL \endcode
  87221. * \a iterator has been successfully initialized with
  87222. * FLAC__metadata_iterator_init()
  87223. * \retval FLAC__StreamMetadata*
  87224. * The current metadata block.
  87225. */
  87226. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  87227. /** Set the metadata block at the current position, replacing the existing
  87228. * block. The new block passed in becomes owned by the chain and it will be
  87229. * deleted when the chain is deleted.
  87230. *
  87231. * \param iterator A pointer to an existing initialized iterator.
  87232. * \param block A pointer to a metadata block.
  87233. * \assert
  87234. * \code iterator != NULL \endcode
  87235. * \a iterator has been successfully initialized with
  87236. * FLAC__metadata_iterator_init()
  87237. * \code block != NULL \endcode
  87238. * \retval FLAC__bool
  87239. * \c false if the conditions in the above description are not met, or
  87240. * a memory allocation error occurs, otherwise \c true.
  87241. */
  87242. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87243. /** Removes the current block from the chain. If \a replace_with_padding is
  87244. * \c true, the block will instead be replaced with a padding block of equal
  87245. * size. You can not delete the STREAMINFO block. The iterator will be
  87246. * left pointing to the block before the one just "deleted", even if
  87247. * \a replace_with_padding is \c true.
  87248. *
  87249. * \param iterator A pointer to an existing initialized iterator.
  87250. * \param replace_with_padding See above.
  87251. * \assert
  87252. * \code iterator != NULL \endcode
  87253. * \a iterator has been successfully initialized with
  87254. * FLAC__metadata_iterator_init()
  87255. * \retval FLAC__bool
  87256. * \c false if the conditions in the above description are not met,
  87257. * otherwise \c true.
  87258. */
  87259. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  87260. /** Insert a new block before the current block. You cannot insert a block
  87261. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  87262. * as there can be only one, the one that already exists at the head when you
  87263. * read in a chain. The chain takes ownership of the new block and it will be
  87264. * deleted when the chain is deleted. The iterator will be left pointing to
  87265. * the new block.
  87266. *
  87267. * \param iterator A pointer to an existing initialized iterator.
  87268. * \param block A pointer to a metadata block to insert.
  87269. * \assert
  87270. * \code iterator != NULL \endcode
  87271. * \a iterator has been successfully initialized with
  87272. * FLAC__metadata_iterator_init()
  87273. * \retval FLAC__bool
  87274. * \c false if the conditions in the above description are not met, or
  87275. * a memory allocation error occurs, otherwise \c true.
  87276. */
  87277. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87278. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  87279. * block as there can be only one, the one that already exists at the head when
  87280. * you read in a chain. The chain takes ownership of the new block and it will
  87281. * be deleted when the chain is deleted. The iterator will be left pointing to
  87282. * the new block.
  87283. *
  87284. * \param iterator A pointer to an existing initialized iterator.
  87285. * \param block A pointer to a metadata block to insert.
  87286. * \assert
  87287. * \code iterator != NULL \endcode
  87288. * \a iterator has been successfully initialized with
  87289. * FLAC__metadata_iterator_init()
  87290. * \retval FLAC__bool
  87291. * \c false if the conditions in the above description are not met, or
  87292. * a memory allocation error occurs, otherwise \c true.
  87293. */
  87294. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87295. /* \} */
  87296. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  87297. * \ingroup flac_metadata
  87298. *
  87299. * \brief
  87300. * This module contains methods for manipulating FLAC metadata objects.
  87301. *
  87302. * Since many are variable length we have to be careful about the memory
  87303. * management. We decree that all pointers to data in the object are
  87304. * owned by the object and memory-managed by the object.
  87305. *
  87306. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  87307. * functions to create all instances. When using the
  87308. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  87309. * \a copy to \c true to have the function make it's own copy of the data, or
  87310. * to \c false to give the object ownership of your data. In the latter case
  87311. * your pointer must be freeable by free() and will be free()d when the object
  87312. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  87313. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  87314. * the length argument is 0 and the \a copy argument is \c false.
  87315. *
  87316. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  87317. * will return \c NULL in the case of a memory allocation error, otherwise a new
  87318. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  87319. * case of a memory allocation error.
  87320. *
  87321. * We don't have the convenience of C++ here, so note that the library relies
  87322. * on you to keep the types straight. In other words, if you pass, for
  87323. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  87324. * FLAC__metadata_object_application_set_data(), you will get an assertion
  87325. * failure.
  87326. *
  87327. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  87328. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  87329. * toward the length or stored in the stream, but it can make working with plain
  87330. * comments (those that don't contain embedded-NULs in the value) easier.
  87331. * Entries passed into these functions have trailing NULs added if missing, and
  87332. * returned entries are guaranteed to have a trailing NUL.
  87333. *
  87334. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  87335. * comment entry/name/value will first validate that it complies with the Vorbis
  87336. * comment specification and return false if it does not.
  87337. *
  87338. * There is no need to recalculate the length field on metadata blocks you
  87339. * have modified. They will be calculated automatically before they are
  87340. * written back to a file.
  87341. *
  87342. * \{
  87343. */
  87344. /** Create a new metadata object instance of the given type.
  87345. *
  87346. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  87347. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  87348. * the vendor string set (but zero comments).
  87349. *
  87350. * Do not pass in a value greater than or equal to
  87351. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  87352. * doing.
  87353. *
  87354. * \param type Type of object to create
  87355. * \retval FLAC__StreamMetadata*
  87356. * \c NULL if there was an error allocating memory or the type code is
  87357. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  87358. */
  87359. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  87360. /** Create a copy of an existing metadata object.
  87361. *
  87362. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  87363. * object is also copied. The caller takes ownership of the new block and
  87364. * is responsible for freeing it with FLAC__metadata_object_delete().
  87365. *
  87366. * \param object Pointer to object to copy.
  87367. * \assert
  87368. * \code object != NULL \endcode
  87369. * \retval FLAC__StreamMetadata*
  87370. * \c NULL if there was an error allocating memory, else the new instance.
  87371. */
  87372. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  87373. /** Free a metadata object. Deletes the object pointed to by \a object.
  87374. *
  87375. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  87376. * object is also deleted.
  87377. *
  87378. * \param object A pointer to an existing object.
  87379. * \assert
  87380. * \code object != NULL \endcode
  87381. */
  87382. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  87383. /** Compares two metadata objects.
  87384. *
  87385. * The compare is "deep", i.e. dynamically allocated data within the
  87386. * object is also compared.
  87387. *
  87388. * \param block1 A pointer to an existing object.
  87389. * \param block2 A pointer to an existing object.
  87390. * \assert
  87391. * \code block1 != NULL \endcode
  87392. * \code block2 != NULL \endcode
  87393. * \retval FLAC__bool
  87394. * \c true if objects are identical, else \c false.
  87395. */
  87396. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  87397. /** Sets the application data of an APPLICATION block.
  87398. *
  87399. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  87400. * takes ownership of the pointer. The existing data will be freed if this
  87401. * function is successful, otherwise the original data will remain if \a copy
  87402. * is \c true and malloc() fails.
  87403. *
  87404. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  87405. *
  87406. * \param object A pointer to an existing APPLICATION object.
  87407. * \param data A pointer to the data to set.
  87408. * \param length The length of \a data in bytes.
  87409. * \param copy See above.
  87410. * \assert
  87411. * \code object != NULL \endcode
  87412. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  87413. * \code (data != NULL && length > 0) ||
  87414. * (data == NULL && length == 0 && copy == false) \endcode
  87415. * \retval FLAC__bool
  87416. * \c false if \a copy is \c true and malloc() fails, else \c true.
  87417. */
  87418. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  87419. /** Resize the seekpoint array.
  87420. *
  87421. * If the size shrinks, elements will truncated; if it grows, new placeholder
  87422. * points will be added to the end.
  87423. *
  87424. * \param object A pointer to an existing SEEKTABLE object.
  87425. * \param new_num_points The desired length of the array; may be \c 0.
  87426. * \assert
  87427. * \code object != NULL \endcode
  87428. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87429. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  87430. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  87431. * \retval FLAC__bool
  87432. * \c false if memory allocation error, else \c true.
  87433. */
  87434. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  87435. /** Set a seekpoint in a seektable.
  87436. *
  87437. * \param object A pointer to an existing SEEKTABLE object.
  87438. * \param point_num Index into seekpoint array to set.
  87439. * \param point The point to set.
  87440. * \assert
  87441. * \code object != NULL \endcode
  87442. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87443. * \code object->data.seek_table.num_points > point_num \endcode
  87444. */
  87445. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  87446. /** Insert a seekpoint into a seektable.
  87447. *
  87448. * \param object A pointer to an existing SEEKTABLE object.
  87449. * \param point_num Index into seekpoint array to set.
  87450. * \param point The point to set.
  87451. * \assert
  87452. * \code object != NULL \endcode
  87453. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87454. * \code object->data.seek_table.num_points >= point_num \endcode
  87455. * \retval FLAC__bool
  87456. * \c false if memory allocation error, else \c true.
  87457. */
  87458. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  87459. /** Delete a seekpoint from a seektable.
  87460. *
  87461. * \param object A pointer to an existing SEEKTABLE object.
  87462. * \param point_num Index into seekpoint array to set.
  87463. * \assert
  87464. * \code object != NULL \endcode
  87465. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87466. * \code object->data.seek_table.num_points > point_num \endcode
  87467. * \retval FLAC__bool
  87468. * \c false if memory allocation error, else \c true.
  87469. */
  87470. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  87471. /** Check a seektable to see if it conforms to the FLAC specification.
  87472. * See the format specification for limits on the contents of the
  87473. * seektable.
  87474. *
  87475. * \param object A pointer to an existing SEEKTABLE object.
  87476. * \assert
  87477. * \code object != NULL \endcode
  87478. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87479. * \retval FLAC__bool
  87480. * \c false if seek table is illegal, else \c true.
  87481. */
  87482. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  87483. /** Append a number of placeholder points to the end of a seek table.
  87484. *
  87485. * \note
  87486. * As with the other ..._seektable_template_... functions, you should
  87487. * call FLAC__metadata_object_seektable_template_sort() when finished
  87488. * to make the seek table legal.
  87489. *
  87490. * \param object A pointer to an existing SEEKTABLE object.
  87491. * \param num The number of placeholder points to append.
  87492. * \assert
  87493. * \code object != NULL \endcode
  87494. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87495. * \retval FLAC__bool
  87496. * \c false if memory allocation fails, else \c true.
  87497. */
  87498. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  87499. /** Append a specific seek point template to the end of a seek table.
  87500. *
  87501. * \note
  87502. * As with the other ..._seektable_template_... functions, you should
  87503. * call FLAC__metadata_object_seektable_template_sort() when finished
  87504. * to make the seek table legal.
  87505. *
  87506. * \param object A pointer to an existing SEEKTABLE object.
  87507. * \param sample_number The sample number of the seek point template.
  87508. * \assert
  87509. * \code object != NULL \endcode
  87510. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87511. * \retval FLAC__bool
  87512. * \c false if memory allocation fails, else \c true.
  87513. */
  87514. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  87515. /** Append specific seek point templates to the end of a seek table.
  87516. *
  87517. * \note
  87518. * As with the other ..._seektable_template_... functions, you should
  87519. * call FLAC__metadata_object_seektable_template_sort() when finished
  87520. * to make the seek table legal.
  87521. *
  87522. * \param object A pointer to an existing SEEKTABLE object.
  87523. * \param sample_numbers An array of sample numbers for the seek points.
  87524. * \param num The number of seek point templates to append.
  87525. * \assert
  87526. * \code object != NULL \endcode
  87527. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87528. * \retval FLAC__bool
  87529. * \c false if memory allocation fails, else \c true.
  87530. */
  87531. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  87532. /** Append a set of evenly-spaced seek point templates to the end of a
  87533. * seek table.
  87534. *
  87535. * \note
  87536. * As with the other ..._seektable_template_... functions, you should
  87537. * call FLAC__metadata_object_seektable_template_sort() when finished
  87538. * to make the seek table legal.
  87539. *
  87540. * \param object A pointer to an existing SEEKTABLE object.
  87541. * \param num The number of placeholder points to append.
  87542. * \param total_samples The total number of samples to be encoded;
  87543. * the seekpoints will be spaced approximately
  87544. * \a total_samples / \a num samples apart.
  87545. * \assert
  87546. * \code object != NULL \endcode
  87547. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87548. * \code total_samples > 0 \endcode
  87549. * \retval FLAC__bool
  87550. * \c false if memory allocation fails, else \c true.
  87551. */
  87552. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  87553. /** Append a set of evenly-spaced seek point templates to the end of a
  87554. * seek table.
  87555. *
  87556. * \note
  87557. * As with the other ..._seektable_template_... functions, you should
  87558. * call FLAC__metadata_object_seektable_template_sort() when finished
  87559. * to make the seek table legal.
  87560. *
  87561. * \param object A pointer to an existing SEEKTABLE object.
  87562. * \param samples The number of samples apart to space the placeholder
  87563. * points. The first point will be at sample \c 0, the
  87564. * second at sample \a samples, then 2*\a samples, and
  87565. * so on. As long as \a samples and \a total_samples
  87566. * are greater than \c 0, there will always be at least
  87567. * one seekpoint at sample \c 0.
  87568. * \param total_samples The total number of samples to be encoded;
  87569. * the seekpoints will be spaced
  87570. * \a samples samples apart.
  87571. * \assert
  87572. * \code object != NULL \endcode
  87573. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87574. * \code samples > 0 \endcode
  87575. * \code total_samples > 0 \endcode
  87576. * \retval FLAC__bool
  87577. * \c false if memory allocation fails, else \c true.
  87578. */
  87579. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  87580. /** Sort a seek table's seek points according to the format specification,
  87581. * removing duplicates.
  87582. *
  87583. * \param object A pointer to a seek table to be sorted.
  87584. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  87585. * If \c true, duplicates are deleted and the seek table is
  87586. * shrunk appropriately; the number of placeholder points
  87587. * present in the seek table will be the same after the call
  87588. * as before.
  87589. * \assert
  87590. * \code object != NULL \endcode
  87591. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87592. * \retval FLAC__bool
  87593. * \c false if realloc() fails, else \c true.
  87594. */
  87595. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  87596. /** Sets the vendor string in a VORBIS_COMMENT block.
  87597. *
  87598. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87599. * one already.
  87600. *
  87601. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87602. * takes ownership of the \c entry.entry pointer.
  87603. *
  87604. * \note If this function returns \c false, the caller still owns the
  87605. * pointer.
  87606. *
  87607. * \param object A pointer to an existing VORBIS_COMMENT object.
  87608. * \param entry The entry to set the vendor string to.
  87609. * \param copy See above.
  87610. * \assert
  87611. * \code object != NULL \endcode
  87612. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87613. * \code (entry.entry != NULL && entry.length > 0) ||
  87614. * (entry.entry == NULL && entry.length == 0) \endcode
  87615. * \retval FLAC__bool
  87616. * \c false if memory allocation fails or \a entry does not comply with the
  87617. * Vorbis comment specification, else \c true.
  87618. */
  87619. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87620. /** Resize the comment array.
  87621. *
  87622. * If the size shrinks, elements will truncated; if it grows, new empty
  87623. * fields will be added to the end.
  87624. *
  87625. * \param object A pointer to an existing VORBIS_COMMENT object.
  87626. * \param new_num_comments The desired length of the array; may be \c 0.
  87627. * \assert
  87628. * \code object != NULL \endcode
  87629. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87630. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  87631. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  87632. * \retval FLAC__bool
  87633. * \c false if memory allocation fails, else \c true.
  87634. */
  87635. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  87636. /** Sets a comment in a VORBIS_COMMENT block.
  87637. *
  87638. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87639. * one already.
  87640. *
  87641. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87642. * takes ownership of the \c entry.entry pointer.
  87643. *
  87644. * \note If this function returns \c false, the caller still owns the
  87645. * pointer.
  87646. *
  87647. * \param object A pointer to an existing VORBIS_COMMENT object.
  87648. * \param comment_num Index into comment array to set.
  87649. * \param entry The entry to set the comment to.
  87650. * \param copy See above.
  87651. * \assert
  87652. * \code object != NULL \endcode
  87653. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87654. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  87655. * \code (entry.entry != NULL && entry.length > 0) ||
  87656. * (entry.entry == NULL && entry.length == 0) \endcode
  87657. * \retval FLAC__bool
  87658. * \c false if memory allocation fails or \a entry does not comply with the
  87659. * Vorbis comment specification, else \c true.
  87660. */
  87661. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87662. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  87663. *
  87664. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87665. * one already.
  87666. *
  87667. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87668. * takes ownership of the \c entry.entry pointer.
  87669. *
  87670. * \note If this function returns \c false, the caller still owns the
  87671. * pointer.
  87672. *
  87673. * \param object A pointer to an existing VORBIS_COMMENT object.
  87674. * \param comment_num The index at which to insert the comment. The comments
  87675. * at and after \a comment_num move right one position.
  87676. * To append a comment to the end, set \a comment_num to
  87677. * \c object->data.vorbis_comment.num_comments .
  87678. * \param entry The comment to insert.
  87679. * \param copy See above.
  87680. * \assert
  87681. * \code object != NULL \endcode
  87682. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87683. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  87684. * \code (entry.entry != NULL && entry.length > 0) ||
  87685. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  87686. * \retval FLAC__bool
  87687. * \c false if memory allocation fails or \a entry does not comply with the
  87688. * Vorbis comment specification, else \c true.
  87689. */
  87690. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87691. /** Appends a comment to a VORBIS_COMMENT block.
  87692. *
  87693. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87694. * one already.
  87695. *
  87696. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87697. * takes ownership of the \c entry.entry pointer.
  87698. *
  87699. * \note If this function returns \c false, the caller still owns the
  87700. * pointer.
  87701. *
  87702. * \param object A pointer to an existing VORBIS_COMMENT object.
  87703. * \param entry The comment to insert.
  87704. * \param copy See above.
  87705. * \assert
  87706. * \code object != NULL \endcode
  87707. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87708. * \code (entry.entry != NULL && entry.length > 0) ||
  87709. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  87710. * \retval FLAC__bool
  87711. * \c false if memory allocation fails or \a entry does not comply with the
  87712. * Vorbis comment specification, else \c true.
  87713. */
  87714. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87715. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  87716. *
  87717. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87718. * one already.
  87719. *
  87720. * Depending on the the value of \a all, either all or just the first comment
  87721. * whose field name(s) match the given entry's name will be replaced by the
  87722. * given entry. If no comments match, \a entry will simply be appended.
  87723. *
  87724. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87725. * takes ownership of the \c entry.entry pointer.
  87726. *
  87727. * \note If this function returns \c false, the caller still owns the
  87728. * pointer.
  87729. *
  87730. * \param object A pointer to an existing VORBIS_COMMENT object.
  87731. * \param entry The comment to insert.
  87732. * \param all If \c true, all comments whose field name matches
  87733. * \a entry's field name will be removed, and \a entry will
  87734. * be inserted at the position of the first matching
  87735. * comment. If \c false, only the first comment whose
  87736. * field name matches \a entry's field name will be
  87737. * replaced with \a entry.
  87738. * \param copy See above.
  87739. * \assert
  87740. * \code object != NULL \endcode
  87741. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87742. * \code (entry.entry != NULL && entry.length > 0) ||
  87743. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  87744. * \retval FLAC__bool
  87745. * \c false if memory allocation fails or \a entry does not comply with the
  87746. * Vorbis comment specification, else \c true.
  87747. */
  87748. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  87749. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  87750. *
  87751. * \param object A pointer to an existing VORBIS_COMMENT object.
  87752. * \param comment_num The index of the comment to delete.
  87753. * \assert
  87754. * \code object != NULL \endcode
  87755. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87756. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  87757. * \retval FLAC__bool
  87758. * \c false if realloc() fails, else \c true.
  87759. */
  87760. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  87761. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  87762. *
  87763. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  87764. * memory and shall be owned by the caller. For convenience the entry will
  87765. * have a terminating NUL.
  87766. *
  87767. * \param entry A pointer to a Vorbis comment entry. The entry's
  87768. * \c entry pointer should not point to allocated
  87769. * memory as it will be overwritten.
  87770. * \param field_name The field name in ASCII, \c NUL terminated.
  87771. * \param field_value The field value in UTF-8, \c NUL terminated.
  87772. * \assert
  87773. * \code entry != NULL \endcode
  87774. * \code field_name != NULL \endcode
  87775. * \code field_value != NULL \endcode
  87776. * \retval FLAC__bool
  87777. * \c false if malloc() fails, or if \a field_name or \a field_value does
  87778. * not comply with the Vorbis comment specification, else \c true.
  87779. */
  87780. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(FLAC__StreamMetadata_VorbisComment_Entry *entry, const char *field_name, const char *field_value);
  87781. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  87782. *
  87783. * The returned pointers to name and value will be allocated by malloc()
  87784. * and shall be owned by the caller.
  87785. *
  87786. * \param entry An existing Vorbis comment entry.
  87787. * \param field_name The address of where the returned pointer to the
  87788. * field name will be stored.
  87789. * \param field_value The address of where the returned pointer to the
  87790. * field value will be stored.
  87791. * \assert
  87792. * \code (entry.entry != NULL && entry.length > 0) \endcode
  87793. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  87794. * \code field_name != NULL \endcode
  87795. * \code field_value != NULL \endcode
  87796. * \retval FLAC__bool
  87797. * \c false if memory allocation fails or \a entry does not comply with the
  87798. * Vorbis comment specification, else \c true.
  87799. */
  87800. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value);
  87801. /** Check if the given Vorbis comment entry's field name matches the given
  87802. * field name.
  87803. *
  87804. * \param entry An existing Vorbis comment entry.
  87805. * \param field_name The field name to check.
  87806. * \param field_name_length The length of \a field_name, not including the
  87807. * terminating \c NUL.
  87808. * \assert
  87809. * \code (entry.entry != NULL && entry.length > 0) \endcode
  87810. * \retval FLAC__bool
  87811. * \c true if the field names match, else \c false
  87812. */
  87813. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  87814. /** Find a Vorbis comment with the given field name.
  87815. *
  87816. * The search begins at entry number \a offset; use an offset of 0 to
  87817. * search from the beginning of the comment array.
  87818. *
  87819. * \param object A pointer to an existing VORBIS_COMMENT object.
  87820. * \param offset The offset into the comment array from where to start
  87821. * the search.
  87822. * \param field_name The field name of the comment to find.
  87823. * \assert
  87824. * \code object != NULL \endcode
  87825. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87826. * \code field_name != NULL \endcode
  87827. * \retval int
  87828. * The offset in the comment array of the first comment whose field
  87829. * name matches \a field_name, or \c -1 if no match was found.
  87830. */
  87831. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  87832. /** Remove first Vorbis comment matching the given field name.
  87833. *
  87834. * \param object A pointer to an existing VORBIS_COMMENT object.
  87835. * \param field_name The field name of comment to delete.
  87836. * \assert
  87837. * \code object != NULL \endcode
  87838. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87839. * \retval int
  87840. * \c -1 for memory allocation error, \c 0 for no matching entries,
  87841. * \c 1 for one matching entry deleted.
  87842. */
  87843. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  87844. /** Remove all Vorbis comments matching the given field name.
  87845. *
  87846. * \param object A pointer to an existing VORBIS_COMMENT object.
  87847. * \param field_name The field name of comments to delete.
  87848. * \assert
  87849. * \code object != NULL \endcode
  87850. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87851. * \retval int
  87852. * \c -1 for memory allocation error, \c 0 for no matching entries,
  87853. * else the number of matching entries deleted.
  87854. */
  87855. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  87856. /** Create a new CUESHEET track instance.
  87857. *
  87858. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  87859. *
  87860. * \retval FLAC__StreamMetadata_CueSheet_Track*
  87861. * \c NULL if there was an error allocating memory, else the new instance.
  87862. */
  87863. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  87864. /** Create a copy of an existing CUESHEET track object.
  87865. *
  87866. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  87867. * object is also copied. The caller takes ownership of the new object and
  87868. * is responsible for freeing it with
  87869. * FLAC__metadata_object_cuesheet_track_delete().
  87870. *
  87871. * \param object Pointer to object to copy.
  87872. * \assert
  87873. * \code object != NULL \endcode
  87874. * \retval FLAC__StreamMetadata_CueSheet_Track*
  87875. * \c NULL if there was an error allocating memory, else the new instance.
  87876. */
  87877. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  87878. /** Delete a CUESHEET track object
  87879. *
  87880. * \param object A pointer to an existing CUESHEET track object.
  87881. * \assert
  87882. * \code object != NULL \endcode
  87883. */
  87884. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  87885. /** Resize a track's index point array.
  87886. *
  87887. * If the size shrinks, elements will truncated; if it grows, new blank
  87888. * indices will be added to the end.
  87889. *
  87890. * \param object A pointer to an existing CUESHEET object.
  87891. * \param track_num The index of the track to modify. NOTE: this is not
  87892. * necessarily the same as the track's \a number field.
  87893. * \param new_num_indices The desired length of the array; may be \c 0.
  87894. * \assert
  87895. * \code object != NULL \endcode
  87896. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  87897. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  87898. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  87899. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  87900. * \retval FLAC__bool
  87901. * \c false if memory allocation error, else \c true.
  87902. */
  87903. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  87904. /** Insert an index point in a CUESHEET track at the given index.
  87905. *
  87906. * \param object A pointer to an existing CUESHEET object.
  87907. * \param track_num The index of the track to modify. NOTE: this is not
  87908. * necessarily the same as the track's \a number field.
  87909. * \param index_num The index into the track's index array at which to
  87910. * insert the index point. NOTE: this is not necessarily
  87911. * the same as the index point's \a number field. The
  87912. * indices at and after \a index_num move right one
  87913. * position. To append an index point to the end, set
  87914. * \a index_num to
  87915. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  87916. * \param index The index point to insert.
  87917. * \assert
  87918. * \code object != NULL \endcode
  87919. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  87920. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  87921. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  87922. * \retval FLAC__bool
  87923. * \c false if realloc() fails, else \c true.
  87924. */
  87925. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index index);
  87926. /** Insert a blank index point in a CUESHEET track at the given index.
  87927. *
  87928. * A blank index point is one in which all field values are zero.
  87929. *
  87930. * \param object A pointer to an existing CUESHEET object.
  87931. * \param track_num The index of the track to modify. NOTE: this is not
  87932. * necessarily the same as the track's \a number field.
  87933. * \param index_num The index into the track's index array at which to
  87934. * insert the index point. NOTE: this is not necessarily
  87935. * the same as the index point's \a number field. The
  87936. * indices at and after \a index_num move right one
  87937. * position. To append an index point to the end, set
  87938. * \a index_num to
  87939. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  87940. * \assert
  87941. * \code object != NULL \endcode
  87942. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  87943. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  87944. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  87945. * \retval FLAC__bool
  87946. * \c false if realloc() fails, else \c true.
  87947. */
  87948. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  87949. /** Delete an index point in a CUESHEET track at the given index.
  87950. *
  87951. * \param object A pointer to an existing CUESHEET object.
  87952. * \param track_num The index into the track array of the track to
  87953. * modify. NOTE: this is not necessarily the same
  87954. * as the track's \a number field.
  87955. * \param index_num The index into the track's index array of the index
  87956. * to delete. NOTE: this is not necessarily the same
  87957. * as the index's \a number field.
  87958. * \assert
  87959. * \code object != NULL \endcode
  87960. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  87961. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  87962. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  87963. * \retval FLAC__bool
  87964. * \c false if realloc() fails, else \c true.
  87965. */
  87966. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  87967. /** Resize the track array.
  87968. *
  87969. * If the size shrinks, elements will truncated; if it grows, new blank
  87970. * tracks will be added to the end.
  87971. *
  87972. * \param object A pointer to an existing CUESHEET object.
  87973. * \param new_num_tracks The desired length of the array; may be \c 0.
  87974. * \assert
  87975. * \code object != NULL \endcode
  87976. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  87977. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  87978. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  87979. * \retval FLAC__bool
  87980. * \c false if memory allocation error, else \c true.
  87981. */
  87982. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  87983. /** Sets a track in a CUESHEET block.
  87984. *
  87985. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  87986. * takes ownership of the \a track pointer.
  87987. *
  87988. * \param object A pointer to an existing CUESHEET object.
  87989. * \param track_num Index into track array to set. NOTE: this is not
  87990. * necessarily the same as the track's \a number field.
  87991. * \param track The track to set the track to. You may safely pass in
  87992. * a const pointer if \a copy is \c true.
  87993. * \param copy See above.
  87994. * \assert
  87995. * \code object != NULL \endcode
  87996. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  87997. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  87998. * \code (track->indices != NULL && track->num_indices > 0) ||
  87999. * (track->indices == NULL && track->num_indices == 0)
  88000. * \retval FLAC__bool
  88001. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88002. */
  88003. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88004. /** Insert a track in a CUESHEET block at the given index.
  88005. *
  88006. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88007. * takes ownership of the \a track pointer.
  88008. *
  88009. * \param object A pointer to an existing CUESHEET object.
  88010. * \param track_num The index at which to insert the track. NOTE: this
  88011. * is not necessarily the same as the track's \a number
  88012. * field. The tracks at and after \a track_num move right
  88013. * one position. To append a track to the end, set
  88014. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88015. * \param track The track to insert. You may safely pass in a const
  88016. * pointer if \a copy is \c true.
  88017. * \param copy See above.
  88018. * \assert
  88019. * \code object != NULL \endcode
  88020. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88021. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88022. * \retval FLAC__bool
  88023. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88024. */
  88025. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88026. /** Insert a blank track in a CUESHEET block at the given index.
  88027. *
  88028. * A blank track is one in which all field values are zero.
  88029. *
  88030. * \param object A pointer to an existing CUESHEET object.
  88031. * \param track_num The index at which to insert the track. NOTE: this
  88032. * is not necessarily the same as the track's \a number
  88033. * field. The tracks at and after \a track_num move right
  88034. * one position. To append a track to the end, set
  88035. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88036. * \assert
  88037. * \code object != NULL \endcode
  88038. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88039. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88040. * \retval FLAC__bool
  88041. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88042. */
  88043. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88044. /** Delete a track in a CUESHEET block at the given index.
  88045. *
  88046. * \param object A pointer to an existing CUESHEET object.
  88047. * \param track_num The index into the track array of the track to
  88048. * delete. NOTE: this is not necessarily the same
  88049. * as the track's \a number field.
  88050. * \assert
  88051. * \code object != NULL \endcode
  88052. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88053. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88054. * \retval FLAC__bool
  88055. * \c false if realloc() fails, else \c true.
  88056. */
  88057. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88058. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88059. * See the format specification for limits on the contents of the
  88060. * cue sheet.
  88061. *
  88062. * \param object A pointer to an existing CUESHEET object.
  88063. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88064. * stringent requirements for a CD-DA (audio) disc.
  88065. * \param violation Address of a pointer to a string. If there is a
  88066. * violation, a pointer to a string explanation of the
  88067. * violation will be returned here. \a violation may be
  88068. * \c NULL if you don't need the returned string. Do not
  88069. * free the returned string; it will always point to static
  88070. * data.
  88071. * \assert
  88072. * \code object != NULL \endcode
  88073. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88074. * \retval FLAC__bool
  88075. * \c false if cue sheet is illegal, else \c true.
  88076. */
  88077. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88078. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88079. * assumes the cue sheet corresponds to a CD; the result is undefined
  88080. * if the cuesheet's is_cd bit is not set.
  88081. *
  88082. * \param object A pointer to an existing CUESHEET object.
  88083. * \assert
  88084. * \code object != NULL \endcode
  88085. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88086. * \retval FLAC__uint32
  88087. * The unsigned integer representation of the CDDB/freedb ID
  88088. */
  88089. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88090. /** Sets the MIME type of a PICTURE block.
  88091. *
  88092. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88093. * takes ownership of the pointer. The existing string will be freed if this
  88094. * function is successful, otherwise the original string will remain if \a copy
  88095. * is \c true and malloc() fails.
  88096. *
  88097. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88098. *
  88099. * \param object A pointer to an existing PICTURE object.
  88100. * \param mime_type A pointer to the MIME type string. The string must be
  88101. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88102. * is done.
  88103. * \param copy See above.
  88104. * \assert
  88105. * \code object != NULL \endcode
  88106. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88107. * \code (mime_type != NULL) \endcode
  88108. * \retval FLAC__bool
  88109. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88110. */
  88111. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  88112. /** Sets the description of a PICTURE block.
  88113. *
  88114. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88115. * takes ownership of the pointer. The existing string will be freed if this
  88116. * function is successful, otherwise the original string will remain if \a copy
  88117. * is \c true and malloc() fails.
  88118. *
  88119. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  88120. *
  88121. * \param object A pointer to an existing PICTURE object.
  88122. * \param description A pointer to the description string. The string must be
  88123. * valid UTF-8, NUL-terminated. No validation is done.
  88124. * \param copy See above.
  88125. * \assert
  88126. * \code object != NULL \endcode
  88127. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88128. * \code (description != NULL) \endcode
  88129. * \retval FLAC__bool
  88130. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88131. */
  88132. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  88133. /** Sets the picture data of a PICTURE block.
  88134. *
  88135. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88136. * takes ownership of the pointer. Also sets the \a data_length field of the
  88137. * metadata object to what is passed in as the \a length parameter. The
  88138. * existing data will be freed if this function is successful, otherwise the
  88139. * original data and data_length will remain if \a copy is \c true and
  88140. * malloc() fails.
  88141. *
  88142. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88143. *
  88144. * \param object A pointer to an existing PICTURE object.
  88145. * \param data A pointer to the data to set.
  88146. * \param length The length of \a data in bytes.
  88147. * \param copy See above.
  88148. * \assert
  88149. * \code object != NULL \endcode
  88150. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88151. * \code (data != NULL && length > 0) ||
  88152. * (data == NULL && length == 0 && copy == false) \endcode
  88153. * \retval FLAC__bool
  88154. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88155. */
  88156. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  88157. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  88158. * See the format specification for limits on the contents of the
  88159. * PICTURE block.
  88160. *
  88161. * \param object A pointer to existing PICTURE block to be checked.
  88162. * \param violation Address of a pointer to a string. If there is a
  88163. * violation, a pointer to a string explanation of the
  88164. * violation will be returned here. \a violation may be
  88165. * \c NULL if you don't need the returned string. Do not
  88166. * free the returned string; it will always point to static
  88167. * data.
  88168. * \assert
  88169. * \code object != NULL \endcode
  88170. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88171. * \retval FLAC__bool
  88172. * \c false if PICTURE block is illegal, else \c true.
  88173. */
  88174. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  88175. /* \} */
  88176. #ifdef __cplusplus
  88177. }
  88178. #endif
  88179. #endif
  88180. /*** End of inlined file: metadata.h ***/
  88181. /*** Start of inlined file: stream_decoder.h ***/
  88182. #ifndef FLAC__STREAM_DECODER_H
  88183. #define FLAC__STREAM_DECODER_H
  88184. #include <stdio.h> /* for FILE */
  88185. #ifdef __cplusplus
  88186. extern "C" {
  88187. #endif
  88188. /** \file include/FLAC/stream_decoder.h
  88189. *
  88190. * \brief
  88191. * This module contains the functions which implement the stream
  88192. * decoder.
  88193. *
  88194. * See the detailed documentation in the
  88195. * \link flac_stream_decoder stream decoder \endlink module.
  88196. */
  88197. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  88198. * \ingroup flac
  88199. *
  88200. * \brief
  88201. * This module describes the decoder layers provided by libFLAC.
  88202. *
  88203. * The stream decoder can be used to decode complete streams either from
  88204. * the client via callbacks, or directly from a file, depending on how
  88205. * it is initialized. When decoding via callbacks, the client provides
  88206. * callbacks for reading FLAC data and writing decoded samples, and
  88207. * handling metadata and errors. If the client also supplies seek-related
  88208. * callback, the decoder function for sample-accurate seeking within the
  88209. * FLAC input is also available. When decoding from a file, the client
  88210. * needs only supply a filename or open \c FILE* and write/metadata/error
  88211. * callbacks; the rest of the callbacks are supplied internally. For more
  88212. * info see the \link flac_stream_decoder stream decoder \endlink module.
  88213. */
  88214. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  88215. * \ingroup flac_decoder
  88216. *
  88217. * \brief
  88218. * This module contains the functions which implement the stream
  88219. * decoder.
  88220. *
  88221. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  88222. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  88223. *
  88224. * The basic usage of this decoder is as follows:
  88225. * - The program creates an instance of a decoder using
  88226. * FLAC__stream_decoder_new().
  88227. * - The program overrides the default settings using
  88228. * FLAC__stream_decoder_set_*() functions.
  88229. * - The program initializes the instance to validate the settings and
  88230. * prepare for decoding using
  88231. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  88232. * or FLAC__stream_decoder_init_file() for native FLAC,
  88233. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  88234. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  88235. * - The program calls the FLAC__stream_decoder_process_*() functions
  88236. * to decode data, which subsequently calls the callbacks.
  88237. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  88238. * which flushes the input and output and resets the decoder to the
  88239. * uninitialized state.
  88240. * - The instance may be used again or deleted with
  88241. * FLAC__stream_decoder_delete().
  88242. *
  88243. * In more detail, the program will create a new instance by calling
  88244. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  88245. * functions to override the default decoder options, and call
  88246. * one of the FLAC__stream_decoder_init_*() functions.
  88247. *
  88248. * There are three initialization functions for native FLAC, one for
  88249. * setting up the decoder to decode FLAC data from the client via
  88250. * callbacks, and two for decoding directly from a FLAC file.
  88251. *
  88252. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  88253. * You must also supply several callbacks for handling I/O. Some (like
  88254. * seeking) are optional, depending on the capabilities of the input.
  88255. *
  88256. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  88257. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  88258. * \c FILE* or filename and fewer callbacks; the decoder will handle
  88259. * the other callbacks internally.
  88260. *
  88261. * There are three similarly-named init functions for decoding from Ogg
  88262. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  88263. * library has been built with Ogg support.
  88264. *
  88265. * Once the decoder is initialized, your program will call one of several
  88266. * functions to start the decoding process:
  88267. *
  88268. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  88269. * most one metadata block or audio frame and return, calling either the
  88270. * metadata callback or write callback, respectively, once. If the decoder
  88271. * loses sync it will return with only the error callback being called.
  88272. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  88273. * to process the stream from the current location and stop upon reaching
  88274. * the first audio frame. The client will get one metadata, write, or error
  88275. * callback per metadata block, audio frame, or sync error, respectively.
  88276. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  88277. * to process the stream from the current location until the read callback
  88278. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  88279. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  88280. * write, or error callback per metadata block, audio frame, or sync error,
  88281. * respectively.
  88282. *
  88283. * When the decoder has finished decoding (normally or through an abort),
  88284. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  88285. * ensures the decoder is in the correct state and frees memory. Then the
  88286. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  88287. * again to decode another stream.
  88288. *
  88289. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  88290. * At any point after the stream decoder has been initialized, the client can
  88291. * call this function to seek to an exact sample within the stream.
  88292. * Subsequently, the first time the write callback is called it will be
  88293. * passed a (possibly partial) block starting at that sample.
  88294. *
  88295. * If the client cannot seek via the callback interface provided, but still
  88296. * has another way of seeking, it can flush the decoder using
  88297. * FLAC__stream_decoder_flush() and start feeding data from the new position
  88298. * through the read callback.
  88299. *
  88300. * The stream decoder also provides MD5 signature checking. If this is
  88301. * turned on before initialization, FLAC__stream_decoder_finish() will
  88302. * report when the decoded MD5 signature does not match the one stored
  88303. * in the STREAMINFO block. MD5 checking is automatically turned off
  88304. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  88305. * in the STREAMINFO block or when a seek is attempted.
  88306. *
  88307. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  88308. * attention. By default, the decoder only calls the metadata_callback for
  88309. * the STREAMINFO block. These functions allow you to tell the decoder
  88310. * explicitly which blocks to parse and return via the metadata_callback
  88311. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  88312. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  88313. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  88314. * which blocks to return. Remember that metadata blocks can potentially
  88315. * be big (for example, cover art) so filtering out the ones you don't
  88316. * use can reduce the memory requirements of the decoder. Also note the
  88317. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  88318. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  88319. * filtering APPLICATION blocks based on the application ID.
  88320. *
  88321. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  88322. * they still can legally be filtered from the metadata_callback.
  88323. *
  88324. * \note
  88325. * The "set" functions may only be called when the decoder is in the
  88326. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  88327. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  88328. * before FLAC__stream_decoder_init_*(). If this is the case they will
  88329. * return \c true, otherwise \c false.
  88330. *
  88331. * \note
  88332. * FLAC__stream_decoder_finish() resets all settings to the constructor
  88333. * defaults, including the callbacks.
  88334. *
  88335. * \{
  88336. */
  88337. /** State values for a FLAC__StreamDecoder
  88338. *
  88339. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  88340. */
  88341. typedef enum {
  88342. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  88343. /**< The decoder is ready to search for metadata. */
  88344. FLAC__STREAM_DECODER_READ_METADATA,
  88345. /**< The decoder is ready to or is in the process of reading metadata. */
  88346. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  88347. /**< The decoder is ready to or is in the process of searching for the
  88348. * frame sync code.
  88349. */
  88350. FLAC__STREAM_DECODER_READ_FRAME,
  88351. /**< The decoder is ready to or is in the process of reading a frame. */
  88352. FLAC__STREAM_DECODER_END_OF_STREAM,
  88353. /**< The decoder has reached the end of the stream. */
  88354. FLAC__STREAM_DECODER_OGG_ERROR,
  88355. /**< An error occurred in the underlying Ogg layer. */
  88356. FLAC__STREAM_DECODER_SEEK_ERROR,
  88357. /**< An error occurred while seeking. The decoder must be flushed
  88358. * with FLAC__stream_decoder_flush() or reset with
  88359. * FLAC__stream_decoder_reset() before decoding can continue.
  88360. */
  88361. FLAC__STREAM_DECODER_ABORTED,
  88362. /**< The decoder was aborted by the read callback. */
  88363. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  88364. /**< An error occurred allocating memory. The decoder is in an invalid
  88365. * state and can no longer be used.
  88366. */
  88367. FLAC__STREAM_DECODER_UNINITIALIZED
  88368. /**< The decoder is in the uninitialized state; one of the
  88369. * FLAC__stream_decoder_init_*() functions must be called before samples
  88370. * can be processed.
  88371. */
  88372. } FLAC__StreamDecoderState;
  88373. /** Maps a FLAC__StreamDecoderState to a C string.
  88374. *
  88375. * Using a FLAC__StreamDecoderState as the index to this array
  88376. * will give the string equivalent. The contents should not be modified.
  88377. */
  88378. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  88379. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  88380. */
  88381. typedef enum {
  88382. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  88383. /**< Initialization was successful. */
  88384. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  88385. /**< The library was not compiled with support for the given container
  88386. * format.
  88387. */
  88388. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  88389. /**< A required callback was not supplied. */
  88390. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  88391. /**< An error occurred allocating memory. */
  88392. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  88393. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  88394. * FLAC__stream_decoder_init_ogg_file(). */
  88395. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  88396. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  88397. * already initialized, usually because
  88398. * FLAC__stream_decoder_finish() was not called.
  88399. */
  88400. } FLAC__StreamDecoderInitStatus;
  88401. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  88402. *
  88403. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  88404. * will give the string equivalent. The contents should not be modified.
  88405. */
  88406. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  88407. /** Return values for the FLAC__StreamDecoder read callback.
  88408. */
  88409. typedef enum {
  88410. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  88411. /**< The read was OK and decoding can continue. */
  88412. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  88413. /**< The read was attempted while at the end of the stream. Note that
  88414. * the client must only return this value when the read callback was
  88415. * called when already at the end of the stream. Otherwise, if the read
  88416. * itself moves to the end of the stream, the client should still return
  88417. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  88418. * the next read callback it should return
  88419. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  88420. * of \c 0.
  88421. */
  88422. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  88423. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88424. } FLAC__StreamDecoderReadStatus;
  88425. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  88426. *
  88427. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  88428. * will give the string equivalent. The contents should not be modified.
  88429. */
  88430. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  88431. /** Return values for the FLAC__StreamDecoder seek callback.
  88432. */
  88433. typedef enum {
  88434. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  88435. /**< The seek was OK and decoding can continue. */
  88436. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  88437. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88438. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  88439. /**< Client does not support seeking. */
  88440. } FLAC__StreamDecoderSeekStatus;
  88441. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  88442. *
  88443. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  88444. * will give the string equivalent. The contents should not be modified.
  88445. */
  88446. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  88447. /** Return values for the FLAC__StreamDecoder tell callback.
  88448. */
  88449. typedef enum {
  88450. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  88451. /**< The tell was OK and decoding can continue. */
  88452. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  88453. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88454. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  88455. /**< Client does not support telling the position. */
  88456. } FLAC__StreamDecoderTellStatus;
  88457. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  88458. *
  88459. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  88460. * will give the string equivalent. The contents should not be modified.
  88461. */
  88462. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  88463. /** Return values for the FLAC__StreamDecoder length callback.
  88464. */
  88465. typedef enum {
  88466. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  88467. /**< The length call was OK and decoding can continue. */
  88468. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  88469. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88470. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  88471. /**< Client does not support reporting the length. */
  88472. } FLAC__StreamDecoderLengthStatus;
  88473. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  88474. *
  88475. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  88476. * will give the string equivalent. The contents should not be modified.
  88477. */
  88478. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  88479. /** Return values for the FLAC__StreamDecoder write callback.
  88480. */
  88481. typedef enum {
  88482. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  88483. /**< The write was OK and decoding can continue. */
  88484. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  88485. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88486. } FLAC__StreamDecoderWriteStatus;
  88487. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  88488. *
  88489. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  88490. * will give the string equivalent. The contents should not be modified.
  88491. */
  88492. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  88493. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  88494. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  88495. * all. The rest could be caused by bad sync (false synchronization on
  88496. * data that is not the start of a frame) or corrupted data. The error
  88497. * itself is the decoder's best guess at what happened assuming a correct
  88498. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  88499. * could be caused by a correct sync on the start of a frame, but some
  88500. * data in the frame header was corrupted. Or it could be the result of
  88501. * syncing on a point the stream that looked like the starting of a frame
  88502. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  88503. * could be because the decoder encountered a valid frame made by a future
  88504. * version of the encoder which it cannot parse, or because of a false
  88505. * sync making it appear as though an encountered frame was generated by
  88506. * a future encoder.
  88507. */
  88508. typedef enum {
  88509. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  88510. /**< An error in the stream caused the decoder to lose synchronization. */
  88511. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  88512. /**< The decoder encountered a corrupted frame header. */
  88513. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  88514. /**< The frame's data did not match the CRC in the footer. */
  88515. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  88516. /**< The decoder encountered reserved fields in use in the stream. */
  88517. } FLAC__StreamDecoderErrorStatus;
  88518. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  88519. *
  88520. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  88521. * will give the string equivalent. The contents should not be modified.
  88522. */
  88523. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  88524. /***********************************************************************
  88525. *
  88526. * class FLAC__StreamDecoder
  88527. *
  88528. ***********************************************************************/
  88529. struct FLAC__StreamDecoderProtected;
  88530. struct FLAC__StreamDecoderPrivate;
  88531. /** The opaque structure definition for the stream decoder type.
  88532. * See the \link flac_stream_decoder stream decoder module \endlink
  88533. * for a detailed description.
  88534. */
  88535. typedef struct {
  88536. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  88537. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  88538. } FLAC__StreamDecoder;
  88539. /** Signature for the read callback.
  88540. *
  88541. * A function pointer matching this signature must be passed to
  88542. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88543. * called when the decoder needs more input data. The address of the
  88544. * buffer to be filled is supplied, along with the number of bytes the
  88545. * buffer can hold. The callback may choose to supply less data and
  88546. * modify the byte count but must be careful not to overflow the buffer.
  88547. * The callback then returns a status code chosen from
  88548. * FLAC__StreamDecoderReadStatus.
  88549. *
  88550. * Here is an example of a read callback for stdio streams:
  88551. * \code
  88552. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  88553. * {
  88554. * FILE *file = ((MyClientData*)client_data)->file;
  88555. * if(*bytes > 0) {
  88556. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  88557. * if(ferror(file))
  88558. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  88559. * else if(*bytes == 0)
  88560. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  88561. * else
  88562. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  88563. * }
  88564. * else
  88565. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  88566. * }
  88567. * \endcode
  88568. *
  88569. * \note In general, FLAC__StreamDecoder functions which change the
  88570. * state should not be called on the \a decoder while in the callback.
  88571. *
  88572. * \param decoder The decoder instance calling the callback.
  88573. * \param buffer A pointer to a location for the callee to store
  88574. * data to be decoded.
  88575. * \param bytes A pointer to the size of the buffer. On entry
  88576. * to the callback, it contains the maximum number
  88577. * of bytes that may be stored in \a buffer. The
  88578. * callee must set it to the actual number of bytes
  88579. * stored (0 in case of error or end-of-stream) before
  88580. * returning.
  88581. * \param client_data The callee's client data set through
  88582. * FLAC__stream_decoder_init_*().
  88583. * \retval FLAC__StreamDecoderReadStatus
  88584. * The callee's return status. Note that the callback should return
  88585. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  88586. * zero bytes were read and there is no more data to be read.
  88587. */
  88588. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  88589. /** Signature for the seek callback.
  88590. *
  88591. * A function pointer matching this signature may be passed to
  88592. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88593. * called when the decoder needs to seek the input stream. The decoder
  88594. * will pass the absolute byte offset to seek to, 0 meaning the
  88595. * beginning of the stream.
  88596. *
  88597. * Here is an example of a seek callback for stdio streams:
  88598. * \code
  88599. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  88600. * {
  88601. * FILE *file = ((MyClientData*)client_data)->file;
  88602. * if(file == stdin)
  88603. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  88604. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  88605. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  88606. * else
  88607. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  88608. * }
  88609. * \endcode
  88610. *
  88611. * \note In general, FLAC__StreamDecoder functions which change the
  88612. * state should not be called on the \a decoder while in the callback.
  88613. *
  88614. * \param decoder The decoder instance calling the callback.
  88615. * \param absolute_byte_offset The offset from the beginning of the stream
  88616. * to seek to.
  88617. * \param client_data The callee's client data set through
  88618. * FLAC__stream_decoder_init_*().
  88619. * \retval FLAC__StreamDecoderSeekStatus
  88620. * The callee's return status.
  88621. */
  88622. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  88623. /** Signature for the tell callback.
  88624. *
  88625. * A function pointer matching this signature may be passed to
  88626. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88627. * called when the decoder wants to know the current position of the
  88628. * stream. The callback should return the byte offset from the
  88629. * beginning of the stream.
  88630. *
  88631. * Here is an example of a tell callback for stdio streams:
  88632. * \code
  88633. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  88634. * {
  88635. * FILE *file = ((MyClientData*)client_data)->file;
  88636. * off_t pos;
  88637. * if(file == stdin)
  88638. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  88639. * else if((pos = ftello(file)) < 0)
  88640. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  88641. * else {
  88642. * *absolute_byte_offset = (FLAC__uint64)pos;
  88643. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  88644. * }
  88645. * }
  88646. * \endcode
  88647. *
  88648. * \note In general, FLAC__StreamDecoder functions which change the
  88649. * state should not be called on the \a decoder while in the callback.
  88650. *
  88651. * \param decoder The decoder instance calling the callback.
  88652. * \param absolute_byte_offset A pointer to storage for the current offset
  88653. * from the beginning of the stream.
  88654. * \param client_data The callee's client data set through
  88655. * FLAC__stream_decoder_init_*().
  88656. * \retval FLAC__StreamDecoderTellStatus
  88657. * The callee's return status.
  88658. */
  88659. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  88660. /** Signature for the length callback.
  88661. *
  88662. * A function pointer matching this signature may be passed to
  88663. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88664. * called when the decoder wants to know the total length of the stream
  88665. * in bytes.
  88666. *
  88667. * Here is an example of a length callback for stdio streams:
  88668. * \code
  88669. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  88670. * {
  88671. * FILE *file = ((MyClientData*)client_data)->file;
  88672. * struct stat filestats;
  88673. *
  88674. * if(file == stdin)
  88675. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  88676. * else if(fstat(fileno(file), &filestats) != 0)
  88677. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  88678. * else {
  88679. * *stream_length = (FLAC__uint64)filestats.st_size;
  88680. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  88681. * }
  88682. * }
  88683. * \endcode
  88684. *
  88685. * \note In general, FLAC__StreamDecoder functions which change the
  88686. * state should not be called on the \a decoder while in the callback.
  88687. *
  88688. * \param decoder The decoder instance calling the callback.
  88689. * \param stream_length A pointer to storage for the length of the stream
  88690. * in bytes.
  88691. * \param client_data The callee's client data set through
  88692. * FLAC__stream_decoder_init_*().
  88693. * \retval FLAC__StreamDecoderLengthStatus
  88694. * The callee's return status.
  88695. */
  88696. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  88697. /** Signature for the EOF callback.
  88698. *
  88699. * A function pointer matching this signature may be passed to
  88700. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88701. * called when the decoder needs to know if the end of the stream has
  88702. * been reached.
  88703. *
  88704. * Here is an example of a EOF callback for stdio streams:
  88705. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  88706. * \code
  88707. * {
  88708. * FILE *file = ((MyClientData*)client_data)->file;
  88709. * return feof(file)? true : false;
  88710. * }
  88711. * \endcode
  88712. *
  88713. * \note In general, FLAC__StreamDecoder functions which change the
  88714. * state should not be called on the \a decoder while in the callback.
  88715. *
  88716. * \param decoder The decoder instance calling the callback.
  88717. * \param client_data The callee's client data set through
  88718. * FLAC__stream_decoder_init_*().
  88719. * \retval FLAC__bool
  88720. * \c true if the currently at the end of the stream, else \c false.
  88721. */
  88722. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  88723. /** Signature for the write callback.
  88724. *
  88725. * A function pointer matching this signature must be passed to one of
  88726. * the FLAC__stream_decoder_init_*() functions.
  88727. * The supplied function will be called when the decoder has decoded a
  88728. * single audio frame. The decoder will pass the frame metadata as well
  88729. * as an array of pointers (one for each channel) pointing to the
  88730. * decoded audio.
  88731. *
  88732. * \note In general, FLAC__StreamDecoder functions which change the
  88733. * state should not be called on the \a decoder while in the callback.
  88734. *
  88735. * \param decoder The decoder instance calling the callback.
  88736. * \param frame The description of the decoded frame. See
  88737. * FLAC__Frame.
  88738. * \param buffer An array of pointers to decoded channels of data.
  88739. * Each pointer will point to an array of signed
  88740. * samples of length \a frame->header.blocksize.
  88741. * Channels will be ordered according to the FLAC
  88742. * specification; see the documentation for the
  88743. * <A HREF="../format.html#frame_header">frame header</A>.
  88744. * \param client_data The callee's client data set through
  88745. * FLAC__stream_decoder_init_*().
  88746. * \retval FLAC__StreamDecoderWriteStatus
  88747. * The callee's return status.
  88748. */
  88749. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  88750. /** Signature for the metadata callback.
  88751. *
  88752. * A function pointer matching this signature must be passed to one of
  88753. * the FLAC__stream_decoder_init_*() functions.
  88754. * The supplied function will be called when the decoder has decoded a
  88755. * metadata block. In a valid FLAC file there will always be one
  88756. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  88757. * These will be supplied by the decoder in the same order as they
  88758. * appear in the stream and always before the first audio frame (i.e.
  88759. * write callback). The metadata block that is passed in must not be
  88760. * modified, and it doesn't live beyond the callback, so you should make
  88761. * a copy of it with FLAC__metadata_object_clone() if you will need it
  88762. * elsewhere. Since metadata blocks can potentially be large, by
  88763. * default the decoder only calls the metadata callback for the
  88764. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  88765. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  88766. *
  88767. * \note In general, FLAC__StreamDecoder functions which change the
  88768. * state should not be called on the \a decoder while in the callback.
  88769. *
  88770. * \param decoder The decoder instance calling the callback.
  88771. * \param metadata The decoded metadata block.
  88772. * \param client_data The callee's client data set through
  88773. * FLAC__stream_decoder_init_*().
  88774. */
  88775. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  88776. /** Signature for the error callback.
  88777. *
  88778. * A function pointer matching this signature must be passed to one of
  88779. * the FLAC__stream_decoder_init_*() functions.
  88780. * The supplied function will be called whenever an error occurs during
  88781. * decoding.
  88782. *
  88783. * \note In general, FLAC__StreamDecoder functions which change the
  88784. * state should not be called on the \a decoder while in the callback.
  88785. *
  88786. * \param decoder The decoder instance calling the callback.
  88787. * \param status The error encountered by the decoder.
  88788. * \param client_data The callee's client data set through
  88789. * FLAC__stream_decoder_init_*().
  88790. */
  88791. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  88792. /***********************************************************************
  88793. *
  88794. * Class constructor/destructor
  88795. *
  88796. ***********************************************************************/
  88797. /** Create a new stream decoder instance. The instance is created with
  88798. * default settings; see the individual FLAC__stream_decoder_set_*()
  88799. * functions for each setting's default.
  88800. *
  88801. * \retval FLAC__StreamDecoder*
  88802. * \c NULL if there was an error allocating memory, else the new instance.
  88803. */
  88804. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  88805. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  88806. *
  88807. * \param decoder A pointer to an existing decoder.
  88808. * \assert
  88809. * \code decoder != NULL \endcode
  88810. */
  88811. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  88812. /***********************************************************************
  88813. *
  88814. * Public class method prototypes
  88815. *
  88816. ***********************************************************************/
  88817. /** Set the serial number for the FLAC stream within the Ogg container.
  88818. * The default behavior is to use the serial number of the first Ogg
  88819. * page. Setting a serial number here will explicitly specify which
  88820. * stream is to be decoded.
  88821. *
  88822. * \note
  88823. * This does not need to be set for native FLAC decoding.
  88824. *
  88825. * \default \c use serial number of first page
  88826. * \param decoder A decoder instance to set.
  88827. * \param serial_number See above.
  88828. * \assert
  88829. * \code decoder != NULL \endcode
  88830. * \retval FLAC__bool
  88831. * \c false if the decoder is already initialized, else \c true.
  88832. */
  88833. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  88834. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  88835. * compute the MD5 signature of the unencoded audio data while decoding
  88836. * and compare it to the signature from the STREAMINFO block, if it
  88837. * exists, during FLAC__stream_decoder_finish().
  88838. *
  88839. * MD5 signature checking will be turned off (until the next
  88840. * FLAC__stream_decoder_reset()) if there is no signature in the
  88841. * STREAMINFO block or when a seek is attempted.
  88842. *
  88843. * Clients that do not use the MD5 check should leave this off to speed
  88844. * up decoding.
  88845. *
  88846. * \default \c false
  88847. * \param decoder A decoder instance to set.
  88848. * \param value Flag value (see above).
  88849. * \assert
  88850. * \code decoder != NULL \endcode
  88851. * \retval FLAC__bool
  88852. * \c false if the decoder is already initialized, else \c true.
  88853. */
  88854. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  88855. /** Direct the decoder to pass on all metadata blocks of type \a type.
  88856. *
  88857. * \default By default, only the \c STREAMINFO block is returned via the
  88858. * metadata callback.
  88859. * \param decoder A decoder instance to set.
  88860. * \param type See above.
  88861. * \assert
  88862. * \code decoder != NULL \endcode
  88863. * \a type is valid
  88864. * \retval FLAC__bool
  88865. * \c false if the decoder is already initialized, else \c true.
  88866. */
  88867. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  88868. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  88869. * given \a id.
  88870. *
  88871. * \default By default, only the \c STREAMINFO block is returned via the
  88872. * metadata callback.
  88873. * \param decoder A decoder instance to set.
  88874. * \param id See above.
  88875. * \assert
  88876. * \code decoder != NULL \endcode
  88877. * \code id != NULL \endcode
  88878. * \retval FLAC__bool
  88879. * \c false if the decoder is already initialized, else \c true.
  88880. */
  88881. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  88882. /** Direct the decoder to pass on all metadata blocks of any type.
  88883. *
  88884. * \default By default, only the \c STREAMINFO block is returned via the
  88885. * metadata callback.
  88886. * \param decoder A decoder instance to set.
  88887. * \assert
  88888. * \code decoder != NULL \endcode
  88889. * \retval FLAC__bool
  88890. * \c false if the decoder is already initialized, else \c true.
  88891. */
  88892. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  88893. /** Direct the decoder to filter out all metadata blocks of type \a type.
  88894. *
  88895. * \default By default, only the \c STREAMINFO block is returned via the
  88896. * metadata callback.
  88897. * \param decoder A decoder instance to set.
  88898. * \param type See above.
  88899. * \assert
  88900. * \code decoder != NULL \endcode
  88901. * \a type is valid
  88902. * \retval FLAC__bool
  88903. * \c false if the decoder is already initialized, else \c true.
  88904. */
  88905. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  88906. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  88907. * the given \a id.
  88908. *
  88909. * \default By default, only the \c STREAMINFO block is returned via the
  88910. * metadata callback.
  88911. * \param decoder A decoder instance to set.
  88912. * \param id See above.
  88913. * \assert
  88914. * \code decoder != NULL \endcode
  88915. * \code id != NULL \endcode
  88916. * \retval FLAC__bool
  88917. * \c false if the decoder is already initialized, else \c true.
  88918. */
  88919. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  88920. /** Direct the decoder to filter out all metadata blocks of any type.
  88921. *
  88922. * \default By default, only the \c STREAMINFO block is returned via the
  88923. * metadata callback.
  88924. * \param decoder A decoder instance to set.
  88925. * \assert
  88926. * \code decoder != NULL \endcode
  88927. * \retval FLAC__bool
  88928. * \c false if the decoder is already initialized, else \c true.
  88929. */
  88930. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  88931. /** Get the current decoder state.
  88932. *
  88933. * \param decoder A decoder instance to query.
  88934. * \assert
  88935. * \code decoder != NULL \endcode
  88936. * \retval FLAC__StreamDecoderState
  88937. * The current decoder state.
  88938. */
  88939. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  88940. /** Get the current decoder state as a C string.
  88941. *
  88942. * \param decoder A decoder instance to query.
  88943. * \assert
  88944. * \code decoder != NULL \endcode
  88945. * \retval const char *
  88946. * The decoder state as a C string. Do not modify the contents.
  88947. */
  88948. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  88949. /** Get the "MD5 signature checking" flag.
  88950. * This is the value of the setting, not whether or not the decoder is
  88951. * currently checking the MD5 (remember, it can be turned off automatically
  88952. * by a seek). When the decoder is reset the flag will be restored to the
  88953. * value returned by this function.
  88954. *
  88955. * \param decoder A decoder instance to query.
  88956. * \assert
  88957. * \code decoder != NULL \endcode
  88958. * \retval FLAC__bool
  88959. * See above.
  88960. */
  88961. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  88962. /** Get the total number of samples in the stream being decoded.
  88963. * Will only be valid after decoding has started and will contain the
  88964. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  88965. *
  88966. * \param decoder A decoder instance to query.
  88967. * \assert
  88968. * \code decoder != NULL \endcode
  88969. * \retval unsigned
  88970. * See above.
  88971. */
  88972. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  88973. /** Get the current number of channels in the stream being decoded.
  88974. * Will only be valid after decoding has started and will contain the
  88975. * value from the most recently decoded frame header.
  88976. *
  88977. * \param decoder A decoder instance to query.
  88978. * \assert
  88979. * \code decoder != NULL \endcode
  88980. * \retval unsigned
  88981. * See above.
  88982. */
  88983. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  88984. /** Get the current channel assignment in the stream being decoded.
  88985. * Will only be valid after decoding has started and will contain the
  88986. * value from the most recently decoded frame header.
  88987. *
  88988. * \param decoder A decoder instance to query.
  88989. * \assert
  88990. * \code decoder != NULL \endcode
  88991. * \retval FLAC__ChannelAssignment
  88992. * See above.
  88993. */
  88994. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  88995. /** Get the current sample resolution in the stream being decoded.
  88996. * Will only be valid after decoding has started and will contain the
  88997. * value from the most recently decoded frame header.
  88998. *
  88999. * \param decoder A decoder instance to query.
  89000. * \assert
  89001. * \code decoder != NULL \endcode
  89002. * \retval unsigned
  89003. * See above.
  89004. */
  89005. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89006. /** Get the current sample rate in Hz of the stream being decoded.
  89007. * Will only be valid after decoding has started and will contain the
  89008. * value from the most recently decoded frame header.
  89009. *
  89010. * \param decoder A decoder instance to query.
  89011. * \assert
  89012. * \code decoder != NULL \endcode
  89013. * \retval unsigned
  89014. * See above.
  89015. */
  89016. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89017. /** Get the current blocksize of the stream being decoded.
  89018. * Will only be valid after decoding has started and will contain the
  89019. * value from the most recently decoded frame header.
  89020. *
  89021. * \param decoder A decoder instance to query.
  89022. * \assert
  89023. * \code decoder != NULL \endcode
  89024. * \retval unsigned
  89025. * See above.
  89026. */
  89027. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89028. /** Returns the decoder's current read position within the stream.
  89029. * The position is the byte offset from the start of the stream.
  89030. * Bytes before this position have been fully decoded. Note that
  89031. * there may still be undecoded bytes in the decoder's read FIFO.
  89032. * The returned position is correct even after a seek.
  89033. *
  89034. * \warning This function currently only works for native FLAC,
  89035. * not Ogg FLAC streams.
  89036. *
  89037. * \param decoder A decoder instance to query.
  89038. * \param position Address at which to return the desired position.
  89039. * \assert
  89040. * \code decoder != NULL \endcode
  89041. * \code position != NULL \endcode
  89042. * \retval FLAC__bool
  89043. * \c true if successful, \c false if the stream is not native FLAC,
  89044. * or there was an error from the 'tell' callback or it returned
  89045. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89046. */
  89047. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89048. /** Initialize the decoder instance to decode native FLAC streams.
  89049. *
  89050. * This flavor of initialization sets up the decoder to decode from a
  89051. * native FLAC stream. I/O is performed via callbacks to the client.
  89052. * For decoding from a plain file via filename or open FILE*,
  89053. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89054. * provide a simpler interface.
  89055. *
  89056. * This function should be called after FLAC__stream_decoder_new() and
  89057. * FLAC__stream_decoder_set_*() but before any of the
  89058. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89059. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89060. * if initialization succeeded.
  89061. *
  89062. * \param decoder An uninitialized decoder instance.
  89063. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89064. * pointer must not be \c NULL.
  89065. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89066. * pointer may be \c NULL if seeking is not
  89067. * supported. If \a seek_callback is not \c NULL then a
  89068. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89069. * Alternatively, a dummy seek callback that just
  89070. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89071. * may also be supplied, all though this is slightly
  89072. * less efficient for the decoder.
  89073. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89074. * pointer may be \c NULL if not supported by the client. If
  89075. * \a seek_callback is not \c NULL then a
  89076. * \a tell_callback must also be supplied.
  89077. * Alternatively, a dummy tell callback that just
  89078. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89079. * may also be supplied, all though this is slightly
  89080. * less efficient for the decoder.
  89081. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89082. * pointer may be \c NULL if not supported by the client. If
  89083. * \a seek_callback is not \c NULL then a
  89084. * \a length_callback must also be supplied.
  89085. * Alternatively, a dummy length callback that just
  89086. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89087. * may also be supplied, all though this is slightly
  89088. * less efficient for the decoder.
  89089. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89090. * pointer may be \c NULL if not supported by the client. If
  89091. * \a seek_callback is not \c NULL then a
  89092. * \a eof_callback must also be supplied.
  89093. * Alternatively, a dummy length callback that just
  89094. * returns \c false
  89095. * may also be supplied, all though this is slightly
  89096. * less efficient for the decoder.
  89097. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89098. * pointer must not be \c NULL.
  89099. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89100. * pointer may be \c NULL if the callback is not
  89101. * desired.
  89102. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89103. * pointer must not be \c NULL.
  89104. * \param client_data This value will be supplied to callbacks in their
  89105. * \a client_data argument.
  89106. * \assert
  89107. * \code decoder != NULL \endcode
  89108. * \retval FLAC__StreamDecoderInitStatus
  89109. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89110. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89111. */
  89112. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  89113. FLAC__StreamDecoder *decoder,
  89114. FLAC__StreamDecoderReadCallback read_callback,
  89115. FLAC__StreamDecoderSeekCallback seek_callback,
  89116. FLAC__StreamDecoderTellCallback tell_callback,
  89117. FLAC__StreamDecoderLengthCallback length_callback,
  89118. FLAC__StreamDecoderEofCallback eof_callback,
  89119. FLAC__StreamDecoderWriteCallback write_callback,
  89120. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89121. FLAC__StreamDecoderErrorCallback error_callback,
  89122. void *client_data
  89123. );
  89124. /** Initialize the decoder instance to decode Ogg FLAC streams.
  89125. *
  89126. * This flavor of initialization sets up the decoder to decode from a
  89127. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  89128. * client. For decoding from a plain file via filename or open FILE*,
  89129. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  89130. * provide a simpler interface.
  89131. *
  89132. * This function should be called after FLAC__stream_decoder_new() and
  89133. * FLAC__stream_decoder_set_*() but before any of the
  89134. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89135. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89136. * if initialization succeeded.
  89137. *
  89138. * \note Support for Ogg FLAC in the library is optional. If this
  89139. * library has been built without support for Ogg FLAC, this function
  89140. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89141. *
  89142. * \param decoder An uninitialized decoder instance.
  89143. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89144. * pointer must not be \c NULL.
  89145. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89146. * pointer may be \c NULL if seeking is not
  89147. * supported. If \a seek_callback is not \c NULL then a
  89148. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89149. * Alternatively, a dummy seek callback that just
  89150. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89151. * may also be supplied, all though this is slightly
  89152. * less efficient for the decoder.
  89153. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89154. * pointer may be \c NULL if not supported by the client. If
  89155. * \a seek_callback is not \c NULL then a
  89156. * \a tell_callback must also be supplied.
  89157. * Alternatively, a dummy tell callback that just
  89158. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89159. * may also be supplied, all though this is slightly
  89160. * less efficient for the decoder.
  89161. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89162. * pointer may be \c NULL if not supported by the client. If
  89163. * \a seek_callback is not \c NULL then a
  89164. * \a length_callback must also be supplied.
  89165. * Alternatively, a dummy length callback that just
  89166. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89167. * may also be supplied, all though this is slightly
  89168. * less efficient for the decoder.
  89169. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89170. * pointer may be \c NULL if not supported by the client. If
  89171. * \a seek_callback is not \c NULL then a
  89172. * \a eof_callback must also be supplied.
  89173. * Alternatively, a dummy length callback that just
  89174. * returns \c false
  89175. * may also be supplied, all though this is slightly
  89176. * less efficient for the decoder.
  89177. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89178. * pointer must not be \c NULL.
  89179. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89180. * pointer may be \c NULL if the callback is not
  89181. * desired.
  89182. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89183. * pointer must not be \c NULL.
  89184. * \param client_data This value will be supplied to callbacks in their
  89185. * \a client_data argument.
  89186. * \assert
  89187. * \code decoder != NULL \endcode
  89188. * \retval FLAC__StreamDecoderInitStatus
  89189. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89190. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89191. */
  89192. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  89193. FLAC__StreamDecoder *decoder,
  89194. FLAC__StreamDecoderReadCallback read_callback,
  89195. FLAC__StreamDecoderSeekCallback seek_callback,
  89196. FLAC__StreamDecoderTellCallback tell_callback,
  89197. FLAC__StreamDecoderLengthCallback length_callback,
  89198. FLAC__StreamDecoderEofCallback eof_callback,
  89199. FLAC__StreamDecoderWriteCallback write_callback,
  89200. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89201. FLAC__StreamDecoderErrorCallback error_callback,
  89202. void *client_data
  89203. );
  89204. /** Initialize the decoder instance to decode native FLAC files.
  89205. *
  89206. * This flavor of initialization sets up the decoder to decode from a
  89207. * plain native FLAC file. For non-stdio streams, you must use
  89208. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  89209. *
  89210. * This function should be called after FLAC__stream_decoder_new() and
  89211. * FLAC__stream_decoder_set_*() but before any of the
  89212. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89213. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89214. * if initialization succeeded.
  89215. *
  89216. * \param decoder An uninitialized decoder instance.
  89217. * \param file An open FLAC file. The file should have been
  89218. * opened with mode \c "rb" and rewound. The file
  89219. * becomes owned by the decoder and should not be
  89220. * manipulated by the client while decoding.
  89221. * Unless \a file is \c stdin, it will be closed
  89222. * when FLAC__stream_decoder_finish() is called.
  89223. * Note however that seeking will not work when
  89224. * decoding from \c stdout since it is not seekable.
  89225. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89226. * pointer must not be \c NULL.
  89227. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89228. * pointer may be \c NULL if the callback is not
  89229. * desired.
  89230. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89231. * pointer must not be \c NULL.
  89232. * \param client_data This value will be supplied to callbacks in their
  89233. * \a client_data argument.
  89234. * \assert
  89235. * \code decoder != NULL \endcode
  89236. * \code file != NULL \endcode
  89237. * \retval FLAC__StreamDecoderInitStatus
  89238. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89239. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89240. */
  89241. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  89242. FLAC__StreamDecoder *decoder,
  89243. FILE *file,
  89244. FLAC__StreamDecoderWriteCallback write_callback,
  89245. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89246. FLAC__StreamDecoderErrorCallback error_callback,
  89247. void *client_data
  89248. );
  89249. /** Initialize the decoder instance to decode Ogg FLAC files.
  89250. *
  89251. * This flavor of initialization sets up the decoder to decode from a
  89252. * plain Ogg FLAC file. For non-stdio streams, you must use
  89253. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  89254. *
  89255. * This function should be called after FLAC__stream_decoder_new() and
  89256. * FLAC__stream_decoder_set_*() but before any of the
  89257. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89258. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89259. * if initialization succeeded.
  89260. *
  89261. * \note Support for Ogg FLAC in the library is optional. If this
  89262. * library has been built without support for Ogg FLAC, this function
  89263. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89264. *
  89265. * \param decoder An uninitialized decoder instance.
  89266. * \param file An open FLAC file. The file should have been
  89267. * opened with mode \c "rb" and rewound. The file
  89268. * becomes owned by the decoder and should not be
  89269. * manipulated by the client while decoding.
  89270. * Unless \a file is \c stdin, it will be closed
  89271. * when FLAC__stream_decoder_finish() is called.
  89272. * Note however that seeking will not work when
  89273. * decoding from \c stdout since it is not seekable.
  89274. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89275. * pointer must not be \c NULL.
  89276. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89277. * pointer may be \c NULL if the callback is not
  89278. * desired.
  89279. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89280. * pointer must not be \c NULL.
  89281. * \param client_data This value will be supplied to callbacks in their
  89282. * \a client_data argument.
  89283. * \assert
  89284. * \code decoder != NULL \endcode
  89285. * \code file != NULL \endcode
  89286. * \retval FLAC__StreamDecoderInitStatus
  89287. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89288. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89289. */
  89290. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  89291. FLAC__StreamDecoder *decoder,
  89292. FILE *file,
  89293. FLAC__StreamDecoderWriteCallback write_callback,
  89294. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89295. FLAC__StreamDecoderErrorCallback error_callback,
  89296. void *client_data
  89297. );
  89298. /** Initialize the decoder instance to decode native FLAC files.
  89299. *
  89300. * This flavor of initialization sets up the decoder to decode from a plain
  89301. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89302. * example, with Unicode filenames on Windows), you must use
  89303. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  89304. * and provide callbacks for the I/O.
  89305. *
  89306. * This function should be called after FLAC__stream_decoder_new() and
  89307. * FLAC__stream_decoder_set_*() but before any of the
  89308. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89309. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89310. * if initialization succeeded.
  89311. *
  89312. * \param decoder An uninitialized decoder instance.
  89313. * \param filename The name of the file to decode from. The file will
  89314. * be opened with fopen(). Use \c NULL to decode from
  89315. * \c stdin. Note that \c stdin is not seekable.
  89316. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89317. * pointer must not be \c NULL.
  89318. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89319. * pointer may be \c NULL if the callback is not
  89320. * desired.
  89321. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89322. * pointer must not be \c NULL.
  89323. * \param client_data This value will be supplied to callbacks in their
  89324. * \a client_data argument.
  89325. * \assert
  89326. * \code decoder != NULL \endcode
  89327. * \retval FLAC__StreamDecoderInitStatus
  89328. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89329. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89330. */
  89331. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  89332. FLAC__StreamDecoder *decoder,
  89333. const char *filename,
  89334. FLAC__StreamDecoderWriteCallback write_callback,
  89335. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89336. FLAC__StreamDecoderErrorCallback error_callback,
  89337. void *client_data
  89338. );
  89339. /** Initialize the decoder instance to decode Ogg FLAC files.
  89340. *
  89341. * This flavor of initialization sets up the decoder to decode from a plain
  89342. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89343. * example, with Unicode filenames on Windows), you must use
  89344. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  89345. * and provide callbacks for the I/O.
  89346. *
  89347. * This function should be called after FLAC__stream_decoder_new() and
  89348. * FLAC__stream_decoder_set_*() but before any of the
  89349. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89350. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89351. * if initialization succeeded.
  89352. *
  89353. * \note Support for Ogg FLAC in the library is optional. If this
  89354. * library has been built without support for Ogg FLAC, this function
  89355. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89356. *
  89357. * \param decoder An uninitialized decoder instance.
  89358. * \param filename The name of the file to decode from. The file will
  89359. * be opened with fopen(). Use \c NULL to decode from
  89360. * \c stdin. Note that \c stdin is not seekable.
  89361. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89362. * pointer must not be \c NULL.
  89363. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89364. * pointer may be \c NULL if the callback is not
  89365. * desired.
  89366. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89367. * pointer must not be \c NULL.
  89368. * \param client_data This value will be supplied to callbacks in their
  89369. * \a client_data argument.
  89370. * \assert
  89371. * \code decoder != NULL \endcode
  89372. * \retval FLAC__StreamDecoderInitStatus
  89373. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89374. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89375. */
  89376. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  89377. FLAC__StreamDecoder *decoder,
  89378. const char *filename,
  89379. FLAC__StreamDecoderWriteCallback write_callback,
  89380. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89381. FLAC__StreamDecoderErrorCallback error_callback,
  89382. void *client_data
  89383. );
  89384. /** Finish the decoding process.
  89385. * Flushes the decoding buffer, releases resources, resets the decoder
  89386. * settings to their defaults, and returns the decoder state to
  89387. * FLAC__STREAM_DECODER_UNINITIALIZED.
  89388. *
  89389. * In the event of a prematurely-terminated decode, it is not strictly
  89390. * necessary to call this immediately before FLAC__stream_decoder_delete()
  89391. * but it is good practice to match every FLAC__stream_decoder_init_*()
  89392. * with a FLAC__stream_decoder_finish().
  89393. *
  89394. * \param decoder An uninitialized decoder instance.
  89395. * \assert
  89396. * \code decoder != NULL \endcode
  89397. * \retval FLAC__bool
  89398. * \c false if MD5 checking is on AND a STREAMINFO block was available
  89399. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  89400. * signature does not match the one computed by the decoder; else
  89401. * \c true.
  89402. */
  89403. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  89404. /** Flush the stream input.
  89405. * The decoder's input buffer will be cleared and the state set to
  89406. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  89407. * off MD5 checking.
  89408. *
  89409. * \param decoder A decoder instance.
  89410. * \assert
  89411. * \code decoder != NULL \endcode
  89412. * \retval FLAC__bool
  89413. * \c true if successful, else \c false if a memory allocation
  89414. * error occurs (in which case the state will be set to
  89415. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  89416. */
  89417. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  89418. /** Reset the decoding process.
  89419. * The decoder's input buffer will be cleared and the state set to
  89420. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  89421. * FLAC__stream_decoder_finish() except that the settings are
  89422. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  89423. * before decoding again. MD5 checking will be restored to its original
  89424. * setting.
  89425. *
  89426. * If the decoder is seekable, or was initialized with
  89427. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  89428. * the decoder will also attempt to seek to the beginning of the file.
  89429. * If this rewind fails, this function will return \c false. It follows
  89430. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  89431. * \c stdin.
  89432. *
  89433. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  89434. * and is not seekable (i.e. no seek callback was provided or the seek
  89435. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  89436. * is the duty of the client to start feeding data from the beginning of
  89437. * the stream on the next FLAC__stream_decoder_process() or
  89438. * FLAC__stream_decoder_process_interleaved() call.
  89439. *
  89440. * \param decoder A decoder instance.
  89441. * \assert
  89442. * \code decoder != NULL \endcode
  89443. * \retval FLAC__bool
  89444. * \c true if successful, else \c false if a memory allocation occurs
  89445. * (in which case the state will be set to
  89446. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  89447. * occurs (the state will be unchanged).
  89448. */
  89449. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  89450. /** Decode one metadata block or audio frame.
  89451. * This version instructs the decoder to decode a either a single metadata
  89452. * block or a single frame and stop, unless the callbacks return a fatal
  89453. * error or the read callback returns
  89454. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89455. *
  89456. * As the decoder needs more input it will call the read callback.
  89457. * Depending on what was decoded, the metadata or write callback will be
  89458. * called with the decoded metadata block or audio frame.
  89459. *
  89460. * Unless there is a fatal read error or end of stream, this function
  89461. * will return once one whole frame is decoded. In other words, if the
  89462. * stream is not synchronized or points to a corrupt frame header, the
  89463. * decoder will continue to try and resync until it gets to a valid
  89464. * frame, then decode one frame, then return. If the decoder points to
  89465. * a frame whose frame CRC in the frame footer does not match the
  89466. * computed frame CRC, this function will issue a
  89467. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  89468. * error callback, and return, having decoded one complete, although
  89469. * corrupt, frame. (Such corrupted frames are sent as silence of the
  89470. * correct length to the write callback.)
  89471. *
  89472. * \param decoder An initialized decoder instance.
  89473. * \assert
  89474. * \code decoder != NULL \endcode
  89475. * \retval FLAC__bool
  89476. * \c false if any fatal read, write, or memory allocation error
  89477. * occurred (meaning decoding must stop), else \c true; for more
  89478. * information about the decoder, check the decoder state with
  89479. * FLAC__stream_decoder_get_state().
  89480. */
  89481. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  89482. /** Decode until the end of the metadata.
  89483. * This version instructs the decoder to decode from the current position
  89484. * and continue until all the metadata has been read, or until the
  89485. * callbacks return a fatal error or the read callback returns
  89486. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89487. *
  89488. * As the decoder needs more input it will call the read callback.
  89489. * As each metadata block is decoded, the metadata callback will be called
  89490. * with the decoded metadata.
  89491. *
  89492. * \param decoder An initialized decoder instance.
  89493. * \assert
  89494. * \code decoder != NULL \endcode
  89495. * \retval FLAC__bool
  89496. * \c false if any fatal read, write, or memory allocation error
  89497. * occurred (meaning decoding must stop), else \c true; for more
  89498. * information about the decoder, check the decoder state with
  89499. * FLAC__stream_decoder_get_state().
  89500. */
  89501. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  89502. /** Decode until the end of the stream.
  89503. * This version instructs the decoder to decode from the current position
  89504. * and continue until the end of stream (the read callback returns
  89505. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  89506. * callbacks return a fatal error.
  89507. *
  89508. * As the decoder needs more input it will call the read callback.
  89509. * As each metadata block and frame is decoded, the metadata or write
  89510. * callback will be called with the decoded metadata or frame.
  89511. *
  89512. * \param decoder An initialized decoder instance.
  89513. * \assert
  89514. * \code decoder != NULL \endcode
  89515. * \retval FLAC__bool
  89516. * \c false if any fatal read, write, or memory allocation error
  89517. * occurred (meaning decoding must stop), else \c true; for more
  89518. * information about the decoder, check the decoder state with
  89519. * FLAC__stream_decoder_get_state().
  89520. */
  89521. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  89522. /** Skip one audio frame.
  89523. * This version instructs the decoder to 'skip' a single frame and stop,
  89524. * unless the callbacks return a fatal error or the read callback returns
  89525. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89526. *
  89527. * The decoding flow is the same as what occurs when
  89528. * FLAC__stream_decoder_process_single() is called to process an audio
  89529. * frame, except that this function does not decode the parsed data into
  89530. * PCM or call the write callback. The integrity of the frame is still
  89531. * checked the same way as in the other process functions.
  89532. *
  89533. * This function will return once one whole frame is skipped, in the
  89534. * same way that FLAC__stream_decoder_process_single() will return once
  89535. * one whole frame is decoded.
  89536. *
  89537. * This function can be used in more quickly determining FLAC frame
  89538. * boundaries when decoding of the actual data is not needed, for
  89539. * example when an application is separating a FLAC stream into frames
  89540. * for editing or storing in a container. To do this, the application
  89541. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  89542. * to the next frame, then use
  89543. * FLAC__stream_decoder_get_decode_position() to find the new frame
  89544. * boundary.
  89545. *
  89546. * This function should only be called when the stream has advanced
  89547. * past all the metadata, otherwise it will return \c false.
  89548. *
  89549. * \param decoder An initialized decoder instance not in a metadata
  89550. * state.
  89551. * \assert
  89552. * \code decoder != NULL \endcode
  89553. * \retval FLAC__bool
  89554. * \c false if any fatal read, write, or memory allocation error
  89555. * occurred (meaning decoding must stop), or if the decoder
  89556. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  89557. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  89558. * information about the decoder, check the decoder state with
  89559. * FLAC__stream_decoder_get_state().
  89560. */
  89561. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  89562. /** Flush the input and seek to an absolute sample.
  89563. * Decoding will resume at the given sample. Note that because of
  89564. * this, the next write callback may contain a partial block. The
  89565. * client must support seeking the input or this function will fail
  89566. * and return \c false. Furthermore, if the decoder state is
  89567. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  89568. * with FLAC__stream_decoder_flush() or reset with
  89569. * FLAC__stream_decoder_reset() before decoding can continue.
  89570. *
  89571. * \param decoder A decoder instance.
  89572. * \param sample The target sample number to seek to.
  89573. * \assert
  89574. * \code decoder != NULL \endcode
  89575. * \retval FLAC__bool
  89576. * \c true if successful, else \c false.
  89577. */
  89578. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  89579. /* \} */
  89580. #ifdef __cplusplus
  89581. }
  89582. #endif
  89583. #endif
  89584. /*** End of inlined file: stream_decoder.h ***/
  89585. /*** Start of inlined file: stream_encoder.h ***/
  89586. #ifndef FLAC__STREAM_ENCODER_H
  89587. #define FLAC__STREAM_ENCODER_H
  89588. #include <stdio.h> /* for FILE */
  89589. #ifdef __cplusplus
  89590. extern "C" {
  89591. #endif
  89592. /** \file include/FLAC/stream_encoder.h
  89593. *
  89594. * \brief
  89595. * This module contains the functions which implement the stream
  89596. * encoder.
  89597. *
  89598. * See the detailed documentation in the
  89599. * \link flac_stream_encoder stream encoder \endlink module.
  89600. */
  89601. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  89602. * \ingroup flac
  89603. *
  89604. * \brief
  89605. * This module describes the encoder layers provided by libFLAC.
  89606. *
  89607. * The stream encoder can be used to encode complete streams either to the
  89608. * client via callbacks, or directly to a file, depending on how it is
  89609. * initialized. When encoding via callbacks, the client provides a write
  89610. * callback which will be called whenever FLAC data is ready to be written.
  89611. * If the client also supplies a seek callback, the encoder will also
  89612. * automatically handle the writing back of metadata discovered while
  89613. * encoding, like stream info, seek points offsets, etc. When encoding to
  89614. * a file, the client needs only supply a filename or open \c FILE* and an
  89615. * optional progress callback for periodic notification of progress; the
  89616. * write and seek callbacks are supplied internally. For more info see the
  89617. * \link flac_stream_encoder stream encoder \endlink module.
  89618. */
  89619. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  89620. * \ingroup flac_encoder
  89621. *
  89622. * \brief
  89623. * This module contains the functions which implement the stream
  89624. * encoder.
  89625. *
  89626. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  89627. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89628. *
  89629. * The basic usage of this encoder is as follows:
  89630. * - The program creates an instance of an encoder using
  89631. * FLAC__stream_encoder_new().
  89632. * - The program overrides the default settings using
  89633. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  89634. * functions should be called:
  89635. * - FLAC__stream_encoder_set_channels()
  89636. * - FLAC__stream_encoder_set_bits_per_sample()
  89637. * - FLAC__stream_encoder_set_sample_rate()
  89638. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  89639. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  89640. * - If the application wants to control the compression level or set its own
  89641. * metadata, then the following should also be called:
  89642. * - FLAC__stream_encoder_set_compression_level()
  89643. * - FLAC__stream_encoder_set_verify()
  89644. * - FLAC__stream_encoder_set_metadata()
  89645. * - The rest of the set functions should only be called if the client needs
  89646. * exact control over how the audio is compressed; thorough understanding
  89647. * of the FLAC format is necessary to achieve good results.
  89648. * - The program initializes the instance to validate the settings and
  89649. * prepare for encoding using
  89650. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  89651. * or FLAC__stream_encoder_init_file() for native FLAC
  89652. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  89653. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  89654. * - The program calls FLAC__stream_encoder_process() or
  89655. * FLAC__stream_encoder_process_interleaved() to encode data, which
  89656. * subsequently calls the callbacks when there is encoder data ready
  89657. * to be written.
  89658. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  89659. * which causes the encoder to encode any data still in its input pipe,
  89660. * update the metadata with the final encoding statistics if output
  89661. * seeking is possible, and finally reset the encoder to the
  89662. * uninitialized state.
  89663. * - The instance may be used again or deleted with
  89664. * FLAC__stream_encoder_delete().
  89665. *
  89666. * In more detail, the stream encoder functions similarly to the
  89667. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  89668. * callbacks and more options. Typically the client will create a new
  89669. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  89670. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  89671. * calling one of the FLAC__stream_encoder_init_*() functions.
  89672. *
  89673. * Unlike the decoders, the stream encoder has many options that can
  89674. * affect the speed and compression ratio. When setting these parameters
  89675. * you should have some basic knowledge of the format (see the
  89676. * <A HREF="../documentation.html#format">user-level documentation</A>
  89677. * or the <A HREF="../format.html">formal description</A>). The
  89678. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  89679. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  89680. * functions will do this, so make sure to pay attention to the state
  89681. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  89682. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  89683. * before FLAC__stream_encoder_init_*() will take on the defaults from
  89684. * the constructor.
  89685. *
  89686. * There are three initialization functions for native FLAC, one for
  89687. * setting up the encoder to encode FLAC data to the client via
  89688. * callbacks, and two for encoding directly to a file.
  89689. *
  89690. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  89691. * You must also supply a write callback which will be called anytime
  89692. * there is raw encoded data to write. If the client can seek the output
  89693. * it is best to also supply seek and tell callbacks, as this allows the
  89694. * encoder to go back after encoding is finished to write back
  89695. * information that was collected while encoding, like seek point offsets,
  89696. * frame sizes, etc.
  89697. *
  89698. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  89699. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  89700. * filename or open \c FILE*; the encoder will handle all the callbacks
  89701. * internally. You may also supply a progress callback for periodic
  89702. * notification of the encoding progress.
  89703. *
  89704. * There are three similarly-named init functions for encoding to Ogg
  89705. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89706. * library has been built with Ogg support.
  89707. *
  89708. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  89709. * call the write callback several times, once with the \c fLaC signature,
  89710. * and once for each encoded metadata block. Note that for Ogg FLAC
  89711. * encoding you will usually get at least twice the number of callbacks than
  89712. * with native FLAC, one for the Ogg page header and one for the page body.
  89713. *
  89714. * After initializing the instance, the client may feed audio data to the
  89715. * encoder in one of two ways:
  89716. *
  89717. * - Channel separate, through FLAC__stream_encoder_process() - The client
  89718. * will pass an array of pointers to buffers, one for each channel, to
  89719. * the encoder, each of the same length. The samples need not be
  89720. * block-aligned, but each channel should have the same number of samples.
  89721. * - Channel interleaved, through
  89722. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  89723. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  89724. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  89725. * Again, the samples need not be block-aligned but they must be
  89726. * sample-aligned, i.e. the first value should be channel0_sample0 and
  89727. * the last value channelN_sampleM.
  89728. *
  89729. * Note that for either process call, each sample in the buffers should be a
  89730. * signed integer, right-justified to the resolution set by
  89731. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  89732. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  89733. *
  89734. * When the client is finished encoding data, it calls
  89735. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  89736. * data still in its input pipe, and call the metadata callback with the
  89737. * final encoding statistics. Then the instance may be deleted with
  89738. * FLAC__stream_encoder_delete() or initialized again to encode another
  89739. * stream.
  89740. *
  89741. * For programs that write their own metadata, but that do not know the
  89742. * actual metadata until after encoding, it is advantageous to instruct
  89743. * the encoder to write a PADDING block of the correct size, so that
  89744. * instead of rewriting the whole stream after encoding, the program can
  89745. * just overwrite the PADDING block. If only the maximum size of the
  89746. * metadata is known, the program can write a slightly larger padding
  89747. * block, then split it after encoding.
  89748. *
  89749. * Make sure you understand how lengths are calculated. All FLAC metadata
  89750. * blocks have a 4 byte header which contains the type and length. This
  89751. * length does not include the 4 bytes of the header. See the format page
  89752. * for the specification of metadata blocks and their lengths.
  89753. *
  89754. * \note
  89755. * If you are writing the FLAC data to a file via callbacks, make sure it
  89756. * is open for update (e.g. mode "w+" for stdio streams). This is because
  89757. * after the first encoding pass, the encoder will try to seek back to the
  89758. * beginning of the stream, to the STREAMINFO block, to write some data
  89759. * there. (If using FLAC__stream_encoder_init*_file() or
  89760. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  89761. *
  89762. * \note
  89763. * The "set" functions may only be called when the encoder is in the
  89764. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  89765. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  89766. * before FLAC__stream_encoder_init_*(). If this is the case they will
  89767. * return \c true, otherwise \c false.
  89768. *
  89769. * \note
  89770. * FLAC__stream_encoder_finish() resets all settings to the constructor
  89771. * defaults.
  89772. *
  89773. * \{
  89774. */
  89775. /** State values for a FLAC__StreamEncoder.
  89776. *
  89777. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  89778. *
  89779. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  89780. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  89781. * must be deleted with FLAC__stream_encoder_delete().
  89782. */
  89783. typedef enum {
  89784. FLAC__STREAM_ENCODER_OK = 0,
  89785. /**< The encoder is in the normal OK state and samples can be processed. */
  89786. FLAC__STREAM_ENCODER_UNINITIALIZED,
  89787. /**< The encoder is in the uninitialized state; one of the
  89788. * FLAC__stream_encoder_init_*() functions must be called before samples
  89789. * can be processed.
  89790. */
  89791. FLAC__STREAM_ENCODER_OGG_ERROR,
  89792. /**< An error occurred in the underlying Ogg layer. */
  89793. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  89794. /**< An error occurred in the underlying verify stream decoder;
  89795. * check FLAC__stream_encoder_get_verify_decoder_state().
  89796. */
  89797. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  89798. /**< The verify decoder detected a mismatch between the original
  89799. * audio signal and the decoded audio signal.
  89800. */
  89801. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  89802. /**< One of the callbacks returned a fatal error. */
  89803. FLAC__STREAM_ENCODER_IO_ERROR,
  89804. /**< An I/O error occurred while opening/reading/writing a file.
  89805. * Check \c errno.
  89806. */
  89807. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  89808. /**< An error occurred while writing the stream; usually, the
  89809. * write_callback returned an error.
  89810. */
  89811. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  89812. /**< Memory allocation failed. */
  89813. } FLAC__StreamEncoderState;
  89814. /** Maps a FLAC__StreamEncoderState to a C string.
  89815. *
  89816. * Using a FLAC__StreamEncoderState as the index to this array
  89817. * will give the string equivalent. The contents should not be modified.
  89818. */
  89819. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  89820. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  89821. */
  89822. typedef enum {
  89823. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  89824. /**< Initialization was successful. */
  89825. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  89826. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  89827. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89828. /**< The library was not compiled with support for the given container
  89829. * format.
  89830. */
  89831. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  89832. /**< A required callback was not supplied. */
  89833. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  89834. /**< The encoder has an invalid setting for number of channels. */
  89835. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  89836. /**< The encoder has an invalid setting for bits-per-sample.
  89837. * FLAC supports 4-32 bps but the reference encoder currently supports
  89838. * only up to 24 bps.
  89839. */
  89840. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  89841. /**< The encoder has an invalid setting for the input sample rate. */
  89842. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  89843. /**< The encoder has an invalid setting for the block size. */
  89844. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  89845. /**< The encoder has an invalid setting for the maximum LPC order. */
  89846. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  89847. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  89848. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  89849. /**< The specified block size is less than the maximum LPC order. */
  89850. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  89851. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  89852. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  89853. /**< The metadata input to the encoder is invalid, in one of the following ways:
  89854. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  89855. * - One of the metadata blocks contains an undefined type
  89856. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  89857. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  89858. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  89859. */
  89860. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  89861. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  89862. * already initialized, usually because
  89863. * FLAC__stream_encoder_finish() was not called.
  89864. */
  89865. } FLAC__StreamEncoderInitStatus;
  89866. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  89867. *
  89868. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  89869. * will give the string equivalent. The contents should not be modified.
  89870. */
  89871. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  89872. /** Return values for the FLAC__StreamEncoder read callback.
  89873. */
  89874. typedef enum {
  89875. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  89876. /**< The read was OK and decoding can continue. */
  89877. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  89878. /**< The read was attempted at the end of the stream. */
  89879. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  89880. /**< An unrecoverable error occurred. */
  89881. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  89882. /**< Client does not support reading back from the output. */
  89883. } FLAC__StreamEncoderReadStatus;
  89884. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  89885. *
  89886. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  89887. * will give the string equivalent. The contents should not be modified.
  89888. */
  89889. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  89890. /** Return values for the FLAC__StreamEncoder write callback.
  89891. */
  89892. typedef enum {
  89893. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  89894. /**< The write was OK and encoding can continue. */
  89895. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  89896. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  89897. } FLAC__StreamEncoderWriteStatus;
  89898. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  89899. *
  89900. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  89901. * will give the string equivalent. The contents should not be modified.
  89902. */
  89903. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  89904. /** Return values for the FLAC__StreamEncoder seek callback.
  89905. */
  89906. typedef enum {
  89907. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  89908. /**< The seek was OK and encoding can continue. */
  89909. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  89910. /**< An unrecoverable error occurred. */
  89911. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  89912. /**< Client does not support seeking. */
  89913. } FLAC__StreamEncoderSeekStatus;
  89914. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  89915. *
  89916. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  89917. * will give the string equivalent. The contents should not be modified.
  89918. */
  89919. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  89920. /** Return values for the FLAC__StreamEncoder tell callback.
  89921. */
  89922. typedef enum {
  89923. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  89924. /**< The tell was OK and encoding can continue. */
  89925. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  89926. /**< An unrecoverable error occurred. */
  89927. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  89928. /**< Client does not support seeking. */
  89929. } FLAC__StreamEncoderTellStatus;
  89930. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  89931. *
  89932. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  89933. * will give the string equivalent. The contents should not be modified.
  89934. */
  89935. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  89936. /***********************************************************************
  89937. *
  89938. * class FLAC__StreamEncoder
  89939. *
  89940. ***********************************************************************/
  89941. struct FLAC__StreamEncoderProtected;
  89942. struct FLAC__StreamEncoderPrivate;
  89943. /** The opaque structure definition for the stream encoder type.
  89944. * See the \link flac_stream_encoder stream encoder module \endlink
  89945. * for a detailed description.
  89946. */
  89947. typedef struct {
  89948. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89949. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89950. } FLAC__StreamEncoder;
  89951. /** Signature for the read callback.
  89952. *
  89953. * A function pointer matching this signature must be passed to
  89954. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  89955. * The supplied function will be called when the encoder needs to read back
  89956. * encoded data. This happens during the metadata callback, when the encoder
  89957. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  89958. * while encoding. The address of the buffer to be filled is supplied, along
  89959. * with the number of bytes the buffer can hold. The callback may choose to
  89960. * supply less data and modify the byte count but must be careful not to
  89961. * overflow the buffer. The callback then returns a status code chosen from
  89962. * FLAC__StreamEncoderReadStatus.
  89963. *
  89964. * Here is an example of a read callback for stdio streams:
  89965. * \code
  89966. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89967. * {
  89968. * FILE *file = ((MyClientData*)client_data)->file;
  89969. * if(*bytes > 0) {
  89970. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89971. * if(ferror(file))
  89972. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  89973. * else if(*bytes == 0)
  89974. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  89975. * else
  89976. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  89977. * }
  89978. * else
  89979. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  89980. * }
  89981. * \endcode
  89982. *
  89983. * \note In general, FLAC__StreamEncoder functions which change the
  89984. * state should not be called on the \a encoder while in the callback.
  89985. *
  89986. * \param encoder The encoder instance calling the callback.
  89987. * \param buffer A pointer to a location for the callee to store
  89988. * data to be encoded.
  89989. * \param bytes A pointer to the size of the buffer. On entry
  89990. * to the callback, it contains the maximum number
  89991. * of bytes that may be stored in \a buffer. The
  89992. * callee must set it to the actual number of bytes
  89993. * stored (0 in case of error or end-of-stream) before
  89994. * returning.
  89995. * \param client_data The callee's client data set through
  89996. * FLAC__stream_encoder_set_client_data().
  89997. * \retval FLAC__StreamEncoderReadStatus
  89998. * The callee's return status.
  89999. */
  90000. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90001. /** Signature for the write callback.
  90002. *
  90003. * A function pointer matching this signature must be passed to
  90004. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90005. * by the encoder anytime there is raw encoded data ready to write. It may
  90006. * include metadata mixed with encoded audio frames and the data is not
  90007. * guaranteed to be aligned on frame or metadata block boundaries.
  90008. *
  90009. * The only duty of the callback is to write out the \a bytes worth of data
  90010. * in \a buffer to the current position in the output stream. The arguments
  90011. * \a samples and \a current_frame are purely informational. If \a samples
  90012. * is greater than \c 0, then \a current_frame will hold the current frame
  90013. * number that is being written; otherwise it indicates that the write
  90014. * callback is being called to write metadata.
  90015. *
  90016. * \note
  90017. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90018. * write callback will be called twice when writing each audio
  90019. * frame; once for the page header, and once for the page body.
  90020. * When writing the page header, the \a samples argument to the
  90021. * write callback will be \c 0.
  90022. *
  90023. * \note In general, FLAC__StreamEncoder functions which change the
  90024. * state should not be called on the \a encoder while in the callback.
  90025. *
  90026. * \param encoder The encoder instance calling the callback.
  90027. * \param buffer An array of encoded data of length \a bytes.
  90028. * \param bytes The byte length of \a buffer.
  90029. * \param samples The number of samples encoded by \a buffer.
  90030. * \c 0 has a special meaning; see above.
  90031. * \param current_frame The number of the current frame being encoded.
  90032. * \param client_data The callee's client data set through
  90033. * FLAC__stream_encoder_init_*().
  90034. * \retval FLAC__StreamEncoderWriteStatus
  90035. * The callee's return status.
  90036. */
  90037. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90038. /** Signature for the seek callback.
  90039. *
  90040. * A function pointer matching this signature may be passed to
  90041. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90042. * when the encoder needs to seek the output stream. The encoder will pass
  90043. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90044. *
  90045. * Here is an example of a seek callback for stdio streams:
  90046. * \code
  90047. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90048. * {
  90049. * FILE *file = ((MyClientData*)client_data)->file;
  90050. * if(file == stdin)
  90051. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90052. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90053. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90054. * else
  90055. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90056. * }
  90057. * \endcode
  90058. *
  90059. * \note In general, FLAC__StreamEncoder functions which change the
  90060. * state should not be called on the \a encoder while in the callback.
  90061. *
  90062. * \param encoder The encoder instance calling the callback.
  90063. * \param absolute_byte_offset The offset from the beginning of the stream
  90064. * to seek to.
  90065. * \param client_data The callee's client data set through
  90066. * FLAC__stream_encoder_init_*().
  90067. * \retval FLAC__StreamEncoderSeekStatus
  90068. * The callee's return status.
  90069. */
  90070. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90071. /** Signature for the tell callback.
  90072. *
  90073. * A function pointer matching this signature may be passed to
  90074. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90075. * when the encoder needs to know the current position of the output stream.
  90076. *
  90077. * \warning
  90078. * The callback must return the true current byte offset of the output to
  90079. * which the encoder is writing. If you are buffering the output, make
  90080. * sure and take this into account. If you are writing directly to a
  90081. * FILE* from your write callback, ftell() is sufficient. If you are
  90082. * writing directly to a file descriptor from your write callback, you
  90083. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90084. * these points to rewrite metadata after encoding.
  90085. *
  90086. * Here is an example of a tell callback for stdio streams:
  90087. * \code
  90088. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90089. * {
  90090. * FILE *file = ((MyClientData*)client_data)->file;
  90091. * off_t pos;
  90092. * if(file == stdin)
  90093. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90094. * else if((pos = ftello(file)) < 0)
  90095. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90096. * else {
  90097. * *absolute_byte_offset = (FLAC__uint64)pos;
  90098. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90099. * }
  90100. * }
  90101. * \endcode
  90102. *
  90103. * \note In general, FLAC__StreamEncoder functions which change the
  90104. * state should not be called on the \a encoder while in the callback.
  90105. *
  90106. * \param encoder The encoder instance calling the callback.
  90107. * \param absolute_byte_offset The address at which to store the current
  90108. * position of the output.
  90109. * \param client_data The callee's client data set through
  90110. * FLAC__stream_encoder_init_*().
  90111. * \retval FLAC__StreamEncoderTellStatus
  90112. * The callee's return status.
  90113. */
  90114. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90115. /** Signature for the metadata callback.
  90116. *
  90117. * A function pointer matching this signature may be passed to
  90118. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90119. * once at the end of encoding with the populated STREAMINFO structure. This
  90120. * is so the client can seek back to the beginning of the file and write the
  90121. * STREAMINFO block with the correct statistics after encoding (like
  90122. * minimum/maximum frame size and total samples).
  90123. *
  90124. * \note In general, FLAC__StreamEncoder functions which change the
  90125. * state should not be called on the \a encoder while in the callback.
  90126. *
  90127. * \param encoder The encoder instance calling the callback.
  90128. * \param metadata The final populated STREAMINFO block.
  90129. * \param client_data The callee's client data set through
  90130. * FLAC__stream_encoder_init_*().
  90131. */
  90132. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90133. /** Signature for the progress callback.
  90134. *
  90135. * A function pointer matching this signature may be passed to
  90136. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  90137. * The supplied function will be called when the encoder has finished
  90138. * writing a frame. The \c total_frames_estimate argument to the
  90139. * callback will be based on the value from
  90140. * FLAC__stream_encoder_set_total_samples_estimate().
  90141. *
  90142. * \note In general, FLAC__StreamEncoder functions which change the
  90143. * state should not be called on the \a encoder while in the callback.
  90144. *
  90145. * \param encoder The encoder instance calling the callback.
  90146. * \param bytes_written Bytes written so far.
  90147. * \param samples_written Samples written so far.
  90148. * \param frames_written Frames written so far.
  90149. * \param total_frames_estimate The estimate of the total number of
  90150. * frames to be written.
  90151. * \param client_data The callee's client data set through
  90152. * FLAC__stream_encoder_init_*().
  90153. */
  90154. typedef void (*FLAC__StreamEncoderProgressCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
  90155. /***********************************************************************
  90156. *
  90157. * Class constructor/destructor
  90158. *
  90159. ***********************************************************************/
  90160. /** Create a new stream encoder instance. The instance is created with
  90161. * default settings; see the individual FLAC__stream_encoder_set_*()
  90162. * functions for each setting's default.
  90163. *
  90164. * \retval FLAC__StreamEncoder*
  90165. * \c NULL if there was an error allocating memory, else the new instance.
  90166. */
  90167. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  90168. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  90169. *
  90170. * \param encoder A pointer to an existing encoder.
  90171. * \assert
  90172. * \code encoder != NULL \endcode
  90173. */
  90174. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  90175. /***********************************************************************
  90176. *
  90177. * Public class method prototypes
  90178. *
  90179. ***********************************************************************/
  90180. /** Set the serial number for the FLAC stream to use in the Ogg container.
  90181. *
  90182. * \note
  90183. * This does not need to be set for native FLAC encoding.
  90184. *
  90185. * \note
  90186. * It is recommended to set a serial number explicitly as the default of '0'
  90187. * may collide with other streams.
  90188. *
  90189. * \default \c 0
  90190. * \param encoder An encoder instance to set.
  90191. * \param serial_number See above.
  90192. * \assert
  90193. * \code encoder != NULL \endcode
  90194. * \retval FLAC__bool
  90195. * \c false if the encoder is already initialized, else \c true.
  90196. */
  90197. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  90198. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  90199. * encoded output by feeding it through an internal decoder and comparing
  90200. * the original signal against the decoded signal. If a mismatch occurs,
  90201. * the process call will return \c false. Note that this will slow the
  90202. * encoding process by the extra time required for decoding and comparison.
  90203. *
  90204. * \default \c false
  90205. * \param encoder An encoder instance to set.
  90206. * \param value Flag value (see above).
  90207. * \assert
  90208. * \code encoder != NULL \endcode
  90209. * \retval FLAC__bool
  90210. * \c false if the encoder is already initialized, else \c true.
  90211. */
  90212. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90213. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  90214. * the encoder will comply with the Subset and will check the
  90215. * settings during FLAC__stream_encoder_init_*() to see if all settings
  90216. * comply. If \c false, the settings may take advantage of the full
  90217. * range that the format allows.
  90218. *
  90219. * Make sure you know what it entails before setting this to \c false.
  90220. *
  90221. * \default \c true
  90222. * \param encoder An encoder instance to set.
  90223. * \param value Flag value (see above).
  90224. * \assert
  90225. * \code encoder != NULL \endcode
  90226. * \retval FLAC__bool
  90227. * \c false if the encoder is already initialized, else \c true.
  90228. */
  90229. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90230. /** Set the number of channels to be encoded.
  90231. *
  90232. * \default \c 2
  90233. * \param encoder An encoder instance to set.
  90234. * \param value See above.
  90235. * \assert
  90236. * \code encoder != NULL \endcode
  90237. * \retval FLAC__bool
  90238. * \c false if the encoder is already initialized, else \c true.
  90239. */
  90240. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  90241. /** Set the sample resolution of the input to be encoded.
  90242. *
  90243. * \warning
  90244. * Do not feed the encoder data that is wider than the value you
  90245. * set here or you will generate an invalid stream.
  90246. *
  90247. * \default \c 16
  90248. * \param encoder An encoder instance to set.
  90249. * \param value See above.
  90250. * \assert
  90251. * \code encoder != NULL \endcode
  90252. * \retval FLAC__bool
  90253. * \c false if the encoder is already initialized, else \c true.
  90254. */
  90255. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  90256. /** Set the sample rate (in Hz) of the input to be encoded.
  90257. *
  90258. * \default \c 44100
  90259. * \param encoder An encoder instance to set.
  90260. * \param value See above.
  90261. * \assert
  90262. * \code encoder != NULL \endcode
  90263. * \retval FLAC__bool
  90264. * \c false if the encoder is already initialized, else \c true.
  90265. */
  90266. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  90267. /** Set the compression level
  90268. *
  90269. * The compression level is roughly proportional to the amount of effort
  90270. * the encoder expends to compress the file. A higher level usually
  90271. * means more computation but higher compression. The default level is
  90272. * suitable for most applications.
  90273. *
  90274. * Currently the levels range from \c 0 (fastest, least compression) to
  90275. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  90276. * treated as \c 8.
  90277. *
  90278. * This function automatically calls the following other \c _set_
  90279. * functions with appropriate values, so the client does not need to
  90280. * unless it specifically wants to override them:
  90281. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  90282. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  90283. * - FLAC__stream_encoder_set_apodization()
  90284. * - FLAC__stream_encoder_set_max_lpc_order()
  90285. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  90286. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  90287. * - FLAC__stream_encoder_set_do_escape_coding()
  90288. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  90289. * - FLAC__stream_encoder_set_min_residual_partition_order()
  90290. * - FLAC__stream_encoder_set_max_residual_partition_order()
  90291. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  90292. *
  90293. * The actual values set for each level are:
  90294. * <table>
  90295. * <tr>
  90296. * <td><b>level</b><td>
  90297. * <td>do mid-side stereo<td>
  90298. * <td>loose mid-side stereo<td>
  90299. * <td>apodization<td>
  90300. * <td>max lpc order<td>
  90301. * <td>qlp coeff precision<td>
  90302. * <td>qlp coeff prec search<td>
  90303. * <td>escape coding<td>
  90304. * <td>exhaustive model search<td>
  90305. * <td>min residual partition order<td>
  90306. * <td>max residual partition order<td>
  90307. * <td>rice parameter search dist<td>
  90308. * </tr>
  90309. * <tr> <td><b>0</b><td> <td>false<td> <td>false<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  90310. * <tr> <td><b>1</b><td> <td>true<td> <td>true<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  90311. * <tr> <td><b>2</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  90312. * <tr> <td><b>3</b><td> <td>false<td> <td>false<td> <td>tukey(0.5)<td> <td>6<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>4<td> <td>0<td> </tr>
  90313. * <tr> <td><b>4</b><td> <td>true<td> <td>true<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>4<td> <td>0<td> </tr>
  90314. * <tr> <td><b>5</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>5<td> <td>0<td> </tr>
  90315. * <tr> <td><b>6</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  90316. * <tr> <td><b>7</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>true<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  90317. * <tr> <td><b>8</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>12<td> <td>0<td> <td>false<td> <td>false<td> <td>true<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  90318. * </table>
  90319. *
  90320. * \default \c 5
  90321. * \param encoder An encoder instance to set.
  90322. * \param value See above.
  90323. * \assert
  90324. * \code encoder != NULL \endcode
  90325. * \retval FLAC__bool
  90326. * \c false if the encoder is already initialized, else \c true.
  90327. */
  90328. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  90329. /** Set the blocksize to use while encoding.
  90330. *
  90331. * The number of samples to use per frame. Use \c 0 to let the encoder
  90332. * estimate a blocksize; this is usually best.
  90333. *
  90334. * \default \c 0
  90335. * \param encoder An encoder instance to set.
  90336. * \param value See above.
  90337. * \assert
  90338. * \code encoder != NULL \endcode
  90339. * \retval FLAC__bool
  90340. * \c false if the encoder is already initialized, else \c true.
  90341. */
  90342. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  90343. /** Set to \c true to enable mid-side encoding on stereo input. The
  90344. * number of channels must be 2 for this to have any effect. Set to
  90345. * \c false to use only independent channel coding.
  90346. *
  90347. * \default \c false
  90348. * \param encoder An encoder instance to set.
  90349. * \param value Flag value (see above).
  90350. * \assert
  90351. * \code encoder != NULL \endcode
  90352. * \retval FLAC__bool
  90353. * \c false if the encoder is already initialized, else \c true.
  90354. */
  90355. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90356. /** Set to \c true to enable adaptive switching between mid-side and
  90357. * left-right encoding on stereo input. Set to \c false to use
  90358. * exhaustive searching. Setting this to \c true requires
  90359. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  90360. * \c true in order to have any effect.
  90361. *
  90362. * \default \c false
  90363. * \param encoder An encoder instance to set.
  90364. * \param value Flag value (see above).
  90365. * \assert
  90366. * \code encoder != NULL \endcode
  90367. * \retval FLAC__bool
  90368. * \c false if the encoder is already initialized, else \c true.
  90369. */
  90370. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90371. /** Sets the apodization function(s) the encoder will use when windowing
  90372. * audio data for LPC analysis.
  90373. *
  90374. * The \a specification is a plain ASCII string which specifies exactly
  90375. * which functions to use. There may be more than one (up to 32),
  90376. * separated by \c ';' characters. Some functions take one or more
  90377. * comma-separated arguments in parentheses.
  90378. *
  90379. * The available functions are \c bartlett, \c bartlett_hann,
  90380. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  90381. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  90382. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  90383. *
  90384. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  90385. * (0<STDDEV<=0.5).
  90386. *
  90387. * For \c tukey(P), P specifies the fraction of the window that is
  90388. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  90389. * corresponds to \c hann.
  90390. *
  90391. * Example specifications are \c "blackman" or
  90392. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  90393. *
  90394. * Any function that is specified erroneously is silently dropped. Up
  90395. * to 32 functions are kept, the rest are dropped. If the specification
  90396. * is empty the encoder defaults to \c "tukey(0.5)".
  90397. *
  90398. * When more than one function is specified, then for every subframe the
  90399. * encoder will try each of them separately and choose the window that
  90400. * results in the smallest compressed subframe.
  90401. *
  90402. * Note that each function specified causes the encoder to occupy a
  90403. * floating point array in which to store the window.
  90404. *
  90405. * \default \c "tukey(0.5)"
  90406. * \param encoder An encoder instance to set.
  90407. * \param specification See above.
  90408. * \assert
  90409. * \code encoder != NULL \endcode
  90410. * \code specification != NULL \endcode
  90411. * \retval FLAC__bool
  90412. * \c false if the encoder is already initialized, else \c true.
  90413. */
  90414. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  90415. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  90416. *
  90417. * \default \c 0
  90418. * \param encoder An encoder instance to set.
  90419. * \param value See above.
  90420. * \assert
  90421. * \code encoder != NULL \endcode
  90422. * \retval FLAC__bool
  90423. * \c false if the encoder is already initialized, else \c true.
  90424. */
  90425. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  90426. /** Set the precision, in bits, of the quantized linear predictor
  90427. * coefficients, or \c 0 to let the encoder select it based on the
  90428. * blocksize.
  90429. *
  90430. * \note
  90431. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  90432. * be less than 32.
  90433. *
  90434. * \default \c 0
  90435. * \param encoder An encoder instance to set.
  90436. * \param value See above.
  90437. * \assert
  90438. * \code encoder != NULL \endcode
  90439. * \retval FLAC__bool
  90440. * \c false if the encoder is already initialized, else \c true.
  90441. */
  90442. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  90443. /** Set to \c false to use only the specified quantized linear predictor
  90444. * coefficient precision, or \c true to search neighboring precision
  90445. * values and use the best one.
  90446. *
  90447. * \default \c false
  90448. * \param encoder An encoder instance to set.
  90449. * \param value See above.
  90450. * \assert
  90451. * \code encoder != NULL \endcode
  90452. * \retval FLAC__bool
  90453. * \c false if the encoder is already initialized, else \c true.
  90454. */
  90455. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90456. /** Deprecated. Setting this value has no effect.
  90457. *
  90458. * \default \c false
  90459. * \param encoder An encoder instance to set.
  90460. * \param value See above.
  90461. * \assert
  90462. * \code encoder != NULL \endcode
  90463. * \retval FLAC__bool
  90464. * \c false if the encoder is already initialized, else \c true.
  90465. */
  90466. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90467. /** Set to \c false to let the encoder estimate the best model order
  90468. * based on the residual signal energy, or \c true to force the
  90469. * encoder to evaluate all order models and select the best.
  90470. *
  90471. * \default \c false
  90472. * \param encoder An encoder instance to set.
  90473. * \param value See above.
  90474. * \assert
  90475. * \code encoder != NULL \endcode
  90476. * \retval FLAC__bool
  90477. * \c false if the encoder is already initialized, else \c true.
  90478. */
  90479. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90480. /** Set the minimum partition order to search when coding the residual.
  90481. * This is used in tandem with
  90482. * FLAC__stream_encoder_set_max_residual_partition_order().
  90483. *
  90484. * The partition order determines the context size in the residual.
  90485. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  90486. *
  90487. * Set both min and max values to \c 0 to force a single context,
  90488. * whose Rice parameter is based on the residual signal variance.
  90489. * Otherwise, set a min and max order, and the encoder will search
  90490. * all orders, using the mean of each context for its Rice parameter,
  90491. * and use the best.
  90492. *
  90493. * \default \c 0
  90494. * \param encoder An encoder instance to set.
  90495. * \param value See above.
  90496. * \assert
  90497. * \code encoder != NULL \endcode
  90498. * \retval FLAC__bool
  90499. * \c false if the encoder is already initialized, else \c true.
  90500. */
  90501. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  90502. /** Set the maximum partition order to search when coding the residual.
  90503. * This is used in tandem with
  90504. * FLAC__stream_encoder_set_min_residual_partition_order().
  90505. *
  90506. * The partition order determines the context size in the residual.
  90507. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  90508. *
  90509. * Set both min and max values to \c 0 to force a single context,
  90510. * whose Rice parameter is based on the residual signal variance.
  90511. * Otherwise, set a min and max order, and the encoder will search
  90512. * all orders, using the mean of each context for its Rice parameter,
  90513. * and use the best.
  90514. *
  90515. * \default \c 0
  90516. * \param encoder An encoder instance to set.
  90517. * \param value See above.
  90518. * \assert
  90519. * \code encoder != NULL \endcode
  90520. * \retval FLAC__bool
  90521. * \c false if the encoder is already initialized, else \c true.
  90522. */
  90523. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  90524. /** Deprecated. Setting this value has no effect.
  90525. *
  90526. * \default \c 0
  90527. * \param encoder An encoder instance to set.
  90528. * \param value See above.
  90529. * \assert
  90530. * \code encoder != NULL \endcode
  90531. * \retval FLAC__bool
  90532. * \c false if the encoder is already initialized, else \c true.
  90533. */
  90534. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  90535. /** Set an estimate of the total samples that will be encoded.
  90536. * This is merely an estimate and may be set to \c 0 if unknown.
  90537. * This value will be written to the STREAMINFO block before encoding,
  90538. * and can remove the need for the caller to rewrite the value later
  90539. * if the value is known before encoding.
  90540. *
  90541. * \default \c 0
  90542. * \param encoder An encoder instance to set.
  90543. * \param value See above.
  90544. * \assert
  90545. * \code encoder != NULL \endcode
  90546. * \retval FLAC__bool
  90547. * \c false if the encoder is already initialized, else \c true.
  90548. */
  90549. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  90550. /** Set the metadata blocks to be emitted to the stream before encoding.
  90551. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  90552. * array of pointers to metadata blocks. The array is non-const since
  90553. * the encoder may need to change the \a is_last flag inside them, and
  90554. * in some cases update seek point offsets. Otherwise, the encoder will
  90555. * not modify or free the blocks. It is up to the caller to free the
  90556. * metadata blocks after encoding finishes.
  90557. *
  90558. * \note
  90559. * The encoder stores only copies of the pointers in the \a metadata array;
  90560. * the metadata blocks themselves must survive at least until after
  90561. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  90562. *
  90563. * \note
  90564. * The STREAMINFO block is always written and no STREAMINFO block may
  90565. * occur in the supplied array.
  90566. *
  90567. * \note
  90568. * By default the encoder does not create a SEEKTABLE. If one is supplied
  90569. * in the \a metadata array, but the client has specified that it does not
  90570. * support seeking, then the SEEKTABLE will be written verbatim. However
  90571. * by itself this is not very useful as the client will not know the stream
  90572. * offsets for the seekpoints ahead of time. In order to get a proper
  90573. * seektable the client must support seeking. See next note.
  90574. *
  90575. * \note
  90576. * SEEKTABLE blocks are handled specially. Since you will not know
  90577. * the values for the seek point stream offsets, you should pass in
  90578. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  90579. * required sample numbers (or placeholder points), with \c 0 for the
  90580. * \a frame_samples and \a stream_offset fields for each point. If the
  90581. * client has specified that it supports seeking by providing a seek
  90582. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  90583. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  90584. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  90585. * then while it is encoding the encoder will fill the stream offsets in
  90586. * for you and when encoding is finished, it will seek back and write the
  90587. * real values into the SEEKTABLE block in the stream. There are helper
  90588. * routines for manipulating seektable template blocks; see metadata.h:
  90589. * FLAC__metadata_object_seektable_template_*(). If the client does
  90590. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  90591. * will slow down or remove the ability to seek in the FLAC stream.
  90592. *
  90593. * \note
  90594. * The encoder instance \b will modify the first \c SEEKTABLE block
  90595. * as it transforms the template to a valid seektable while encoding,
  90596. * but it is still up to the caller to free all metadata blocks after
  90597. * encoding.
  90598. *
  90599. * \note
  90600. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  90601. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  90602. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  90603. * will simply write it's own into the stream. If no VORBIS_COMMENT
  90604. * block is present in the \a metadata array, libFLAC will write an
  90605. * empty one, containing only the vendor string.
  90606. *
  90607. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  90608. * the second metadata block of the stream. The encoder already supplies
  90609. * the STREAMINFO block automatically. If \a metadata does not contain a
  90610. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  90611. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  90612. * first, the init function will reorder \a metadata by moving the
  90613. * VORBIS_COMMENT block to the front; the relative ordering of the other
  90614. * blocks will remain as they were.
  90615. *
  90616. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  90617. * stream to \c 65535. If \a num_blocks exceeds this the function will
  90618. * return \c false.
  90619. *
  90620. * \default \c NULL, 0
  90621. * \param encoder An encoder instance to set.
  90622. * \param metadata See above.
  90623. * \param num_blocks See above.
  90624. * \assert
  90625. * \code encoder != NULL \endcode
  90626. * \retval FLAC__bool
  90627. * \c false if the encoder is already initialized, else \c true.
  90628. * \c false if the encoder is already initialized, or if
  90629. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  90630. */
  90631. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  90632. /** Get the current encoder state.
  90633. *
  90634. * \param encoder An encoder instance to query.
  90635. * \assert
  90636. * \code encoder != NULL \endcode
  90637. * \retval FLAC__StreamEncoderState
  90638. * The current encoder state.
  90639. */
  90640. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  90641. /** Get the state of the verify stream decoder.
  90642. * Useful when the stream encoder state is
  90643. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  90644. *
  90645. * \param encoder An encoder instance to query.
  90646. * \assert
  90647. * \code encoder != NULL \endcode
  90648. * \retval FLAC__StreamDecoderState
  90649. * The verify stream decoder state.
  90650. */
  90651. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  90652. /** Get the current encoder state as a C string.
  90653. * This version automatically resolves
  90654. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  90655. * verify decoder's state.
  90656. *
  90657. * \param encoder A encoder instance to query.
  90658. * \assert
  90659. * \code encoder != NULL \endcode
  90660. * \retval const char *
  90661. * The encoder state as a C string. Do not modify the contents.
  90662. */
  90663. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  90664. /** Get relevant values about the nature of a verify decoder error.
  90665. * Useful when the stream encoder state is
  90666. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  90667. * be addresses in which the stats will be returned, or NULL if value
  90668. * is not desired.
  90669. *
  90670. * \param encoder An encoder instance to query.
  90671. * \param absolute_sample The absolute sample number of the mismatch.
  90672. * \param frame_number The number of the frame in which the mismatch occurred.
  90673. * \param channel The channel in which the mismatch occurred.
  90674. * \param sample The number of the sample (relative to the frame) in
  90675. * which the mismatch occurred.
  90676. * \param expected The expected value for the sample in question.
  90677. * \param got The actual value returned by the decoder.
  90678. * \assert
  90679. * \code encoder != NULL \endcode
  90680. */
  90681. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got);
  90682. /** Get the "verify" flag.
  90683. *
  90684. * \param encoder An encoder instance to query.
  90685. * \assert
  90686. * \code encoder != NULL \endcode
  90687. * \retval FLAC__bool
  90688. * See FLAC__stream_encoder_set_verify().
  90689. */
  90690. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  90691. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  90692. *
  90693. * \param encoder An encoder instance to query.
  90694. * \assert
  90695. * \code encoder != NULL \endcode
  90696. * \retval FLAC__bool
  90697. * See FLAC__stream_encoder_set_streamable_subset().
  90698. */
  90699. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  90700. /** Get the number of input channels being processed.
  90701. *
  90702. * \param encoder An encoder instance to query.
  90703. * \assert
  90704. * \code encoder != NULL \endcode
  90705. * \retval unsigned
  90706. * See FLAC__stream_encoder_set_channels().
  90707. */
  90708. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  90709. /** Get the input sample resolution setting.
  90710. *
  90711. * \param encoder An encoder instance to query.
  90712. * \assert
  90713. * \code encoder != NULL \endcode
  90714. * \retval unsigned
  90715. * See FLAC__stream_encoder_set_bits_per_sample().
  90716. */
  90717. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  90718. /** Get the input sample rate setting.
  90719. *
  90720. * \param encoder An encoder instance to query.
  90721. * \assert
  90722. * \code encoder != NULL \endcode
  90723. * \retval unsigned
  90724. * See FLAC__stream_encoder_set_sample_rate().
  90725. */
  90726. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  90727. /** Get the blocksize setting.
  90728. *
  90729. * \param encoder An encoder instance to query.
  90730. * \assert
  90731. * \code encoder != NULL \endcode
  90732. * \retval unsigned
  90733. * See FLAC__stream_encoder_set_blocksize().
  90734. */
  90735. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  90736. /** Get the "mid/side stereo coding" flag.
  90737. *
  90738. * \param encoder An encoder instance to query.
  90739. * \assert
  90740. * \code encoder != NULL \endcode
  90741. * \retval FLAC__bool
  90742. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  90743. */
  90744. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  90745. /** Get the "adaptive mid/side switching" flag.
  90746. *
  90747. * \param encoder An encoder instance to query.
  90748. * \assert
  90749. * \code encoder != NULL \endcode
  90750. * \retval FLAC__bool
  90751. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  90752. */
  90753. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  90754. /** Get the maximum LPC order setting.
  90755. *
  90756. * \param encoder An encoder instance to query.
  90757. * \assert
  90758. * \code encoder != NULL \endcode
  90759. * \retval unsigned
  90760. * See FLAC__stream_encoder_set_max_lpc_order().
  90761. */
  90762. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  90763. /** Get the quantized linear predictor coefficient precision setting.
  90764. *
  90765. * \param encoder An encoder instance to query.
  90766. * \assert
  90767. * \code encoder != NULL \endcode
  90768. * \retval unsigned
  90769. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  90770. */
  90771. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  90772. /** Get the qlp coefficient precision search flag.
  90773. *
  90774. * \param encoder An encoder instance to query.
  90775. * \assert
  90776. * \code encoder != NULL \endcode
  90777. * \retval FLAC__bool
  90778. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  90779. */
  90780. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  90781. /** Get the "escape coding" flag.
  90782. *
  90783. * \param encoder An encoder instance to query.
  90784. * \assert
  90785. * \code encoder != NULL \endcode
  90786. * \retval FLAC__bool
  90787. * See FLAC__stream_encoder_set_do_escape_coding().
  90788. */
  90789. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  90790. /** Get the exhaustive model search flag.
  90791. *
  90792. * \param encoder An encoder instance to query.
  90793. * \assert
  90794. * \code encoder != NULL \endcode
  90795. * \retval FLAC__bool
  90796. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  90797. */
  90798. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  90799. /** Get the minimum residual partition order setting.
  90800. *
  90801. * \param encoder An encoder instance to query.
  90802. * \assert
  90803. * \code encoder != NULL \endcode
  90804. * \retval unsigned
  90805. * See FLAC__stream_encoder_set_min_residual_partition_order().
  90806. */
  90807. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  90808. /** Get maximum residual partition order setting.
  90809. *
  90810. * \param encoder An encoder instance to query.
  90811. * \assert
  90812. * \code encoder != NULL \endcode
  90813. * \retval unsigned
  90814. * See FLAC__stream_encoder_set_max_residual_partition_order().
  90815. */
  90816. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  90817. /** Get the Rice parameter search distance setting.
  90818. *
  90819. * \param encoder An encoder instance to query.
  90820. * \assert
  90821. * \code encoder != NULL \endcode
  90822. * \retval unsigned
  90823. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  90824. */
  90825. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  90826. /** Get the previously set estimate of the total samples to be encoded.
  90827. * The encoder merely mimics back the value given to
  90828. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  90829. * other way of knowing how many samples the client will encode.
  90830. *
  90831. * \param encoder An encoder instance to set.
  90832. * \assert
  90833. * \code encoder != NULL \endcode
  90834. * \retval FLAC__uint64
  90835. * See FLAC__stream_encoder_get_total_samples_estimate().
  90836. */
  90837. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  90838. /** Initialize the encoder instance to encode native FLAC streams.
  90839. *
  90840. * This flavor of initialization sets up the encoder to encode to a
  90841. * native FLAC stream. I/O is performed via callbacks to the client.
  90842. * For encoding to a plain file via filename or open \c FILE*,
  90843. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  90844. * provide a simpler interface.
  90845. *
  90846. * This function should be called after FLAC__stream_encoder_new() and
  90847. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  90848. * or FLAC__stream_encoder_process_interleaved().
  90849. * initialization succeeded.
  90850. *
  90851. * The call to FLAC__stream_encoder_init_stream() currently will also
  90852. * immediately call the write callback several times, once with the \c fLaC
  90853. * signature, and once for each encoded metadata block.
  90854. *
  90855. * \param encoder An uninitialized encoder instance.
  90856. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  90857. * pointer must not be \c NULL.
  90858. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  90859. * pointer may be \c NULL if seeking is not
  90860. * supported. The encoder uses seeking to go back
  90861. * and write some some stream statistics to the
  90862. * STREAMINFO block; this is recommended but not
  90863. * necessary to create a valid FLAC stream. If
  90864. * \a seek_callback is not \c NULL then a
  90865. * \a tell_callback must also be supplied.
  90866. * Alternatively, a dummy seek callback that just
  90867. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90868. * may also be supplied, all though this is slightly
  90869. * less efficient for the encoder.
  90870. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  90871. * pointer may be \c NULL if seeking is not
  90872. * supported. If \a seek_callback is \c NULL then
  90873. * this argument will be ignored. If
  90874. * \a seek_callback is not \c NULL then a
  90875. * \a tell_callback must also be supplied.
  90876. * Alternatively, a dummy tell callback that just
  90877. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90878. * may also be supplied, all though this is slightly
  90879. * less efficient for the encoder.
  90880. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  90881. * pointer may be \c NULL if the callback is not
  90882. * desired. If the client provides a seek callback,
  90883. * this function is not necessary as the encoder
  90884. * will automatically seek back and update the
  90885. * STREAMINFO block. It may also be \c NULL if the
  90886. * client does not support seeking, since it will
  90887. * have no way of going back to update the
  90888. * STREAMINFO. However the client can still supply
  90889. * a callback if it would like to know the details
  90890. * from the STREAMINFO.
  90891. * \param client_data This value will be supplied to callbacks in their
  90892. * \a client_data argument.
  90893. * \assert
  90894. * \code encoder != NULL \endcode
  90895. * \retval FLAC__StreamEncoderInitStatus
  90896. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  90897. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  90898. */
  90899. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data);
  90900. /** Initialize the encoder instance to encode Ogg FLAC streams.
  90901. *
  90902. * This flavor of initialization sets up the encoder to encode to a FLAC
  90903. * stream in an Ogg container. I/O is performed via callbacks to the
  90904. * client. For encoding to a plain file via filename or open \c FILE*,
  90905. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  90906. * provide a simpler interface.
  90907. *
  90908. * This function should be called after FLAC__stream_encoder_new() and
  90909. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  90910. * or FLAC__stream_encoder_process_interleaved().
  90911. * initialization succeeded.
  90912. *
  90913. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  90914. * immediately call the write callback several times to write the metadata
  90915. * packets.
  90916. *
  90917. * \param encoder An uninitialized encoder instance.
  90918. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  90919. * pointer must not be \c NULL if \a seek_callback
  90920. * is non-NULL since they are both needed to be
  90921. * able to write data back to the Ogg FLAC stream
  90922. * in the post-encode phase.
  90923. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  90924. * pointer must not be \c NULL.
  90925. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  90926. * pointer may be \c NULL if seeking is not
  90927. * supported. The encoder uses seeking to go back
  90928. * and write some some stream statistics to the
  90929. * STREAMINFO block; this is recommended but not
  90930. * necessary to create a valid FLAC stream. If
  90931. * \a seek_callback is not \c NULL then a
  90932. * \a tell_callback must also be supplied.
  90933. * Alternatively, a dummy seek callback that just
  90934. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90935. * may also be supplied, all though this is slightly
  90936. * less efficient for the encoder.
  90937. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  90938. * pointer may be \c NULL if seeking is not
  90939. * supported. If \a seek_callback is \c NULL then
  90940. * this argument will be ignored. If
  90941. * \a seek_callback is not \c NULL then a
  90942. * \a tell_callback must also be supplied.
  90943. * Alternatively, a dummy tell callback that just
  90944. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90945. * may also be supplied, all though this is slightly
  90946. * less efficient for the encoder.
  90947. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  90948. * pointer may be \c NULL if the callback is not
  90949. * desired. If the client provides a seek callback,
  90950. * this function is not necessary as the encoder
  90951. * will automatically seek back and update the
  90952. * STREAMINFO block. It may also be \c NULL if the
  90953. * client does not support seeking, since it will
  90954. * have no way of going back to update the
  90955. * STREAMINFO. However the client can still supply
  90956. * a callback if it would like to know the details
  90957. * from the STREAMINFO.
  90958. * \param client_data This value will be supplied to callbacks in their
  90959. * \a client_data argument.
  90960. * \assert
  90961. * \code encoder != NULL \endcode
  90962. * \retval FLAC__StreamEncoderInitStatus
  90963. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  90964. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  90965. */
  90966. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderReadCallback read_callback, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data);
  90967. /** Initialize the encoder instance to encode native FLAC files.
  90968. *
  90969. * This flavor of initialization sets up the encoder to encode to a
  90970. * plain native FLAC file. For non-stdio streams, you must use
  90971. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  90972. *
  90973. * This function should be called after FLAC__stream_encoder_new() and
  90974. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  90975. * or FLAC__stream_encoder_process_interleaved().
  90976. * initialization succeeded.
  90977. *
  90978. * \param encoder An uninitialized encoder instance.
  90979. * \param file An open file. The file should have been opened
  90980. * with mode \c "w+b" and rewound. The file
  90981. * becomes owned by the encoder and should not be
  90982. * manipulated by the client while encoding.
  90983. * Unless \a file is \c stdout, it will be closed
  90984. * when FLAC__stream_encoder_finish() is called.
  90985. * Note however that a proper SEEKTABLE cannot be
  90986. * created when encoding to \c stdout since it is
  90987. * not seekable.
  90988. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  90989. * pointer may be \c NULL if the callback is not
  90990. * desired.
  90991. * \param client_data This value will be supplied to callbacks in their
  90992. * \a client_data argument.
  90993. * \assert
  90994. * \code encoder != NULL \endcode
  90995. * \code file != NULL \endcode
  90996. * \retval FLAC__StreamEncoderInitStatus
  90997. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  90998. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  90999. */
  91000. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91001. /** Initialize the encoder instance to encode Ogg FLAC files.
  91002. *
  91003. * This flavor of initialization sets up the encoder to encode to a
  91004. * plain Ogg FLAC file. For non-stdio streams, you must use
  91005. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91006. *
  91007. * This function should be called after FLAC__stream_encoder_new() and
  91008. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91009. * or FLAC__stream_encoder_process_interleaved().
  91010. * initialization succeeded.
  91011. *
  91012. * \param encoder An uninitialized encoder instance.
  91013. * \param file An open file. The file should have been opened
  91014. * with mode \c "w+b" and rewound. The file
  91015. * becomes owned by the encoder and should not be
  91016. * manipulated by the client while encoding.
  91017. * Unless \a file is \c stdout, it will be closed
  91018. * when FLAC__stream_encoder_finish() is called.
  91019. * Note however that a proper SEEKTABLE cannot be
  91020. * created when encoding to \c stdout since it is
  91021. * not seekable.
  91022. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91023. * pointer may be \c NULL if the callback is not
  91024. * desired.
  91025. * \param client_data This value will be supplied to callbacks in their
  91026. * \a client_data argument.
  91027. * \assert
  91028. * \code encoder != NULL \endcode
  91029. * \code file != NULL \endcode
  91030. * \retval FLAC__StreamEncoderInitStatus
  91031. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91032. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91033. */
  91034. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91035. /** Initialize the encoder instance to encode native FLAC files.
  91036. *
  91037. * This flavor of initialization sets up the encoder to encode to a plain
  91038. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91039. * with Unicode filenames on Windows), you must use
  91040. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91041. * and provide callbacks for the I/O.
  91042. *
  91043. * This function should be called after FLAC__stream_encoder_new() and
  91044. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91045. * or FLAC__stream_encoder_process_interleaved().
  91046. * initialization succeeded.
  91047. *
  91048. * \param encoder An uninitialized encoder instance.
  91049. * \param filename The name of the file to encode to. The file will
  91050. * be opened with fopen(). Use \c NULL to encode to
  91051. * \c stdout. Note however that a proper SEEKTABLE
  91052. * cannot be created when encoding to \c stdout since
  91053. * it is not seekable.
  91054. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91055. * pointer may be \c NULL if the callback is not
  91056. * desired.
  91057. * \param client_data This value will be supplied to callbacks in their
  91058. * \a client_data argument.
  91059. * \assert
  91060. * \code encoder != NULL \endcode
  91061. * \retval FLAC__StreamEncoderInitStatus
  91062. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91063. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91064. */
  91065. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91066. /** Initialize the encoder instance to encode Ogg FLAC files.
  91067. *
  91068. * This flavor of initialization sets up the encoder to encode to a plain
  91069. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91070. * with Unicode filenames on Windows), you must use
  91071. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91072. * and provide callbacks for the I/O.
  91073. *
  91074. * This function should be called after FLAC__stream_encoder_new() and
  91075. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91076. * or FLAC__stream_encoder_process_interleaved().
  91077. * initialization succeeded.
  91078. *
  91079. * \param encoder An uninitialized encoder instance.
  91080. * \param filename The name of the file to encode to. The file will
  91081. * be opened with fopen(). Use \c NULL to encode to
  91082. * \c stdout. Note however that a proper SEEKTABLE
  91083. * cannot be created when encoding to \c stdout since
  91084. * it is not seekable.
  91085. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91086. * pointer may be \c NULL if the callback is not
  91087. * desired.
  91088. * \param client_data This value will be supplied to callbacks in their
  91089. * \a client_data argument.
  91090. * \assert
  91091. * \code encoder != NULL \endcode
  91092. * \retval FLAC__StreamEncoderInitStatus
  91093. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91094. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91095. */
  91096. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91097. /** Finish the encoding process.
  91098. * Flushes the encoding buffer, releases resources, resets the encoder
  91099. * settings to their defaults, and returns the encoder state to
  91100. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91101. * one or more write callbacks before returning, and will generate
  91102. * a metadata callback.
  91103. *
  91104. * Note that in the course of processing the last frame, errors can
  91105. * occur, so the caller should be sure to check the return value to
  91106. * ensure the file was encoded properly.
  91107. *
  91108. * In the event of a prematurely-terminated encode, it is not strictly
  91109. * necessary to call this immediately before FLAC__stream_encoder_delete()
  91110. * but it is good practice to match every FLAC__stream_encoder_init_*()
  91111. * with a FLAC__stream_encoder_finish().
  91112. *
  91113. * \param encoder An uninitialized encoder instance.
  91114. * \assert
  91115. * \code encoder != NULL \endcode
  91116. * \retval FLAC__bool
  91117. * \c false if an error occurred processing the last frame; or if verify
  91118. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  91119. * verify mismatch; else \c true. If \c false, caller should check the
  91120. * state with FLAC__stream_encoder_get_state() for more information
  91121. * about the error.
  91122. */
  91123. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  91124. /** Submit data for encoding.
  91125. * This version allows you to supply the input data via an array of
  91126. * pointers, each pointer pointing to an array of \a samples samples
  91127. * representing one channel. The samples need not be block-aligned,
  91128. * but each channel should have the same number of samples. Each sample
  91129. * should be a signed integer, right-justified to the resolution set by
  91130. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91131. * resolution is 16 bits per sample, the samples should all be in the
  91132. * range [-32768,32767].
  91133. *
  91134. * For applications where channel order is important, channels must
  91135. * follow the order as described in the
  91136. * <A HREF="../format.html#frame_header">frame header</A>.
  91137. *
  91138. * \param encoder An initialized encoder instance in the OK state.
  91139. * \param buffer An array of pointers to each channel's signal.
  91140. * \param samples The number of samples in one channel.
  91141. * \assert
  91142. * \code encoder != NULL \endcode
  91143. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91144. * \retval FLAC__bool
  91145. * \c true if successful, else \c false; in this case, check the
  91146. * encoder state with FLAC__stream_encoder_get_state() to see what
  91147. * went wrong.
  91148. */
  91149. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  91150. /** Submit data for encoding.
  91151. * This version allows you to supply the input data where the channels
  91152. * are interleaved into a single array (i.e. channel0_sample0,
  91153. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91154. * The samples need not be block-aligned but they must be
  91155. * sample-aligned, i.e. the first value should be channel0_sample0
  91156. * and the last value channelN_sampleM. Each sample should be a signed
  91157. * integer, right-justified to the resolution set by
  91158. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91159. * resolution is 16 bits per sample, the samples should all be in the
  91160. * range [-32768,32767].
  91161. *
  91162. * For applications where channel order is important, channels must
  91163. * follow the order as described in the
  91164. * <A HREF="../format.html#frame_header">frame header</A>.
  91165. *
  91166. * \param encoder An initialized encoder instance in the OK state.
  91167. * \param buffer An array of channel-interleaved data (see above).
  91168. * \param samples The number of samples in one channel, the same as for
  91169. * FLAC__stream_encoder_process(). For example, if
  91170. * encoding two channels, \c 1000 \a samples corresponds
  91171. * to a \a buffer of 2000 values.
  91172. * \assert
  91173. * \code encoder != NULL \endcode
  91174. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91175. * \retval FLAC__bool
  91176. * \c true if successful, else \c false; in this case, check the
  91177. * encoder state with FLAC__stream_encoder_get_state() to see what
  91178. * went wrong.
  91179. */
  91180. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  91181. /* \} */
  91182. #ifdef __cplusplus
  91183. }
  91184. #endif
  91185. #endif
  91186. /*** End of inlined file: stream_encoder.h ***/
  91187. #ifdef _MSC_VER
  91188. /* OPT: an MSVC built-in would be better */
  91189. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  91190. {
  91191. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  91192. return (x>>16) | (x<<16);
  91193. }
  91194. #endif
  91195. #if defined(_MSC_VER) && defined(_X86_)
  91196. /* OPT: an MSVC built-in would be better */
  91197. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  91198. {
  91199. __asm {
  91200. mov edx, start
  91201. mov ecx, len
  91202. test ecx, ecx
  91203. loop1:
  91204. jz done1
  91205. mov eax, [edx]
  91206. bswap eax
  91207. mov [edx], eax
  91208. add edx, 4
  91209. dec ecx
  91210. jmp short loop1
  91211. done1:
  91212. }
  91213. }
  91214. #endif
  91215. /** \mainpage
  91216. *
  91217. * \section intro Introduction
  91218. *
  91219. * This is the documentation for the FLAC C and C++ APIs. It is
  91220. * highly interconnected; this introduction should give you a top
  91221. * level idea of the structure and how to find the information you
  91222. * need. As a prerequisite you should have at least a basic
  91223. * knowledge of the FLAC format, documented
  91224. * <A HREF="../format.html">here</A>.
  91225. *
  91226. * \section c_api FLAC C API
  91227. *
  91228. * The FLAC C API is the interface to libFLAC, a set of structures
  91229. * describing the components of FLAC streams, and functions for
  91230. * encoding and decoding streams, as well as manipulating FLAC
  91231. * metadata in files. The public include files will be installed
  91232. * in your include area (for example /usr/include/FLAC/...).
  91233. *
  91234. * By writing a little code and linking against libFLAC, it is
  91235. * relatively easy to add FLAC support to another program. The
  91236. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  91237. * Complete source code of libFLAC as well as the command-line
  91238. * encoder and plugins is available and is a useful source of
  91239. * examples.
  91240. *
  91241. * Aside from encoders and decoders, libFLAC provides a powerful
  91242. * metadata interface for manipulating metadata in FLAC files. It
  91243. * allows the user to add, delete, and modify FLAC metadata blocks
  91244. * and it can automatically take advantage of PADDING blocks to avoid
  91245. * rewriting the entire FLAC file when changing the size of the
  91246. * metadata.
  91247. *
  91248. * libFLAC usually only requires the standard C library and C math
  91249. * library. In particular, threading is not used so there is no
  91250. * dependency on a thread library. However, libFLAC does not use
  91251. * global variables and should be thread-safe.
  91252. *
  91253. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  91254. * However the metadata editing interfaces currently have limited
  91255. * read-only support for Ogg FLAC files.
  91256. *
  91257. * \section cpp_api FLAC C++ API
  91258. *
  91259. * The FLAC C++ API is a set of classes that encapsulate the
  91260. * structures and functions in libFLAC. They provide slightly more
  91261. * functionality with respect to metadata but are otherwise
  91262. * equivalent. For the most part, they share the same usage as
  91263. * their counterparts in libFLAC, and the FLAC C API documentation
  91264. * can be used as a supplement. The public include files
  91265. * for the C++ API will be installed in your include area (for
  91266. * example /usr/include/FLAC++/...).
  91267. *
  91268. * libFLAC++ is also licensed under
  91269. * <A HREF="../license.html">Xiph's BSD license</A>.
  91270. *
  91271. * \section getting_started Getting Started
  91272. *
  91273. * A good starting point for learning the API is to browse through
  91274. * the <A HREF="modules.html">modules</A>. Modules are logical
  91275. * groupings of related functions or classes, which correspond roughly
  91276. * to header files or sections of header files. Each module includes a
  91277. * detailed description of the general usage of its functions or
  91278. * classes.
  91279. *
  91280. * From there you can go on to look at the documentation of
  91281. * individual functions. You can see different views of the individual
  91282. * functions through the links in top bar across this page.
  91283. *
  91284. * If you prefer a more hands-on approach, you can jump right to some
  91285. * <A HREF="../documentation_example_code.html">example code</A>.
  91286. *
  91287. * \section porting_guide Porting Guide
  91288. *
  91289. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  91290. * has been introduced which gives detailed instructions on how to
  91291. * port your code to newer versions of FLAC.
  91292. *
  91293. * \section embedded_developers Embedded Developers
  91294. *
  91295. * libFLAC has grown larger over time as more functionality has been
  91296. * included, but much of it may be unnecessary for a particular embedded
  91297. * implementation. Unused parts may be pruned by some simple editing of
  91298. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  91299. * metadata interface are all independent from each other.
  91300. *
  91301. * It is easiest to just describe the dependencies:
  91302. *
  91303. * - All modules depend on the \link flac_format Format \endlink module.
  91304. * - The decoders and encoders depend on the bitbuffer.
  91305. * - The decoder is independent of the encoder. The encoder uses the
  91306. * decoder because of the verify feature, but this can be removed if
  91307. * not needed.
  91308. * - Parts of the metadata interface require the stream decoder (but not
  91309. * the encoder).
  91310. * - Ogg support is selectable through the compile time macro
  91311. * \c FLAC__HAS_OGG.
  91312. *
  91313. * For example, if your application only requires the stream decoder, no
  91314. * encoder, and no metadata interface, you can remove the stream encoder
  91315. * and the metadata interface, which will greatly reduce the size of the
  91316. * library.
  91317. *
  91318. * Also, there are several places in the libFLAC code with comments marked
  91319. * with "OPT:" where a #define can be changed to enable code that might be
  91320. * faster on a specific platform. Experimenting with these can yield faster
  91321. * binaries.
  91322. */
  91323. /** \defgroup porting Porting Guide for New Versions
  91324. *
  91325. * This module describes differences in the library interfaces from
  91326. * version to version. It assists in the porting of code that uses
  91327. * the libraries to newer versions of FLAC.
  91328. *
  91329. * One simple facility for making porting easier that has been added
  91330. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  91331. * library's includes (e.g. \c include/FLAC/export.h). The
  91332. * \c #defines mirror the libraries'
  91333. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  91334. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  91335. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  91336. * These can be used to support multiple versions of an API during the
  91337. * transition phase, e.g.
  91338. *
  91339. * \code
  91340. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  91341. * legacy code
  91342. * #else
  91343. * new code
  91344. * #endif
  91345. * \endcode
  91346. *
  91347. * The the source will work for multiple versions and the legacy code can
  91348. * easily be removed when the transition is complete.
  91349. *
  91350. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  91351. * include/FLAC/export.h), which can be used to determine whether or not
  91352. * the library has been compiled with support for Ogg FLAC. This is
  91353. * simpler than trying to call an Ogg init function and catching the
  91354. * error.
  91355. */
  91356. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  91357. * \ingroup porting
  91358. *
  91359. * \brief
  91360. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  91361. *
  91362. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  91363. * been simplified. First, libOggFLAC has been merged into libFLAC and
  91364. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  91365. * decoding layers and three encoding layers have been merged into a
  91366. * single stream decoder and stream encoder. That is, the functionality
  91367. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  91368. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  91369. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  91370. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  91371. * is there is now a single API that can be used to encode or decode
  91372. * streams to/from native FLAC or Ogg FLAC and the single API can work
  91373. * on both seekable and non-seekable streams.
  91374. *
  91375. * Instead of creating an encoder or decoder of a certain layer, now the
  91376. * client will always create a FLAC__StreamEncoder or
  91377. * FLAC__StreamDecoder. The old layers are now differentiated by the
  91378. * initialization function. For example, for the decoder,
  91379. * FLAC__stream_decoder_init() has been replaced by
  91380. * FLAC__stream_decoder_init_stream(). This init function takes
  91381. * callbacks for the I/O, and the seeking callbacks are optional. This
  91382. * allows the client to use the same object for seekable and
  91383. * non-seekable streams. For decoding a FLAC file directly, the client
  91384. * can use FLAC__stream_decoder_init_file() and pass just a filename
  91385. * and fewer callbacks; most of the other callbacks are supplied
  91386. * internally. For situations where fopen()ing by filename is not
  91387. * possible (e.g. Unicode filenames on Windows) the client can instead
  91388. * open the file itself and supply the FILE* to
  91389. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  91390. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  91391. * Since the callbacks and client data are now passed to the init
  91392. * function, the FLAC__stream_decoder_set_*_callback() functions and
  91393. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  91394. * rest of the calls to the decoder are the same as before.
  91395. *
  91396. * There are counterpart init functions for Ogg FLAC, e.g.
  91397. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  91398. * and callbacks are the same as for native FLAC.
  91399. *
  91400. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  91401. * been set up like so:
  91402. *
  91403. * \code
  91404. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  91405. * if(decoder == NULL) do_something;
  91406. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  91407. * [... other settings ...]
  91408. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  91409. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  91410. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  91411. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  91412. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  91413. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  91414. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  91415. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  91416. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  91417. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  91418. * \endcode
  91419. *
  91420. * In FLAC 1.1.3 it is like this:
  91421. *
  91422. * \code
  91423. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  91424. * if(decoder == NULL) do_something;
  91425. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  91426. * [... other settings ...]
  91427. * if(FLAC__stream_decoder_init_stream(
  91428. * decoder,
  91429. * my_read_callback,
  91430. * my_seek_callback, // or NULL
  91431. * my_tell_callback, // or NULL
  91432. * my_length_callback, // or NULL
  91433. * my_eof_callback, // or NULL
  91434. * my_write_callback,
  91435. * my_metadata_callback, // or NULL
  91436. * my_error_callback,
  91437. * my_client_data
  91438. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91439. * \endcode
  91440. *
  91441. * or you could do;
  91442. *
  91443. * \code
  91444. * [...]
  91445. * FILE *file = fopen("somefile.flac","rb");
  91446. * if(file == NULL) do_somthing;
  91447. * if(FLAC__stream_decoder_init_FILE(
  91448. * decoder,
  91449. * file,
  91450. * my_write_callback,
  91451. * my_metadata_callback, // or NULL
  91452. * my_error_callback,
  91453. * my_client_data
  91454. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91455. * \endcode
  91456. *
  91457. * or just:
  91458. *
  91459. * \code
  91460. * [...]
  91461. * if(FLAC__stream_decoder_init_file(
  91462. * decoder,
  91463. * "somefile.flac",
  91464. * my_write_callback,
  91465. * my_metadata_callback, // or NULL
  91466. * my_error_callback,
  91467. * my_client_data
  91468. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91469. * \endcode
  91470. *
  91471. * Another small change to the decoder is in how it handles unparseable
  91472. * streams. Before, when the decoder found an unparseable stream
  91473. * (reserved for when the decoder encounters a stream from a future
  91474. * encoder that it can't parse), it changed the state to
  91475. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  91476. * drops sync and calls the error callback with a new error code
  91477. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  91478. * more robust. If your error callback does not discriminate on the the
  91479. * error state, your code does not need to be changed.
  91480. *
  91481. * The encoder now has a new setting:
  91482. * FLAC__stream_encoder_set_apodization(). This is for setting the
  91483. * method used to window the data before LPC analysis. You only need to
  91484. * add a call to this function if the default is not suitable. There
  91485. * are also two new convenience functions that may be useful:
  91486. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  91487. * FLAC__metadata_get_cuesheet().
  91488. *
  91489. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  91490. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  91491. * is now \c size_t instead of \c unsigned.
  91492. */
  91493. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  91494. * \ingroup porting
  91495. *
  91496. * \brief
  91497. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  91498. *
  91499. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  91500. * There was a slight change in the implementation of
  91501. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  91502. * of the \a metadata array of pointers so the client no longer needs
  91503. * to maintain it after the call. The objects themselves that are
  91504. * pointed to by the array are still not copied though and must be
  91505. * maintained until the call to FLAC__stream_encoder_finish().
  91506. */
  91507. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  91508. * \ingroup porting
  91509. *
  91510. * \brief
  91511. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  91512. *
  91513. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  91514. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  91515. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  91516. *
  91517. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  91518. * has changed to reflect the conversion of one of the reserved bits
  91519. * into active use. It used to be \c 2 and now is \c 1. However the
  91520. * FLAC frame header length has not changed, so to skip the proper
  91521. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  91522. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  91523. */
  91524. /** \defgroup flac FLAC C API
  91525. *
  91526. * The FLAC C API is the interface to libFLAC, a set of structures
  91527. * describing the components of FLAC streams, and functions for
  91528. * encoding and decoding streams, as well as manipulating FLAC
  91529. * metadata in files.
  91530. *
  91531. * You should start with the format components as all other modules
  91532. * are dependent on it.
  91533. */
  91534. #endif
  91535. /*** End of inlined file: all.h ***/
  91536. /*** Start of inlined file: bitmath.c ***/
  91537. /*** Start of inlined file: juce_FlacHeader.h ***/
  91538. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91539. // tasks..
  91540. #define VERSION "1.2.1"
  91541. #define FLAC__NO_DLL 1
  91542. #if JUCE_MSVC
  91543. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91544. #endif
  91545. #if JUCE_MAC
  91546. #define FLAC__SYS_DARWIN 1
  91547. #endif
  91548. /*** End of inlined file: juce_FlacHeader.h ***/
  91549. #if JUCE_USE_FLAC
  91550. #if HAVE_CONFIG_H
  91551. # include <config.h>
  91552. #endif
  91553. /*** Start of inlined file: bitmath.h ***/
  91554. #ifndef FLAC__PRIVATE__BITMATH_H
  91555. #define FLAC__PRIVATE__BITMATH_H
  91556. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  91557. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  91558. unsigned FLAC__bitmath_silog2(int v);
  91559. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  91560. #endif
  91561. /*** End of inlined file: bitmath.h ***/
  91562. /* An example of what FLAC__bitmath_ilog2() computes:
  91563. *
  91564. * ilog2( 0) = assertion failure
  91565. * ilog2( 1) = 0
  91566. * ilog2( 2) = 1
  91567. * ilog2( 3) = 1
  91568. * ilog2( 4) = 2
  91569. * ilog2( 5) = 2
  91570. * ilog2( 6) = 2
  91571. * ilog2( 7) = 2
  91572. * ilog2( 8) = 3
  91573. * ilog2( 9) = 3
  91574. * ilog2(10) = 3
  91575. * ilog2(11) = 3
  91576. * ilog2(12) = 3
  91577. * ilog2(13) = 3
  91578. * ilog2(14) = 3
  91579. * ilog2(15) = 3
  91580. * ilog2(16) = 4
  91581. * ilog2(17) = 4
  91582. * ilog2(18) = 4
  91583. */
  91584. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  91585. {
  91586. unsigned l = 0;
  91587. FLAC__ASSERT(v > 0);
  91588. while(v >>= 1)
  91589. l++;
  91590. return l;
  91591. }
  91592. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  91593. {
  91594. unsigned l = 0;
  91595. FLAC__ASSERT(v > 0);
  91596. while(v >>= 1)
  91597. l++;
  91598. return l;
  91599. }
  91600. /* An example of what FLAC__bitmath_silog2() computes:
  91601. *
  91602. * silog2(-10) = 5
  91603. * silog2(- 9) = 5
  91604. * silog2(- 8) = 4
  91605. * silog2(- 7) = 4
  91606. * silog2(- 6) = 4
  91607. * silog2(- 5) = 4
  91608. * silog2(- 4) = 3
  91609. * silog2(- 3) = 3
  91610. * silog2(- 2) = 2
  91611. * silog2(- 1) = 2
  91612. * silog2( 0) = 0
  91613. * silog2( 1) = 2
  91614. * silog2( 2) = 3
  91615. * silog2( 3) = 3
  91616. * silog2( 4) = 4
  91617. * silog2( 5) = 4
  91618. * silog2( 6) = 4
  91619. * silog2( 7) = 4
  91620. * silog2( 8) = 5
  91621. * silog2( 9) = 5
  91622. * silog2( 10) = 5
  91623. */
  91624. unsigned FLAC__bitmath_silog2(int v)
  91625. {
  91626. while(1) {
  91627. if(v == 0) {
  91628. return 0;
  91629. }
  91630. else if(v > 0) {
  91631. unsigned l = 0;
  91632. while(v) {
  91633. l++;
  91634. v >>= 1;
  91635. }
  91636. return l+1;
  91637. }
  91638. else if(v == -1) {
  91639. return 2;
  91640. }
  91641. else {
  91642. v++;
  91643. v = -v;
  91644. }
  91645. }
  91646. }
  91647. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  91648. {
  91649. while(1) {
  91650. if(v == 0) {
  91651. return 0;
  91652. }
  91653. else if(v > 0) {
  91654. unsigned l = 0;
  91655. while(v) {
  91656. l++;
  91657. v >>= 1;
  91658. }
  91659. return l+1;
  91660. }
  91661. else if(v == -1) {
  91662. return 2;
  91663. }
  91664. else {
  91665. v++;
  91666. v = -v;
  91667. }
  91668. }
  91669. }
  91670. #endif
  91671. /*** End of inlined file: bitmath.c ***/
  91672. /*** Start of inlined file: bitreader.c ***/
  91673. /*** Start of inlined file: juce_FlacHeader.h ***/
  91674. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91675. // tasks..
  91676. #define VERSION "1.2.1"
  91677. #define FLAC__NO_DLL 1
  91678. #if JUCE_MSVC
  91679. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91680. #endif
  91681. #if JUCE_MAC
  91682. #define FLAC__SYS_DARWIN 1
  91683. #endif
  91684. /*** End of inlined file: juce_FlacHeader.h ***/
  91685. #if JUCE_USE_FLAC
  91686. #if HAVE_CONFIG_H
  91687. # include <config.h>
  91688. #endif
  91689. #include <stdlib.h> /* for malloc() */
  91690. #include <string.h> /* for memcpy(), memset() */
  91691. #ifdef _MSC_VER
  91692. #include <winsock.h> /* for ntohl() */
  91693. #elif defined FLAC__SYS_DARWIN
  91694. #include <machine/endian.h> /* for ntohl() */
  91695. #elif defined __MINGW32__
  91696. #include <winsock.h> /* for ntohl() */
  91697. #else
  91698. #include <netinet/in.h> /* for ntohl() */
  91699. #endif
  91700. /*** Start of inlined file: bitreader.h ***/
  91701. #ifndef FLAC__PRIVATE__BITREADER_H
  91702. #define FLAC__PRIVATE__BITREADER_H
  91703. #include <stdio.h> /* for FILE */
  91704. /*** Start of inlined file: cpu.h ***/
  91705. #ifndef FLAC__PRIVATE__CPU_H
  91706. #define FLAC__PRIVATE__CPU_H
  91707. #ifdef HAVE_CONFIG_H
  91708. #include <config.h>
  91709. #endif
  91710. typedef enum {
  91711. FLAC__CPUINFO_TYPE_IA32,
  91712. FLAC__CPUINFO_TYPE_PPC,
  91713. FLAC__CPUINFO_TYPE_UNKNOWN
  91714. } FLAC__CPUInfo_Type;
  91715. typedef struct {
  91716. FLAC__bool cpuid;
  91717. FLAC__bool bswap;
  91718. FLAC__bool cmov;
  91719. FLAC__bool mmx;
  91720. FLAC__bool fxsr;
  91721. FLAC__bool sse;
  91722. FLAC__bool sse2;
  91723. FLAC__bool sse3;
  91724. FLAC__bool ssse3;
  91725. FLAC__bool _3dnow;
  91726. FLAC__bool ext3dnow;
  91727. FLAC__bool extmmx;
  91728. } FLAC__CPUInfo_IA32;
  91729. typedef struct {
  91730. FLAC__bool altivec;
  91731. FLAC__bool ppc64;
  91732. } FLAC__CPUInfo_PPC;
  91733. typedef struct {
  91734. FLAC__bool use_asm;
  91735. FLAC__CPUInfo_Type type;
  91736. union {
  91737. FLAC__CPUInfo_IA32 ia32;
  91738. FLAC__CPUInfo_PPC ppc;
  91739. } data;
  91740. } FLAC__CPUInfo;
  91741. void FLAC__cpu_info(FLAC__CPUInfo *info);
  91742. #ifndef FLAC__NO_ASM
  91743. #ifdef FLAC__CPU_IA32
  91744. #ifdef FLAC__HAS_NASM
  91745. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  91746. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  91747. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  91748. #endif
  91749. #endif
  91750. #endif
  91751. #endif
  91752. /*** End of inlined file: cpu.h ***/
  91753. /*
  91754. * opaque structure definition
  91755. */
  91756. struct FLAC__BitReader;
  91757. typedef struct FLAC__BitReader FLAC__BitReader;
  91758. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  91759. /*
  91760. * construction, deletion, initialization, etc functions
  91761. */
  91762. FLAC__BitReader *FLAC__bitreader_new(void);
  91763. void FLAC__bitreader_delete(FLAC__BitReader *br);
  91764. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  91765. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  91766. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  91767. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  91768. /*
  91769. * CRC functions
  91770. */
  91771. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  91772. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  91773. /*
  91774. * info functions
  91775. */
  91776. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  91777. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  91778. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  91779. /*
  91780. * read functions
  91781. */
  91782. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  91783. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  91784. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  91785. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  91786. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  91787. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  91788. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  91789. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  91790. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  91791. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  91792. #ifndef FLAC__NO_ASM
  91793. # ifdef FLAC__CPU_IA32
  91794. # ifdef FLAC__HAS_NASM
  91795. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  91796. # endif
  91797. # endif
  91798. #endif
  91799. #if 0 /* UNUSED */
  91800. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  91801. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  91802. #endif
  91803. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  91804. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  91805. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  91806. #endif
  91807. /*** End of inlined file: bitreader.h ***/
  91808. /*** Start of inlined file: crc.h ***/
  91809. #ifndef FLAC__PRIVATE__CRC_H
  91810. #define FLAC__PRIVATE__CRC_H
  91811. /* 8 bit CRC generator, MSB shifted first
  91812. ** polynomial = x^8 + x^2 + x^1 + x^0
  91813. ** init = 0
  91814. */
  91815. extern FLAC__byte const FLAC__crc8_table[256];
  91816. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  91817. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  91818. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  91819. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  91820. /* 16 bit CRC generator, MSB shifted first
  91821. ** polynomial = x^16 + x^15 + x^2 + x^0
  91822. ** init = 0
  91823. */
  91824. extern unsigned FLAC__crc16_table[256];
  91825. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  91826. /* this alternate may be faster on some systems/compilers */
  91827. #if 0
  91828. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  91829. #endif
  91830. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  91831. #endif
  91832. /*** End of inlined file: crc.h ***/
  91833. /* Things should be fastest when this matches the machine word size */
  91834. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  91835. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  91836. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  91837. typedef FLAC__uint32 brword;
  91838. #define FLAC__BYTES_PER_WORD 4
  91839. #define FLAC__BITS_PER_WORD 32
  91840. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  91841. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  91842. #if WORDS_BIGENDIAN
  91843. #define SWAP_BE_WORD_TO_HOST(x) (x)
  91844. #else
  91845. #if defined (_MSC_VER) && defined (_X86_)
  91846. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  91847. #else
  91848. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  91849. #endif
  91850. #endif
  91851. /* counts the # of zero MSBs in a word */
  91852. #define COUNT_ZERO_MSBS(word) ( \
  91853. (word) <= 0xffff ? \
  91854. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  91855. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  91856. )
  91857. /* this alternate might be slightly faster on some systems/compilers: */
  91858. #define COUNT_ZERO_MSBS2(word) ( (word) <= 0xff ? byte_to_unary_table[word] + 24 : ((word) <= 0xffff ? byte_to_unary_table[(word) >> 8] + 16 : ((word) <= 0xffffff ? byte_to_unary_table[(word) >> 16] + 8 : byte_to_unary_table[(word) >> 24])) )
  91859. /*
  91860. * This should be at least twice as large as the largest number of words
  91861. * required to represent any 'number' (in any encoding) you are going to
  91862. * read. With FLAC this is on the order of maybe a few hundred bits.
  91863. * If the buffer is smaller than that, the decoder won't be able to read
  91864. * in a whole number that is in a variable length encoding (e.g. Rice).
  91865. * But to be practical it should be at least 1K bytes.
  91866. *
  91867. * Increase this number to decrease the number of read callbacks, at the
  91868. * expense of using more memory. Or decrease for the reverse effect,
  91869. * keeping in mind the limit from the first paragraph. The optimal size
  91870. * also depends on the CPU cache size and other factors; some twiddling
  91871. * may be necessary to squeeze out the best performance.
  91872. */
  91873. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  91874. static const unsigned char byte_to_unary_table[] = {
  91875. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  91876. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  91877. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  91878. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  91879. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  91880. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  91881. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  91882. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  91883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  91891. };
  91892. #ifdef min
  91893. #undef min
  91894. #endif
  91895. #define min(x,y) ((x)<(y)?(x):(y))
  91896. #ifdef max
  91897. #undef max
  91898. #endif
  91899. #define max(x,y) ((x)>(y)?(x):(y))
  91900. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91901. #ifdef _MSC_VER
  91902. #define FLAC__U64L(x) x
  91903. #else
  91904. #define FLAC__U64L(x) x##LLU
  91905. #endif
  91906. #ifndef FLaC__INLINE
  91907. #define FLaC__INLINE
  91908. #endif
  91909. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  91910. struct FLAC__BitReader {
  91911. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  91912. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  91913. brword *buffer;
  91914. unsigned capacity; /* in words */
  91915. unsigned words; /* # of completed words in buffer */
  91916. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  91917. unsigned consumed_words; /* #words ... */
  91918. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  91919. unsigned read_crc16; /* the running frame CRC */
  91920. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  91921. FLAC__BitReaderReadCallback read_callback;
  91922. void *client_data;
  91923. FLAC__CPUInfo cpu_info;
  91924. };
  91925. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  91926. {
  91927. register unsigned crc = br->read_crc16;
  91928. #if FLAC__BYTES_PER_WORD == 4
  91929. switch(br->crc16_align) {
  91930. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  91931. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  91932. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  91933. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  91934. }
  91935. #elif FLAC__BYTES_PER_WORD == 8
  91936. switch(br->crc16_align) {
  91937. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  91938. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  91939. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  91940. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  91941. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  91942. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  91943. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  91944. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  91945. }
  91946. #else
  91947. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  91948. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  91949. br->read_crc16 = crc;
  91950. #endif
  91951. br->crc16_align = 0;
  91952. }
  91953. /* would be static except it needs to be called by asm routines */
  91954. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  91955. {
  91956. unsigned start, end;
  91957. size_t bytes;
  91958. FLAC__byte *target;
  91959. /* first shift the unconsumed buffer data toward the front as much as possible */
  91960. if(br->consumed_words > 0) {
  91961. start = br->consumed_words;
  91962. end = br->words + (br->bytes? 1:0);
  91963. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  91964. br->words -= start;
  91965. br->consumed_words = 0;
  91966. }
  91967. /*
  91968. * set the target for reading, taking into account word alignment and endianness
  91969. */
  91970. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  91971. if(bytes == 0)
  91972. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  91973. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  91974. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  91975. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  91976. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  91977. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  91978. * ^^-------target, bytes=3
  91979. * on LE machines, have to byteswap the odd tail word so nothing is
  91980. * overwritten:
  91981. */
  91982. #if WORDS_BIGENDIAN
  91983. #else
  91984. if(br->bytes)
  91985. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  91986. #endif
  91987. /* now it looks like:
  91988. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  91989. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  91990. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  91991. * ^^-------target, bytes=3
  91992. */
  91993. /* read in the data; note that the callback may return a smaller number of bytes */
  91994. if(!br->read_callback(target, &bytes, br->client_data))
  91995. return false;
  91996. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  91997. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  91998. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  91999. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92000. * now have to byteswap on LE machines:
  92001. */
  92002. #if WORDS_BIGENDIAN
  92003. #else
  92004. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92005. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92006. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92007. start = br->words;
  92008. local_swap32_block_(br->buffer + start, end - start);
  92009. }
  92010. else
  92011. # endif
  92012. for(start = br->words; start < end; start++)
  92013. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92014. #endif
  92015. /* now it looks like:
  92016. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92017. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92018. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92019. * finally we'll update the reader values:
  92020. */
  92021. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92022. br->words = end / FLAC__BYTES_PER_WORD;
  92023. br->bytes = end % FLAC__BYTES_PER_WORD;
  92024. return true;
  92025. }
  92026. /***********************************************************************
  92027. *
  92028. * Class constructor/destructor
  92029. *
  92030. ***********************************************************************/
  92031. FLAC__BitReader *FLAC__bitreader_new(void)
  92032. {
  92033. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92034. /* calloc() implies:
  92035. memset(br, 0, sizeof(FLAC__BitReader));
  92036. br->buffer = 0;
  92037. br->capacity = 0;
  92038. br->words = br->bytes = 0;
  92039. br->consumed_words = br->consumed_bits = 0;
  92040. br->read_callback = 0;
  92041. br->client_data = 0;
  92042. */
  92043. return br;
  92044. }
  92045. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92046. {
  92047. FLAC__ASSERT(0 != br);
  92048. FLAC__bitreader_free(br);
  92049. free(br);
  92050. }
  92051. /***********************************************************************
  92052. *
  92053. * Public class methods
  92054. *
  92055. ***********************************************************************/
  92056. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92057. {
  92058. FLAC__ASSERT(0 != br);
  92059. br->words = br->bytes = 0;
  92060. br->consumed_words = br->consumed_bits = 0;
  92061. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92062. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92063. if(br->buffer == 0)
  92064. return false;
  92065. br->read_callback = rcb;
  92066. br->client_data = cd;
  92067. br->cpu_info = cpu;
  92068. return true;
  92069. }
  92070. void FLAC__bitreader_free(FLAC__BitReader *br)
  92071. {
  92072. FLAC__ASSERT(0 != br);
  92073. if(0 != br->buffer)
  92074. free(br->buffer);
  92075. br->buffer = 0;
  92076. br->capacity = 0;
  92077. br->words = br->bytes = 0;
  92078. br->consumed_words = br->consumed_bits = 0;
  92079. br->read_callback = 0;
  92080. br->client_data = 0;
  92081. }
  92082. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92083. {
  92084. br->words = br->bytes = 0;
  92085. br->consumed_words = br->consumed_bits = 0;
  92086. return true;
  92087. }
  92088. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92089. {
  92090. unsigned i, j;
  92091. if(br == 0) {
  92092. fprintf(out, "bitreader is NULL\n");
  92093. }
  92094. else {
  92095. fprintf(out, "bitreader: capacity=%u words=%u bytes=%u consumed: words=%u, bits=%u\n", br->capacity, br->words, br->bytes, br->consumed_words, br->consumed_bits);
  92096. for(i = 0; i < br->words; i++) {
  92097. fprintf(out, "%08X: ", i);
  92098. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92099. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92100. fprintf(out, ".");
  92101. else
  92102. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92103. fprintf(out, "\n");
  92104. }
  92105. if(br->bytes > 0) {
  92106. fprintf(out, "%08X: ", i);
  92107. for(j = 0; j < br->bytes*8; j++)
  92108. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92109. fprintf(out, ".");
  92110. else
  92111. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  92112. fprintf(out, "\n");
  92113. }
  92114. }
  92115. }
  92116. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  92117. {
  92118. FLAC__ASSERT(0 != br);
  92119. FLAC__ASSERT(0 != br->buffer);
  92120. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92121. br->read_crc16 = (unsigned)seed;
  92122. br->crc16_align = br->consumed_bits;
  92123. }
  92124. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  92125. {
  92126. FLAC__ASSERT(0 != br);
  92127. FLAC__ASSERT(0 != br->buffer);
  92128. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92129. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  92130. /* CRC any tail bytes in a partially-consumed word */
  92131. if(br->consumed_bits) {
  92132. const brword tail = br->buffer[br->consumed_words];
  92133. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  92134. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  92135. }
  92136. return br->read_crc16;
  92137. }
  92138. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  92139. {
  92140. return ((br->consumed_bits & 7) == 0);
  92141. }
  92142. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  92143. {
  92144. return 8 - (br->consumed_bits & 7);
  92145. }
  92146. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  92147. {
  92148. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  92149. }
  92150. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  92151. {
  92152. FLAC__ASSERT(0 != br);
  92153. FLAC__ASSERT(0 != br->buffer);
  92154. FLAC__ASSERT(bits <= 32);
  92155. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  92156. FLAC__ASSERT(br->consumed_words <= br->words);
  92157. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92158. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92159. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  92160. *val = 0;
  92161. return true;
  92162. }
  92163. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  92164. if(!bitreader_read_from_client_(br))
  92165. return false;
  92166. }
  92167. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92168. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92169. if(br->consumed_bits) {
  92170. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92171. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  92172. const brword word = br->buffer[br->consumed_words];
  92173. if(bits < n) {
  92174. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  92175. br->consumed_bits += bits;
  92176. return true;
  92177. }
  92178. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  92179. bits -= n;
  92180. crc16_update_word_(br, word);
  92181. br->consumed_words++;
  92182. br->consumed_bits = 0;
  92183. if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  92184. *val <<= bits;
  92185. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  92186. br->consumed_bits = bits;
  92187. }
  92188. return true;
  92189. }
  92190. else {
  92191. const brword word = br->buffer[br->consumed_words];
  92192. if(bits < FLAC__BITS_PER_WORD) {
  92193. *val = word >> (FLAC__BITS_PER_WORD-bits);
  92194. br->consumed_bits = bits;
  92195. return true;
  92196. }
  92197. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  92198. *val = word;
  92199. crc16_update_word_(br, word);
  92200. br->consumed_words++;
  92201. return true;
  92202. }
  92203. }
  92204. else {
  92205. /* in this case we're starting our read at a partial tail word;
  92206. * the reader has guaranteed that we have at least 'bits' bits
  92207. * available to read, which makes this case simpler.
  92208. */
  92209. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92210. if(br->consumed_bits) {
  92211. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92212. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  92213. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  92214. br->consumed_bits += bits;
  92215. return true;
  92216. }
  92217. else {
  92218. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  92219. br->consumed_bits += bits;
  92220. return true;
  92221. }
  92222. }
  92223. }
  92224. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  92225. {
  92226. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  92227. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  92228. return false;
  92229. /* sign-extend: */
  92230. *val <<= (32-bits);
  92231. *val >>= (32-bits);
  92232. return true;
  92233. }
  92234. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  92235. {
  92236. FLAC__uint32 hi, lo;
  92237. if(bits > 32) {
  92238. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  92239. return false;
  92240. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  92241. return false;
  92242. *val = hi;
  92243. *val <<= 32;
  92244. *val |= lo;
  92245. }
  92246. else {
  92247. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  92248. return false;
  92249. *val = lo;
  92250. }
  92251. return true;
  92252. }
  92253. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  92254. {
  92255. FLAC__uint32 x8, x32 = 0;
  92256. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  92257. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  92258. return false;
  92259. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92260. return false;
  92261. x32 |= (x8 << 8);
  92262. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92263. return false;
  92264. x32 |= (x8 << 16);
  92265. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92266. return false;
  92267. x32 |= (x8 << 24);
  92268. *val = x32;
  92269. return true;
  92270. }
  92271. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  92272. {
  92273. /*
  92274. * OPT: a faster implementation is possible but probably not that useful
  92275. * since this is only called a couple of times in the metadata readers.
  92276. */
  92277. FLAC__ASSERT(0 != br);
  92278. FLAC__ASSERT(0 != br->buffer);
  92279. if(bits > 0) {
  92280. const unsigned n = br->consumed_bits & 7;
  92281. unsigned m;
  92282. FLAC__uint32 x;
  92283. if(n != 0) {
  92284. m = min(8-n, bits);
  92285. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  92286. return false;
  92287. bits -= m;
  92288. }
  92289. m = bits / 8;
  92290. if(m > 0) {
  92291. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  92292. return false;
  92293. bits %= 8;
  92294. }
  92295. if(bits > 0) {
  92296. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  92297. return false;
  92298. }
  92299. }
  92300. return true;
  92301. }
  92302. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  92303. {
  92304. FLAC__uint32 x;
  92305. FLAC__ASSERT(0 != br);
  92306. FLAC__ASSERT(0 != br->buffer);
  92307. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92308. /* step 1: skip over partial head word to get word aligned */
  92309. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92310. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92311. return false;
  92312. nvals--;
  92313. }
  92314. if(0 == nvals)
  92315. return true;
  92316. /* step 2: skip whole words in chunks */
  92317. while(nvals >= FLAC__BYTES_PER_WORD) {
  92318. if(br->consumed_words < br->words) {
  92319. br->consumed_words++;
  92320. nvals -= FLAC__BYTES_PER_WORD;
  92321. }
  92322. else if(!bitreader_read_from_client_(br))
  92323. return false;
  92324. }
  92325. /* step 3: skip any remainder from partial tail bytes */
  92326. while(nvals) {
  92327. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92328. return false;
  92329. nvals--;
  92330. }
  92331. return true;
  92332. }
  92333. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  92334. {
  92335. FLAC__uint32 x;
  92336. FLAC__ASSERT(0 != br);
  92337. FLAC__ASSERT(0 != br->buffer);
  92338. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92339. /* step 1: read from partial head word to get word aligned */
  92340. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92341. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92342. return false;
  92343. *val++ = (FLAC__byte)x;
  92344. nvals--;
  92345. }
  92346. if(0 == nvals)
  92347. return true;
  92348. /* step 2: read whole words in chunks */
  92349. while(nvals >= FLAC__BYTES_PER_WORD) {
  92350. if(br->consumed_words < br->words) {
  92351. const brword word = br->buffer[br->consumed_words++];
  92352. #if FLAC__BYTES_PER_WORD == 4
  92353. val[0] = (FLAC__byte)(word >> 24);
  92354. val[1] = (FLAC__byte)(word >> 16);
  92355. val[2] = (FLAC__byte)(word >> 8);
  92356. val[3] = (FLAC__byte)word;
  92357. #elif FLAC__BYTES_PER_WORD == 8
  92358. val[0] = (FLAC__byte)(word >> 56);
  92359. val[1] = (FLAC__byte)(word >> 48);
  92360. val[2] = (FLAC__byte)(word >> 40);
  92361. val[3] = (FLAC__byte)(word >> 32);
  92362. val[4] = (FLAC__byte)(word >> 24);
  92363. val[5] = (FLAC__byte)(word >> 16);
  92364. val[6] = (FLAC__byte)(word >> 8);
  92365. val[7] = (FLAC__byte)word;
  92366. #else
  92367. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  92368. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  92369. #endif
  92370. val += FLAC__BYTES_PER_WORD;
  92371. nvals -= FLAC__BYTES_PER_WORD;
  92372. }
  92373. else if(!bitreader_read_from_client_(br))
  92374. return false;
  92375. }
  92376. /* step 3: read any remainder from partial tail bytes */
  92377. while(nvals) {
  92378. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92379. return false;
  92380. *val++ = (FLAC__byte)x;
  92381. nvals--;
  92382. }
  92383. return true;
  92384. }
  92385. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  92386. #if 0 /* slow but readable version */
  92387. {
  92388. unsigned bit;
  92389. FLAC__ASSERT(0 != br);
  92390. FLAC__ASSERT(0 != br->buffer);
  92391. *val = 0;
  92392. while(1) {
  92393. if(!FLAC__bitreader_read_bit(br, &bit))
  92394. return false;
  92395. if(bit)
  92396. break;
  92397. else
  92398. *val++;
  92399. }
  92400. return true;
  92401. }
  92402. #else
  92403. {
  92404. unsigned i;
  92405. FLAC__ASSERT(0 != br);
  92406. FLAC__ASSERT(0 != br->buffer);
  92407. *val = 0;
  92408. while(1) {
  92409. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92410. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  92411. if(b) {
  92412. i = COUNT_ZERO_MSBS(b);
  92413. *val += i;
  92414. i++;
  92415. br->consumed_bits += i;
  92416. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  92417. crc16_update_word_(br, br->buffer[br->consumed_words]);
  92418. br->consumed_words++;
  92419. br->consumed_bits = 0;
  92420. }
  92421. return true;
  92422. }
  92423. else {
  92424. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  92425. crc16_update_word_(br, br->buffer[br->consumed_words]);
  92426. br->consumed_words++;
  92427. br->consumed_bits = 0;
  92428. /* didn't find stop bit yet, have to keep going... */
  92429. }
  92430. }
  92431. /* at this point we've eaten up all the whole words; have to try
  92432. * reading through any tail bytes before calling the read callback.
  92433. * this is a repeat of the above logic adjusted for the fact we
  92434. * don't have a whole word. note though if the client is feeding
  92435. * us data a byte at a time (unlikely), br->consumed_bits may not
  92436. * be zero.
  92437. */
  92438. if(br->bytes) {
  92439. const unsigned end = br->bytes * 8;
  92440. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  92441. if(b) {
  92442. i = COUNT_ZERO_MSBS(b);
  92443. *val += i;
  92444. i++;
  92445. br->consumed_bits += i;
  92446. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  92447. return true;
  92448. }
  92449. else {
  92450. *val += end - br->consumed_bits;
  92451. br->consumed_bits += end;
  92452. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  92453. /* didn't find stop bit yet, have to keep going... */
  92454. }
  92455. }
  92456. if(!bitreader_read_from_client_(br))
  92457. return false;
  92458. }
  92459. }
  92460. #endif
  92461. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  92462. {
  92463. FLAC__uint32 lsbs = 0, msbs = 0;
  92464. unsigned uval;
  92465. FLAC__ASSERT(0 != br);
  92466. FLAC__ASSERT(0 != br->buffer);
  92467. FLAC__ASSERT(parameter <= 31);
  92468. /* read the unary MSBs and end bit */
  92469. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  92470. return false;
  92471. /* read the binary LSBs */
  92472. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  92473. return false;
  92474. /* compose the value */
  92475. uval = (msbs << parameter) | lsbs;
  92476. if(uval & 1)
  92477. *val = -((int)(uval >> 1)) - 1;
  92478. else
  92479. *val = (int)(uval >> 1);
  92480. return true;
  92481. }
  92482. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  92483. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  92484. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  92485. /* OPT: possibly faster version for use with MSVC */
  92486. #ifdef _MSC_VER
  92487. {
  92488. unsigned i;
  92489. unsigned uval = 0;
  92490. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  92491. /* try and get br->consumed_words and br->consumed_bits into register;
  92492. * must remember to flush them back to *br before calling other
  92493. * bitwriter functions that use them, and before returning */
  92494. register unsigned cwords;
  92495. register unsigned cbits;
  92496. FLAC__ASSERT(0 != br);
  92497. FLAC__ASSERT(0 != br->buffer);
  92498. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92499. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92500. FLAC__ASSERT(parameter < 32);
  92501. /* the above two asserts also guarantee that the binary part never straddles more that 2 words, so we don't have to loop to read it */
  92502. if(nvals == 0)
  92503. return true;
  92504. cbits = br->consumed_bits;
  92505. cwords = br->consumed_words;
  92506. while(1) {
  92507. /* read unary part */
  92508. while(1) {
  92509. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92510. brword b = br->buffer[cwords] << cbits;
  92511. if(b) {
  92512. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  92513. __asm {
  92514. bsr eax, b
  92515. not eax
  92516. and eax, 31
  92517. mov i, eax
  92518. }
  92519. #else
  92520. i = COUNT_ZERO_MSBS(b);
  92521. #endif
  92522. uval += i;
  92523. bits = parameter;
  92524. i++;
  92525. cbits += i;
  92526. if(cbits == FLAC__BITS_PER_WORD) {
  92527. crc16_update_word_(br, br->buffer[cwords]);
  92528. cwords++;
  92529. cbits = 0;
  92530. }
  92531. goto break1;
  92532. }
  92533. else {
  92534. uval += FLAC__BITS_PER_WORD - cbits;
  92535. crc16_update_word_(br, br->buffer[cwords]);
  92536. cwords++;
  92537. cbits = 0;
  92538. /* didn't find stop bit yet, have to keep going... */
  92539. }
  92540. }
  92541. /* at this point we've eaten up all the whole words; have to try
  92542. * reading through any tail bytes before calling the read callback.
  92543. * this is a repeat of the above logic adjusted for the fact we
  92544. * don't have a whole word. note though if the client is feeding
  92545. * us data a byte at a time (unlikely), br->consumed_bits may not
  92546. * be zero.
  92547. */
  92548. if(br->bytes) {
  92549. const unsigned end = br->bytes * 8;
  92550. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  92551. if(b) {
  92552. i = COUNT_ZERO_MSBS(b);
  92553. uval += i;
  92554. bits = parameter;
  92555. i++;
  92556. cbits += i;
  92557. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92558. goto break1;
  92559. }
  92560. else {
  92561. uval += end - cbits;
  92562. cbits += end;
  92563. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92564. /* didn't find stop bit yet, have to keep going... */
  92565. }
  92566. }
  92567. /* flush registers and read; bitreader_read_from_client_() does
  92568. * not touch br->consumed_bits at all but we still need to set
  92569. * it in case it fails and we have to return false.
  92570. */
  92571. br->consumed_bits = cbits;
  92572. br->consumed_words = cwords;
  92573. if(!bitreader_read_from_client_(br))
  92574. return false;
  92575. cwords = br->consumed_words;
  92576. }
  92577. break1:
  92578. /* read binary part */
  92579. FLAC__ASSERT(cwords <= br->words);
  92580. if(bits) {
  92581. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  92582. /* flush registers and read; bitreader_read_from_client_() does
  92583. * not touch br->consumed_bits at all but we still need to set
  92584. * it in case it fails and we have to return false.
  92585. */
  92586. br->consumed_bits = cbits;
  92587. br->consumed_words = cwords;
  92588. if(!bitreader_read_from_client_(br))
  92589. return false;
  92590. cwords = br->consumed_words;
  92591. }
  92592. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92593. if(cbits) {
  92594. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92595. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  92596. const brword word = br->buffer[cwords];
  92597. if(bits < n) {
  92598. uval <<= bits;
  92599. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  92600. cbits += bits;
  92601. goto break2;
  92602. }
  92603. uval <<= n;
  92604. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  92605. bits -= n;
  92606. crc16_update_word_(br, word);
  92607. cwords++;
  92608. cbits = 0;
  92609. if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  92610. uval <<= bits;
  92611. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  92612. cbits = bits;
  92613. }
  92614. goto break2;
  92615. }
  92616. else {
  92617. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  92618. uval <<= bits;
  92619. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  92620. cbits = bits;
  92621. goto break2;
  92622. }
  92623. }
  92624. else {
  92625. /* in this case we're starting our read at a partial tail word;
  92626. * the reader has guaranteed that we have at least 'bits' bits
  92627. * available to read, which makes this case simpler.
  92628. */
  92629. uval <<= bits;
  92630. if(cbits) {
  92631. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92632. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  92633. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  92634. cbits += bits;
  92635. goto break2;
  92636. }
  92637. else {
  92638. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  92639. cbits += bits;
  92640. goto break2;
  92641. }
  92642. }
  92643. }
  92644. break2:
  92645. /* compose the value */
  92646. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  92647. /* are we done? */
  92648. --nvals;
  92649. if(nvals == 0) {
  92650. br->consumed_bits = cbits;
  92651. br->consumed_words = cwords;
  92652. return true;
  92653. }
  92654. uval = 0;
  92655. ++vals;
  92656. }
  92657. }
  92658. #else
  92659. {
  92660. unsigned i;
  92661. unsigned uval = 0;
  92662. /* try and get br->consumed_words and br->consumed_bits into register;
  92663. * must remember to flush them back to *br before calling other
  92664. * bitwriter functions that use them, and before returning */
  92665. register unsigned cwords;
  92666. register unsigned cbits;
  92667. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  92668. FLAC__ASSERT(0 != br);
  92669. FLAC__ASSERT(0 != br->buffer);
  92670. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92671. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92672. FLAC__ASSERT(parameter < 32);
  92673. /* the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it */
  92674. if(nvals == 0)
  92675. return true;
  92676. cbits = br->consumed_bits;
  92677. cwords = br->consumed_words;
  92678. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  92679. while(1) {
  92680. /* read unary part */
  92681. while(1) {
  92682. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92683. brword b = br->buffer[cwords] << cbits;
  92684. if(b) {
  92685. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  92686. asm volatile (
  92687. "bsrl %1, %0;"
  92688. "notl %0;"
  92689. "andl $31, %0;"
  92690. : "=r"(i)
  92691. : "r"(b)
  92692. );
  92693. #else
  92694. i = COUNT_ZERO_MSBS(b);
  92695. #endif
  92696. uval += i;
  92697. cbits += i;
  92698. cbits++; /* skip over stop bit */
  92699. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  92700. crc16_update_word_(br, br->buffer[cwords]);
  92701. cwords++;
  92702. cbits = 0;
  92703. }
  92704. goto break1;
  92705. }
  92706. else {
  92707. uval += FLAC__BITS_PER_WORD - cbits;
  92708. crc16_update_word_(br, br->buffer[cwords]);
  92709. cwords++;
  92710. cbits = 0;
  92711. /* didn't find stop bit yet, have to keep going... */
  92712. }
  92713. }
  92714. /* at this point we've eaten up all the whole words; have to try
  92715. * reading through any tail bytes before calling the read callback.
  92716. * this is a repeat of the above logic adjusted for the fact we
  92717. * don't have a whole word. note though if the client is feeding
  92718. * us data a byte at a time (unlikely), br->consumed_bits may not
  92719. * be zero.
  92720. */
  92721. if(br->bytes) {
  92722. const unsigned end = br->bytes * 8;
  92723. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  92724. if(b) {
  92725. i = COUNT_ZERO_MSBS(b);
  92726. uval += i;
  92727. cbits += i;
  92728. cbits++; /* skip over stop bit */
  92729. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92730. goto break1;
  92731. }
  92732. else {
  92733. uval += end - cbits;
  92734. cbits += end;
  92735. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92736. /* didn't find stop bit yet, have to keep going... */
  92737. }
  92738. }
  92739. /* flush registers and read; bitreader_read_from_client_() does
  92740. * not touch br->consumed_bits at all but we still need to set
  92741. * it in case it fails and we have to return false.
  92742. */
  92743. br->consumed_bits = cbits;
  92744. br->consumed_words = cwords;
  92745. if(!bitreader_read_from_client_(br))
  92746. return false;
  92747. cwords = br->consumed_words;
  92748. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  92749. /* + uval to offset our count by the # of unary bits already
  92750. * consumed before the read, because we will add these back
  92751. * in all at once at break1
  92752. */
  92753. }
  92754. break1:
  92755. ucbits -= uval;
  92756. ucbits--; /* account for stop bit */
  92757. /* read binary part */
  92758. FLAC__ASSERT(cwords <= br->words);
  92759. if(parameter) {
  92760. while(ucbits < parameter) {
  92761. /* flush registers and read; bitreader_read_from_client_() does
  92762. * not touch br->consumed_bits at all but we still need to set
  92763. * it in case it fails and we have to return false.
  92764. */
  92765. br->consumed_bits = cbits;
  92766. br->consumed_words = cwords;
  92767. if(!bitreader_read_from_client_(br))
  92768. return false;
  92769. cwords = br->consumed_words;
  92770. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  92771. }
  92772. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92773. if(cbits) {
  92774. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  92775. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  92776. const brword word = br->buffer[cwords];
  92777. if(parameter < n) {
  92778. uval <<= parameter;
  92779. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  92780. cbits += parameter;
  92781. }
  92782. else {
  92783. uval <<= n;
  92784. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  92785. crc16_update_word_(br, word);
  92786. cwords++;
  92787. cbits = parameter - n;
  92788. if(cbits) { /* parameter > n, i.e. if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  92789. uval <<= cbits;
  92790. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  92791. }
  92792. }
  92793. }
  92794. else {
  92795. cbits = parameter;
  92796. uval <<= parameter;
  92797. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  92798. }
  92799. }
  92800. else {
  92801. /* in this case we're starting our read at a partial tail word;
  92802. * the reader has guaranteed that we have at least 'parameter'
  92803. * bits available to read, which makes this case simpler.
  92804. */
  92805. uval <<= parameter;
  92806. if(cbits) {
  92807. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92808. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  92809. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  92810. cbits += parameter;
  92811. }
  92812. else {
  92813. cbits = parameter;
  92814. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  92815. }
  92816. }
  92817. }
  92818. ucbits -= parameter;
  92819. /* compose the value */
  92820. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  92821. /* are we done? */
  92822. --nvals;
  92823. if(nvals == 0) {
  92824. br->consumed_bits = cbits;
  92825. br->consumed_words = cwords;
  92826. return true;
  92827. }
  92828. uval = 0;
  92829. ++vals;
  92830. }
  92831. }
  92832. #endif
  92833. #if 0 /* UNUSED */
  92834. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  92835. {
  92836. FLAC__uint32 lsbs = 0, msbs = 0;
  92837. unsigned bit, uval, k;
  92838. FLAC__ASSERT(0 != br);
  92839. FLAC__ASSERT(0 != br->buffer);
  92840. k = FLAC__bitmath_ilog2(parameter);
  92841. /* read the unary MSBs and end bit */
  92842. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  92843. return false;
  92844. /* read the binary LSBs */
  92845. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  92846. return false;
  92847. if(parameter == 1u<<k) {
  92848. /* compose the value */
  92849. uval = (msbs << k) | lsbs;
  92850. }
  92851. else {
  92852. unsigned d = (1 << (k+1)) - parameter;
  92853. if(lsbs >= d) {
  92854. if(!FLAC__bitreader_read_bit(br, &bit))
  92855. return false;
  92856. lsbs <<= 1;
  92857. lsbs |= bit;
  92858. lsbs -= d;
  92859. }
  92860. /* compose the value */
  92861. uval = msbs * parameter + lsbs;
  92862. }
  92863. /* unfold unsigned to signed */
  92864. if(uval & 1)
  92865. *val = -((int)(uval >> 1)) - 1;
  92866. else
  92867. *val = (int)(uval >> 1);
  92868. return true;
  92869. }
  92870. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  92871. {
  92872. FLAC__uint32 lsbs, msbs = 0;
  92873. unsigned bit, k;
  92874. FLAC__ASSERT(0 != br);
  92875. FLAC__ASSERT(0 != br->buffer);
  92876. k = FLAC__bitmath_ilog2(parameter);
  92877. /* read the unary MSBs and end bit */
  92878. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  92879. return false;
  92880. /* read the binary LSBs */
  92881. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  92882. return false;
  92883. if(parameter == 1u<<k) {
  92884. /* compose the value */
  92885. *val = (msbs << k) | lsbs;
  92886. }
  92887. else {
  92888. unsigned d = (1 << (k+1)) - parameter;
  92889. if(lsbs >= d) {
  92890. if(!FLAC__bitreader_read_bit(br, &bit))
  92891. return false;
  92892. lsbs <<= 1;
  92893. lsbs |= bit;
  92894. lsbs -= d;
  92895. }
  92896. /* compose the value */
  92897. *val = msbs * parameter + lsbs;
  92898. }
  92899. return true;
  92900. }
  92901. #endif /* UNUSED */
  92902. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  92903. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  92904. {
  92905. FLAC__uint32 v = 0;
  92906. FLAC__uint32 x;
  92907. unsigned i;
  92908. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92909. return false;
  92910. if(raw)
  92911. raw[(*rawlen)++] = (FLAC__byte)x;
  92912. if(!(x & 0x80)) { /* 0xxxxxxx */
  92913. v = x;
  92914. i = 0;
  92915. }
  92916. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  92917. v = x & 0x1F;
  92918. i = 1;
  92919. }
  92920. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  92921. v = x & 0x0F;
  92922. i = 2;
  92923. }
  92924. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  92925. v = x & 0x07;
  92926. i = 3;
  92927. }
  92928. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  92929. v = x & 0x03;
  92930. i = 4;
  92931. }
  92932. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  92933. v = x & 0x01;
  92934. i = 5;
  92935. }
  92936. else {
  92937. *val = 0xffffffff;
  92938. return true;
  92939. }
  92940. for( ; i; i--) {
  92941. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92942. return false;
  92943. if(raw)
  92944. raw[(*rawlen)++] = (FLAC__byte)x;
  92945. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  92946. *val = 0xffffffff;
  92947. return true;
  92948. }
  92949. v <<= 6;
  92950. v |= (x & 0x3F);
  92951. }
  92952. *val = v;
  92953. return true;
  92954. }
  92955. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  92956. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  92957. {
  92958. FLAC__uint64 v = 0;
  92959. FLAC__uint32 x;
  92960. unsigned i;
  92961. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92962. return false;
  92963. if(raw)
  92964. raw[(*rawlen)++] = (FLAC__byte)x;
  92965. if(!(x & 0x80)) { /* 0xxxxxxx */
  92966. v = x;
  92967. i = 0;
  92968. }
  92969. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  92970. v = x & 0x1F;
  92971. i = 1;
  92972. }
  92973. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  92974. v = x & 0x0F;
  92975. i = 2;
  92976. }
  92977. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  92978. v = x & 0x07;
  92979. i = 3;
  92980. }
  92981. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  92982. v = x & 0x03;
  92983. i = 4;
  92984. }
  92985. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  92986. v = x & 0x01;
  92987. i = 5;
  92988. }
  92989. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  92990. v = 0;
  92991. i = 6;
  92992. }
  92993. else {
  92994. *val = FLAC__U64L(0xffffffffffffffff);
  92995. return true;
  92996. }
  92997. for( ; i; i--) {
  92998. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92999. return false;
  93000. if(raw)
  93001. raw[(*rawlen)++] = (FLAC__byte)x;
  93002. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93003. *val = FLAC__U64L(0xffffffffffffffff);
  93004. return true;
  93005. }
  93006. v <<= 6;
  93007. v |= (x & 0x3F);
  93008. }
  93009. *val = v;
  93010. return true;
  93011. }
  93012. #endif
  93013. /*** End of inlined file: bitreader.c ***/
  93014. /*** Start of inlined file: bitwriter.c ***/
  93015. /*** Start of inlined file: juce_FlacHeader.h ***/
  93016. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93017. // tasks..
  93018. #define VERSION "1.2.1"
  93019. #define FLAC__NO_DLL 1
  93020. #if JUCE_MSVC
  93021. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93022. #endif
  93023. #if JUCE_MAC
  93024. #define FLAC__SYS_DARWIN 1
  93025. #endif
  93026. /*** End of inlined file: juce_FlacHeader.h ***/
  93027. #if JUCE_USE_FLAC
  93028. #if HAVE_CONFIG_H
  93029. # include <config.h>
  93030. #endif
  93031. #include <stdlib.h> /* for malloc() */
  93032. #include <string.h> /* for memcpy(), memset() */
  93033. #ifdef _MSC_VER
  93034. #include <winsock.h> /* for ntohl() */
  93035. #elif defined FLAC__SYS_DARWIN
  93036. #include <machine/endian.h> /* for ntohl() */
  93037. #elif defined __MINGW32__
  93038. #include <winsock.h> /* for ntohl() */
  93039. #else
  93040. #include <netinet/in.h> /* for ntohl() */
  93041. #endif
  93042. #if 0 /* UNUSED */
  93043. #endif
  93044. /*** Start of inlined file: bitwriter.h ***/
  93045. #ifndef FLAC__PRIVATE__BITWRITER_H
  93046. #define FLAC__PRIVATE__BITWRITER_H
  93047. #include <stdio.h> /* for FILE */
  93048. /*
  93049. * opaque structure definition
  93050. */
  93051. struct FLAC__BitWriter;
  93052. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93053. /*
  93054. * construction, deletion, initialization, etc functions
  93055. */
  93056. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93057. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93058. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93059. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93060. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93061. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93062. /*
  93063. * CRC functions
  93064. *
  93065. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93066. */
  93067. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93068. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93069. /*
  93070. * info functions
  93071. */
  93072. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93073. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93074. /*
  93075. * direct buffer access
  93076. *
  93077. * there may be no calls on the bitwriter between get and release.
  93078. * the bitwriter continues to own the returned buffer.
  93079. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93080. */
  93081. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93082. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93083. /*
  93084. * write functions
  93085. */
  93086. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93087. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93088. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93089. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93090. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93091. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93092. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93093. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93094. #if 0 /* UNUSED */
  93095. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93096. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93097. #endif
  93098. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93099. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93100. #if 0 /* UNUSED */
  93101. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93102. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93103. #endif
  93104. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  93105. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  93106. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  93107. #endif
  93108. /*** End of inlined file: bitwriter.h ***/
  93109. /*** Start of inlined file: alloc.h ***/
  93110. #ifndef FLAC__SHARE__ALLOC_H
  93111. #define FLAC__SHARE__ALLOC_H
  93112. #if HAVE_CONFIG_H
  93113. # include <config.h>
  93114. #endif
  93115. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  93116. * before #including this file, otherwise SIZE_MAX might not be defined
  93117. */
  93118. #include <limits.h> /* for SIZE_MAX */
  93119. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  93120. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  93121. #endif
  93122. #include <stdlib.h> /* for size_t, malloc(), etc */
  93123. #ifndef SIZE_MAX
  93124. # ifndef SIZE_T_MAX
  93125. # ifdef _MSC_VER
  93126. # define SIZE_T_MAX UINT_MAX
  93127. # else
  93128. # error
  93129. # endif
  93130. # endif
  93131. # define SIZE_MAX SIZE_T_MAX
  93132. #endif
  93133. #ifndef FLaC__INLINE
  93134. #define FLaC__INLINE
  93135. #endif
  93136. /* avoid malloc()ing 0 bytes, see:
  93137. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  93138. */
  93139. static FLaC__INLINE void *safe_malloc_(size_t size)
  93140. {
  93141. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93142. if(!size)
  93143. size++;
  93144. return malloc(size);
  93145. }
  93146. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  93147. {
  93148. if(!nmemb || !size)
  93149. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93150. return calloc(nmemb, size);
  93151. }
  93152. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  93153. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  93154. {
  93155. size2 += size1;
  93156. if(size2 < size1)
  93157. return 0;
  93158. return safe_malloc_(size2);
  93159. }
  93160. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  93161. {
  93162. size2 += size1;
  93163. if(size2 < size1)
  93164. return 0;
  93165. size3 += size2;
  93166. if(size3 < size2)
  93167. return 0;
  93168. return safe_malloc_(size3);
  93169. }
  93170. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  93171. {
  93172. size2 += size1;
  93173. if(size2 < size1)
  93174. return 0;
  93175. size3 += size2;
  93176. if(size3 < size2)
  93177. return 0;
  93178. size4 += size3;
  93179. if(size4 < size3)
  93180. return 0;
  93181. return safe_malloc_(size4);
  93182. }
  93183. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  93184. #if 0
  93185. needs support for cases where sizeof(size_t) != 4
  93186. {
  93187. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  93188. if(sizeof(size_t) == 4) {
  93189. if ((double)size1 * (double)size2 < 4294967296.0)
  93190. return malloc(size1*size2);
  93191. }
  93192. return 0;
  93193. }
  93194. #else
  93195. /* better? */
  93196. {
  93197. if(!size1 || !size2)
  93198. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93199. if(size1 > SIZE_MAX / size2)
  93200. return 0;
  93201. return malloc(size1*size2);
  93202. }
  93203. #endif
  93204. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  93205. {
  93206. if(!size1 || !size2 || !size3)
  93207. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93208. if(size1 > SIZE_MAX / size2)
  93209. return 0;
  93210. size1 *= size2;
  93211. if(size1 > SIZE_MAX / size3)
  93212. return 0;
  93213. return malloc(size1*size3);
  93214. }
  93215. /* size1*size2 + size3 */
  93216. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  93217. {
  93218. if(!size1 || !size2)
  93219. return safe_malloc_(size3);
  93220. if(size1 > SIZE_MAX / size2)
  93221. return 0;
  93222. return safe_malloc_add_2op_(size1*size2, size3);
  93223. }
  93224. /* size1 * (size2 + size3) */
  93225. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  93226. {
  93227. if(!size1 || (!size2 && !size3))
  93228. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93229. size2 += size3;
  93230. if(size2 < size3)
  93231. return 0;
  93232. return safe_malloc_mul_2op_(size1, size2);
  93233. }
  93234. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  93235. {
  93236. size2 += size1;
  93237. if(size2 < size1)
  93238. return 0;
  93239. return realloc(ptr, size2);
  93240. }
  93241. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  93242. {
  93243. size2 += size1;
  93244. if(size2 < size1)
  93245. return 0;
  93246. size3 += size2;
  93247. if(size3 < size2)
  93248. return 0;
  93249. return realloc(ptr, size3);
  93250. }
  93251. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  93252. {
  93253. size2 += size1;
  93254. if(size2 < size1)
  93255. return 0;
  93256. size3 += size2;
  93257. if(size3 < size2)
  93258. return 0;
  93259. size4 += size3;
  93260. if(size4 < size3)
  93261. return 0;
  93262. return realloc(ptr, size4);
  93263. }
  93264. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  93265. {
  93266. if(!size1 || !size2)
  93267. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93268. if(size1 > SIZE_MAX / size2)
  93269. return 0;
  93270. return realloc(ptr, size1*size2);
  93271. }
  93272. /* size1 * (size2 + size3) */
  93273. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  93274. {
  93275. if(!size1 || (!size2 && !size3))
  93276. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93277. size2 += size3;
  93278. if(size2 < size3)
  93279. return 0;
  93280. return safe_realloc_mul_2op_(ptr, size1, size2);
  93281. }
  93282. #endif
  93283. /*** End of inlined file: alloc.h ***/
  93284. /* Things should be fastest when this matches the machine word size */
  93285. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  93286. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  93287. typedef FLAC__uint32 bwword;
  93288. #define FLAC__BYTES_PER_WORD 4
  93289. #define FLAC__BITS_PER_WORD 32
  93290. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93291. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  93292. #if WORDS_BIGENDIAN
  93293. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93294. #else
  93295. #ifdef _MSC_VER
  93296. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93297. #else
  93298. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93299. #endif
  93300. #endif
  93301. /*
  93302. * The default capacity here doesn't matter too much. The buffer always grows
  93303. * to hold whatever is written to it. Usually the encoder will stop adding at
  93304. * a frame or metadata block, then write that out and clear the buffer for the
  93305. * next one.
  93306. */
  93307. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  93308. /* When growing, increment 4K at a time */
  93309. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  93310. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  93311. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  93312. #ifdef min
  93313. #undef min
  93314. #endif
  93315. #define min(x,y) ((x)<(y)?(x):(y))
  93316. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93317. #ifdef _MSC_VER
  93318. #define FLAC__U64L(x) x
  93319. #else
  93320. #define FLAC__U64L(x) x##LLU
  93321. #endif
  93322. #ifndef FLaC__INLINE
  93323. #define FLaC__INLINE
  93324. #endif
  93325. struct FLAC__BitWriter {
  93326. bwword *buffer;
  93327. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  93328. unsigned capacity; /* capacity of buffer in words */
  93329. unsigned words; /* # of complete words in buffer */
  93330. unsigned bits; /* # of used bits in accum */
  93331. };
  93332. /* * WATCHOUT: The current implementation only grows the buffer. */
  93333. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  93334. {
  93335. unsigned new_capacity;
  93336. bwword *new_buffer;
  93337. FLAC__ASSERT(0 != bw);
  93338. FLAC__ASSERT(0 != bw->buffer);
  93339. /* calculate total words needed to store 'bits_to_add' additional bits */
  93340. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  93341. /* it's possible (due to pessimism in the growth estimation that
  93342. * leads to this call) that we don't actually need to grow
  93343. */
  93344. if(bw->capacity >= new_capacity)
  93345. return true;
  93346. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  93347. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  93348. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93349. /* make sure we got everything right */
  93350. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93351. FLAC__ASSERT(new_capacity > bw->capacity);
  93352. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  93353. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  93354. if(new_buffer == 0)
  93355. return false;
  93356. bw->buffer = new_buffer;
  93357. bw->capacity = new_capacity;
  93358. return true;
  93359. }
  93360. /***********************************************************************
  93361. *
  93362. * Class constructor/destructor
  93363. *
  93364. ***********************************************************************/
  93365. FLAC__BitWriter *FLAC__bitwriter_new(void)
  93366. {
  93367. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  93368. /* note that calloc() sets all members to 0 for us */
  93369. return bw;
  93370. }
  93371. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  93372. {
  93373. FLAC__ASSERT(0 != bw);
  93374. FLAC__bitwriter_free(bw);
  93375. free(bw);
  93376. }
  93377. /***********************************************************************
  93378. *
  93379. * Public class methods
  93380. *
  93381. ***********************************************************************/
  93382. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  93383. {
  93384. FLAC__ASSERT(0 != bw);
  93385. bw->words = bw->bits = 0;
  93386. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  93387. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  93388. if(bw->buffer == 0)
  93389. return false;
  93390. return true;
  93391. }
  93392. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  93393. {
  93394. FLAC__ASSERT(0 != bw);
  93395. if(0 != bw->buffer)
  93396. free(bw->buffer);
  93397. bw->buffer = 0;
  93398. bw->capacity = 0;
  93399. bw->words = bw->bits = 0;
  93400. }
  93401. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  93402. {
  93403. bw->words = bw->bits = 0;
  93404. }
  93405. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  93406. {
  93407. unsigned i, j;
  93408. if(bw == 0) {
  93409. fprintf(out, "bitwriter is NULL\n");
  93410. }
  93411. else {
  93412. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  93413. for(i = 0; i < bw->words; i++) {
  93414. fprintf(out, "%08X: ", i);
  93415. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93416. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93417. fprintf(out, "\n");
  93418. }
  93419. if(bw->bits > 0) {
  93420. fprintf(out, "%08X: ", i);
  93421. for(j = 0; j < bw->bits; j++)
  93422. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  93423. fprintf(out, "\n");
  93424. }
  93425. }
  93426. }
  93427. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  93428. {
  93429. const FLAC__byte *buffer;
  93430. size_t bytes;
  93431. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  93432. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  93433. return false;
  93434. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  93435. FLAC__bitwriter_release_buffer(bw);
  93436. return true;
  93437. }
  93438. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  93439. {
  93440. const FLAC__byte *buffer;
  93441. size_t bytes;
  93442. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  93443. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  93444. return false;
  93445. *crc = FLAC__crc8(buffer, bytes);
  93446. FLAC__bitwriter_release_buffer(bw);
  93447. return true;
  93448. }
  93449. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  93450. {
  93451. return ((bw->bits & 7) == 0);
  93452. }
  93453. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  93454. {
  93455. return FLAC__TOTAL_BITS(bw);
  93456. }
  93457. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  93458. {
  93459. FLAC__ASSERT((bw->bits & 7) == 0);
  93460. /* double protection */
  93461. if(bw->bits & 7)
  93462. return false;
  93463. /* if we have bits in the accumulator we have to flush those to the buffer first */
  93464. if(bw->bits) {
  93465. FLAC__ASSERT(bw->words <= bw->capacity);
  93466. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  93467. return false;
  93468. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  93469. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  93470. }
  93471. /* now we can just return what we have */
  93472. *buffer = (FLAC__byte*)bw->buffer;
  93473. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  93474. return true;
  93475. }
  93476. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  93477. {
  93478. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  93479. * get-mode' flag could be added everywhere and then cleared here
  93480. */
  93481. (void)bw;
  93482. }
  93483. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  93484. {
  93485. unsigned n;
  93486. FLAC__ASSERT(0 != bw);
  93487. FLAC__ASSERT(0 != bw->buffer);
  93488. if(bits == 0)
  93489. return true;
  93490. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93491. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  93492. return false;
  93493. /* first part gets to word alignment */
  93494. if(bw->bits) {
  93495. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  93496. bw->accum <<= n;
  93497. bits -= n;
  93498. bw->bits += n;
  93499. if(bw->bits == FLAC__BITS_PER_WORD) {
  93500. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93501. bw->bits = 0;
  93502. }
  93503. else
  93504. return true;
  93505. }
  93506. /* do whole words */
  93507. while(bits >= FLAC__BITS_PER_WORD) {
  93508. bw->buffer[bw->words++] = 0;
  93509. bits -= FLAC__BITS_PER_WORD;
  93510. }
  93511. /* do any leftovers */
  93512. if(bits > 0) {
  93513. bw->accum = 0;
  93514. bw->bits = bits;
  93515. }
  93516. return true;
  93517. }
  93518. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  93519. {
  93520. register unsigned left;
  93521. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93522. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93523. FLAC__ASSERT(0 != bw);
  93524. FLAC__ASSERT(0 != bw->buffer);
  93525. FLAC__ASSERT(bits <= 32);
  93526. if(bits == 0)
  93527. return true;
  93528. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93529. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  93530. return false;
  93531. left = FLAC__BITS_PER_WORD - bw->bits;
  93532. if(bits < left) {
  93533. bw->accum <<= bits;
  93534. bw->accum |= val;
  93535. bw->bits += bits;
  93536. }
  93537. else if(bw->bits) { /* WATCHOUT: if bw->bits == 0, left==FLAC__BITS_PER_WORD and bw->accum<<=left is a NOP instead of setting to 0 */
  93538. bw->accum <<= left;
  93539. bw->accum |= val >> (bw->bits = bits - left);
  93540. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93541. bw->accum = val;
  93542. }
  93543. else {
  93544. bw->accum = val;
  93545. bw->bits = 0;
  93546. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  93547. }
  93548. return true;
  93549. }
  93550. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  93551. {
  93552. /* zero-out unused bits */
  93553. if(bits < 32)
  93554. val &= (~(0xffffffff << bits));
  93555. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  93556. }
  93557. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  93558. {
  93559. /* this could be a little faster but it's not used for much */
  93560. if(bits > 32) {
  93561. return
  93562. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  93563. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  93564. }
  93565. else
  93566. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  93567. }
  93568. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  93569. {
  93570. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93571. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  93572. return false;
  93573. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  93574. return false;
  93575. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  93576. return false;
  93577. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  93578. return false;
  93579. return true;
  93580. }
  93581. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  93582. {
  93583. unsigned i;
  93584. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  93585. for(i = 0; i < nvals; i++) {
  93586. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  93587. return false;
  93588. }
  93589. return true;
  93590. }
  93591. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  93592. {
  93593. if(val < 32)
  93594. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  93595. else
  93596. return
  93597. FLAC__bitwriter_write_zeroes(bw, val) &&
  93598. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  93599. }
  93600. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  93601. {
  93602. FLAC__uint32 uval;
  93603. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  93604. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  93605. uval = (val<<1) ^ (val>>31);
  93606. return 1 + parameter + (uval >> parameter);
  93607. }
  93608. #if 0 /* UNUSED */
  93609. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  93610. {
  93611. unsigned bits, msbs, uval;
  93612. unsigned k;
  93613. FLAC__ASSERT(parameter > 0);
  93614. /* fold signed to unsigned */
  93615. if(val < 0)
  93616. uval = (unsigned)(((-(++val)) << 1) + 1);
  93617. else
  93618. uval = (unsigned)(val << 1);
  93619. k = FLAC__bitmath_ilog2(parameter);
  93620. if(parameter == 1u<<k) {
  93621. FLAC__ASSERT(k <= 30);
  93622. msbs = uval >> k;
  93623. bits = 1 + k + msbs;
  93624. }
  93625. else {
  93626. unsigned q, r, d;
  93627. d = (1 << (k+1)) - parameter;
  93628. q = uval / parameter;
  93629. r = uval - (q * parameter);
  93630. bits = 1 + q + k;
  93631. if(r >= d)
  93632. bits++;
  93633. }
  93634. return bits;
  93635. }
  93636. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  93637. {
  93638. unsigned bits, msbs;
  93639. unsigned k;
  93640. FLAC__ASSERT(parameter > 0);
  93641. k = FLAC__bitmath_ilog2(parameter);
  93642. if(parameter == 1u<<k) {
  93643. FLAC__ASSERT(k <= 30);
  93644. msbs = uval >> k;
  93645. bits = 1 + k + msbs;
  93646. }
  93647. else {
  93648. unsigned q, r, d;
  93649. d = (1 << (k+1)) - parameter;
  93650. q = uval / parameter;
  93651. r = uval - (q * parameter);
  93652. bits = 1 + q + k;
  93653. if(r >= d)
  93654. bits++;
  93655. }
  93656. return bits;
  93657. }
  93658. #endif /* UNUSED */
  93659. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  93660. {
  93661. unsigned total_bits, interesting_bits, msbs;
  93662. FLAC__uint32 uval, pattern;
  93663. FLAC__ASSERT(0 != bw);
  93664. FLAC__ASSERT(0 != bw->buffer);
  93665. FLAC__ASSERT(parameter < 8*sizeof(uval));
  93666. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  93667. uval = (val<<1) ^ (val>>31);
  93668. msbs = uval >> parameter;
  93669. interesting_bits = 1 + parameter;
  93670. total_bits = interesting_bits + msbs;
  93671. pattern = 1 << parameter; /* the unary end bit */
  93672. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  93673. if(total_bits <= 32)
  93674. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  93675. else
  93676. return
  93677. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  93678. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  93679. }
  93680. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  93681. {
  93682. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  93683. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  93684. FLAC__uint32 uval;
  93685. unsigned left;
  93686. const unsigned lsbits = 1 + parameter;
  93687. unsigned msbits;
  93688. FLAC__ASSERT(0 != bw);
  93689. FLAC__ASSERT(0 != bw->buffer);
  93690. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  93691. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93692. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93693. while(nvals) {
  93694. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  93695. uval = (*vals<<1) ^ (*vals>>31);
  93696. msbits = uval >> parameter;
  93697. #if 0 /* OPT: can remove this special case if it doesn't make up for the extra compare (doesn't make a statistically significant difference with msvc or gcc/x86) */
  93698. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  93699. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  93700. bw->bits = bw->bits + msbits + lsbits;
  93701. uval |= mask1; /* set stop bit */
  93702. uval &= mask2; /* mask off unused top bits */
  93703. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  93704. bw->accum <<= msbits;
  93705. bw->accum <<= lsbits;
  93706. bw->accum |= uval;
  93707. if(bw->bits == FLAC__BITS_PER_WORD) {
  93708. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93709. bw->bits = 0;
  93710. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  93711. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  93712. FLAC__ASSERT(bw->capacity == bw->words);
  93713. return false;
  93714. }
  93715. }
  93716. }
  93717. else {
  93718. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  93719. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  93720. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  93721. bw->bits = bw->bits + msbits + lsbits;
  93722. uval |= mask1; /* set stop bit */
  93723. uval &= mask2; /* mask off unused top bits */
  93724. bw->accum <<= msbits + lsbits;
  93725. bw->accum |= uval;
  93726. }
  93727. else {
  93728. #endif
  93729. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93730. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  93731. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  93732. return false;
  93733. if(msbits) {
  93734. /* first part gets to word alignment */
  93735. if(bw->bits) {
  93736. left = FLAC__BITS_PER_WORD - bw->bits;
  93737. if(msbits < left) {
  93738. bw->accum <<= msbits;
  93739. bw->bits += msbits;
  93740. goto break1;
  93741. }
  93742. else {
  93743. bw->accum <<= left;
  93744. msbits -= left;
  93745. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93746. bw->bits = 0;
  93747. }
  93748. }
  93749. /* do whole words */
  93750. while(msbits >= FLAC__BITS_PER_WORD) {
  93751. bw->buffer[bw->words++] = 0;
  93752. msbits -= FLAC__BITS_PER_WORD;
  93753. }
  93754. /* do any leftovers */
  93755. if(msbits > 0) {
  93756. bw->accum = 0;
  93757. bw->bits = msbits;
  93758. }
  93759. }
  93760. break1:
  93761. uval |= mask1; /* set stop bit */
  93762. uval &= mask2; /* mask off unused top bits */
  93763. left = FLAC__BITS_PER_WORD - bw->bits;
  93764. if(lsbits < left) {
  93765. bw->accum <<= lsbits;
  93766. bw->accum |= uval;
  93767. bw->bits += lsbits;
  93768. }
  93769. else {
  93770. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  93771. * be > lsbits (because of previous assertions) so it would have
  93772. * triggered the (lsbits<left) case above.
  93773. */
  93774. FLAC__ASSERT(bw->bits);
  93775. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  93776. bw->accum <<= left;
  93777. bw->accum |= uval >> (bw->bits = lsbits - left);
  93778. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93779. bw->accum = uval;
  93780. }
  93781. #if 1
  93782. }
  93783. #endif
  93784. vals++;
  93785. nvals--;
  93786. }
  93787. return true;
  93788. }
  93789. #if 0 /* UNUSED */
  93790. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  93791. {
  93792. unsigned total_bits, msbs, uval;
  93793. unsigned k;
  93794. FLAC__ASSERT(0 != bw);
  93795. FLAC__ASSERT(0 != bw->buffer);
  93796. FLAC__ASSERT(parameter > 0);
  93797. /* fold signed to unsigned */
  93798. if(val < 0)
  93799. uval = (unsigned)(((-(++val)) << 1) + 1);
  93800. else
  93801. uval = (unsigned)(val << 1);
  93802. k = FLAC__bitmath_ilog2(parameter);
  93803. if(parameter == 1u<<k) {
  93804. unsigned pattern;
  93805. FLAC__ASSERT(k <= 30);
  93806. msbs = uval >> k;
  93807. total_bits = 1 + k + msbs;
  93808. pattern = 1 << k; /* the unary end bit */
  93809. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  93810. if(total_bits <= 32) {
  93811. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  93812. return false;
  93813. }
  93814. else {
  93815. /* write the unary MSBs */
  93816. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  93817. return false;
  93818. /* write the unary end bit and binary LSBs */
  93819. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  93820. return false;
  93821. }
  93822. }
  93823. else {
  93824. unsigned q, r, d;
  93825. d = (1 << (k+1)) - parameter;
  93826. q = uval / parameter;
  93827. r = uval - (q * parameter);
  93828. /* write the unary MSBs */
  93829. if(!FLAC__bitwriter_write_zeroes(bw, q))
  93830. return false;
  93831. /* write the unary end bit */
  93832. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  93833. return false;
  93834. /* write the binary LSBs */
  93835. if(r >= d) {
  93836. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  93837. return false;
  93838. }
  93839. else {
  93840. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  93841. return false;
  93842. }
  93843. }
  93844. return true;
  93845. }
  93846. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  93847. {
  93848. unsigned total_bits, msbs;
  93849. unsigned k;
  93850. FLAC__ASSERT(0 != bw);
  93851. FLAC__ASSERT(0 != bw->buffer);
  93852. FLAC__ASSERT(parameter > 0);
  93853. k = FLAC__bitmath_ilog2(parameter);
  93854. if(parameter == 1u<<k) {
  93855. unsigned pattern;
  93856. FLAC__ASSERT(k <= 30);
  93857. msbs = uval >> k;
  93858. total_bits = 1 + k + msbs;
  93859. pattern = 1 << k; /* the unary end bit */
  93860. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  93861. if(total_bits <= 32) {
  93862. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  93863. return false;
  93864. }
  93865. else {
  93866. /* write the unary MSBs */
  93867. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  93868. return false;
  93869. /* write the unary end bit and binary LSBs */
  93870. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  93871. return false;
  93872. }
  93873. }
  93874. else {
  93875. unsigned q, r, d;
  93876. d = (1 << (k+1)) - parameter;
  93877. q = uval / parameter;
  93878. r = uval - (q * parameter);
  93879. /* write the unary MSBs */
  93880. if(!FLAC__bitwriter_write_zeroes(bw, q))
  93881. return false;
  93882. /* write the unary end bit */
  93883. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  93884. return false;
  93885. /* write the binary LSBs */
  93886. if(r >= d) {
  93887. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  93888. return false;
  93889. }
  93890. else {
  93891. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  93892. return false;
  93893. }
  93894. }
  93895. return true;
  93896. }
  93897. #endif /* UNUSED */
  93898. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  93899. {
  93900. FLAC__bool ok = 1;
  93901. FLAC__ASSERT(0 != bw);
  93902. FLAC__ASSERT(0 != bw->buffer);
  93903. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  93904. if(val < 0x80) {
  93905. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  93906. }
  93907. else if(val < 0x800) {
  93908. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  93909. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  93910. }
  93911. else if(val < 0x10000) {
  93912. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  93913. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  93914. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  93915. }
  93916. else if(val < 0x200000) {
  93917. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  93918. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  93919. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  93920. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  93921. }
  93922. else if(val < 0x4000000) {
  93923. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  93924. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  93925. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  93926. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  93927. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  93928. }
  93929. else {
  93930. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  93931. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  93932. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  93933. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  93934. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  93935. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  93936. }
  93937. return ok;
  93938. }
  93939. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  93940. {
  93941. FLAC__bool ok = 1;
  93942. FLAC__ASSERT(0 != bw);
  93943. FLAC__ASSERT(0 != bw->buffer);
  93944. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  93945. if(val < 0x80) {
  93946. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  93947. }
  93948. else if(val < 0x800) {
  93949. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  93950. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  93951. }
  93952. else if(val < 0x10000) {
  93953. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  93954. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  93955. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  93956. }
  93957. else if(val < 0x200000) {
  93958. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  93959. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  93960. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  93961. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  93962. }
  93963. else if(val < 0x4000000) {
  93964. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  93965. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  93966. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  93967. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  93968. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  93969. }
  93970. else if(val < 0x80000000) {
  93971. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  93972. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  93973. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  93974. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  93975. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  93976. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  93977. }
  93978. else {
  93979. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  93980. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  93981. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  93982. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  93983. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  93984. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  93985. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  93986. }
  93987. return ok;
  93988. }
  93989. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  93990. {
  93991. /* 0-pad to byte boundary */
  93992. if(bw->bits & 7u)
  93993. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  93994. else
  93995. return true;
  93996. }
  93997. #endif
  93998. /*** End of inlined file: bitwriter.c ***/
  93999. /*** Start of inlined file: cpu.c ***/
  94000. /*** Start of inlined file: juce_FlacHeader.h ***/
  94001. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94002. // tasks..
  94003. #define VERSION "1.2.1"
  94004. #define FLAC__NO_DLL 1
  94005. #if JUCE_MSVC
  94006. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94007. #endif
  94008. #if JUCE_MAC
  94009. #define FLAC__SYS_DARWIN 1
  94010. #endif
  94011. /*** End of inlined file: juce_FlacHeader.h ***/
  94012. #if JUCE_USE_FLAC
  94013. #if HAVE_CONFIG_H
  94014. # include <config.h>
  94015. #endif
  94016. #include <stdlib.h>
  94017. #include <stdio.h>
  94018. #if defined FLAC__CPU_IA32
  94019. # include <signal.h>
  94020. #elif defined FLAC__CPU_PPC
  94021. # if !defined FLAC__NO_ASM
  94022. # if defined FLAC__SYS_DARWIN
  94023. # include <sys/sysctl.h>
  94024. # include <mach/mach.h>
  94025. # include <mach/mach_host.h>
  94026. # include <mach/host_info.h>
  94027. # include <mach/machine.h>
  94028. # ifndef CPU_SUBTYPE_POWERPC_970
  94029. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94030. # endif
  94031. # else /* FLAC__SYS_DARWIN */
  94032. # include <signal.h>
  94033. # include <setjmp.h>
  94034. static sigjmp_buf jmpbuf;
  94035. static volatile sig_atomic_t canjump = 0;
  94036. static void sigill_handler (int sig)
  94037. {
  94038. if (!canjump) {
  94039. signal (sig, SIG_DFL);
  94040. raise (sig);
  94041. }
  94042. canjump = 0;
  94043. siglongjmp (jmpbuf, 1);
  94044. }
  94045. # endif /* FLAC__SYS_DARWIN */
  94046. # endif /* FLAC__NO_ASM */
  94047. #endif /* FLAC__CPU_PPC */
  94048. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94049. #include <sys/param.h>
  94050. #include <sys/sysctl.h>
  94051. #include <machine/cpu.h>
  94052. #endif
  94053. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94054. #include <sys/types.h>
  94055. #include <sys/sysctl.h>
  94056. #endif
  94057. #if defined(__APPLE__)
  94058. /* how to get sysctlbyname()? */
  94059. #endif
  94060. /* these are flags in EDX of CPUID AX=00000001 */
  94061. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94062. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94063. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94064. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94065. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94066. /* these are flags in ECX of CPUID AX=00000001 */
  94067. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94068. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94069. /* these are flags in EDX of CPUID AX=80000001 */
  94070. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94071. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94072. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94073. /*
  94074. * Extra stuff needed for detection of OS support for SSE on IA-32
  94075. */
  94076. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94077. # if defined(__linux__)
  94078. /*
  94079. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94080. * modify the return address to jump over the offending SSE instruction
  94081. * and also the operation following it that indicates the instruction
  94082. * executed successfully. In this way we use no global variables and
  94083. * stay thread-safe.
  94084. *
  94085. * 3 + 3 + 6:
  94086. * 3 bytes for "xorps xmm0,xmm0"
  94087. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94088. * 6 bytes extra in case our estimate is wrong
  94089. * 12 bytes puts us in the NOP "landing zone"
  94090. */
  94091. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94092. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94093. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94094. {
  94095. (void)signal;
  94096. sc.eip += 3 + 3 + 6;
  94097. }
  94098. # else
  94099. # include <sys/ucontext.h>
  94100. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94101. {
  94102. (void)signal, (void)si;
  94103. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  94104. }
  94105. # endif
  94106. # elif defined(_MSC_VER)
  94107. # include <windows.h>
  94108. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  94109. # ifdef USE_TRY_CATCH_FLAVOR
  94110. # else
  94111. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  94112. {
  94113. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  94114. ep->ContextRecord->Eip += 3 + 3 + 6;
  94115. return EXCEPTION_CONTINUE_EXECUTION;
  94116. }
  94117. return EXCEPTION_CONTINUE_SEARCH;
  94118. }
  94119. # endif
  94120. # endif
  94121. #endif
  94122. void FLAC__cpu_info(FLAC__CPUInfo *info)
  94123. {
  94124. /*
  94125. * IA32-specific
  94126. */
  94127. #ifdef FLAC__CPU_IA32
  94128. info->type = FLAC__CPUINFO_TYPE_IA32;
  94129. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  94130. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  94131. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  94132. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  94133. info->data.ia32.cmov = false;
  94134. info->data.ia32.mmx = false;
  94135. info->data.ia32.fxsr = false;
  94136. info->data.ia32.sse = false;
  94137. info->data.ia32.sse2 = false;
  94138. info->data.ia32.sse3 = false;
  94139. info->data.ia32.ssse3 = false;
  94140. info->data.ia32._3dnow = false;
  94141. info->data.ia32.ext3dnow = false;
  94142. info->data.ia32.extmmx = false;
  94143. if(info->data.ia32.cpuid) {
  94144. /* http://www.sandpile.org/ia32/cpuid.htm */
  94145. FLAC__uint32 flags_edx, flags_ecx;
  94146. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  94147. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  94148. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  94149. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  94150. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  94151. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  94152. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  94153. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  94154. #ifdef FLAC__USE_3DNOW
  94155. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  94156. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  94157. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  94158. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  94159. #else
  94160. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  94161. #endif
  94162. #ifdef DEBUG
  94163. fprintf(stderr, "CPU info (IA-32):\n");
  94164. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  94165. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  94166. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  94167. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  94168. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  94169. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94170. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  94171. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  94172. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  94173. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  94174. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  94175. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  94176. #endif
  94177. /*
  94178. * now have to check for OS support of SSE/SSE2
  94179. */
  94180. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  94181. #if defined FLAC__NO_SSE_OS
  94182. /* assume user knows better than us; turn it off */
  94183. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94184. #elif defined FLAC__SSE_OS
  94185. /* assume user knows better than us; leave as detected above */
  94186. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  94187. int sse = 0;
  94188. size_t len;
  94189. /* at least one of these must work: */
  94190. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  94191. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  94192. if(!sse)
  94193. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94194. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  94195. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  94196. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  94197. size_t len = sizeof(val);
  94198. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94199. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94200. else { /* double-check SSE2 */
  94201. mib[1] = CPU_SSE2;
  94202. len = sizeof(val);
  94203. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94204. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94205. }
  94206. # else
  94207. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94208. # endif
  94209. #elif defined(__linux__)
  94210. int sse = 0;
  94211. struct sigaction sigill_save;
  94212. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94213. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  94214. #else
  94215. struct sigaction sigill_sse;
  94216. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  94217. __sigemptyset(&sigill_sse.sa_mask);
  94218. sigill_sse.sa_flags = SA_SIGINFO | SA_RESETHAND; /* SA_RESETHAND just in case our SIGILL return jump breaks, so we don't get stuck in a loop */
  94219. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  94220. #endif
  94221. {
  94222. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  94223. /* see sigill_handler_sse_os() for an explanation of the following: */
  94224. asm volatile (
  94225. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  94226. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  94227. "incl %0\n\t" /* SIGILL handler will jump over this */
  94228. /* landing zone */
  94229. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  94230. "nop\n\t"
  94231. "nop\n\t"
  94232. "nop\n\t"
  94233. "nop\n\t"
  94234. "nop\n\t"
  94235. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  94236. "nop\n\t"
  94237. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  94238. : "=r"(sse)
  94239. : "r"(sse)
  94240. );
  94241. sigaction(SIGILL, &sigill_save, NULL);
  94242. }
  94243. if(!sse)
  94244. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94245. #elif defined(_MSC_VER)
  94246. # ifdef USE_TRY_CATCH_FLAVOR
  94247. _try {
  94248. __asm {
  94249. # if _MSC_VER <= 1200
  94250. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94251. _emit 0x0F
  94252. _emit 0x57
  94253. _emit 0xC0
  94254. # else
  94255. xorps xmm0,xmm0
  94256. # endif
  94257. }
  94258. }
  94259. _except(EXCEPTION_EXECUTE_HANDLER) {
  94260. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  94261. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94262. }
  94263. # else
  94264. int sse = 0;
  94265. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  94266. /* see GCC version above for explanation */
  94267. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  94268. /* http://www.codeproject.com/cpp/gccasm.asp */
  94269. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  94270. __asm {
  94271. # if _MSC_VER <= 1200
  94272. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94273. _emit 0x0F
  94274. _emit 0x57
  94275. _emit 0xC0
  94276. # else
  94277. xorps xmm0,xmm0
  94278. # endif
  94279. inc sse
  94280. nop
  94281. nop
  94282. nop
  94283. nop
  94284. nop
  94285. nop
  94286. nop
  94287. nop
  94288. nop
  94289. }
  94290. SetUnhandledExceptionFilter(save);
  94291. if(!sse)
  94292. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94293. # endif
  94294. #else
  94295. /* no way to test, disable to be safe */
  94296. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94297. #endif
  94298. #ifdef DEBUG
  94299. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94300. #endif
  94301. }
  94302. }
  94303. #else
  94304. info->use_asm = false;
  94305. #endif
  94306. /*
  94307. * PPC-specific
  94308. */
  94309. #elif defined FLAC__CPU_PPC
  94310. info->type = FLAC__CPUINFO_TYPE_PPC;
  94311. # if !defined FLAC__NO_ASM
  94312. info->use_asm = true;
  94313. # ifdef FLAC__USE_ALTIVEC
  94314. # if defined FLAC__SYS_DARWIN
  94315. {
  94316. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  94317. size_t len = sizeof(val);
  94318. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  94319. }
  94320. {
  94321. host_basic_info_data_t hostInfo;
  94322. mach_msg_type_number_t infoCount;
  94323. infoCount = HOST_BASIC_INFO_COUNT;
  94324. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  94325. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  94326. }
  94327. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  94328. {
  94329. /* no Darwin, do it the brute-force way */
  94330. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  94331. info->data.ppc.altivec = 0;
  94332. info->data.ppc.ppc64 = 0;
  94333. signal (SIGILL, sigill_handler);
  94334. canjump = 0;
  94335. if (!sigsetjmp (jmpbuf, 1)) {
  94336. canjump = 1;
  94337. asm volatile (
  94338. "mtspr 256, %0\n\t"
  94339. "vand %%v0, %%v0, %%v0"
  94340. :
  94341. : "r" (-1)
  94342. );
  94343. info->data.ppc.altivec = 1;
  94344. }
  94345. canjump = 0;
  94346. if (!sigsetjmp (jmpbuf, 1)) {
  94347. int x = 0;
  94348. canjump = 1;
  94349. /* PPC64 hardware implements the cntlzd instruction */
  94350. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  94351. info->data.ppc.ppc64 = 1;
  94352. }
  94353. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  94354. }
  94355. # endif
  94356. # else /* !FLAC__USE_ALTIVEC */
  94357. info->data.ppc.altivec = 0;
  94358. info->data.ppc.ppc64 = 0;
  94359. # endif
  94360. # else
  94361. info->use_asm = false;
  94362. # endif
  94363. /*
  94364. * unknown CPI
  94365. */
  94366. #else
  94367. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  94368. info->use_asm = false;
  94369. #endif
  94370. }
  94371. #endif
  94372. /*** End of inlined file: cpu.c ***/
  94373. /*** Start of inlined file: crc.c ***/
  94374. /*** Start of inlined file: juce_FlacHeader.h ***/
  94375. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94376. // tasks..
  94377. #define VERSION "1.2.1"
  94378. #define FLAC__NO_DLL 1
  94379. #if JUCE_MSVC
  94380. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94381. #endif
  94382. #if JUCE_MAC
  94383. #define FLAC__SYS_DARWIN 1
  94384. #endif
  94385. /*** End of inlined file: juce_FlacHeader.h ***/
  94386. #if JUCE_USE_FLAC
  94387. #if HAVE_CONFIG_H
  94388. # include <config.h>
  94389. #endif
  94390. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  94391. FLAC__byte const FLAC__crc8_table[256] = {
  94392. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  94393. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  94394. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  94395. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  94396. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  94397. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  94398. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  94399. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  94400. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  94401. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  94402. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  94403. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  94404. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  94405. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  94406. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  94407. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  94408. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  94409. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  94410. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  94411. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  94412. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  94413. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  94414. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  94415. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  94416. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  94417. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  94418. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  94419. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  94420. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  94421. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  94422. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  94423. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  94424. };
  94425. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  94426. unsigned FLAC__crc16_table[256] = {
  94427. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  94428. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  94429. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  94430. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  94431. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  94432. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  94433. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  94434. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  94435. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  94436. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  94437. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  94438. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  94439. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  94440. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  94441. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  94442. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  94443. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  94444. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  94445. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  94446. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  94447. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  94448. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  94449. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  94450. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  94451. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  94452. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  94453. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  94454. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  94455. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  94456. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  94457. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  94458. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  94459. };
  94460. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  94461. {
  94462. *crc = FLAC__crc8_table[*crc ^ data];
  94463. }
  94464. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  94465. {
  94466. while(len--)
  94467. *crc = FLAC__crc8_table[*crc ^ *data++];
  94468. }
  94469. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  94470. {
  94471. FLAC__uint8 crc = 0;
  94472. while(len--)
  94473. crc = FLAC__crc8_table[crc ^ *data++];
  94474. return crc;
  94475. }
  94476. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  94477. {
  94478. unsigned crc = 0;
  94479. while(len--)
  94480. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  94481. return crc;
  94482. }
  94483. #endif
  94484. /*** End of inlined file: crc.c ***/
  94485. /*** Start of inlined file: fixed.c ***/
  94486. /*** Start of inlined file: juce_FlacHeader.h ***/
  94487. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94488. // tasks..
  94489. #define VERSION "1.2.1"
  94490. #define FLAC__NO_DLL 1
  94491. #if JUCE_MSVC
  94492. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94493. #endif
  94494. #if JUCE_MAC
  94495. #define FLAC__SYS_DARWIN 1
  94496. #endif
  94497. /*** End of inlined file: juce_FlacHeader.h ***/
  94498. #if JUCE_USE_FLAC
  94499. #if HAVE_CONFIG_H
  94500. # include <config.h>
  94501. #endif
  94502. #include <math.h>
  94503. #include <string.h>
  94504. /*** Start of inlined file: fixed.h ***/
  94505. #ifndef FLAC__PRIVATE__FIXED_H
  94506. #define FLAC__PRIVATE__FIXED_H
  94507. #ifdef HAVE_CONFIG_H
  94508. #include <config.h>
  94509. #endif
  94510. /*** Start of inlined file: float.h ***/
  94511. #ifndef FLAC__PRIVATE__FLOAT_H
  94512. #define FLAC__PRIVATE__FLOAT_H
  94513. #ifdef HAVE_CONFIG_H
  94514. #include <config.h>
  94515. #endif
  94516. /*
  94517. * These typedefs make it easier to ensure that integer versions of
  94518. * the library really only contain integer operations. All the code
  94519. * in libFLAC should use FLAC__float and FLAC__double in place of
  94520. * float and double, and be protected by checks of the macro
  94521. * FLAC__INTEGER_ONLY_LIBRARY.
  94522. *
  94523. * FLAC__real is the basic floating point type used in LPC analysis.
  94524. */
  94525. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94526. typedef double FLAC__double;
  94527. typedef float FLAC__float;
  94528. /*
  94529. * WATCHOUT: changing FLAC__real will change the signatures of many
  94530. * functions that have assembly language equivalents and break them.
  94531. */
  94532. typedef float FLAC__real;
  94533. #else
  94534. /*
  94535. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  94536. * for the integer part and lower 16 bits for the fractional part.
  94537. */
  94538. typedef FLAC__int32 FLAC__fixedpoint;
  94539. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  94540. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  94541. extern const FLAC__fixedpoint FLAC__FP_ONE;
  94542. extern const FLAC__fixedpoint FLAC__FP_LN2;
  94543. extern const FLAC__fixedpoint FLAC__FP_E;
  94544. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  94545. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  94546. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  94547. /*
  94548. * FLAC__fixedpoint_log2()
  94549. * --------------------------------------------------------------------
  94550. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  94551. * algorithm by Knuth for x >= 1.0
  94552. *
  94553. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  94554. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  94555. *
  94556. * 'precision' roughly limits the number of iterations that are done;
  94557. * use (unsigned)(-1) for maximum precision.
  94558. *
  94559. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  94560. * function will punt and return 0.
  94561. *
  94562. * The return value will also have 'fracbits' fractional bits.
  94563. */
  94564. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  94565. #endif
  94566. #endif
  94567. /*** End of inlined file: float.h ***/
  94568. /*** Start of inlined file: format.h ***/
  94569. #ifndef FLAC__PRIVATE__FORMAT_H
  94570. #define FLAC__PRIVATE__FORMAT_H
  94571. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  94572. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  94573. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  94574. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  94575. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  94576. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  94577. #endif
  94578. /*** End of inlined file: format.h ***/
  94579. /*
  94580. * FLAC__fixed_compute_best_predictor()
  94581. * --------------------------------------------------------------------
  94582. * Compute the best fixed predictor and the expected bits-per-sample
  94583. * of the residual signal for each order. The _wide() version uses
  94584. * 64-bit integers which is statistically necessary when bits-per-
  94585. * sample + log2(blocksize) > 30
  94586. *
  94587. * IN data[0,data_len-1]
  94588. * IN data_len
  94589. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  94590. */
  94591. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94592. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94593. # ifndef FLAC__NO_ASM
  94594. # ifdef FLAC__CPU_IA32
  94595. # ifdef FLAC__HAS_NASM
  94596. unsigned FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94597. # endif
  94598. # endif
  94599. # endif
  94600. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94601. #else
  94602. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94603. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94604. #endif
  94605. /*
  94606. * FLAC__fixed_compute_residual()
  94607. * --------------------------------------------------------------------
  94608. * Compute the residual signal obtained from sutracting the predicted
  94609. * signal from the original.
  94610. *
  94611. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  94612. * IN data_len length of original signal
  94613. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  94614. * OUT residual[0,data_len-1] residual signal
  94615. */
  94616. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  94617. /*
  94618. * FLAC__fixed_restore_signal()
  94619. * --------------------------------------------------------------------
  94620. * Restore the original signal by summing the residual and the
  94621. * predictor.
  94622. *
  94623. * IN residual[0,data_len-1] residual signal
  94624. * IN data_len length of original signal
  94625. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  94626. * *** IMPORTANT: the caller must pass in the historical samples:
  94627. * IN data[-order,-1] previously-reconstructed historical samples
  94628. * OUT data[0,data_len-1] original signal
  94629. */
  94630. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  94631. #endif
  94632. /*** End of inlined file: fixed.h ***/
  94633. #ifndef M_LN2
  94634. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  94635. #define M_LN2 0.69314718055994530942
  94636. #endif
  94637. #ifdef min
  94638. #undef min
  94639. #endif
  94640. #define min(x,y) ((x) < (y)? (x) : (y))
  94641. #ifdef local_abs
  94642. #undef local_abs
  94643. #endif
  94644. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  94645. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  94646. /* rbps stands for residual bits per sample
  94647. *
  94648. * (ln(2) * err)
  94649. * rbps = log (-----------)
  94650. * 2 ( n )
  94651. */
  94652. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  94653. {
  94654. FLAC__uint32 rbps;
  94655. unsigned bits; /* the number of bits required to represent a number */
  94656. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  94657. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  94658. FLAC__ASSERT(err > 0);
  94659. FLAC__ASSERT(n > 0);
  94660. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  94661. if(err <= n)
  94662. return 0;
  94663. /*
  94664. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  94665. * These allow us later to know we won't lose too much precision in the
  94666. * fixed-point division (err<<fracbits)/n.
  94667. */
  94668. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  94669. err <<= fracbits;
  94670. err /= n;
  94671. /* err now holds err/n with fracbits fractional bits */
  94672. /*
  94673. * Whittle err down to 16 bits max. 16 significant bits is enough for
  94674. * our purposes.
  94675. */
  94676. FLAC__ASSERT(err > 0);
  94677. bits = FLAC__bitmath_ilog2(err)+1;
  94678. if(bits > 16) {
  94679. err >>= (bits-16);
  94680. fracbits -= (bits-16);
  94681. }
  94682. rbps = (FLAC__uint32)err;
  94683. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  94684. rbps *= FLAC__FP_LN2;
  94685. fracbits += 16;
  94686. FLAC__ASSERT(fracbits >= 0);
  94687. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  94688. {
  94689. const int f = fracbits & 3;
  94690. if(f) {
  94691. rbps >>= f;
  94692. fracbits -= f;
  94693. }
  94694. }
  94695. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  94696. if(rbps == 0)
  94697. return 0;
  94698. /*
  94699. * The return value must have 16 fractional bits. Since the whole part
  94700. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  94701. * must be >= -3, these assertion allows us to be able to shift rbps
  94702. * left if necessary to get 16 fracbits without losing any bits of the
  94703. * whole part of rbps.
  94704. *
  94705. * There is a slight chance due to accumulated error that the whole part
  94706. * will require 6 bits, so we use 6 in the assertion. Really though as
  94707. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  94708. */
  94709. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  94710. FLAC__ASSERT(fracbits >= -3);
  94711. /* now shift the decimal point into place */
  94712. if(fracbits < 16)
  94713. return rbps << (16-fracbits);
  94714. else if(fracbits > 16)
  94715. return rbps >> (fracbits-16);
  94716. else
  94717. return rbps;
  94718. }
  94719. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  94720. {
  94721. FLAC__uint32 rbps;
  94722. unsigned bits; /* the number of bits required to represent a number */
  94723. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  94724. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  94725. FLAC__ASSERT(err > 0);
  94726. FLAC__ASSERT(n > 0);
  94727. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  94728. if(err <= n)
  94729. return 0;
  94730. /*
  94731. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  94732. * These allow us later to know we won't lose too much precision in the
  94733. * fixed-point division (err<<fracbits)/n.
  94734. */
  94735. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  94736. err <<= fracbits;
  94737. err /= n;
  94738. /* err now holds err/n with fracbits fractional bits */
  94739. /*
  94740. * Whittle err down to 16 bits max. 16 significant bits is enough for
  94741. * our purposes.
  94742. */
  94743. FLAC__ASSERT(err > 0);
  94744. bits = FLAC__bitmath_ilog2_wide(err)+1;
  94745. if(bits > 16) {
  94746. err >>= (bits-16);
  94747. fracbits -= (bits-16);
  94748. }
  94749. rbps = (FLAC__uint32)err;
  94750. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  94751. rbps *= FLAC__FP_LN2;
  94752. fracbits += 16;
  94753. FLAC__ASSERT(fracbits >= 0);
  94754. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  94755. {
  94756. const int f = fracbits & 3;
  94757. if(f) {
  94758. rbps >>= f;
  94759. fracbits -= f;
  94760. }
  94761. }
  94762. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  94763. if(rbps == 0)
  94764. return 0;
  94765. /*
  94766. * The return value must have 16 fractional bits. Since the whole part
  94767. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  94768. * must be >= -3, these assertion allows us to be able to shift rbps
  94769. * left if necessary to get 16 fracbits without losing any bits of the
  94770. * whole part of rbps.
  94771. *
  94772. * There is a slight chance due to accumulated error that the whole part
  94773. * will require 6 bits, so we use 6 in the assertion. Really though as
  94774. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  94775. */
  94776. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  94777. FLAC__ASSERT(fracbits >= -3);
  94778. /* now shift the decimal point into place */
  94779. if(fracbits < 16)
  94780. return rbps << (16-fracbits);
  94781. else if(fracbits > 16)
  94782. return rbps >> (fracbits-16);
  94783. else
  94784. return rbps;
  94785. }
  94786. #endif
  94787. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94788. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  94789. #else
  94790. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  94791. #endif
  94792. {
  94793. FLAC__int32 last_error_0 = data[-1];
  94794. FLAC__int32 last_error_1 = data[-1] - data[-2];
  94795. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  94796. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  94797. FLAC__int32 error, save;
  94798. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  94799. unsigned i, order;
  94800. for(i = 0; i < data_len; i++) {
  94801. error = data[i] ; total_error_0 += local_abs(error); save = error;
  94802. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  94803. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  94804. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  94805. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  94806. }
  94807. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  94808. order = 0;
  94809. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  94810. order = 1;
  94811. else if(total_error_2 < min(total_error_3, total_error_4))
  94812. order = 2;
  94813. else if(total_error_3 < total_error_4)
  94814. order = 3;
  94815. else
  94816. order = 4;
  94817. /* Estimate the expected number of bits per residual signal sample. */
  94818. /* 'total_error*' is linearly related to the variance of the residual */
  94819. /* signal, so we use it directly to compute E(|x|) */
  94820. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  94821. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  94822. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  94823. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  94824. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  94825. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94826. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94827. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94828. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94829. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94830. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94831. #else
  94832. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  94833. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  94834. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  94835. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  94836. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  94837. #endif
  94838. return order;
  94839. }
  94840. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94841. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  94842. #else
  94843. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  94844. #endif
  94845. {
  94846. FLAC__int32 last_error_0 = data[-1];
  94847. FLAC__int32 last_error_1 = data[-1] - data[-2];
  94848. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  94849. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  94850. FLAC__int32 error, save;
  94851. /* total_error_* are 64-bits to avoid overflow when encoding
  94852. * erratic signals when the bits-per-sample and blocksize are
  94853. * large.
  94854. */
  94855. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  94856. unsigned i, order;
  94857. for(i = 0; i < data_len; i++) {
  94858. error = data[i] ; total_error_0 += local_abs(error); save = error;
  94859. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  94860. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  94861. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  94862. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  94863. }
  94864. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  94865. order = 0;
  94866. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  94867. order = 1;
  94868. else if(total_error_2 < min(total_error_3, total_error_4))
  94869. order = 2;
  94870. else if(total_error_3 < total_error_4)
  94871. order = 3;
  94872. else
  94873. order = 4;
  94874. /* Estimate the expected number of bits per residual signal sample. */
  94875. /* 'total_error*' is linearly related to the variance of the residual */
  94876. /* signal, so we use it directly to compute E(|x|) */
  94877. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  94878. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  94879. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  94880. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  94881. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  94882. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94883. #if defined _MSC_VER || defined __MINGW32__
  94884. /* with MSVC you have to spoon feed it the casting */
  94885. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94886. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94887. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94888. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94889. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94890. #else
  94891. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94892. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94893. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94894. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94895. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  94896. #endif
  94897. #else
  94898. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  94899. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  94900. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  94901. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  94902. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  94903. #endif
  94904. return order;
  94905. }
  94906. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  94907. {
  94908. const int idata_len = (int)data_len;
  94909. int i;
  94910. switch(order) {
  94911. case 0:
  94912. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  94913. memcpy(residual, data, sizeof(residual[0])*data_len);
  94914. break;
  94915. case 1:
  94916. for(i = 0; i < idata_len; i++)
  94917. residual[i] = data[i] - data[i-1];
  94918. break;
  94919. case 2:
  94920. for(i = 0; i < idata_len; i++)
  94921. #if 1 /* OPT: may be faster with some compilers on some systems */
  94922. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  94923. #else
  94924. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  94925. #endif
  94926. break;
  94927. case 3:
  94928. for(i = 0; i < idata_len; i++)
  94929. #if 1 /* OPT: may be faster with some compilers on some systems */
  94930. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  94931. #else
  94932. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  94933. #endif
  94934. break;
  94935. case 4:
  94936. for(i = 0; i < idata_len; i++)
  94937. #if 1 /* OPT: may be faster with some compilers on some systems */
  94938. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  94939. #else
  94940. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  94941. #endif
  94942. break;
  94943. default:
  94944. FLAC__ASSERT(0);
  94945. }
  94946. }
  94947. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  94948. {
  94949. int i, idata_len = (int)data_len;
  94950. switch(order) {
  94951. case 0:
  94952. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  94953. memcpy(data, residual, sizeof(residual[0])*data_len);
  94954. break;
  94955. case 1:
  94956. for(i = 0; i < idata_len; i++)
  94957. data[i] = residual[i] + data[i-1];
  94958. break;
  94959. case 2:
  94960. for(i = 0; i < idata_len; i++)
  94961. #if 1 /* OPT: may be faster with some compilers on some systems */
  94962. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  94963. #else
  94964. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  94965. #endif
  94966. break;
  94967. case 3:
  94968. for(i = 0; i < idata_len; i++)
  94969. #if 1 /* OPT: may be faster with some compilers on some systems */
  94970. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  94971. #else
  94972. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  94973. #endif
  94974. break;
  94975. case 4:
  94976. for(i = 0; i < idata_len; i++)
  94977. #if 1 /* OPT: may be faster with some compilers on some systems */
  94978. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  94979. #else
  94980. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  94981. #endif
  94982. break;
  94983. default:
  94984. FLAC__ASSERT(0);
  94985. }
  94986. }
  94987. #endif
  94988. /*** End of inlined file: fixed.c ***/
  94989. /*** Start of inlined file: float.c ***/
  94990. /*** Start of inlined file: juce_FlacHeader.h ***/
  94991. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94992. // tasks..
  94993. #define VERSION "1.2.1"
  94994. #define FLAC__NO_DLL 1
  94995. #if JUCE_MSVC
  94996. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94997. #endif
  94998. #if JUCE_MAC
  94999. #define FLAC__SYS_DARWIN 1
  95000. #endif
  95001. /*** End of inlined file: juce_FlacHeader.h ***/
  95002. #if JUCE_USE_FLAC
  95003. #if HAVE_CONFIG_H
  95004. # include <config.h>
  95005. #endif
  95006. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95007. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95008. #ifdef _MSC_VER
  95009. #define FLAC__U64L(x) x
  95010. #else
  95011. #define FLAC__U64L(x) x##LLU
  95012. #endif
  95013. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95014. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95015. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95016. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95017. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95018. /* Lookup tables for Knuth's logarithm algorithm */
  95019. #define LOG2_LOOKUP_PRECISION 16
  95020. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95021. {
  95022. /*
  95023. * 0 fraction bits
  95024. */
  95025. /* undefined */ 0x00000000,
  95026. /* lg(2/1) = */ 0x00000001,
  95027. /* lg(4/3) = */ 0x00000000,
  95028. /* lg(8/7) = */ 0x00000000,
  95029. /* lg(16/15) = */ 0x00000000,
  95030. /* lg(32/31) = */ 0x00000000,
  95031. /* lg(64/63) = */ 0x00000000,
  95032. /* lg(128/127) = */ 0x00000000,
  95033. /* lg(256/255) = */ 0x00000000,
  95034. /* lg(512/511) = */ 0x00000000,
  95035. /* lg(1024/1023) = */ 0x00000000,
  95036. /* lg(2048/2047) = */ 0x00000000,
  95037. /* lg(4096/4095) = */ 0x00000000,
  95038. /* lg(8192/8191) = */ 0x00000000,
  95039. /* lg(16384/16383) = */ 0x00000000,
  95040. /* lg(32768/32767) = */ 0x00000000
  95041. },
  95042. {
  95043. /*
  95044. * 4 fraction bits
  95045. */
  95046. /* undefined */ 0x00000000,
  95047. /* lg(2/1) = */ 0x00000010,
  95048. /* lg(4/3) = */ 0x00000007,
  95049. /* lg(8/7) = */ 0x00000003,
  95050. /* lg(16/15) = */ 0x00000001,
  95051. /* lg(32/31) = */ 0x00000001,
  95052. /* lg(64/63) = */ 0x00000000,
  95053. /* lg(128/127) = */ 0x00000000,
  95054. /* lg(256/255) = */ 0x00000000,
  95055. /* lg(512/511) = */ 0x00000000,
  95056. /* lg(1024/1023) = */ 0x00000000,
  95057. /* lg(2048/2047) = */ 0x00000000,
  95058. /* lg(4096/4095) = */ 0x00000000,
  95059. /* lg(8192/8191) = */ 0x00000000,
  95060. /* lg(16384/16383) = */ 0x00000000,
  95061. /* lg(32768/32767) = */ 0x00000000
  95062. },
  95063. {
  95064. /*
  95065. * 8 fraction bits
  95066. */
  95067. /* undefined */ 0x00000000,
  95068. /* lg(2/1) = */ 0x00000100,
  95069. /* lg(4/3) = */ 0x0000006a,
  95070. /* lg(8/7) = */ 0x00000031,
  95071. /* lg(16/15) = */ 0x00000018,
  95072. /* lg(32/31) = */ 0x0000000c,
  95073. /* lg(64/63) = */ 0x00000006,
  95074. /* lg(128/127) = */ 0x00000003,
  95075. /* lg(256/255) = */ 0x00000001,
  95076. /* lg(512/511) = */ 0x00000001,
  95077. /* lg(1024/1023) = */ 0x00000000,
  95078. /* lg(2048/2047) = */ 0x00000000,
  95079. /* lg(4096/4095) = */ 0x00000000,
  95080. /* lg(8192/8191) = */ 0x00000000,
  95081. /* lg(16384/16383) = */ 0x00000000,
  95082. /* lg(32768/32767) = */ 0x00000000
  95083. },
  95084. {
  95085. /*
  95086. * 12 fraction bits
  95087. */
  95088. /* undefined */ 0x00000000,
  95089. /* lg(2/1) = */ 0x00001000,
  95090. /* lg(4/3) = */ 0x000006a4,
  95091. /* lg(8/7) = */ 0x00000315,
  95092. /* lg(16/15) = */ 0x0000017d,
  95093. /* lg(32/31) = */ 0x000000bc,
  95094. /* lg(64/63) = */ 0x0000005d,
  95095. /* lg(128/127) = */ 0x0000002e,
  95096. /* lg(256/255) = */ 0x00000017,
  95097. /* lg(512/511) = */ 0x0000000c,
  95098. /* lg(1024/1023) = */ 0x00000006,
  95099. /* lg(2048/2047) = */ 0x00000003,
  95100. /* lg(4096/4095) = */ 0x00000001,
  95101. /* lg(8192/8191) = */ 0x00000001,
  95102. /* lg(16384/16383) = */ 0x00000000,
  95103. /* lg(32768/32767) = */ 0x00000000
  95104. },
  95105. {
  95106. /*
  95107. * 16 fraction bits
  95108. */
  95109. /* undefined */ 0x00000000,
  95110. /* lg(2/1) = */ 0x00010000,
  95111. /* lg(4/3) = */ 0x00006a40,
  95112. /* lg(8/7) = */ 0x00003151,
  95113. /* lg(16/15) = */ 0x000017d6,
  95114. /* lg(32/31) = */ 0x00000bba,
  95115. /* lg(64/63) = */ 0x000005d1,
  95116. /* lg(128/127) = */ 0x000002e6,
  95117. /* lg(256/255) = */ 0x00000172,
  95118. /* lg(512/511) = */ 0x000000b9,
  95119. /* lg(1024/1023) = */ 0x0000005c,
  95120. /* lg(2048/2047) = */ 0x0000002e,
  95121. /* lg(4096/4095) = */ 0x00000017,
  95122. /* lg(8192/8191) = */ 0x0000000c,
  95123. /* lg(16384/16383) = */ 0x00000006,
  95124. /* lg(32768/32767) = */ 0x00000003
  95125. },
  95126. {
  95127. /*
  95128. * 20 fraction bits
  95129. */
  95130. /* undefined */ 0x00000000,
  95131. /* lg(2/1) = */ 0x00100000,
  95132. /* lg(4/3) = */ 0x0006a3fe,
  95133. /* lg(8/7) = */ 0x00031513,
  95134. /* lg(16/15) = */ 0x00017d60,
  95135. /* lg(32/31) = */ 0x0000bb9d,
  95136. /* lg(64/63) = */ 0x00005d10,
  95137. /* lg(128/127) = */ 0x00002e59,
  95138. /* lg(256/255) = */ 0x00001721,
  95139. /* lg(512/511) = */ 0x00000b8e,
  95140. /* lg(1024/1023) = */ 0x000005c6,
  95141. /* lg(2048/2047) = */ 0x000002e3,
  95142. /* lg(4096/4095) = */ 0x00000171,
  95143. /* lg(8192/8191) = */ 0x000000b9,
  95144. /* lg(16384/16383) = */ 0x0000005c,
  95145. /* lg(32768/32767) = */ 0x0000002e
  95146. },
  95147. {
  95148. /*
  95149. * 24 fraction bits
  95150. */
  95151. /* undefined */ 0x00000000,
  95152. /* lg(2/1) = */ 0x01000000,
  95153. /* lg(4/3) = */ 0x006a3fe6,
  95154. /* lg(8/7) = */ 0x00315130,
  95155. /* lg(16/15) = */ 0x0017d605,
  95156. /* lg(32/31) = */ 0x000bb9ca,
  95157. /* lg(64/63) = */ 0x0005d0fc,
  95158. /* lg(128/127) = */ 0x0002e58f,
  95159. /* lg(256/255) = */ 0x0001720e,
  95160. /* lg(512/511) = */ 0x0000b8d8,
  95161. /* lg(1024/1023) = */ 0x00005c61,
  95162. /* lg(2048/2047) = */ 0x00002e2d,
  95163. /* lg(4096/4095) = */ 0x00001716,
  95164. /* lg(8192/8191) = */ 0x00000b8b,
  95165. /* lg(16384/16383) = */ 0x000005c5,
  95166. /* lg(32768/32767) = */ 0x000002e3
  95167. },
  95168. {
  95169. /*
  95170. * 28 fraction bits
  95171. */
  95172. /* undefined */ 0x00000000,
  95173. /* lg(2/1) = */ 0x10000000,
  95174. /* lg(4/3) = */ 0x06a3fe5c,
  95175. /* lg(8/7) = */ 0x03151301,
  95176. /* lg(16/15) = */ 0x017d6049,
  95177. /* lg(32/31) = */ 0x00bb9ca6,
  95178. /* lg(64/63) = */ 0x005d0fba,
  95179. /* lg(128/127) = */ 0x002e58f7,
  95180. /* lg(256/255) = */ 0x001720da,
  95181. /* lg(512/511) = */ 0x000b8d87,
  95182. /* lg(1024/1023) = */ 0x0005c60b,
  95183. /* lg(2048/2047) = */ 0x0002e2d7,
  95184. /* lg(4096/4095) = */ 0x00017160,
  95185. /* lg(8192/8191) = */ 0x0000b8ad,
  95186. /* lg(16384/16383) = */ 0x00005c56,
  95187. /* lg(32768/32767) = */ 0x00002e2b
  95188. }
  95189. };
  95190. #if 0
  95191. static const FLAC__uint64 log2_lookup_wide[] = {
  95192. {
  95193. /*
  95194. * 32 fraction bits
  95195. */
  95196. /* undefined */ 0x00000000,
  95197. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  95198. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  95199. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  95200. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  95201. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  95202. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  95203. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  95204. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  95205. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  95206. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  95207. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  95208. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  95209. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  95210. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  95211. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  95212. },
  95213. {
  95214. /*
  95215. * 48 fraction bits
  95216. */
  95217. /* undefined */ 0x00000000,
  95218. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  95219. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  95220. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  95221. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  95222. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  95223. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  95224. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  95225. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  95226. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  95227. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  95228. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  95229. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  95230. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  95231. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  95232. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  95233. }
  95234. };
  95235. #endif
  95236. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  95237. {
  95238. const FLAC__uint32 ONE = (1u << fracbits);
  95239. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  95240. FLAC__ASSERT(fracbits < 32);
  95241. FLAC__ASSERT((fracbits & 0x3) == 0);
  95242. if(x < ONE)
  95243. return 0;
  95244. if(precision > LOG2_LOOKUP_PRECISION)
  95245. precision = LOG2_LOOKUP_PRECISION;
  95246. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  95247. {
  95248. FLAC__uint32 y = 0;
  95249. FLAC__uint32 z = x >> 1, k = 1;
  95250. while (x > ONE && k < precision) {
  95251. if (x - z >= ONE) {
  95252. x -= z;
  95253. z = x >> k;
  95254. y += table[k];
  95255. }
  95256. else {
  95257. z >>= 1;
  95258. k++;
  95259. }
  95260. }
  95261. return y;
  95262. }
  95263. }
  95264. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  95265. #endif
  95266. /*** End of inlined file: float.c ***/
  95267. /*** Start of inlined file: format.c ***/
  95268. /*** Start of inlined file: juce_FlacHeader.h ***/
  95269. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95270. // tasks..
  95271. #define VERSION "1.2.1"
  95272. #define FLAC__NO_DLL 1
  95273. #if JUCE_MSVC
  95274. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95275. #endif
  95276. #if JUCE_MAC
  95277. #define FLAC__SYS_DARWIN 1
  95278. #endif
  95279. /*** End of inlined file: juce_FlacHeader.h ***/
  95280. #if JUCE_USE_FLAC
  95281. #if HAVE_CONFIG_H
  95282. # include <config.h>
  95283. #endif
  95284. #include <stdio.h>
  95285. #include <stdlib.h> /* for qsort() */
  95286. #include <string.h> /* for memset() */
  95287. #ifndef FLaC__INLINE
  95288. #define FLaC__INLINE
  95289. #endif
  95290. #ifdef min
  95291. #undef min
  95292. #endif
  95293. #define min(a,b) ((a)<(b)?(a):(b))
  95294. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95295. #ifdef _MSC_VER
  95296. #define FLAC__U64L(x) x
  95297. #else
  95298. #define FLAC__U64L(x) x##LLU
  95299. #endif
  95300. /* VERSION should come from configure */
  95301. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  95302. ;
  95303. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  95304. /* yet one more hack because of MSVC6: */
  95305. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  95306. #else
  95307. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  95308. #endif
  95309. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  95310. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  95311. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  95312. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  95313. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  95314. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  95315. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  95316. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  95317. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  95318. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  95319. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  95320. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  95321. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  95322. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  95323. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  95324. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  95325. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  95326. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  95327. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  95328. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  95329. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  95330. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  95331. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  95332. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  95333. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  95334. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  95335. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  95336. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  95337. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  95338. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  95339. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  95340. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  95341. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  95342. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  95343. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  95344. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  95345. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  95346. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  95347. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  95348. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  95349. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  95350. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  95351. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  95352. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  95353. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  95354. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  95355. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  95356. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  95357. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  95358. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  95359. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  95360. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  95361. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  95362. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  95363. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  95364. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  95365. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  95366. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  95367. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  95368. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  95369. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  95370. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  95371. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  95372. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  95373. "PARTITIONED_RICE",
  95374. "PARTITIONED_RICE2"
  95375. };
  95376. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  95377. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  95378. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  95379. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  95380. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  95381. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  95382. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  95383. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  95384. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  95385. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  95386. "CONSTANT",
  95387. "VERBATIM",
  95388. "FIXED",
  95389. "LPC"
  95390. };
  95391. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  95392. "INDEPENDENT",
  95393. "LEFT_SIDE",
  95394. "RIGHT_SIDE",
  95395. "MID_SIDE"
  95396. };
  95397. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  95398. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  95399. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  95400. };
  95401. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  95402. "STREAMINFO",
  95403. "PADDING",
  95404. "APPLICATION",
  95405. "SEEKTABLE",
  95406. "VORBIS_COMMENT",
  95407. "CUESHEET",
  95408. "PICTURE"
  95409. };
  95410. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  95411. "Other",
  95412. "32x32 pixels 'file icon' (PNG only)",
  95413. "Other file icon",
  95414. "Cover (front)",
  95415. "Cover (back)",
  95416. "Leaflet page",
  95417. "Media (e.g. label side of CD)",
  95418. "Lead artist/lead performer/soloist",
  95419. "Artist/performer",
  95420. "Conductor",
  95421. "Band/Orchestra",
  95422. "Composer",
  95423. "Lyricist/text writer",
  95424. "Recording Location",
  95425. "During recording",
  95426. "During performance",
  95427. "Movie/video screen capture",
  95428. "A bright coloured fish",
  95429. "Illustration",
  95430. "Band/artist logotype",
  95431. "Publisher/Studio logotype"
  95432. };
  95433. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  95434. {
  95435. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  95436. return false;
  95437. }
  95438. else
  95439. return true;
  95440. }
  95441. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  95442. {
  95443. if(
  95444. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  95445. (
  95446. sample_rate >= (1u << 16) &&
  95447. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  95448. )
  95449. ) {
  95450. return false;
  95451. }
  95452. else
  95453. return true;
  95454. }
  95455. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95456. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  95457. {
  95458. unsigned i;
  95459. FLAC__uint64 prev_sample_number = 0;
  95460. FLAC__bool got_prev = false;
  95461. FLAC__ASSERT(0 != seek_table);
  95462. for(i = 0; i < seek_table->num_points; i++) {
  95463. if(got_prev) {
  95464. if(
  95465. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95466. seek_table->points[i].sample_number <= prev_sample_number
  95467. )
  95468. return false;
  95469. }
  95470. prev_sample_number = seek_table->points[i].sample_number;
  95471. got_prev = true;
  95472. }
  95473. return true;
  95474. }
  95475. /* used as the sort predicate for qsort() */
  95476. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  95477. {
  95478. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  95479. if(l->sample_number == r->sample_number)
  95480. return 0;
  95481. else if(l->sample_number < r->sample_number)
  95482. return -1;
  95483. else
  95484. return 1;
  95485. }
  95486. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95487. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  95488. {
  95489. unsigned i, j;
  95490. FLAC__bool first;
  95491. FLAC__ASSERT(0 != seek_table);
  95492. /* sort the seekpoints */
  95493. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  95494. /* uniquify the seekpoints */
  95495. first = true;
  95496. for(i = j = 0; i < seek_table->num_points; i++) {
  95497. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  95498. if(!first) {
  95499. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  95500. continue;
  95501. }
  95502. }
  95503. first = false;
  95504. seek_table->points[j++] = seek_table->points[i];
  95505. }
  95506. for(i = j; i < seek_table->num_points; i++) {
  95507. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  95508. seek_table->points[i].stream_offset = 0;
  95509. seek_table->points[i].frame_samples = 0;
  95510. }
  95511. return j;
  95512. }
  95513. /*
  95514. * also disallows non-shortest-form encodings, c.f.
  95515. * http://www.unicode.org/versions/corrigendum1.html
  95516. * and a more clear explanation at the end of this section:
  95517. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  95518. */
  95519. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  95520. {
  95521. FLAC__ASSERT(0 != utf8);
  95522. if ((utf8[0] & 0x80) == 0) {
  95523. return 1;
  95524. }
  95525. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  95526. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  95527. return 0;
  95528. return 2;
  95529. }
  95530. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  95531. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  95532. return 0;
  95533. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  95534. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  95535. return 0;
  95536. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  95537. return 0;
  95538. return 3;
  95539. }
  95540. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  95541. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  95542. return 0;
  95543. return 4;
  95544. }
  95545. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  95546. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  95547. return 0;
  95548. return 5;
  95549. }
  95550. else if ((utf8[0] & 0xFE) == 0xFC && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80 && (utf8[5] & 0xC0) == 0x80) {
  95551. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  95552. return 0;
  95553. return 6;
  95554. }
  95555. else {
  95556. return 0;
  95557. }
  95558. }
  95559. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  95560. {
  95561. char c;
  95562. for(c = *name; c; c = *(++name))
  95563. if(c < 0x20 || c == 0x3d || c > 0x7d)
  95564. return false;
  95565. return true;
  95566. }
  95567. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  95568. {
  95569. if(length == (unsigned)(-1)) {
  95570. while(*value) {
  95571. unsigned n = utf8len_(value);
  95572. if(n == 0)
  95573. return false;
  95574. value += n;
  95575. }
  95576. }
  95577. else {
  95578. const FLAC__byte *end = value + length;
  95579. while(value < end) {
  95580. unsigned n = utf8len_(value);
  95581. if(n == 0)
  95582. return false;
  95583. value += n;
  95584. }
  95585. if(value != end)
  95586. return false;
  95587. }
  95588. return true;
  95589. }
  95590. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  95591. {
  95592. const FLAC__byte *s, *end;
  95593. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  95594. if(*s < 0x20 || *s > 0x7D)
  95595. return false;
  95596. }
  95597. if(s == end)
  95598. return false;
  95599. s++; /* skip '=' */
  95600. while(s < end) {
  95601. unsigned n = utf8len_(s);
  95602. if(n == 0)
  95603. return false;
  95604. s += n;
  95605. }
  95606. if(s != end)
  95607. return false;
  95608. return true;
  95609. }
  95610. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95611. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  95612. {
  95613. unsigned i, j;
  95614. if(check_cd_da_subset) {
  95615. if(cue_sheet->lead_in < 2 * 44100) {
  95616. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  95617. return false;
  95618. }
  95619. if(cue_sheet->lead_in % 588 != 0) {
  95620. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  95621. return false;
  95622. }
  95623. }
  95624. if(cue_sheet->num_tracks == 0) {
  95625. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  95626. return false;
  95627. }
  95628. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  95629. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  95630. return false;
  95631. }
  95632. for(i = 0; i < cue_sheet->num_tracks; i++) {
  95633. if(cue_sheet->tracks[i].number == 0) {
  95634. if(violation) *violation = "cue sheet may not have a track number 0";
  95635. return false;
  95636. }
  95637. if(check_cd_da_subset) {
  95638. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  95639. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  95640. return false;
  95641. }
  95642. }
  95643. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  95644. if(violation) {
  95645. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  95646. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  95647. else
  95648. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  95649. }
  95650. return false;
  95651. }
  95652. if(i < cue_sheet->num_tracks - 1) {
  95653. if(cue_sheet->tracks[i].num_indices == 0) {
  95654. if(violation) *violation = "cue sheet track must have at least one index point";
  95655. return false;
  95656. }
  95657. if(cue_sheet->tracks[i].indices[0].number > 1) {
  95658. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  95659. return false;
  95660. }
  95661. }
  95662. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  95663. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  95664. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  95665. return false;
  95666. }
  95667. if(j > 0) {
  95668. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  95669. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  95670. return false;
  95671. }
  95672. }
  95673. }
  95674. }
  95675. return true;
  95676. }
  95677. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95678. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  95679. {
  95680. char *p;
  95681. FLAC__byte *b;
  95682. for(p = picture->mime_type; *p; p++) {
  95683. if(*p < 0x20 || *p > 0x7e) {
  95684. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  95685. return false;
  95686. }
  95687. }
  95688. for(b = picture->description; *b; ) {
  95689. unsigned n = utf8len_(b);
  95690. if(n == 0) {
  95691. if(violation) *violation = "description string must be valid UTF-8";
  95692. return false;
  95693. }
  95694. b += n;
  95695. }
  95696. return true;
  95697. }
  95698. /*
  95699. * These routines are private to libFLAC
  95700. */
  95701. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  95702. {
  95703. return
  95704. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  95705. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  95706. blocksize,
  95707. predictor_order
  95708. );
  95709. }
  95710. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  95711. {
  95712. unsigned max_rice_partition_order = 0;
  95713. while(!(blocksize & 1)) {
  95714. max_rice_partition_order++;
  95715. blocksize >>= 1;
  95716. }
  95717. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  95718. }
  95719. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  95720. {
  95721. unsigned max_rice_partition_order = limit;
  95722. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  95723. max_rice_partition_order--;
  95724. FLAC__ASSERT(
  95725. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  95726. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  95727. );
  95728. return max_rice_partition_order;
  95729. }
  95730. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  95731. {
  95732. FLAC__ASSERT(0 != object);
  95733. object->parameters = 0;
  95734. object->raw_bits = 0;
  95735. object->capacity_by_order = 0;
  95736. }
  95737. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  95738. {
  95739. FLAC__ASSERT(0 != object);
  95740. if(0 != object->parameters)
  95741. free(object->parameters);
  95742. if(0 != object->raw_bits)
  95743. free(object->raw_bits);
  95744. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  95745. }
  95746. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  95747. {
  95748. FLAC__ASSERT(0 != object);
  95749. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  95750. if(object->capacity_by_order < max_partition_order) {
  95751. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  95752. return false;
  95753. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  95754. return false;
  95755. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  95756. object->capacity_by_order = max_partition_order;
  95757. }
  95758. return true;
  95759. }
  95760. #endif
  95761. /*** End of inlined file: format.c ***/
  95762. /*** Start of inlined file: lpc_flac.c ***/
  95763. /*** Start of inlined file: juce_FlacHeader.h ***/
  95764. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95765. // tasks..
  95766. #define VERSION "1.2.1"
  95767. #define FLAC__NO_DLL 1
  95768. #if JUCE_MSVC
  95769. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95770. #endif
  95771. #if JUCE_MAC
  95772. #define FLAC__SYS_DARWIN 1
  95773. #endif
  95774. /*** End of inlined file: juce_FlacHeader.h ***/
  95775. #if JUCE_USE_FLAC
  95776. #if HAVE_CONFIG_H
  95777. # include <config.h>
  95778. #endif
  95779. #include <math.h>
  95780. /*** Start of inlined file: lpc.h ***/
  95781. #ifndef FLAC__PRIVATE__LPC_H
  95782. #define FLAC__PRIVATE__LPC_H
  95783. #ifdef HAVE_CONFIG_H
  95784. #include <config.h>
  95785. #endif
  95786. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95787. /*
  95788. * FLAC__lpc_window_data()
  95789. * --------------------------------------------------------------------
  95790. * Applies the given window to the data.
  95791. * OPT: asm implementation
  95792. *
  95793. * IN in[0,data_len-1]
  95794. * IN window[0,data_len-1]
  95795. * OUT out[0,lag-1]
  95796. * IN data_len
  95797. */
  95798. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  95799. /*
  95800. * FLAC__lpc_compute_autocorrelation()
  95801. * --------------------------------------------------------------------
  95802. * Compute the autocorrelation for lags between 0 and lag-1.
  95803. * Assumes data[] outside of [0,data_len-1] == 0.
  95804. * Asserts that lag > 0.
  95805. *
  95806. * IN data[0,data_len-1]
  95807. * IN data_len
  95808. * IN 0 < lag <= data_len
  95809. * OUT autoc[0,lag-1]
  95810. */
  95811. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95812. #ifndef FLAC__NO_ASM
  95813. # ifdef FLAC__CPU_IA32
  95814. # ifdef FLAC__HAS_NASM
  95815. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95816. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95817. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95818. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95819. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95820. # endif
  95821. # endif
  95822. #endif
  95823. /*
  95824. * FLAC__lpc_compute_lp_coefficients()
  95825. * --------------------------------------------------------------------
  95826. * Computes LP coefficients for orders 1..max_order.
  95827. * Do not call if autoc[0] == 0.0. This means the signal is zero
  95828. * and there is no point in calculating a predictor.
  95829. *
  95830. * IN autoc[0,max_order] autocorrelation values
  95831. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  95832. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  95833. * *** IMPORTANT:
  95834. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  95835. * OUT error[0,max_order-1] error for each order (more
  95836. * specifically, the variance of
  95837. * the error signal times # of
  95838. * samples in the signal)
  95839. *
  95840. * Example: if max_order is 9, the LP coefficients for order 9 will be
  95841. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  95842. * in lp_coeff[7][0,7], etc.
  95843. */
  95844. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  95845. /*
  95846. * FLAC__lpc_quantize_coefficients()
  95847. * --------------------------------------------------------------------
  95848. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  95849. * must be less than 32 (sizeof(FLAC__int32)*8).
  95850. *
  95851. * IN lp_coeff[0,order-1] LP coefficients
  95852. * IN order LP order
  95853. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  95854. * desired precision (in bits, including sign
  95855. * bit) of largest coefficient
  95856. * OUT qlp_coeff[0,order-1] quantized coefficients
  95857. * OUT shift # of bits to shift right to get approximated
  95858. * LP coefficients. NOTE: could be negative.
  95859. * RETURN 0 => quantization OK
  95860. * 1 => coefficients require too much shifting for *shift to
  95861. * fit in the LPC subframe header. 'shift' is unset.
  95862. * 2 => coefficients are all zero, which is bad. 'shift' is
  95863. * unset.
  95864. */
  95865. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  95866. /*
  95867. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  95868. * --------------------------------------------------------------------
  95869. * Compute the residual signal obtained from sutracting the predicted
  95870. * signal from the original.
  95871. *
  95872. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95873. * IN data_len length of original signal
  95874. * IN qlp_coeff[0,order-1] quantized LP coefficients
  95875. * IN order > 0 LP order
  95876. * IN lp_quantization quantization of LP coefficients in bits
  95877. * OUT residual[0,data_len-1] residual signal
  95878. */
  95879. void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  95880. void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  95881. #ifndef FLAC__NO_ASM
  95882. # ifdef FLAC__CPU_IA32
  95883. # ifdef FLAC__HAS_NASM
  95884. void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  95885. void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  95886. # endif
  95887. # endif
  95888. #endif
  95889. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  95890. /*
  95891. * FLAC__lpc_restore_signal()
  95892. * --------------------------------------------------------------------
  95893. * Restore the original signal by summing the residual and the
  95894. * predictor.
  95895. *
  95896. * IN residual[0,data_len-1] residual signal
  95897. * IN data_len length of original signal
  95898. * IN qlp_coeff[0,order-1] quantized LP coefficients
  95899. * IN order > 0 LP order
  95900. * IN lp_quantization quantization of LP coefficients in bits
  95901. * *** IMPORTANT: the caller must pass in the historical samples:
  95902. * IN data[-order,-1] previously-reconstructed historical samples
  95903. * OUT data[0,data_len-1] original signal
  95904. */
  95905. void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  95906. void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  95907. #ifndef FLAC__NO_ASM
  95908. # ifdef FLAC__CPU_IA32
  95909. # ifdef FLAC__HAS_NASM
  95910. void FLAC__lpc_restore_signal_asm_ia32(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  95911. void FLAC__lpc_restore_signal_asm_ia32_mmx(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  95912. # endif /* FLAC__HAS_NASM */
  95913. # elif defined FLAC__CPU_PPC
  95914. void FLAC__lpc_restore_signal_asm_ppc_altivec_16(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  95915. void FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  95916. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  95917. #endif /* FLAC__NO_ASM */
  95918. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95919. /*
  95920. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  95921. * --------------------------------------------------------------------
  95922. * Compute the expected number of bits per residual signal sample
  95923. * based on the LP error (which is related to the residual variance).
  95924. *
  95925. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  95926. * IN total_samples > 0 # of samples in residual signal
  95927. * RETURN expected bits per sample
  95928. */
  95929. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  95930. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  95931. /*
  95932. * FLAC__lpc_compute_best_order()
  95933. * --------------------------------------------------------------------
  95934. * Compute the best order from the array of signal errors returned
  95935. * during coefficient computation.
  95936. *
  95937. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  95938. * IN max_order > 0 max LP order
  95939. * IN total_samples > 0 # of samples in residual signal
  95940. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  95941. * (includes warmup sample size and quantized LP coefficient)
  95942. * RETURN [1,max_order] best order
  95943. */
  95944. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  95945. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  95946. #endif
  95947. /*** End of inlined file: lpc.h ***/
  95948. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  95949. #include <stdio.h>
  95950. #endif
  95951. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95952. #ifndef M_LN2
  95953. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95954. #define M_LN2 0.69314718055994530942
  95955. #endif
  95956. /* OPT: #undef'ing this may improve the speed on some architectures */
  95957. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  95958. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  95959. {
  95960. unsigned i;
  95961. for(i = 0; i < data_len; i++)
  95962. out[i] = in[i] * window[i];
  95963. }
  95964. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  95965. {
  95966. /* a readable, but slower, version */
  95967. #if 0
  95968. FLAC__real d;
  95969. unsigned i;
  95970. FLAC__ASSERT(lag > 0);
  95971. FLAC__ASSERT(lag <= data_len);
  95972. /*
  95973. * Technically we should subtract the mean first like so:
  95974. * for(i = 0; i < data_len; i++)
  95975. * data[i] -= mean;
  95976. * but it appears not to make enough of a difference to matter, and
  95977. * most signals are already closely centered around zero
  95978. */
  95979. while(lag--) {
  95980. for(i = lag, d = 0.0; i < data_len; i++)
  95981. d += data[i] * data[i - lag];
  95982. autoc[lag] = d;
  95983. }
  95984. #endif
  95985. /*
  95986. * this version tends to run faster because of better data locality
  95987. * ('data_len' is usually much larger than 'lag')
  95988. */
  95989. FLAC__real d;
  95990. unsigned sample, coeff;
  95991. const unsigned limit = data_len - lag;
  95992. FLAC__ASSERT(lag > 0);
  95993. FLAC__ASSERT(lag <= data_len);
  95994. for(coeff = 0; coeff < lag; coeff++)
  95995. autoc[coeff] = 0.0;
  95996. for(sample = 0; sample <= limit; sample++) {
  95997. d = data[sample];
  95998. for(coeff = 0; coeff < lag; coeff++)
  95999. autoc[coeff] += d * data[sample+coeff];
  96000. }
  96001. for(; sample < data_len; sample++) {
  96002. d = data[sample];
  96003. for(coeff = 0; coeff < data_len - sample; coeff++)
  96004. autoc[coeff] += d * data[sample+coeff];
  96005. }
  96006. }
  96007. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96008. {
  96009. unsigned i, j;
  96010. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96011. FLAC__ASSERT(0 != max_order);
  96012. FLAC__ASSERT(0 < *max_order);
  96013. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96014. FLAC__ASSERT(autoc[0] != 0.0);
  96015. err = autoc[0];
  96016. for(i = 0; i < *max_order; i++) {
  96017. /* Sum up this iteration's reflection coefficient. */
  96018. r = -autoc[i+1];
  96019. for(j = 0; j < i; j++)
  96020. r -= lpc[j] * autoc[i-j];
  96021. ref[i] = (r/=err);
  96022. /* Update LPC coefficients and total error. */
  96023. lpc[i]=r;
  96024. for(j = 0; j < (i>>1); j++) {
  96025. FLAC__double tmp = lpc[j];
  96026. lpc[j] += r * lpc[i-1-j];
  96027. lpc[i-1-j] += r * tmp;
  96028. }
  96029. if(i & 1)
  96030. lpc[j] += lpc[j] * r;
  96031. err *= (1.0 - r * r);
  96032. /* save this order */
  96033. for(j = 0; j <= i; j++)
  96034. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96035. error[i] = err;
  96036. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96037. if(err == 0.0) {
  96038. *max_order = i+1;
  96039. return;
  96040. }
  96041. }
  96042. }
  96043. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96044. {
  96045. unsigned i;
  96046. FLAC__double cmax;
  96047. FLAC__int32 qmax, qmin;
  96048. FLAC__ASSERT(precision > 0);
  96049. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96050. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96051. precision--;
  96052. qmax = 1 << precision;
  96053. qmin = -qmax;
  96054. qmax--;
  96055. /* calc cmax = max( |lp_coeff[i]| ) */
  96056. cmax = 0.0;
  96057. for(i = 0; i < order; i++) {
  96058. const FLAC__double d = fabs(lp_coeff[i]);
  96059. if(d > cmax)
  96060. cmax = d;
  96061. }
  96062. if(cmax <= 0.0) {
  96063. /* => coefficients are all 0, which means our constant-detect didn't work */
  96064. return 2;
  96065. }
  96066. else {
  96067. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96068. const int min_shiftlimit = -max_shiftlimit - 1;
  96069. int log2cmax;
  96070. (void)frexp(cmax, &log2cmax);
  96071. log2cmax--;
  96072. *shift = (int)precision - log2cmax - 1;
  96073. if(*shift > max_shiftlimit)
  96074. *shift = max_shiftlimit;
  96075. else if(*shift < min_shiftlimit)
  96076. return 1;
  96077. }
  96078. if(*shift >= 0) {
  96079. FLAC__double error = 0.0;
  96080. FLAC__int32 q;
  96081. for(i = 0; i < order; i++) {
  96082. error += lp_coeff[i] * (1 << *shift);
  96083. #if 1 /* unfortunately lround() is C99 */
  96084. if(error >= 0.0)
  96085. q = (FLAC__int32)(error + 0.5);
  96086. else
  96087. q = (FLAC__int32)(error - 0.5);
  96088. #else
  96089. q = lround(error);
  96090. #endif
  96091. #ifdef FLAC__OVERFLOW_DETECT
  96092. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96093. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
  96094. else if(q < qmin)
  96095. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
  96096. #endif
  96097. if(q > qmax)
  96098. q = qmax;
  96099. else if(q < qmin)
  96100. q = qmin;
  96101. error -= q;
  96102. qlp_coeff[i] = q;
  96103. }
  96104. }
  96105. /* negative shift is very rare but due to design flaw, negative shift is
  96106. * a NOP in the decoder, so it must be handled specially by scaling down
  96107. * coeffs
  96108. */
  96109. else {
  96110. const int nshift = -(*shift);
  96111. FLAC__double error = 0.0;
  96112. FLAC__int32 q;
  96113. #ifdef DEBUG
  96114. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  96115. #endif
  96116. for(i = 0; i < order; i++) {
  96117. error += lp_coeff[i] / (1 << nshift);
  96118. #if 1 /* unfortunately lround() is C99 */
  96119. if(error >= 0.0)
  96120. q = (FLAC__int32)(error + 0.5);
  96121. else
  96122. q = (FLAC__int32)(error - 0.5);
  96123. #else
  96124. q = lround(error);
  96125. #endif
  96126. #ifdef FLAC__OVERFLOW_DETECT
  96127. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96128. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
  96129. else if(q < qmin)
  96130. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
  96131. #endif
  96132. if(q > qmax)
  96133. q = qmax;
  96134. else if(q < qmin)
  96135. q = qmin;
  96136. error -= q;
  96137. qlp_coeff[i] = q;
  96138. }
  96139. *shift = 0;
  96140. }
  96141. return 0;
  96142. }
  96143. void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
  96144. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96145. {
  96146. FLAC__int64 sumo;
  96147. unsigned i, j;
  96148. FLAC__int32 sum;
  96149. const FLAC__int32 *history;
  96150. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96151. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96152. for(i=0;i<order;i++)
  96153. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96154. fprintf(stderr,"\n");
  96155. #endif
  96156. FLAC__ASSERT(order > 0);
  96157. for(i = 0; i < data_len; i++) {
  96158. sumo = 0;
  96159. sum = 0;
  96160. history = data;
  96161. for(j = 0; j < order; j++) {
  96162. sum += qlp_coeff[j] * (*(--history));
  96163. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96164. #if defined _MSC_VER
  96165. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96166. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
  96167. #else
  96168. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96169. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
  96170. #endif
  96171. }
  96172. *(residual++) = *(data++) - (sum >> lp_quantization);
  96173. }
  96174. /* Here's a slower but clearer version:
  96175. for(i = 0; i < data_len; i++) {
  96176. sum = 0;
  96177. for(j = 0; j < order; j++)
  96178. sum += qlp_coeff[j] * data[i-j-1];
  96179. residual[i] = data[i] - (sum >> lp_quantization);
  96180. }
  96181. */
  96182. }
  96183. #else /* fully unrolled version for normal use */
  96184. {
  96185. int i;
  96186. FLAC__int32 sum;
  96187. FLAC__ASSERT(order > 0);
  96188. FLAC__ASSERT(order <= 32);
  96189. /*
  96190. * We do unique versions up to 12th order since that's the subset limit.
  96191. * Also they are roughly ordered to match frequency of occurrence to
  96192. * minimize branching.
  96193. */
  96194. if(order <= 12) {
  96195. if(order > 8) {
  96196. if(order > 10) {
  96197. if(order == 12) {
  96198. for(i = 0; i < (int)data_len; i++) {
  96199. sum = 0;
  96200. sum += qlp_coeff[11] * data[i-12];
  96201. sum += qlp_coeff[10] * data[i-11];
  96202. sum += qlp_coeff[9] * data[i-10];
  96203. sum += qlp_coeff[8] * data[i-9];
  96204. sum += qlp_coeff[7] * data[i-8];
  96205. sum += qlp_coeff[6] * data[i-7];
  96206. sum += qlp_coeff[5] * data[i-6];
  96207. sum += qlp_coeff[4] * data[i-5];
  96208. sum += qlp_coeff[3] * data[i-4];
  96209. sum += qlp_coeff[2] * data[i-3];
  96210. sum += qlp_coeff[1] * data[i-2];
  96211. sum += qlp_coeff[0] * data[i-1];
  96212. residual[i] = data[i] - (sum >> lp_quantization);
  96213. }
  96214. }
  96215. else { /* order == 11 */
  96216. for(i = 0; i < (int)data_len; i++) {
  96217. sum = 0;
  96218. sum += qlp_coeff[10] * data[i-11];
  96219. sum += qlp_coeff[9] * data[i-10];
  96220. sum += qlp_coeff[8] * data[i-9];
  96221. sum += qlp_coeff[7] * data[i-8];
  96222. sum += qlp_coeff[6] * data[i-7];
  96223. sum += qlp_coeff[5] * data[i-6];
  96224. sum += qlp_coeff[4] * data[i-5];
  96225. sum += qlp_coeff[3] * data[i-4];
  96226. sum += qlp_coeff[2] * data[i-3];
  96227. sum += qlp_coeff[1] * data[i-2];
  96228. sum += qlp_coeff[0] * data[i-1];
  96229. residual[i] = data[i] - (sum >> lp_quantization);
  96230. }
  96231. }
  96232. }
  96233. else {
  96234. if(order == 10) {
  96235. for(i = 0; i < (int)data_len; i++) {
  96236. sum = 0;
  96237. sum += qlp_coeff[9] * data[i-10];
  96238. sum += qlp_coeff[8] * data[i-9];
  96239. sum += qlp_coeff[7] * data[i-8];
  96240. sum += qlp_coeff[6] * data[i-7];
  96241. sum += qlp_coeff[5] * data[i-6];
  96242. sum += qlp_coeff[4] * data[i-5];
  96243. sum += qlp_coeff[3] * data[i-4];
  96244. sum += qlp_coeff[2] * data[i-3];
  96245. sum += qlp_coeff[1] * data[i-2];
  96246. sum += qlp_coeff[0] * data[i-1];
  96247. residual[i] = data[i] - (sum >> lp_quantization);
  96248. }
  96249. }
  96250. else { /* order == 9 */
  96251. for(i = 0; i < (int)data_len; i++) {
  96252. sum = 0;
  96253. sum += qlp_coeff[8] * data[i-9];
  96254. sum += qlp_coeff[7] * data[i-8];
  96255. sum += qlp_coeff[6] * data[i-7];
  96256. sum += qlp_coeff[5] * data[i-6];
  96257. sum += qlp_coeff[4] * data[i-5];
  96258. sum += qlp_coeff[3] * data[i-4];
  96259. sum += qlp_coeff[2] * data[i-3];
  96260. sum += qlp_coeff[1] * data[i-2];
  96261. sum += qlp_coeff[0] * data[i-1];
  96262. residual[i] = data[i] - (sum >> lp_quantization);
  96263. }
  96264. }
  96265. }
  96266. }
  96267. else if(order > 4) {
  96268. if(order > 6) {
  96269. if(order == 8) {
  96270. for(i = 0; i < (int)data_len; i++) {
  96271. sum = 0;
  96272. sum += qlp_coeff[7] * data[i-8];
  96273. sum += qlp_coeff[6] * data[i-7];
  96274. sum += qlp_coeff[5] * data[i-6];
  96275. sum += qlp_coeff[4] * data[i-5];
  96276. sum += qlp_coeff[3] * data[i-4];
  96277. sum += qlp_coeff[2] * data[i-3];
  96278. sum += qlp_coeff[1] * data[i-2];
  96279. sum += qlp_coeff[0] * data[i-1];
  96280. residual[i] = data[i] - (sum >> lp_quantization);
  96281. }
  96282. }
  96283. else { /* order == 7 */
  96284. for(i = 0; i < (int)data_len; i++) {
  96285. sum = 0;
  96286. sum += qlp_coeff[6] * data[i-7];
  96287. sum += qlp_coeff[5] * data[i-6];
  96288. sum += qlp_coeff[4] * data[i-5];
  96289. sum += qlp_coeff[3] * data[i-4];
  96290. sum += qlp_coeff[2] * data[i-3];
  96291. sum += qlp_coeff[1] * data[i-2];
  96292. sum += qlp_coeff[0] * data[i-1];
  96293. residual[i] = data[i] - (sum >> lp_quantization);
  96294. }
  96295. }
  96296. }
  96297. else {
  96298. if(order == 6) {
  96299. for(i = 0; i < (int)data_len; i++) {
  96300. sum = 0;
  96301. sum += qlp_coeff[5] * data[i-6];
  96302. sum += qlp_coeff[4] * data[i-5];
  96303. sum += qlp_coeff[3] * data[i-4];
  96304. sum += qlp_coeff[2] * data[i-3];
  96305. sum += qlp_coeff[1] * data[i-2];
  96306. sum += qlp_coeff[0] * data[i-1];
  96307. residual[i] = data[i] - (sum >> lp_quantization);
  96308. }
  96309. }
  96310. else { /* order == 5 */
  96311. for(i = 0; i < (int)data_len; i++) {
  96312. sum = 0;
  96313. sum += qlp_coeff[4] * data[i-5];
  96314. sum += qlp_coeff[3] * data[i-4];
  96315. sum += qlp_coeff[2] * data[i-3];
  96316. sum += qlp_coeff[1] * data[i-2];
  96317. sum += qlp_coeff[0] * data[i-1];
  96318. residual[i] = data[i] - (sum >> lp_quantization);
  96319. }
  96320. }
  96321. }
  96322. }
  96323. else {
  96324. if(order > 2) {
  96325. if(order == 4) {
  96326. for(i = 0; i < (int)data_len; i++) {
  96327. sum = 0;
  96328. sum += qlp_coeff[3] * data[i-4];
  96329. sum += qlp_coeff[2] * data[i-3];
  96330. sum += qlp_coeff[1] * data[i-2];
  96331. sum += qlp_coeff[0] * data[i-1];
  96332. residual[i] = data[i] - (sum >> lp_quantization);
  96333. }
  96334. }
  96335. else { /* order == 3 */
  96336. for(i = 0; i < (int)data_len; i++) {
  96337. sum = 0;
  96338. sum += qlp_coeff[2] * data[i-3];
  96339. sum += qlp_coeff[1] * data[i-2];
  96340. sum += qlp_coeff[0] * data[i-1];
  96341. residual[i] = data[i] - (sum >> lp_quantization);
  96342. }
  96343. }
  96344. }
  96345. else {
  96346. if(order == 2) {
  96347. for(i = 0; i < (int)data_len; i++) {
  96348. sum = 0;
  96349. sum += qlp_coeff[1] * data[i-2];
  96350. sum += qlp_coeff[0] * data[i-1];
  96351. residual[i] = data[i] - (sum >> lp_quantization);
  96352. }
  96353. }
  96354. else { /* order == 1 */
  96355. for(i = 0; i < (int)data_len; i++)
  96356. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  96357. }
  96358. }
  96359. }
  96360. }
  96361. else { /* order > 12 */
  96362. for(i = 0; i < (int)data_len; i++) {
  96363. sum = 0;
  96364. switch(order) {
  96365. case 32: sum += qlp_coeff[31] * data[i-32];
  96366. case 31: sum += qlp_coeff[30] * data[i-31];
  96367. case 30: sum += qlp_coeff[29] * data[i-30];
  96368. case 29: sum += qlp_coeff[28] * data[i-29];
  96369. case 28: sum += qlp_coeff[27] * data[i-28];
  96370. case 27: sum += qlp_coeff[26] * data[i-27];
  96371. case 26: sum += qlp_coeff[25] * data[i-26];
  96372. case 25: sum += qlp_coeff[24] * data[i-25];
  96373. case 24: sum += qlp_coeff[23] * data[i-24];
  96374. case 23: sum += qlp_coeff[22] * data[i-23];
  96375. case 22: sum += qlp_coeff[21] * data[i-22];
  96376. case 21: sum += qlp_coeff[20] * data[i-21];
  96377. case 20: sum += qlp_coeff[19] * data[i-20];
  96378. case 19: sum += qlp_coeff[18] * data[i-19];
  96379. case 18: sum += qlp_coeff[17] * data[i-18];
  96380. case 17: sum += qlp_coeff[16] * data[i-17];
  96381. case 16: sum += qlp_coeff[15] * data[i-16];
  96382. case 15: sum += qlp_coeff[14] * data[i-15];
  96383. case 14: sum += qlp_coeff[13] * data[i-14];
  96384. case 13: sum += qlp_coeff[12] * data[i-13];
  96385. sum += qlp_coeff[11] * data[i-12];
  96386. sum += qlp_coeff[10] * data[i-11];
  96387. sum += qlp_coeff[ 9] * data[i-10];
  96388. sum += qlp_coeff[ 8] * data[i- 9];
  96389. sum += qlp_coeff[ 7] * data[i- 8];
  96390. sum += qlp_coeff[ 6] * data[i- 7];
  96391. sum += qlp_coeff[ 5] * data[i- 6];
  96392. sum += qlp_coeff[ 4] * data[i- 5];
  96393. sum += qlp_coeff[ 3] * data[i- 4];
  96394. sum += qlp_coeff[ 2] * data[i- 3];
  96395. sum += qlp_coeff[ 1] * data[i- 2];
  96396. sum += qlp_coeff[ 0] * data[i- 1];
  96397. }
  96398. residual[i] = data[i] - (sum >> lp_quantization);
  96399. }
  96400. }
  96401. }
  96402. #endif
  96403. void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
  96404. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96405. {
  96406. unsigned i, j;
  96407. FLAC__int64 sum;
  96408. const FLAC__int32 *history;
  96409. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96410. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96411. for(i=0;i<order;i++)
  96412. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96413. fprintf(stderr,"\n");
  96414. #endif
  96415. FLAC__ASSERT(order > 0);
  96416. for(i = 0; i < data_len; i++) {
  96417. sum = 0;
  96418. history = data;
  96419. for(j = 0; j < order; j++)
  96420. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  96421. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  96422. #if defined _MSC_VER
  96423. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  96424. #else
  96425. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  96426. #endif
  96427. break;
  96428. }
  96429. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  96430. #if defined _MSC_VER
  96431. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%I64d, residual=%I64d\n", i, *data, sum >> lp_quantization, (FLAC__int64)(*data) - (sum >> lp_quantization));
  96432. #else
  96433. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%lld, residual=%lld\n", i, *data, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*data) - (sum >> lp_quantization)));
  96434. #endif
  96435. break;
  96436. }
  96437. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  96438. }
  96439. }
  96440. #else /* fully unrolled version for normal use */
  96441. {
  96442. int i;
  96443. FLAC__int64 sum;
  96444. FLAC__ASSERT(order > 0);
  96445. FLAC__ASSERT(order <= 32);
  96446. /*
  96447. * We do unique versions up to 12th order since that's the subset limit.
  96448. * Also they are roughly ordered to match frequency of occurrence to
  96449. * minimize branching.
  96450. */
  96451. if(order <= 12) {
  96452. if(order > 8) {
  96453. if(order > 10) {
  96454. if(order == 12) {
  96455. for(i = 0; i < (int)data_len; i++) {
  96456. sum = 0;
  96457. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  96458. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96459. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96460. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96461. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96462. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96463. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96464. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96465. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96466. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96467. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96468. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96469. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96470. }
  96471. }
  96472. else { /* order == 11 */
  96473. for(i = 0; i < (int)data_len; i++) {
  96474. sum = 0;
  96475. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96476. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96477. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96478. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96479. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96480. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96481. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96482. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96483. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96484. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96485. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96486. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96487. }
  96488. }
  96489. }
  96490. else {
  96491. if(order == 10) {
  96492. for(i = 0; i < (int)data_len; i++) {
  96493. sum = 0;
  96494. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96495. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96496. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96497. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96498. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96499. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96500. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96501. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96502. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96503. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96504. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96505. }
  96506. }
  96507. else { /* order == 9 */
  96508. for(i = 0; i < (int)data_len; i++) {
  96509. sum = 0;
  96510. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96511. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96512. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96513. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96514. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96515. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96516. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96517. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96518. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96519. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96520. }
  96521. }
  96522. }
  96523. }
  96524. else if(order > 4) {
  96525. if(order > 6) {
  96526. if(order == 8) {
  96527. for(i = 0; i < (int)data_len; i++) {
  96528. sum = 0;
  96529. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96530. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96531. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96532. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96533. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96534. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96535. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96536. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96537. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96538. }
  96539. }
  96540. else { /* order == 7 */
  96541. for(i = 0; i < (int)data_len; i++) {
  96542. sum = 0;
  96543. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96544. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96545. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96546. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96547. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96548. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96549. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96550. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96551. }
  96552. }
  96553. }
  96554. else {
  96555. if(order == 6) {
  96556. for(i = 0; i < (int)data_len; i++) {
  96557. sum = 0;
  96558. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96559. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96560. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96561. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96562. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96563. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96564. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96565. }
  96566. }
  96567. else { /* order == 5 */
  96568. for(i = 0; i < (int)data_len; i++) {
  96569. sum = 0;
  96570. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96571. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96572. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96573. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96574. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96575. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96576. }
  96577. }
  96578. }
  96579. }
  96580. else {
  96581. if(order > 2) {
  96582. if(order == 4) {
  96583. for(i = 0; i < (int)data_len; i++) {
  96584. sum = 0;
  96585. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96586. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96587. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96588. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96589. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96590. }
  96591. }
  96592. else { /* order == 3 */
  96593. for(i = 0; i < (int)data_len; i++) {
  96594. sum = 0;
  96595. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96596. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96597. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96598. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96599. }
  96600. }
  96601. }
  96602. else {
  96603. if(order == 2) {
  96604. for(i = 0; i < (int)data_len; i++) {
  96605. sum = 0;
  96606. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96607. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96608. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96609. }
  96610. }
  96611. else { /* order == 1 */
  96612. for(i = 0; i < (int)data_len; i++)
  96613. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  96614. }
  96615. }
  96616. }
  96617. }
  96618. else { /* order > 12 */
  96619. for(i = 0; i < (int)data_len; i++) {
  96620. sum = 0;
  96621. switch(order) {
  96622. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  96623. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  96624. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  96625. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  96626. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  96627. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  96628. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  96629. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  96630. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  96631. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  96632. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  96633. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  96634. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  96635. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  96636. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  96637. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  96638. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  96639. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  96640. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  96641. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  96642. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  96643. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96644. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  96645. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  96646. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  96647. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  96648. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  96649. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  96650. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  96651. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  96652. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  96653. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  96654. }
  96655. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96656. }
  96657. }
  96658. }
  96659. #endif
  96660. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96661. void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
  96662. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96663. {
  96664. FLAC__int64 sumo;
  96665. unsigned i, j;
  96666. FLAC__int32 sum;
  96667. const FLAC__int32 *r = residual, *history;
  96668. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96669. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96670. for(i=0;i<order;i++)
  96671. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96672. fprintf(stderr,"\n");
  96673. #endif
  96674. FLAC__ASSERT(order > 0);
  96675. for(i = 0; i < data_len; i++) {
  96676. sumo = 0;
  96677. sum = 0;
  96678. history = data;
  96679. for(j = 0; j < order; j++) {
  96680. sum += qlp_coeff[j] * (*(--history));
  96681. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96682. #if defined _MSC_VER
  96683. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96684. fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
  96685. #else
  96686. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96687. fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
  96688. #endif
  96689. }
  96690. *(data++) = *(r++) + (sum >> lp_quantization);
  96691. }
  96692. /* Here's a slower but clearer version:
  96693. for(i = 0; i < data_len; i++) {
  96694. sum = 0;
  96695. for(j = 0; j < order; j++)
  96696. sum += qlp_coeff[j] * data[i-j-1];
  96697. data[i] = residual[i] + (sum >> lp_quantization);
  96698. }
  96699. */
  96700. }
  96701. #else /* fully unrolled version for normal use */
  96702. {
  96703. int i;
  96704. FLAC__int32 sum;
  96705. FLAC__ASSERT(order > 0);
  96706. FLAC__ASSERT(order <= 32);
  96707. /*
  96708. * We do unique versions up to 12th order since that's the subset limit.
  96709. * Also they are roughly ordered to match frequency of occurrence to
  96710. * minimize branching.
  96711. */
  96712. if(order <= 12) {
  96713. if(order > 8) {
  96714. if(order > 10) {
  96715. if(order == 12) {
  96716. for(i = 0; i < (int)data_len; i++) {
  96717. sum = 0;
  96718. sum += qlp_coeff[11] * data[i-12];
  96719. sum += qlp_coeff[10] * data[i-11];
  96720. sum += qlp_coeff[9] * data[i-10];
  96721. sum += qlp_coeff[8] * data[i-9];
  96722. sum += qlp_coeff[7] * data[i-8];
  96723. sum += qlp_coeff[6] * data[i-7];
  96724. sum += qlp_coeff[5] * data[i-6];
  96725. sum += qlp_coeff[4] * data[i-5];
  96726. sum += qlp_coeff[3] * data[i-4];
  96727. sum += qlp_coeff[2] * data[i-3];
  96728. sum += qlp_coeff[1] * data[i-2];
  96729. sum += qlp_coeff[0] * data[i-1];
  96730. data[i] = residual[i] + (sum >> lp_quantization);
  96731. }
  96732. }
  96733. else { /* order == 11 */
  96734. for(i = 0; i < (int)data_len; i++) {
  96735. sum = 0;
  96736. sum += qlp_coeff[10] * data[i-11];
  96737. sum += qlp_coeff[9] * data[i-10];
  96738. sum += qlp_coeff[8] * data[i-9];
  96739. sum += qlp_coeff[7] * data[i-8];
  96740. sum += qlp_coeff[6] * data[i-7];
  96741. sum += qlp_coeff[5] * data[i-6];
  96742. sum += qlp_coeff[4] * data[i-5];
  96743. sum += qlp_coeff[3] * data[i-4];
  96744. sum += qlp_coeff[2] * data[i-3];
  96745. sum += qlp_coeff[1] * data[i-2];
  96746. sum += qlp_coeff[0] * data[i-1];
  96747. data[i] = residual[i] + (sum >> lp_quantization);
  96748. }
  96749. }
  96750. }
  96751. else {
  96752. if(order == 10) {
  96753. for(i = 0; i < (int)data_len; i++) {
  96754. sum = 0;
  96755. sum += qlp_coeff[9] * data[i-10];
  96756. sum += qlp_coeff[8] * data[i-9];
  96757. sum += qlp_coeff[7] * data[i-8];
  96758. sum += qlp_coeff[6] * data[i-7];
  96759. sum += qlp_coeff[5] * data[i-6];
  96760. sum += qlp_coeff[4] * data[i-5];
  96761. sum += qlp_coeff[3] * data[i-4];
  96762. sum += qlp_coeff[2] * data[i-3];
  96763. sum += qlp_coeff[1] * data[i-2];
  96764. sum += qlp_coeff[0] * data[i-1];
  96765. data[i] = residual[i] + (sum >> lp_quantization);
  96766. }
  96767. }
  96768. else { /* order == 9 */
  96769. for(i = 0; i < (int)data_len; i++) {
  96770. sum = 0;
  96771. sum += qlp_coeff[8] * data[i-9];
  96772. sum += qlp_coeff[7] * data[i-8];
  96773. sum += qlp_coeff[6] * data[i-7];
  96774. sum += qlp_coeff[5] * data[i-6];
  96775. sum += qlp_coeff[4] * data[i-5];
  96776. sum += qlp_coeff[3] * data[i-4];
  96777. sum += qlp_coeff[2] * data[i-3];
  96778. sum += qlp_coeff[1] * data[i-2];
  96779. sum += qlp_coeff[0] * data[i-1];
  96780. data[i] = residual[i] + (sum >> lp_quantization);
  96781. }
  96782. }
  96783. }
  96784. }
  96785. else if(order > 4) {
  96786. if(order > 6) {
  96787. if(order == 8) {
  96788. for(i = 0; i < (int)data_len; i++) {
  96789. sum = 0;
  96790. sum += qlp_coeff[7] * data[i-8];
  96791. sum += qlp_coeff[6] * data[i-7];
  96792. sum += qlp_coeff[5] * data[i-6];
  96793. sum += qlp_coeff[4] * data[i-5];
  96794. sum += qlp_coeff[3] * data[i-4];
  96795. sum += qlp_coeff[2] * data[i-3];
  96796. sum += qlp_coeff[1] * data[i-2];
  96797. sum += qlp_coeff[0] * data[i-1];
  96798. data[i] = residual[i] + (sum >> lp_quantization);
  96799. }
  96800. }
  96801. else { /* order == 7 */
  96802. for(i = 0; i < (int)data_len; i++) {
  96803. sum = 0;
  96804. sum += qlp_coeff[6] * data[i-7];
  96805. sum += qlp_coeff[5] * data[i-6];
  96806. sum += qlp_coeff[4] * data[i-5];
  96807. sum += qlp_coeff[3] * data[i-4];
  96808. sum += qlp_coeff[2] * data[i-3];
  96809. sum += qlp_coeff[1] * data[i-2];
  96810. sum += qlp_coeff[0] * data[i-1];
  96811. data[i] = residual[i] + (sum >> lp_quantization);
  96812. }
  96813. }
  96814. }
  96815. else {
  96816. if(order == 6) {
  96817. for(i = 0; i < (int)data_len; i++) {
  96818. sum = 0;
  96819. sum += qlp_coeff[5] * data[i-6];
  96820. sum += qlp_coeff[4] * data[i-5];
  96821. sum += qlp_coeff[3] * data[i-4];
  96822. sum += qlp_coeff[2] * data[i-3];
  96823. sum += qlp_coeff[1] * data[i-2];
  96824. sum += qlp_coeff[0] * data[i-1];
  96825. data[i] = residual[i] + (sum >> lp_quantization);
  96826. }
  96827. }
  96828. else { /* order == 5 */
  96829. for(i = 0; i < (int)data_len; i++) {
  96830. sum = 0;
  96831. sum += qlp_coeff[4] * data[i-5];
  96832. sum += qlp_coeff[3] * data[i-4];
  96833. sum += qlp_coeff[2] * data[i-3];
  96834. sum += qlp_coeff[1] * data[i-2];
  96835. sum += qlp_coeff[0] * data[i-1];
  96836. data[i] = residual[i] + (sum >> lp_quantization);
  96837. }
  96838. }
  96839. }
  96840. }
  96841. else {
  96842. if(order > 2) {
  96843. if(order == 4) {
  96844. for(i = 0; i < (int)data_len; i++) {
  96845. sum = 0;
  96846. sum += qlp_coeff[3] * data[i-4];
  96847. sum += qlp_coeff[2] * data[i-3];
  96848. sum += qlp_coeff[1] * data[i-2];
  96849. sum += qlp_coeff[0] * data[i-1];
  96850. data[i] = residual[i] + (sum >> lp_quantization);
  96851. }
  96852. }
  96853. else { /* order == 3 */
  96854. for(i = 0; i < (int)data_len; i++) {
  96855. sum = 0;
  96856. sum += qlp_coeff[2] * data[i-3];
  96857. sum += qlp_coeff[1] * data[i-2];
  96858. sum += qlp_coeff[0] * data[i-1];
  96859. data[i] = residual[i] + (sum >> lp_quantization);
  96860. }
  96861. }
  96862. }
  96863. else {
  96864. if(order == 2) {
  96865. for(i = 0; i < (int)data_len; i++) {
  96866. sum = 0;
  96867. sum += qlp_coeff[1] * data[i-2];
  96868. sum += qlp_coeff[0] * data[i-1];
  96869. data[i] = residual[i] + (sum >> lp_quantization);
  96870. }
  96871. }
  96872. else { /* order == 1 */
  96873. for(i = 0; i < (int)data_len; i++)
  96874. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  96875. }
  96876. }
  96877. }
  96878. }
  96879. else { /* order > 12 */
  96880. for(i = 0; i < (int)data_len; i++) {
  96881. sum = 0;
  96882. switch(order) {
  96883. case 32: sum += qlp_coeff[31] * data[i-32];
  96884. case 31: sum += qlp_coeff[30] * data[i-31];
  96885. case 30: sum += qlp_coeff[29] * data[i-30];
  96886. case 29: sum += qlp_coeff[28] * data[i-29];
  96887. case 28: sum += qlp_coeff[27] * data[i-28];
  96888. case 27: sum += qlp_coeff[26] * data[i-27];
  96889. case 26: sum += qlp_coeff[25] * data[i-26];
  96890. case 25: sum += qlp_coeff[24] * data[i-25];
  96891. case 24: sum += qlp_coeff[23] * data[i-24];
  96892. case 23: sum += qlp_coeff[22] * data[i-23];
  96893. case 22: sum += qlp_coeff[21] * data[i-22];
  96894. case 21: sum += qlp_coeff[20] * data[i-21];
  96895. case 20: sum += qlp_coeff[19] * data[i-20];
  96896. case 19: sum += qlp_coeff[18] * data[i-19];
  96897. case 18: sum += qlp_coeff[17] * data[i-18];
  96898. case 17: sum += qlp_coeff[16] * data[i-17];
  96899. case 16: sum += qlp_coeff[15] * data[i-16];
  96900. case 15: sum += qlp_coeff[14] * data[i-15];
  96901. case 14: sum += qlp_coeff[13] * data[i-14];
  96902. case 13: sum += qlp_coeff[12] * data[i-13];
  96903. sum += qlp_coeff[11] * data[i-12];
  96904. sum += qlp_coeff[10] * data[i-11];
  96905. sum += qlp_coeff[ 9] * data[i-10];
  96906. sum += qlp_coeff[ 8] * data[i- 9];
  96907. sum += qlp_coeff[ 7] * data[i- 8];
  96908. sum += qlp_coeff[ 6] * data[i- 7];
  96909. sum += qlp_coeff[ 5] * data[i- 6];
  96910. sum += qlp_coeff[ 4] * data[i- 5];
  96911. sum += qlp_coeff[ 3] * data[i- 4];
  96912. sum += qlp_coeff[ 2] * data[i- 3];
  96913. sum += qlp_coeff[ 1] * data[i- 2];
  96914. sum += qlp_coeff[ 0] * data[i- 1];
  96915. }
  96916. data[i] = residual[i] + (sum >> lp_quantization);
  96917. }
  96918. }
  96919. }
  96920. #endif
  96921. void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
  96922. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96923. {
  96924. unsigned i, j;
  96925. FLAC__int64 sum;
  96926. const FLAC__int32 *r = residual, *history;
  96927. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96928. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96929. for(i=0;i<order;i++)
  96930. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96931. fprintf(stderr,"\n");
  96932. #endif
  96933. FLAC__ASSERT(order > 0);
  96934. for(i = 0; i < data_len; i++) {
  96935. sum = 0;
  96936. history = data;
  96937. for(j = 0; j < order; j++)
  96938. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  96939. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  96940. #ifdef _MSC_VER
  96941. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  96942. #else
  96943. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  96944. #endif
  96945. break;
  96946. }
  96947. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  96948. #ifdef _MSC_VER
  96949. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%I64d, data=%I64d\n", i, *r, sum >> lp_quantization, (FLAC__int64)(*r) + (sum >> lp_quantization));
  96950. #else
  96951. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%lld, data=%lld\n", i, *r, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*r) + (sum >> lp_quantization)));
  96952. #endif
  96953. break;
  96954. }
  96955. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  96956. }
  96957. }
  96958. #else /* fully unrolled version for normal use */
  96959. {
  96960. int i;
  96961. FLAC__int64 sum;
  96962. FLAC__ASSERT(order > 0);
  96963. FLAC__ASSERT(order <= 32);
  96964. /*
  96965. * We do unique versions up to 12th order since that's the subset limit.
  96966. * Also they are roughly ordered to match frequency of occurrence to
  96967. * minimize branching.
  96968. */
  96969. if(order <= 12) {
  96970. if(order > 8) {
  96971. if(order > 10) {
  96972. if(order == 12) {
  96973. for(i = 0; i < (int)data_len; i++) {
  96974. sum = 0;
  96975. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  96976. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96977. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96978. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96979. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96980. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96981. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96982. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96983. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96984. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96985. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96986. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96987. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  96988. }
  96989. }
  96990. else { /* order == 11 */
  96991. for(i = 0; i < (int)data_len; i++) {
  96992. sum = 0;
  96993. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96994. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96995. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96996. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96997. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96998. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96999. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97000. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97001. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97002. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97003. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97004. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97005. }
  97006. }
  97007. }
  97008. else {
  97009. if(order == 10) {
  97010. for(i = 0; i < (int)data_len; i++) {
  97011. sum = 0;
  97012. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97013. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97014. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97015. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97016. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97017. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97018. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97019. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97020. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97021. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97022. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97023. }
  97024. }
  97025. else { /* order == 9 */
  97026. for(i = 0; i < (int)data_len; i++) {
  97027. sum = 0;
  97028. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97029. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97030. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97031. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97032. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97033. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97034. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97035. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97036. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97037. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97038. }
  97039. }
  97040. }
  97041. }
  97042. else if(order > 4) {
  97043. if(order > 6) {
  97044. if(order == 8) {
  97045. for(i = 0; i < (int)data_len; i++) {
  97046. sum = 0;
  97047. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97048. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97049. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97050. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97051. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97052. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97053. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97054. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97055. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97056. }
  97057. }
  97058. else { /* order == 7 */
  97059. for(i = 0; i < (int)data_len; i++) {
  97060. sum = 0;
  97061. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97062. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97063. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97064. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97065. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97066. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97067. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97068. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97069. }
  97070. }
  97071. }
  97072. else {
  97073. if(order == 6) {
  97074. for(i = 0; i < (int)data_len; i++) {
  97075. sum = 0;
  97076. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97077. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97078. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97079. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97080. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97081. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97082. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97083. }
  97084. }
  97085. else { /* order == 5 */
  97086. for(i = 0; i < (int)data_len; i++) {
  97087. sum = 0;
  97088. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97089. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97090. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97091. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97092. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97093. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97094. }
  97095. }
  97096. }
  97097. }
  97098. else {
  97099. if(order > 2) {
  97100. if(order == 4) {
  97101. for(i = 0; i < (int)data_len; i++) {
  97102. sum = 0;
  97103. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97104. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97105. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97106. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97107. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97108. }
  97109. }
  97110. else { /* order == 3 */
  97111. for(i = 0; i < (int)data_len; i++) {
  97112. sum = 0;
  97113. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97114. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97115. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97116. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97117. }
  97118. }
  97119. }
  97120. else {
  97121. if(order == 2) {
  97122. for(i = 0; i < (int)data_len; i++) {
  97123. sum = 0;
  97124. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97125. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97126. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97127. }
  97128. }
  97129. else { /* order == 1 */
  97130. for(i = 0; i < (int)data_len; i++)
  97131. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97132. }
  97133. }
  97134. }
  97135. }
  97136. else { /* order > 12 */
  97137. for(i = 0; i < (int)data_len; i++) {
  97138. sum = 0;
  97139. switch(order) {
  97140. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97141. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97142. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97143. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97144. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97145. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97146. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97147. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97148. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97149. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97150. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97151. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97152. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97153. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97154. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97155. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97156. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97157. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97158. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97159. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97160. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97161. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97162. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97163. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97164. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97165. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97166. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97167. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97168. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97169. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97170. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97171. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97172. }
  97173. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97174. }
  97175. }
  97176. }
  97177. #endif
  97178. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97179. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  97180. {
  97181. FLAC__double error_scale;
  97182. FLAC__ASSERT(total_samples > 0);
  97183. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97184. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  97185. }
  97186. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  97187. {
  97188. if(lpc_error > 0.0) {
  97189. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  97190. if(bps >= 0.0)
  97191. return bps;
  97192. else
  97193. return 0.0;
  97194. }
  97195. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  97196. return 1e32;
  97197. }
  97198. else {
  97199. return 0.0;
  97200. }
  97201. }
  97202. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  97203. {
  97204. unsigned order, index, best_index; /* 'index' the index into lpc_error; index==order-1 since lpc_error[0] is for order==1, lpc_error[1] is for order==2, etc */
  97205. FLAC__double bits, best_bits, error_scale;
  97206. FLAC__ASSERT(max_order > 0);
  97207. FLAC__ASSERT(total_samples > 0);
  97208. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97209. best_index = 0;
  97210. best_bits = (unsigned)(-1);
  97211. for(index = 0, order = 1; index < max_order; index++, order++) {
  97212. bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[index], error_scale) * (FLAC__double)(total_samples - order) + (FLAC__double)(order * overhead_bits_per_order);
  97213. if(bits < best_bits) {
  97214. best_index = index;
  97215. best_bits = bits;
  97216. }
  97217. }
  97218. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  97219. }
  97220. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97221. #endif
  97222. /*** End of inlined file: lpc_flac.c ***/
  97223. /*** Start of inlined file: md5.c ***/
  97224. /*** Start of inlined file: juce_FlacHeader.h ***/
  97225. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97226. // tasks..
  97227. #define VERSION "1.2.1"
  97228. #define FLAC__NO_DLL 1
  97229. #if JUCE_MSVC
  97230. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97231. #endif
  97232. #if JUCE_MAC
  97233. #define FLAC__SYS_DARWIN 1
  97234. #endif
  97235. /*** End of inlined file: juce_FlacHeader.h ***/
  97236. #if JUCE_USE_FLAC
  97237. #if HAVE_CONFIG_H
  97238. # include <config.h>
  97239. #endif
  97240. #include <stdlib.h> /* for malloc() */
  97241. #include <string.h> /* for memcpy() */
  97242. /*** Start of inlined file: md5.h ***/
  97243. #ifndef FLAC__PRIVATE__MD5_H
  97244. #define FLAC__PRIVATE__MD5_H
  97245. /*
  97246. * This is the header file for the MD5 message-digest algorithm.
  97247. * The algorithm is due to Ron Rivest. This code was
  97248. * written by Colin Plumb in 1993, no copyright is claimed.
  97249. * This code is in the public domain; do with it what you wish.
  97250. *
  97251. * Equivalent code is available from RSA Data Security, Inc.
  97252. * This code has been tested against that, and is equivalent,
  97253. * except that you don't need to include two pages of legalese
  97254. * with every copy.
  97255. *
  97256. * To compute the message digest of a chunk of bytes, declare an
  97257. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97258. * needed on buffers full of bytes, and then call MD5Final, which
  97259. * will fill a supplied 16-byte array with the digest.
  97260. *
  97261. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  97262. * header definitions; now uses stuff from dpkg's config.h
  97263. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97264. * Still in the public domain.
  97265. *
  97266. * Josh Coalson: made some changes to integrate with libFLAC.
  97267. * Still in the public domain, with no warranty.
  97268. */
  97269. typedef struct {
  97270. FLAC__uint32 in[16];
  97271. FLAC__uint32 buf[4];
  97272. FLAC__uint32 bytes[2];
  97273. FLAC__byte *internal_buf;
  97274. size_t capacity;
  97275. } FLAC__MD5Context;
  97276. void FLAC__MD5Init(FLAC__MD5Context *context);
  97277. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  97278. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  97279. #endif
  97280. /*** End of inlined file: md5.h ***/
  97281. #ifndef FLaC__INLINE
  97282. #define FLaC__INLINE
  97283. #endif
  97284. /*
  97285. * This code implements the MD5 message-digest algorithm.
  97286. * The algorithm is due to Ron Rivest. This code was
  97287. * written by Colin Plumb in 1993, no copyright is claimed.
  97288. * This code is in the public domain; do with it what you wish.
  97289. *
  97290. * Equivalent code is available from RSA Data Security, Inc.
  97291. * This code has been tested against that, and is equivalent,
  97292. * except that you don't need to include two pages of legalese
  97293. * with every copy.
  97294. *
  97295. * To compute the message digest of a chunk of bytes, declare an
  97296. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97297. * needed on buffers full of bytes, and then call MD5Final, which
  97298. * will fill a supplied 16-byte array with the digest.
  97299. *
  97300. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  97301. * definitions; now uses stuff from dpkg's config.h.
  97302. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97303. * Still in the public domain.
  97304. *
  97305. * Josh Coalson: made some changes to integrate with libFLAC.
  97306. * Still in the public domain.
  97307. */
  97308. /* The four core functions - F1 is optimized somewhat */
  97309. /* #define F1(x, y, z) (x & y | ~x & z) */
  97310. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  97311. #define F2(x, y, z) F1(z, x, y)
  97312. #define F3(x, y, z) (x ^ y ^ z)
  97313. #define F4(x, y, z) (y ^ (x | ~z))
  97314. /* This is the central step in the MD5 algorithm. */
  97315. #define MD5STEP(f,w,x,y,z,in,s) \
  97316. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  97317. /*
  97318. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  97319. * reflect the addition of 16 longwords of new data. MD5Update blocks
  97320. * the data and converts bytes into longwords for this routine.
  97321. */
  97322. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  97323. {
  97324. register FLAC__uint32 a, b, c, d;
  97325. a = buf[0];
  97326. b = buf[1];
  97327. c = buf[2];
  97328. d = buf[3];
  97329. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  97330. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  97331. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  97332. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  97333. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  97334. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  97335. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  97336. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  97337. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  97338. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  97339. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  97340. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  97341. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  97342. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  97343. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  97344. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  97345. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  97346. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  97347. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  97348. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  97349. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  97350. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  97351. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  97352. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  97353. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  97354. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  97355. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  97356. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  97357. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  97358. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  97359. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  97360. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  97361. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  97362. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  97363. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  97364. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  97365. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  97366. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  97367. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  97368. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  97369. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  97370. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  97371. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  97372. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  97373. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  97374. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  97375. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  97376. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  97377. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  97378. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  97379. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  97380. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  97381. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  97382. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  97383. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  97384. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  97385. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  97386. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  97387. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  97388. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  97389. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  97390. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  97391. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  97392. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  97393. buf[0] += a;
  97394. buf[1] += b;
  97395. buf[2] += c;
  97396. buf[3] += d;
  97397. }
  97398. #if WORDS_BIGENDIAN
  97399. //@@@@@@ OPT: use bswap/intrinsics
  97400. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  97401. {
  97402. register FLAC__uint32 x;
  97403. do {
  97404. x = *buf;
  97405. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  97406. *buf++ = (x >> 16) | (x << 16);
  97407. } while (--words);
  97408. }
  97409. static void byteSwapX16(FLAC__uint32 *buf)
  97410. {
  97411. register FLAC__uint32 x;
  97412. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97413. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97414. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97415. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97416. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97417. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97418. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97419. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97420. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97421. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97422. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97423. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97424. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97425. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97426. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97427. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  97428. }
  97429. #else
  97430. #define byteSwap(buf, words)
  97431. #define byteSwapX16(buf)
  97432. #endif
  97433. /*
  97434. * Update context to reflect the concatenation of another buffer full
  97435. * of bytes.
  97436. */
  97437. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  97438. {
  97439. FLAC__uint32 t;
  97440. /* Update byte count */
  97441. t = ctx->bytes[0];
  97442. if ((ctx->bytes[0] = t + len) < t)
  97443. ctx->bytes[1]++; /* Carry from low to high */
  97444. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  97445. if (t > len) {
  97446. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  97447. return;
  97448. }
  97449. /* First chunk is an odd size */
  97450. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  97451. byteSwapX16(ctx->in);
  97452. FLAC__MD5Transform(ctx->buf, ctx->in);
  97453. buf += t;
  97454. len -= t;
  97455. /* Process data in 64-byte chunks */
  97456. while (len >= 64) {
  97457. memcpy(ctx->in, buf, 64);
  97458. byteSwapX16(ctx->in);
  97459. FLAC__MD5Transform(ctx->buf, ctx->in);
  97460. buf += 64;
  97461. len -= 64;
  97462. }
  97463. /* Handle any remaining bytes of data. */
  97464. memcpy(ctx->in, buf, len);
  97465. }
  97466. /*
  97467. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  97468. * initialization constants.
  97469. */
  97470. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  97471. {
  97472. ctx->buf[0] = 0x67452301;
  97473. ctx->buf[1] = 0xefcdab89;
  97474. ctx->buf[2] = 0x98badcfe;
  97475. ctx->buf[3] = 0x10325476;
  97476. ctx->bytes[0] = 0;
  97477. ctx->bytes[1] = 0;
  97478. ctx->internal_buf = 0;
  97479. ctx->capacity = 0;
  97480. }
  97481. /*
  97482. * Final wrapup - pad to 64-byte boundary with the bit pattern
  97483. * 1 0* (64-bit count of bits processed, MSB-first)
  97484. */
  97485. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  97486. {
  97487. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  97488. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  97489. /* Set the first char of padding to 0x80. There is always room. */
  97490. *p++ = 0x80;
  97491. /* Bytes of padding needed to make 56 bytes (-8..55) */
  97492. count = 56 - 1 - count;
  97493. if (count < 0) { /* Padding forces an extra block */
  97494. memset(p, 0, count + 8);
  97495. byteSwapX16(ctx->in);
  97496. FLAC__MD5Transform(ctx->buf, ctx->in);
  97497. p = (FLAC__byte *)ctx->in;
  97498. count = 56;
  97499. }
  97500. memset(p, 0, count);
  97501. byteSwap(ctx->in, 14);
  97502. /* Append length in bits and transform */
  97503. ctx->in[14] = ctx->bytes[0] << 3;
  97504. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  97505. FLAC__MD5Transform(ctx->buf, ctx->in);
  97506. byteSwap(ctx->buf, 4);
  97507. memcpy(digest, ctx->buf, 16);
  97508. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  97509. if(0 != ctx->internal_buf) {
  97510. free(ctx->internal_buf);
  97511. ctx->internal_buf = 0;
  97512. ctx->capacity = 0;
  97513. }
  97514. }
  97515. /*
  97516. * Convert the incoming audio signal to a byte stream
  97517. */
  97518. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  97519. {
  97520. unsigned channel, sample;
  97521. register FLAC__int32 a_word;
  97522. register FLAC__byte *buf_ = buf;
  97523. #if WORDS_BIGENDIAN
  97524. #else
  97525. if(channels == 2 && bytes_per_sample == 2) {
  97526. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  97527. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  97528. for(sample = 0; sample < samples; sample++, buf1_+=2)
  97529. *buf1_ = (FLAC__int16)signal[1][sample];
  97530. }
  97531. else if(channels == 1 && bytes_per_sample == 2) {
  97532. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  97533. for(sample = 0; sample < samples; sample++)
  97534. *buf1_++ = (FLAC__int16)signal[0][sample];
  97535. }
  97536. else
  97537. #endif
  97538. if(bytes_per_sample == 2) {
  97539. if(channels == 2) {
  97540. for(sample = 0; sample < samples; sample++) {
  97541. a_word = signal[0][sample];
  97542. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97543. *buf_++ = (FLAC__byte)a_word;
  97544. a_word = signal[1][sample];
  97545. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97546. *buf_++ = (FLAC__byte)a_word;
  97547. }
  97548. }
  97549. else if(channels == 1) {
  97550. for(sample = 0; sample < samples; sample++) {
  97551. a_word = signal[0][sample];
  97552. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97553. *buf_++ = (FLAC__byte)a_word;
  97554. }
  97555. }
  97556. else {
  97557. for(sample = 0; sample < samples; sample++) {
  97558. for(channel = 0; channel < channels; channel++) {
  97559. a_word = signal[channel][sample];
  97560. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97561. *buf_++ = (FLAC__byte)a_word;
  97562. }
  97563. }
  97564. }
  97565. }
  97566. else if(bytes_per_sample == 3) {
  97567. if(channels == 2) {
  97568. for(sample = 0; sample < samples; sample++) {
  97569. a_word = signal[0][sample];
  97570. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97571. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97572. *buf_++ = (FLAC__byte)a_word;
  97573. a_word = signal[1][sample];
  97574. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97575. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97576. *buf_++ = (FLAC__byte)a_word;
  97577. }
  97578. }
  97579. else if(channels == 1) {
  97580. for(sample = 0; sample < samples; sample++) {
  97581. a_word = signal[0][sample];
  97582. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97583. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97584. *buf_++ = (FLAC__byte)a_word;
  97585. }
  97586. }
  97587. else {
  97588. for(sample = 0; sample < samples; sample++) {
  97589. for(channel = 0; channel < channels; channel++) {
  97590. a_word = signal[channel][sample];
  97591. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97592. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97593. *buf_++ = (FLAC__byte)a_word;
  97594. }
  97595. }
  97596. }
  97597. }
  97598. else if(bytes_per_sample == 1) {
  97599. if(channels == 2) {
  97600. for(sample = 0; sample < samples; sample++) {
  97601. a_word = signal[0][sample];
  97602. *buf_++ = (FLAC__byte)a_word;
  97603. a_word = signal[1][sample];
  97604. *buf_++ = (FLAC__byte)a_word;
  97605. }
  97606. }
  97607. else if(channels == 1) {
  97608. for(sample = 0; sample < samples; sample++) {
  97609. a_word = signal[0][sample];
  97610. *buf_++ = (FLAC__byte)a_word;
  97611. }
  97612. }
  97613. else {
  97614. for(sample = 0; sample < samples; sample++) {
  97615. for(channel = 0; channel < channels; channel++) {
  97616. a_word = signal[channel][sample];
  97617. *buf_++ = (FLAC__byte)a_word;
  97618. }
  97619. }
  97620. }
  97621. }
  97622. else { /* bytes_per_sample == 4, maybe optimize more later */
  97623. for(sample = 0; sample < samples; sample++) {
  97624. for(channel = 0; channel < channels; channel++) {
  97625. a_word = signal[channel][sample];
  97626. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97627. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97628. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97629. *buf_++ = (FLAC__byte)a_word;
  97630. }
  97631. }
  97632. }
  97633. }
  97634. /*
  97635. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  97636. */
  97637. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  97638. {
  97639. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  97640. /* overflow check */
  97641. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  97642. return false;
  97643. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  97644. return false;
  97645. if(ctx->capacity < bytes_needed) {
  97646. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  97647. if(0 == tmp) {
  97648. free(ctx->internal_buf);
  97649. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  97650. return false;
  97651. }
  97652. ctx->internal_buf = tmp;
  97653. ctx->capacity = bytes_needed;
  97654. }
  97655. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  97656. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  97657. return true;
  97658. }
  97659. #endif
  97660. /*** End of inlined file: md5.c ***/
  97661. /*** Start of inlined file: memory.c ***/
  97662. /*** Start of inlined file: juce_FlacHeader.h ***/
  97663. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97664. // tasks..
  97665. #define VERSION "1.2.1"
  97666. #define FLAC__NO_DLL 1
  97667. #if JUCE_MSVC
  97668. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97669. #endif
  97670. #if JUCE_MAC
  97671. #define FLAC__SYS_DARWIN 1
  97672. #endif
  97673. /*** End of inlined file: juce_FlacHeader.h ***/
  97674. #if JUCE_USE_FLAC
  97675. #if HAVE_CONFIG_H
  97676. # include <config.h>
  97677. #endif
  97678. /*** Start of inlined file: memory.h ***/
  97679. #ifndef FLAC__PRIVATE__MEMORY_H
  97680. #define FLAC__PRIVATE__MEMORY_H
  97681. #ifdef HAVE_CONFIG_H
  97682. #include <config.h>
  97683. #endif
  97684. #include <stdlib.h> /* for size_t */
  97685. /* Returns the unaligned address returned by malloc.
  97686. * Use free() on this address to deallocate.
  97687. */
  97688. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  97689. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  97690. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  97691. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  97692. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  97693. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97694. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  97695. #endif
  97696. #endif
  97697. /*** End of inlined file: memory.h ***/
  97698. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  97699. {
  97700. void *x;
  97701. FLAC__ASSERT(0 != aligned_address);
  97702. #ifdef FLAC__ALIGN_MALLOC_DATA
  97703. /* align on 32-byte (256-bit) boundary */
  97704. x = safe_malloc_add_2op_(bytes, /*+*/31);
  97705. #ifdef SIZEOF_VOIDP
  97706. #if SIZEOF_VOIDP == 4
  97707. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  97708. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  97709. #elif SIZEOF_VOIDP == 8
  97710. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  97711. #else
  97712. # error Unsupported sizeof(void*)
  97713. #endif
  97714. #else
  97715. /* there's got to be a better way to do this right for all archs */
  97716. if(sizeof(void*) == sizeof(unsigned))
  97717. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  97718. else if(sizeof(void*) == sizeof(FLAC__uint64))
  97719. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  97720. else
  97721. return 0;
  97722. #endif
  97723. #else
  97724. x = safe_malloc_(bytes);
  97725. *aligned_address = x;
  97726. #endif
  97727. return x;
  97728. }
  97729. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  97730. {
  97731. FLAC__int32 *pu; /* unaligned pointer */
  97732. union { /* union needed to comply with C99 pointer aliasing rules */
  97733. FLAC__int32 *pa; /* aligned pointer */
  97734. void *pv; /* aligned pointer alias */
  97735. } u;
  97736. FLAC__ASSERT(elements > 0);
  97737. FLAC__ASSERT(0 != unaligned_pointer);
  97738. FLAC__ASSERT(0 != aligned_pointer);
  97739. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  97740. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  97741. if(0 == pu) {
  97742. return false;
  97743. }
  97744. else {
  97745. if(*unaligned_pointer != 0)
  97746. free(*unaligned_pointer);
  97747. *unaligned_pointer = pu;
  97748. *aligned_pointer = u.pa;
  97749. return true;
  97750. }
  97751. }
  97752. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  97753. {
  97754. FLAC__uint32 *pu; /* unaligned pointer */
  97755. union { /* union needed to comply with C99 pointer aliasing rules */
  97756. FLAC__uint32 *pa; /* aligned pointer */
  97757. void *pv; /* aligned pointer alias */
  97758. } u;
  97759. FLAC__ASSERT(elements > 0);
  97760. FLAC__ASSERT(0 != unaligned_pointer);
  97761. FLAC__ASSERT(0 != aligned_pointer);
  97762. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  97763. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  97764. if(0 == pu) {
  97765. return false;
  97766. }
  97767. else {
  97768. if(*unaligned_pointer != 0)
  97769. free(*unaligned_pointer);
  97770. *unaligned_pointer = pu;
  97771. *aligned_pointer = u.pa;
  97772. return true;
  97773. }
  97774. }
  97775. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  97776. {
  97777. FLAC__uint64 *pu; /* unaligned pointer */
  97778. union { /* union needed to comply with C99 pointer aliasing rules */
  97779. FLAC__uint64 *pa; /* aligned pointer */
  97780. void *pv; /* aligned pointer alias */
  97781. } u;
  97782. FLAC__ASSERT(elements > 0);
  97783. FLAC__ASSERT(0 != unaligned_pointer);
  97784. FLAC__ASSERT(0 != aligned_pointer);
  97785. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  97786. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  97787. if(0 == pu) {
  97788. return false;
  97789. }
  97790. else {
  97791. if(*unaligned_pointer != 0)
  97792. free(*unaligned_pointer);
  97793. *unaligned_pointer = pu;
  97794. *aligned_pointer = u.pa;
  97795. return true;
  97796. }
  97797. }
  97798. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  97799. {
  97800. unsigned *pu; /* unaligned pointer */
  97801. union { /* union needed to comply with C99 pointer aliasing rules */
  97802. unsigned *pa; /* aligned pointer */
  97803. void *pv; /* aligned pointer alias */
  97804. } u;
  97805. FLAC__ASSERT(elements > 0);
  97806. FLAC__ASSERT(0 != unaligned_pointer);
  97807. FLAC__ASSERT(0 != aligned_pointer);
  97808. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  97809. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  97810. if(0 == pu) {
  97811. return false;
  97812. }
  97813. else {
  97814. if(*unaligned_pointer != 0)
  97815. free(*unaligned_pointer);
  97816. *unaligned_pointer = pu;
  97817. *aligned_pointer = u.pa;
  97818. return true;
  97819. }
  97820. }
  97821. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97822. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  97823. {
  97824. FLAC__real *pu; /* unaligned pointer */
  97825. union { /* union needed to comply with C99 pointer aliasing rules */
  97826. FLAC__real *pa; /* aligned pointer */
  97827. void *pv; /* aligned pointer alias */
  97828. } u;
  97829. FLAC__ASSERT(elements > 0);
  97830. FLAC__ASSERT(0 != unaligned_pointer);
  97831. FLAC__ASSERT(0 != aligned_pointer);
  97832. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  97833. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  97834. if(0 == pu) {
  97835. return false;
  97836. }
  97837. else {
  97838. if(*unaligned_pointer != 0)
  97839. free(*unaligned_pointer);
  97840. *unaligned_pointer = pu;
  97841. *aligned_pointer = u.pa;
  97842. return true;
  97843. }
  97844. }
  97845. #endif
  97846. #endif
  97847. /*** End of inlined file: memory.c ***/
  97848. /*** Start of inlined file: stream_decoder.c ***/
  97849. /*** Start of inlined file: juce_FlacHeader.h ***/
  97850. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97851. // tasks..
  97852. #define VERSION "1.2.1"
  97853. #define FLAC__NO_DLL 1
  97854. #if JUCE_MSVC
  97855. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97856. #endif
  97857. #if JUCE_MAC
  97858. #define FLAC__SYS_DARWIN 1
  97859. #endif
  97860. /*** End of inlined file: juce_FlacHeader.h ***/
  97861. #if JUCE_USE_FLAC
  97862. #if HAVE_CONFIG_H
  97863. # include <config.h>
  97864. #endif
  97865. #if defined _MSC_VER || defined __MINGW32__
  97866. #include <io.h> /* for _setmode() */
  97867. #include <fcntl.h> /* for _O_BINARY */
  97868. #endif
  97869. #if defined __CYGWIN__ || defined __EMX__
  97870. #include <io.h> /* for setmode(), O_BINARY */
  97871. #include <fcntl.h> /* for _O_BINARY */
  97872. #endif
  97873. #include <stdio.h>
  97874. #include <stdlib.h> /* for malloc() */
  97875. #include <string.h> /* for memset/memcpy() */
  97876. #include <sys/stat.h> /* for stat() */
  97877. #include <sys/types.h> /* for off_t */
  97878. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  97879. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  97880. #define fseeko fseek
  97881. #define ftello ftell
  97882. #endif
  97883. #endif
  97884. /*** Start of inlined file: stream_decoder.h ***/
  97885. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  97886. #define FLAC__PROTECTED__STREAM_DECODER_H
  97887. #if FLAC__HAS_OGG
  97888. #include "include/private/ogg_decoder_aspect.h"
  97889. #endif
  97890. typedef struct FLAC__StreamDecoderProtected {
  97891. FLAC__StreamDecoderState state;
  97892. unsigned channels;
  97893. FLAC__ChannelAssignment channel_assignment;
  97894. unsigned bits_per_sample;
  97895. unsigned sample_rate; /* in Hz */
  97896. unsigned blocksize; /* in samples (per channel) */
  97897. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  97898. #if FLAC__HAS_OGG
  97899. FLAC__OggDecoderAspect ogg_decoder_aspect;
  97900. #endif
  97901. } FLAC__StreamDecoderProtected;
  97902. /*
  97903. * return the number of input bytes consumed
  97904. */
  97905. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  97906. #endif
  97907. /*** End of inlined file: stream_decoder.h ***/
  97908. #ifdef max
  97909. #undef max
  97910. #endif
  97911. #define max(a,b) ((a)>(b)?(a):(b))
  97912. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  97913. #ifdef _MSC_VER
  97914. #define FLAC__U64L(x) x
  97915. #else
  97916. #define FLAC__U64L(x) x##LLU
  97917. #endif
  97918. /* technically this should be in an "export.c" but this is convenient enough */
  97919. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  97920. #if FLAC__HAS_OGG
  97921. 1
  97922. #else
  97923. 0
  97924. #endif
  97925. ;
  97926. /***********************************************************************
  97927. *
  97928. * Private static data
  97929. *
  97930. ***********************************************************************/
  97931. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  97932. /***********************************************************************
  97933. *
  97934. * Private class method prototypes
  97935. *
  97936. ***********************************************************************/
  97937. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  97938. static FILE *get_binary_stdin_(void);
  97939. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  97940. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  97941. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  97942. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  97943. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  97944. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  97945. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  97946. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  97947. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  97948. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  97949. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  97950. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  97951. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  97952. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  97953. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  97954. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  97955. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  97956. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  97957. static FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended);
  97958. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  97959. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  97960. #if FLAC__HAS_OGG
  97961. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  97962. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  97963. #endif
  97964. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  97965. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  97966. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  97967. #if FLAC__HAS_OGG
  97968. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  97969. #endif
  97970. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  97971. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  97972. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  97973. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  97974. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  97975. /***********************************************************************
  97976. *
  97977. * Private class data
  97978. *
  97979. ***********************************************************************/
  97980. typedef struct FLAC__StreamDecoderPrivate {
  97981. #if FLAC__HAS_OGG
  97982. FLAC__bool is_ogg;
  97983. #endif
  97984. FLAC__StreamDecoderReadCallback read_callback;
  97985. FLAC__StreamDecoderSeekCallback seek_callback;
  97986. FLAC__StreamDecoderTellCallback tell_callback;
  97987. FLAC__StreamDecoderLengthCallback length_callback;
  97988. FLAC__StreamDecoderEofCallback eof_callback;
  97989. FLAC__StreamDecoderWriteCallback write_callback;
  97990. FLAC__StreamDecoderMetadataCallback metadata_callback;
  97991. FLAC__StreamDecoderErrorCallback error_callback;
  97992. /* generic 32-bit datapath: */
  97993. void (*local_lpc_restore_signal)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  97994. /* generic 64-bit datapath: */
  97995. void (*local_lpc_restore_signal_64bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  97996. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  97997. void (*local_lpc_restore_signal_16bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  97998. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit), AND order <= 8: */
  97999. void (*local_lpc_restore_signal_16bit_order8)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  98000. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98001. void *client_data;
  98002. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98003. FLAC__BitReader *input;
  98004. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98005. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98006. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98007. unsigned output_capacity, output_channels;
  98008. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98009. FLAC__uint64 samples_decoded;
  98010. FLAC__bool has_stream_info, has_seek_table;
  98011. FLAC__StreamMetadata stream_info;
  98012. FLAC__StreamMetadata seek_table;
  98013. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98014. FLAC__byte *metadata_filter_ids;
  98015. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98016. FLAC__Frame frame;
  98017. FLAC__bool cached; /* true if there is a byte in lookahead */
  98018. FLAC__CPUInfo cpuinfo;
  98019. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98020. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98021. /* unaligned (original) pointers to allocated data */
  98022. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98023. FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
  98024. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98025. FLAC__bool is_seeking;
  98026. FLAC__MD5Context md5context;
  98027. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98028. /* (the rest of these are only used for seeking) */
  98029. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98030. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98031. FLAC__uint64 target_sample;
  98032. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98033. #if FLAC__HAS_OGG
  98034. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98035. #endif
  98036. } FLAC__StreamDecoderPrivate;
  98037. /***********************************************************************
  98038. *
  98039. * Public static class data
  98040. *
  98041. ***********************************************************************/
  98042. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98043. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98044. "FLAC__STREAM_DECODER_READ_METADATA",
  98045. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98046. "FLAC__STREAM_DECODER_READ_FRAME",
  98047. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98048. "FLAC__STREAM_DECODER_OGG_ERROR",
  98049. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98050. "FLAC__STREAM_DECODER_ABORTED",
  98051. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98052. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98053. };
  98054. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98055. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98056. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98057. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98058. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98059. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98060. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98061. };
  98062. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98063. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98064. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98065. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98066. };
  98067. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98068. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98069. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98070. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98071. };
  98072. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98073. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98074. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98075. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98076. };
  98077. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98078. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98079. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98080. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98081. };
  98082. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98083. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98084. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98085. };
  98086. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98087. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98088. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98089. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98090. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98091. };
  98092. /***********************************************************************
  98093. *
  98094. * Class constructor/destructor
  98095. *
  98096. ***********************************************************************/
  98097. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98098. {
  98099. FLAC__StreamDecoder *decoder;
  98100. unsigned i;
  98101. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98102. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98103. if(decoder == 0) {
  98104. return 0;
  98105. }
  98106. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  98107. if(decoder->protected_ == 0) {
  98108. free(decoder);
  98109. return 0;
  98110. }
  98111. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  98112. if(decoder->private_ == 0) {
  98113. free(decoder->protected_);
  98114. free(decoder);
  98115. return 0;
  98116. }
  98117. decoder->private_->input = FLAC__bitreader_new();
  98118. if(decoder->private_->input == 0) {
  98119. free(decoder->private_);
  98120. free(decoder->protected_);
  98121. free(decoder);
  98122. return 0;
  98123. }
  98124. decoder->private_->metadata_filter_ids_capacity = 16;
  98125. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  98126. FLAC__bitreader_delete(decoder->private_->input);
  98127. free(decoder->private_);
  98128. free(decoder->protected_);
  98129. free(decoder);
  98130. return 0;
  98131. }
  98132. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98133. decoder->private_->output[i] = 0;
  98134. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98135. }
  98136. decoder->private_->output_capacity = 0;
  98137. decoder->private_->output_channels = 0;
  98138. decoder->private_->has_seek_table = false;
  98139. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98140. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  98141. decoder->private_->file = 0;
  98142. set_defaults_dec(decoder);
  98143. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98144. return decoder;
  98145. }
  98146. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  98147. {
  98148. unsigned i;
  98149. FLAC__ASSERT(0 != decoder);
  98150. FLAC__ASSERT(0 != decoder->protected_);
  98151. FLAC__ASSERT(0 != decoder->private_);
  98152. FLAC__ASSERT(0 != decoder->private_->input);
  98153. (void)FLAC__stream_decoder_finish(decoder);
  98154. if(0 != decoder->private_->metadata_filter_ids)
  98155. free(decoder->private_->metadata_filter_ids);
  98156. FLAC__bitreader_delete(decoder->private_->input);
  98157. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98158. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  98159. free(decoder->private_);
  98160. free(decoder->protected_);
  98161. free(decoder);
  98162. }
  98163. /***********************************************************************
  98164. *
  98165. * Public class methods
  98166. *
  98167. ***********************************************************************/
  98168. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  98169. FLAC__StreamDecoder *decoder,
  98170. FLAC__StreamDecoderReadCallback read_callback,
  98171. FLAC__StreamDecoderSeekCallback seek_callback,
  98172. FLAC__StreamDecoderTellCallback tell_callback,
  98173. FLAC__StreamDecoderLengthCallback length_callback,
  98174. FLAC__StreamDecoderEofCallback eof_callback,
  98175. FLAC__StreamDecoderWriteCallback write_callback,
  98176. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98177. FLAC__StreamDecoderErrorCallback error_callback,
  98178. void *client_data,
  98179. FLAC__bool is_ogg
  98180. )
  98181. {
  98182. FLAC__ASSERT(0 != decoder);
  98183. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98184. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  98185. #if !FLAC__HAS_OGG
  98186. if(is_ogg)
  98187. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98188. #endif
  98189. if(
  98190. 0 == read_callback ||
  98191. 0 == write_callback ||
  98192. 0 == error_callback ||
  98193. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  98194. )
  98195. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  98196. #if FLAC__HAS_OGG
  98197. decoder->private_->is_ogg = is_ogg;
  98198. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  98199. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  98200. #endif
  98201. /*
  98202. * get the CPU info and set the function pointers
  98203. */
  98204. FLAC__cpu_info(&decoder->private_->cpuinfo);
  98205. /* first default to the non-asm routines */
  98206. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  98207. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  98208. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  98209. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  98210. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  98211. /* now override with asm where appropriate */
  98212. #ifndef FLAC__NO_ASM
  98213. if(decoder->private_->cpuinfo.use_asm) {
  98214. #ifdef FLAC__CPU_IA32
  98215. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98216. #ifdef FLAC__HAS_NASM
  98217. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  98218. if(decoder->private_->cpuinfo.data.ia32.bswap)
  98219. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  98220. #endif
  98221. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  98222. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98223. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98224. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98225. }
  98226. else {
  98227. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98228. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  98229. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  98230. }
  98231. #endif
  98232. #elif defined FLAC__CPU_PPC
  98233. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  98234. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  98235. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  98236. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  98237. }
  98238. #endif
  98239. }
  98240. #endif
  98241. /* from here on, errors are fatal */
  98242. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  98243. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98244. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98245. }
  98246. decoder->private_->read_callback = read_callback;
  98247. decoder->private_->seek_callback = seek_callback;
  98248. decoder->private_->tell_callback = tell_callback;
  98249. decoder->private_->length_callback = length_callback;
  98250. decoder->private_->eof_callback = eof_callback;
  98251. decoder->private_->write_callback = write_callback;
  98252. decoder->private_->metadata_callback = metadata_callback;
  98253. decoder->private_->error_callback = error_callback;
  98254. decoder->private_->client_data = client_data;
  98255. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  98256. decoder->private_->samples_decoded = 0;
  98257. decoder->private_->has_stream_info = false;
  98258. decoder->private_->cached = false;
  98259. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  98260. decoder->private_->is_seeking = false;
  98261. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  98262. if(!FLAC__stream_decoder_reset(decoder)) {
  98263. /* above call sets the state for us */
  98264. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98265. }
  98266. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  98267. }
  98268. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  98269. FLAC__StreamDecoder *decoder,
  98270. FLAC__StreamDecoderReadCallback read_callback,
  98271. FLAC__StreamDecoderSeekCallback seek_callback,
  98272. FLAC__StreamDecoderTellCallback tell_callback,
  98273. FLAC__StreamDecoderLengthCallback length_callback,
  98274. FLAC__StreamDecoderEofCallback eof_callback,
  98275. FLAC__StreamDecoderWriteCallback write_callback,
  98276. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98277. FLAC__StreamDecoderErrorCallback error_callback,
  98278. void *client_data
  98279. )
  98280. {
  98281. return init_stream_internal_dec(
  98282. decoder,
  98283. read_callback,
  98284. seek_callback,
  98285. tell_callback,
  98286. length_callback,
  98287. eof_callback,
  98288. write_callback,
  98289. metadata_callback,
  98290. error_callback,
  98291. client_data,
  98292. /*is_ogg=*/false
  98293. );
  98294. }
  98295. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  98296. FLAC__StreamDecoder *decoder,
  98297. FLAC__StreamDecoderReadCallback read_callback,
  98298. FLAC__StreamDecoderSeekCallback seek_callback,
  98299. FLAC__StreamDecoderTellCallback tell_callback,
  98300. FLAC__StreamDecoderLengthCallback length_callback,
  98301. FLAC__StreamDecoderEofCallback eof_callback,
  98302. FLAC__StreamDecoderWriteCallback write_callback,
  98303. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98304. FLAC__StreamDecoderErrorCallback error_callback,
  98305. void *client_data
  98306. )
  98307. {
  98308. return init_stream_internal_dec(
  98309. decoder,
  98310. read_callback,
  98311. seek_callback,
  98312. tell_callback,
  98313. length_callback,
  98314. eof_callback,
  98315. write_callback,
  98316. metadata_callback,
  98317. error_callback,
  98318. client_data,
  98319. /*is_ogg=*/true
  98320. );
  98321. }
  98322. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  98323. FLAC__StreamDecoder *decoder,
  98324. FILE *file,
  98325. FLAC__StreamDecoderWriteCallback write_callback,
  98326. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98327. FLAC__StreamDecoderErrorCallback error_callback,
  98328. void *client_data,
  98329. FLAC__bool is_ogg
  98330. )
  98331. {
  98332. FLAC__ASSERT(0 != decoder);
  98333. FLAC__ASSERT(0 != file);
  98334. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98335. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98336. if(0 == write_callback || 0 == error_callback)
  98337. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98338. /*
  98339. * To make sure that our file does not go unclosed after an error, we
  98340. * must assign the FILE pointer before any further error can occur in
  98341. * this routine.
  98342. */
  98343. if(file == stdin)
  98344. file = get_binary_stdin_(); /* just to be safe */
  98345. decoder->private_->file = file;
  98346. return init_stream_internal_dec(
  98347. decoder,
  98348. file_read_callback_dec,
  98349. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  98350. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  98351. decoder->private_->file == stdin? 0: file_length_callback_,
  98352. file_eof_callback_,
  98353. write_callback,
  98354. metadata_callback,
  98355. error_callback,
  98356. client_data,
  98357. is_ogg
  98358. );
  98359. }
  98360. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  98361. FLAC__StreamDecoder *decoder,
  98362. FILE *file,
  98363. FLAC__StreamDecoderWriteCallback write_callback,
  98364. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98365. FLAC__StreamDecoderErrorCallback error_callback,
  98366. void *client_data
  98367. )
  98368. {
  98369. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98370. }
  98371. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  98372. FLAC__StreamDecoder *decoder,
  98373. FILE *file,
  98374. FLAC__StreamDecoderWriteCallback write_callback,
  98375. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98376. FLAC__StreamDecoderErrorCallback error_callback,
  98377. void *client_data
  98378. )
  98379. {
  98380. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98381. }
  98382. static FLAC__StreamDecoderInitStatus init_file_internal_(
  98383. FLAC__StreamDecoder *decoder,
  98384. const char *filename,
  98385. FLAC__StreamDecoderWriteCallback write_callback,
  98386. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98387. FLAC__StreamDecoderErrorCallback error_callback,
  98388. void *client_data,
  98389. FLAC__bool is_ogg
  98390. )
  98391. {
  98392. FILE *file;
  98393. FLAC__ASSERT(0 != decoder);
  98394. /*
  98395. * To make sure that our file does not go unclosed after an error, we
  98396. * have to do the same entrance checks here that are later performed
  98397. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  98398. */
  98399. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98400. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98401. if(0 == write_callback || 0 == error_callback)
  98402. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98403. file = filename? fopen(filename, "rb") : stdin;
  98404. if(0 == file)
  98405. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  98406. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  98407. }
  98408. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  98409. FLAC__StreamDecoder *decoder,
  98410. const char *filename,
  98411. FLAC__StreamDecoderWriteCallback write_callback,
  98412. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98413. FLAC__StreamDecoderErrorCallback error_callback,
  98414. void *client_data
  98415. )
  98416. {
  98417. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98418. }
  98419. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  98420. FLAC__StreamDecoder *decoder,
  98421. const char *filename,
  98422. FLAC__StreamDecoderWriteCallback write_callback,
  98423. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98424. FLAC__StreamDecoderErrorCallback error_callback,
  98425. void *client_data
  98426. )
  98427. {
  98428. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98429. }
  98430. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  98431. {
  98432. FLAC__bool md5_failed = false;
  98433. unsigned i;
  98434. FLAC__ASSERT(0 != decoder);
  98435. FLAC__ASSERT(0 != decoder->private_);
  98436. FLAC__ASSERT(0 != decoder->protected_);
  98437. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  98438. return true;
  98439. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  98440. * always call FLAC__MD5Final()
  98441. */
  98442. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  98443. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  98444. free(decoder->private_->seek_table.data.seek_table.points);
  98445. decoder->private_->seek_table.data.seek_table.points = 0;
  98446. decoder->private_->has_seek_table = false;
  98447. }
  98448. FLAC__bitreader_free(decoder->private_->input);
  98449. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98450. /* WATCHOUT:
  98451. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  98452. * output arrays have a buffer of up to 3 zeroes in front
  98453. * (at negative indices) for alignment purposes; we use 4
  98454. * to keep the data well-aligned.
  98455. */
  98456. if(0 != decoder->private_->output[i]) {
  98457. free(decoder->private_->output[i]-4);
  98458. decoder->private_->output[i] = 0;
  98459. }
  98460. if(0 != decoder->private_->residual_unaligned[i]) {
  98461. free(decoder->private_->residual_unaligned[i]);
  98462. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98463. }
  98464. }
  98465. decoder->private_->output_capacity = 0;
  98466. decoder->private_->output_channels = 0;
  98467. #if FLAC__HAS_OGG
  98468. if(decoder->private_->is_ogg)
  98469. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  98470. #endif
  98471. if(0 != decoder->private_->file) {
  98472. if(decoder->private_->file != stdin)
  98473. fclose(decoder->private_->file);
  98474. decoder->private_->file = 0;
  98475. }
  98476. if(decoder->private_->do_md5_checking) {
  98477. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  98478. md5_failed = true;
  98479. }
  98480. decoder->private_->is_seeking = false;
  98481. set_defaults_dec(decoder);
  98482. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98483. return !md5_failed;
  98484. }
  98485. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  98486. {
  98487. FLAC__ASSERT(0 != decoder);
  98488. FLAC__ASSERT(0 != decoder->private_);
  98489. FLAC__ASSERT(0 != decoder->protected_);
  98490. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98491. return false;
  98492. #if FLAC__HAS_OGG
  98493. /* can't check decoder->private_->is_ogg since that's not set until init time */
  98494. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  98495. return true;
  98496. #else
  98497. (void)value;
  98498. return false;
  98499. #endif
  98500. }
  98501. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  98502. {
  98503. FLAC__ASSERT(0 != decoder);
  98504. FLAC__ASSERT(0 != decoder->protected_);
  98505. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98506. return false;
  98507. decoder->protected_->md5_checking = value;
  98508. return true;
  98509. }
  98510. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  98511. {
  98512. FLAC__ASSERT(0 != decoder);
  98513. FLAC__ASSERT(0 != decoder->private_);
  98514. FLAC__ASSERT(0 != decoder->protected_);
  98515. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  98516. /* double protection */
  98517. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  98518. return false;
  98519. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98520. return false;
  98521. decoder->private_->metadata_filter[type] = true;
  98522. if(type == FLAC__METADATA_TYPE_APPLICATION)
  98523. decoder->private_->metadata_filter_ids_count = 0;
  98524. return true;
  98525. }
  98526. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  98527. {
  98528. FLAC__ASSERT(0 != decoder);
  98529. FLAC__ASSERT(0 != decoder->private_);
  98530. FLAC__ASSERT(0 != decoder->protected_);
  98531. FLAC__ASSERT(0 != id);
  98532. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98533. return false;
  98534. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  98535. return true;
  98536. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  98537. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  98538. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
  98539. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98540. return false;
  98541. }
  98542. decoder->private_->metadata_filter_ids_capacity *= 2;
  98543. }
  98544. memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
  98545. decoder->private_->metadata_filter_ids_count++;
  98546. return true;
  98547. }
  98548. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  98549. {
  98550. unsigned i;
  98551. FLAC__ASSERT(0 != decoder);
  98552. FLAC__ASSERT(0 != decoder->private_);
  98553. FLAC__ASSERT(0 != decoder->protected_);
  98554. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98555. return false;
  98556. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  98557. decoder->private_->metadata_filter[i] = true;
  98558. decoder->private_->metadata_filter_ids_count = 0;
  98559. return true;
  98560. }
  98561. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  98562. {
  98563. FLAC__ASSERT(0 != decoder);
  98564. FLAC__ASSERT(0 != decoder->private_);
  98565. FLAC__ASSERT(0 != decoder->protected_);
  98566. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  98567. /* double protection */
  98568. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  98569. return false;
  98570. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98571. return false;
  98572. decoder->private_->metadata_filter[type] = false;
  98573. if(type == FLAC__METADATA_TYPE_APPLICATION)
  98574. decoder->private_->metadata_filter_ids_count = 0;
  98575. return true;
  98576. }
  98577. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  98578. {
  98579. FLAC__ASSERT(0 != decoder);
  98580. FLAC__ASSERT(0 != decoder->private_);
  98581. FLAC__ASSERT(0 != decoder->protected_);
  98582. FLAC__ASSERT(0 != id);
  98583. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98584. return false;
  98585. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  98586. return true;
  98587. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  98588. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  98589. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
  98590. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98591. return false;
  98592. }
  98593. decoder->private_->metadata_filter_ids_capacity *= 2;
  98594. }
  98595. memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
  98596. decoder->private_->metadata_filter_ids_count++;
  98597. return true;
  98598. }
  98599. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  98600. {
  98601. FLAC__ASSERT(0 != decoder);
  98602. FLAC__ASSERT(0 != decoder->private_);
  98603. FLAC__ASSERT(0 != decoder->protected_);
  98604. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98605. return false;
  98606. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  98607. decoder->private_->metadata_filter_ids_count = 0;
  98608. return true;
  98609. }
  98610. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  98611. {
  98612. FLAC__ASSERT(0 != decoder);
  98613. FLAC__ASSERT(0 != decoder->protected_);
  98614. return decoder->protected_->state;
  98615. }
  98616. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  98617. {
  98618. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  98619. }
  98620. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  98621. {
  98622. FLAC__ASSERT(0 != decoder);
  98623. FLAC__ASSERT(0 != decoder->protected_);
  98624. return decoder->protected_->md5_checking;
  98625. }
  98626. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  98627. {
  98628. FLAC__ASSERT(0 != decoder);
  98629. FLAC__ASSERT(0 != decoder->protected_);
  98630. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  98631. }
  98632. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  98633. {
  98634. FLAC__ASSERT(0 != decoder);
  98635. FLAC__ASSERT(0 != decoder->protected_);
  98636. return decoder->protected_->channels;
  98637. }
  98638. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  98639. {
  98640. FLAC__ASSERT(0 != decoder);
  98641. FLAC__ASSERT(0 != decoder->protected_);
  98642. return decoder->protected_->channel_assignment;
  98643. }
  98644. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  98645. {
  98646. FLAC__ASSERT(0 != decoder);
  98647. FLAC__ASSERT(0 != decoder->protected_);
  98648. return decoder->protected_->bits_per_sample;
  98649. }
  98650. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  98651. {
  98652. FLAC__ASSERT(0 != decoder);
  98653. FLAC__ASSERT(0 != decoder->protected_);
  98654. return decoder->protected_->sample_rate;
  98655. }
  98656. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  98657. {
  98658. FLAC__ASSERT(0 != decoder);
  98659. FLAC__ASSERT(0 != decoder->protected_);
  98660. return decoder->protected_->blocksize;
  98661. }
  98662. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  98663. {
  98664. FLAC__ASSERT(0 != decoder);
  98665. FLAC__ASSERT(0 != decoder->private_);
  98666. FLAC__ASSERT(0 != position);
  98667. #if FLAC__HAS_OGG
  98668. if(decoder->private_->is_ogg)
  98669. return false;
  98670. #endif
  98671. if(0 == decoder->private_->tell_callback)
  98672. return false;
  98673. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  98674. return false;
  98675. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  98676. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  98677. return false;
  98678. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  98679. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  98680. return true;
  98681. }
  98682. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  98683. {
  98684. FLAC__ASSERT(0 != decoder);
  98685. FLAC__ASSERT(0 != decoder->private_);
  98686. FLAC__ASSERT(0 != decoder->protected_);
  98687. decoder->private_->samples_decoded = 0;
  98688. decoder->private_->do_md5_checking = false;
  98689. #if FLAC__HAS_OGG
  98690. if(decoder->private_->is_ogg)
  98691. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  98692. #endif
  98693. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  98694. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98695. return false;
  98696. }
  98697. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98698. return true;
  98699. }
  98700. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  98701. {
  98702. FLAC__ASSERT(0 != decoder);
  98703. FLAC__ASSERT(0 != decoder->private_);
  98704. FLAC__ASSERT(0 != decoder->protected_);
  98705. if(!FLAC__stream_decoder_flush(decoder)) {
  98706. /* above call sets the state for us */
  98707. return false;
  98708. }
  98709. #if FLAC__HAS_OGG
  98710. /*@@@ could go in !internal_reset_hack block below */
  98711. if(decoder->private_->is_ogg)
  98712. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  98713. #endif
  98714. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  98715. * (internal_reset_hack) don't try to rewind since we are already at
  98716. * the beginning of the stream and don't want to fail if the input is
  98717. * not seekable.
  98718. */
  98719. if(!decoder->private_->internal_reset_hack) {
  98720. if(decoder->private_->file == stdin)
  98721. return false; /* can't rewind stdin, reset fails */
  98722. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  98723. return false; /* seekable and seek fails, reset fails */
  98724. }
  98725. else
  98726. decoder->private_->internal_reset_hack = false;
  98727. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  98728. decoder->private_->has_stream_info = false;
  98729. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  98730. free(decoder->private_->seek_table.data.seek_table.points);
  98731. decoder->private_->seek_table.data.seek_table.points = 0;
  98732. decoder->private_->has_seek_table = false;
  98733. }
  98734. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  98735. /*
  98736. * This goes in reset() and not flush() because according to the spec, a
  98737. * fixed-blocksize stream must stay that way through the whole stream.
  98738. */
  98739. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  98740. /* We initialize the FLAC__MD5Context even though we may never use it. This
  98741. * is because md5 checking may be turned on to start and then turned off if
  98742. * a seek occurs. So we init the context here and finalize it in
  98743. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  98744. * properly.
  98745. */
  98746. FLAC__MD5Init(&decoder->private_->md5context);
  98747. decoder->private_->first_frame_offset = 0;
  98748. decoder->private_->unparseable_frame_count = 0;
  98749. return true;
  98750. }
  98751. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  98752. {
  98753. FLAC__bool got_a_frame;
  98754. FLAC__ASSERT(0 != decoder);
  98755. FLAC__ASSERT(0 != decoder->protected_);
  98756. while(1) {
  98757. switch(decoder->protected_->state) {
  98758. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  98759. if(!find_metadata_(decoder))
  98760. return false; /* above function sets the status for us */
  98761. break;
  98762. case FLAC__STREAM_DECODER_READ_METADATA:
  98763. if(!read_metadata_(decoder))
  98764. return false; /* above function sets the status for us */
  98765. else
  98766. return true;
  98767. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  98768. if(!frame_sync_(decoder))
  98769. return true; /* above function sets the status for us */
  98770. break;
  98771. case FLAC__STREAM_DECODER_READ_FRAME:
  98772. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  98773. return false; /* above function sets the status for us */
  98774. if(got_a_frame)
  98775. return true; /* above function sets the status for us */
  98776. break;
  98777. case FLAC__STREAM_DECODER_END_OF_STREAM:
  98778. case FLAC__STREAM_DECODER_ABORTED:
  98779. return true;
  98780. default:
  98781. FLAC__ASSERT(0);
  98782. return false;
  98783. }
  98784. }
  98785. }
  98786. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  98787. {
  98788. FLAC__ASSERT(0 != decoder);
  98789. FLAC__ASSERT(0 != decoder->protected_);
  98790. while(1) {
  98791. switch(decoder->protected_->state) {
  98792. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  98793. if(!find_metadata_(decoder))
  98794. return false; /* above function sets the status for us */
  98795. break;
  98796. case FLAC__STREAM_DECODER_READ_METADATA:
  98797. if(!read_metadata_(decoder))
  98798. return false; /* above function sets the status for us */
  98799. break;
  98800. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  98801. case FLAC__STREAM_DECODER_READ_FRAME:
  98802. case FLAC__STREAM_DECODER_END_OF_STREAM:
  98803. case FLAC__STREAM_DECODER_ABORTED:
  98804. return true;
  98805. default:
  98806. FLAC__ASSERT(0);
  98807. return false;
  98808. }
  98809. }
  98810. }
  98811. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  98812. {
  98813. FLAC__bool dummy;
  98814. FLAC__ASSERT(0 != decoder);
  98815. FLAC__ASSERT(0 != decoder->protected_);
  98816. while(1) {
  98817. switch(decoder->protected_->state) {
  98818. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  98819. if(!find_metadata_(decoder))
  98820. return false; /* above function sets the status for us */
  98821. break;
  98822. case FLAC__STREAM_DECODER_READ_METADATA:
  98823. if(!read_metadata_(decoder))
  98824. return false; /* above function sets the status for us */
  98825. break;
  98826. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  98827. if(!frame_sync_(decoder))
  98828. return true; /* above function sets the status for us */
  98829. break;
  98830. case FLAC__STREAM_DECODER_READ_FRAME:
  98831. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  98832. return false; /* above function sets the status for us */
  98833. break;
  98834. case FLAC__STREAM_DECODER_END_OF_STREAM:
  98835. case FLAC__STREAM_DECODER_ABORTED:
  98836. return true;
  98837. default:
  98838. FLAC__ASSERT(0);
  98839. return false;
  98840. }
  98841. }
  98842. }
  98843. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  98844. {
  98845. FLAC__bool got_a_frame;
  98846. FLAC__ASSERT(0 != decoder);
  98847. FLAC__ASSERT(0 != decoder->protected_);
  98848. while(1) {
  98849. switch(decoder->protected_->state) {
  98850. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  98851. case FLAC__STREAM_DECODER_READ_METADATA:
  98852. return false; /* above function sets the status for us */
  98853. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  98854. if(!frame_sync_(decoder))
  98855. return true; /* above function sets the status for us */
  98856. break;
  98857. case FLAC__STREAM_DECODER_READ_FRAME:
  98858. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  98859. return false; /* above function sets the status for us */
  98860. if(got_a_frame)
  98861. return true; /* above function sets the status for us */
  98862. break;
  98863. case FLAC__STREAM_DECODER_END_OF_STREAM:
  98864. case FLAC__STREAM_DECODER_ABORTED:
  98865. return true;
  98866. default:
  98867. FLAC__ASSERT(0);
  98868. return false;
  98869. }
  98870. }
  98871. }
  98872. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  98873. {
  98874. FLAC__uint64 length;
  98875. FLAC__ASSERT(0 != decoder);
  98876. if(
  98877. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  98878. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  98879. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  98880. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  98881. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  98882. )
  98883. return false;
  98884. if(0 == decoder->private_->seek_callback)
  98885. return false;
  98886. FLAC__ASSERT(decoder->private_->seek_callback);
  98887. FLAC__ASSERT(decoder->private_->tell_callback);
  98888. FLAC__ASSERT(decoder->private_->length_callback);
  98889. FLAC__ASSERT(decoder->private_->eof_callback);
  98890. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  98891. return false;
  98892. decoder->private_->is_seeking = true;
  98893. /* turn off md5 checking if a seek is attempted */
  98894. decoder->private_->do_md5_checking = false;
  98895. /* get the file length (currently our algorithm needs to know the length so it's also an error to get FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED) */
  98896. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  98897. decoder->private_->is_seeking = false;
  98898. return false;
  98899. }
  98900. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  98901. if(
  98902. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  98903. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  98904. ) {
  98905. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  98906. /* above call sets the state for us */
  98907. decoder->private_->is_seeking = false;
  98908. return false;
  98909. }
  98910. /* check this again in case we didn't know total_samples the first time */
  98911. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  98912. decoder->private_->is_seeking = false;
  98913. return false;
  98914. }
  98915. }
  98916. {
  98917. const FLAC__bool ok =
  98918. #if FLAC__HAS_OGG
  98919. decoder->private_->is_ogg?
  98920. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  98921. #endif
  98922. seek_to_absolute_sample_(decoder, length, sample)
  98923. ;
  98924. decoder->private_->is_seeking = false;
  98925. return ok;
  98926. }
  98927. }
  98928. /***********************************************************************
  98929. *
  98930. * Protected class methods
  98931. *
  98932. ***********************************************************************/
  98933. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  98934. {
  98935. FLAC__ASSERT(0 != decoder);
  98936. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  98937. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  98938. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  98939. }
  98940. /***********************************************************************
  98941. *
  98942. * Private class methods
  98943. *
  98944. ***********************************************************************/
  98945. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  98946. {
  98947. #if FLAC__HAS_OGG
  98948. decoder->private_->is_ogg = false;
  98949. #endif
  98950. decoder->private_->read_callback = 0;
  98951. decoder->private_->seek_callback = 0;
  98952. decoder->private_->tell_callback = 0;
  98953. decoder->private_->length_callback = 0;
  98954. decoder->private_->eof_callback = 0;
  98955. decoder->private_->write_callback = 0;
  98956. decoder->private_->metadata_callback = 0;
  98957. decoder->private_->error_callback = 0;
  98958. decoder->private_->client_data = 0;
  98959. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  98960. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  98961. decoder->private_->metadata_filter_ids_count = 0;
  98962. decoder->protected_->md5_checking = false;
  98963. #if FLAC__HAS_OGG
  98964. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  98965. #endif
  98966. }
  98967. /*
  98968. * This will forcibly set stdin to binary mode (for OSes that require it)
  98969. */
  98970. FILE *get_binary_stdin_(void)
  98971. {
  98972. /* if something breaks here it is probably due to the presence or
  98973. * absence of an underscore before the identifiers 'setmode',
  98974. * 'fileno', and/or 'O_BINARY'; check your system header files.
  98975. */
  98976. #if defined _MSC_VER || defined __MINGW32__
  98977. _setmode(_fileno(stdin), _O_BINARY);
  98978. #elif defined __CYGWIN__
  98979. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  98980. setmode(_fileno(stdin), _O_BINARY);
  98981. #elif defined __EMX__
  98982. setmode(fileno(stdin), O_BINARY);
  98983. #endif
  98984. return stdin;
  98985. }
  98986. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  98987. {
  98988. unsigned i;
  98989. FLAC__int32 *tmp;
  98990. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  98991. return true;
  98992. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  98993. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98994. if(0 != decoder->private_->output[i]) {
  98995. free(decoder->private_->output[i]-4);
  98996. decoder->private_->output[i] = 0;
  98997. }
  98998. if(0 != decoder->private_->residual_unaligned[i]) {
  98999. free(decoder->private_->residual_unaligned[i]);
  99000. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99001. }
  99002. }
  99003. for(i = 0; i < channels; i++) {
  99004. /* WATCHOUT:
  99005. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99006. * output arrays have a buffer of up to 3 zeroes in front
  99007. * (at negative indices) for alignment purposes; we use 4
  99008. * to keep the data well-aligned.
  99009. */
  99010. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99011. if(tmp == 0) {
  99012. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99013. return false;
  99014. }
  99015. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99016. decoder->private_->output[i] = tmp + 4;
  99017. /* WATCHOUT:
  99018. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99019. */
  99020. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99021. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99022. return false;
  99023. }
  99024. }
  99025. decoder->private_->output_capacity = size;
  99026. decoder->private_->output_channels = channels;
  99027. return true;
  99028. }
  99029. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99030. {
  99031. size_t i;
  99032. FLAC__ASSERT(0 != decoder);
  99033. FLAC__ASSERT(0 != decoder->private_);
  99034. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99035. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99036. return true;
  99037. return false;
  99038. }
  99039. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99040. {
  99041. FLAC__uint32 x;
  99042. unsigned i, id_;
  99043. FLAC__bool first = true;
  99044. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99045. for(i = id_ = 0; i < 4; ) {
  99046. if(decoder->private_->cached) {
  99047. x = (FLAC__uint32)decoder->private_->lookahead;
  99048. decoder->private_->cached = false;
  99049. }
  99050. else {
  99051. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99052. return false; /* read_callback_ sets the state for us */
  99053. }
  99054. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99055. first = true;
  99056. i++;
  99057. id_ = 0;
  99058. continue;
  99059. }
  99060. if(x == ID3V2_TAG_[id_]) {
  99061. id_++;
  99062. i = 0;
  99063. if(id_ == 3) {
  99064. if(!skip_id3v2_tag_(decoder))
  99065. return false; /* skip_id3v2_tag_ sets the state for us */
  99066. }
  99067. continue;
  99068. }
  99069. id_ = 0;
  99070. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99071. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99072. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99073. return false; /* read_callback_ sets the state for us */
  99074. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  99075. /* else we have to check if the second byte is the end of a sync code */
  99076. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99077. decoder->private_->lookahead = (FLAC__byte)x;
  99078. decoder->private_->cached = true;
  99079. }
  99080. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99081. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99082. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99083. return true;
  99084. }
  99085. }
  99086. i = 0;
  99087. if(first) {
  99088. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99089. first = false;
  99090. }
  99091. }
  99092. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99093. return true;
  99094. }
  99095. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99096. {
  99097. FLAC__bool is_last;
  99098. FLAC__uint32 i, x, type, length;
  99099. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99100. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99101. return false; /* read_callback_ sets the state for us */
  99102. is_last = x? true : false;
  99103. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  99104. return false; /* read_callback_ sets the state for us */
  99105. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  99106. return false; /* read_callback_ sets the state for us */
  99107. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  99108. if(!read_metadata_streaminfo_(decoder, is_last, length))
  99109. return false;
  99110. decoder->private_->has_stream_info = true;
  99111. if(0 == memcmp(decoder->private_->stream_info.data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
  99112. decoder->private_->do_md5_checking = false;
  99113. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  99114. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  99115. }
  99116. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99117. if(!read_metadata_seektable_(decoder, is_last, length))
  99118. return false;
  99119. decoder->private_->has_seek_table = true;
  99120. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  99121. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  99122. }
  99123. else {
  99124. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  99125. unsigned real_length = length;
  99126. FLAC__StreamMetadata block;
  99127. block.is_last = is_last;
  99128. block.type = (FLAC__MetadataType)type;
  99129. block.length = length;
  99130. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  99131. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  99132. return false; /* read_callback_ sets the state for us */
  99133. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  99134. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  99135. return false;
  99136. }
  99137. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  99138. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  99139. skip_it = !skip_it;
  99140. }
  99141. if(skip_it) {
  99142. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99143. return false; /* read_callback_ sets the state for us */
  99144. }
  99145. else {
  99146. switch(type) {
  99147. case FLAC__METADATA_TYPE_PADDING:
  99148. /* skip the padding bytes */
  99149. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99150. return false; /* read_callback_ sets the state for us */
  99151. break;
  99152. case FLAC__METADATA_TYPE_APPLICATION:
  99153. /* remember, we read the ID already */
  99154. if(real_length > 0) {
  99155. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  99156. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99157. return false;
  99158. }
  99159. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  99160. return false; /* read_callback_ sets the state for us */
  99161. }
  99162. else
  99163. block.data.application.data = 0;
  99164. break;
  99165. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99166. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  99167. return false;
  99168. break;
  99169. case FLAC__METADATA_TYPE_CUESHEET:
  99170. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  99171. return false;
  99172. break;
  99173. case FLAC__METADATA_TYPE_PICTURE:
  99174. if(!read_metadata_picture_(decoder, &block.data.picture))
  99175. return false;
  99176. break;
  99177. case FLAC__METADATA_TYPE_STREAMINFO:
  99178. case FLAC__METADATA_TYPE_SEEKTABLE:
  99179. FLAC__ASSERT(0);
  99180. break;
  99181. default:
  99182. if(real_length > 0) {
  99183. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  99184. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99185. return false;
  99186. }
  99187. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  99188. return false; /* read_callback_ sets the state for us */
  99189. }
  99190. else
  99191. block.data.unknown.data = 0;
  99192. break;
  99193. }
  99194. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  99195. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  99196. /* now we have to free any malloc()ed data in the block */
  99197. switch(type) {
  99198. case FLAC__METADATA_TYPE_PADDING:
  99199. break;
  99200. case FLAC__METADATA_TYPE_APPLICATION:
  99201. if(0 != block.data.application.data)
  99202. free(block.data.application.data);
  99203. break;
  99204. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99205. if(0 != block.data.vorbis_comment.vendor_string.entry)
  99206. free(block.data.vorbis_comment.vendor_string.entry);
  99207. if(block.data.vorbis_comment.num_comments > 0)
  99208. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  99209. if(0 != block.data.vorbis_comment.comments[i].entry)
  99210. free(block.data.vorbis_comment.comments[i].entry);
  99211. if(0 != block.data.vorbis_comment.comments)
  99212. free(block.data.vorbis_comment.comments);
  99213. break;
  99214. case FLAC__METADATA_TYPE_CUESHEET:
  99215. if(block.data.cue_sheet.num_tracks > 0)
  99216. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  99217. if(0 != block.data.cue_sheet.tracks[i].indices)
  99218. free(block.data.cue_sheet.tracks[i].indices);
  99219. if(0 != block.data.cue_sheet.tracks)
  99220. free(block.data.cue_sheet.tracks);
  99221. break;
  99222. case FLAC__METADATA_TYPE_PICTURE:
  99223. if(0 != block.data.picture.mime_type)
  99224. free(block.data.picture.mime_type);
  99225. if(0 != block.data.picture.description)
  99226. free(block.data.picture.description);
  99227. if(0 != block.data.picture.data)
  99228. free(block.data.picture.data);
  99229. break;
  99230. case FLAC__METADATA_TYPE_STREAMINFO:
  99231. case FLAC__METADATA_TYPE_SEEKTABLE:
  99232. FLAC__ASSERT(0);
  99233. default:
  99234. if(0 != block.data.unknown.data)
  99235. free(block.data.unknown.data);
  99236. break;
  99237. }
  99238. }
  99239. }
  99240. if(is_last) {
  99241. /* if this fails, it's OK, it's just a hint for the seek routine */
  99242. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  99243. decoder->private_->first_frame_offset = 0;
  99244. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99245. }
  99246. return true;
  99247. }
  99248. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99249. {
  99250. FLAC__uint32 x;
  99251. unsigned bits, used_bits = 0;
  99252. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99253. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  99254. decoder->private_->stream_info.is_last = is_last;
  99255. decoder->private_->stream_info.length = length;
  99256. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  99257. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  99258. return false; /* read_callback_ sets the state for us */
  99259. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  99260. used_bits += bits;
  99261. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  99262. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  99263. return false; /* read_callback_ sets the state for us */
  99264. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  99265. used_bits += bits;
  99266. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  99267. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  99268. return false; /* read_callback_ sets the state for us */
  99269. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  99270. used_bits += bits;
  99271. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  99272. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  99273. return false; /* read_callback_ sets the state for us */
  99274. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  99275. used_bits += bits;
  99276. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  99277. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  99278. return false; /* read_callback_ sets the state for us */
  99279. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  99280. used_bits += bits;
  99281. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  99282. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  99283. return false; /* read_callback_ sets the state for us */
  99284. decoder->private_->stream_info.data.stream_info.channels = x+1;
  99285. used_bits += bits;
  99286. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  99287. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  99288. return false; /* read_callback_ sets the state for us */
  99289. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  99290. used_bits += bits;
  99291. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  99292. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  99293. return false; /* read_callback_ sets the state for us */
  99294. used_bits += bits;
  99295. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  99296. return false; /* read_callback_ sets the state for us */
  99297. used_bits += 16*8;
  99298. /* skip the rest of the block */
  99299. FLAC__ASSERT(used_bits % 8 == 0);
  99300. length -= (used_bits / 8);
  99301. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99302. return false; /* read_callback_ sets the state for us */
  99303. return true;
  99304. }
  99305. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99306. {
  99307. FLAC__uint32 i, x;
  99308. FLAC__uint64 xx;
  99309. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99310. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  99311. decoder->private_->seek_table.is_last = is_last;
  99312. decoder->private_->seek_table.length = length;
  99313. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  99314. /* use realloc since we may pass through here several times (e.g. after seeking) */
  99315. if(0 == (decoder->private_->seek_table.data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)safe_realloc_mul_2op_(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint)))) {
  99316. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99317. return false;
  99318. }
  99319. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  99320. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  99321. return false; /* read_callback_ sets the state for us */
  99322. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  99323. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  99324. return false; /* read_callback_ sets the state for us */
  99325. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  99326. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  99327. return false; /* read_callback_ sets the state for us */
  99328. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  99329. }
  99330. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  99331. /* if there is a partial point left, skip over it */
  99332. if(length > 0) {
  99333. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  99334. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99335. return false; /* read_callback_ sets the state for us */
  99336. }
  99337. return true;
  99338. }
  99339. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  99340. {
  99341. FLAC__uint32 i;
  99342. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99343. /* read vendor string */
  99344. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99345. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  99346. return false; /* read_callback_ sets the state for us */
  99347. if(obj->vendor_string.length > 0) {
  99348. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  99349. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99350. return false;
  99351. }
  99352. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  99353. return false; /* read_callback_ sets the state for us */
  99354. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  99355. }
  99356. else
  99357. obj->vendor_string.entry = 0;
  99358. /* read num comments */
  99359. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  99360. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  99361. return false; /* read_callback_ sets the state for us */
  99362. /* read comments */
  99363. if(obj->num_comments > 0) {
  99364. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  99365. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99366. return false;
  99367. }
  99368. for(i = 0; i < obj->num_comments; i++) {
  99369. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99370. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  99371. return false; /* read_callback_ sets the state for us */
  99372. if(obj->comments[i].length > 0) {
  99373. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  99374. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99375. return false;
  99376. }
  99377. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  99378. return false; /* read_callback_ sets the state for us */
  99379. obj->comments[i].entry[obj->comments[i].length] = '\0';
  99380. }
  99381. else
  99382. obj->comments[i].entry = 0;
  99383. }
  99384. }
  99385. else {
  99386. obj->comments = 0;
  99387. }
  99388. return true;
  99389. }
  99390. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  99391. {
  99392. FLAC__uint32 i, j, x;
  99393. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99394. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  99395. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  99396. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
  99397. return false; /* read_callback_ sets the state for us */
  99398. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  99399. return false; /* read_callback_ sets the state for us */
  99400. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  99401. return false; /* read_callback_ sets the state for us */
  99402. obj->is_cd = x? true : false;
  99403. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  99404. return false; /* read_callback_ sets the state for us */
  99405. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  99406. return false; /* read_callback_ sets the state for us */
  99407. obj->num_tracks = x;
  99408. if(obj->num_tracks > 0) {
  99409. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  99410. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99411. return false;
  99412. }
  99413. for(i = 0; i < obj->num_tracks; i++) {
  99414. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  99415. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  99416. return false; /* read_callback_ sets the state for us */
  99417. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  99418. return false; /* read_callback_ sets the state for us */
  99419. track->number = (FLAC__byte)x;
  99420. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  99421. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  99422. return false; /* read_callback_ sets the state for us */
  99423. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  99424. return false; /* read_callback_ sets the state for us */
  99425. track->type = x;
  99426. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  99427. return false; /* read_callback_ sets the state for us */
  99428. track->pre_emphasis = x;
  99429. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  99430. return false; /* read_callback_ sets the state for us */
  99431. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  99432. return false; /* read_callback_ sets the state for us */
  99433. track->num_indices = (FLAC__byte)x;
  99434. if(track->num_indices > 0) {
  99435. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  99436. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99437. return false;
  99438. }
  99439. for(j = 0; j < track->num_indices; j++) {
  99440. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  99441. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  99442. return false; /* read_callback_ sets the state for us */
  99443. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  99444. return false; /* read_callback_ sets the state for us */
  99445. index->number = (FLAC__byte)x;
  99446. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  99447. return false; /* read_callback_ sets the state for us */
  99448. }
  99449. }
  99450. }
  99451. }
  99452. return true;
  99453. }
  99454. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  99455. {
  99456. FLAC__uint32 x;
  99457. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99458. /* read type */
  99459. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  99460. return false; /* read_callback_ sets the state for us */
  99461. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  99462. /* read MIME type */
  99463. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  99464. return false; /* read_callback_ sets the state for us */
  99465. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  99466. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99467. return false;
  99468. }
  99469. if(x > 0) {
  99470. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  99471. return false; /* read_callback_ sets the state for us */
  99472. }
  99473. obj->mime_type[x] = '\0';
  99474. /* read description */
  99475. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  99476. return false; /* read_callback_ sets the state for us */
  99477. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  99478. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99479. return false;
  99480. }
  99481. if(x > 0) {
  99482. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  99483. return false; /* read_callback_ sets the state for us */
  99484. }
  99485. obj->description[x] = '\0';
  99486. /* read width */
  99487. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  99488. return false; /* read_callback_ sets the state for us */
  99489. /* read height */
  99490. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  99491. return false; /* read_callback_ sets the state for us */
  99492. /* read depth */
  99493. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  99494. return false; /* read_callback_ sets the state for us */
  99495. /* read colors */
  99496. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  99497. return false; /* read_callback_ sets the state for us */
  99498. /* read data */
  99499. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  99500. return false; /* read_callback_ sets the state for us */
  99501. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  99502. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99503. return false;
  99504. }
  99505. if(obj->data_length > 0) {
  99506. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  99507. return false; /* read_callback_ sets the state for us */
  99508. }
  99509. return true;
  99510. }
  99511. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  99512. {
  99513. FLAC__uint32 x;
  99514. unsigned i, skip;
  99515. /* skip the version and flags bytes */
  99516. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  99517. return false; /* read_callback_ sets the state for us */
  99518. /* get the size (in bytes) to skip */
  99519. skip = 0;
  99520. for(i = 0; i < 4; i++) {
  99521. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99522. return false; /* read_callback_ sets the state for us */
  99523. skip <<= 7;
  99524. skip |= (x & 0x7f);
  99525. }
  99526. /* skip the rest of the tag */
  99527. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  99528. return false; /* read_callback_ sets the state for us */
  99529. return true;
  99530. }
  99531. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  99532. {
  99533. FLAC__uint32 x;
  99534. FLAC__bool first = true;
  99535. /* If we know the total number of samples in the stream, stop if we've read that many. */
  99536. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  99537. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  99538. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99539. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  99540. return true;
  99541. }
  99542. }
  99543. /* make sure we're byte aligned */
  99544. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  99545. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  99546. return false; /* read_callback_ sets the state for us */
  99547. }
  99548. while(1) {
  99549. if(decoder->private_->cached) {
  99550. x = (FLAC__uint32)decoder->private_->lookahead;
  99551. decoder->private_->cached = false;
  99552. }
  99553. else {
  99554. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99555. return false; /* read_callback_ sets the state for us */
  99556. }
  99557. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99558. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99559. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99560. return false; /* read_callback_ sets the state for us */
  99561. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  99562. /* else we have to check if the second byte is the end of a sync code */
  99563. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99564. decoder->private_->lookahead = (FLAC__byte)x;
  99565. decoder->private_->cached = true;
  99566. }
  99567. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99568. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99569. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99570. return true;
  99571. }
  99572. }
  99573. if(first) {
  99574. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99575. first = false;
  99576. }
  99577. }
  99578. return true;
  99579. }
  99580. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  99581. {
  99582. unsigned channel;
  99583. unsigned i;
  99584. FLAC__int32 mid, side;
  99585. unsigned frame_crc; /* the one we calculate from the input stream */
  99586. FLAC__uint32 x;
  99587. *got_a_frame = false;
  99588. /* init the CRC */
  99589. frame_crc = 0;
  99590. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  99591. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  99592. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  99593. if(!read_frame_header_(decoder))
  99594. return false;
  99595. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  99596. return true;
  99597. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  99598. return false;
  99599. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  99600. /*
  99601. * first figure the correct bits-per-sample of the subframe
  99602. */
  99603. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  99604. switch(decoder->private_->frame.header.channel_assignment) {
  99605. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99606. /* no adjustment needed */
  99607. break;
  99608. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99609. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99610. if(channel == 1)
  99611. bps++;
  99612. break;
  99613. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99614. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99615. if(channel == 0)
  99616. bps++;
  99617. break;
  99618. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99619. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99620. if(channel == 1)
  99621. bps++;
  99622. break;
  99623. default:
  99624. FLAC__ASSERT(0);
  99625. }
  99626. /*
  99627. * now read it
  99628. */
  99629. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  99630. return false;
  99631. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  99632. return true;
  99633. }
  99634. if(!read_zero_padding_(decoder))
  99635. return false;
  99636. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption (i.e. "zero bits" were not all zeroes) */
  99637. return true;
  99638. /*
  99639. * Read the frame CRC-16 from the footer and check
  99640. */
  99641. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  99642. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  99643. return false; /* read_callback_ sets the state for us */
  99644. if(frame_crc == x) {
  99645. if(do_full_decode) {
  99646. /* Undo any special channel coding */
  99647. switch(decoder->private_->frame.header.channel_assignment) {
  99648. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99649. /* do nothing */
  99650. break;
  99651. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99652. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99653. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  99654. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  99655. break;
  99656. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99657. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99658. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  99659. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  99660. break;
  99661. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99662. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99663. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  99664. #if 1
  99665. mid = decoder->private_->output[0][i];
  99666. side = decoder->private_->output[1][i];
  99667. mid <<= 1;
  99668. mid |= (side & 1); /* i.e. if 'side' is odd... */
  99669. decoder->private_->output[0][i] = (mid + side) >> 1;
  99670. decoder->private_->output[1][i] = (mid - side) >> 1;
  99671. #else
  99672. /* OPT: without 'side' temp variable */
  99673. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  99674. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  99675. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  99676. #endif
  99677. }
  99678. break;
  99679. default:
  99680. FLAC__ASSERT(0);
  99681. break;
  99682. }
  99683. }
  99684. }
  99685. else {
  99686. /* Bad frame, emit error and zero the output signal */
  99687. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  99688. if(do_full_decode) {
  99689. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  99690. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  99691. }
  99692. }
  99693. }
  99694. *got_a_frame = true;
  99695. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  99696. if(decoder->private_->next_fixed_block_size)
  99697. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  99698. /* put the latest values into the public section of the decoder instance */
  99699. decoder->protected_->channels = decoder->private_->frame.header.channels;
  99700. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  99701. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  99702. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  99703. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  99704. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  99705. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  99706. /* write it */
  99707. if(do_full_decode) {
  99708. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  99709. return false;
  99710. }
  99711. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99712. return true;
  99713. }
  99714. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  99715. {
  99716. FLAC__uint32 x;
  99717. FLAC__uint64 xx;
  99718. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  99719. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  99720. unsigned raw_header_len;
  99721. FLAC__bool is_unparseable = false;
  99722. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99723. /* init the raw header with the saved bits from synchronization */
  99724. raw_header[0] = decoder->private_->header_warmup[0];
  99725. raw_header[1] = decoder->private_->header_warmup[1];
  99726. raw_header_len = 2;
  99727. /* check to make sure that reserved bit is 0 */
  99728. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  99729. is_unparseable = true;
  99730. /*
  99731. * Note that along the way as we read the header, we look for a sync
  99732. * code inside. If we find one it would indicate that our original
  99733. * sync was bad since there cannot be a sync code in a valid header.
  99734. *
  99735. * Three kinds of things can go wrong when reading the frame header:
  99736. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  99737. * If we don't find a sync code, it can end up looking like we read
  99738. * a valid but unparseable header, until getting to the frame header
  99739. * CRC. Even then we could get a false positive on the CRC.
  99740. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  99741. * future encoder).
  99742. * 3) We may be on a damaged frame which appears valid but unparseable.
  99743. *
  99744. * For all these reasons, we try and read a complete frame header as
  99745. * long as it seems valid, even if unparseable, up until the frame
  99746. * header CRC.
  99747. */
  99748. /*
  99749. * read in the raw header as bytes so we can CRC it, and parse it on the way
  99750. */
  99751. for(i = 0; i < 2; i++) {
  99752. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99753. return false; /* read_callback_ sets the state for us */
  99754. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99755. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  99756. decoder->private_->lookahead = (FLAC__byte)x;
  99757. decoder->private_->cached = true;
  99758. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  99759. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99760. return true;
  99761. }
  99762. raw_header[raw_header_len++] = (FLAC__byte)x;
  99763. }
  99764. switch(x = raw_header[2] >> 4) {
  99765. case 0:
  99766. is_unparseable = true;
  99767. break;
  99768. case 1:
  99769. decoder->private_->frame.header.blocksize = 192;
  99770. break;
  99771. case 2:
  99772. case 3:
  99773. case 4:
  99774. case 5:
  99775. decoder->private_->frame.header.blocksize = 576 << (x-2);
  99776. break;
  99777. case 6:
  99778. case 7:
  99779. blocksize_hint = x;
  99780. break;
  99781. case 8:
  99782. case 9:
  99783. case 10:
  99784. case 11:
  99785. case 12:
  99786. case 13:
  99787. case 14:
  99788. case 15:
  99789. decoder->private_->frame.header.blocksize = 256 << (x-8);
  99790. break;
  99791. default:
  99792. FLAC__ASSERT(0);
  99793. break;
  99794. }
  99795. switch(x = raw_header[2] & 0x0f) {
  99796. case 0:
  99797. if(decoder->private_->has_stream_info)
  99798. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  99799. else
  99800. is_unparseable = true;
  99801. break;
  99802. case 1:
  99803. decoder->private_->frame.header.sample_rate = 88200;
  99804. break;
  99805. case 2:
  99806. decoder->private_->frame.header.sample_rate = 176400;
  99807. break;
  99808. case 3:
  99809. decoder->private_->frame.header.sample_rate = 192000;
  99810. break;
  99811. case 4:
  99812. decoder->private_->frame.header.sample_rate = 8000;
  99813. break;
  99814. case 5:
  99815. decoder->private_->frame.header.sample_rate = 16000;
  99816. break;
  99817. case 6:
  99818. decoder->private_->frame.header.sample_rate = 22050;
  99819. break;
  99820. case 7:
  99821. decoder->private_->frame.header.sample_rate = 24000;
  99822. break;
  99823. case 8:
  99824. decoder->private_->frame.header.sample_rate = 32000;
  99825. break;
  99826. case 9:
  99827. decoder->private_->frame.header.sample_rate = 44100;
  99828. break;
  99829. case 10:
  99830. decoder->private_->frame.header.sample_rate = 48000;
  99831. break;
  99832. case 11:
  99833. decoder->private_->frame.header.sample_rate = 96000;
  99834. break;
  99835. case 12:
  99836. case 13:
  99837. case 14:
  99838. sample_rate_hint = x;
  99839. break;
  99840. case 15:
  99841. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  99842. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99843. return true;
  99844. default:
  99845. FLAC__ASSERT(0);
  99846. }
  99847. x = (unsigned)(raw_header[3] >> 4);
  99848. if(x & 8) {
  99849. decoder->private_->frame.header.channels = 2;
  99850. switch(x & 7) {
  99851. case 0:
  99852. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  99853. break;
  99854. case 1:
  99855. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  99856. break;
  99857. case 2:
  99858. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  99859. break;
  99860. default:
  99861. is_unparseable = true;
  99862. break;
  99863. }
  99864. }
  99865. else {
  99866. decoder->private_->frame.header.channels = (unsigned)x + 1;
  99867. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  99868. }
  99869. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  99870. case 0:
  99871. if(decoder->private_->has_stream_info)
  99872. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  99873. else
  99874. is_unparseable = true;
  99875. break;
  99876. case 1:
  99877. decoder->private_->frame.header.bits_per_sample = 8;
  99878. break;
  99879. case 2:
  99880. decoder->private_->frame.header.bits_per_sample = 12;
  99881. break;
  99882. case 4:
  99883. decoder->private_->frame.header.bits_per_sample = 16;
  99884. break;
  99885. case 5:
  99886. decoder->private_->frame.header.bits_per_sample = 20;
  99887. break;
  99888. case 6:
  99889. decoder->private_->frame.header.bits_per_sample = 24;
  99890. break;
  99891. case 3:
  99892. case 7:
  99893. is_unparseable = true;
  99894. break;
  99895. default:
  99896. FLAC__ASSERT(0);
  99897. break;
  99898. }
  99899. /* check to make sure that reserved bit is 0 */
  99900. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  99901. is_unparseable = true;
  99902. /* read the frame's starting sample number (or frame number as the case may be) */
  99903. if(
  99904. raw_header[1] & 0x01 ||
  99905. /*@@@ this clause is a concession to the old way of doing variable blocksize; the only known implementation is flake and can probably be removed without inconveniencing anyone */
  99906. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  99907. ) { /* variable blocksize */
  99908. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  99909. return false; /* read_callback_ sets the state for us */
  99910. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  99911. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  99912. decoder->private_->cached = true;
  99913. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  99914. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99915. return true;
  99916. }
  99917. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  99918. decoder->private_->frame.header.number.sample_number = xx;
  99919. }
  99920. else { /* fixed blocksize */
  99921. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  99922. return false; /* read_callback_ sets the state for us */
  99923. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  99924. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  99925. decoder->private_->cached = true;
  99926. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  99927. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99928. return true;
  99929. }
  99930. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  99931. decoder->private_->frame.header.number.frame_number = x;
  99932. }
  99933. if(blocksize_hint) {
  99934. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99935. return false; /* read_callback_ sets the state for us */
  99936. raw_header[raw_header_len++] = (FLAC__byte)x;
  99937. if(blocksize_hint == 7) {
  99938. FLAC__uint32 _x;
  99939. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  99940. return false; /* read_callback_ sets the state for us */
  99941. raw_header[raw_header_len++] = (FLAC__byte)_x;
  99942. x = (x << 8) | _x;
  99943. }
  99944. decoder->private_->frame.header.blocksize = x+1;
  99945. }
  99946. if(sample_rate_hint) {
  99947. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99948. return false; /* read_callback_ sets the state for us */
  99949. raw_header[raw_header_len++] = (FLAC__byte)x;
  99950. if(sample_rate_hint != 12) {
  99951. FLAC__uint32 _x;
  99952. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  99953. return false; /* read_callback_ sets the state for us */
  99954. raw_header[raw_header_len++] = (FLAC__byte)_x;
  99955. x = (x << 8) | _x;
  99956. }
  99957. if(sample_rate_hint == 12)
  99958. decoder->private_->frame.header.sample_rate = x*1000;
  99959. else if(sample_rate_hint == 13)
  99960. decoder->private_->frame.header.sample_rate = x;
  99961. else
  99962. decoder->private_->frame.header.sample_rate = x*10;
  99963. }
  99964. /* read the CRC-8 byte */
  99965. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99966. return false; /* read_callback_ sets the state for us */
  99967. crc8 = (FLAC__byte)x;
  99968. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  99969. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  99970. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99971. return true;
  99972. }
  99973. /* calculate the sample number from the frame number if needed */
  99974. decoder->private_->next_fixed_block_size = 0;
  99975. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  99976. x = decoder->private_->frame.header.number.frame_number;
  99977. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  99978. if(decoder->private_->fixed_block_size)
  99979. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  99980. else if(decoder->private_->has_stream_info) {
  99981. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  99982. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  99983. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  99984. }
  99985. else
  99986. is_unparseable = true;
  99987. }
  99988. else if(x == 0) {
  99989. decoder->private_->frame.header.number.sample_number = 0;
  99990. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  99991. }
  99992. else {
  99993. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  99994. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  99995. }
  99996. }
  99997. if(is_unparseable) {
  99998. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  99999. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100000. return true;
  100001. }
  100002. return true;
  100003. }
  100004. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100005. {
  100006. FLAC__uint32 x;
  100007. FLAC__bool wasted_bits;
  100008. unsigned i;
  100009. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100010. return false; /* read_callback_ sets the state for us */
  100011. wasted_bits = (x & 1);
  100012. x &= 0xfe;
  100013. if(wasted_bits) {
  100014. unsigned u;
  100015. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100016. return false; /* read_callback_ sets the state for us */
  100017. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100018. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100019. }
  100020. else
  100021. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100022. /*
  100023. * Lots of magic numbers here
  100024. */
  100025. if(x & 0x80) {
  100026. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100027. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100028. return true;
  100029. }
  100030. else if(x == 0) {
  100031. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100032. return false;
  100033. }
  100034. else if(x == 2) {
  100035. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100036. return false;
  100037. }
  100038. else if(x < 16) {
  100039. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100040. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100041. return true;
  100042. }
  100043. else if(x <= 24) {
  100044. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100045. return false;
  100046. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100047. return true;
  100048. }
  100049. else if(x < 64) {
  100050. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100051. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100052. return true;
  100053. }
  100054. else {
  100055. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100056. return false;
  100057. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100058. return true;
  100059. }
  100060. if(wasted_bits && do_full_decode) {
  100061. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100062. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100063. decoder->private_->output[channel][i] <<= x;
  100064. }
  100065. return true;
  100066. }
  100067. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100068. {
  100069. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100070. FLAC__int32 x;
  100071. unsigned i;
  100072. FLAC__int32 *output = decoder->private_->output[channel];
  100073. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100074. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100075. return false; /* read_callback_ sets the state for us */
  100076. subframe->value = x;
  100077. /* decode the subframe */
  100078. if(do_full_decode) {
  100079. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100080. output[i] = x;
  100081. }
  100082. return true;
  100083. }
  100084. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100085. {
  100086. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100087. FLAC__int32 i32;
  100088. FLAC__uint32 u32;
  100089. unsigned u;
  100090. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100091. subframe->residual = decoder->private_->residual[channel];
  100092. subframe->order = order;
  100093. /* read warm-up samples */
  100094. for(u = 0; u < order; u++) {
  100095. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100096. return false; /* read_callback_ sets the state for us */
  100097. subframe->warmup[u] = i32;
  100098. }
  100099. /* read entropy coding method info */
  100100. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100101. return false; /* read_callback_ sets the state for us */
  100102. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100103. switch(subframe->entropy_coding_method.type) {
  100104. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100105. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100106. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100107. return false; /* read_callback_ sets the state for us */
  100108. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100109. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100110. break;
  100111. default:
  100112. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100113. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100114. return true;
  100115. }
  100116. /* read residual */
  100117. switch(subframe->entropy_coding_method.type) {
  100118. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100119. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100120. if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
  100121. return false;
  100122. break;
  100123. default:
  100124. FLAC__ASSERT(0);
  100125. }
  100126. /* decode the subframe */
  100127. if(do_full_decode) {
  100128. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100129. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  100130. }
  100131. return true;
  100132. }
  100133. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100134. {
  100135. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  100136. FLAC__int32 i32;
  100137. FLAC__uint32 u32;
  100138. unsigned u;
  100139. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  100140. subframe->residual = decoder->private_->residual[channel];
  100141. subframe->order = order;
  100142. /* read warm-up samples */
  100143. for(u = 0; u < order; u++) {
  100144. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100145. return false; /* read_callback_ sets the state for us */
  100146. subframe->warmup[u] = i32;
  100147. }
  100148. /* read qlp coeff precision */
  100149. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100150. return false; /* read_callback_ sets the state for us */
  100151. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  100152. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100153. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100154. return true;
  100155. }
  100156. subframe->qlp_coeff_precision = u32+1;
  100157. /* read qlp shift */
  100158. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100159. return false; /* read_callback_ sets the state for us */
  100160. subframe->quantization_level = i32;
  100161. /* read quantized lp coefficiencts */
  100162. for(u = 0; u < order; u++) {
  100163. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  100164. return false; /* read_callback_ sets the state for us */
  100165. subframe->qlp_coeff[u] = i32;
  100166. }
  100167. /* read entropy coding method info */
  100168. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100169. return false; /* read_callback_ sets the state for us */
  100170. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100171. switch(subframe->entropy_coding_method.type) {
  100172. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100173. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100174. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100175. return false; /* read_callback_ sets the state for us */
  100176. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100177. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100178. break;
  100179. default:
  100180. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100181. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100182. return true;
  100183. }
  100184. /* read residual */
  100185. switch(subframe->entropy_coding_method.type) {
  100186. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100187. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100188. if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
  100189. return false;
  100190. break;
  100191. default:
  100192. FLAC__ASSERT(0);
  100193. }
  100194. /* decode the subframe */
  100195. if(do_full_decode) {
  100196. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100197. /*@@@@@@ technically not pessimistic enough, should be more like
  100198. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  100199. */
  100200. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100201. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  100202. if(order <= 8)
  100203. decoder->private_->local_lpc_restore_signal_16bit_order8(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  100204. else
  100205. decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  100206. }
  100207. else
  100208. decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  100209. else
  100210. decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  100211. }
  100212. return true;
  100213. }
  100214. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100215. {
  100216. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  100217. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  100218. unsigned i;
  100219. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  100220. subframe->data = residual;
  100221. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100222. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100223. return false; /* read_callback_ sets the state for us */
  100224. residual[i] = x;
  100225. }
  100226. /* decode the subframe */
  100227. if(do_full_decode)
  100228. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100229. return true;
  100230. }
  100231. FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended)
  100232. {
  100233. FLAC__uint32 rice_parameter;
  100234. int i;
  100235. unsigned partition, sample, u;
  100236. const unsigned partitions = 1u << partition_order;
  100237. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  100238. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100239. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100240. /* sanity checks */
  100241. if(partition_order == 0) {
  100242. if(decoder->private_->frame.header.blocksize < predictor_order) {
  100243. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100244. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100245. return true;
  100246. }
  100247. }
  100248. else {
  100249. if(partition_samples < predictor_order) {
  100250. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100251. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100252. return true;
  100253. }
  100254. }
  100255. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  100256. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100257. return false;
  100258. }
  100259. sample = 0;
  100260. for(partition = 0; partition < partitions; partition++) {
  100261. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  100262. return false; /* read_callback_ sets the state for us */
  100263. partitioned_rice_contents->parameters[partition] = rice_parameter;
  100264. if(rice_parameter < pesc) {
  100265. partitioned_rice_contents->raw_bits[partition] = 0;
  100266. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  100267. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  100268. return false; /* read_callback_ sets the state for us */
  100269. sample += u;
  100270. }
  100271. else {
  100272. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100273. return false; /* read_callback_ sets the state for us */
  100274. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  100275. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  100276. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  100277. return false; /* read_callback_ sets the state for us */
  100278. residual[sample] = i;
  100279. }
  100280. }
  100281. }
  100282. return true;
  100283. }
  100284. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  100285. {
  100286. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100287. FLAC__uint32 zero = 0;
  100288. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100289. return false; /* read_callback_ sets the state for us */
  100290. if(zero != 0) {
  100291. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100292. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100293. }
  100294. }
  100295. return true;
  100296. }
  100297. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  100298. {
  100299. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  100300. if(
  100301. #if FLAC__HAS_OGG
  100302. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100303. !decoder->private_->is_ogg &&
  100304. #endif
  100305. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100306. ) {
  100307. *bytes = 0;
  100308. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100309. return false;
  100310. }
  100311. else if(*bytes > 0) {
  100312. /* While seeking, it is possible for our seek to land in the
  100313. * middle of audio data that looks exactly like a frame header
  100314. * from a future version of an encoder. When that happens, our
  100315. * error callback will get an
  100316. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  100317. * unparseable_frame_count. But there is a remote possibility
  100318. * that it is properly synced at such a "future-codec frame",
  100319. * so to make sure, we wait to see many "unparseable" errors in
  100320. * a row before bailing out.
  100321. */
  100322. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  100323. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100324. return false;
  100325. }
  100326. else {
  100327. const FLAC__StreamDecoderReadStatus status =
  100328. #if FLAC__HAS_OGG
  100329. decoder->private_->is_ogg?
  100330. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  100331. #endif
  100332. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  100333. ;
  100334. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  100335. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100336. return false;
  100337. }
  100338. else if(*bytes == 0) {
  100339. if(
  100340. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  100341. (
  100342. #if FLAC__HAS_OGG
  100343. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100344. !decoder->private_->is_ogg &&
  100345. #endif
  100346. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100347. )
  100348. ) {
  100349. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100350. return false;
  100351. }
  100352. else
  100353. return true;
  100354. }
  100355. else
  100356. return true;
  100357. }
  100358. }
  100359. else {
  100360. /* abort to avoid a deadlock */
  100361. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100362. return false;
  100363. }
  100364. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  100365. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  100366. * and at the same time hit the end of the stream (for example, seeking
  100367. * to a point that is after the beginning of the last Ogg page). There
  100368. * is no way to report an Ogg sync loss through the callbacks (see note
  100369. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  100370. * So to keep the decoder from stopping at this point we gate the call
  100371. * to the eof_callback and let the Ogg decoder aspect set the
  100372. * end-of-stream state when it is needed.
  100373. */
  100374. }
  100375. #if FLAC__HAS_OGG
  100376. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  100377. {
  100378. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  100379. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  100380. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100381. /* we don't really have a way to handle lost sync via read
  100382. * callback so we'll let it pass and let the underlying
  100383. * FLAC decoder catch the error
  100384. */
  100385. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  100386. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100387. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  100388. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  100389. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  100390. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  100391. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  100392. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  100393. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  100394. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100395. default:
  100396. FLAC__ASSERT(0);
  100397. /* double protection */
  100398. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100399. }
  100400. }
  100401. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100402. {
  100403. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  100404. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  100405. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  100406. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  100407. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  100408. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  100409. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  100410. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  100411. default:
  100412. /* double protection: */
  100413. FLAC__ASSERT(0);
  100414. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  100415. }
  100416. }
  100417. #endif
  100418. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  100419. {
  100420. if(decoder->private_->is_seeking) {
  100421. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  100422. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  100423. FLAC__uint64 target_sample = decoder->private_->target_sample;
  100424. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100425. #if FLAC__HAS_OGG
  100426. decoder->private_->got_a_frame = true;
  100427. #endif
  100428. decoder->private_->last_frame = *frame; /* save the frame */
  100429. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  100430. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  100431. /* kick out of seek mode */
  100432. decoder->private_->is_seeking = false;
  100433. /* shift out the samples before target_sample */
  100434. if(delta > 0) {
  100435. unsigned channel;
  100436. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  100437. for(channel = 0; channel < frame->header.channels; channel++)
  100438. newbuffer[channel] = buffer[channel] + delta;
  100439. decoder->private_->last_frame.header.blocksize -= delta;
  100440. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  100441. /* write the relevant samples */
  100442. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  100443. }
  100444. else {
  100445. /* write the relevant samples */
  100446. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  100447. }
  100448. }
  100449. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100450. }
  100451. /*
  100452. * If we never got STREAMINFO, turn off MD5 checking to save
  100453. * cycles since we don't have a sum to compare to anyway
  100454. */
  100455. if(!decoder->private_->has_stream_info)
  100456. decoder->private_->do_md5_checking = false;
  100457. if(decoder->private_->do_md5_checking) {
  100458. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  100459. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  100460. }
  100461. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  100462. }
  100463. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  100464. {
  100465. if(!decoder->private_->is_seeking)
  100466. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  100467. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  100468. decoder->private_->unparseable_frame_count++;
  100469. }
  100470. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  100471. {
  100472. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  100473. FLAC__int64 pos = -1;
  100474. int i;
  100475. unsigned approx_bytes_per_frame;
  100476. FLAC__bool first_seek = true;
  100477. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  100478. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  100479. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100480. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  100481. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  100482. /* take these from the current frame in case they've changed mid-stream */
  100483. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  100484. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  100485. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  100486. /* use values from stream info if we didn't decode a frame */
  100487. if(channels == 0)
  100488. channels = decoder->private_->stream_info.data.stream_info.channels;
  100489. if(bps == 0)
  100490. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100491. /* we are just guessing here */
  100492. if(max_framesize > 0)
  100493. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  100494. /*
  100495. * Check if it's a known fixed-blocksize stream. Note that though
  100496. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  100497. * never get a STREAMINFO block when decoding so the value of
  100498. * min_blocksize might be zero.
  100499. */
  100500. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  100501. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  100502. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  100503. }
  100504. else
  100505. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  100506. /*
  100507. * First, we set an upper and lower bound on where in the
  100508. * stream we will search. For now we assume the worst case
  100509. * scenario, which is our best guess at the beginning of
  100510. * the first frame and end of the stream.
  100511. */
  100512. lower_bound = first_frame_offset;
  100513. lower_bound_sample = 0;
  100514. upper_bound = stream_length;
  100515. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  100516. /*
  100517. * Now we refine the bounds if we have a seektable with
  100518. * suitable points. Note that according to the spec they
  100519. * must be ordered by ascending sample number.
  100520. *
  100521. * Note: to protect against invalid seek tables we will ignore points
  100522. * that have frame_samples==0 or sample_number>=total_samples
  100523. */
  100524. if(seek_table) {
  100525. FLAC__uint64 new_lower_bound = lower_bound;
  100526. FLAC__uint64 new_upper_bound = upper_bound;
  100527. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  100528. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  100529. /* find the closest seek point <= target_sample, if it exists */
  100530. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  100531. if(
  100532. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  100533. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  100534. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  100535. seek_table->points[i].sample_number <= target_sample
  100536. )
  100537. break;
  100538. }
  100539. if(i >= 0) { /* i.e. we found a suitable seek point... */
  100540. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  100541. new_lower_bound_sample = seek_table->points[i].sample_number;
  100542. }
  100543. /* find the closest seek point > target_sample, if it exists */
  100544. for(i = 0; i < (int)seek_table->num_points; i++) {
  100545. if(
  100546. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  100547. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  100548. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  100549. seek_table->points[i].sample_number > target_sample
  100550. )
  100551. break;
  100552. }
  100553. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  100554. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  100555. new_upper_bound_sample = seek_table->points[i].sample_number;
  100556. }
  100557. /* final protection against unsorted seek tables; keep original values if bogus */
  100558. if(new_upper_bound >= new_lower_bound) {
  100559. lower_bound = new_lower_bound;
  100560. upper_bound = new_upper_bound;
  100561. lower_bound_sample = new_lower_bound_sample;
  100562. upper_bound_sample = new_upper_bound_sample;
  100563. }
  100564. }
  100565. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  100566. /* there are 2 insidious ways that the following equality occurs, which
  100567. * we need to fix:
  100568. * 1) total_samples is 0 (unknown) and target_sample is 0
  100569. * 2) total_samples is 0 (unknown) and target_sample happens to be
  100570. * exactly equal to the last seek point in the seek table; this
  100571. * means there is no seek point above it, and upper_bound_samples
  100572. * remains equal to the estimate (of target_samples) we made above
  100573. * in either case it does not hurt to move upper_bound_sample up by 1
  100574. */
  100575. if(upper_bound_sample == lower_bound_sample)
  100576. upper_bound_sample++;
  100577. decoder->private_->target_sample = target_sample;
  100578. while(1) {
  100579. /* check if the bounds are still ok */
  100580. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  100581. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100582. return false;
  100583. }
  100584. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100585. #if defined _MSC_VER || defined __MINGW32__
  100586. /* with VC++ you have to spoon feed it the casting */
  100587. pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(FLAC__int64)(target_sample - lower_bound_sample) / (FLAC__double)(FLAC__int64)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(FLAC__int64)(upper_bound - lower_bound)) - approx_bytes_per_frame;
  100588. #else
  100589. pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(target_sample - lower_bound_sample) / (FLAC__double)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(upper_bound - lower_bound)) - approx_bytes_per_frame;
  100590. #endif
  100591. #else
  100592. /* a little less accurate: */
  100593. if(upper_bound - lower_bound < 0xffffffff)
  100594. pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_sample - lower_bound_sample) * (upper_bound - lower_bound)) / (upper_bound_sample - lower_bound_sample)) - approx_bytes_per_frame;
  100595. else /* @@@ WATCHOUT, ~2TB limit */
  100596. pos = (FLAC__int64)lower_bound + (FLAC__int64)((((target_sample - lower_bound_sample)>>8) * ((upper_bound - lower_bound)>>8)) / ((upper_bound_sample - lower_bound_sample)>>16)) - approx_bytes_per_frame;
  100597. #endif
  100598. if(pos >= (FLAC__int64)upper_bound)
  100599. pos = (FLAC__int64)upper_bound - 1;
  100600. if(pos < (FLAC__int64)lower_bound)
  100601. pos = (FLAC__int64)lower_bound;
  100602. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  100603. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100604. return false;
  100605. }
  100606. if(!FLAC__stream_decoder_flush(decoder)) {
  100607. /* above call sets the state for us */
  100608. return false;
  100609. }
  100610. /* Now we need to get a frame. First we need to reset our
  100611. * unparseable_frame_count; if we get too many unparseable
  100612. * frames in a row, the read callback will return
  100613. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  100614. * FLAC__stream_decoder_process_single() to return false.
  100615. */
  100616. decoder->private_->unparseable_frame_count = 0;
  100617. if(!FLAC__stream_decoder_process_single(decoder)) {
  100618. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100619. return false;
  100620. }
  100621. /* our write callback will change the state when it gets to the target frame */
  100622. /* actually, we could have got_a_frame if our decoder is at FLAC__STREAM_DECODER_END_OF_STREAM so we need to check for that also */
  100623. #if 0
  100624. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  100625. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  100626. break;
  100627. #endif
  100628. if(!decoder->private_->is_seeking)
  100629. break;
  100630. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100631. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  100632. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  100633. if (pos == (FLAC__int64)lower_bound) {
  100634. /* can't move back any more than the first frame, something is fatally wrong */
  100635. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100636. return false;
  100637. }
  100638. /* our last move backwards wasn't big enough, try again */
  100639. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  100640. continue;
  100641. }
  100642. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  100643. first_seek = false;
  100644. /* make sure we are not seeking in corrupted stream */
  100645. if (this_frame_sample < lower_bound_sample) {
  100646. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100647. return false;
  100648. }
  100649. /* we need to narrow the search */
  100650. if(target_sample < this_frame_sample) {
  100651. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  100652. /*@@@@@@ what will decode position be if at end of stream? */
  100653. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  100654. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100655. return false;
  100656. }
  100657. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  100658. }
  100659. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  100660. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  100661. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  100662. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100663. return false;
  100664. }
  100665. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  100666. }
  100667. }
  100668. return true;
  100669. }
  100670. #if FLAC__HAS_OGG
  100671. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  100672. {
  100673. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  100674. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  100675. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  100676. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  100677. FLAC__bool did_a_seek;
  100678. unsigned iteration = 0;
  100679. /* In the first iterations, we will calculate the target byte position
  100680. * by the distance from the target sample to left_sample and
  100681. * right_sample (let's call it "proportional search"). After that, we
  100682. * will switch to binary search.
  100683. */
  100684. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  100685. /* We will switch to a linear search once our current sample is less
  100686. * than this number of samples ahead of the target sample
  100687. */
  100688. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  100689. /* If the total number of samples is unknown, use a large value, and
  100690. * force binary search immediately.
  100691. */
  100692. if(right_sample == 0) {
  100693. right_sample = (FLAC__uint64)(-1);
  100694. BINARY_SEARCH_AFTER_ITERATION = 0;
  100695. }
  100696. decoder->private_->target_sample = target_sample;
  100697. for( ; ; iteration++) {
  100698. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  100699. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  100700. pos = (right_pos + left_pos) / 2;
  100701. }
  100702. else {
  100703. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100704. #if defined _MSC_VER || defined __MINGW32__
  100705. /* with MSVC you have to spoon feed it the casting */
  100706. pos = (FLAC__uint64)((FLAC__double)(FLAC__int64)(target_sample - left_sample) / (FLAC__double)(FLAC__int64)(right_sample - left_sample) * (FLAC__double)(FLAC__int64)(right_pos - left_pos));
  100707. #else
  100708. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  100709. #endif
  100710. #else
  100711. /* a little less accurate: */
  100712. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  100713. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  100714. else /* @@@ WATCHOUT, ~2TB limit */
  100715. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  100716. #endif
  100717. /* @@@ TODO: might want to limit pos to some distance
  100718. * before EOF, to make sure we land before the last frame,
  100719. * thereby getting a this_frame_sample and so having a better
  100720. * estimate.
  100721. */
  100722. }
  100723. /* physical seek */
  100724. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  100725. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100726. return false;
  100727. }
  100728. if(!FLAC__stream_decoder_flush(decoder)) {
  100729. /* above call sets the state for us */
  100730. return false;
  100731. }
  100732. did_a_seek = true;
  100733. }
  100734. else
  100735. did_a_seek = false;
  100736. decoder->private_->got_a_frame = false;
  100737. if(!FLAC__stream_decoder_process_single(decoder)) {
  100738. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100739. return false;
  100740. }
  100741. if(!decoder->private_->got_a_frame) {
  100742. if(did_a_seek) {
  100743. /* this can happen if we seek to a point after the last frame; we drop
  100744. * to binary search right away in this case to avoid any wasted
  100745. * iterations of proportional search.
  100746. */
  100747. right_pos = pos;
  100748. BINARY_SEARCH_AFTER_ITERATION = 0;
  100749. }
  100750. else {
  100751. /* this can probably only happen if total_samples is unknown and the
  100752. * target_sample is past the end of the stream
  100753. */
  100754. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100755. return false;
  100756. }
  100757. }
  100758. /* our write callback will change the state when it gets to the target frame */
  100759. else if(!decoder->private_->is_seeking) {
  100760. break;
  100761. }
  100762. else {
  100763. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  100764. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100765. if (did_a_seek) {
  100766. if (this_frame_sample <= target_sample) {
  100767. /* The 'equal' case should not happen, since
  100768. * FLAC__stream_decoder_process_single()
  100769. * should recognize that it has hit the
  100770. * target sample and we would exit through
  100771. * the 'break' above.
  100772. */
  100773. FLAC__ASSERT(this_frame_sample != target_sample);
  100774. left_sample = this_frame_sample;
  100775. /* sanity check to avoid infinite loop */
  100776. if (left_pos == pos) {
  100777. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100778. return false;
  100779. }
  100780. left_pos = pos;
  100781. }
  100782. else if(this_frame_sample > target_sample) {
  100783. right_sample = this_frame_sample;
  100784. /* sanity check to avoid infinite loop */
  100785. if (right_pos == pos) {
  100786. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100787. return false;
  100788. }
  100789. right_pos = pos;
  100790. }
  100791. }
  100792. }
  100793. }
  100794. return true;
  100795. }
  100796. #endif
  100797. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100798. {
  100799. (void)client_data;
  100800. if(*bytes > 0) {
  100801. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  100802. if(ferror(decoder->private_->file))
  100803. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100804. else if(*bytes == 0)
  100805. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  100806. else
  100807. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100808. }
  100809. else
  100810. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  100811. }
  100812. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  100813. {
  100814. (void)client_data;
  100815. if(decoder->private_->file == stdin)
  100816. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  100817. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  100818. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  100819. else
  100820. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  100821. }
  100822. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  100823. {
  100824. off_t pos;
  100825. (void)client_data;
  100826. if(decoder->private_->file == stdin)
  100827. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  100828. else if((pos = ftello(decoder->private_->file)) < 0)
  100829. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  100830. else {
  100831. *absolute_byte_offset = (FLAC__uint64)pos;
  100832. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  100833. }
  100834. }
  100835. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  100836. {
  100837. struct stat filestats;
  100838. (void)client_data;
  100839. if(decoder->private_->file == stdin)
  100840. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  100841. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  100842. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  100843. else {
  100844. *stream_length = (FLAC__uint64)filestats.st_size;
  100845. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  100846. }
  100847. }
  100848. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  100849. {
  100850. (void)client_data;
  100851. return feof(decoder->private_->file)? true : false;
  100852. }
  100853. #endif
  100854. /*** End of inlined file: stream_decoder.c ***/
  100855. /*** Start of inlined file: stream_encoder.c ***/
  100856. /*** Start of inlined file: juce_FlacHeader.h ***/
  100857. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  100858. // tasks..
  100859. #define VERSION "1.2.1"
  100860. #define FLAC__NO_DLL 1
  100861. #if JUCE_MSVC
  100862. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  100863. #endif
  100864. #if JUCE_MAC
  100865. #define FLAC__SYS_DARWIN 1
  100866. #endif
  100867. /*** End of inlined file: juce_FlacHeader.h ***/
  100868. #if JUCE_USE_FLAC
  100869. #if HAVE_CONFIG_H
  100870. # include <config.h>
  100871. #endif
  100872. #if defined _MSC_VER || defined __MINGW32__
  100873. #include <io.h> /* for _setmode() */
  100874. #include <fcntl.h> /* for _O_BINARY */
  100875. #endif
  100876. #if defined __CYGWIN__ || defined __EMX__
  100877. #include <io.h> /* for setmode(), O_BINARY */
  100878. #include <fcntl.h> /* for _O_BINARY */
  100879. #endif
  100880. #include <limits.h>
  100881. #include <stdio.h>
  100882. #include <stdlib.h> /* for malloc() */
  100883. #include <string.h> /* for memcpy() */
  100884. #include <sys/types.h> /* for off_t */
  100885. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  100886. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  100887. #define fseeko fseek
  100888. #define ftello ftell
  100889. #endif
  100890. #endif
  100891. /*** Start of inlined file: stream_encoder.h ***/
  100892. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  100893. #define FLAC__PROTECTED__STREAM_ENCODER_H
  100894. #if FLAC__HAS_OGG
  100895. #include "private/ogg_encoder_aspect.h"
  100896. #endif
  100897. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100898. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  100899. typedef enum {
  100900. FLAC__APODIZATION_BARTLETT,
  100901. FLAC__APODIZATION_BARTLETT_HANN,
  100902. FLAC__APODIZATION_BLACKMAN,
  100903. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  100904. FLAC__APODIZATION_CONNES,
  100905. FLAC__APODIZATION_FLATTOP,
  100906. FLAC__APODIZATION_GAUSS,
  100907. FLAC__APODIZATION_HAMMING,
  100908. FLAC__APODIZATION_HANN,
  100909. FLAC__APODIZATION_KAISER_BESSEL,
  100910. FLAC__APODIZATION_NUTTALL,
  100911. FLAC__APODIZATION_RECTANGLE,
  100912. FLAC__APODIZATION_TRIANGLE,
  100913. FLAC__APODIZATION_TUKEY,
  100914. FLAC__APODIZATION_WELCH
  100915. } FLAC__ApodizationFunction;
  100916. typedef struct {
  100917. FLAC__ApodizationFunction type;
  100918. union {
  100919. struct {
  100920. FLAC__real stddev;
  100921. } gauss;
  100922. struct {
  100923. FLAC__real p;
  100924. } tukey;
  100925. } parameters;
  100926. } FLAC__ApodizationSpecification;
  100927. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100928. typedef struct FLAC__StreamEncoderProtected {
  100929. FLAC__StreamEncoderState state;
  100930. FLAC__bool verify;
  100931. FLAC__bool streamable_subset;
  100932. FLAC__bool do_md5;
  100933. FLAC__bool do_mid_side_stereo;
  100934. FLAC__bool loose_mid_side_stereo;
  100935. unsigned channels;
  100936. unsigned bits_per_sample;
  100937. unsigned sample_rate;
  100938. unsigned blocksize;
  100939. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100940. unsigned num_apodizations;
  100941. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  100942. #endif
  100943. unsigned max_lpc_order;
  100944. unsigned qlp_coeff_precision;
  100945. FLAC__bool do_qlp_coeff_prec_search;
  100946. FLAC__bool do_exhaustive_model_search;
  100947. FLAC__bool do_escape_coding;
  100948. unsigned min_residual_partition_order;
  100949. unsigned max_residual_partition_order;
  100950. unsigned rice_parameter_search_dist;
  100951. FLAC__uint64 total_samples_estimate;
  100952. FLAC__StreamMetadata **metadata;
  100953. unsigned num_metadata_blocks;
  100954. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  100955. #if FLAC__HAS_OGG
  100956. FLAC__OggEncoderAspect ogg_encoder_aspect;
  100957. #endif
  100958. } FLAC__StreamEncoderProtected;
  100959. #endif
  100960. /*** End of inlined file: stream_encoder.h ***/
  100961. #if FLAC__HAS_OGG
  100962. #include "include/private/ogg_helper.h"
  100963. #include "include/private/ogg_mapping.h"
  100964. #endif
  100965. /*** Start of inlined file: stream_encoder_framing.h ***/
  100966. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  100967. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  100968. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  100969. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  100970. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  100971. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  100972. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  100973. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  100974. #endif
  100975. /*** End of inlined file: stream_encoder_framing.h ***/
  100976. /*** Start of inlined file: window.h ***/
  100977. #ifndef FLAC__PRIVATE__WINDOW_H
  100978. #define FLAC__PRIVATE__WINDOW_H
  100979. #ifdef HAVE_CONFIG_H
  100980. #include <config.h>
  100981. #endif
  100982. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100983. /*
  100984. * FLAC__window_*()
  100985. * --------------------------------------------------------------------
  100986. * Calculates window coefficients according to different apodization
  100987. * functions.
  100988. *
  100989. * OUT window[0,L-1]
  100990. * IN L (number of points in window)
  100991. */
  100992. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  100993. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  100994. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  100995. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  100996. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  100997. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  100998. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  100999. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101000. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101001. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101002. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101003. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101004. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101005. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101006. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101007. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101008. #endif
  101009. /*** End of inlined file: window.h ***/
  101010. #ifndef FLaC__INLINE
  101011. #define FLaC__INLINE
  101012. #endif
  101013. #ifdef min
  101014. #undef min
  101015. #endif
  101016. #define min(x,y) ((x)<(y)?(x):(y))
  101017. #ifdef max
  101018. #undef max
  101019. #endif
  101020. #define max(x,y) ((x)>(y)?(x):(y))
  101021. /* Exact Rice codeword length calculation is off by default. The simple
  101022. * (and fast) estimation (of how many bits a residual value will be
  101023. * encoded with) in this encoder is very good, almost always yielding
  101024. * compression within 0.1% of exact calculation.
  101025. */
  101026. #undef EXACT_RICE_BITS_CALCULATION
  101027. /* Rice parameter searching is off by default. The simple (and fast)
  101028. * parameter estimation in this encoder is very good, almost always
  101029. * yielding compression within 0.1% of the optimal parameters.
  101030. */
  101031. #undef ENABLE_RICE_PARAMETER_SEARCH
  101032. typedef struct {
  101033. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101034. unsigned size; /* of each data[] in samples */
  101035. unsigned tail;
  101036. } verify_input_fifo;
  101037. typedef struct {
  101038. const FLAC__byte *data;
  101039. unsigned capacity;
  101040. unsigned bytes;
  101041. } verify_output;
  101042. typedef enum {
  101043. ENCODER_IN_MAGIC = 0,
  101044. ENCODER_IN_METADATA = 1,
  101045. ENCODER_IN_AUDIO = 2
  101046. } EncoderStateHint;
  101047. static struct CompressionLevels {
  101048. FLAC__bool do_mid_side_stereo;
  101049. FLAC__bool loose_mid_side_stereo;
  101050. unsigned max_lpc_order;
  101051. unsigned qlp_coeff_precision;
  101052. FLAC__bool do_qlp_coeff_prec_search;
  101053. FLAC__bool do_escape_coding;
  101054. FLAC__bool do_exhaustive_model_search;
  101055. unsigned min_residual_partition_order;
  101056. unsigned max_residual_partition_order;
  101057. unsigned rice_parameter_search_dist;
  101058. } compression_levels_[] = {
  101059. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101060. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101061. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101062. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101063. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101064. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101065. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101066. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101067. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101068. };
  101069. /***********************************************************************
  101070. *
  101071. * Private class method prototypes
  101072. *
  101073. ***********************************************************************/
  101074. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101075. static void free_(FLAC__StreamEncoder *encoder);
  101076. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101077. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101078. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101079. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101080. #if FLAC__HAS_OGG
  101081. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101082. #endif
  101083. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101084. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101085. static FLAC__bool process_subframe_(
  101086. FLAC__StreamEncoder *encoder,
  101087. unsigned min_partition_order,
  101088. unsigned max_partition_order,
  101089. const FLAC__FrameHeader *frame_header,
  101090. unsigned subframe_bps,
  101091. const FLAC__int32 integer_signal[],
  101092. FLAC__Subframe *subframe[2],
  101093. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101094. FLAC__int32 *residual[2],
  101095. unsigned *best_subframe,
  101096. unsigned *best_bits
  101097. );
  101098. static FLAC__bool add_subframe_(
  101099. FLAC__StreamEncoder *encoder,
  101100. unsigned blocksize,
  101101. unsigned subframe_bps,
  101102. const FLAC__Subframe *subframe,
  101103. FLAC__BitWriter *frame
  101104. );
  101105. static unsigned evaluate_constant_subframe_(
  101106. FLAC__StreamEncoder *encoder,
  101107. const FLAC__int32 signal,
  101108. unsigned blocksize,
  101109. unsigned subframe_bps,
  101110. FLAC__Subframe *subframe
  101111. );
  101112. static unsigned evaluate_fixed_subframe_(
  101113. FLAC__StreamEncoder *encoder,
  101114. const FLAC__int32 signal[],
  101115. FLAC__int32 residual[],
  101116. FLAC__uint64 abs_residual_partition_sums[],
  101117. unsigned raw_bits_per_partition[],
  101118. unsigned blocksize,
  101119. unsigned subframe_bps,
  101120. unsigned order,
  101121. unsigned rice_parameter,
  101122. unsigned rice_parameter_limit,
  101123. unsigned min_partition_order,
  101124. unsigned max_partition_order,
  101125. FLAC__bool do_escape_coding,
  101126. unsigned rice_parameter_search_dist,
  101127. FLAC__Subframe *subframe,
  101128. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101129. );
  101130. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101131. static unsigned evaluate_lpc_subframe_(
  101132. FLAC__StreamEncoder *encoder,
  101133. const FLAC__int32 signal[],
  101134. FLAC__int32 residual[],
  101135. FLAC__uint64 abs_residual_partition_sums[],
  101136. unsigned raw_bits_per_partition[],
  101137. const FLAC__real lp_coeff[],
  101138. unsigned blocksize,
  101139. unsigned subframe_bps,
  101140. unsigned order,
  101141. unsigned qlp_coeff_precision,
  101142. unsigned rice_parameter,
  101143. unsigned rice_parameter_limit,
  101144. unsigned min_partition_order,
  101145. unsigned max_partition_order,
  101146. FLAC__bool do_escape_coding,
  101147. unsigned rice_parameter_search_dist,
  101148. FLAC__Subframe *subframe,
  101149. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101150. );
  101151. #endif
  101152. static unsigned evaluate_verbatim_subframe_(
  101153. FLAC__StreamEncoder *encoder,
  101154. const FLAC__int32 signal[],
  101155. unsigned blocksize,
  101156. unsigned subframe_bps,
  101157. FLAC__Subframe *subframe
  101158. );
  101159. static unsigned find_best_partition_order_(
  101160. struct FLAC__StreamEncoderPrivate *private_,
  101161. const FLAC__int32 residual[],
  101162. FLAC__uint64 abs_residual_partition_sums[],
  101163. unsigned raw_bits_per_partition[],
  101164. unsigned residual_samples,
  101165. unsigned predictor_order,
  101166. unsigned rice_parameter,
  101167. unsigned rice_parameter_limit,
  101168. unsigned min_partition_order,
  101169. unsigned max_partition_order,
  101170. unsigned bps,
  101171. FLAC__bool do_escape_coding,
  101172. unsigned rice_parameter_search_dist,
  101173. FLAC__EntropyCodingMethod *best_ecm
  101174. );
  101175. static void precompute_partition_info_sums_(
  101176. const FLAC__int32 residual[],
  101177. FLAC__uint64 abs_residual_partition_sums[],
  101178. unsigned residual_samples,
  101179. unsigned predictor_order,
  101180. unsigned min_partition_order,
  101181. unsigned max_partition_order,
  101182. unsigned bps
  101183. );
  101184. static void precompute_partition_info_escapes_(
  101185. const FLAC__int32 residual[],
  101186. unsigned raw_bits_per_partition[],
  101187. unsigned residual_samples,
  101188. unsigned predictor_order,
  101189. unsigned min_partition_order,
  101190. unsigned max_partition_order
  101191. );
  101192. static FLAC__bool set_partitioned_rice_(
  101193. #ifdef EXACT_RICE_BITS_CALCULATION
  101194. const FLAC__int32 residual[],
  101195. #endif
  101196. const FLAC__uint64 abs_residual_partition_sums[],
  101197. const unsigned raw_bits_per_partition[],
  101198. const unsigned residual_samples,
  101199. const unsigned predictor_order,
  101200. const unsigned suggested_rice_parameter,
  101201. const unsigned rice_parameter_limit,
  101202. const unsigned rice_parameter_search_dist,
  101203. const unsigned partition_order,
  101204. const FLAC__bool search_for_escapes,
  101205. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101206. unsigned *bits
  101207. );
  101208. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  101209. /* verify-related routines: */
  101210. static void append_to_verify_fifo_(
  101211. verify_input_fifo *fifo,
  101212. const FLAC__int32 * const input[],
  101213. unsigned input_offset,
  101214. unsigned channels,
  101215. unsigned wide_samples
  101216. );
  101217. static void append_to_verify_fifo_interleaved_(
  101218. verify_input_fifo *fifo,
  101219. const FLAC__int32 input[],
  101220. unsigned input_offset,
  101221. unsigned channels,
  101222. unsigned wide_samples
  101223. );
  101224. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101225. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  101226. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  101227. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  101228. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101229. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  101230. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  101231. static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  101232. static FILE *get_binary_stdout_(void);
  101233. /***********************************************************************
  101234. *
  101235. * Private class data
  101236. *
  101237. ***********************************************************************/
  101238. typedef struct FLAC__StreamEncoderPrivate {
  101239. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  101240. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  101241. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  101242. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101243. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  101244. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  101245. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  101246. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  101247. #endif
  101248. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  101249. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  101250. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  101251. FLAC__int32 *residual_workspace_mid_side[2][2];
  101252. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  101253. FLAC__Subframe subframe_workspace_mid_side[2][2];
  101254. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101255. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  101256. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  101257. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  101258. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101259. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  101260. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  101261. unsigned best_subframe_mid_side[2];
  101262. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  101263. unsigned best_subframe_bits_mid_side[2];
  101264. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  101265. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  101266. FLAC__BitWriter *frame; /* the current frame being worked on */
  101267. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  101268. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  101269. FLAC__ChannelAssignment last_channel_assignment;
  101270. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  101271. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  101272. unsigned current_sample_number;
  101273. unsigned current_frame_number;
  101274. FLAC__MD5Context md5context;
  101275. FLAC__CPUInfo cpuinfo;
  101276. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101277. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101278. #else
  101279. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101280. #endif
  101281. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101282. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  101283. void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  101284. void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  101285. void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  101286. #endif
  101287. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  101288. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  101289. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  101290. FLAC__bool disable_constant_subframes;
  101291. FLAC__bool disable_fixed_subframes;
  101292. FLAC__bool disable_verbatim_subframes;
  101293. #if FLAC__HAS_OGG
  101294. FLAC__bool is_ogg;
  101295. #endif
  101296. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  101297. FLAC__StreamEncoderSeekCallback seek_callback;
  101298. FLAC__StreamEncoderTellCallback tell_callback;
  101299. FLAC__StreamEncoderWriteCallback write_callback;
  101300. FLAC__StreamEncoderMetadataCallback metadata_callback;
  101301. FLAC__StreamEncoderProgressCallback progress_callback;
  101302. void *client_data;
  101303. unsigned first_seekpoint_to_check;
  101304. FILE *file; /* only used when encoding to a file */
  101305. FLAC__uint64 bytes_written;
  101306. FLAC__uint64 samples_written;
  101307. unsigned frames_written;
  101308. unsigned total_frames_estimate;
  101309. /* unaligned (original) pointers to allocated data */
  101310. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  101311. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  101312. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101313. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  101314. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  101315. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  101316. FLAC__real *windowed_signal_unaligned;
  101317. #endif
  101318. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  101319. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  101320. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  101321. unsigned *raw_bits_per_partition_unaligned;
  101322. /*
  101323. * These fields have been moved here from private function local
  101324. * declarations merely to save stack space during encoding.
  101325. */
  101326. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101327. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  101328. #endif
  101329. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  101330. /*
  101331. * The data for the verify section
  101332. */
  101333. struct {
  101334. FLAC__StreamDecoder *decoder;
  101335. EncoderStateHint state_hint;
  101336. FLAC__bool needs_magic_hack;
  101337. verify_input_fifo input_fifo;
  101338. verify_output output;
  101339. struct {
  101340. FLAC__uint64 absolute_sample;
  101341. unsigned frame_number;
  101342. unsigned channel;
  101343. unsigned sample;
  101344. FLAC__int32 expected;
  101345. FLAC__int32 got;
  101346. } error_stats;
  101347. } verify;
  101348. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  101349. } FLAC__StreamEncoderPrivate;
  101350. /***********************************************************************
  101351. *
  101352. * Public static class data
  101353. *
  101354. ***********************************************************************/
  101355. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  101356. "FLAC__STREAM_ENCODER_OK",
  101357. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  101358. "FLAC__STREAM_ENCODER_OGG_ERROR",
  101359. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  101360. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  101361. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  101362. "FLAC__STREAM_ENCODER_IO_ERROR",
  101363. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  101364. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  101365. };
  101366. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  101367. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  101368. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  101369. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  101370. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  101371. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  101372. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  101373. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  101374. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  101375. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  101376. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  101377. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  101378. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  101379. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  101380. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  101381. };
  101382. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  101383. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  101384. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  101385. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  101386. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  101387. };
  101388. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  101389. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  101390. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  101391. };
  101392. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  101393. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  101394. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  101395. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  101396. };
  101397. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  101398. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  101399. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  101400. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  101401. };
  101402. /* Number of samples that will be overread to watch for end of stream. By
  101403. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  101404. * always try to read blocksize+1 samples before encoding a block, so that
  101405. * even if the stream has a total sample count that is an integral multiple
  101406. * of the blocksize, we will still notice when we are encoding the last
  101407. * block. This is needed, for example, to correctly set the end-of-stream
  101408. * marker in Ogg FLAC.
  101409. *
  101410. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  101411. * not really any reason to change it.
  101412. */
  101413. static const unsigned OVERREAD_ = 1;
  101414. /***********************************************************************
  101415. *
  101416. * Class constructor/destructor
  101417. *
  101418. */
  101419. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  101420. {
  101421. FLAC__StreamEncoder *encoder;
  101422. unsigned i;
  101423. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  101424. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  101425. if(encoder == 0) {
  101426. return 0;
  101427. }
  101428. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  101429. if(encoder->protected_ == 0) {
  101430. free(encoder);
  101431. return 0;
  101432. }
  101433. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  101434. if(encoder->private_ == 0) {
  101435. free(encoder->protected_);
  101436. free(encoder);
  101437. return 0;
  101438. }
  101439. encoder->private_->frame = FLAC__bitwriter_new();
  101440. if(encoder->private_->frame == 0) {
  101441. free(encoder->private_);
  101442. free(encoder->protected_);
  101443. free(encoder);
  101444. return 0;
  101445. }
  101446. encoder->private_->file = 0;
  101447. set_defaults_enc(encoder);
  101448. encoder->private_->is_being_deleted = false;
  101449. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101450. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  101451. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  101452. }
  101453. for(i = 0; i < 2; i++) {
  101454. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  101455. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  101456. }
  101457. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101458. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  101459. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  101460. }
  101461. for(i = 0; i < 2; i++) {
  101462. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  101463. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  101464. }
  101465. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101466. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  101467. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  101468. }
  101469. for(i = 0; i < 2; i++) {
  101470. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  101471. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  101472. }
  101473. for(i = 0; i < 2; i++)
  101474. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  101475. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  101476. return encoder;
  101477. }
  101478. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  101479. {
  101480. unsigned i;
  101481. FLAC__ASSERT(0 != encoder);
  101482. FLAC__ASSERT(0 != encoder->protected_);
  101483. FLAC__ASSERT(0 != encoder->private_);
  101484. FLAC__ASSERT(0 != encoder->private_->frame);
  101485. encoder->private_->is_being_deleted = true;
  101486. (void)FLAC__stream_encoder_finish(encoder);
  101487. if(0 != encoder->private_->verify.decoder)
  101488. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  101489. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101490. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  101491. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  101492. }
  101493. for(i = 0; i < 2; i++) {
  101494. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  101495. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  101496. }
  101497. for(i = 0; i < 2; i++)
  101498. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  101499. FLAC__bitwriter_delete(encoder->private_->frame);
  101500. free(encoder->private_);
  101501. free(encoder->protected_);
  101502. free(encoder);
  101503. }
  101504. /***********************************************************************
  101505. *
  101506. * Public class methods
  101507. *
  101508. ***********************************************************************/
  101509. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  101510. FLAC__StreamEncoder *encoder,
  101511. FLAC__StreamEncoderReadCallback read_callback,
  101512. FLAC__StreamEncoderWriteCallback write_callback,
  101513. FLAC__StreamEncoderSeekCallback seek_callback,
  101514. FLAC__StreamEncoderTellCallback tell_callback,
  101515. FLAC__StreamEncoderMetadataCallback metadata_callback,
  101516. void *client_data,
  101517. FLAC__bool is_ogg
  101518. )
  101519. {
  101520. unsigned i;
  101521. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  101522. FLAC__ASSERT(0 != encoder);
  101523. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  101524. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  101525. #if !FLAC__HAS_OGG
  101526. if(is_ogg)
  101527. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  101528. #endif
  101529. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  101530. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  101531. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  101532. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  101533. if(encoder->protected_->channels != 2) {
  101534. encoder->protected_->do_mid_side_stereo = false;
  101535. encoder->protected_->loose_mid_side_stereo = false;
  101536. }
  101537. else if(!encoder->protected_->do_mid_side_stereo)
  101538. encoder->protected_->loose_mid_side_stereo = false;
  101539. if(encoder->protected_->bits_per_sample >= 32)
  101540. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  101541. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  101542. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  101543. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  101544. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  101545. if(encoder->protected_->blocksize == 0) {
  101546. if(encoder->protected_->max_lpc_order == 0)
  101547. encoder->protected_->blocksize = 1152;
  101548. else
  101549. encoder->protected_->blocksize = 4096;
  101550. }
  101551. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  101552. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  101553. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  101554. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  101555. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  101556. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  101557. if(encoder->protected_->qlp_coeff_precision == 0) {
  101558. if(encoder->protected_->bits_per_sample < 16) {
  101559. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  101560. /* @@@ until then we'll make a guess */
  101561. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  101562. }
  101563. else if(encoder->protected_->bits_per_sample == 16) {
  101564. if(encoder->protected_->blocksize <= 192)
  101565. encoder->protected_->qlp_coeff_precision = 7;
  101566. else if(encoder->protected_->blocksize <= 384)
  101567. encoder->protected_->qlp_coeff_precision = 8;
  101568. else if(encoder->protected_->blocksize <= 576)
  101569. encoder->protected_->qlp_coeff_precision = 9;
  101570. else if(encoder->protected_->blocksize <= 1152)
  101571. encoder->protected_->qlp_coeff_precision = 10;
  101572. else if(encoder->protected_->blocksize <= 2304)
  101573. encoder->protected_->qlp_coeff_precision = 11;
  101574. else if(encoder->protected_->blocksize <= 4608)
  101575. encoder->protected_->qlp_coeff_precision = 12;
  101576. else
  101577. encoder->protected_->qlp_coeff_precision = 13;
  101578. }
  101579. else {
  101580. if(encoder->protected_->blocksize <= 384)
  101581. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  101582. else if(encoder->protected_->blocksize <= 1152)
  101583. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  101584. else
  101585. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  101586. }
  101587. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  101588. }
  101589. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  101590. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  101591. if(encoder->protected_->streamable_subset) {
  101592. if(
  101593. encoder->protected_->blocksize != 192 &&
  101594. encoder->protected_->blocksize != 576 &&
  101595. encoder->protected_->blocksize != 1152 &&
  101596. encoder->protected_->blocksize != 2304 &&
  101597. encoder->protected_->blocksize != 4608 &&
  101598. encoder->protected_->blocksize != 256 &&
  101599. encoder->protected_->blocksize != 512 &&
  101600. encoder->protected_->blocksize != 1024 &&
  101601. encoder->protected_->blocksize != 2048 &&
  101602. encoder->protected_->blocksize != 4096 &&
  101603. encoder->protected_->blocksize != 8192 &&
  101604. encoder->protected_->blocksize != 16384
  101605. )
  101606. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101607. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  101608. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101609. if(
  101610. encoder->protected_->bits_per_sample != 8 &&
  101611. encoder->protected_->bits_per_sample != 12 &&
  101612. encoder->protected_->bits_per_sample != 16 &&
  101613. encoder->protected_->bits_per_sample != 20 &&
  101614. encoder->protected_->bits_per_sample != 24
  101615. )
  101616. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101617. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  101618. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101619. if(
  101620. encoder->protected_->sample_rate <= 48000 &&
  101621. (
  101622. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  101623. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  101624. )
  101625. ) {
  101626. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101627. }
  101628. }
  101629. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101630. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  101631. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  101632. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  101633. #if FLAC__HAS_OGG
  101634. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  101635. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  101636. unsigned i;
  101637. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  101638. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101639. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  101640. for( ; i > 0; i--)
  101641. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  101642. encoder->protected_->metadata[0] = vc;
  101643. break;
  101644. }
  101645. }
  101646. }
  101647. #endif
  101648. /* keep track of any SEEKTABLE block */
  101649. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  101650. unsigned i;
  101651. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  101652. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  101653. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  101654. break; /* take only the first one */
  101655. }
  101656. }
  101657. }
  101658. /* validate metadata */
  101659. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  101660. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101661. metadata_has_seektable = false;
  101662. metadata_has_vorbis_comment = false;
  101663. metadata_picture_has_type1 = false;
  101664. metadata_picture_has_type2 = false;
  101665. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  101666. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  101667. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  101668. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101669. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  101670. if(metadata_has_seektable) /* only one is allowed */
  101671. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101672. metadata_has_seektable = true;
  101673. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  101674. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101675. }
  101676. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101677. if(metadata_has_vorbis_comment) /* only one is allowed */
  101678. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101679. metadata_has_vorbis_comment = true;
  101680. }
  101681. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  101682. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  101683. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101684. }
  101685. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  101686. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  101687. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101688. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  101689. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  101690. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101691. metadata_picture_has_type1 = true;
  101692. /* standard icon must be 32x32 pixel PNG */
  101693. if(
  101694. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  101695. (
  101696. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  101697. m->data.picture.width != 32 ||
  101698. m->data.picture.height != 32
  101699. )
  101700. )
  101701. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101702. }
  101703. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  101704. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  101705. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101706. metadata_picture_has_type2 = true;
  101707. }
  101708. }
  101709. }
  101710. encoder->private_->input_capacity = 0;
  101711. for(i = 0; i < encoder->protected_->channels; i++) {
  101712. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  101713. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101714. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  101715. #endif
  101716. }
  101717. for(i = 0; i < 2; i++) {
  101718. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  101719. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101720. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  101721. #endif
  101722. }
  101723. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101724. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  101725. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  101726. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  101727. #endif
  101728. for(i = 0; i < encoder->protected_->channels; i++) {
  101729. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  101730. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  101731. encoder->private_->best_subframe[i] = 0;
  101732. }
  101733. for(i = 0; i < 2; i++) {
  101734. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  101735. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  101736. encoder->private_->best_subframe_mid_side[i] = 0;
  101737. }
  101738. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  101739. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  101740. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101741. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  101742. #else
  101743. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  101744. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  101745. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  101746. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  101747. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  101748. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  101749. encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
  101750. #endif
  101751. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  101752. encoder->private_->loose_mid_side_stereo_frames = 1;
  101753. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  101754. encoder->private_->current_sample_number = 0;
  101755. encoder->private_->current_frame_number = 0;
  101756. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  101757. encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
  101758. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  101759. /*
  101760. * get the CPU info and set the function pointers
  101761. */
  101762. FLAC__cpu_info(&encoder->private_->cpuinfo);
  101763. /* first default to the non-asm routines */
  101764. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101765. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  101766. #endif
  101767. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  101768. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101769. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  101770. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  101771. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  101772. #endif
  101773. /* now override with asm where appropriate */
  101774. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101775. # ifndef FLAC__NO_ASM
  101776. if(encoder->private_->cpuinfo.use_asm) {
  101777. # ifdef FLAC__CPU_IA32
  101778. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  101779. # ifdef FLAC__HAS_NASM
  101780. if(encoder->private_->cpuinfo.data.ia32.sse) {
  101781. if(encoder->protected_->max_lpc_order < 4)
  101782. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  101783. else if(encoder->protected_->max_lpc_order < 8)
  101784. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  101785. else if(encoder->protected_->max_lpc_order < 12)
  101786. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  101787. else
  101788. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  101789. }
  101790. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  101791. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  101792. else
  101793. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  101794. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  101795. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  101796. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  101797. }
  101798. else {
  101799. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  101800. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  101801. }
  101802. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  101803. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  101804. # endif /* FLAC__HAS_NASM */
  101805. # endif /* FLAC__CPU_IA32 */
  101806. }
  101807. # endif /* !FLAC__NO_ASM */
  101808. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  101809. /* finally override based on wide-ness if necessary */
  101810. if(encoder->private_->use_wide_by_block) {
  101811. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  101812. }
  101813. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  101814. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  101815. #if FLAC__HAS_OGG
  101816. encoder->private_->is_ogg = is_ogg;
  101817. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  101818. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101819. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101820. }
  101821. #endif
  101822. encoder->private_->read_callback = read_callback;
  101823. encoder->private_->write_callback = write_callback;
  101824. encoder->private_->seek_callback = seek_callback;
  101825. encoder->private_->tell_callback = tell_callback;
  101826. encoder->private_->metadata_callback = metadata_callback;
  101827. encoder->private_->client_data = client_data;
  101828. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  101829. /* the above function sets the state for us in case of an error */
  101830. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101831. }
  101832. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  101833. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101834. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101835. }
  101836. /*
  101837. * Set up the verify stuff if necessary
  101838. */
  101839. if(encoder->protected_->verify) {
  101840. /*
  101841. * First, set up the fifo which will hold the
  101842. * original signal to compare against
  101843. */
  101844. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  101845. for(i = 0; i < encoder->protected_->channels; i++) {
  101846. if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)safe_malloc_mul_2op_(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
  101847. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101848. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101849. }
  101850. }
  101851. encoder->private_->verify.input_fifo.tail = 0;
  101852. /*
  101853. * Now set up a stream decoder for verification
  101854. */
  101855. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  101856. if(0 == encoder->private_->verify.decoder) {
  101857. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  101858. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101859. }
  101860. if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
  101861. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  101862. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101863. }
  101864. }
  101865. encoder->private_->verify.error_stats.absolute_sample = 0;
  101866. encoder->private_->verify.error_stats.frame_number = 0;
  101867. encoder->private_->verify.error_stats.channel = 0;
  101868. encoder->private_->verify.error_stats.sample = 0;
  101869. encoder->private_->verify.error_stats.expected = 0;
  101870. encoder->private_->verify.error_stats.got = 0;
  101871. /*
  101872. * These must be done before we write any metadata, because that
  101873. * calls the write_callback, which uses these values.
  101874. */
  101875. encoder->private_->first_seekpoint_to_check = 0;
  101876. encoder->private_->samples_written = 0;
  101877. encoder->protected_->streaminfo_offset = 0;
  101878. encoder->protected_->seektable_offset = 0;
  101879. encoder->protected_->audio_offset = 0;
  101880. /*
  101881. * write the stream header
  101882. */
  101883. if(encoder->protected_->verify)
  101884. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  101885. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  101886. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101887. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101888. }
  101889. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  101890. /* the above function sets the state for us in case of an error */
  101891. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101892. }
  101893. /*
  101894. * write the STREAMINFO metadata block
  101895. */
  101896. if(encoder->protected_->verify)
  101897. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  101898. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  101899. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  101900. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  101901. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  101902. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  101903. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  101904. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  101905. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  101906. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  101907. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  101908. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  101909. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  101910. if(encoder->protected_->do_md5)
  101911. FLAC__MD5Init(&encoder->private_->md5context);
  101912. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  101913. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101914. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101915. }
  101916. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  101917. /* the above function sets the state for us in case of an error */
  101918. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101919. }
  101920. /*
  101921. * Now that the STREAMINFO block is written, we can init this to an
  101922. * absurdly-high value...
  101923. */
  101924. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  101925. /* ... and clear this to 0 */
  101926. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  101927. /*
  101928. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  101929. * if not, we will write an empty one (FLAC__add_metadata_block()
  101930. * automatically supplies the vendor string).
  101931. *
  101932. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  101933. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  101934. * true it will have already insured that the metadata list is properly
  101935. * ordered.)
  101936. */
  101937. if(!metadata_has_vorbis_comment) {
  101938. FLAC__StreamMetadata vorbis_comment;
  101939. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  101940. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  101941. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  101942. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  101943. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  101944. vorbis_comment.data.vorbis_comment.num_comments = 0;
  101945. vorbis_comment.data.vorbis_comment.comments = 0;
  101946. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  101947. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101948. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101949. }
  101950. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  101951. /* the above function sets the state for us in case of an error */
  101952. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101953. }
  101954. }
  101955. /*
  101956. * write the user's metadata blocks
  101957. */
  101958. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  101959. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  101960. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  101961. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101962. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101963. }
  101964. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  101965. /* the above function sets the state for us in case of an error */
  101966. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101967. }
  101968. }
  101969. /* now that all the metadata is written, we save the stream offset */
  101970. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  101971. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101972. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101973. }
  101974. if(encoder->protected_->verify)
  101975. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  101976. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  101977. }
  101978. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  101979. FLAC__StreamEncoder *encoder,
  101980. FLAC__StreamEncoderWriteCallback write_callback,
  101981. FLAC__StreamEncoderSeekCallback seek_callback,
  101982. FLAC__StreamEncoderTellCallback tell_callback,
  101983. FLAC__StreamEncoderMetadataCallback metadata_callback,
  101984. void *client_data
  101985. )
  101986. {
  101987. return init_stream_internal_enc(
  101988. encoder,
  101989. /*read_callback=*/0,
  101990. write_callback,
  101991. seek_callback,
  101992. tell_callback,
  101993. metadata_callback,
  101994. client_data,
  101995. /*is_ogg=*/false
  101996. );
  101997. }
  101998. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  101999. FLAC__StreamEncoder *encoder,
  102000. FLAC__StreamEncoderReadCallback read_callback,
  102001. FLAC__StreamEncoderWriteCallback write_callback,
  102002. FLAC__StreamEncoderSeekCallback seek_callback,
  102003. FLAC__StreamEncoderTellCallback tell_callback,
  102004. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102005. void *client_data
  102006. )
  102007. {
  102008. return init_stream_internal_enc(
  102009. encoder,
  102010. read_callback,
  102011. write_callback,
  102012. seek_callback,
  102013. tell_callback,
  102014. metadata_callback,
  102015. client_data,
  102016. /*is_ogg=*/true
  102017. );
  102018. }
  102019. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102020. FLAC__StreamEncoder *encoder,
  102021. FILE *file,
  102022. FLAC__StreamEncoderProgressCallback progress_callback,
  102023. void *client_data,
  102024. FLAC__bool is_ogg
  102025. )
  102026. {
  102027. FLAC__StreamEncoderInitStatus init_status;
  102028. FLAC__ASSERT(0 != encoder);
  102029. FLAC__ASSERT(0 != file);
  102030. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102031. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102032. /* double protection */
  102033. if(file == 0) {
  102034. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102035. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102036. }
  102037. /*
  102038. * To make sure that our file does not go unclosed after an error, we
  102039. * must assign the FILE pointer before any further error can occur in
  102040. * this routine.
  102041. */
  102042. if(file == stdout)
  102043. file = get_binary_stdout_(); /* just to be safe */
  102044. encoder->private_->file = file;
  102045. encoder->private_->progress_callback = progress_callback;
  102046. encoder->private_->bytes_written = 0;
  102047. encoder->private_->samples_written = 0;
  102048. encoder->private_->frames_written = 0;
  102049. init_status = init_stream_internal_enc(
  102050. encoder,
  102051. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102052. file_write_callback_,
  102053. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102054. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102055. /*metadata_callback=*/0,
  102056. client_data,
  102057. is_ogg
  102058. );
  102059. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102060. /* the above function sets the state for us in case of an error */
  102061. return init_status;
  102062. }
  102063. {
  102064. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102065. FLAC__ASSERT(blocksize != 0);
  102066. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102067. }
  102068. return init_status;
  102069. }
  102070. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102071. FLAC__StreamEncoder *encoder,
  102072. FILE *file,
  102073. FLAC__StreamEncoderProgressCallback progress_callback,
  102074. void *client_data
  102075. )
  102076. {
  102077. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102078. }
  102079. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102080. FLAC__StreamEncoder *encoder,
  102081. FILE *file,
  102082. FLAC__StreamEncoderProgressCallback progress_callback,
  102083. void *client_data
  102084. )
  102085. {
  102086. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102087. }
  102088. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102089. FLAC__StreamEncoder *encoder,
  102090. const char *filename,
  102091. FLAC__StreamEncoderProgressCallback progress_callback,
  102092. void *client_data,
  102093. FLAC__bool is_ogg
  102094. )
  102095. {
  102096. FILE *file;
  102097. FLAC__ASSERT(0 != encoder);
  102098. /*
  102099. * To make sure that our file does not go unclosed after an error, we
  102100. * have to do the same entrance checks here that are later performed
  102101. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102102. */
  102103. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102104. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102105. file = filename? fopen(filename, "w+b") : stdout;
  102106. if(file == 0) {
  102107. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102108. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102109. }
  102110. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  102111. }
  102112. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  102113. FLAC__StreamEncoder *encoder,
  102114. const char *filename,
  102115. FLAC__StreamEncoderProgressCallback progress_callback,
  102116. void *client_data
  102117. )
  102118. {
  102119. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  102120. }
  102121. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  102122. FLAC__StreamEncoder *encoder,
  102123. const char *filename,
  102124. FLAC__StreamEncoderProgressCallback progress_callback,
  102125. void *client_data
  102126. )
  102127. {
  102128. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  102129. }
  102130. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  102131. {
  102132. FLAC__bool error = false;
  102133. FLAC__ASSERT(0 != encoder);
  102134. FLAC__ASSERT(0 != encoder->private_);
  102135. FLAC__ASSERT(0 != encoder->protected_);
  102136. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  102137. return true;
  102138. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  102139. if(encoder->private_->current_sample_number != 0) {
  102140. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  102141. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  102142. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  102143. error = true;
  102144. }
  102145. }
  102146. if(encoder->protected_->do_md5)
  102147. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  102148. if(!encoder->private_->is_being_deleted) {
  102149. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  102150. if(encoder->private_->seek_callback) {
  102151. #if FLAC__HAS_OGG
  102152. if(encoder->private_->is_ogg)
  102153. update_ogg_metadata_(encoder);
  102154. else
  102155. #endif
  102156. update_metadata_(encoder);
  102157. /* check if an error occurred while updating metadata */
  102158. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  102159. error = true;
  102160. }
  102161. if(encoder->private_->metadata_callback)
  102162. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  102163. }
  102164. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  102165. if(!error)
  102166. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102167. error = true;
  102168. }
  102169. }
  102170. if(0 != encoder->private_->file) {
  102171. if(encoder->private_->file != stdout)
  102172. fclose(encoder->private_->file);
  102173. encoder->private_->file = 0;
  102174. }
  102175. #if FLAC__HAS_OGG
  102176. if(encoder->private_->is_ogg)
  102177. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  102178. #endif
  102179. free_(encoder);
  102180. set_defaults_enc(encoder);
  102181. if(!error)
  102182. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102183. return !error;
  102184. }
  102185. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  102186. {
  102187. FLAC__ASSERT(0 != encoder);
  102188. FLAC__ASSERT(0 != encoder->private_);
  102189. FLAC__ASSERT(0 != encoder->protected_);
  102190. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102191. return false;
  102192. #if FLAC__HAS_OGG
  102193. /* can't check encoder->private_->is_ogg since that's not set until init time */
  102194. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  102195. return true;
  102196. #else
  102197. (void)value;
  102198. return false;
  102199. #endif
  102200. }
  102201. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102202. {
  102203. FLAC__ASSERT(0 != encoder);
  102204. FLAC__ASSERT(0 != encoder->private_);
  102205. FLAC__ASSERT(0 != encoder->protected_);
  102206. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102207. return false;
  102208. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  102209. encoder->protected_->verify = value;
  102210. #endif
  102211. return true;
  102212. }
  102213. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102214. {
  102215. FLAC__ASSERT(0 != encoder);
  102216. FLAC__ASSERT(0 != encoder->private_);
  102217. FLAC__ASSERT(0 != encoder->protected_);
  102218. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102219. return false;
  102220. encoder->protected_->streamable_subset = value;
  102221. return true;
  102222. }
  102223. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102224. {
  102225. FLAC__ASSERT(0 != encoder);
  102226. FLAC__ASSERT(0 != encoder->private_);
  102227. FLAC__ASSERT(0 != encoder->protected_);
  102228. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102229. return false;
  102230. encoder->protected_->do_md5 = value;
  102231. return true;
  102232. }
  102233. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  102234. {
  102235. FLAC__ASSERT(0 != encoder);
  102236. FLAC__ASSERT(0 != encoder->private_);
  102237. FLAC__ASSERT(0 != encoder->protected_);
  102238. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102239. return false;
  102240. encoder->protected_->channels = value;
  102241. return true;
  102242. }
  102243. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  102244. {
  102245. FLAC__ASSERT(0 != encoder);
  102246. FLAC__ASSERT(0 != encoder->private_);
  102247. FLAC__ASSERT(0 != encoder->protected_);
  102248. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102249. return false;
  102250. encoder->protected_->bits_per_sample = value;
  102251. return true;
  102252. }
  102253. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  102254. {
  102255. FLAC__ASSERT(0 != encoder);
  102256. FLAC__ASSERT(0 != encoder->private_);
  102257. FLAC__ASSERT(0 != encoder->protected_);
  102258. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102259. return false;
  102260. encoder->protected_->sample_rate = value;
  102261. return true;
  102262. }
  102263. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  102264. {
  102265. FLAC__bool ok = true;
  102266. FLAC__ASSERT(0 != encoder);
  102267. FLAC__ASSERT(0 != encoder->private_);
  102268. FLAC__ASSERT(0 != encoder->protected_);
  102269. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102270. return false;
  102271. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  102272. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  102273. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  102274. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  102275. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102276. #if 0
  102277. /* was: */
  102278. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  102279. /* but it's too hard to specify the string in a locale-specific way */
  102280. #else
  102281. encoder->protected_->num_apodizations = 1;
  102282. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102283. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102284. #endif
  102285. #endif
  102286. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  102287. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  102288. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  102289. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  102290. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  102291. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  102292. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  102293. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  102294. return ok;
  102295. }
  102296. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  102297. {
  102298. FLAC__ASSERT(0 != encoder);
  102299. FLAC__ASSERT(0 != encoder->private_);
  102300. FLAC__ASSERT(0 != encoder->protected_);
  102301. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102302. return false;
  102303. encoder->protected_->blocksize = value;
  102304. return true;
  102305. }
  102306. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102307. {
  102308. FLAC__ASSERT(0 != encoder);
  102309. FLAC__ASSERT(0 != encoder->private_);
  102310. FLAC__ASSERT(0 != encoder->protected_);
  102311. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102312. return false;
  102313. encoder->protected_->do_mid_side_stereo = value;
  102314. return true;
  102315. }
  102316. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102317. {
  102318. FLAC__ASSERT(0 != encoder);
  102319. FLAC__ASSERT(0 != encoder->private_);
  102320. FLAC__ASSERT(0 != encoder->protected_);
  102321. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102322. return false;
  102323. encoder->protected_->loose_mid_side_stereo = value;
  102324. return true;
  102325. }
  102326. /*@@@@add to tests*/
  102327. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  102328. {
  102329. FLAC__ASSERT(0 != encoder);
  102330. FLAC__ASSERT(0 != encoder->private_);
  102331. FLAC__ASSERT(0 != encoder->protected_);
  102332. FLAC__ASSERT(0 != specification);
  102333. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102334. return false;
  102335. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  102336. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  102337. #else
  102338. encoder->protected_->num_apodizations = 0;
  102339. while(1) {
  102340. const char *s = strchr(specification, ';');
  102341. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  102342. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  102343. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  102344. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  102345. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  102346. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  102347. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  102348. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  102349. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  102350. else if(n==6 && 0 == strncmp("connes" , specification, n))
  102351. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  102352. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  102353. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  102354. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  102355. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  102356. if (stddev > 0.0 && stddev <= 0.5) {
  102357. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  102358. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  102359. }
  102360. }
  102361. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  102362. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  102363. else if(n==4 && 0 == strncmp("hann" , specification, n))
  102364. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  102365. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  102366. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  102367. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  102368. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  102369. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  102370. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  102371. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  102372. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  102373. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  102374. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  102375. if (p >= 0.0 && p <= 1.0) {
  102376. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  102377. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  102378. }
  102379. }
  102380. else if(n==5 && 0 == strncmp("welch" , specification, n))
  102381. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  102382. if (encoder->protected_->num_apodizations == 32)
  102383. break;
  102384. if (s)
  102385. specification = s+1;
  102386. else
  102387. break;
  102388. }
  102389. if(encoder->protected_->num_apodizations == 0) {
  102390. encoder->protected_->num_apodizations = 1;
  102391. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102392. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102393. }
  102394. #endif
  102395. return true;
  102396. }
  102397. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  102398. {
  102399. FLAC__ASSERT(0 != encoder);
  102400. FLAC__ASSERT(0 != encoder->private_);
  102401. FLAC__ASSERT(0 != encoder->protected_);
  102402. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102403. return false;
  102404. encoder->protected_->max_lpc_order = value;
  102405. return true;
  102406. }
  102407. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  102408. {
  102409. FLAC__ASSERT(0 != encoder);
  102410. FLAC__ASSERT(0 != encoder->private_);
  102411. FLAC__ASSERT(0 != encoder->protected_);
  102412. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102413. return false;
  102414. encoder->protected_->qlp_coeff_precision = value;
  102415. return true;
  102416. }
  102417. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102418. {
  102419. FLAC__ASSERT(0 != encoder);
  102420. FLAC__ASSERT(0 != encoder->private_);
  102421. FLAC__ASSERT(0 != encoder->protected_);
  102422. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102423. return false;
  102424. encoder->protected_->do_qlp_coeff_prec_search = value;
  102425. return true;
  102426. }
  102427. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102428. {
  102429. FLAC__ASSERT(0 != encoder);
  102430. FLAC__ASSERT(0 != encoder->private_);
  102431. FLAC__ASSERT(0 != encoder->protected_);
  102432. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102433. return false;
  102434. #if 0
  102435. /*@@@ deprecated: */
  102436. encoder->protected_->do_escape_coding = value;
  102437. #else
  102438. (void)value;
  102439. #endif
  102440. return true;
  102441. }
  102442. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102443. {
  102444. FLAC__ASSERT(0 != encoder);
  102445. FLAC__ASSERT(0 != encoder->private_);
  102446. FLAC__ASSERT(0 != encoder->protected_);
  102447. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102448. return false;
  102449. encoder->protected_->do_exhaustive_model_search = value;
  102450. return true;
  102451. }
  102452. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  102453. {
  102454. FLAC__ASSERT(0 != encoder);
  102455. FLAC__ASSERT(0 != encoder->private_);
  102456. FLAC__ASSERT(0 != encoder->protected_);
  102457. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102458. return false;
  102459. encoder->protected_->min_residual_partition_order = value;
  102460. return true;
  102461. }
  102462. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  102463. {
  102464. FLAC__ASSERT(0 != encoder);
  102465. FLAC__ASSERT(0 != encoder->private_);
  102466. FLAC__ASSERT(0 != encoder->protected_);
  102467. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102468. return false;
  102469. encoder->protected_->max_residual_partition_order = value;
  102470. return true;
  102471. }
  102472. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  102473. {
  102474. FLAC__ASSERT(0 != encoder);
  102475. FLAC__ASSERT(0 != encoder->private_);
  102476. FLAC__ASSERT(0 != encoder->protected_);
  102477. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102478. return false;
  102479. #if 0
  102480. /*@@@ deprecated: */
  102481. encoder->protected_->rice_parameter_search_dist = value;
  102482. #else
  102483. (void)value;
  102484. #endif
  102485. return true;
  102486. }
  102487. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  102488. {
  102489. FLAC__ASSERT(0 != encoder);
  102490. FLAC__ASSERT(0 != encoder->private_);
  102491. FLAC__ASSERT(0 != encoder->protected_);
  102492. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102493. return false;
  102494. encoder->protected_->total_samples_estimate = value;
  102495. return true;
  102496. }
  102497. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  102498. {
  102499. FLAC__ASSERT(0 != encoder);
  102500. FLAC__ASSERT(0 != encoder->private_);
  102501. FLAC__ASSERT(0 != encoder->protected_);
  102502. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102503. return false;
  102504. if(0 == metadata)
  102505. num_blocks = 0;
  102506. if(0 == num_blocks)
  102507. metadata = 0;
  102508. /* realloc() does not do exactly what we want so... */
  102509. if(encoder->protected_->metadata) {
  102510. free(encoder->protected_->metadata);
  102511. encoder->protected_->metadata = 0;
  102512. encoder->protected_->num_metadata_blocks = 0;
  102513. }
  102514. if(num_blocks) {
  102515. FLAC__StreamMetadata **m;
  102516. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  102517. return false;
  102518. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  102519. encoder->protected_->metadata = m;
  102520. encoder->protected_->num_metadata_blocks = num_blocks;
  102521. }
  102522. #if FLAC__HAS_OGG
  102523. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  102524. return false;
  102525. #endif
  102526. return true;
  102527. }
  102528. /*
  102529. * These three functions are not static, but not publically exposed in
  102530. * include/FLAC/ either. They are used by the test suite.
  102531. */
  102532. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102533. {
  102534. FLAC__ASSERT(0 != encoder);
  102535. FLAC__ASSERT(0 != encoder->private_);
  102536. FLAC__ASSERT(0 != encoder->protected_);
  102537. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102538. return false;
  102539. encoder->private_->disable_constant_subframes = value;
  102540. return true;
  102541. }
  102542. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102543. {
  102544. FLAC__ASSERT(0 != encoder);
  102545. FLAC__ASSERT(0 != encoder->private_);
  102546. FLAC__ASSERT(0 != encoder->protected_);
  102547. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102548. return false;
  102549. encoder->private_->disable_fixed_subframes = value;
  102550. return true;
  102551. }
  102552. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102553. {
  102554. FLAC__ASSERT(0 != encoder);
  102555. FLAC__ASSERT(0 != encoder->private_);
  102556. FLAC__ASSERT(0 != encoder->protected_);
  102557. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102558. return false;
  102559. encoder->private_->disable_verbatim_subframes = value;
  102560. return true;
  102561. }
  102562. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  102563. {
  102564. FLAC__ASSERT(0 != encoder);
  102565. FLAC__ASSERT(0 != encoder->private_);
  102566. FLAC__ASSERT(0 != encoder->protected_);
  102567. return encoder->protected_->state;
  102568. }
  102569. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  102570. {
  102571. FLAC__ASSERT(0 != encoder);
  102572. FLAC__ASSERT(0 != encoder->private_);
  102573. FLAC__ASSERT(0 != encoder->protected_);
  102574. if(encoder->protected_->verify)
  102575. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  102576. else
  102577. return FLAC__STREAM_DECODER_UNINITIALIZED;
  102578. }
  102579. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  102580. {
  102581. FLAC__ASSERT(0 != encoder);
  102582. FLAC__ASSERT(0 != encoder->private_);
  102583. FLAC__ASSERT(0 != encoder->protected_);
  102584. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  102585. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  102586. else
  102587. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  102588. }
  102589. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
  102590. {
  102591. FLAC__ASSERT(0 != encoder);
  102592. FLAC__ASSERT(0 != encoder->private_);
  102593. FLAC__ASSERT(0 != encoder->protected_);
  102594. if(0 != absolute_sample)
  102595. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  102596. if(0 != frame_number)
  102597. *frame_number = encoder->private_->verify.error_stats.frame_number;
  102598. if(0 != channel)
  102599. *channel = encoder->private_->verify.error_stats.channel;
  102600. if(0 != sample)
  102601. *sample = encoder->private_->verify.error_stats.sample;
  102602. if(0 != expected)
  102603. *expected = encoder->private_->verify.error_stats.expected;
  102604. if(0 != got)
  102605. *got = encoder->private_->verify.error_stats.got;
  102606. }
  102607. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  102608. {
  102609. FLAC__ASSERT(0 != encoder);
  102610. FLAC__ASSERT(0 != encoder->private_);
  102611. FLAC__ASSERT(0 != encoder->protected_);
  102612. return encoder->protected_->verify;
  102613. }
  102614. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  102615. {
  102616. FLAC__ASSERT(0 != encoder);
  102617. FLAC__ASSERT(0 != encoder->private_);
  102618. FLAC__ASSERT(0 != encoder->protected_);
  102619. return encoder->protected_->streamable_subset;
  102620. }
  102621. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  102622. {
  102623. FLAC__ASSERT(0 != encoder);
  102624. FLAC__ASSERT(0 != encoder->private_);
  102625. FLAC__ASSERT(0 != encoder->protected_);
  102626. return encoder->protected_->do_md5;
  102627. }
  102628. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  102629. {
  102630. FLAC__ASSERT(0 != encoder);
  102631. FLAC__ASSERT(0 != encoder->private_);
  102632. FLAC__ASSERT(0 != encoder->protected_);
  102633. return encoder->protected_->channels;
  102634. }
  102635. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  102636. {
  102637. FLAC__ASSERT(0 != encoder);
  102638. FLAC__ASSERT(0 != encoder->private_);
  102639. FLAC__ASSERT(0 != encoder->protected_);
  102640. return encoder->protected_->bits_per_sample;
  102641. }
  102642. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  102643. {
  102644. FLAC__ASSERT(0 != encoder);
  102645. FLAC__ASSERT(0 != encoder->private_);
  102646. FLAC__ASSERT(0 != encoder->protected_);
  102647. return encoder->protected_->sample_rate;
  102648. }
  102649. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  102650. {
  102651. FLAC__ASSERT(0 != encoder);
  102652. FLAC__ASSERT(0 != encoder->private_);
  102653. FLAC__ASSERT(0 != encoder->protected_);
  102654. return encoder->protected_->blocksize;
  102655. }
  102656. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  102657. {
  102658. FLAC__ASSERT(0 != encoder);
  102659. FLAC__ASSERT(0 != encoder->private_);
  102660. FLAC__ASSERT(0 != encoder->protected_);
  102661. return encoder->protected_->do_mid_side_stereo;
  102662. }
  102663. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  102664. {
  102665. FLAC__ASSERT(0 != encoder);
  102666. FLAC__ASSERT(0 != encoder->private_);
  102667. FLAC__ASSERT(0 != encoder->protected_);
  102668. return encoder->protected_->loose_mid_side_stereo;
  102669. }
  102670. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  102671. {
  102672. FLAC__ASSERT(0 != encoder);
  102673. FLAC__ASSERT(0 != encoder->private_);
  102674. FLAC__ASSERT(0 != encoder->protected_);
  102675. return encoder->protected_->max_lpc_order;
  102676. }
  102677. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  102678. {
  102679. FLAC__ASSERT(0 != encoder);
  102680. FLAC__ASSERT(0 != encoder->private_);
  102681. FLAC__ASSERT(0 != encoder->protected_);
  102682. return encoder->protected_->qlp_coeff_precision;
  102683. }
  102684. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  102685. {
  102686. FLAC__ASSERT(0 != encoder);
  102687. FLAC__ASSERT(0 != encoder->private_);
  102688. FLAC__ASSERT(0 != encoder->protected_);
  102689. return encoder->protected_->do_qlp_coeff_prec_search;
  102690. }
  102691. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  102692. {
  102693. FLAC__ASSERT(0 != encoder);
  102694. FLAC__ASSERT(0 != encoder->private_);
  102695. FLAC__ASSERT(0 != encoder->protected_);
  102696. return encoder->protected_->do_escape_coding;
  102697. }
  102698. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  102699. {
  102700. FLAC__ASSERT(0 != encoder);
  102701. FLAC__ASSERT(0 != encoder->private_);
  102702. FLAC__ASSERT(0 != encoder->protected_);
  102703. return encoder->protected_->do_exhaustive_model_search;
  102704. }
  102705. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  102706. {
  102707. FLAC__ASSERT(0 != encoder);
  102708. FLAC__ASSERT(0 != encoder->private_);
  102709. FLAC__ASSERT(0 != encoder->protected_);
  102710. return encoder->protected_->min_residual_partition_order;
  102711. }
  102712. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  102713. {
  102714. FLAC__ASSERT(0 != encoder);
  102715. FLAC__ASSERT(0 != encoder->private_);
  102716. FLAC__ASSERT(0 != encoder->protected_);
  102717. return encoder->protected_->max_residual_partition_order;
  102718. }
  102719. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  102720. {
  102721. FLAC__ASSERT(0 != encoder);
  102722. FLAC__ASSERT(0 != encoder->private_);
  102723. FLAC__ASSERT(0 != encoder->protected_);
  102724. return encoder->protected_->rice_parameter_search_dist;
  102725. }
  102726. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  102727. {
  102728. FLAC__ASSERT(0 != encoder);
  102729. FLAC__ASSERT(0 != encoder->private_);
  102730. FLAC__ASSERT(0 != encoder->protected_);
  102731. return encoder->protected_->total_samples_estimate;
  102732. }
  102733. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  102734. {
  102735. unsigned i, j = 0, channel;
  102736. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  102737. FLAC__ASSERT(0 != encoder);
  102738. FLAC__ASSERT(0 != encoder->private_);
  102739. FLAC__ASSERT(0 != encoder->protected_);
  102740. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  102741. do {
  102742. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  102743. if(encoder->protected_->verify)
  102744. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  102745. for(channel = 0; channel < channels; channel++)
  102746. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  102747. if(encoder->protected_->do_mid_side_stereo) {
  102748. FLAC__ASSERT(channels == 2);
  102749. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  102750. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  102751. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  102752. encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
  102753. }
  102754. }
  102755. else
  102756. j += n;
  102757. encoder->private_->current_sample_number += n;
  102758. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  102759. if(encoder->private_->current_sample_number > blocksize) {
  102760. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  102761. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  102762. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  102763. return false;
  102764. /* move unprocessed overread samples to beginnings of arrays */
  102765. for(channel = 0; channel < channels; channel++)
  102766. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  102767. if(encoder->protected_->do_mid_side_stereo) {
  102768. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  102769. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  102770. }
  102771. encoder->private_->current_sample_number = 1;
  102772. }
  102773. } while(j < samples);
  102774. return true;
  102775. }
  102776. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  102777. {
  102778. unsigned i, j, k, channel;
  102779. FLAC__int32 x, mid, side;
  102780. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  102781. FLAC__ASSERT(0 != encoder);
  102782. FLAC__ASSERT(0 != encoder->private_);
  102783. FLAC__ASSERT(0 != encoder->protected_);
  102784. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  102785. j = k = 0;
  102786. /*
  102787. * we have several flavors of the same basic loop, optimized for
  102788. * different conditions:
  102789. */
  102790. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  102791. /*
  102792. * stereo coding: unroll channel loop
  102793. */
  102794. do {
  102795. if(encoder->protected_->verify)
  102796. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  102797. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  102798. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  102799. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  102800. x = buffer[k++];
  102801. encoder->private_->integer_signal[1][i] = x;
  102802. mid += x;
  102803. side -= x;
  102804. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  102805. encoder->private_->integer_signal_mid_side[1][i] = side;
  102806. encoder->private_->integer_signal_mid_side[0][i] = mid;
  102807. }
  102808. encoder->private_->current_sample_number = i;
  102809. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  102810. if(i > blocksize) {
  102811. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  102812. return false;
  102813. /* move unprocessed overread samples to beginnings of arrays */
  102814. FLAC__ASSERT(i == blocksize+OVERREAD_);
  102815. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  102816. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  102817. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  102818. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  102819. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  102820. encoder->private_->current_sample_number = 1;
  102821. }
  102822. } while(j < samples);
  102823. }
  102824. else {
  102825. /*
  102826. * independent channel coding: buffer each channel in inner loop
  102827. */
  102828. do {
  102829. if(encoder->protected_->verify)
  102830. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  102831. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  102832. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  102833. for(channel = 0; channel < channels; channel++)
  102834. encoder->private_->integer_signal[channel][i] = buffer[k++];
  102835. }
  102836. encoder->private_->current_sample_number = i;
  102837. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  102838. if(i > blocksize) {
  102839. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  102840. return false;
  102841. /* move unprocessed overread samples to beginnings of arrays */
  102842. FLAC__ASSERT(i == blocksize+OVERREAD_);
  102843. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  102844. for(channel = 0; channel < channels; channel++)
  102845. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  102846. encoder->private_->current_sample_number = 1;
  102847. }
  102848. } while(j < samples);
  102849. }
  102850. return true;
  102851. }
  102852. /***********************************************************************
  102853. *
  102854. * Private class methods
  102855. *
  102856. ***********************************************************************/
  102857. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  102858. {
  102859. FLAC__ASSERT(0 != encoder);
  102860. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  102861. encoder->protected_->verify = true;
  102862. #else
  102863. encoder->protected_->verify = false;
  102864. #endif
  102865. encoder->protected_->streamable_subset = true;
  102866. encoder->protected_->do_md5 = true;
  102867. encoder->protected_->do_mid_side_stereo = false;
  102868. encoder->protected_->loose_mid_side_stereo = false;
  102869. encoder->protected_->channels = 2;
  102870. encoder->protected_->bits_per_sample = 16;
  102871. encoder->protected_->sample_rate = 44100;
  102872. encoder->protected_->blocksize = 0;
  102873. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102874. encoder->protected_->num_apodizations = 1;
  102875. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102876. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102877. #endif
  102878. encoder->protected_->max_lpc_order = 0;
  102879. encoder->protected_->qlp_coeff_precision = 0;
  102880. encoder->protected_->do_qlp_coeff_prec_search = false;
  102881. encoder->protected_->do_exhaustive_model_search = false;
  102882. encoder->protected_->do_escape_coding = false;
  102883. encoder->protected_->min_residual_partition_order = 0;
  102884. encoder->protected_->max_residual_partition_order = 0;
  102885. encoder->protected_->rice_parameter_search_dist = 0;
  102886. encoder->protected_->total_samples_estimate = 0;
  102887. encoder->protected_->metadata = 0;
  102888. encoder->protected_->num_metadata_blocks = 0;
  102889. encoder->private_->seek_table = 0;
  102890. encoder->private_->disable_constant_subframes = false;
  102891. encoder->private_->disable_fixed_subframes = false;
  102892. encoder->private_->disable_verbatim_subframes = false;
  102893. #if FLAC__HAS_OGG
  102894. encoder->private_->is_ogg = false;
  102895. #endif
  102896. encoder->private_->read_callback = 0;
  102897. encoder->private_->write_callback = 0;
  102898. encoder->private_->seek_callback = 0;
  102899. encoder->private_->tell_callback = 0;
  102900. encoder->private_->metadata_callback = 0;
  102901. encoder->private_->progress_callback = 0;
  102902. encoder->private_->client_data = 0;
  102903. #if FLAC__HAS_OGG
  102904. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  102905. #endif
  102906. }
  102907. void free_(FLAC__StreamEncoder *encoder)
  102908. {
  102909. unsigned i, channel;
  102910. FLAC__ASSERT(0 != encoder);
  102911. if(encoder->protected_->metadata) {
  102912. free(encoder->protected_->metadata);
  102913. encoder->protected_->metadata = 0;
  102914. encoder->protected_->num_metadata_blocks = 0;
  102915. }
  102916. for(i = 0; i < encoder->protected_->channels; i++) {
  102917. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  102918. free(encoder->private_->integer_signal_unaligned[i]);
  102919. encoder->private_->integer_signal_unaligned[i] = 0;
  102920. }
  102921. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102922. if(0 != encoder->private_->real_signal_unaligned[i]) {
  102923. free(encoder->private_->real_signal_unaligned[i]);
  102924. encoder->private_->real_signal_unaligned[i] = 0;
  102925. }
  102926. #endif
  102927. }
  102928. for(i = 0; i < 2; i++) {
  102929. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  102930. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  102931. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  102932. }
  102933. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102934. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  102935. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  102936. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  102937. }
  102938. #endif
  102939. }
  102940. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102941. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  102942. if(0 != encoder->private_->window_unaligned[i]) {
  102943. free(encoder->private_->window_unaligned[i]);
  102944. encoder->private_->window_unaligned[i] = 0;
  102945. }
  102946. }
  102947. if(0 != encoder->private_->windowed_signal_unaligned) {
  102948. free(encoder->private_->windowed_signal_unaligned);
  102949. encoder->private_->windowed_signal_unaligned = 0;
  102950. }
  102951. #endif
  102952. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  102953. for(i = 0; i < 2; i++) {
  102954. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  102955. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  102956. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  102957. }
  102958. }
  102959. }
  102960. for(channel = 0; channel < 2; channel++) {
  102961. for(i = 0; i < 2; i++) {
  102962. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  102963. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  102964. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  102965. }
  102966. }
  102967. }
  102968. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  102969. free(encoder->private_->abs_residual_partition_sums_unaligned);
  102970. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  102971. }
  102972. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  102973. free(encoder->private_->raw_bits_per_partition_unaligned);
  102974. encoder->private_->raw_bits_per_partition_unaligned = 0;
  102975. }
  102976. if(encoder->protected_->verify) {
  102977. for(i = 0; i < encoder->protected_->channels; i++) {
  102978. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  102979. free(encoder->private_->verify.input_fifo.data[i]);
  102980. encoder->private_->verify.input_fifo.data[i] = 0;
  102981. }
  102982. }
  102983. }
  102984. FLAC__bitwriter_free(encoder->private_->frame);
  102985. }
  102986. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  102987. {
  102988. FLAC__bool ok;
  102989. unsigned i, channel;
  102990. FLAC__ASSERT(new_blocksize > 0);
  102991. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  102992. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  102993. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  102994. if(new_blocksize <= encoder->private_->input_capacity)
  102995. return true;
  102996. ok = true;
  102997. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  102998. * requires that the input arrays (in our case the integer signals)
  102999. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103000. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103001. */
  103002. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103003. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103004. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103005. encoder->private_->integer_signal[i] += 4;
  103006. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103007. #if 0 /* @@@ currently unused */
  103008. if(encoder->protected_->max_lpc_order > 0)
  103009. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103010. #endif
  103011. #endif
  103012. }
  103013. for(i = 0; ok && i < 2; i++) {
  103014. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
  103015. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103016. encoder->private_->integer_signal_mid_side[i] += 4;
  103017. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103018. #if 0 /* @@@ currently unused */
  103019. if(encoder->protected_->max_lpc_order > 0)
  103020. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
  103021. #endif
  103022. #endif
  103023. }
  103024. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103025. if(ok && encoder->protected_->max_lpc_order > 0) {
  103026. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103027. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103028. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103029. }
  103030. #endif
  103031. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103032. for(i = 0; ok && i < 2; i++) {
  103033. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103034. }
  103035. }
  103036. for(channel = 0; ok && channel < 2; channel++) {
  103037. for(i = 0; ok && i < 2; i++) {
  103038. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
  103039. }
  103040. }
  103041. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103042. /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
  103043. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103044. if(encoder->protected_->do_escape_coding)
  103045. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103046. /* now adjust the windows if the blocksize has changed */
  103047. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103048. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103049. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103050. switch(encoder->protected_->apodizations[i].type) {
  103051. case FLAC__APODIZATION_BARTLETT:
  103052. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103053. break;
  103054. case FLAC__APODIZATION_BARTLETT_HANN:
  103055. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103056. break;
  103057. case FLAC__APODIZATION_BLACKMAN:
  103058. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103059. break;
  103060. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103061. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103062. break;
  103063. case FLAC__APODIZATION_CONNES:
  103064. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103065. break;
  103066. case FLAC__APODIZATION_FLATTOP:
  103067. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103068. break;
  103069. case FLAC__APODIZATION_GAUSS:
  103070. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103071. break;
  103072. case FLAC__APODIZATION_HAMMING:
  103073. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103074. break;
  103075. case FLAC__APODIZATION_HANN:
  103076. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103077. break;
  103078. case FLAC__APODIZATION_KAISER_BESSEL:
  103079. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103080. break;
  103081. case FLAC__APODIZATION_NUTTALL:
  103082. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103083. break;
  103084. case FLAC__APODIZATION_RECTANGLE:
  103085. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103086. break;
  103087. case FLAC__APODIZATION_TRIANGLE:
  103088. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103089. break;
  103090. case FLAC__APODIZATION_TUKEY:
  103091. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103092. break;
  103093. case FLAC__APODIZATION_WELCH:
  103094. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103095. break;
  103096. default:
  103097. FLAC__ASSERT(0);
  103098. /* double protection */
  103099. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103100. break;
  103101. }
  103102. }
  103103. }
  103104. #endif
  103105. if(ok)
  103106. encoder->private_->input_capacity = new_blocksize;
  103107. else
  103108. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103109. return ok;
  103110. }
  103111. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  103112. {
  103113. const FLAC__byte *buffer;
  103114. size_t bytes;
  103115. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103116. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  103117. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103118. return false;
  103119. }
  103120. if(encoder->protected_->verify) {
  103121. encoder->private_->verify.output.data = buffer;
  103122. encoder->private_->verify.output.bytes = bytes;
  103123. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  103124. encoder->private_->verify.needs_magic_hack = true;
  103125. }
  103126. else {
  103127. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  103128. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103129. FLAC__bitwriter_clear(encoder->private_->frame);
  103130. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  103131. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103132. return false;
  103133. }
  103134. }
  103135. }
  103136. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103137. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103138. FLAC__bitwriter_clear(encoder->private_->frame);
  103139. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103140. return false;
  103141. }
  103142. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103143. FLAC__bitwriter_clear(encoder->private_->frame);
  103144. if(samples > 0) {
  103145. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  103146. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  103147. }
  103148. return true;
  103149. }
  103150. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  103151. {
  103152. FLAC__StreamEncoderWriteStatus status;
  103153. FLAC__uint64 output_position = 0;
  103154. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  103155. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  103156. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103157. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103158. }
  103159. /*
  103160. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  103161. */
  103162. if(samples == 0) {
  103163. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  103164. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  103165. encoder->protected_->streaminfo_offset = output_position;
  103166. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  103167. encoder->protected_->seektable_offset = output_position;
  103168. }
  103169. /*
  103170. * Mark the current seek point if hit (if audio_offset == 0 that
  103171. * means we're still writing metadata and haven't hit the first
  103172. * frame yet)
  103173. */
  103174. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  103175. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103176. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  103177. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  103178. FLAC__uint64 test_sample;
  103179. unsigned i;
  103180. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  103181. test_sample = encoder->private_->seek_table->points[i].sample_number;
  103182. if(test_sample > frame_last_sample) {
  103183. break;
  103184. }
  103185. else if(test_sample >= frame_first_sample) {
  103186. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  103187. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  103188. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  103189. encoder->private_->first_seekpoint_to_check++;
  103190. /* DO NOT: "break;" and here's why:
  103191. * The seektable template may contain more than one target
  103192. * sample for any given frame; we will keep looping, generating
  103193. * duplicate seekpoints for them, and we'll clean it up later,
  103194. * just before writing the seektable back to the metadata.
  103195. */
  103196. }
  103197. else {
  103198. encoder->private_->first_seekpoint_to_check++;
  103199. }
  103200. }
  103201. }
  103202. #if FLAC__HAS_OGG
  103203. if(encoder->private_->is_ogg) {
  103204. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  103205. &encoder->protected_->ogg_encoder_aspect,
  103206. buffer,
  103207. bytes,
  103208. samples,
  103209. encoder->private_->current_frame_number,
  103210. is_last_block,
  103211. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  103212. encoder,
  103213. encoder->private_->client_data
  103214. );
  103215. }
  103216. else
  103217. #endif
  103218. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  103219. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103220. encoder->private_->bytes_written += bytes;
  103221. encoder->private_->samples_written += samples;
  103222. /* we keep a high watermark on the number of frames written because
  103223. * when the encoder goes back to write metadata, 'current_frame'
  103224. * will drop back to 0.
  103225. */
  103226. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  103227. }
  103228. else
  103229. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103230. return status;
  103231. }
  103232. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103233. void update_metadata_(const FLAC__StreamEncoder *encoder)
  103234. {
  103235. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103236. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103237. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103238. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103239. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103240. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  103241. FLAC__StreamEncoderSeekStatus seek_status;
  103242. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103243. /* All this is based on intimate knowledge of the stream header
  103244. * layout, but a change to the header format that would break this
  103245. * would also break all streams encoded in the previous format.
  103246. */
  103247. /*
  103248. * Write MD5 signature
  103249. */
  103250. {
  103251. const unsigned md5_offset =
  103252. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103253. (
  103254. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103255. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103256. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103257. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103258. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103259. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103260. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103261. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103262. ) / 8;
  103263. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103264. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103265. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103266. return;
  103267. }
  103268. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103269. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103270. return;
  103271. }
  103272. }
  103273. /*
  103274. * Write total samples
  103275. */
  103276. {
  103277. const unsigned total_samples_byte_offset =
  103278. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103279. (
  103280. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103281. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103282. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103283. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103284. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103285. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103286. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103287. - 4
  103288. ) / 8;
  103289. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  103290. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103291. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103292. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103293. b[4] = (FLAC__byte)(samples & 0xFF);
  103294. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + total_samples_byte_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103295. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103296. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103297. return;
  103298. }
  103299. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103300. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103301. return;
  103302. }
  103303. }
  103304. /*
  103305. * Write min/max framesize
  103306. */
  103307. {
  103308. const unsigned min_framesize_offset =
  103309. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103310. (
  103311. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103312. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103313. ) / 8;
  103314. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103315. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103316. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103317. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103318. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103319. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103320. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + min_framesize_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103321. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103322. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103323. return;
  103324. }
  103325. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103326. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103327. return;
  103328. }
  103329. }
  103330. /*
  103331. * Write seektable
  103332. */
  103333. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103334. unsigned i;
  103335. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103336. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103337. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->seektable_offset + FLAC__STREAM_METADATA_HEADER_LENGTH, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103338. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103339. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103340. return;
  103341. }
  103342. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  103343. FLAC__uint64 xx;
  103344. unsigned x;
  103345. xx = encoder->private_->seek_table->points[i].sample_number;
  103346. b[7] = (FLAC__byte)xx; xx >>= 8;
  103347. b[6] = (FLAC__byte)xx; xx >>= 8;
  103348. b[5] = (FLAC__byte)xx; xx >>= 8;
  103349. b[4] = (FLAC__byte)xx; xx >>= 8;
  103350. b[3] = (FLAC__byte)xx; xx >>= 8;
  103351. b[2] = (FLAC__byte)xx; xx >>= 8;
  103352. b[1] = (FLAC__byte)xx; xx >>= 8;
  103353. b[0] = (FLAC__byte)xx; xx >>= 8;
  103354. xx = encoder->private_->seek_table->points[i].stream_offset;
  103355. b[15] = (FLAC__byte)xx; xx >>= 8;
  103356. b[14] = (FLAC__byte)xx; xx >>= 8;
  103357. b[13] = (FLAC__byte)xx; xx >>= 8;
  103358. b[12] = (FLAC__byte)xx; xx >>= 8;
  103359. b[11] = (FLAC__byte)xx; xx >>= 8;
  103360. b[10] = (FLAC__byte)xx; xx >>= 8;
  103361. b[9] = (FLAC__byte)xx; xx >>= 8;
  103362. b[8] = (FLAC__byte)xx; xx >>= 8;
  103363. x = encoder->private_->seek_table->points[i].frame_samples;
  103364. b[17] = (FLAC__byte)x; x >>= 8;
  103365. b[16] = (FLAC__byte)x; x >>= 8;
  103366. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103367. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103368. return;
  103369. }
  103370. }
  103371. }
  103372. }
  103373. #if FLAC__HAS_OGG
  103374. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103375. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  103376. {
  103377. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  103378. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  103379. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  103380. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  103381. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  103382. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  103383. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  103384. FLAC__STREAM_SYNC_LENGTH
  103385. ;
  103386. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103387. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103388. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103389. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103390. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103391. ogg_page page;
  103392. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103393. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  103394. /* Pre-check that client supports seeking, since we don't want the
  103395. * ogg_helper code to ever have to deal with this condition.
  103396. */
  103397. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  103398. return;
  103399. /* All this is based on intimate knowledge of the stream header
  103400. * layout, but a change to the header format that would break this
  103401. * would also break all streams encoded in the previous format.
  103402. */
  103403. /**
  103404. ** Write STREAMINFO stats
  103405. **/
  103406. simple_ogg_page__init(&page);
  103407. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  103408. simple_ogg_page__clear(&page);
  103409. return; /* state already set */
  103410. }
  103411. /*
  103412. * Write MD5 signature
  103413. */
  103414. {
  103415. const unsigned md5_offset =
  103416. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103417. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103418. (
  103419. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103420. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103421. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103422. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103423. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103424. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103425. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103426. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103427. ) / 8;
  103428. if(md5_offset + 16 > (unsigned)page.body_len) {
  103429. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103430. simple_ogg_page__clear(&page);
  103431. return;
  103432. }
  103433. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  103434. }
  103435. /*
  103436. * Write total samples
  103437. */
  103438. {
  103439. const unsigned total_samples_byte_offset =
  103440. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103441. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103442. (
  103443. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103444. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103445. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103446. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103447. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103448. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103449. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103450. - 4
  103451. ) / 8;
  103452. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  103453. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103454. simple_ogg_page__clear(&page);
  103455. return;
  103456. }
  103457. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  103458. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  103459. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103460. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103461. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103462. b[4] = (FLAC__byte)(samples & 0xFF);
  103463. memcpy(page.body + total_samples_byte_offset, b, 5);
  103464. }
  103465. /*
  103466. * Write min/max framesize
  103467. */
  103468. {
  103469. const unsigned min_framesize_offset =
  103470. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103471. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103472. (
  103473. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103474. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103475. ) / 8;
  103476. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  103477. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103478. simple_ogg_page__clear(&page);
  103479. return;
  103480. }
  103481. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103482. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103483. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103484. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103485. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103486. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103487. memcpy(page.body + min_framesize_offset, b, 6);
  103488. }
  103489. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  103490. simple_ogg_page__clear(&page);
  103491. return; /* state already set */
  103492. }
  103493. simple_ogg_page__clear(&page);
  103494. /*
  103495. * Write seektable
  103496. */
  103497. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103498. unsigned i;
  103499. FLAC__byte *p;
  103500. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103501. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103502. simple_ogg_page__init(&page);
  103503. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  103504. simple_ogg_page__clear(&page);
  103505. return; /* state already set */
  103506. }
  103507. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  103508. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103509. simple_ogg_page__clear(&page);
  103510. return;
  103511. }
  103512. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  103513. FLAC__uint64 xx;
  103514. unsigned x;
  103515. xx = encoder->private_->seek_table->points[i].sample_number;
  103516. b[7] = (FLAC__byte)xx; xx >>= 8;
  103517. b[6] = (FLAC__byte)xx; xx >>= 8;
  103518. b[5] = (FLAC__byte)xx; xx >>= 8;
  103519. b[4] = (FLAC__byte)xx; xx >>= 8;
  103520. b[3] = (FLAC__byte)xx; xx >>= 8;
  103521. b[2] = (FLAC__byte)xx; xx >>= 8;
  103522. b[1] = (FLAC__byte)xx; xx >>= 8;
  103523. b[0] = (FLAC__byte)xx; xx >>= 8;
  103524. xx = encoder->private_->seek_table->points[i].stream_offset;
  103525. b[15] = (FLAC__byte)xx; xx >>= 8;
  103526. b[14] = (FLAC__byte)xx; xx >>= 8;
  103527. b[13] = (FLAC__byte)xx; xx >>= 8;
  103528. b[12] = (FLAC__byte)xx; xx >>= 8;
  103529. b[11] = (FLAC__byte)xx; xx >>= 8;
  103530. b[10] = (FLAC__byte)xx; xx >>= 8;
  103531. b[9] = (FLAC__byte)xx; xx >>= 8;
  103532. b[8] = (FLAC__byte)xx; xx >>= 8;
  103533. x = encoder->private_->seek_table->points[i].frame_samples;
  103534. b[17] = (FLAC__byte)x; x >>= 8;
  103535. b[16] = (FLAC__byte)x; x >>= 8;
  103536. memcpy(p, b, 18);
  103537. }
  103538. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  103539. simple_ogg_page__clear(&page);
  103540. return; /* state already set */
  103541. }
  103542. simple_ogg_page__clear(&page);
  103543. }
  103544. }
  103545. #endif
  103546. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  103547. {
  103548. FLAC__uint16 crc;
  103549. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103550. /*
  103551. * Accumulate raw signal to the MD5 signature
  103552. */
  103553. if(encoder->protected_->do_md5 && !FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
  103554. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103555. return false;
  103556. }
  103557. /*
  103558. * Process the frame header and subframes into the frame bitbuffer
  103559. */
  103560. if(!process_subframes_(encoder, is_fractional_block)) {
  103561. /* the above function sets the state for us in case of an error */
  103562. return false;
  103563. }
  103564. /*
  103565. * Zero-pad the frame to a byte_boundary
  103566. */
  103567. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  103568. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103569. return false;
  103570. }
  103571. /*
  103572. * CRC-16 the whole thing
  103573. */
  103574. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103575. if(
  103576. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  103577. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  103578. ) {
  103579. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103580. return false;
  103581. }
  103582. /*
  103583. * Write it
  103584. */
  103585. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  103586. /* the above function sets the state for us in case of an error */
  103587. return false;
  103588. }
  103589. /*
  103590. * Get ready for the next frame
  103591. */
  103592. encoder->private_->current_sample_number = 0;
  103593. encoder->private_->current_frame_number++;
  103594. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  103595. return true;
  103596. }
  103597. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  103598. {
  103599. FLAC__FrameHeader frame_header;
  103600. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  103601. FLAC__bool do_independent, do_mid_side;
  103602. /*
  103603. * Calculate the min,max Rice partition orders
  103604. */
  103605. if(is_fractional_block) {
  103606. max_partition_order = 0;
  103607. }
  103608. else {
  103609. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  103610. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  103611. }
  103612. min_partition_order = min(min_partition_order, max_partition_order);
  103613. /*
  103614. * Setup the frame
  103615. */
  103616. frame_header.blocksize = encoder->protected_->blocksize;
  103617. frame_header.sample_rate = encoder->protected_->sample_rate;
  103618. frame_header.channels = encoder->protected_->channels;
  103619. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  103620. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  103621. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  103622. frame_header.number.frame_number = encoder->private_->current_frame_number;
  103623. /*
  103624. * Figure out what channel assignments to try
  103625. */
  103626. if(encoder->protected_->do_mid_side_stereo) {
  103627. if(encoder->protected_->loose_mid_side_stereo) {
  103628. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  103629. do_independent = true;
  103630. do_mid_side = true;
  103631. }
  103632. else {
  103633. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  103634. do_mid_side = !do_independent;
  103635. }
  103636. }
  103637. else {
  103638. do_independent = true;
  103639. do_mid_side = true;
  103640. }
  103641. }
  103642. else {
  103643. do_independent = true;
  103644. do_mid_side = false;
  103645. }
  103646. FLAC__ASSERT(do_independent || do_mid_side);
  103647. /*
  103648. * Check for wasted bits; set effective bps for each subframe
  103649. */
  103650. if(do_independent) {
  103651. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103652. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  103653. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  103654. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  103655. }
  103656. }
  103657. if(do_mid_side) {
  103658. FLAC__ASSERT(encoder->protected_->channels == 2);
  103659. for(channel = 0; channel < 2; channel++) {
  103660. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  103661. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  103662. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  103663. }
  103664. }
  103665. /*
  103666. * First do a normal encoding pass of each independent channel
  103667. */
  103668. if(do_independent) {
  103669. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103670. if(!
  103671. process_subframe_(
  103672. encoder,
  103673. min_partition_order,
  103674. max_partition_order,
  103675. &frame_header,
  103676. encoder->private_->subframe_bps[channel],
  103677. encoder->private_->integer_signal[channel],
  103678. encoder->private_->subframe_workspace_ptr[channel],
  103679. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  103680. encoder->private_->residual_workspace[channel],
  103681. encoder->private_->best_subframe+channel,
  103682. encoder->private_->best_subframe_bits+channel
  103683. )
  103684. )
  103685. return false;
  103686. }
  103687. }
  103688. /*
  103689. * Now do mid and side channels if requested
  103690. */
  103691. if(do_mid_side) {
  103692. FLAC__ASSERT(encoder->protected_->channels == 2);
  103693. for(channel = 0; channel < 2; channel++) {
  103694. if(!
  103695. process_subframe_(
  103696. encoder,
  103697. min_partition_order,
  103698. max_partition_order,
  103699. &frame_header,
  103700. encoder->private_->subframe_bps_mid_side[channel],
  103701. encoder->private_->integer_signal_mid_side[channel],
  103702. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  103703. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  103704. encoder->private_->residual_workspace_mid_side[channel],
  103705. encoder->private_->best_subframe_mid_side+channel,
  103706. encoder->private_->best_subframe_bits_mid_side+channel
  103707. )
  103708. )
  103709. return false;
  103710. }
  103711. }
  103712. /*
  103713. * Compose the frame bitbuffer
  103714. */
  103715. if(do_mid_side) {
  103716. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  103717. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  103718. FLAC__ChannelAssignment channel_assignment;
  103719. FLAC__ASSERT(encoder->protected_->channels == 2);
  103720. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  103721. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  103722. }
  103723. else {
  103724. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  103725. unsigned min_bits;
  103726. int ca;
  103727. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  103728. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  103729. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  103730. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  103731. FLAC__ASSERT(do_independent && do_mid_side);
  103732. /* We have to figure out which channel assignent results in the smallest frame */
  103733. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  103734. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  103735. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  103736. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  103737. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  103738. min_bits = bits[channel_assignment];
  103739. for(ca = 1; ca <= 3; ca++) {
  103740. if(bits[ca] < min_bits) {
  103741. min_bits = bits[ca];
  103742. channel_assignment = (FLAC__ChannelAssignment)ca;
  103743. }
  103744. }
  103745. }
  103746. frame_header.channel_assignment = channel_assignment;
  103747. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  103748. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103749. return false;
  103750. }
  103751. switch(channel_assignment) {
  103752. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  103753. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  103754. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  103755. break;
  103756. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  103757. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  103758. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  103759. break;
  103760. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  103761. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  103762. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  103763. break;
  103764. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  103765. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  103766. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  103767. break;
  103768. default:
  103769. FLAC__ASSERT(0);
  103770. }
  103771. switch(channel_assignment) {
  103772. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  103773. left_bps = encoder->private_->subframe_bps [0];
  103774. right_bps = encoder->private_->subframe_bps [1];
  103775. break;
  103776. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  103777. left_bps = encoder->private_->subframe_bps [0];
  103778. right_bps = encoder->private_->subframe_bps_mid_side[1];
  103779. break;
  103780. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  103781. left_bps = encoder->private_->subframe_bps_mid_side[1];
  103782. right_bps = encoder->private_->subframe_bps [1];
  103783. break;
  103784. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  103785. left_bps = encoder->private_->subframe_bps_mid_side[0];
  103786. right_bps = encoder->private_->subframe_bps_mid_side[1];
  103787. break;
  103788. default:
  103789. FLAC__ASSERT(0);
  103790. }
  103791. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  103792. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  103793. return false;
  103794. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  103795. return false;
  103796. }
  103797. else {
  103798. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  103799. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103800. return false;
  103801. }
  103802. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103803. if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
  103804. /* the above function sets the state for us in case of an error */
  103805. return false;
  103806. }
  103807. }
  103808. }
  103809. if(encoder->protected_->loose_mid_side_stereo) {
  103810. encoder->private_->loose_mid_side_stereo_frame_count++;
  103811. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  103812. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103813. }
  103814. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  103815. return true;
  103816. }
  103817. FLAC__bool process_subframe_(
  103818. FLAC__StreamEncoder *encoder,
  103819. unsigned min_partition_order,
  103820. unsigned max_partition_order,
  103821. const FLAC__FrameHeader *frame_header,
  103822. unsigned subframe_bps,
  103823. const FLAC__int32 integer_signal[],
  103824. FLAC__Subframe *subframe[2],
  103825. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  103826. FLAC__int32 *residual[2],
  103827. unsigned *best_subframe,
  103828. unsigned *best_bits
  103829. )
  103830. {
  103831. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103832. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  103833. #else
  103834. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  103835. #endif
  103836. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103837. FLAC__double lpc_residual_bits_per_sample;
  103838. FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm routines need all the space */
  103839. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  103840. unsigned min_lpc_order, max_lpc_order, lpc_order;
  103841. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  103842. #endif
  103843. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  103844. unsigned rice_parameter;
  103845. unsigned _candidate_bits, _best_bits;
  103846. unsigned _best_subframe;
  103847. /* only use RICE2 partitions if stream bps > 16 */
  103848. const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  103849. FLAC__ASSERT(frame_header->blocksize > 0);
  103850. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  103851. _best_subframe = 0;
  103852. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  103853. _best_bits = UINT_MAX;
  103854. else
  103855. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  103856. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  103857. unsigned signal_is_constant = false;
  103858. guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
  103859. /* check for constant subframe */
  103860. if(
  103861. !encoder->private_->disable_constant_subframes &&
  103862. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103863. fixed_residual_bits_per_sample[1] == 0.0
  103864. #else
  103865. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  103866. #endif
  103867. ) {
  103868. /* the above means it's possible all samples are the same value; now double-check it: */
  103869. unsigned i;
  103870. signal_is_constant = true;
  103871. for(i = 1; i < frame_header->blocksize; i++) {
  103872. if(integer_signal[0] != integer_signal[i]) {
  103873. signal_is_constant = false;
  103874. break;
  103875. }
  103876. }
  103877. }
  103878. if(signal_is_constant) {
  103879. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  103880. if(_candidate_bits < _best_bits) {
  103881. _best_subframe = !_best_subframe;
  103882. _best_bits = _candidate_bits;
  103883. }
  103884. }
  103885. else {
  103886. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  103887. /* encode fixed */
  103888. if(encoder->protected_->do_exhaustive_model_search) {
  103889. min_fixed_order = 0;
  103890. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  103891. }
  103892. else {
  103893. min_fixed_order = max_fixed_order = guess_fixed_order;
  103894. }
  103895. if(max_fixed_order >= frame_header->blocksize)
  103896. max_fixed_order = frame_header->blocksize - 1;
  103897. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  103898. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103899. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  103900. continue; /* don't even try */
  103901. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
  103902. #else
  103903. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  103904. continue; /* don't even try */
  103905. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
  103906. #endif
  103907. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  103908. if(rice_parameter >= rice_parameter_limit) {
  103909. #ifdef DEBUG_VERBOSE
  103910. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  103911. #endif
  103912. rice_parameter = rice_parameter_limit - 1;
  103913. }
  103914. _candidate_bits =
  103915. evaluate_fixed_subframe_(
  103916. encoder,
  103917. integer_signal,
  103918. residual[!_best_subframe],
  103919. encoder->private_->abs_residual_partition_sums,
  103920. encoder->private_->raw_bits_per_partition,
  103921. frame_header->blocksize,
  103922. subframe_bps,
  103923. fixed_order,
  103924. rice_parameter,
  103925. rice_parameter_limit,
  103926. min_partition_order,
  103927. max_partition_order,
  103928. encoder->protected_->do_escape_coding,
  103929. encoder->protected_->rice_parameter_search_dist,
  103930. subframe[!_best_subframe],
  103931. partitioned_rice_contents[!_best_subframe]
  103932. );
  103933. if(_candidate_bits < _best_bits) {
  103934. _best_subframe = !_best_subframe;
  103935. _best_bits = _candidate_bits;
  103936. }
  103937. }
  103938. }
  103939. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103940. /* encode lpc */
  103941. if(encoder->protected_->max_lpc_order > 0) {
  103942. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  103943. max_lpc_order = frame_header->blocksize-1;
  103944. else
  103945. max_lpc_order = encoder->protected_->max_lpc_order;
  103946. if(max_lpc_order > 0) {
  103947. unsigned a;
  103948. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  103949. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  103950. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  103951. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  103952. if(autoc[0] != 0.0) {
  103953. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  103954. if(encoder->protected_->do_exhaustive_model_search) {
  103955. min_lpc_order = 1;
  103956. }
  103957. else {
  103958. const unsigned guess_lpc_order =
  103959. FLAC__lpc_compute_best_order(
  103960. lpc_error,
  103961. max_lpc_order,
  103962. frame_header->blocksize,
  103963. subframe_bps + (
  103964. encoder->protected_->do_qlp_coeff_prec_search?
  103965. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  103966. encoder->protected_->qlp_coeff_precision
  103967. )
  103968. );
  103969. min_lpc_order = max_lpc_order = guess_lpc_order;
  103970. }
  103971. if(max_lpc_order >= frame_header->blocksize)
  103972. max_lpc_order = frame_header->blocksize - 1;
  103973. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  103974. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  103975. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  103976. continue; /* don't even try */
  103977. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  103978. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  103979. if(rice_parameter >= rice_parameter_limit) {
  103980. #ifdef DEBUG_VERBOSE
  103981. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  103982. #endif
  103983. rice_parameter = rice_parameter_limit - 1;
  103984. }
  103985. if(encoder->protected_->do_qlp_coeff_prec_search) {
  103986. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  103987. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  103988. if(subframe_bps <= 17) {
  103989. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  103990. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  103991. }
  103992. else
  103993. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  103994. }
  103995. else {
  103996. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  103997. }
  103998. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  103999. _candidate_bits =
  104000. evaluate_lpc_subframe_(
  104001. encoder,
  104002. integer_signal,
  104003. residual[!_best_subframe],
  104004. encoder->private_->abs_residual_partition_sums,
  104005. encoder->private_->raw_bits_per_partition,
  104006. encoder->private_->lp_coeff[lpc_order-1],
  104007. frame_header->blocksize,
  104008. subframe_bps,
  104009. lpc_order,
  104010. qlp_coeff_precision,
  104011. rice_parameter,
  104012. rice_parameter_limit,
  104013. min_partition_order,
  104014. max_partition_order,
  104015. encoder->protected_->do_escape_coding,
  104016. encoder->protected_->rice_parameter_search_dist,
  104017. subframe[!_best_subframe],
  104018. partitioned_rice_contents[!_best_subframe]
  104019. );
  104020. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104021. if(_candidate_bits < _best_bits) {
  104022. _best_subframe = !_best_subframe;
  104023. _best_bits = _candidate_bits;
  104024. }
  104025. }
  104026. }
  104027. }
  104028. }
  104029. }
  104030. }
  104031. }
  104032. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104033. }
  104034. }
  104035. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104036. if(_best_bits == UINT_MAX) {
  104037. FLAC__ASSERT(_best_subframe == 0);
  104038. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104039. }
  104040. *best_subframe = _best_subframe;
  104041. *best_bits = _best_bits;
  104042. return true;
  104043. }
  104044. FLAC__bool add_subframe_(
  104045. FLAC__StreamEncoder *encoder,
  104046. unsigned blocksize,
  104047. unsigned subframe_bps,
  104048. const FLAC__Subframe *subframe,
  104049. FLAC__BitWriter *frame
  104050. )
  104051. {
  104052. switch(subframe->type) {
  104053. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104054. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104055. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104056. return false;
  104057. }
  104058. break;
  104059. case FLAC__SUBFRAME_TYPE_FIXED:
  104060. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104061. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104062. return false;
  104063. }
  104064. break;
  104065. case FLAC__SUBFRAME_TYPE_LPC:
  104066. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104067. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104068. return false;
  104069. }
  104070. break;
  104071. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104072. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104073. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104074. return false;
  104075. }
  104076. break;
  104077. default:
  104078. FLAC__ASSERT(0);
  104079. }
  104080. return true;
  104081. }
  104082. #define SPOTCHECK_ESTIMATE 0
  104083. #if SPOTCHECK_ESTIMATE
  104084. static void spotcheck_subframe_estimate_(
  104085. FLAC__StreamEncoder *encoder,
  104086. unsigned blocksize,
  104087. unsigned subframe_bps,
  104088. const FLAC__Subframe *subframe,
  104089. unsigned estimate
  104090. )
  104091. {
  104092. FLAC__bool ret;
  104093. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104094. if(frame == 0) {
  104095. fprintf(stderr, "EST: can't allocate frame\n");
  104096. return;
  104097. }
  104098. if(!FLAC__bitwriter_init(frame)) {
  104099. fprintf(stderr, "EST: can't init frame\n");
  104100. return;
  104101. }
  104102. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104103. FLAC__ASSERT(ret);
  104104. {
  104105. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  104106. if(estimate != actual)
  104107. fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
  104108. }
  104109. FLAC__bitwriter_delete(frame);
  104110. }
  104111. #endif
  104112. unsigned evaluate_constant_subframe_(
  104113. FLAC__StreamEncoder *encoder,
  104114. const FLAC__int32 signal,
  104115. unsigned blocksize,
  104116. unsigned subframe_bps,
  104117. FLAC__Subframe *subframe
  104118. )
  104119. {
  104120. unsigned estimate;
  104121. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  104122. subframe->data.constant.value = signal;
  104123. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  104124. #if SPOTCHECK_ESTIMATE
  104125. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104126. #else
  104127. (void)encoder, (void)blocksize;
  104128. #endif
  104129. return estimate;
  104130. }
  104131. unsigned evaluate_fixed_subframe_(
  104132. FLAC__StreamEncoder *encoder,
  104133. const FLAC__int32 signal[],
  104134. FLAC__int32 residual[],
  104135. FLAC__uint64 abs_residual_partition_sums[],
  104136. unsigned raw_bits_per_partition[],
  104137. unsigned blocksize,
  104138. unsigned subframe_bps,
  104139. unsigned order,
  104140. unsigned rice_parameter,
  104141. unsigned rice_parameter_limit,
  104142. unsigned min_partition_order,
  104143. unsigned max_partition_order,
  104144. FLAC__bool do_escape_coding,
  104145. unsigned rice_parameter_search_dist,
  104146. FLAC__Subframe *subframe,
  104147. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104148. )
  104149. {
  104150. unsigned i, residual_bits, estimate;
  104151. const unsigned residual_samples = blocksize - order;
  104152. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  104153. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  104154. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104155. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104156. subframe->data.fixed.residual = residual;
  104157. residual_bits =
  104158. find_best_partition_order_(
  104159. encoder->private_,
  104160. residual,
  104161. abs_residual_partition_sums,
  104162. raw_bits_per_partition,
  104163. residual_samples,
  104164. order,
  104165. rice_parameter,
  104166. rice_parameter_limit,
  104167. min_partition_order,
  104168. max_partition_order,
  104169. subframe_bps,
  104170. do_escape_coding,
  104171. rice_parameter_search_dist,
  104172. &subframe->data.fixed.entropy_coding_method
  104173. );
  104174. subframe->data.fixed.order = order;
  104175. for(i = 0; i < order; i++)
  104176. subframe->data.fixed.warmup[i] = signal[i];
  104177. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  104178. #if SPOTCHECK_ESTIMATE
  104179. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104180. #endif
  104181. return estimate;
  104182. }
  104183. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104184. unsigned evaluate_lpc_subframe_(
  104185. FLAC__StreamEncoder *encoder,
  104186. const FLAC__int32 signal[],
  104187. FLAC__int32 residual[],
  104188. FLAC__uint64 abs_residual_partition_sums[],
  104189. unsigned raw_bits_per_partition[],
  104190. const FLAC__real lp_coeff[],
  104191. unsigned blocksize,
  104192. unsigned subframe_bps,
  104193. unsigned order,
  104194. unsigned qlp_coeff_precision,
  104195. unsigned rice_parameter,
  104196. unsigned rice_parameter_limit,
  104197. unsigned min_partition_order,
  104198. unsigned max_partition_order,
  104199. FLAC__bool do_escape_coding,
  104200. unsigned rice_parameter_search_dist,
  104201. FLAC__Subframe *subframe,
  104202. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104203. )
  104204. {
  104205. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  104206. unsigned i, residual_bits, estimate;
  104207. int quantization, ret;
  104208. const unsigned residual_samples = blocksize - order;
  104209. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  104210. if(subframe_bps <= 16) {
  104211. FLAC__ASSERT(order > 0);
  104212. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  104213. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  104214. }
  104215. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  104216. if(ret != 0)
  104217. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  104218. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  104219. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  104220. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104221. else
  104222. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104223. else
  104224. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104225. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  104226. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104227. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104228. subframe->data.lpc.residual = residual;
  104229. residual_bits =
  104230. find_best_partition_order_(
  104231. encoder->private_,
  104232. residual,
  104233. abs_residual_partition_sums,
  104234. raw_bits_per_partition,
  104235. residual_samples,
  104236. order,
  104237. rice_parameter,
  104238. rice_parameter_limit,
  104239. min_partition_order,
  104240. max_partition_order,
  104241. subframe_bps,
  104242. do_escape_coding,
  104243. rice_parameter_search_dist,
  104244. &subframe->data.lpc.entropy_coding_method
  104245. );
  104246. subframe->data.lpc.order = order;
  104247. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  104248. subframe->data.lpc.quantization_level = quantization;
  104249. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  104250. for(i = 0; i < order; i++)
  104251. subframe->data.lpc.warmup[i] = signal[i];
  104252. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
  104253. #if SPOTCHECK_ESTIMATE
  104254. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104255. #endif
  104256. return estimate;
  104257. }
  104258. #endif
  104259. unsigned evaluate_verbatim_subframe_(
  104260. FLAC__StreamEncoder *encoder,
  104261. const FLAC__int32 signal[],
  104262. unsigned blocksize,
  104263. unsigned subframe_bps,
  104264. FLAC__Subframe *subframe
  104265. )
  104266. {
  104267. unsigned estimate;
  104268. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  104269. subframe->data.verbatim.data = signal;
  104270. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  104271. #if SPOTCHECK_ESTIMATE
  104272. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104273. #else
  104274. (void)encoder;
  104275. #endif
  104276. return estimate;
  104277. }
  104278. unsigned find_best_partition_order_(
  104279. FLAC__StreamEncoderPrivate *private_,
  104280. const FLAC__int32 residual[],
  104281. FLAC__uint64 abs_residual_partition_sums[],
  104282. unsigned raw_bits_per_partition[],
  104283. unsigned residual_samples,
  104284. unsigned predictor_order,
  104285. unsigned rice_parameter,
  104286. unsigned rice_parameter_limit,
  104287. unsigned min_partition_order,
  104288. unsigned max_partition_order,
  104289. unsigned bps,
  104290. FLAC__bool do_escape_coding,
  104291. unsigned rice_parameter_search_dist,
  104292. FLAC__EntropyCodingMethod *best_ecm
  104293. )
  104294. {
  104295. unsigned residual_bits, best_residual_bits = 0;
  104296. unsigned best_parameters_index = 0;
  104297. unsigned best_partition_order = 0;
  104298. const unsigned blocksize = residual_samples + predictor_order;
  104299. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  104300. min_partition_order = min(min_partition_order, max_partition_order);
  104301. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  104302. if(do_escape_coding)
  104303. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  104304. {
  104305. int partition_order;
  104306. unsigned sum;
  104307. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  104308. if(!
  104309. set_partitioned_rice_(
  104310. #ifdef EXACT_RICE_BITS_CALCULATION
  104311. residual,
  104312. #endif
  104313. abs_residual_partition_sums+sum,
  104314. raw_bits_per_partition+sum,
  104315. residual_samples,
  104316. predictor_order,
  104317. rice_parameter,
  104318. rice_parameter_limit,
  104319. rice_parameter_search_dist,
  104320. (unsigned)partition_order,
  104321. do_escape_coding,
  104322. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  104323. &residual_bits
  104324. )
  104325. )
  104326. {
  104327. FLAC__ASSERT(best_residual_bits != 0);
  104328. break;
  104329. }
  104330. sum += 1u << partition_order;
  104331. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  104332. best_residual_bits = residual_bits;
  104333. best_parameters_index = !best_parameters_index;
  104334. best_partition_order = partition_order;
  104335. }
  104336. }
  104337. }
  104338. best_ecm->data.partitioned_rice.order = best_partition_order;
  104339. {
  104340. /*
  104341. * We are allowed to de-const the pointer based on our special
  104342. * knowledge; it is const to the outside world.
  104343. */
  104344. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  104345. unsigned partition;
  104346. /* save best parameters and raw_bits */
  104347. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  104348. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  104349. if(do_escape_coding)
  104350. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  104351. /*
  104352. * Now need to check if the type should be changed to
  104353. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  104354. * size of the rice parameters.
  104355. */
  104356. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  104357. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  104358. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  104359. break;
  104360. }
  104361. }
  104362. }
  104363. return best_residual_bits;
  104364. }
  104365. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104366. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  104367. const FLAC__int32 residual[],
  104368. FLAC__uint64 abs_residual_partition_sums[],
  104369. unsigned blocksize,
  104370. unsigned predictor_order,
  104371. unsigned min_partition_order,
  104372. unsigned max_partition_order
  104373. );
  104374. #endif
  104375. void precompute_partition_info_sums_(
  104376. const FLAC__int32 residual[],
  104377. FLAC__uint64 abs_residual_partition_sums[],
  104378. unsigned residual_samples,
  104379. unsigned predictor_order,
  104380. unsigned min_partition_order,
  104381. unsigned max_partition_order,
  104382. unsigned bps
  104383. )
  104384. {
  104385. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  104386. unsigned partitions = 1u << max_partition_order;
  104387. FLAC__ASSERT(default_partition_samples > predictor_order);
  104388. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104389. /* slightly pessimistic but still catches all common cases */
  104390. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  104391. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  104392. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  104393. return;
  104394. }
  104395. #endif
  104396. /* first do max_partition_order */
  104397. {
  104398. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  104399. /* slightly pessimistic but still catches all common cases */
  104400. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  104401. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  104402. FLAC__uint32 abs_residual_partition_sum;
  104403. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104404. end += default_partition_samples;
  104405. abs_residual_partition_sum = 0;
  104406. for( ; residual_sample < end; residual_sample++)
  104407. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  104408. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  104409. }
  104410. }
  104411. else { /* have to pessimistically use 64 bits for accumulator */
  104412. FLAC__uint64 abs_residual_partition_sum;
  104413. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104414. end += default_partition_samples;
  104415. abs_residual_partition_sum = 0;
  104416. for( ; residual_sample < end; residual_sample++)
  104417. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  104418. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  104419. }
  104420. }
  104421. }
  104422. /* now merge partitions for lower orders */
  104423. {
  104424. unsigned from_partition = 0, to_partition = partitions;
  104425. int partition_order;
  104426. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  104427. unsigned i;
  104428. partitions >>= 1;
  104429. for(i = 0; i < partitions; i++) {
  104430. abs_residual_partition_sums[to_partition++] =
  104431. abs_residual_partition_sums[from_partition ] +
  104432. abs_residual_partition_sums[from_partition+1];
  104433. from_partition += 2;
  104434. }
  104435. }
  104436. }
  104437. }
  104438. void precompute_partition_info_escapes_(
  104439. const FLAC__int32 residual[],
  104440. unsigned raw_bits_per_partition[],
  104441. unsigned residual_samples,
  104442. unsigned predictor_order,
  104443. unsigned min_partition_order,
  104444. unsigned max_partition_order
  104445. )
  104446. {
  104447. int partition_order;
  104448. unsigned from_partition, to_partition = 0;
  104449. const unsigned blocksize = residual_samples + predictor_order;
  104450. /* first do max_partition_order */
  104451. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  104452. FLAC__int32 r;
  104453. FLAC__uint32 rmax;
  104454. unsigned partition, partition_sample, partition_samples, residual_sample;
  104455. const unsigned partitions = 1u << partition_order;
  104456. const unsigned default_partition_samples = blocksize >> partition_order;
  104457. FLAC__ASSERT(default_partition_samples > predictor_order);
  104458. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104459. partition_samples = default_partition_samples;
  104460. if(partition == 0)
  104461. partition_samples -= predictor_order;
  104462. rmax = 0;
  104463. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  104464. r = residual[residual_sample++];
  104465. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  104466. if(r < 0)
  104467. rmax |= ~r;
  104468. else
  104469. rmax |= r;
  104470. }
  104471. /* now we know all residual values are in the range [-rmax-1,rmax] */
  104472. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  104473. }
  104474. to_partition = partitions;
  104475. break; /*@@@ yuck, should remove the 'for' loop instead */
  104476. }
  104477. /* now merge partitions for lower orders */
  104478. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  104479. unsigned m;
  104480. unsigned i;
  104481. const unsigned partitions = 1u << partition_order;
  104482. for(i = 0; i < partitions; i++) {
  104483. m = raw_bits_per_partition[from_partition];
  104484. from_partition++;
  104485. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  104486. from_partition++;
  104487. to_partition++;
  104488. }
  104489. }
  104490. }
  104491. #ifdef EXACT_RICE_BITS_CALCULATION
  104492. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  104493. const unsigned rice_parameter,
  104494. const unsigned partition_samples,
  104495. const FLAC__int32 *residual
  104496. )
  104497. {
  104498. unsigned i, partition_bits =
  104499. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  104500. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  104501. ;
  104502. for(i = 0; i < partition_samples; i++)
  104503. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  104504. return partition_bits;
  104505. }
  104506. #else
  104507. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  104508. const unsigned rice_parameter,
  104509. const unsigned partition_samples,
  104510. const FLAC__uint64 abs_residual_partition_sum
  104511. )
  104512. {
  104513. return
  104514. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  104515. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  104516. (
  104517. rice_parameter?
  104518. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  104519. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  104520. )
  104521. - (partition_samples >> 1)
  104522. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  104523. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  104524. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  104525. * So the subtraction term tries to guess how many extra bits were contributed.
  104526. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  104527. */
  104528. ;
  104529. }
  104530. #endif
  104531. FLAC__bool set_partitioned_rice_(
  104532. #ifdef EXACT_RICE_BITS_CALCULATION
  104533. const FLAC__int32 residual[],
  104534. #endif
  104535. const FLAC__uint64 abs_residual_partition_sums[],
  104536. const unsigned raw_bits_per_partition[],
  104537. const unsigned residual_samples,
  104538. const unsigned predictor_order,
  104539. const unsigned suggested_rice_parameter,
  104540. const unsigned rice_parameter_limit,
  104541. const unsigned rice_parameter_search_dist,
  104542. const unsigned partition_order,
  104543. const FLAC__bool search_for_escapes,
  104544. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  104545. unsigned *bits
  104546. )
  104547. {
  104548. unsigned rice_parameter, partition_bits;
  104549. unsigned best_partition_bits, best_rice_parameter = 0;
  104550. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  104551. unsigned *parameters, *raw_bits;
  104552. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104553. unsigned min_rice_parameter, max_rice_parameter;
  104554. #else
  104555. (void)rice_parameter_search_dist;
  104556. #endif
  104557. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  104558. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  104559. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  104560. parameters = partitioned_rice_contents->parameters;
  104561. raw_bits = partitioned_rice_contents->raw_bits;
  104562. if(partition_order == 0) {
  104563. best_partition_bits = (unsigned)(-1);
  104564. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104565. if(rice_parameter_search_dist) {
  104566. if(suggested_rice_parameter < rice_parameter_search_dist)
  104567. min_rice_parameter = 0;
  104568. else
  104569. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  104570. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  104571. if(max_rice_parameter >= rice_parameter_limit) {
  104572. #ifdef DEBUG_VERBOSE
  104573. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  104574. #endif
  104575. max_rice_parameter = rice_parameter_limit - 1;
  104576. }
  104577. }
  104578. else
  104579. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  104580. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  104581. #else
  104582. rice_parameter = suggested_rice_parameter;
  104583. #endif
  104584. #ifdef EXACT_RICE_BITS_CALCULATION
  104585. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  104586. #else
  104587. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  104588. #endif
  104589. if(partition_bits < best_partition_bits) {
  104590. best_rice_parameter = rice_parameter;
  104591. best_partition_bits = partition_bits;
  104592. }
  104593. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104594. }
  104595. #endif
  104596. if(search_for_escapes) {
  104597. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
  104598. if(partition_bits <= best_partition_bits) {
  104599. raw_bits[0] = raw_bits_per_partition[0];
  104600. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  104601. best_partition_bits = partition_bits;
  104602. }
  104603. else
  104604. raw_bits[0] = 0;
  104605. }
  104606. parameters[0] = best_rice_parameter;
  104607. bits_ += best_partition_bits;
  104608. }
  104609. else {
  104610. unsigned partition, residual_sample;
  104611. unsigned partition_samples;
  104612. FLAC__uint64 mean, k;
  104613. const unsigned partitions = 1u << partition_order;
  104614. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104615. partition_samples = (residual_samples+predictor_order) >> partition_order;
  104616. if(partition == 0) {
  104617. if(partition_samples <= predictor_order)
  104618. return false;
  104619. else
  104620. partition_samples -= predictor_order;
  104621. }
  104622. mean = abs_residual_partition_sums[partition];
  104623. /* we are basically calculating the size in bits of the
  104624. * average residual magnitude in the partition:
  104625. * rice_parameter = floor(log2(mean/partition_samples))
  104626. * 'mean' is not a good name for the variable, it is
  104627. * actually the sum of magnitudes of all residual values
  104628. * in the partition, so the actual mean is
  104629. * mean/partition_samples
  104630. */
  104631. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  104632. ;
  104633. if(rice_parameter >= rice_parameter_limit) {
  104634. #ifdef DEBUG_VERBOSE
  104635. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  104636. #endif
  104637. rice_parameter = rice_parameter_limit - 1;
  104638. }
  104639. best_partition_bits = (unsigned)(-1);
  104640. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104641. if(rice_parameter_search_dist) {
  104642. if(rice_parameter < rice_parameter_search_dist)
  104643. min_rice_parameter = 0;
  104644. else
  104645. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  104646. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  104647. if(max_rice_parameter >= rice_parameter_limit) {
  104648. #ifdef DEBUG_VERBOSE
  104649. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  104650. #endif
  104651. max_rice_parameter = rice_parameter_limit - 1;
  104652. }
  104653. }
  104654. else
  104655. min_rice_parameter = max_rice_parameter = rice_parameter;
  104656. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  104657. #endif
  104658. #ifdef EXACT_RICE_BITS_CALCULATION
  104659. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  104660. #else
  104661. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  104662. #endif
  104663. if(partition_bits < best_partition_bits) {
  104664. best_rice_parameter = rice_parameter;
  104665. best_partition_bits = partition_bits;
  104666. }
  104667. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104668. }
  104669. #endif
  104670. if(search_for_escapes) {
  104671. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
  104672. if(partition_bits <= best_partition_bits) {
  104673. raw_bits[partition] = raw_bits_per_partition[partition];
  104674. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  104675. best_partition_bits = partition_bits;
  104676. }
  104677. else
  104678. raw_bits[partition] = 0;
  104679. }
  104680. parameters[partition] = best_rice_parameter;
  104681. bits_ += best_partition_bits;
  104682. residual_sample += partition_samples;
  104683. }
  104684. }
  104685. *bits = bits_;
  104686. return true;
  104687. }
  104688. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  104689. {
  104690. unsigned i, shift;
  104691. FLAC__int32 x = 0;
  104692. for(i = 0; i < samples && !(x&1); i++)
  104693. x |= signal[i];
  104694. if(x == 0) {
  104695. shift = 0;
  104696. }
  104697. else {
  104698. for(shift = 0; !(x&1); shift++)
  104699. x >>= 1;
  104700. }
  104701. if(shift > 0) {
  104702. for(i = 0; i < samples; i++)
  104703. signal[i] >>= shift;
  104704. }
  104705. return shift;
  104706. }
  104707. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  104708. {
  104709. unsigned channel;
  104710. for(channel = 0; channel < channels; channel++)
  104711. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  104712. fifo->tail += wide_samples;
  104713. FLAC__ASSERT(fifo->tail <= fifo->size);
  104714. }
  104715. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  104716. {
  104717. unsigned channel;
  104718. unsigned sample, wide_sample;
  104719. unsigned tail = fifo->tail;
  104720. sample = input_offset * channels;
  104721. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  104722. for(channel = 0; channel < channels; channel++)
  104723. fifo->data[channel][tail] = input[sample++];
  104724. tail++;
  104725. }
  104726. fifo->tail = tail;
  104727. FLAC__ASSERT(fifo->tail <= fifo->size);
  104728. }
  104729. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  104730. {
  104731. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  104732. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  104733. (void)decoder;
  104734. if(encoder->private_->verify.needs_magic_hack) {
  104735. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  104736. *bytes = FLAC__STREAM_SYNC_LENGTH;
  104737. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  104738. encoder->private_->verify.needs_magic_hack = false;
  104739. }
  104740. else {
  104741. if(encoded_bytes == 0) {
  104742. /*
  104743. * If we get here, a FIFO underflow has occurred,
  104744. * which means there is a bug somewhere.
  104745. */
  104746. FLAC__ASSERT(0);
  104747. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  104748. }
  104749. else if(encoded_bytes < *bytes)
  104750. *bytes = encoded_bytes;
  104751. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  104752. encoder->private_->verify.output.data += *bytes;
  104753. encoder->private_->verify.output.bytes -= *bytes;
  104754. }
  104755. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  104756. }
  104757. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  104758. {
  104759. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  104760. unsigned channel;
  104761. const unsigned channels = frame->header.channels;
  104762. const unsigned blocksize = frame->header.blocksize;
  104763. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  104764. (void)decoder;
  104765. for(channel = 0; channel < channels; channel++) {
  104766. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  104767. unsigned i, sample = 0;
  104768. FLAC__int32 expect = 0, got = 0;
  104769. for(i = 0; i < blocksize; i++) {
  104770. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  104771. sample = i;
  104772. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  104773. got = (FLAC__int32)buffer[channel][i];
  104774. break;
  104775. }
  104776. }
  104777. FLAC__ASSERT(i < blocksize);
  104778. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  104779. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  104780. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  104781. encoder->private_->verify.error_stats.channel = channel;
  104782. encoder->private_->verify.error_stats.sample = sample;
  104783. encoder->private_->verify.error_stats.expected = expect;
  104784. encoder->private_->verify.error_stats.got = got;
  104785. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  104786. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  104787. }
  104788. }
  104789. /* dequeue the frame from the fifo */
  104790. encoder->private_->verify.input_fifo.tail -= blocksize;
  104791. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  104792. for(channel = 0; channel < channels; channel++)
  104793. memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
  104794. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  104795. }
  104796. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  104797. {
  104798. (void)decoder, (void)metadata, (void)client_data;
  104799. }
  104800. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  104801. {
  104802. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  104803. (void)decoder, (void)status;
  104804. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104805. }
  104806. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  104807. {
  104808. (void)client_data;
  104809. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  104810. if (*bytes == 0) {
  104811. if (feof(encoder->private_->file))
  104812. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  104813. else if (ferror(encoder->private_->file))
  104814. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  104815. }
  104816. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  104817. }
  104818. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  104819. {
  104820. (void)client_data;
  104821. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  104822. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  104823. else
  104824. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  104825. }
  104826. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  104827. {
  104828. off_t offset;
  104829. (void)client_data;
  104830. offset = ftello(encoder->private_->file);
  104831. if(offset < 0) {
  104832. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  104833. }
  104834. else {
  104835. *absolute_byte_offset = (FLAC__uint64)offset;
  104836. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  104837. }
  104838. }
  104839. #ifdef FLAC__VALGRIND_TESTING
  104840. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  104841. {
  104842. size_t ret = fwrite(ptr, size, nmemb, stream);
  104843. if(!ferror(stream))
  104844. fflush(stream);
  104845. return ret;
  104846. }
  104847. #else
  104848. #define local__fwrite fwrite
  104849. #endif
  104850. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  104851. {
  104852. (void)client_data, (void)current_frame;
  104853. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  104854. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  104855. #if FLAC__HAS_OGG
  104856. /* We would like to be able to use 'samples > 0' in the
  104857. * clause here but currently because of the nature of our
  104858. * Ogg writing implementation, 'samples' is always 0 (see
  104859. * ogg_encoder_aspect.c). The downside is extra progress
  104860. * callbacks.
  104861. */
  104862. encoder->private_->is_ogg? true :
  104863. #endif
  104864. samples > 0
  104865. );
  104866. if(call_it) {
  104867. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  104868. * because at this point in the callback chain, the stats
  104869. * have not been updated. Only after we return and control
  104870. * gets back to write_frame_() are the stats updated
  104871. */
  104872. encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
  104873. }
  104874. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  104875. }
  104876. else
  104877. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104878. }
  104879. /*
  104880. * This will forcibly set stdout to binary mode (for OSes that require it)
  104881. */
  104882. FILE *get_binary_stdout_(void)
  104883. {
  104884. /* if something breaks here it is probably due to the presence or
  104885. * absence of an underscore before the identifiers 'setmode',
  104886. * 'fileno', and/or 'O_BINARY'; check your system header files.
  104887. */
  104888. #if defined _MSC_VER || defined __MINGW32__
  104889. _setmode(_fileno(stdout), _O_BINARY);
  104890. #elif defined __CYGWIN__
  104891. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  104892. setmode(_fileno(stdout), _O_BINARY);
  104893. #elif defined __EMX__
  104894. setmode(fileno(stdout), O_BINARY);
  104895. #endif
  104896. return stdout;
  104897. }
  104898. #endif
  104899. /*** End of inlined file: stream_encoder.c ***/
  104900. /*** Start of inlined file: stream_encoder_framing.c ***/
  104901. /*** Start of inlined file: juce_FlacHeader.h ***/
  104902. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  104903. // tasks..
  104904. #define VERSION "1.2.1"
  104905. #define FLAC__NO_DLL 1
  104906. #if JUCE_MSVC
  104907. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  104908. #endif
  104909. #if JUCE_MAC
  104910. #define FLAC__SYS_DARWIN 1
  104911. #endif
  104912. /*** End of inlined file: juce_FlacHeader.h ***/
  104913. #if JUCE_USE_FLAC
  104914. #if HAVE_CONFIG_H
  104915. # include <config.h>
  104916. #endif
  104917. #include <stdio.h>
  104918. #include <string.h> /* for strlen() */
  104919. #ifdef max
  104920. #undef max
  104921. #endif
  104922. #define max(x,y) ((x)>(y)?(x):(y))
  104923. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  104924. static FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended);
  104925. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  104926. {
  104927. unsigned i, j;
  104928. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  104929. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  104930. return false;
  104931. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  104932. return false;
  104933. /*
  104934. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  104935. */
  104936. i = metadata->length;
  104937. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  104938. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  104939. i -= metadata->data.vorbis_comment.vendor_string.length;
  104940. i += vendor_string_length;
  104941. }
  104942. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  104943. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  104944. return false;
  104945. switch(metadata->type) {
  104946. case FLAC__METADATA_TYPE_STREAMINFO:
  104947. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  104948. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  104949. return false;
  104950. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  104951. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  104952. return false;
  104953. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  104954. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  104955. return false;
  104956. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  104957. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  104958. return false;
  104959. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  104960. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  104961. return false;
  104962. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  104963. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  104964. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  104965. return false;
  104966. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  104967. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  104968. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  104969. return false;
  104970. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  104971. return false;
  104972. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  104973. return false;
  104974. break;
  104975. case FLAC__METADATA_TYPE_PADDING:
  104976. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  104977. return false;
  104978. break;
  104979. case FLAC__METADATA_TYPE_APPLICATION:
  104980. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  104981. return false;
  104982. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  104983. return false;
  104984. break;
  104985. case FLAC__METADATA_TYPE_SEEKTABLE:
  104986. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  104987. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  104988. return false;
  104989. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  104990. return false;
  104991. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  104992. return false;
  104993. }
  104994. break;
  104995. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  104996. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  104997. return false;
  104998. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  104999. return false;
  105000. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105001. return false;
  105002. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105003. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105004. return false;
  105005. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105006. return false;
  105007. }
  105008. break;
  105009. case FLAC__METADATA_TYPE_CUESHEET:
  105010. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105011. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.cue_sheet.media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
  105012. return false;
  105013. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105014. return false;
  105015. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105016. return false;
  105017. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105018. return false;
  105019. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105020. return false;
  105021. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105022. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105023. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105024. return false;
  105025. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105026. return false;
  105027. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105028. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105029. return false;
  105030. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105031. return false;
  105032. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105033. return false;
  105034. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105035. return false;
  105036. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105037. return false;
  105038. for(j = 0; j < track->num_indices; j++) {
  105039. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105040. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105041. return false;
  105042. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105043. return false;
  105044. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105045. return false;
  105046. }
  105047. }
  105048. break;
  105049. case FLAC__METADATA_TYPE_PICTURE:
  105050. {
  105051. size_t len;
  105052. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105053. return false;
  105054. len = strlen(metadata->data.picture.mime_type);
  105055. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105056. return false;
  105057. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105058. return false;
  105059. len = strlen((const char *)metadata->data.picture.description);
  105060. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105061. return false;
  105062. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105063. return false;
  105064. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105065. return false;
  105066. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105067. return false;
  105068. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105069. return false;
  105070. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105071. return false;
  105072. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105073. return false;
  105074. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105075. return false;
  105076. }
  105077. break;
  105078. default:
  105079. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105080. return false;
  105081. break;
  105082. }
  105083. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105084. return true;
  105085. }
  105086. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105087. {
  105088. unsigned u, blocksize_hint, sample_rate_hint;
  105089. FLAC__byte crc;
  105090. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105091. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105092. return false;
  105093. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105094. return false;
  105095. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105096. return false;
  105097. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105098. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105099. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105100. blocksize_hint = 0;
  105101. switch(header->blocksize) {
  105102. case 192: u = 1; break;
  105103. case 576: u = 2; break;
  105104. case 1152: u = 3; break;
  105105. case 2304: u = 4; break;
  105106. case 4608: u = 5; break;
  105107. case 256: u = 8; break;
  105108. case 512: u = 9; break;
  105109. case 1024: u = 10; break;
  105110. case 2048: u = 11; break;
  105111. case 4096: u = 12; break;
  105112. case 8192: u = 13; break;
  105113. case 16384: u = 14; break;
  105114. case 32768: u = 15; break;
  105115. default:
  105116. if(header->blocksize <= 0x100)
  105117. blocksize_hint = u = 6;
  105118. else
  105119. blocksize_hint = u = 7;
  105120. break;
  105121. }
  105122. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  105123. return false;
  105124. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  105125. sample_rate_hint = 0;
  105126. switch(header->sample_rate) {
  105127. case 88200: u = 1; break;
  105128. case 176400: u = 2; break;
  105129. case 192000: u = 3; break;
  105130. case 8000: u = 4; break;
  105131. case 16000: u = 5; break;
  105132. case 22050: u = 6; break;
  105133. case 24000: u = 7; break;
  105134. case 32000: u = 8; break;
  105135. case 44100: u = 9; break;
  105136. case 48000: u = 10; break;
  105137. case 96000: u = 11; break;
  105138. default:
  105139. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  105140. sample_rate_hint = u = 12;
  105141. else if(header->sample_rate % 10 == 0)
  105142. sample_rate_hint = u = 14;
  105143. else if(header->sample_rate <= 0xffff)
  105144. sample_rate_hint = u = 13;
  105145. else
  105146. u = 0;
  105147. break;
  105148. }
  105149. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  105150. return false;
  105151. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  105152. switch(header->channel_assignment) {
  105153. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105154. u = header->channels - 1;
  105155. break;
  105156. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105157. FLAC__ASSERT(header->channels == 2);
  105158. u = 8;
  105159. break;
  105160. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105161. FLAC__ASSERT(header->channels == 2);
  105162. u = 9;
  105163. break;
  105164. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105165. FLAC__ASSERT(header->channels == 2);
  105166. u = 10;
  105167. break;
  105168. default:
  105169. FLAC__ASSERT(0);
  105170. }
  105171. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  105172. return false;
  105173. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105174. switch(header->bits_per_sample) {
  105175. case 8 : u = 1; break;
  105176. case 12: u = 2; break;
  105177. case 16: u = 4; break;
  105178. case 20: u = 5; break;
  105179. case 24: u = 6; break;
  105180. default: u = 0; break;
  105181. }
  105182. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  105183. return false;
  105184. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  105185. return false;
  105186. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  105187. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  105188. return false;
  105189. }
  105190. else {
  105191. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  105192. return false;
  105193. }
  105194. if(blocksize_hint)
  105195. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  105196. return false;
  105197. switch(sample_rate_hint) {
  105198. case 12:
  105199. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  105200. return false;
  105201. break;
  105202. case 13:
  105203. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  105204. return false;
  105205. break;
  105206. case 14:
  105207. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  105208. return false;
  105209. break;
  105210. }
  105211. /* write the CRC */
  105212. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  105213. return false;
  105214. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  105215. return false;
  105216. return true;
  105217. }
  105218. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105219. {
  105220. FLAC__bool ok;
  105221. ok =
  105222. FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN) &&
  105223. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  105224. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  105225. ;
  105226. return ok;
  105227. }
  105228. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105229. {
  105230. unsigned i;
  105231. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK | (subframe->order<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  105232. return false;
  105233. if(wasted_bits)
  105234. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105235. return false;
  105236. for(i = 0; i < subframe->order; i++)
  105237. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105238. return false;
  105239. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105240. return false;
  105241. switch(subframe->entropy_coding_method.type) {
  105242. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105243. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105244. if(!add_residual_partitioned_rice_(
  105245. bw,
  105246. subframe->residual,
  105247. residual_samples,
  105248. subframe->order,
  105249. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105250. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105251. subframe->entropy_coding_method.data.partitioned_rice.order,
  105252. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105253. ))
  105254. return false;
  105255. break;
  105256. default:
  105257. FLAC__ASSERT(0);
  105258. }
  105259. return true;
  105260. }
  105261. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105262. {
  105263. unsigned i;
  105264. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK | ((subframe->order-1)<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  105265. return false;
  105266. if(wasted_bits)
  105267. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105268. return false;
  105269. for(i = 0; i < subframe->order; i++)
  105270. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105271. return false;
  105272. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  105273. return false;
  105274. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  105275. return false;
  105276. for(i = 0; i < subframe->order; i++)
  105277. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  105278. return false;
  105279. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105280. return false;
  105281. switch(subframe->entropy_coding_method.type) {
  105282. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105283. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105284. if(!add_residual_partitioned_rice_(
  105285. bw,
  105286. subframe->residual,
  105287. residual_samples,
  105288. subframe->order,
  105289. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105290. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105291. subframe->entropy_coding_method.data.partitioned_rice.order,
  105292. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105293. ))
  105294. return false;
  105295. break;
  105296. default:
  105297. FLAC__ASSERT(0);
  105298. }
  105299. return true;
  105300. }
  105301. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105302. {
  105303. unsigned i;
  105304. const FLAC__int32 *signal = subframe->data;
  105305. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  105306. return false;
  105307. if(wasted_bits)
  105308. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105309. return false;
  105310. for(i = 0; i < samples; i++)
  105311. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  105312. return false;
  105313. return true;
  105314. }
  105315. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  105316. {
  105317. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  105318. return false;
  105319. switch(method->type) {
  105320. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105321. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105322. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  105323. return false;
  105324. break;
  105325. default:
  105326. FLAC__ASSERT(0);
  105327. }
  105328. return true;
  105329. }
  105330. FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended)
  105331. {
  105332. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  105333. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  105334. if(partition_order == 0) {
  105335. unsigned i;
  105336. if(raw_bits[0] == 0) {
  105337. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  105338. return false;
  105339. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  105340. return false;
  105341. }
  105342. else {
  105343. FLAC__ASSERT(rice_parameters[0] == 0);
  105344. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105345. return false;
  105346. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105347. return false;
  105348. for(i = 0; i < residual_samples; i++) {
  105349. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  105350. return false;
  105351. }
  105352. }
  105353. return true;
  105354. }
  105355. else {
  105356. unsigned i, j, k = 0, k_last = 0;
  105357. unsigned partition_samples;
  105358. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  105359. for(i = 0; i < (1u<<partition_order); i++) {
  105360. partition_samples = default_partition_samples;
  105361. if(i == 0)
  105362. partition_samples -= predictor_order;
  105363. k += partition_samples;
  105364. if(raw_bits[i] == 0) {
  105365. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  105366. return false;
  105367. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  105368. return false;
  105369. }
  105370. else {
  105371. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105372. return false;
  105373. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105374. return false;
  105375. for(j = k_last; j < k; j++) {
  105376. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  105377. return false;
  105378. }
  105379. }
  105380. k_last = k;
  105381. }
  105382. return true;
  105383. }
  105384. }
  105385. #endif
  105386. /*** End of inlined file: stream_encoder_framing.c ***/
  105387. /*** Start of inlined file: window_flac.c ***/
  105388. /*** Start of inlined file: juce_FlacHeader.h ***/
  105389. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105390. // tasks..
  105391. #define VERSION "1.2.1"
  105392. #define FLAC__NO_DLL 1
  105393. #if JUCE_MSVC
  105394. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105395. #endif
  105396. #if JUCE_MAC
  105397. #define FLAC__SYS_DARWIN 1
  105398. #endif
  105399. /*** End of inlined file: juce_FlacHeader.h ***/
  105400. #if JUCE_USE_FLAC
  105401. #if HAVE_CONFIG_H
  105402. # include <config.h>
  105403. #endif
  105404. #include <math.h>
  105405. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105406. #ifndef M_PI
  105407. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  105408. #define M_PI 3.14159265358979323846
  105409. #endif
  105410. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  105411. {
  105412. const FLAC__int32 N = L - 1;
  105413. FLAC__int32 n;
  105414. if (L & 1) {
  105415. for (n = 0; n <= N/2; n++)
  105416. window[n] = 2.0f * n / (float)N;
  105417. for (; n <= N; n++)
  105418. window[n] = 2.0f - 2.0f * n / (float)N;
  105419. }
  105420. else {
  105421. for (n = 0; n <= L/2-1; n++)
  105422. window[n] = 2.0f * n / (float)N;
  105423. for (; n <= N; n++)
  105424. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  105425. }
  105426. }
  105427. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  105428. {
  105429. const FLAC__int32 N = L - 1;
  105430. FLAC__int32 n;
  105431. for (n = 0; n < L; n++)
  105432. window[n] = (FLAC__real)(0.62f - 0.48f * fabs((float)n/(float)N+0.5f) + 0.38f * cos(2.0f * M_PI * ((float)n/(float)N+0.5f)));
  105433. }
  105434. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  105435. {
  105436. const FLAC__int32 N = L - 1;
  105437. FLAC__int32 n;
  105438. for (n = 0; n < L; n++)
  105439. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  105440. }
  105441. /* 4-term -92dB side-lobe */
  105442. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  105443. {
  105444. const FLAC__int32 N = L - 1;
  105445. FLAC__int32 n;
  105446. for (n = 0; n <= N; n++)
  105447. window[n] = (FLAC__real)(0.35875f - 0.48829f * cos(2.0f * M_PI * n / N) + 0.14128f * cos(4.0f * M_PI * n / N) - 0.01168f * cos(6.0f * M_PI * n / N));
  105448. }
  105449. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  105450. {
  105451. const FLAC__int32 N = L - 1;
  105452. const double N2 = (double)N / 2.;
  105453. FLAC__int32 n;
  105454. for (n = 0; n <= N; n++) {
  105455. double k = ((double)n - N2) / N2;
  105456. k = 1.0f - k * k;
  105457. window[n] = (FLAC__real)(k * k);
  105458. }
  105459. }
  105460. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  105461. {
  105462. const FLAC__int32 N = L - 1;
  105463. FLAC__int32 n;
  105464. for (n = 0; n < L; n++)
  105465. window[n] = (FLAC__real)(1.0f - 1.93f * cos(2.0f * M_PI * n / N) + 1.29f * cos(4.0f * M_PI * n / N) - 0.388f * cos(6.0f * M_PI * n / N) + 0.0322f * cos(8.0f * M_PI * n / N));
  105466. }
  105467. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  105468. {
  105469. const FLAC__int32 N = L - 1;
  105470. const double N2 = (double)N / 2.;
  105471. FLAC__int32 n;
  105472. for (n = 0; n <= N; n++) {
  105473. const double k = ((double)n - N2) / (stddev * N2);
  105474. window[n] = (FLAC__real)exp(-0.5f * k * k);
  105475. }
  105476. }
  105477. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  105478. {
  105479. const FLAC__int32 N = L - 1;
  105480. FLAC__int32 n;
  105481. for (n = 0; n < L; n++)
  105482. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  105483. }
  105484. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  105485. {
  105486. const FLAC__int32 N = L - 1;
  105487. FLAC__int32 n;
  105488. for (n = 0; n < L; n++)
  105489. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  105490. }
  105491. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  105492. {
  105493. const FLAC__int32 N = L - 1;
  105494. FLAC__int32 n;
  105495. for (n = 0; n < L; n++)
  105496. window[n] = (FLAC__real)(0.402f - 0.498f * cos(2.0f * M_PI * n / N) + 0.098f * cos(4.0f * M_PI * n / N) - 0.001f * cos(6.0f * M_PI * n / N));
  105497. }
  105498. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  105499. {
  105500. const FLAC__int32 N = L - 1;
  105501. FLAC__int32 n;
  105502. for (n = 0; n < L; n++)
  105503. window[n] = (FLAC__real)(0.3635819f - 0.4891775f*cos(2.0f*M_PI*n/N) + 0.1365995f*cos(4.0f*M_PI*n/N) - 0.0106411f*cos(6.0f*M_PI*n/N));
  105504. }
  105505. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  105506. {
  105507. FLAC__int32 n;
  105508. for (n = 0; n < L; n++)
  105509. window[n] = 1.0f;
  105510. }
  105511. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  105512. {
  105513. FLAC__int32 n;
  105514. if (L & 1) {
  105515. for (n = 1; n <= L+1/2; n++)
  105516. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  105517. for (; n <= L; n++)
  105518. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  105519. }
  105520. else {
  105521. for (n = 1; n <= L/2; n++)
  105522. window[n-1] = 2.0f * n / (float)L;
  105523. for (; n <= L; n++)
  105524. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  105525. }
  105526. }
  105527. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  105528. {
  105529. if (p <= 0.0)
  105530. FLAC__window_rectangle(window, L);
  105531. else if (p >= 1.0)
  105532. FLAC__window_hann(window, L);
  105533. else {
  105534. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  105535. FLAC__int32 n;
  105536. /* start with rectangle... */
  105537. FLAC__window_rectangle(window, L);
  105538. /* ...replace ends with hann */
  105539. if (Np > 0) {
  105540. for (n = 0; n <= Np; n++) {
  105541. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  105542. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  105543. }
  105544. }
  105545. }
  105546. }
  105547. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  105548. {
  105549. const FLAC__int32 N = L - 1;
  105550. const double N2 = (double)N / 2.;
  105551. FLAC__int32 n;
  105552. for (n = 0; n <= N; n++) {
  105553. const double k = ((double)n - N2) / N2;
  105554. window[n] = (FLAC__real)(1.0f - k * k);
  105555. }
  105556. }
  105557. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105558. #endif
  105559. /*** End of inlined file: window_flac.c ***/
  105560. #else
  105561. #include <FLAC/all.h>
  105562. #endif
  105563. }
  105564. #undef max
  105565. #undef min
  105566. BEGIN_JUCE_NAMESPACE
  105567. static const char* const flacFormatName = "FLAC file";
  105568. static const char* const flacExtensions[] = { ".flac", 0 };
  105569. class FlacReader : public AudioFormatReader
  105570. {
  105571. public:
  105572. FlacReader (InputStream* const in)
  105573. : AudioFormatReader (in, TRANS (flacFormatName)),
  105574. reservoir (2, 0),
  105575. reservoirStart (0),
  105576. samplesInReservoir (0),
  105577. scanningForLength (false)
  105578. {
  105579. using namespace FlacNamespace;
  105580. lengthInSamples = 0;
  105581. decoder = FLAC__stream_decoder_new();
  105582. ok = FLAC__stream_decoder_init_stream (decoder,
  105583. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  105584. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  105585. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  105586. if (ok)
  105587. {
  105588. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  105589. if (lengthInSamples == 0 && sampleRate > 0)
  105590. {
  105591. // the length hasn't been stored in the metadata, so we'll need to
  105592. // work it out the length the hard way, by scanning the whole file..
  105593. scanningForLength = true;
  105594. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  105595. scanningForLength = false;
  105596. const int64 tempLength = lengthInSamples;
  105597. FLAC__stream_decoder_reset (decoder);
  105598. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  105599. lengthInSamples = tempLength;
  105600. }
  105601. }
  105602. }
  105603. ~FlacReader()
  105604. {
  105605. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  105606. }
  105607. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  105608. {
  105609. sampleRate = info.sample_rate;
  105610. bitsPerSample = info.bits_per_sample;
  105611. lengthInSamples = (unsigned int) info.total_samples;
  105612. numChannels = info.channels;
  105613. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  105614. }
  105615. // returns the number of samples read
  105616. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  105617. int64 startSampleInFile, int numSamples)
  105618. {
  105619. using namespace FlacNamespace;
  105620. if (! ok)
  105621. return false;
  105622. while (numSamples > 0)
  105623. {
  105624. if (startSampleInFile >= reservoirStart
  105625. && startSampleInFile < reservoirStart + samplesInReservoir)
  105626. {
  105627. const int num = (int) jmin ((int64) numSamples,
  105628. reservoirStart + samplesInReservoir - startSampleInFile);
  105629. jassert (num > 0);
  105630. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  105631. if (destSamples[i] != 0)
  105632. memcpy (destSamples[i] + startOffsetInDestBuffer,
  105633. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  105634. sizeof (int) * num);
  105635. startOffsetInDestBuffer += num;
  105636. startSampleInFile += num;
  105637. numSamples -= num;
  105638. }
  105639. else
  105640. {
  105641. if (startSampleInFile >= (int) lengthInSamples)
  105642. {
  105643. samplesInReservoir = 0;
  105644. }
  105645. else if (startSampleInFile < reservoirStart
  105646. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  105647. {
  105648. // had some problems with flac crashing if the read pos is aligned more
  105649. // accurately than this. Probably fixed in newer versions of the library, though.
  105650. reservoirStart = (int) (startSampleInFile & ~511);
  105651. samplesInReservoir = 0;
  105652. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  105653. }
  105654. else
  105655. {
  105656. reservoirStart += samplesInReservoir;
  105657. samplesInReservoir = 0;
  105658. FLAC__stream_decoder_process_single (decoder);
  105659. }
  105660. if (samplesInReservoir == 0)
  105661. break;
  105662. }
  105663. }
  105664. if (numSamples > 0)
  105665. {
  105666. for (int i = numDestChannels; --i >= 0;)
  105667. if (destSamples[i] != 0)
  105668. zeromem (destSamples[i] + startOffsetInDestBuffer,
  105669. sizeof (int) * numSamples);
  105670. }
  105671. return true;
  105672. }
  105673. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  105674. {
  105675. if (scanningForLength)
  105676. {
  105677. lengthInSamples += numSamples;
  105678. }
  105679. else
  105680. {
  105681. if (numSamples > reservoir.getNumSamples())
  105682. reservoir.setSize (numChannels, numSamples, false, false, true);
  105683. const int bitsToShift = 32 - bitsPerSample;
  105684. for (int i = 0; i < (int) numChannels; ++i)
  105685. {
  105686. const FlacNamespace::FLAC__int32* src = buffer[i];
  105687. int n = i;
  105688. while (src == 0 && n > 0)
  105689. src = buffer [--n];
  105690. if (src != 0)
  105691. {
  105692. int* dest = (int*) reservoir.getSampleData(i);
  105693. for (int j = 0; j < numSamples; ++j)
  105694. dest[j] = src[j] << bitsToShift;
  105695. }
  105696. }
  105697. samplesInReservoir = numSamples;
  105698. }
  105699. }
  105700. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  105701. {
  105702. using namespace FlacNamespace;
  105703. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  105704. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105705. }
  105706. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  105707. {
  105708. using namespace FlacNamespace;
  105709. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  105710. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  105711. }
  105712. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  105713. {
  105714. using namespace FlacNamespace;
  105715. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  105716. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  105717. }
  105718. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  105719. {
  105720. using namespace FlacNamespace;
  105721. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  105722. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  105723. }
  105724. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  105725. {
  105726. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  105727. }
  105728. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  105729. const FlacNamespace::FLAC__Frame* frame,
  105730. const FlacNamespace::FLAC__int32* const buffer[],
  105731. void* client_data)
  105732. {
  105733. using namespace FlacNamespace;
  105734. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  105735. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105736. }
  105737. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  105738. const FlacNamespace::FLAC__StreamMetadata* metadata,
  105739. void* client_data)
  105740. {
  105741. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  105742. }
  105743. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  105744. {
  105745. }
  105746. juce_UseDebuggingNewOperator
  105747. private:
  105748. FlacNamespace::FLAC__StreamDecoder* decoder;
  105749. AudioSampleBuffer reservoir;
  105750. int reservoirStart, samplesInReservoir;
  105751. bool ok, scanningForLength;
  105752. FlacReader (const FlacReader&);
  105753. FlacReader& operator= (const FlacReader&);
  105754. };
  105755. class FlacWriter : public AudioFormatWriter
  105756. {
  105757. public:
  105758. FlacWriter (OutputStream* const out,
  105759. const double sampleRate_,
  105760. const int numChannels_,
  105761. const int bitsPerSample_)
  105762. : AudioFormatWriter (out, TRANS (flacFormatName),
  105763. sampleRate_,
  105764. numChannels_,
  105765. bitsPerSample_)
  105766. {
  105767. using namespace FlacNamespace;
  105768. encoder = FLAC__stream_encoder_new();
  105769. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  105770. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  105771. FLAC__stream_encoder_set_channels (encoder, numChannels);
  105772. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  105773. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  105774. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  105775. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  105776. ok = FLAC__stream_encoder_init_stream (encoder,
  105777. encodeWriteCallback, encodeSeekCallback,
  105778. encodeTellCallback, encodeMetadataCallback,
  105779. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  105780. }
  105781. ~FlacWriter()
  105782. {
  105783. if (ok)
  105784. {
  105785. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  105786. output->flush();
  105787. }
  105788. else
  105789. {
  105790. output = 0; // to stop the base class deleting this, as it needs to be returned
  105791. // to the caller of createWriter()
  105792. }
  105793. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  105794. }
  105795. bool write (const int** samplesToWrite, int numSamples)
  105796. {
  105797. using namespace FlacNamespace;
  105798. if (! ok)
  105799. return false;
  105800. int* buf[3];
  105801. const int bitsToShift = 32 - bitsPerSample;
  105802. if (bitsToShift > 0)
  105803. {
  105804. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  105805. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  105806. buf[0] = (int*) temp.getData();
  105807. buf[1] = buf[0] + numSamples;
  105808. buf[2] = 0;
  105809. for (int i = numChannelsToWrite; --i >= 0;)
  105810. {
  105811. if (samplesToWrite[i] != 0)
  105812. {
  105813. for (int j = 0; j < numSamples; ++j)
  105814. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  105815. }
  105816. }
  105817. samplesToWrite = (const int**) buf;
  105818. }
  105819. return FLAC__stream_encoder_process (encoder,
  105820. (const FLAC__int32**) samplesToWrite,
  105821. numSamples) != 0;
  105822. }
  105823. bool writeData (const void* const data, const int size) const
  105824. {
  105825. return output->write (data, size);
  105826. }
  105827. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  105828. {
  105829. using namespace FlacNamespace;
  105830. b += bytes;
  105831. for (int i = 0; i < bytes; ++i)
  105832. {
  105833. *(--b) = (FLAC__byte) (val & 0xff);
  105834. val >>= 8;
  105835. }
  105836. }
  105837. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  105838. {
  105839. using namespace FlacNamespace;
  105840. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  105841. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  105842. const unsigned int channelsMinus1 = info.channels - 1;
  105843. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  105844. packUint32 (info.min_blocksize, buffer, 2);
  105845. packUint32 (info.max_blocksize, buffer + 2, 2);
  105846. packUint32 (info.min_framesize, buffer + 4, 3);
  105847. packUint32 (info.max_framesize, buffer + 7, 3);
  105848. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  105849. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  105850. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  105851. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  105852. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  105853. memcpy (buffer + 18, info.md5sum, 16);
  105854. const bool seekOk = output->setPosition (4);
  105855. (void) seekOk;
  105856. // if this fails, you've given it an output stream that can't seek! It needs
  105857. // to be able to seek back to write the header
  105858. jassert (seekOk);
  105859. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  105860. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  105861. }
  105862. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  105863. const FlacNamespace::FLAC__byte buffer[],
  105864. size_t bytes,
  105865. unsigned int /*samples*/,
  105866. unsigned int /*current_frame*/,
  105867. void* client_data)
  105868. {
  105869. using namespace FlacNamespace;
  105870. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  105871. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  105872. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105873. }
  105874. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  105875. {
  105876. using namespace FlacNamespace;
  105877. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  105878. }
  105879. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  105880. {
  105881. using namespace FlacNamespace;
  105882. if (client_data == 0)
  105883. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  105884. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  105885. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105886. }
  105887. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  105888. {
  105889. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  105890. }
  105891. juce_UseDebuggingNewOperator
  105892. bool ok;
  105893. private:
  105894. FlacNamespace::FLAC__StreamEncoder* encoder;
  105895. MemoryBlock temp;
  105896. FlacWriter (const FlacWriter&);
  105897. FlacWriter& operator= (const FlacWriter&);
  105898. };
  105899. FlacAudioFormat::FlacAudioFormat()
  105900. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  105901. {
  105902. }
  105903. FlacAudioFormat::~FlacAudioFormat()
  105904. {
  105905. }
  105906. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  105907. {
  105908. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  105909. return Array <int> (rates);
  105910. }
  105911. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  105912. {
  105913. const int depths[] = { 16, 24, 0 };
  105914. return Array <int> (depths);
  105915. }
  105916. bool FlacAudioFormat::canDoStereo()
  105917. {
  105918. return true;
  105919. }
  105920. bool FlacAudioFormat::canDoMono()
  105921. {
  105922. return true;
  105923. }
  105924. bool FlacAudioFormat::isCompressed()
  105925. {
  105926. return true;
  105927. }
  105928. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  105929. const bool deleteStreamIfOpeningFails)
  105930. {
  105931. ScopedPointer<FlacReader> r (new FlacReader (in));
  105932. if (r->sampleRate != 0)
  105933. return r.release();
  105934. if (! deleteStreamIfOpeningFails)
  105935. r->input = 0;
  105936. return 0;
  105937. }
  105938. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  105939. double sampleRate,
  105940. unsigned int numberOfChannels,
  105941. int bitsPerSample,
  105942. const StringPairArray& /*metadataValues*/,
  105943. int /*qualityOptionIndex*/)
  105944. {
  105945. if (getPossibleBitDepths().contains (bitsPerSample))
  105946. {
  105947. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  105948. if (w->ok)
  105949. return w.release();
  105950. }
  105951. return 0;
  105952. }
  105953. END_JUCE_NAMESPACE
  105954. #endif
  105955. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  105956. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  105957. #if JUCE_USE_OGGVORBIS
  105958. #if JUCE_MAC
  105959. #define __MACOSX__ 1
  105960. #endif
  105961. namespace OggVorbisNamespace
  105962. {
  105963. #if JUCE_INCLUDE_OGGVORBIS_CODE
  105964. /*** Start of inlined file: vorbisenc.h ***/
  105965. #ifndef _OV_ENC_H_
  105966. #define _OV_ENC_H_
  105967. #ifdef __cplusplus
  105968. extern "C"
  105969. {
  105970. #endif /* __cplusplus */
  105971. /*** Start of inlined file: codec.h ***/
  105972. #ifndef _vorbis_codec_h_
  105973. #define _vorbis_codec_h_
  105974. #ifdef __cplusplus
  105975. extern "C"
  105976. {
  105977. #endif /* __cplusplus */
  105978. /*** Start of inlined file: ogg.h ***/
  105979. #ifndef _OGG_H
  105980. #define _OGG_H
  105981. #ifdef __cplusplus
  105982. extern "C" {
  105983. #endif
  105984. /*** Start of inlined file: os_types.h ***/
  105985. #ifndef _OS_TYPES_H
  105986. #define _OS_TYPES_H
  105987. /* make it easy on the folks that want to compile the libs with a
  105988. different malloc than stdlib */
  105989. #define _ogg_malloc malloc
  105990. #define _ogg_calloc calloc
  105991. #define _ogg_realloc realloc
  105992. #define _ogg_free free
  105993. #if defined(_WIN32)
  105994. # if defined(__CYGWIN__)
  105995. # include <_G_config.h>
  105996. typedef _G_int64_t ogg_int64_t;
  105997. typedef _G_int32_t ogg_int32_t;
  105998. typedef _G_uint32_t ogg_uint32_t;
  105999. typedef _G_int16_t ogg_int16_t;
  106000. typedef _G_uint16_t ogg_uint16_t;
  106001. # elif defined(__MINGW32__)
  106002. typedef short ogg_int16_t;
  106003. typedef unsigned short ogg_uint16_t;
  106004. typedef int ogg_int32_t;
  106005. typedef unsigned int ogg_uint32_t;
  106006. typedef long long ogg_int64_t;
  106007. typedef unsigned long long ogg_uint64_t;
  106008. # elif defined(__MWERKS__)
  106009. typedef long long ogg_int64_t;
  106010. typedef int ogg_int32_t;
  106011. typedef unsigned int ogg_uint32_t;
  106012. typedef short ogg_int16_t;
  106013. typedef unsigned short ogg_uint16_t;
  106014. # else
  106015. /* MSVC/Borland */
  106016. typedef __int64 ogg_int64_t;
  106017. typedef __int32 ogg_int32_t;
  106018. typedef unsigned __int32 ogg_uint32_t;
  106019. typedef __int16 ogg_int16_t;
  106020. typedef unsigned __int16 ogg_uint16_t;
  106021. # endif
  106022. #elif defined(__MACOS__)
  106023. # include <sys/types.h>
  106024. typedef SInt16 ogg_int16_t;
  106025. typedef UInt16 ogg_uint16_t;
  106026. typedef SInt32 ogg_int32_t;
  106027. typedef UInt32 ogg_uint32_t;
  106028. typedef SInt64 ogg_int64_t;
  106029. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106030. # include <sys/types.h>
  106031. typedef int16_t ogg_int16_t;
  106032. typedef u_int16_t ogg_uint16_t;
  106033. typedef int32_t ogg_int32_t;
  106034. typedef u_int32_t ogg_uint32_t;
  106035. typedef int64_t ogg_int64_t;
  106036. #elif defined(__BEOS__)
  106037. /* Be */
  106038. # include <inttypes.h>
  106039. typedef int16_t ogg_int16_t;
  106040. typedef u_int16_t ogg_uint16_t;
  106041. typedef int32_t ogg_int32_t;
  106042. typedef u_int32_t ogg_uint32_t;
  106043. typedef int64_t ogg_int64_t;
  106044. #elif defined (__EMX__)
  106045. /* OS/2 GCC */
  106046. typedef short ogg_int16_t;
  106047. typedef unsigned short ogg_uint16_t;
  106048. typedef int ogg_int32_t;
  106049. typedef unsigned int ogg_uint32_t;
  106050. typedef long long ogg_int64_t;
  106051. #elif defined (DJGPP)
  106052. /* DJGPP */
  106053. typedef short ogg_int16_t;
  106054. typedef int ogg_int32_t;
  106055. typedef unsigned int ogg_uint32_t;
  106056. typedef long long ogg_int64_t;
  106057. #elif defined(R5900)
  106058. /* PS2 EE */
  106059. typedef long ogg_int64_t;
  106060. typedef int ogg_int32_t;
  106061. typedef unsigned ogg_uint32_t;
  106062. typedef short ogg_int16_t;
  106063. #elif defined(__SYMBIAN32__)
  106064. /* Symbian GCC */
  106065. typedef signed short ogg_int16_t;
  106066. typedef unsigned short ogg_uint16_t;
  106067. typedef signed int ogg_int32_t;
  106068. typedef unsigned int ogg_uint32_t;
  106069. typedef long long int ogg_int64_t;
  106070. #else
  106071. # include <sys/types.h>
  106072. /*** Start of inlined file: config_types.h ***/
  106073. #ifndef __CONFIG_TYPES_H__
  106074. #define __CONFIG_TYPES_H__
  106075. typedef int16_t ogg_int16_t;
  106076. typedef unsigned short ogg_uint16_t;
  106077. typedef int32_t ogg_int32_t;
  106078. typedef unsigned int ogg_uint32_t;
  106079. typedef int64_t ogg_int64_t;
  106080. #endif
  106081. /*** End of inlined file: config_types.h ***/
  106082. #endif
  106083. #endif /* _OS_TYPES_H */
  106084. /*** End of inlined file: os_types.h ***/
  106085. typedef struct {
  106086. long endbyte;
  106087. int endbit;
  106088. unsigned char *buffer;
  106089. unsigned char *ptr;
  106090. long storage;
  106091. } oggpack_buffer;
  106092. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106093. typedef struct {
  106094. unsigned char *header;
  106095. long header_len;
  106096. unsigned char *body;
  106097. long body_len;
  106098. } ogg_page;
  106099. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106100. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106101. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106102. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106103. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106104. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106105. }
  106106. /* ogg_stream_state contains the current encode/decode state of a logical
  106107. Ogg bitstream **********************************************************/
  106108. typedef struct {
  106109. unsigned char *body_data; /* bytes from packet bodies */
  106110. long body_storage; /* storage elements allocated */
  106111. long body_fill; /* elements stored; fill mark */
  106112. long body_returned; /* elements of fill returned */
  106113. int *lacing_vals; /* The values that will go to the segment table */
  106114. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106115. this way, but it is simple coupled to the
  106116. lacing fifo */
  106117. long lacing_storage;
  106118. long lacing_fill;
  106119. long lacing_packet;
  106120. long lacing_returned;
  106121. unsigned char header[282]; /* working space for header encode */
  106122. int header_fill;
  106123. int e_o_s; /* set when we have buffered the last packet in the
  106124. logical bitstream */
  106125. int b_o_s; /* set after we've written the initial page
  106126. of a logical bitstream */
  106127. long serialno;
  106128. long pageno;
  106129. ogg_int64_t packetno; /* sequence number for decode; the framing
  106130. knows where there's a hole in the data,
  106131. but we need coupling so that the codec
  106132. (which is in a seperate abstraction
  106133. layer) also knows about the gap */
  106134. ogg_int64_t granulepos;
  106135. } ogg_stream_state;
  106136. /* ogg_packet is used to encapsulate the data and metadata belonging
  106137. to a single raw Ogg/Vorbis packet *************************************/
  106138. typedef struct {
  106139. unsigned char *packet;
  106140. long bytes;
  106141. long b_o_s;
  106142. long e_o_s;
  106143. ogg_int64_t granulepos;
  106144. ogg_int64_t packetno; /* sequence number for decode; the framing
  106145. knows where there's a hole in the data,
  106146. but we need coupling so that the codec
  106147. (which is in a seperate abstraction
  106148. layer) also knows about the gap */
  106149. } ogg_packet;
  106150. typedef struct {
  106151. unsigned char *data;
  106152. int storage;
  106153. int fill;
  106154. int returned;
  106155. int unsynced;
  106156. int headerbytes;
  106157. int bodybytes;
  106158. } ogg_sync_state;
  106159. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  106160. extern void oggpack_writeinit(oggpack_buffer *b);
  106161. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  106162. extern void oggpack_writealign(oggpack_buffer *b);
  106163. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  106164. extern void oggpack_reset(oggpack_buffer *b);
  106165. extern void oggpack_writeclear(oggpack_buffer *b);
  106166. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106167. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  106168. extern long oggpack_look(oggpack_buffer *b,int bits);
  106169. extern long oggpack_look1(oggpack_buffer *b);
  106170. extern void oggpack_adv(oggpack_buffer *b,int bits);
  106171. extern void oggpack_adv1(oggpack_buffer *b);
  106172. extern long oggpack_read(oggpack_buffer *b,int bits);
  106173. extern long oggpack_read1(oggpack_buffer *b);
  106174. extern long oggpack_bytes(oggpack_buffer *b);
  106175. extern long oggpack_bits(oggpack_buffer *b);
  106176. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  106177. extern void oggpackB_writeinit(oggpack_buffer *b);
  106178. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  106179. extern void oggpackB_writealign(oggpack_buffer *b);
  106180. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  106181. extern void oggpackB_reset(oggpack_buffer *b);
  106182. extern void oggpackB_writeclear(oggpack_buffer *b);
  106183. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106184. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  106185. extern long oggpackB_look(oggpack_buffer *b,int bits);
  106186. extern long oggpackB_look1(oggpack_buffer *b);
  106187. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  106188. extern void oggpackB_adv1(oggpack_buffer *b);
  106189. extern long oggpackB_read(oggpack_buffer *b,int bits);
  106190. extern long oggpackB_read1(oggpack_buffer *b);
  106191. extern long oggpackB_bytes(oggpack_buffer *b);
  106192. extern long oggpackB_bits(oggpack_buffer *b);
  106193. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  106194. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  106195. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  106196. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  106197. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  106198. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  106199. extern int ogg_sync_init(ogg_sync_state *oy);
  106200. extern int ogg_sync_clear(ogg_sync_state *oy);
  106201. extern int ogg_sync_reset(ogg_sync_state *oy);
  106202. extern int ogg_sync_destroy(ogg_sync_state *oy);
  106203. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  106204. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  106205. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  106206. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  106207. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  106208. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  106209. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  106210. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  106211. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  106212. extern int ogg_stream_clear(ogg_stream_state *os);
  106213. extern int ogg_stream_reset(ogg_stream_state *os);
  106214. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  106215. extern int ogg_stream_destroy(ogg_stream_state *os);
  106216. extern int ogg_stream_eos(ogg_stream_state *os);
  106217. extern void ogg_page_checksum_set(ogg_page *og);
  106218. extern int ogg_page_version(ogg_page *og);
  106219. extern int ogg_page_continued(ogg_page *og);
  106220. extern int ogg_page_bos(ogg_page *og);
  106221. extern int ogg_page_eos(ogg_page *og);
  106222. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  106223. extern int ogg_page_serialno(ogg_page *og);
  106224. extern long ogg_page_pageno(ogg_page *og);
  106225. extern int ogg_page_packets(ogg_page *og);
  106226. extern void ogg_packet_clear(ogg_packet *op);
  106227. #ifdef __cplusplus
  106228. }
  106229. #endif
  106230. #endif /* _OGG_H */
  106231. /*** End of inlined file: ogg.h ***/
  106232. typedef struct vorbis_info{
  106233. int version;
  106234. int channels;
  106235. long rate;
  106236. /* The below bitrate declarations are *hints*.
  106237. Combinations of the three values carry the following implications:
  106238. all three set to the same value:
  106239. implies a fixed rate bitstream
  106240. only nominal set:
  106241. implies a VBR stream that averages the nominal bitrate. No hard
  106242. upper/lower limit
  106243. upper and or lower set:
  106244. implies a VBR bitstream that obeys the bitrate limits. nominal
  106245. may also be set to give a nominal rate.
  106246. none set:
  106247. the coder does not care to speculate.
  106248. */
  106249. long bitrate_upper;
  106250. long bitrate_nominal;
  106251. long bitrate_lower;
  106252. long bitrate_window;
  106253. void *codec_setup;
  106254. } vorbis_info;
  106255. /* vorbis_dsp_state buffers the current vorbis audio
  106256. analysis/synthesis state. The DSP state belongs to a specific
  106257. logical bitstream ****************************************************/
  106258. typedef struct vorbis_dsp_state{
  106259. int analysisp;
  106260. vorbis_info *vi;
  106261. float **pcm;
  106262. float **pcmret;
  106263. int pcm_storage;
  106264. int pcm_current;
  106265. int pcm_returned;
  106266. int preextrapolate;
  106267. int eofflag;
  106268. long lW;
  106269. long W;
  106270. long nW;
  106271. long centerW;
  106272. ogg_int64_t granulepos;
  106273. ogg_int64_t sequence;
  106274. ogg_int64_t glue_bits;
  106275. ogg_int64_t time_bits;
  106276. ogg_int64_t floor_bits;
  106277. ogg_int64_t res_bits;
  106278. void *backend_state;
  106279. } vorbis_dsp_state;
  106280. typedef struct vorbis_block{
  106281. /* necessary stream state for linking to the framing abstraction */
  106282. float **pcm; /* this is a pointer into local storage */
  106283. oggpack_buffer opb;
  106284. long lW;
  106285. long W;
  106286. long nW;
  106287. int pcmend;
  106288. int mode;
  106289. int eofflag;
  106290. ogg_int64_t granulepos;
  106291. ogg_int64_t sequence;
  106292. vorbis_dsp_state *vd; /* For read-only access of configuration */
  106293. /* local storage to avoid remallocing; it's up to the mapping to
  106294. structure it */
  106295. void *localstore;
  106296. long localtop;
  106297. long localalloc;
  106298. long totaluse;
  106299. struct alloc_chain *reap;
  106300. /* bitmetrics for the frame */
  106301. long glue_bits;
  106302. long time_bits;
  106303. long floor_bits;
  106304. long res_bits;
  106305. void *internal;
  106306. } vorbis_block;
  106307. /* vorbis_block is a single block of data to be processed as part of
  106308. the analysis/synthesis stream; it belongs to a specific logical
  106309. bitstream, but is independant from other vorbis_blocks belonging to
  106310. that logical bitstream. *************************************************/
  106311. struct alloc_chain{
  106312. void *ptr;
  106313. struct alloc_chain *next;
  106314. };
  106315. /* vorbis_info contains all the setup information specific to the
  106316. specific compression/decompression mode in progress (eg,
  106317. psychoacoustic settings, channel setup, options, codebook
  106318. etc). vorbis_info and substructures are in backends.h.
  106319. *********************************************************************/
  106320. /* the comments are not part of vorbis_info so that vorbis_info can be
  106321. static storage */
  106322. typedef struct vorbis_comment{
  106323. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  106324. whatever vendor is set to in encode */
  106325. char **user_comments;
  106326. int *comment_lengths;
  106327. int comments;
  106328. char *vendor;
  106329. } vorbis_comment;
  106330. /* libvorbis encodes in two abstraction layers; first we perform DSP
  106331. and produce a packet (see docs/analysis.txt). The packet is then
  106332. coded into a framed OggSquish bitstream by the second layer (see
  106333. docs/framing.txt). Decode is the reverse process; we sync/frame
  106334. the bitstream and extract individual packets, then decode the
  106335. packet back into PCM audio.
  106336. The extra framing/packetizing is used in streaming formats, such as
  106337. files. Over the net (such as with UDP), the framing and
  106338. packetization aren't necessary as they're provided by the transport
  106339. and the streaming layer is not used */
  106340. /* Vorbis PRIMITIVES: general ***************************************/
  106341. extern void vorbis_info_init(vorbis_info *vi);
  106342. extern void vorbis_info_clear(vorbis_info *vi);
  106343. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  106344. extern void vorbis_comment_init(vorbis_comment *vc);
  106345. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  106346. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  106347. const char *tag, char *contents);
  106348. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  106349. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  106350. extern void vorbis_comment_clear(vorbis_comment *vc);
  106351. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  106352. extern int vorbis_block_clear(vorbis_block *vb);
  106353. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  106354. extern double vorbis_granule_time(vorbis_dsp_state *v,
  106355. ogg_int64_t granulepos);
  106356. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  106357. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106358. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  106359. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  106360. vorbis_comment *vc,
  106361. ogg_packet *op,
  106362. ogg_packet *op_comm,
  106363. ogg_packet *op_code);
  106364. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  106365. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  106366. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  106367. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  106368. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106369. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  106370. ogg_packet *op);
  106371. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  106372. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  106373. ogg_packet *op);
  106374. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106375. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  106376. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  106377. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  106378. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  106379. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  106380. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  106381. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  106382. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  106383. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  106384. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  106385. /* Vorbis ERRORS and return codes ***********************************/
  106386. #define OV_FALSE -1
  106387. #define OV_EOF -2
  106388. #define OV_HOLE -3
  106389. #define OV_EREAD -128
  106390. #define OV_EFAULT -129
  106391. #define OV_EIMPL -130
  106392. #define OV_EINVAL -131
  106393. #define OV_ENOTVORBIS -132
  106394. #define OV_EBADHEADER -133
  106395. #define OV_EVERSION -134
  106396. #define OV_ENOTAUDIO -135
  106397. #define OV_EBADPACKET -136
  106398. #define OV_EBADLINK -137
  106399. #define OV_ENOSEEK -138
  106400. #ifdef __cplusplus
  106401. }
  106402. #endif /* __cplusplus */
  106403. #endif
  106404. /*** End of inlined file: codec.h ***/
  106405. extern int vorbis_encode_init(vorbis_info *vi,
  106406. long channels,
  106407. long rate,
  106408. long max_bitrate,
  106409. long nominal_bitrate,
  106410. long min_bitrate);
  106411. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  106412. long channels,
  106413. long rate,
  106414. long max_bitrate,
  106415. long nominal_bitrate,
  106416. long min_bitrate);
  106417. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  106418. long channels,
  106419. long rate,
  106420. float quality /* quality level from 0. (lo) to 1. (hi) */
  106421. );
  106422. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  106423. long channels,
  106424. long rate,
  106425. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  106426. );
  106427. extern int vorbis_encode_setup_init(vorbis_info *vi);
  106428. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  106429. /* deprecated rate management supported only for compatability */
  106430. #define OV_ECTL_RATEMANAGE_GET 0x10
  106431. #define OV_ECTL_RATEMANAGE_SET 0x11
  106432. #define OV_ECTL_RATEMANAGE_AVG 0x12
  106433. #define OV_ECTL_RATEMANAGE_HARD 0x13
  106434. struct ovectl_ratemanage_arg {
  106435. int management_active;
  106436. long bitrate_hard_min;
  106437. long bitrate_hard_max;
  106438. double bitrate_hard_window;
  106439. long bitrate_av_lo;
  106440. long bitrate_av_hi;
  106441. double bitrate_av_window;
  106442. double bitrate_av_window_center;
  106443. };
  106444. /* new rate setup */
  106445. #define OV_ECTL_RATEMANAGE2_GET 0x14
  106446. #define OV_ECTL_RATEMANAGE2_SET 0x15
  106447. struct ovectl_ratemanage2_arg {
  106448. int management_active;
  106449. long bitrate_limit_min_kbps;
  106450. long bitrate_limit_max_kbps;
  106451. long bitrate_limit_reservoir_bits;
  106452. double bitrate_limit_reservoir_bias;
  106453. long bitrate_average_kbps;
  106454. double bitrate_average_damping;
  106455. };
  106456. #define OV_ECTL_LOWPASS_GET 0x20
  106457. #define OV_ECTL_LOWPASS_SET 0x21
  106458. #define OV_ECTL_IBLOCK_GET 0x30
  106459. #define OV_ECTL_IBLOCK_SET 0x31
  106460. #ifdef __cplusplus
  106461. }
  106462. #endif /* __cplusplus */
  106463. #endif
  106464. /*** End of inlined file: vorbisenc.h ***/
  106465. /*** Start of inlined file: vorbisfile.h ***/
  106466. #ifndef _OV_FILE_H_
  106467. #define _OV_FILE_H_
  106468. #ifdef __cplusplus
  106469. extern "C"
  106470. {
  106471. #endif /* __cplusplus */
  106472. #include <stdio.h>
  106473. /* The function prototypes for the callbacks are basically the same as for
  106474. * the stdio functions fread, fseek, fclose, ftell.
  106475. * The one difference is that the FILE * arguments have been replaced with
  106476. * a void * - this is to be used as a pointer to whatever internal data these
  106477. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  106478. *
  106479. * If you use other functions, check the docs for these functions and return
  106480. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  106481. * unseekable
  106482. */
  106483. typedef struct {
  106484. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  106485. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  106486. int (*close_func) (void *datasource);
  106487. long (*tell_func) (void *datasource);
  106488. } ov_callbacks;
  106489. #define NOTOPEN 0
  106490. #define PARTOPEN 1
  106491. #define OPENED 2
  106492. #define STREAMSET 3
  106493. #define INITSET 4
  106494. typedef struct OggVorbis_File {
  106495. void *datasource; /* Pointer to a FILE *, etc. */
  106496. int seekable;
  106497. ogg_int64_t offset;
  106498. ogg_int64_t end;
  106499. ogg_sync_state oy;
  106500. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  106501. stream appears */
  106502. int links;
  106503. ogg_int64_t *offsets;
  106504. ogg_int64_t *dataoffsets;
  106505. long *serialnos;
  106506. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  106507. compatability; x2 size, stores both
  106508. beginning and end values */
  106509. vorbis_info *vi;
  106510. vorbis_comment *vc;
  106511. /* Decoding working state local storage */
  106512. ogg_int64_t pcm_offset;
  106513. int ready_state;
  106514. long current_serialno;
  106515. int current_link;
  106516. double bittrack;
  106517. double samptrack;
  106518. ogg_stream_state os; /* take physical pages, weld into a logical
  106519. stream of packets */
  106520. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  106521. vorbis_block vb; /* local working space for packet->PCM decode */
  106522. ov_callbacks callbacks;
  106523. } OggVorbis_File;
  106524. extern int ov_clear(OggVorbis_File *vf);
  106525. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  106526. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  106527. char *initial, long ibytes, ov_callbacks callbacks);
  106528. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  106529. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  106530. char *initial, long ibytes, ov_callbacks callbacks);
  106531. extern int ov_test_open(OggVorbis_File *vf);
  106532. extern long ov_bitrate(OggVorbis_File *vf,int i);
  106533. extern long ov_bitrate_instant(OggVorbis_File *vf);
  106534. extern long ov_streams(OggVorbis_File *vf);
  106535. extern long ov_seekable(OggVorbis_File *vf);
  106536. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  106537. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  106538. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  106539. extern double ov_time_total(OggVorbis_File *vf,int i);
  106540. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  106541. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  106542. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  106543. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  106544. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  106545. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106546. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106547. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106548. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  106549. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  106550. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  106551. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  106552. extern double ov_time_tell(OggVorbis_File *vf);
  106553. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  106554. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  106555. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  106556. int *bitstream);
  106557. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  106558. int bigendianp,int word,int sgned,int *bitstream);
  106559. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  106560. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  106561. extern int ov_halfrate_p(OggVorbis_File *vf);
  106562. #ifdef __cplusplus
  106563. }
  106564. #endif /* __cplusplus */
  106565. #endif
  106566. /*** End of inlined file: vorbisfile.h ***/
  106567. /*** Start of inlined file: bitwise.c ***/
  106568. /* We're 'LSb' endian; if we write a word but read individual bits,
  106569. then we'll read the lsb first */
  106570. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  106571. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106572. // tasks..
  106573. #if JUCE_MSVC
  106574. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106575. #endif
  106576. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  106577. #if JUCE_USE_OGGVORBIS
  106578. #include <string.h>
  106579. #include <stdlib.h>
  106580. #define BUFFER_INCREMENT 256
  106581. static const unsigned long mask[]=
  106582. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  106583. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  106584. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  106585. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  106586. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  106587. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  106588. 0x3fffffff,0x7fffffff,0xffffffff };
  106589. static const unsigned int mask8B[]=
  106590. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  106591. void oggpack_writeinit(oggpack_buffer *b){
  106592. memset(b,0,sizeof(*b));
  106593. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  106594. b->buffer[0]='\0';
  106595. b->storage=BUFFER_INCREMENT;
  106596. }
  106597. void oggpackB_writeinit(oggpack_buffer *b){
  106598. oggpack_writeinit(b);
  106599. }
  106600. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  106601. long bytes=bits>>3;
  106602. bits-=bytes*8;
  106603. b->ptr=b->buffer+bytes;
  106604. b->endbit=bits;
  106605. b->endbyte=bytes;
  106606. *b->ptr&=mask[bits];
  106607. }
  106608. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  106609. long bytes=bits>>3;
  106610. bits-=bytes*8;
  106611. b->ptr=b->buffer+bytes;
  106612. b->endbit=bits;
  106613. b->endbyte=bytes;
  106614. *b->ptr&=mask8B[bits];
  106615. }
  106616. /* Takes only up to 32 bits. */
  106617. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  106618. if(b->endbyte+4>=b->storage){
  106619. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  106620. b->storage+=BUFFER_INCREMENT;
  106621. b->ptr=b->buffer+b->endbyte;
  106622. }
  106623. value&=mask[bits];
  106624. bits+=b->endbit;
  106625. b->ptr[0]|=value<<b->endbit;
  106626. if(bits>=8){
  106627. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  106628. if(bits>=16){
  106629. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  106630. if(bits>=24){
  106631. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  106632. if(bits>=32){
  106633. if(b->endbit)
  106634. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  106635. else
  106636. b->ptr[4]=0;
  106637. }
  106638. }
  106639. }
  106640. }
  106641. b->endbyte+=bits/8;
  106642. b->ptr+=bits/8;
  106643. b->endbit=bits&7;
  106644. }
  106645. /* Takes only up to 32 bits. */
  106646. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  106647. if(b->endbyte+4>=b->storage){
  106648. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  106649. b->storage+=BUFFER_INCREMENT;
  106650. b->ptr=b->buffer+b->endbyte;
  106651. }
  106652. value=(value&mask[bits])<<(32-bits);
  106653. bits+=b->endbit;
  106654. b->ptr[0]|=value>>(24+b->endbit);
  106655. if(bits>=8){
  106656. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  106657. if(bits>=16){
  106658. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  106659. if(bits>=24){
  106660. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  106661. if(bits>=32){
  106662. if(b->endbit)
  106663. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  106664. else
  106665. b->ptr[4]=0;
  106666. }
  106667. }
  106668. }
  106669. }
  106670. b->endbyte+=bits/8;
  106671. b->ptr+=bits/8;
  106672. b->endbit=bits&7;
  106673. }
  106674. void oggpack_writealign(oggpack_buffer *b){
  106675. int bits=8-b->endbit;
  106676. if(bits<8)
  106677. oggpack_write(b,0,bits);
  106678. }
  106679. void oggpackB_writealign(oggpack_buffer *b){
  106680. int bits=8-b->endbit;
  106681. if(bits<8)
  106682. oggpackB_write(b,0,bits);
  106683. }
  106684. static void oggpack_writecopy_helper(oggpack_buffer *b,
  106685. void *source,
  106686. long bits,
  106687. void (*w)(oggpack_buffer *,
  106688. unsigned long,
  106689. int),
  106690. int msb){
  106691. unsigned char *ptr=(unsigned char *)source;
  106692. long bytes=bits/8;
  106693. bits-=bytes*8;
  106694. if(b->endbit){
  106695. int i;
  106696. /* unaligned copy. Do it the hard way. */
  106697. for(i=0;i<bytes;i++)
  106698. w(b,(unsigned long)(ptr[i]),8);
  106699. }else{
  106700. /* aligned block copy */
  106701. if(b->endbyte+bytes+1>=b->storage){
  106702. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  106703. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  106704. b->ptr=b->buffer+b->endbyte;
  106705. }
  106706. memmove(b->ptr,source,bytes);
  106707. b->ptr+=bytes;
  106708. b->endbyte+=bytes;
  106709. *b->ptr=0;
  106710. }
  106711. if(bits){
  106712. if(msb)
  106713. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  106714. else
  106715. w(b,(unsigned long)(ptr[bytes]),bits);
  106716. }
  106717. }
  106718. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  106719. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  106720. }
  106721. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  106722. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  106723. }
  106724. void oggpack_reset(oggpack_buffer *b){
  106725. b->ptr=b->buffer;
  106726. b->buffer[0]=0;
  106727. b->endbit=b->endbyte=0;
  106728. }
  106729. void oggpackB_reset(oggpack_buffer *b){
  106730. oggpack_reset(b);
  106731. }
  106732. void oggpack_writeclear(oggpack_buffer *b){
  106733. _ogg_free(b->buffer);
  106734. memset(b,0,sizeof(*b));
  106735. }
  106736. void oggpackB_writeclear(oggpack_buffer *b){
  106737. oggpack_writeclear(b);
  106738. }
  106739. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  106740. memset(b,0,sizeof(*b));
  106741. b->buffer=b->ptr=buf;
  106742. b->storage=bytes;
  106743. }
  106744. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  106745. oggpack_readinit(b,buf,bytes);
  106746. }
  106747. /* Read in bits without advancing the bitptr; bits <= 32 */
  106748. long oggpack_look(oggpack_buffer *b,int bits){
  106749. unsigned long ret;
  106750. unsigned long m=mask[bits];
  106751. bits+=b->endbit;
  106752. if(b->endbyte+4>=b->storage){
  106753. /* not the main path */
  106754. if(b->endbyte*8+bits>b->storage*8)return(-1);
  106755. }
  106756. ret=b->ptr[0]>>b->endbit;
  106757. if(bits>8){
  106758. ret|=b->ptr[1]<<(8-b->endbit);
  106759. if(bits>16){
  106760. ret|=b->ptr[2]<<(16-b->endbit);
  106761. if(bits>24){
  106762. ret|=b->ptr[3]<<(24-b->endbit);
  106763. if(bits>32 && b->endbit)
  106764. ret|=b->ptr[4]<<(32-b->endbit);
  106765. }
  106766. }
  106767. }
  106768. return(m&ret);
  106769. }
  106770. /* Read in bits without advancing the bitptr; bits <= 32 */
  106771. long oggpackB_look(oggpack_buffer *b,int bits){
  106772. unsigned long ret;
  106773. int m=32-bits;
  106774. bits+=b->endbit;
  106775. if(b->endbyte+4>=b->storage){
  106776. /* not the main path */
  106777. if(b->endbyte*8+bits>b->storage*8)return(-1);
  106778. }
  106779. ret=b->ptr[0]<<(24+b->endbit);
  106780. if(bits>8){
  106781. ret|=b->ptr[1]<<(16+b->endbit);
  106782. if(bits>16){
  106783. ret|=b->ptr[2]<<(8+b->endbit);
  106784. if(bits>24){
  106785. ret|=b->ptr[3]<<(b->endbit);
  106786. if(bits>32 && b->endbit)
  106787. ret|=b->ptr[4]>>(8-b->endbit);
  106788. }
  106789. }
  106790. }
  106791. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  106792. }
  106793. long oggpack_look1(oggpack_buffer *b){
  106794. if(b->endbyte>=b->storage)return(-1);
  106795. return((b->ptr[0]>>b->endbit)&1);
  106796. }
  106797. long oggpackB_look1(oggpack_buffer *b){
  106798. if(b->endbyte>=b->storage)return(-1);
  106799. return((b->ptr[0]>>(7-b->endbit))&1);
  106800. }
  106801. void oggpack_adv(oggpack_buffer *b,int bits){
  106802. bits+=b->endbit;
  106803. b->ptr+=bits/8;
  106804. b->endbyte+=bits/8;
  106805. b->endbit=bits&7;
  106806. }
  106807. void oggpackB_adv(oggpack_buffer *b,int bits){
  106808. oggpack_adv(b,bits);
  106809. }
  106810. void oggpack_adv1(oggpack_buffer *b){
  106811. if(++(b->endbit)>7){
  106812. b->endbit=0;
  106813. b->ptr++;
  106814. b->endbyte++;
  106815. }
  106816. }
  106817. void oggpackB_adv1(oggpack_buffer *b){
  106818. oggpack_adv1(b);
  106819. }
  106820. /* bits <= 32 */
  106821. long oggpack_read(oggpack_buffer *b,int bits){
  106822. long ret;
  106823. unsigned long m=mask[bits];
  106824. bits+=b->endbit;
  106825. if(b->endbyte+4>=b->storage){
  106826. /* not the main path */
  106827. ret=-1L;
  106828. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  106829. }
  106830. ret=b->ptr[0]>>b->endbit;
  106831. if(bits>8){
  106832. ret|=b->ptr[1]<<(8-b->endbit);
  106833. if(bits>16){
  106834. ret|=b->ptr[2]<<(16-b->endbit);
  106835. if(bits>24){
  106836. ret|=b->ptr[3]<<(24-b->endbit);
  106837. if(bits>32 && b->endbit){
  106838. ret|=b->ptr[4]<<(32-b->endbit);
  106839. }
  106840. }
  106841. }
  106842. }
  106843. ret&=m;
  106844. overflow:
  106845. b->ptr+=bits/8;
  106846. b->endbyte+=bits/8;
  106847. b->endbit=bits&7;
  106848. return(ret);
  106849. }
  106850. /* bits <= 32 */
  106851. long oggpackB_read(oggpack_buffer *b,int bits){
  106852. long ret;
  106853. long m=32-bits;
  106854. bits+=b->endbit;
  106855. if(b->endbyte+4>=b->storage){
  106856. /* not the main path */
  106857. ret=-1L;
  106858. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  106859. }
  106860. ret=b->ptr[0]<<(24+b->endbit);
  106861. if(bits>8){
  106862. ret|=b->ptr[1]<<(16+b->endbit);
  106863. if(bits>16){
  106864. ret|=b->ptr[2]<<(8+b->endbit);
  106865. if(bits>24){
  106866. ret|=b->ptr[3]<<(b->endbit);
  106867. if(bits>32 && b->endbit)
  106868. ret|=b->ptr[4]>>(8-b->endbit);
  106869. }
  106870. }
  106871. }
  106872. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  106873. overflow:
  106874. b->ptr+=bits/8;
  106875. b->endbyte+=bits/8;
  106876. b->endbit=bits&7;
  106877. return(ret);
  106878. }
  106879. long oggpack_read1(oggpack_buffer *b){
  106880. long ret;
  106881. if(b->endbyte>=b->storage){
  106882. /* not the main path */
  106883. ret=-1L;
  106884. goto overflow;
  106885. }
  106886. ret=(b->ptr[0]>>b->endbit)&1;
  106887. overflow:
  106888. b->endbit++;
  106889. if(b->endbit>7){
  106890. b->endbit=0;
  106891. b->ptr++;
  106892. b->endbyte++;
  106893. }
  106894. return(ret);
  106895. }
  106896. long oggpackB_read1(oggpack_buffer *b){
  106897. long ret;
  106898. if(b->endbyte>=b->storage){
  106899. /* not the main path */
  106900. ret=-1L;
  106901. goto overflow;
  106902. }
  106903. ret=(b->ptr[0]>>(7-b->endbit))&1;
  106904. overflow:
  106905. b->endbit++;
  106906. if(b->endbit>7){
  106907. b->endbit=0;
  106908. b->ptr++;
  106909. b->endbyte++;
  106910. }
  106911. return(ret);
  106912. }
  106913. long oggpack_bytes(oggpack_buffer *b){
  106914. return(b->endbyte+(b->endbit+7)/8);
  106915. }
  106916. long oggpack_bits(oggpack_buffer *b){
  106917. return(b->endbyte*8+b->endbit);
  106918. }
  106919. long oggpackB_bytes(oggpack_buffer *b){
  106920. return oggpack_bytes(b);
  106921. }
  106922. long oggpackB_bits(oggpack_buffer *b){
  106923. return oggpack_bits(b);
  106924. }
  106925. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  106926. return(b->buffer);
  106927. }
  106928. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  106929. return oggpack_get_buffer(b);
  106930. }
  106931. /* Self test of the bitwise routines; everything else is based on
  106932. them, so they damned well better be solid. */
  106933. #ifdef _V_SELFTEST
  106934. #include <stdio.h>
  106935. static int ilog(unsigned int v){
  106936. int ret=0;
  106937. while(v){
  106938. ret++;
  106939. v>>=1;
  106940. }
  106941. return(ret);
  106942. }
  106943. oggpack_buffer o;
  106944. oggpack_buffer r;
  106945. void report(char *in){
  106946. fprintf(stderr,"%s",in);
  106947. exit(1);
  106948. }
  106949. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  106950. long bytes,i;
  106951. unsigned char *buffer;
  106952. oggpack_reset(&o);
  106953. for(i=0;i<vals;i++)
  106954. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  106955. buffer=oggpack_get_buffer(&o);
  106956. bytes=oggpack_bytes(&o);
  106957. if(bytes!=compsize)report("wrong number of bytes!\n");
  106958. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  106959. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  106960. report("wrote incorrect value!\n");
  106961. }
  106962. oggpack_readinit(&r,buffer,bytes);
  106963. for(i=0;i<vals;i++){
  106964. int tbit=bits?bits:ilog(b[i]);
  106965. if(oggpack_look(&r,tbit)==-1)
  106966. report("out of data!\n");
  106967. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  106968. report("looked at incorrect value!\n");
  106969. if(tbit==1)
  106970. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  106971. report("looked at single bit incorrect value!\n");
  106972. if(tbit==1){
  106973. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  106974. report("read incorrect single bit value!\n");
  106975. }else{
  106976. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  106977. report("read incorrect value!\n");
  106978. }
  106979. }
  106980. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  106981. }
  106982. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  106983. long bytes,i;
  106984. unsigned char *buffer;
  106985. oggpackB_reset(&o);
  106986. for(i=0;i<vals;i++)
  106987. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  106988. buffer=oggpackB_get_buffer(&o);
  106989. bytes=oggpackB_bytes(&o);
  106990. if(bytes!=compsize)report("wrong number of bytes!\n");
  106991. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  106992. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  106993. report("wrote incorrect value!\n");
  106994. }
  106995. oggpackB_readinit(&r,buffer,bytes);
  106996. for(i=0;i<vals;i++){
  106997. int tbit=bits?bits:ilog(b[i]);
  106998. if(oggpackB_look(&r,tbit)==-1)
  106999. report("out of data!\n");
  107000. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107001. report("looked at incorrect value!\n");
  107002. if(tbit==1)
  107003. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107004. report("looked at single bit incorrect value!\n");
  107005. if(tbit==1){
  107006. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107007. report("read incorrect single bit value!\n");
  107008. }else{
  107009. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107010. report("read incorrect value!\n");
  107011. }
  107012. }
  107013. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107014. }
  107015. int main(void){
  107016. unsigned char *buffer;
  107017. long bytes,i;
  107018. static unsigned long testbuffer1[]=
  107019. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107020. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107021. int test1size=43;
  107022. static unsigned long testbuffer2[]=
  107023. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107024. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107025. 85525151,0,12321,1,349528352};
  107026. int test2size=21;
  107027. static unsigned long testbuffer3[]=
  107028. {1,0,14,0,1,0,12,0,1,0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,1,1,1,1,1,0,0,1,
  107029. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107030. int test3size=56;
  107031. static unsigned long large[]=
  107032. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107033. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107034. 85525151,0,12321,1,2146528352};
  107035. int onesize=33;
  107036. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107037. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107038. 223,4};
  107039. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107040. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107041. 245,251,128};
  107042. int twosize=6;
  107043. static int two[6]={61,255,255,251,231,29};
  107044. static int twoB[6]={247,63,255,253,249,120};
  107045. int threesize=54;
  107046. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107047. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107048. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107049. 100,52,4,14,18,86,77,1};
  107050. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107051. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107052. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107053. 200,20,254,4,58,106,176,144,0};
  107054. int foursize=38;
  107055. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107056. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107057. 28,2,133,0,1};
  107058. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107059. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107060. 129,10,4,32};
  107061. int fivesize=45;
  107062. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107063. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107064. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107065. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107066. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107067. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107068. int sixsize=7;
  107069. static int six[7]={17,177,170,242,169,19,148};
  107070. static int sixB[7]={136,141,85,79,149,200,41};
  107071. /* Test read/write together */
  107072. /* Later we test against pregenerated bitstreams */
  107073. oggpack_writeinit(&o);
  107074. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107075. cliptest(testbuffer1,test1size,0,one,onesize);
  107076. fprintf(stderr,"ok.");
  107077. fprintf(stderr,"\nNull bit call (LSb): ");
  107078. cliptest(testbuffer3,test3size,0,two,twosize);
  107079. fprintf(stderr,"ok.");
  107080. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107081. cliptest(testbuffer2,test2size,0,three,threesize);
  107082. fprintf(stderr,"ok.");
  107083. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107084. oggpack_reset(&o);
  107085. for(i=0;i<test2size;i++)
  107086. oggpack_write(&o,large[i],32);
  107087. buffer=oggpack_get_buffer(&o);
  107088. bytes=oggpack_bytes(&o);
  107089. oggpack_readinit(&r,buffer,bytes);
  107090. for(i=0;i<test2size;i++){
  107091. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107092. if(oggpack_look(&r,32)!=large[i]){
  107093. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107094. oggpack_look(&r,32),large[i]);
  107095. report("read incorrect value!\n");
  107096. }
  107097. oggpack_adv(&r,32);
  107098. }
  107099. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107100. fprintf(stderr,"ok.");
  107101. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107102. cliptest(testbuffer1,test1size,7,four,foursize);
  107103. fprintf(stderr,"ok.");
  107104. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107105. cliptest(testbuffer2,test2size,17,five,fivesize);
  107106. fprintf(stderr,"ok.");
  107107. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107108. cliptest(testbuffer3,test3size,1,six,sixsize);
  107109. fprintf(stderr,"ok.");
  107110. fprintf(stderr,"\nTesting read past end (LSb): ");
  107111. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107112. for(i=0;i<64;i++){
  107113. if(oggpack_read(&r,1)!=0){
  107114. fprintf(stderr,"failed; got -1 prematurely.\n");
  107115. exit(1);
  107116. }
  107117. }
  107118. if(oggpack_look(&r,1)!=-1 ||
  107119. oggpack_read(&r,1)!=-1){
  107120. fprintf(stderr,"failed; read past end without -1.\n");
  107121. exit(1);
  107122. }
  107123. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107124. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  107125. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107126. exit(1);
  107127. }
  107128. if(oggpack_look(&r,18)!=0 ||
  107129. oggpack_look(&r,18)!=0){
  107130. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107131. exit(1);
  107132. }
  107133. if(oggpack_look(&r,19)!=-1 ||
  107134. oggpack_look(&r,19)!=-1){
  107135. fprintf(stderr,"failed; read past end without -1.\n");
  107136. exit(1);
  107137. }
  107138. if(oggpack_look(&r,32)!=-1 ||
  107139. oggpack_look(&r,32)!=-1){
  107140. fprintf(stderr,"failed; read past end without -1.\n");
  107141. exit(1);
  107142. }
  107143. oggpack_writeclear(&o);
  107144. fprintf(stderr,"ok.\n");
  107145. /********** lazy, cut-n-paste retest with MSb packing ***********/
  107146. /* Test read/write together */
  107147. /* Later we test against pregenerated bitstreams */
  107148. oggpackB_writeinit(&o);
  107149. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  107150. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  107151. fprintf(stderr,"ok.");
  107152. fprintf(stderr,"\nNull bit call (MSb): ");
  107153. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  107154. fprintf(stderr,"ok.");
  107155. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  107156. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  107157. fprintf(stderr,"ok.");
  107158. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  107159. oggpackB_reset(&o);
  107160. for(i=0;i<test2size;i++)
  107161. oggpackB_write(&o,large[i],32);
  107162. buffer=oggpackB_get_buffer(&o);
  107163. bytes=oggpackB_bytes(&o);
  107164. oggpackB_readinit(&r,buffer,bytes);
  107165. for(i=0;i<test2size;i++){
  107166. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  107167. if(oggpackB_look(&r,32)!=large[i]){
  107168. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  107169. oggpackB_look(&r,32),large[i]);
  107170. report("read incorrect value!\n");
  107171. }
  107172. oggpackB_adv(&r,32);
  107173. }
  107174. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107175. fprintf(stderr,"ok.");
  107176. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  107177. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  107178. fprintf(stderr,"ok.");
  107179. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  107180. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  107181. fprintf(stderr,"ok.");
  107182. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  107183. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  107184. fprintf(stderr,"ok.");
  107185. fprintf(stderr,"\nTesting read past end (MSb): ");
  107186. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107187. for(i=0;i<64;i++){
  107188. if(oggpackB_read(&r,1)!=0){
  107189. fprintf(stderr,"failed; got -1 prematurely.\n");
  107190. exit(1);
  107191. }
  107192. }
  107193. if(oggpackB_look(&r,1)!=-1 ||
  107194. oggpackB_read(&r,1)!=-1){
  107195. fprintf(stderr,"failed; read past end without -1.\n");
  107196. exit(1);
  107197. }
  107198. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107199. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  107200. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107201. exit(1);
  107202. }
  107203. if(oggpackB_look(&r,18)!=0 ||
  107204. oggpackB_look(&r,18)!=0){
  107205. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107206. exit(1);
  107207. }
  107208. if(oggpackB_look(&r,19)!=-1 ||
  107209. oggpackB_look(&r,19)!=-1){
  107210. fprintf(stderr,"failed; read past end without -1.\n");
  107211. exit(1);
  107212. }
  107213. if(oggpackB_look(&r,32)!=-1 ||
  107214. oggpackB_look(&r,32)!=-1){
  107215. fprintf(stderr,"failed; read past end without -1.\n");
  107216. exit(1);
  107217. }
  107218. oggpackB_writeclear(&o);
  107219. fprintf(stderr,"ok.\n\n");
  107220. return(0);
  107221. }
  107222. #endif /* _V_SELFTEST */
  107223. #undef BUFFER_INCREMENT
  107224. #endif
  107225. /*** End of inlined file: bitwise.c ***/
  107226. /*** Start of inlined file: framing.c ***/
  107227. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107228. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107229. // tasks..
  107230. #if JUCE_MSVC
  107231. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107232. #endif
  107233. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107234. #if JUCE_USE_OGGVORBIS
  107235. #include <stdlib.h>
  107236. #include <string.h>
  107237. /* A complete description of Ogg framing exists in docs/framing.html */
  107238. int ogg_page_version(ogg_page *og){
  107239. return((int)(og->header[4]));
  107240. }
  107241. int ogg_page_continued(ogg_page *og){
  107242. return((int)(og->header[5]&0x01));
  107243. }
  107244. int ogg_page_bos(ogg_page *og){
  107245. return((int)(og->header[5]&0x02));
  107246. }
  107247. int ogg_page_eos(ogg_page *og){
  107248. return((int)(og->header[5]&0x04));
  107249. }
  107250. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  107251. unsigned char *page=og->header;
  107252. ogg_int64_t granulepos=page[13]&(0xff);
  107253. granulepos= (granulepos<<8)|(page[12]&0xff);
  107254. granulepos= (granulepos<<8)|(page[11]&0xff);
  107255. granulepos= (granulepos<<8)|(page[10]&0xff);
  107256. granulepos= (granulepos<<8)|(page[9]&0xff);
  107257. granulepos= (granulepos<<8)|(page[8]&0xff);
  107258. granulepos= (granulepos<<8)|(page[7]&0xff);
  107259. granulepos= (granulepos<<8)|(page[6]&0xff);
  107260. return(granulepos);
  107261. }
  107262. int ogg_page_serialno(ogg_page *og){
  107263. return(og->header[14] |
  107264. (og->header[15]<<8) |
  107265. (og->header[16]<<16) |
  107266. (og->header[17]<<24));
  107267. }
  107268. long ogg_page_pageno(ogg_page *og){
  107269. return(og->header[18] |
  107270. (og->header[19]<<8) |
  107271. (og->header[20]<<16) |
  107272. (og->header[21]<<24));
  107273. }
  107274. /* returns the number of packets that are completed on this page (if
  107275. the leading packet is begun on a previous page, but ends on this
  107276. page, it's counted */
  107277. /* NOTE:
  107278. If a page consists of a packet begun on a previous page, and a new
  107279. packet begun (but not completed) on this page, the return will be:
  107280. ogg_page_packets(page) ==1,
  107281. ogg_page_continued(page) !=0
  107282. If a page happens to be a single packet that was begun on a
  107283. previous page, and spans to the next page (in the case of a three or
  107284. more page packet), the return will be:
  107285. ogg_page_packets(page) ==0,
  107286. ogg_page_continued(page) !=0
  107287. */
  107288. int ogg_page_packets(ogg_page *og){
  107289. int i,n=og->header[26],count=0;
  107290. for(i=0;i<n;i++)
  107291. if(og->header[27+i]<255)count++;
  107292. return(count);
  107293. }
  107294. #if 0
  107295. /* helper to initialize lookup for direct-table CRC (illustrative; we
  107296. use the static init below) */
  107297. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  107298. int i;
  107299. unsigned long r;
  107300. r = index << 24;
  107301. for (i=0; i<8; i++)
  107302. if (r & 0x80000000UL)
  107303. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  107304. polynomial, although we use an
  107305. unreflected alg and an init/final
  107306. of 0, not 0xffffffff */
  107307. else
  107308. r<<=1;
  107309. return (r & 0xffffffffUL);
  107310. }
  107311. #endif
  107312. static const ogg_uint32_t crc_lookup[256]={
  107313. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  107314. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  107315. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  107316. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  107317. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  107318. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  107319. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  107320. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  107321. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  107322. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  107323. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  107324. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  107325. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  107326. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  107327. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  107328. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  107329. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  107330. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  107331. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  107332. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  107333. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  107334. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  107335. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  107336. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  107337. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  107338. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  107339. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  107340. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  107341. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  107342. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  107343. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  107344. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  107345. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  107346. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  107347. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  107348. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  107349. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  107350. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  107351. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  107352. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  107353. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  107354. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  107355. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  107356. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  107357. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  107358. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  107359. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  107360. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  107361. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  107362. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  107363. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  107364. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  107365. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  107366. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  107367. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  107368. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  107369. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  107370. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  107371. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  107372. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  107373. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  107374. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  107375. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  107376. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  107377. /* init the encode/decode logical stream state */
  107378. int ogg_stream_init(ogg_stream_state *os,int serialno){
  107379. if(os){
  107380. memset(os,0,sizeof(*os));
  107381. os->body_storage=16*1024;
  107382. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  107383. os->lacing_storage=1024;
  107384. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  107385. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  107386. os->serialno=serialno;
  107387. return(0);
  107388. }
  107389. return(-1);
  107390. }
  107391. /* _clear does not free os, only the non-flat storage within */
  107392. int ogg_stream_clear(ogg_stream_state *os){
  107393. if(os){
  107394. if(os->body_data)_ogg_free(os->body_data);
  107395. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  107396. if(os->granule_vals)_ogg_free(os->granule_vals);
  107397. memset(os,0,sizeof(*os));
  107398. }
  107399. return(0);
  107400. }
  107401. int ogg_stream_destroy(ogg_stream_state *os){
  107402. if(os){
  107403. ogg_stream_clear(os);
  107404. _ogg_free(os);
  107405. }
  107406. return(0);
  107407. }
  107408. /* Helpers for ogg_stream_encode; this keeps the structure and
  107409. what's happening fairly clear */
  107410. static void _os_body_expand(ogg_stream_state *os,int needed){
  107411. if(os->body_storage<=os->body_fill+needed){
  107412. os->body_storage+=(needed+1024);
  107413. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  107414. }
  107415. }
  107416. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  107417. if(os->lacing_storage<=os->lacing_fill+needed){
  107418. os->lacing_storage+=(needed+32);
  107419. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  107420. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  107421. }
  107422. }
  107423. /* checksum the page */
  107424. /* Direct table CRC; note that this will be faster in the future if we
  107425. perform the checksum silmultaneously with other copies */
  107426. void ogg_page_checksum_set(ogg_page *og){
  107427. if(og){
  107428. ogg_uint32_t crc_reg=0;
  107429. int i;
  107430. /* safety; needed for API behavior, but not framing code */
  107431. og->header[22]=0;
  107432. og->header[23]=0;
  107433. og->header[24]=0;
  107434. og->header[25]=0;
  107435. for(i=0;i<og->header_len;i++)
  107436. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  107437. for(i=0;i<og->body_len;i++)
  107438. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  107439. og->header[22]=(unsigned char)(crc_reg&0xff);
  107440. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  107441. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  107442. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  107443. }
  107444. }
  107445. /* submit data to the internal buffer of the framing engine */
  107446. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  107447. int lacing_vals=op->bytes/255+1,i;
  107448. if(os->body_returned){
  107449. /* advance packet data according to the body_returned pointer. We
  107450. had to keep it around to return a pointer into the buffer last
  107451. call */
  107452. os->body_fill-=os->body_returned;
  107453. if(os->body_fill)
  107454. memmove(os->body_data,os->body_data+os->body_returned,
  107455. os->body_fill);
  107456. os->body_returned=0;
  107457. }
  107458. /* make sure we have the buffer storage */
  107459. _os_body_expand(os,op->bytes);
  107460. _os_lacing_expand(os,lacing_vals);
  107461. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  107462. the liability of overly clean abstraction for the time being. It
  107463. will actually be fairly easy to eliminate the extra copy in the
  107464. future */
  107465. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  107466. os->body_fill+=op->bytes;
  107467. /* Store lacing vals for this packet */
  107468. for(i=0;i<lacing_vals-1;i++){
  107469. os->lacing_vals[os->lacing_fill+i]=255;
  107470. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  107471. }
  107472. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  107473. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  107474. /* flag the first segment as the beginning of the packet */
  107475. os->lacing_vals[os->lacing_fill]|= 0x100;
  107476. os->lacing_fill+=lacing_vals;
  107477. /* for the sake of completeness */
  107478. os->packetno++;
  107479. if(op->e_o_s)os->e_o_s=1;
  107480. return(0);
  107481. }
  107482. /* This will flush remaining packets into a page (returning nonzero),
  107483. even if there is not enough data to trigger a flush normally
  107484. (undersized page). If there are no packets or partial packets to
  107485. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  107486. try to flush a normal sized page like ogg_stream_pageout; a call to
  107487. ogg_stream_flush does not guarantee that all packets have flushed.
  107488. Only a return value of 0 from ogg_stream_flush indicates all packet
  107489. data is flushed into pages.
  107490. since ogg_stream_flush will flush the last page in a stream even if
  107491. it's undersized, you almost certainly want to use ogg_stream_pageout
  107492. (and *not* ogg_stream_flush) unless you specifically need to flush
  107493. an page regardless of size in the middle of a stream. */
  107494. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  107495. int i;
  107496. int vals=0;
  107497. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  107498. int bytes=0;
  107499. long acc=0;
  107500. ogg_int64_t granule_pos=-1;
  107501. if(maxvals==0)return(0);
  107502. /* construct a page */
  107503. /* decide how many segments to include */
  107504. /* If this is the initial header case, the first page must only include
  107505. the initial header packet */
  107506. if(os->b_o_s==0){ /* 'initial header page' case */
  107507. granule_pos=0;
  107508. for(vals=0;vals<maxvals;vals++){
  107509. if((os->lacing_vals[vals]&0x0ff)<255){
  107510. vals++;
  107511. break;
  107512. }
  107513. }
  107514. }else{
  107515. for(vals=0;vals<maxvals;vals++){
  107516. if(acc>4096)break;
  107517. acc+=os->lacing_vals[vals]&0x0ff;
  107518. if((os->lacing_vals[vals]&0xff)<255)
  107519. granule_pos=os->granule_vals[vals];
  107520. }
  107521. }
  107522. /* construct the header in temp storage */
  107523. memcpy(os->header,"OggS",4);
  107524. /* stream structure version */
  107525. os->header[4]=0x00;
  107526. /* continued packet flag? */
  107527. os->header[5]=0x00;
  107528. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  107529. /* first page flag? */
  107530. if(os->b_o_s==0)os->header[5]|=0x02;
  107531. /* last page flag? */
  107532. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  107533. os->b_o_s=1;
  107534. /* 64 bits of PCM position */
  107535. for(i=6;i<14;i++){
  107536. os->header[i]=(unsigned char)(granule_pos&0xff);
  107537. granule_pos>>=8;
  107538. }
  107539. /* 32 bits of stream serial number */
  107540. {
  107541. long serialno=os->serialno;
  107542. for(i=14;i<18;i++){
  107543. os->header[i]=(unsigned char)(serialno&0xff);
  107544. serialno>>=8;
  107545. }
  107546. }
  107547. /* 32 bits of page counter (we have both counter and page header
  107548. because this val can roll over) */
  107549. if(os->pageno==-1)os->pageno=0; /* because someone called
  107550. stream_reset; this would be a
  107551. strange thing to do in an
  107552. encode stream, but it has
  107553. plausible uses */
  107554. {
  107555. long pageno=os->pageno++;
  107556. for(i=18;i<22;i++){
  107557. os->header[i]=(unsigned char)(pageno&0xff);
  107558. pageno>>=8;
  107559. }
  107560. }
  107561. /* zero for computation; filled in later */
  107562. os->header[22]=0;
  107563. os->header[23]=0;
  107564. os->header[24]=0;
  107565. os->header[25]=0;
  107566. /* segment table */
  107567. os->header[26]=(unsigned char)(vals&0xff);
  107568. for(i=0;i<vals;i++)
  107569. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  107570. /* set pointers in the ogg_page struct */
  107571. og->header=os->header;
  107572. og->header_len=os->header_fill=vals+27;
  107573. og->body=os->body_data+os->body_returned;
  107574. og->body_len=bytes;
  107575. /* advance the lacing data and set the body_returned pointer */
  107576. os->lacing_fill-=vals;
  107577. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  107578. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  107579. os->body_returned+=bytes;
  107580. /* calculate the checksum */
  107581. ogg_page_checksum_set(og);
  107582. /* done */
  107583. return(1);
  107584. }
  107585. /* This constructs pages from buffered packet segments. The pointers
  107586. returned are to static buffers; do not free. The returned buffers are
  107587. good only until the next call (using the same ogg_stream_state) */
  107588. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  107589. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  107590. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  107591. os->lacing_fill>=255 || /* 'segment table full' case */
  107592. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  107593. return(ogg_stream_flush(os,og));
  107594. }
  107595. /* not enough data to construct a page and not end of stream */
  107596. return(0);
  107597. }
  107598. int ogg_stream_eos(ogg_stream_state *os){
  107599. return os->e_o_s;
  107600. }
  107601. /* DECODING PRIMITIVES: packet streaming layer **********************/
  107602. /* This has two layers to place more of the multi-serialno and paging
  107603. control in the application's hands. First, we expose a data buffer
  107604. using ogg_sync_buffer(). The app either copies into the
  107605. buffer, or passes it directly to read(), etc. We then call
  107606. ogg_sync_wrote() to tell how many bytes we just added.
  107607. Pages are returned (pointers into the buffer in ogg_sync_state)
  107608. by ogg_sync_pageout(). The page is then submitted to
  107609. ogg_stream_pagein() along with the appropriate
  107610. ogg_stream_state* (ie, matching serialno). We then get raw
  107611. packets out calling ogg_stream_packetout() with a
  107612. ogg_stream_state. */
  107613. /* initialize the struct to a known state */
  107614. int ogg_sync_init(ogg_sync_state *oy){
  107615. if(oy){
  107616. memset(oy,0,sizeof(*oy));
  107617. }
  107618. return(0);
  107619. }
  107620. /* clear non-flat storage within */
  107621. int ogg_sync_clear(ogg_sync_state *oy){
  107622. if(oy){
  107623. if(oy->data)_ogg_free(oy->data);
  107624. ogg_sync_init(oy);
  107625. }
  107626. return(0);
  107627. }
  107628. int ogg_sync_destroy(ogg_sync_state *oy){
  107629. if(oy){
  107630. ogg_sync_clear(oy);
  107631. _ogg_free(oy);
  107632. }
  107633. return(0);
  107634. }
  107635. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  107636. /* first, clear out any space that has been previously returned */
  107637. if(oy->returned){
  107638. oy->fill-=oy->returned;
  107639. if(oy->fill>0)
  107640. memmove(oy->data,oy->data+oy->returned,oy->fill);
  107641. oy->returned=0;
  107642. }
  107643. if(size>oy->storage-oy->fill){
  107644. /* We need to extend the internal buffer */
  107645. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  107646. if(oy->data)
  107647. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  107648. else
  107649. oy->data=(unsigned char*) _ogg_malloc(newsize);
  107650. oy->storage=newsize;
  107651. }
  107652. /* expose a segment at least as large as requested at the fill mark */
  107653. return((char *)oy->data+oy->fill);
  107654. }
  107655. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  107656. if(oy->fill+bytes>oy->storage)return(-1);
  107657. oy->fill+=bytes;
  107658. return(0);
  107659. }
  107660. /* sync the stream. This is meant to be useful for finding page
  107661. boundaries.
  107662. return values for this:
  107663. -n) skipped n bytes
  107664. 0) page not ready; more data (no bytes skipped)
  107665. n) page synced at current location; page length n bytes
  107666. */
  107667. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  107668. unsigned char *page=oy->data+oy->returned;
  107669. unsigned char *next;
  107670. long bytes=oy->fill-oy->returned;
  107671. if(oy->headerbytes==0){
  107672. int headerbytes,i;
  107673. if(bytes<27)return(0); /* not enough for a header */
  107674. /* verify capture pattern */
  107675. if(memcmp(page,"OggS",4))goto sync_fail;
  107676. headerbytes=page[26]+27;
  107677. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  107678. /* count up body length in the segment table */
  107679. for(i=0;i<page[26];i++)
  107680. oy->bodybytes+=page[27+i];
  107681. oy->headerbytes=headerbytes;
  107682. }
  107683. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  107684. /* The whole test page is buffered. Verify the checksum */
  107685. {
  107686. /* Grab the checksum bytes, set the header field to zero */
  107687. char chksum[4];
  107688. ogg_page log;
  107689. memcpy(chksum,page+22,4);
  107690. memset(page+22,0,4);
  107691. /* set up a temp page struct and recompute the checksum */
  107692. log.header=page;
  107693. log.header_len=oy->headerbytes;
  107694. log.body=page+oy->headerbytes;
  107695. log.body_len=oy->bodybytes;
  107696. ogg_page_checksum_set(&log);
  107697. /* Compare */
  107698. if(memcmp(chksum,page+22,4)){
  107699. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  107700. at all) */
  107701. /* replace the computed checksum with the one actually read in */
  107702. memcpy(page+22,chksum,4);
  107703. /* Bad checksum. Lose sync */
  107704. goto sync_fail;
  107705. }
  107706. }
  107707. /* yes, have a whole page all ready to go */
  107708. {
  107709. unsigned char *page=oy->data+oy->returned;
  107710. long bytes;
  107711. if(og){
  107712. og->header=page;
  107713. og->header_len=oy->headerbytes;
  107714. og->body=page+oy->headerbytes;
  107715. og->body_len=oy->bodybytes;
  107716. }
  107717. oy->unsynced=0;
  107718. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  107719. oy->headerbytes=0;
  107720. oy->bodybytes=0;
  107721. return(bytes);
  107722. }
  107723. sync_fail:
  107724. oy->headerbytes=0;
  107725. oy->bodybytes=0;
  107726. /* search for possible capture */
  107727. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  107728. if(!next)
  107729. next=oy->data+oy->fill;
  107730. oy->returned=next-oy->data;
  107731. return(-(next-page));
  107732. }
  107733. /* sync the stream and get a page. Keep trying until we find a page.
  107734. Supress 'sync errors' after reporting the first.
  107735. return values:
  107736. -1) recapture (hole in data)
  107737. 0) need more data
  107738. 1) page returned
  107739. Returns pointers into buffered data; invalidated by next call to
  107740. _stream, _clear, _init, or _buffer */
  107741. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  107742. /* all we need to do is verify a page at the head of the stream
  107743. buffer. If it doesn't verify, we look for the next potential
  107744. frame */
  107745. for(;;){
  107746. long ret=ogg_sync_pageseek(oy,og);
  107747. if(ret>0){
  107748. /* have a page */
  107749. return(1);
  107750. }
  107751. if(ret==0){
  107752. /* need more data */
  107753. return(0);
  107754. }
  107755. /* head did not start a synced page... skipped some bytes */
  107756. if(!oy->unsynced){
  107757. oy->unsynced=1;
  107758. return(-1);
  107759. }
  107760. /* loop. keep looking */
  107761. }
  107762. }
  107763. /* add the incoming page to the stream state; we decompose the page
  107764. into packet segments here as well. */
  107765. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  107766. unsigned char *header=og->header;
  107767. unsigned char *body=og->body;
  107768. long bodysize=og->body_len;
  107769. int segptr=0;
  107770. int version=ogg_page_version(og);
  107771. int continued=ogg_page_continued(og);
  107772. int bos=ogg_page_bos(og);
  107773. int eos=ogg_page_eos(og);
  107774. ogg_int64_t granulepos=ogg_page_granulepos(og);
  107775. int serialno=ogg_page_serialno(og);
  107776. long pageno=ogg_page_pageno(og);
  107777. int segments=header[26];
  107778. /* clean up 'returned data' */
  107779. {
  107780. long lr=os->lacing_returned;
  107781. long br=os->body_returned;
  107782. /* body data */
  107783. if(br){
  107784. os->body_fill-=br;
  107785. if(os->body_fill)
  107786. memmove(os->body_data,os->body_data+br,os->body_fill);
  107787. os->body_returned=0;
  107788. }
  107789. if(lr){
  107790. /* segment table */
  107791. if(os->lacing_fill-lr){
  107792. memmove(os->lacing_vals,os->lacing_vals+lr,
  107793. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  107794. memmove(os->granule_vals,os->granule_vals+lr,
  107795. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  107796. }
  107797. os->lacing_fill-=lr;
  107798. os->lacing_packet-=lr;
  107799. os->lacing_returned=0;
  107800. }
  107801. }
  107802. /* check the serial number */
  107803. if(serialno!=os->serialno)return(-1);
  107804. if(version>0)return(-1);
  107805. _os_lacing_expand(os,segments+1);
  107806. /* are we in sequence? */
  107807. if(pageno!=os->pageno){
  107808. int i;
  107809. /* unroll previous partial packet (if any) */
  107810. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  107811. os->body_fill-=os->lacing_vals[i]&0xff;
  107812. os->lacing_fill=os->lacing_packet;
  107813. /* make a note of dropped data in segment table */
  107814. if(os->pageno!=-1){
  107815. os->lacing_vals[os->lacing_fill++]=0x400;
  107816. os->lacing_packet++;
  107817. }
  107818. }
  107819. /* are we a 'continued packet' page? If so, we may need to skip
  107820. some segments */
  107821. if(continued){
  107822. if(os->lacing_fill<1 ||
  107823. os->lacing_vals[os->lacing_fill-1]==0x400){
  107824. bos=0;
  107825. for(;segptr<segments;segptr++){
  107826. int val=header[27+segptr];
  107827. body+=val;
  107828. bodysize-=val;
  107829. if(val<255){
  107830. segptr++;
  107831. break;
  107832. }
  107833. }
  107834. }
  107835. }
  107836. if(bodysize){
  107837. _os_body_expand(os,bodysize);
  107838. memcpy(os->body_data+os->body_fill,body,bodysize);
  107839. os->body_fill+=bodysize;
  107840. }
  107841. {
  107842. int saved=-1;
  107843. while(segptr<segments){
  107844. int val=header[27+segptr];
  107845. os->lacing_vals[os->lacing_fill]=val;
  107846. os->granule_vals[os->lacing_fill]=-1;
  107847. if(bos){
  107848. os->lacing_vals[os->lacing_fill]|=0x100;
  107849. bos=0;
  107850. }
  107851. if(val<255)saved=os->lacing_fill;
  107852. os->lacing_fill++;
  107853. segptr++;
  107854. if(val<255)os->lacing_packet=os->lacing_fill;
  107855. }
  107856. /* set the granulepos on the last granuleval of the last full packet */
  107857. if(saved!=-1){
  107858. os->granule_vals[saved]=granulepos;
  107859. }
  107860. }
  107861. if(eos){
  107862. os->e_o_s=1;
  107863. if(os->lacing_fill>0)
  107864. os->lacing_vals[os->lacing_fill-1]|=0x200;
  107865. }
  107866. os->pageno=pageno+1;
  107867. return(0);
  107868. }
  107869. /* clear things to an initial state. Good to call, eg, before seeking */
  107870. int ogg_sync_reset(ogg_sync_state *oy){
  107871. oy->fill=0;
  107872. oy->returned=0;
  107873. oy->unsynced=0;
  107874. oy->headerbytes=0;
  107875. oy->bodybytes=0;
  107876. return(0);
  107877. }
  107878. int ogg_stream_reset(ogg_stream_state *os){
  107879. os->body_fill=0;
  107880. os->body_returned=0;
  107881. os->lacing_fill=0;
  107882. os->lacing_packet=0;
  107883. os->lacing_returned=0;
  107884. os->header_fill=0;
  107885. os->e_o_s=0;
  107886. os->b_o_s=0;
  107887. os->pageno=-1;
  107888. os->packetno=0;
  107889. os->granulepos=0;
  107890. return(0);
  107891. }
  107892. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  107893. ogg_stream_reset(os);
  107894. os->serialno=serialno;
  107895. return(0);
  107896. }
  107897. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  107898. /* The last part of decode. We have the stream broken into packet
  107899. segments. Now we need to group them into packets (or return the
  107900. out of sync markers) */
  107901. int ptr=os->lacing_returned;
  107902. if(os->lacing_packet<=ptr)return(0);
  107903. if(os->lacing_vals[ptr]&0x400){
  107904. /* we need to tell the codec there's a gap; it might need to
  107905. handle previous packet dependencies. */
  107906. os->lacing_returned++;
  107907. os->packetno++;
  107908. return(-1);
  107909. }
  107910. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  107911. to ask if there's a whole packet
  107912. waiting */
  107913. /* Gather the whole packet. We'll have no holes or a partial packet */
  107914. {
  107915. int size=os->lacing_vals[ptr]&0xff;
  107916. int bytes=size;
  107917. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  107918. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  107919. while(size==255){
  107920. int val=os->lacing_vals[++ptr];
  107921. size=val&0xff;
  107922. if(val&0x200)eos=0x200;
  107923. bytes+=size;
  107924. }
  107925. if(op){
  107926. op->e_o_s=eos;
  107927. op->b_o_s=bos;
  107928. op->packet=os->body_data+os->body_returned;
  107929. op->packetno=os->packetno;
  107930. op->granulepos=os->granule_vals[ptr];
  107931. op->bytes=bytes;
  107932. }
  107933. if(adv){
  107934. os->body_returned+=bytes;
  107935. os->lacing_returned=ptr+1;
  107936. os->packetno++;
  107937. }
  107938. }
  107939. return(1);
  107940. }
  107941. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  107942. return _packetout(os,op,1);
  107943. }
  107944. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  107945. return _packetout(os,op,0);
  107946. }
  107947. void ogg_packet_clear(ogg_packet *op) {
  107948. _ogg_free(op->packet);
  107949. memset(op, 0, sizeof(*op));
  107950. }
  107951. #ifdef _V_SELFTEST
  107952. #include <stdio.h>
  107953. ogg_stream_state os_en, os_de;
  107954. ogg_sync_state oy;
  107955. void checkpacket(ogg_packet *op,int len, int no, int pos){
  107956. long j;
  107957. static int sequence=0;
  107958. static int lastno=0;
  107959. if(op->bytes!=len){
  107960. fprintf(stderr,"incorrect packet length!\n");
  107961. exit(1);
  107962. }
  107963. if(op->granulepos!=pos){
  107964. fprintf(stderr,"incorrect packet position!\n");
  107965. exit(1);
  107966. }
  107967. /* packet number just follows sequence/gap; adjust the input number
  107968. for that */
  107969. if(no==0){
  107970. sequence=0;
  107971. }else{
  107972. sequence++;
  107973. if(no>lastno+1)
  107974. sequence++;
  107975. }
  107976. lastno=no;
  107977. if(op->packetno!=sequence){
  107978. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  107979. (long)(op->packetno),sequence);
  107980. exit(1);
  107981. }
  107982. /* Test data */
  107983. for(j=0;j<op->bytes;j++)
  107984. if(op->packet[j]!=((j+no)&0xff)){
  107985. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  107986. j,op->packet[j],(j+no)&0xff);
  107987. exit(1);
  107988. }
  107989. }
  107990. void check_page(unsigned char *data,const int *header,ogg_page *og){
  107991. long j;
  107992. /* Test data */
  107993. for(j=0;j<og->body_len;j++)
  107994. if(og->body[j]!=data[j]){
  107995. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  107996. j,data[j],og->body[j]);
  107997. exit(1);
  107998. }
  107999. /* Test header */
  108000. for(j=0;j<og->header_len;j++){
  108001. if(og->header[j]!=header[j]){
  108002. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108003. for(j=0;j<header[26]+27;j++)
  108004. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108005. fprintf(stderr,"\n");
  108006. exit(1);
  108007. }
  108008. }
  108009. if(og->header_len!=header[26]+27){
  108010. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108011. og->header_len,header[26]+27);
  108012. exit(1);
  108013. }
  108014. }
  108015. void print_header(ogg_page *og){
  108016. int j;
  108017. fprintf(stderr,"\nHEADER:\n");
  108018. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108019. og->header[0],og->header[1],og->header[2],og->header[3],
  108020. (int)og->header[4],(int)og->header[5]);
  108021. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108022. (og->header[9]<<24)|(og->header[8]<<16)|
  108023. (og->header[7]<<8)|og->header[6],
  108024. (og->header[17]<<24)|(og->header[16]<<16)|
  108025. (og->header[15]<<8)|og->header[14],
  108026. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108027. (og->header[19]<<8)|og->header[18]);
  108028. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108029. (int)og->header[22],(int)og->header[23],
  108030. (int)og->header[24],(int)og->header[25],
  108031. (int)og->header[26]);
  108032. for(j=27;j<og->header_len;j++)
  108033. fprintf(stderr,"%d ",(int)og->header[j]);
  108034. fprintf(stderr,")\n\n");
  108035. }
  108036. void copy_page(ogg_page *og){
  108037. unsigned char *temp=_ogg_malloc(og->header_len);
  108038. memcpy(temp,og->header,og->header_len);
  108039. og->header=temp;
  108040. temp=_ogg_malloc(og->body_len);
  108041. memcpy(temp,og->body,og->body_len);
  108042. og->body=temp;
  108043. }
  108044. void free_page(ogg_page *og){
  108045. _ogg_free (og->header);
  108046. _ogg_free (og->body);
  108047. }
  108048. void error(void){
  108049. fprintf(stderr,"error!\n");
  108050. exit(1);
  108051. }
  108052. /* 17 only */
  108053. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108054. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108055. 0x01,0x02,0x03,0x04,0,0,0,0,
  108056. 0x15,0xed,0xec,0x91,
  108057. 1,
  108058. 17};
  108059. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108060. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108061. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108062. 0x01,0x02,0x03,0x04,0,0,0,0,
  108063. 0x59,0x10,0x6c,0x2c,
  108064. 1,
  108065. 17};
  108066. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108067. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108068. 0x01,0x02,0x03,0x04,1,0,0,0,
  108069. 0x89,0x33,0x85,0xce,
  108070. 13,
  108071. 254,255,0,255,1,255,245,255,255,0,
  108072. 255,255,90};
  108073. /* nil packets; beginning,middle,end */
  108074. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108075. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108076. 0x01,0x02,0x03,0x04,0,0,0,0,
  108077. 0xff,0x7b,0x23,0x17,
  108078. 1,
  108079. 0};
  108080. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108081. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108082. 0x01,0x02,0x03,0x04,1,0,0,0,
  108083. 0x5c,0x3f,0x66,0xcb,
  108084. 17,
  108085. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108086. 255,255,90,0};
  108087. /* large initial packet */
  108088. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108089. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108090. 0x01,0x02,0x03,0x04,0,0,0,0,
  108091. 0x01,0x27,0x31,0xaa,
  108092. 18,
  108093. 255,255,255,255,255,255,255,255,
  108094. 255,255,255,255,255,255,255,255,255,10};
  108095. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108096. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108097. 0x01,0x02,0x03,0x04,1,0,0,0,
  108098. 0x7f,0x4e,0x8a,0xd2,
  108099. 4,
  108100. 255,4,255,0};
  108101. /* continuing packet test */
  108102. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108103. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108104. 0x01,0x02,0x03,0x04,0,0,0,0,
  108105. 0xff,0x7b,0x23,0x17,
  108106. 1,
  108107. 0};
  108108. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108109. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108110. 0x01,0x02,0x03,0x04,1,0,0,0,
  108111. 0x54,0x05,0x51,0xc8,
  108112. 17,
  108113. 255,255,255,255,255,255,255,255,
  108114. 255,255,255,255,255,255,255,255,255};
  108115. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108116. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108117. 0x01,0x02,0x03,0x04,2,0,0,0,
  108118. 0xc8,0xc3,0xcb,0xed,
  108119. 5,
  108120. 10,255,4,255,0};
  108121. /* page with the 255 segment limit */
  108122. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108123. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108124. 0x01,0x02,0x03,0x04,0,0,0,0,
  108125. 0xff,0x7b,0x23,0x17,
  108126. 1,
  108127. 0};
  108128. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108129. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  108130. 0x01,0x02,0x03,0x04,1,0,0,0,
  108131. 0xed,0x2a,0x2e,0xa7,
  108132. 255,
  108133. 10,10,10,10,10,10,10,10,
  108134. 10,10,10,10,10,10,10,10,
  108135. 10,10,10,10,10,10,10,10,
  108136. 10,10,10,10,10,10,10,10,
  108137. 10,10,10,10,10,10,10,10,
  108138. 10,10,10,10,10,10,10,10,
  108139. 10,10,10,10,10,10,10,10,
  108140. 10,10,10,10,10,10,10,10,
  108141. 10,10,10,10,10,10,10,10,
  108142. 10,10,10,10,10,10,10,10,
  108143. 10,10,10,10,10,10,10,10,
  108144. 10,10,10,10,10,10,10,10,
  108145. 10,10,10,10,10,10,10,10,
  108146. 10,10,10,10,10,10,10,10,
  108147. 10,10,10,10,10,10,10,10,
  108148. 10,10,10,10,10,10,10,10,
  108149. 10,10,10,10,10,10,10,10,
  108150. 10,10,10,10,10,10,10,10,
  108151. 10,10,10,10,10,10,10,10,
  108152. 10,10,10,10,10,10,10,10,
  108153. 10,10,10,10,10,10,10,10,
  108154. 10,10,10,10,10,10,10,10,
  108155. 10,10,10,10,10,10,10,10,
  108156. 10,10,10,10,10,10,10,10,
  108157. 10,10,10,10,10,10,10,10,
  108158. 10,10,10,10,10,10,10,10,
  108159. 10,10,10,10,10,10,10,10,
  108160. 10,10,10,10,10,10,10,10,
  108161. 10,10,10,10,10,10,10,10,
  108162. 10,10,10,10,10,10,10,10,
  108163. 10,10,10,10,10,10,10,10,
  108164. 10,10,10,10,10,10,10};
  108165. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108166. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  108167. 0x01,0x02,0x03,0x04,2,0,0,0,
  108168. 0x6c,0x3b,0x82,0x3d,
  108169. 1,
  108170. 50};
  108171. /* packet that overspans over an entire page */
  108172. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108173. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108174. 0x01,0x02,0x03,0x04,0,0,0,0,
  108175. 0xff,0x7b,0x23,0x17,
  108176. 1,
  108177. 0};
  108178. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108179. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108180. 0x01,0x02,0x03,0x04,1,0,0,0,
  108181. 0x3c,0xd9,0x4d,0x3f,
  108182. 17,
  108183. 100,255,255,255,255,255,255,255,255,
  108184. 255,255,255,255,255,255,255,255};
  108185. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  108186. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108187. 0x01,0x02,0x03,0x04,2,0,0,0,
  108188. 0x01,0xd2,0xe5,0xe5,
  108189. 17,
  108190. 255,255,255,255,255,255,255,255,
  108191. 255,255,255,255,255,255,255,255,255};
  108192. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108193. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  108194. 0x01,0x02,0x03,0x04,3,0,0,0,
  108195. 0xef,0xdd,0x88,0xde,
  108196. 7,
  108197. 255,255,75,255,4,255,0};
  108198. /* packet that overspans over an entire page */
  108199. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108200. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108201. 0x01,0x02,0x03,0x04,0,0,0,0,
  108202. 0xff,0x7b,0x23,0x17,
  108203. 1,
  108204. 0};
  108205. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108206. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108207. 0x01,0x02,0x03,0x04,1,0,0,0,
  108208. 0x3c,0xd9,0x4d,0x3f,
  108209. 17,
  108210. 100,255,255,255,255,255,255,255,255,
  108211. 255,255,255,255,255,255,255,255};
  108212. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108213. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108214. 0x01,0x02,0x03,0x04,2,0,0,0,
  108215. 0xd4,0xe0,0x60,0xe5,
  108216. 1,0};
  108217. void test_pack(const int *pl, const int **headers, int byteskip,
  108218. int pageskip, int packetskip){
  108219. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  108220. long inptr=0;
  108221. long outptr=0;
  108222. long deptr=0;
  108223. long depacket=0;
  108224. long granule_pos=7,pageno=0;
  108225. int i,j,packets,pageout=pageskip;
  108226. int eosflag=0;
  108227. int bosflag=0;
  108228. int byteskipcount=0;
  108229. ogg_stream_reset(&os_en);
  108230. ogg_stream_reset(&os_de);
  108231. ogg_sync_reset(&oy);
  108232. for(packets=0;packets<packetskip;packets++)
  108233. depacket+=pl[packets];
  108234. for(packets=0;;packets++)if(pl[packets]==-1)break;
  108235. for(i=0;i<packets;i++){
  108236. /* construct a test packet */
  108237. ogg_packet op;
  108238. int len=pl[i];
  108239. op.packet=data+inptr;
  108240. op.bytes=len;
  108241. op.e_o_s=(pl[i+1]<0?1:0);
  108242. op.granulepos=granule_pos;
  108243. granule_pos+=1024;
  108244. for(j=0;j<len;j++)data[inptr++]=i+j;
  108245. /* submit the test packet */
  108246. ogg_stream_packetin(&os_en,&op);
  108247. /* retrieve any finished pages */
  108248. {
  108249. ogg_page og;
  108250. while(ogg_stream_pageout(&os_en,&og)){
  108251. /* We have a page. Check it carefully */
  108252. fprintf(stderr,"%ld, ",pageno);
  108253. if(headers[pageno]==NULL){
  108254. fprintf(stderr,"coded too many pages!\n");
  108255. exit(1);
  108256. }
  108257. check_page(data+outptr,headers[pageno],&og);
  108258. outptr+=og.body_len;
  108259. pageno++;
  108260. if(pageskip){
  108261. bosflag=1;
  108262. pageskip--;
  108263. deptr+=og.body_len;
  108264. }
  108265. /* have a complete page; submit it to sync/decode */
  108266. {
  108267. ogg_page og_de;
  108268. ogg_packet op_de,op_de2;
  108269. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  108270. char *next=buf;
  108271. byteskipcount+=og.header_len;
  108272. if(byteskipcount>byteskip){
  108273. memcpy(next,og.header,byteskipcount-byteskip);
  108274. next+=byteskipcount-byteskip;
  108275. byteskipcount=byteskip;
  108276. }
  108277. byteskipcount+=og.body_len;
  108278. if(byteskipcount>byteskip){
  108279. memcpy(next,og.body,byteskipcount-byteskip);
  108280. next+=byteskipcount-byteskip;
  108281. byteskipcount=byteskip;
  108282. }
  108283. ogg_sync_wrote(&oy,next-buf);
  108284. while(1){
  108285. int ret=ogg_sync_pageout(&oy,&og_de);
  108286. if(ret==0)break;
  108287. if(ret<0)continue;
  108288. /* got a page. Happy happy. Verify that it's good. */
  108289. fprintf(stderr,"(%ld), ",pageout);
  108290. check_page(data+deptr,headers[pageout],&og_de);
  108291. deptr+=og_de.body_len;
  108292. pageout++;
  108293. /* submit it to deconstitution */
  108294. ogg_stream_pagein(&os_de,&og_de);
  108295. /* packets out? */
  108296. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  108297. ogg_stream_packetpeek(&os_de,NULL);
  108298. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  108299. /* verify peek and out match */
  108300. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  108301. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  108302. depacket);
  108303. exit(1);
  108304. }
  108305. /* verify the packet! */
  108306. /* check data */
  108307. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  108308. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  108309. depacket);
  108310. exit(1);
  108311. }
  108312. /* check bos flag */
  108313. if(bosflag==0 && op_de.b_o_s==0){
  108314. fprintf(stderr,"b_o_s flag not set on packet!\n");
  108315. exit(1);
  108316. }
  108317. if(bosflag && op_de.b_o_s){
  108318. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  108319. exit(1);
  108320. }
  108321. bosflag=1;
  108322. depacket+=op_de.bytes;
  108323. /* check eos flag */
  108324. if(eosflag){
  108325. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  108326. exit(1);
  108327. }
  108328. if(op_de.e_o_s)eosflag=1;
  108329. /* check granulepos flag */
  108330. if(op_de.granulepos!=-1){
  108331. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  108332. }
  108333. }
  108334. }
  108335. }
  108336. }
  108337. }
  108338. }
  108339. _ogg_free(data);
  108340. if(headers[pageno]!=NULL){
  108341. fprintf(stderr,"did not write last page!\n");
  108342. exit(1);
  108343. }
  108344. if(headers[pageout]!=NULL){
  108345. fprintf(stderr,"did not decode last page!\n");
  108346. exit(1);
  108347. }
  108348. if(inptr!=outptr){
  108349. fprintf(stderr,"encoded page data incomplete!\n");
  108350. exit(1);
  108351. }
  108352. if(inptr!=deptr){
  108353. fprintf(stderr,"decoded page data incomplete!\n");
  108354. exit(1);
  108355. }
  108356. if(inptr!=depacket){
  108357. fprintf(stderr,"decoded packet data incomplete!\n");
  108358. exit(1);
  108359. }
  108360. if(!eosflag){
  108361. fprintf(stderr,"Never got a packet with EOS set!\n");
  108362. exit(1);
  108363. }
  108364. fprintf(stderr,"ok.\n");
  108365. }
  108366. int main(void){
  108367. ogg_stream_init(&os_en,0x04030201);
  108368. ogg_stream_init(&os_de,0x04030201);
  108369. ogg_sync_init(&oy);
  108370. /* Exercise each code path in the framing code. Also verify that
  108371. the checksums are working. */
  108372. {
  108373. /* 17 only */
  108374. const int packets[]={17, -1};
  108375. const int *headret[]={head1_0,NULL};
  108376. fprintf(stderr,"testing single page encoding... ");
  108377. test_pack(packets,headret,0,0,0);
  108378. }
  108379. {
  108380. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108381. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  108382. const int *headret[]={head1_1,head2_1,NULL};
  108383. fprintf(stderr,"testing basic page encoding... ");
  108384. test_pack(packets,headret,0,0,0);
  108385. }
  108386. {
  108387. /* nil packets; beginning,middle,end */
  108388. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  108389. const int *headret[]={head1_2,head2_2,NULL};
  108390. fprintf(stderr,"testing basic nil packets... ");
  108391. test_pack(packets,headret,0,0,0);
  108392. }
  108393. {
  108394. /* large initial packet */
  108395. const int packets[]={4345,259,255,-1};
  108396. const int *headret[]={head1_3,head2_3,NULL};
  108397. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  108398. test_pack(packets,headret,0,0,0);
  108399. }
  108400. {
  108401. /* continuing packet test */
  108402. const int packets[]={0,4345,259,255,-1};
  108403. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  108404. fprintf(stderr,"testing single packet page span... ");
  108405. test_pack(packets,headret,0,0,0);
  108406. }
  108407. /* page with the 255 segment limit */
  108408. {
  108409. const int packets[]={0,10,10,10,10,10,10,10,10,
  108410. 10,10,10,10,10,10,10,10,
  108411. 10,10,10,10,10,10,10,10,
  108412. 10,10,10,10,10,10,10,10,
  108413. 10,10,10,10,10,10,10,10,
  108414. 10,10,10,10,10,10,10,10,
  108415. 10,10,10,10,10,10,10,10,
  108416. 10,10,10,10,10,10,10,10,
  108417. 10,10,10,10,10,10,10,10,
  108418. 10,10,10,10,10,10,10,10,
  108419. 10,10,10,10,10,10,10,10,
  108420. 10,10,10,10,10,10,10,10,
  108421. 10,10,10,10,10,10,10,10,
  108422. 10,10,10,10,10,10,10,10,
  108423. 10,10,10,10,10,10,10,10,
  108424. 10,10,10,10,10,10,10,10,
  108425. 10,10,10,10,10,10,10,10,
  108426. 10,10,10,10,10,10,10,10,
  108427. 10,10,10,10,10,10,10,10,
  108428. 10,10,10,10,10,10,10,10,
  108429. 10,10,10,10,10,10,10,10,
  108430. 10,10,10,10,10,10,10,10,
  108431. 10,10,10,10,10,10,10,10,
  108432. 10,10,10,10,10,10,10,10,
  108433. 10,10,10,10,10,10,10,10,
  108434. 10,10,10,10,10,10,10,10,
  108435. 10,10,10,10,10,10,10,10,
  108436. 10,10,10,10,10,10,10,10,
  108437. 10,10,10,10,10,10,10,10,
  108438. 10,10,10,10,10,10,10,10,
  108439. 10,10,10,10,10,10,10,10,
  108440. 10,10,10,10,10,10,10,50,-1};
  108441. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  108442. fprintf(stderr,"testing max packet segments... ");
  108443. test_pack(packets,headret,0,0,0);
  108444. }
  108445. {
  108446. /* packet that overspans over an entire page */
  108447. const int packets[]={0,100,9000,259,255,-1};
  108448. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  108449. fprintf(stderr,"testing very large packets... ");
  108450. test_pack(packets,headret,0,0,0);
  108451. }
  108452. {
  108453. /* test for the libogg 1.1.1 resync in large continuation bug
  108454. found by Josh Coalson) */
  108455. const int packets[]={0,100,9000,259,255,-1};
  108456. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  108457. fprintf(stderr,"testing continuation resync in very large packets... ");
  108458. test_pack(packets,headret,100,2,3);
  108459. }
  108460. {
  108461. /* term only page. why not? */
  108462. const int packets[]={0,100,4080,-1};
  108463. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  108464. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  108465. test_pack(packets,headret,0,0,0);
  108466. }
  108467. {
  108468. /* build a bunch of pages for testing */
  108469. unsigned char *data=_ogg_malloc(1024*1024);
  108470. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  108471. int inptr=0,i,j;
  108472. ogg_page og[5];
  108473. ogg_stream_reset(&os_en);
  108474. for(i=0;pl[i]!=-1;i++){
  108475. ogg_packet op;
  108476. int len=pl[i];
  108477. op.packet=data+inptr;
  108478. op.bytes=len;
  108479. op.e_o_s=(pl[i+1]<0?1:0);
  108480. op.granulepos=(i+1)*1000;
  108481. for(j=0;j<len;j++)data[inptr++]=i+j;
  108482. ogg_stream_packetin(&os_en,&op);
  108483. }
  108484. _ogg_free(data);
  108485. /* retrieve finished pages */
  108486. for(i=0;i<5;i++){
  108487. if(ogg_stream_pageout(&os_en,&og[i])==0){
  108488. fprintf(stderr,"Too few pages output building sync tests!\n");
  108489. exit(1);
  108490. }
  108491. copy_page(&og[i]);
  108492. }
  108493. /* Test lost pages on pagein/packetout: no rollback */
  108494. {
  108495. ogg_page temp;
  108496. ogg_packet test;
  108497. fprintf(stderr,"Testing loss of pages... ");
  108498. ogg_sync_reset(&oy);
  108499. ogg_stream_reset(&os_de);
  108500. for(i=0;i<5;i++){
  108501. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  108502. og[i].header_len);
  108503. ogg_sync_wrote(&oy,og[i].header_len);
  108504. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  108505. ogg_sync_wrote(&oy,og[i].body_len);
  108506. }
  108507. ogg_sync_pageout(&oy,&temp);
  108508. ogg_stream_pagein(&os_de,&temp);
  108509. ogg_sync_pageout(&oy,&temp);
  108510. ogg_stream_pagein(&os_de,&temp);
  108511. ogg_sync_pageout(&oy,&temp);
  108512. /* skip */
  108513. ogg_sync_pageout(&oy,&temp);
  108514. ogg_stream_pagein(&os_de,&temp);
  108515. /* do we get the expected results/packets? */
  108516. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108517. checkpacket(&test,0,0,0);
  108518. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108519. checkpacket(&test,100,1,-1);
  108520. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108521. checkpacket(&test,4079,2,3000);
  108522. if(ogg_stream_packetout(&os_de,&test)!=-1){
  108523. fprintf(stderr,"Error: loss of page did not return error\n");
  108524. exit(1);
  108525. }
  108526. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108527. checkpacket(&test,76,5,-1);
  108528. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108529. checkpacket(&test,34,6,-1);
  108530. fprintf(stderr,"ok.\n");
  108531. }
  108532. /* Test lost pages on pagein/packetout: rollback with continuation */
  108533. {
  108534. ogg_page temp;
  108535. ogg_packet test;
  108536. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  108537. ogg_sync_reset(&oy);
  108538. ogg_stream_reset(&os_de);
  108539. for(i=0;i<5;i++){
  108540. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  108541. og[i].header_len);
  108542. ogg_sync_wrote(&oy,og[i].header_len);
  108543. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  108544. ogg_sync_wrote(&oy,og[i].body_len);
  108545. }
  108546. ogg_sync_pageout(&oy,&temp);
  108547. ogg_stream_pagein(&os_de,&temp);
  108548. ogg_sync_pageout(&oy,&temp);
  108549. ogg_stream_pagein(&os_de,&temp);
  108550. ogg_sync_pageout(&oy,&temp);
  108551. ogg_stream_pagein(&os_de,&temp);
  108552. ogg_sync_pageout(&oy,&temp);
  108553. /* skip */
  108554. ogg_sync_pageout(&oy,&temp);
  108555. ogg_stream_pagein(&os_de,&temp);
  108556. /* do we get the expected results/packets? */
  108557. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108558. checkpacket(&test,0,0,0);
  108559. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108560. checkpacket(&test,100,1,-1);
  108561. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108562. checkpacket(&test,4079,2,3000);
  108563. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108564. checkpacket(&test,2956,3,4000);
  108565. if(ogg_stream_packetout(&os_de,&test)!=-1){
  108566. fprintf(stderr,"Error: loss of page did not return error\n");
  108567. exit(1);
  108568. }
  108569. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108570. checkpacket(&test,300,13,14000);
  108571. fprintf(stderr,"ok.\n");
  108572. }
  108573. /* the rest only test sync */
  108574. {
  108575. ogg_page og_de;
  108576. /* Test fractional page inputs: incomplete capture */
  108577. fprintf(stderr,"Testing sync on partial inputs... ");
  108578. ogg_sync_reset(&oy);
  108579. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108580. 3);
  108581. ogg_sync_wrote(&oy,3);
  108582. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108583. /* Test fractional page inputs: incomplete fixed header */
  108584. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  108585. 20);
  108586. ogg_sync_wrote(&oy,20);
  108587. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108588. /* Test fractional page inputs: incomplete header */
  108589. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  108590. 5);
  108591. ogg_sync_wrote(&oy,5);
  108592. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108593. /* Test fractional page inputs: incomplete body */
  108594. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  108595. og[1].header_len-28);
  108596. ogg_sync_wrote(&oy,og[1].header_len-28);
  108597. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108598. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  108599. ogg_sync_wrote(&oy,1000);
  108600. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108601. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  108602. og[1].body_len-1000);
  108603. ogg_sync_wrote(&oy,og[1].body_len-1000);
  108604. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108605. fprintf(stderr,"ok.\n");
  108606. }
  108607. /* Test fractional page inputs: page + incomplete capture */
  108608. {
  108609. ogg_page og_de;
  108610. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  108611. ogg_sync_reset(&oy);
  108612. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108613. og[1].header_len);
  108614. ogg_sync_wrote(&oy,og[1].header_len);
  108615. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108616. og[1].body_len);
  108617. ogg_sync_wrote(&oy,og[1].body_len);
  108618. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108619. 20);
  108620. ogg_sync_wrote(&oy,20);
  108621. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108622. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108623. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  108624. og[1].header_len-20);
  108625. ogg_sync_wrote(&oy,og[1].header_len-20);
  108626. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108627. og[1].body_len);
  108628. ogg_sync_wrote(&oy,og[1].body_len);
  108629. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108630. fprintf(stderr,"ok.\n");
  108631. }
  108632. /* Test recapture: garbage + page */
  108633. {
  108634. ogg_page og_de;
  108635. fprintf(stderr,"Testing search for capture... ");
  108636. ogg_sync_reset(&oy);
  108637. /* 'garbage' */
  108638. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108639. og[1].body_len);
  108640. ogg_sync_wrote(&oy,og[1].body_len);
  108641. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108642. og[1].header_len);
  108643. ogg_sync_wrote(&oy,og[1].header_len);
  108644. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108645. og[1].body_len);
  108646. ogg_sync_wrote(&oy,og[1].body_len);
  108647. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108648. 20);
  108649. ogg_sync_wrote(&oy,20);
  108650. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108651. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108652. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108653. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  108654. og[2].header_len-20);
  108655. ogg_sync_wrote(&oy,og[2].header_len-20);
  108656. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  108657. og[2].body_len);
  108658. ogg_sync_wrote(&oy,og[2].body_len);
  108659. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108660. fprintf(stderr,"ok.\n");
  108661. }
  108662. /* Test recapture: page + garbage + page */
  108663. {
  108664. ogg_page og_de;
  108665. fprintf(stderr,"Testing recapture... ");
  108666. ogg_sync_reset(&oy);
  108667. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108668. og[1].header_len);
  108669. ogg_sync_wrote(&oy,og[1].header_len);
  108670. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108671. og[1].body_len);
  108672. ogg_sync_wrote(&oy,og[1].body_len);
  108673. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108674. og[2].header_len);
  108675. ogg_sync_wrote(&oy,og[2].header_len);
  108676. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108677. og[2].header_len);
  108678. ogg_sync_wrote(&oy,og[2].header_len);
  108679. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108680. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  108681. og[2].body_len-5);
  108682. ogg_sync_wrote(&oy,og[2].body_len-5);
  108683. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  108684. og[3].header_len);
  108685. ogg_sync_wrote(&oy,og[3].header_len);
  108686. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  108687. og[3].body_len);
  108688. ogg_sync_wrote(&oy,og[3].body_len);
  108689. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108690. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108691. fprintf(stderr,"ok.\n");
  108692. }
  108693. /* Free page data that was previously copied */
  108694. {
  108695. for(i=0;i<5;i++){
  108696. free_page(&og[i]);
  108697. }
  108698. }
  108699. }
  108700. return(0);
  108701. }
  108702. #endif
  108703. #endif
  108704. /*** End of inlined file: framing.c ***/
  108705. /*** Start of inlined file: analysis.c ***/
  108706. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108707. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108708. // tasks..
  108709. #if JUCE_MSVC
  108710. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108711. #endif
  108712. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108713. #if JUCE_USE_OGGVORBIS
  108714. #include <stdio.h>
  108715. #include <string.h>
  108716. #include <math.h>
  108717. /*** Start of inlined file: codec_internal.h ***/
  108718. #ifndef _V_CODECI_H_
  108719. #define _V_CODECI_H_
  108720. /*** Start of inlined file: envelope.h ***/
  108721. #ifndef _V_ENVELOPE_
  108722. #define _V_ENVELOPE_
  108723. /*** Start of inlined file: mdct.h ***/
  108724. #ifndef _OGG_mdct_H_
  108725. #define _OGG_mdct_H_
  108726. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  108727. #ifdef MDCT_INTEGERIZED
  108728. #define DATA_TYPE int
  108729. #define REG_TYPE register int
  108730. #define TRIGBITS 14
  108731. #define cPI3_8 6270
  108732. #define cPI2_8 11585
  108733. #define cPI1_8 15137
  108734. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  108735. #define MULT_NORM(x) ((x)>>TRIGBITS)
  108736. #define HALVE(x) ((x)>>1)
  108737. #else
  108738. #define DATA_TYPE float
  108739. #define REG_TYPE float
  108740. #define cPI3_8 .38268343236508977175F
  108741. #define cPI2_8 .70710678118654752441F
  108742. #define cPI1_8 .92387953251128675613F
  108743. #define FLOAT_CONV(x) (x)
  108744. #define MULT_NORM(x) (x)
  108745. #define HALVE(x) ((x)*.5f)
  108746. #endif
  108747. typedef struct {
  108748. int n;
  108749. int log2n;
  108750. DATA_TYPE *trig;
  108751. int *bitrev;
  108752. DATA_TYPE scale;
  108753. } mdct_lookup;
  108754. extern void mdct_init(mdct_lookup *lookup,int n);
  108755. extern void mdct_clear(mdct_lookup *l);
  108756. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  108757. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  108758. #endif
  108759. /*** End of inlined file: mdct.h ***/
  108760. #define VE_PRE 16
  108761. #define VE_WIN 4
  108762. #define VE_POST 2
  108763. #define VE_AMP (VE_PRE+VE_POST-1)
  108764. #define VE_BANDS 7
  108765. #define VE_NEARDC 15
  108766. #define VE_MINSTRETCH 2 /* a bit less than short block */
  108767. #define VE_MAXSTRETCH 12 /* one-third full block */
  108768. typedef struct {
  108769. float ampbuf[VE_AMP];
  108770. int ampptr;
  108771. float nearDC[VE_NEARDC];
  108772. float nearDC_acc;
  108773. float nearDC_partialacc;
  108774. int nearptr;
  108775. } envelope_filter_state;
  108776. typedef struct {
  108777. int begin;
  108778. int end;
  108779. float *window;
  108780. float total;
  108781. } envelope_band;
  108782. typedef struct {
  108783. int ch;
  108784. int winlength;
  108785. int searchstep;
  108786. float minenergy;
  108787. mdct_lookup mdct;
  108788. float *mdct_win;
  108789. envelope_band band[VE_BANDS];
  108790. envelope_filter_state *filter;
  108791. int stretch;
  108792. int *mark;
  108793. long storage;
  108794. long current;
  108795. long curmark;
  108796. long cursor;
  108797. } envelope_lookup;
  108798. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  108799. extern void _ve_envelope_clear(envelope_lookup *e);
  108800. extern long _ve_envelope_search(vorbis_dsp_state *v);
  108801. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  108802. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  108803. #endif
  108804. /*** End of inlined file: envelope.h ***/
  108805. /*** Start of inlined file: codebook.h ***/
  108806. #ifndef _V_CODEBOOK_H_
  108807. #define _V_CODEBOOK_H_
  108808. /* This structure encapsulates huffman and VQ style encoding books; it
  108809. doesn't do anything specific to either.
  108810. valuelist/quantlist are nonNULL (and q_* significant) only if
  108811. there's entry->value mapping to be done.
  108812. If encode-side mapping must be done (and thus the entry needs to be
  108813. hunted), the auxiliary encode pointer will point to a decision
  108814. tree. This is true of both VQ and huffman, but is mostly useful
  108815. with VQ.
  108816. */
  108817. typedef struct static_codebook{
  108818. long dim; /* codebook dimensions (elements per vector) */
  108819. long entries; /* codebook entries */
  108820. long *lengthlist; /* codeword lengths in bits */
  108821. /* mapping ***************************************************************/
  108822. int maptype; /* 0=none
  108823. 1=implicitly populated values from map column
  108824. 2=listed arbitrary values */
  108825. /* The below does a linear, single monotonic sequence mapping. */
  108826. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  108827. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  108828. int q_quant; /* bits: 0 < quant <= 16 */
  108829. int q_sequencep; /* bitflag */
  108830. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  108831. map == 2: list of dim*entries quantized entry vals
  108832. */
  108833. /* encode helpers ********************************************************/
  108834. struct encode_aux_nearestmatch *nearest_tree;
  108835. struct encode_aux_threshmatch *thresh_tree;
  108836. struct encode_aux_pigeonhole *pigeon_tree;
  108837. int allocedp;
  108838. } static_codebook;
  108839. /* this structures an arbitrary trained book to quickly find the
  108840. nearest cell match */
  108841. typedef struct encode_aux_nearestmatch{
  108842. /* pre-calculated partitioning tree */
  108843. long *ptr0;
  108844. long *ptr1;
  108845. long *p; /* decision points (each is an entry) */
  108846. long *q; /* decision points (each is an entry) */
  108847. long aux; /* number of tree entries */
  108848. long alloc;
  108849. } encode_aux_nearestmatch;
  108850. /* assumes a maptype of 1; encode side only, so that's OK */
  108851. typedef struct encode_aux_threshmatch{
  108852. float *quantthresh;
  108853. long *quantmap;
  108854. int quantvals;
  108855. int threshvals;
  108856. } encode_aux_threshmatch;
  108857. typedef struct encode_aux_pigeonhole{
  108858. float min;
  108859. float del;
  108860. int mapentries;
  108861. int quantvals;
  108862. long *pigeonmap;
  108863. long fittotal;
  108864. long *fitlist;
  108865. long *fitmap;
  108866. long *fitlength;
  108867. } encode_aux_pigeonhole;
  108868. typedef struct codebook{
  108869. long dim; /* codebook dimensions (elements per vector) */
  108870. long entries; /* codebook entries */
  108871. long used_entries; /* populated codebook entries */
  108872. const static_codebook *c;
  108873. /* for encode, the below are entry-ordered, fully populated */
  108874. /* for decode, the below are ordered by bitreversed codeword and only
  108875. used entries are populated */
  108876. float *valuelist; /* list of dim*entries actual entry values */
  108877. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  108878. int *dec_index; /* only used if sparseness collapsed */
  108879. char *dec_codelengths;
  108880. ogg_uint32_t *dec_firsttable;
  108881. int dec_firsttablen;
  108882. int dec_maxlength;
  108883. } codebook;
  108884. extern void vorbis_staticbook_clear(static_codebook *b);
  108885. extern void vorbis_staticbook_destroy(static_codebook *b);
  108886. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  108887. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  108888. extern void vorbis_book_clear(codebook *b);
  108889. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  108890. extern float *_book_logdist(const static_codebook *b,float *vals);
  108891. extern float _float32_unpack(long val);
  108892. extern long _float32_pack(float val);
  108893. extern int _best(codebook *book, float *a, int step);
  108894. extern int _ilog(unsigned int v);
  108895. extern long _book_maptype1_quantvals(const static_codebook *b);
  108896. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  108897. extern long vorbis_book_codeword(codebook *book,int entry);
  108898. extern long vorbis_book_codelen(codebook *book,int entry);
  108899. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  108900. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  108901. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  108902. extern int vorbis_book_errorv(codebook *book, float *a);
  108903. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  108904. oggpack_buffer *b);
  108905. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  108906. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  108907. oggpack_buffer *b,int n);
  108908. extern long vorbis_book_decodev_set(codebook *book, float *a,
  108909. oggpack_buffer *b,int n);
  108910. extern long vorbis_book_decodev_add(codebook *book, float *a,
  108911. oggpack_buffer *b,int n);
  108912. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  108913. long off,int ch,
  108914. oggpack_buffer *b,int n);
  108915. #endif
  108916. /*** End of inlined file: codebook.h ***/
  108917. #define BLOCKTYPE_IMPULSE 0
  108918. #define BLOCKTYPE_PADDING 1
  108919. #define BLOCKTYPE_TRANSITION 0
  108920. #define BLOCKTYPE_LONG 1
  108921. #define PACKETBLOBS 15
  108922. typedef struct vorbis_block_internal{
  108923. float **pcmdelay; /* this is a pointer into local storage */
  108924. float ampmax;
  108925. int blocktype;
  108926. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  108927. blob [PACKETBLOBS/2] points to
  108928. the oggpack_buffer in the
  108929. main vorbis_block */
  108930. } vorbis_block_internal;
  108931. typedef void vorbis_look_floor;
  108932. typedef void vorbis_look_residue;
  108933. typedef void vorbis_look_transform;
  108934. /* mode ************************************************************/
  108935. typedef struct {
  108936. int blockflag;
  108937. int windowtype;
  108938. int transformtype;
  108939. int mapping;
  108940. } vorbis_info_mode;
  108941. typedef void vorbis_info_floor;
  108942. typedef void vorbis_info_residue;
  108943. typedef void vorbis_info_mapping;
  108944. /*** Start of inlined file: psy.h ***/
  108945. #ifndef _V_PSY_H_
  108946. #define _V_PSY_H_
  108947. /*** Start of inlined file: smallft.h ***/
  108948. #ifndef _V_SMFT_H_
  108949. #define _V_SMFT_H_
  108950. typedef struct {
  108951. int n;
  108952. float *trigcache;
  108953. int *splitcache;
  108954. } drft_lookup;
  108955. extern void drft_forward(drft_lookup *l,float *data);
  108956. extern void drft_backward(drft_lookup *l,float *data);
  108957. extern void drft_init(drft_lookup *l,int n);
  108958. extern void drft_clear(drft_lookup *l);
  108959. #endif
  108960. /*** End of inlined file: smallft.h ***/
  108961. /*** Start of inlined file: backends.h ***/
  108962. /* this is exposed up here because we need it for static modes.
  108963. Lookups for each backend aren't exposed because there's no reason
  108964. to do so */
  108965. #ifndef _vorbis_backend_h_
  108966. #define _vorbis_backend_h_
  108967. /* this would all be simpler/shorter with templates, but.... */
  108968. /* Floor backend generic *****************************************/
  108969. typedef struct{
  108970. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  108971. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  108972. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  108973. void (*free_info) (vorbis_info_floor *);
  108974. void (*free_look) (vorbis_look_floor *);
  108975. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  108976. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  108977. void *buffer,float *);
  108978. } vorbis_func_floor;
  108979. typedef struct{
  108980. int order;
  108981. long rate;
  108982. long barkmap;
  108983. int ampbits;
  108984. int ampdB;
  108985. int numbooks; /* <= 16 */
  108986. int books[16];
  108987. float lessthan; /* encode-only config setting hacks for libvorbis */
  108988. float greaterthan; /* encode-only config setting hacks for libvorbis */
  108989. } vorbis_info_floor0;
  108990. #define VIF_POSIT 63
  108991. #define VIF_CLASS 16
  108992. #define VIF_PARTS 31
  108993. typedef struct{
  108994. int partitions; /* 0 to 31 */
  108995. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  108996. int class_dim[VIF_CLASS]; /* 1 to 8 */
  108997. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  108998. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  108999. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109000. int mult; /* 1 2 3 or 4 */
  109001. int postlist[VIF_POSIT+2]; /* first two implicit */
  109002. /* encode side analysis parameters */
  109003. float maxover;
  109004. float maxunder;
  109005. float maxerr;
  109006. float twofitweight;
  109007. float twofitatten;
  109008. int n;
  109009. } vorbis_info_floor1;
  109010. /* Residue backend generic *****************************************/
  109011. typedef struct{
  109012. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109013. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109014. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109015. vorbis_info_residue *);
  109016. void (*free_info) (vorbis_info_residue *);
  109017. void (*free_look) (vorbis_look_residue *);
  109018. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109019. float **,int *,int);
  109020. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109021. vorbis_look_residue *,
  109022. float **,float **,int *,int,long **);
  109023. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109024. float **,int *,int);
  109025. } vorbis_func_residue;
  109026. typedef struct vorbis_info_residue0{
  109027. /* block-partitioned VQ coded straight residue */
  109028. long begin;
  109029. long end;
  109030. /* first stage (lossless partitioning) */
  109031. int grouping; /* group n vectors per partition */
  109032. int partitions; /* possible codebooks for a partition */
  109033. int groupbook; /* huffbook for partitioning */
  109034. int secondstages[64]; /* expanded out to pointers in lookup */
  109035. int booklist[256]; /* list of second stage books */
  109036. float classmetric1[64];
  109037. float classmetric2[64];
  109038. } vorbis_info_residue0;
  109039. /* Mapping backend generic *****************************************/
  109040. typedef struct{
  109041. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109042. oggpack_buffer *);
  109043. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109044. void (*free_info) (vorbis_info_mapping *);
  109045. int (*forward) (struct vorbis_block *vb);
  109046. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109047. } vorbis_func_mapping;
  109048. typedef struct vorbis_info_mapping0{
  109049. int submaps; /* <= 16 */
  109050. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109051. int floorsubmap[16]; /* [mux] submap to floors */
  109052. int residuesubmap[16]; /* [mux] submap to residue */
  109053. int coupling_steps;
  109054. int coupling_mag[256];
  109055. int coupling_ang[256];
  109056. } vorbis_info_mapping0;
  109057. #endif
  109058. /*** End of inlined file: backends.h ***/
  109059. #ifndef EHMER_MAX
  109060. #define EHMER_MAX 56
  109061. #endif
  109062. /* psychoacoustic setup ********************************************/
  109063. #define P_BANDS 17 /* 62Hz to 16kHz */
  109064. #define P_LEVELS 8 /* 30dB to 100dB */
  109065. #define P_LEVEL_0 30. /* 30 dB */
  109066. #define P_NOISECURVES 3
  109067. #define NOISE_COMPAND_LEVELS 40
  109068. typedef struct vorbis_info_psy{
  109069. int blockflag;
  109070. float ath_adjatt;
  109071. float ath_maxatt;
  109072. float tone_masteratt[P_NOISECURVES];
  109073. float tone_centerboost;
  109074. float tone_decay;
  109075. float tone_abs_limit;
  109076. float toneatt[P_BANDS];
  109077. int noisemaskp;
  109078. float noisemaxsupp;
  109079. float noisewindowlo;
  109080. float noisewindowhi;
  109081. int noisewindowlomin;
  109082. int noisewindowhimin;
  109083. int noisewindowfixed;
  109084. float noiseoff[P_NOISECURVES][P_BANDS];
  109085. float noisecompand[NOISE_COMPAND_LEVELS];
  109086. float max_curve_dB;
  109087. int normal_channel_p;
  109088. int normal_point_p;
  109089. int normal_start;
  109090. int normal_partition;
  109091. double normal_thresh;
  109092. } vorbis_info_psy;
  109093. typedef struct{
  109094. int eighth_octave_lines;
  109095. /* for block long/short tuning; encode only */
  109096. float preecho_thresh[VE_BANDS];
  109097. float postecho_thresh[VE_BANDS];
  109098. float stretch_penalty;
  109099. float preecho_minenergy;
  109100. float ampmax_att_per_sec;
  109101. /* channel coupling config */
  109102. int coupling_pkHz[PACKETBLOBS];
  109103. int coupling_pointlimit[2][PACKETBLOBS];
  109104. int coupling_prepointamp[PACKETBLOBS];
  109105. int coupling_postpointamp[PACKETBLOBS];
  109106. int sliding_lowpass[2][PACKETBLOBS];
  109107. } vorbis_info_psy_global;
  109108. typedef struct {
  109109. float ampmax;
  109110. int channels;
  109111. vorbis_info_psy_global *gi;
  109112. int coupling_pointlimit[2][P_NOISECURVES];
  109113. } vorbis_look_psy_global;
  109114. typedef struct {
  109115. int n;
  109116. struct vorbis_info_psy *vi;
  109117. float ***tonecurves;
  109118. float **noiseoffset;
  109119. float *ath;
  109120. long *octave; /* in n.ocshift format */
  109121. long *bark;
  109122. long firstoc;
  109123. long shiftoc;
  109124. int eighth_octave_lines; /* power of two, please */
  109125. int total_octave_lines;
  109126. long rate; /* cache it */
  109127. float m_val; /* Masking compensation value */
  109128. } vorbis_look_psy;
  109129. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  109130. vorbis_info_psy_global *gi,int n,long rate);
  109131. extern void _vp_psy_clear(vorbis_look_psy *p);
  109132. extern void *_vi_psy_dup(void *source);
  109133. extern void _vi_psy_free(vorbis_info_psy *i);
  109134. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  109135. extern void _vp_remove_floor(vorbis_look_psy *p,
  109136. float *mdct,
  109137. int *icodedflr,
  109138. float *residue,
  109139. int sliding_lowpass);
  109140. extern void _vp_noisemask(vorbis_look_psy *p,
  109141. float *logmdct,
  109142. float *logmask);
  109143. extern void _vp_tonemask(vorbis_look_psy *p,
  109144. float *logfft,
  109145. float *logmask,
  109146. float global_specmax,
  109147. float local_specmax);
  109148. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  109149. float *noise,
  109150. float *tone,
  109151. int offset_select,
  109152. float *logmask,
  109153. float *mdct,
  109154. float *logmdct);
  109155. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  109156. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  109157. vorbis_info_psy_global *g,
  109158. vorbis_look_psy *p,
  109159. vorbis_info_mapping0 *vi,
  109160. float **mdct);
  109161. extern void _vp_couple(int blobno,
  109162. vorbis_info_psy_global *g,
  109163. vorbis_look_psy *p,
  109164. vorbis_info_mapping0 *vi,
  109165. float **res,
  109166. float **mag_memo,
  109167. int **mag_sort,
  109168. int **ifloor,
  109169. int *nonzero,
  109170. int sliding_lowpass);
  109171. extern void _vp_noise_normalize(vorbis_look_psy *p,
  109172. float *in,float *out,int *sortedindex);
  109173. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  109174. float *magnitudes,int *sortedindex);
  109175. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  109176. vorbis_look_psy *p,
  109177. vorbis_info_mapping0 *vi,
  109178. float **mags);
  109179. extern void hf_reduction(vorbis_info_psy_global *g,
  109180. vorbis_look_psy *p,
  109181. vorbis_info_mapping0 *vi,
  109182. float **mdct);
  109183. #endif
  109184. /*** End of inlined file: psy.h ***/
  109185. /*** Start of inlined file: bitrate.h ***/
  109186. #ifndef _V_BITRATE_H_
  109187. #define _V_BITRATE_H_
  109188. /*** Start of inlined file: os.h ***/
  109189. #ifndef _OS_H
  109190. #define _OS_H
  109191. /********************************************************************
  109192. * *
  109193. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  109194. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  109195. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  109196. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  109197. * *
  109198. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  109199. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  109200. * *
  109201. ********************************************************************
  109202. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  109203. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  109204. ********************************************************************/
  109205. #ifdef HAVE_CONFIG_H
  109206. #include "config.h"
  109207. #endif
  109208. #include <math.h>
  109209. /*** Start of inlined file: misc.h ***/
  109210. #ifndef _V_RANDOM_H_
  109211. #define _V_RANDOM_H_
  109212. extern int analysis_noisy;
  109213. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  109214. extern void _vorbis_block_ripcord(vorbis_block *vb);
  109215. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109216. ogg_int64_t off);
  109217. #ifdef DEBUG_MALLOC
  109218. #define _VDBG_GRAPHFILE "malloc.m"
  109219. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  109220. extern void _VDBG_free(void *ptr,char *file,long line);
  109221. #ifndef MISC_C
  109222. #undef _ogg_malloc
  109223. #undef _ogg_calloc
  109224. #undef _ogg_realloc
  109225. #undef _ogg_free
  109226. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  109227. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  109228. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  109229. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  109230. #endif
  109231. #endif
  109232. #endif
  109233. /*** End of inlined file: misc.h ***/
  109234. #ifndef _V_IFDEFJAIL_H_
  109235. # define _V_IFDEFJAIL_H_
  109236. # ifdef __GNUC__
  109237. # define STIN static __inline__
  109238. # elif _WIN32
  109239. # define STIN static __inline
  109240. # else
  109241. # define STIN static
  109242. # endif
  109243. #ifdef DJGPP
  109244. # define rint(x) (floor((x)+0.5f))
  109245. #endif
  109246. #ifndef M_PI
  109247. # define M_PI (3.1415926536f)
  109248. #endif
  109249. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  109250. # include <malloc.h>
  109251. # define rint(x) (floor((x)+0.5f))
  109252. # define NO_FLOAT_MATH_LIB
  109253. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  109254. #endif
  109255. #if defined(__SYMBIAN32__) && defined(__WINS__)
  109256. void *_alloca(size_t size);
  109257. # define alloca _alloca
  109258. #endif
  109259. #ifndef FAST_HYPOT
  109260. # define FAST_HYPOT hypot
  109261. #endif
  109262. #endif
  109263. #ifdef HAVE_ALLOCA_H
  109264. # include <alloca.h>
  109265. #endif
  109266. #ifdef USE_MEMORY_H
  109267. # include <memory.h>
  109268. #endif
  109269. #ifndef min
  109270. # define min(x,y) ((x)>(y)?(y):(x))
  109271. #endif
  109272. #ifndef max
  109273. # define max(x,y) ((x)<(y)?(y):(x))
  109274. #endif
  109275. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  109276. # define VORBIS_FPU_CONTROL
  109277. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  109278. Because of encapsulation constraints (GCC can't see inside the asm
  109279. block and so we end up doing stupid things like a store/load that
  109280. is collectively a noop), we do it this way */
  109281. /* we must set up the fpu before this works!! */
  109282. typedef ogg_int16_t vorbis_fpu_control;
  109283. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109284. ogg_int16_t ret;
  109285. ogg_int16_t temp;
  109286. __asm__ __volatile__("fnstcw %0\n\t"
  109287. "movw %0,%%dx\n\t"
  109288. "orw $62463,%%dx\n\t"
  109289. "movw %%dx,%1\n\t"
  109290. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  109291. *fpu=ret;
  109292. }
  109293. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109294. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  109295. }
  109296. /* assumes the FPU is in round mode! */
  109297. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  109298. we get extra fst/fld to
  109299. truncate precision */
  109300. int i;
  109301. __asm__("fistl %0": "=m"(i) : "t"(f));
  109302. return(i);
  109303. }
  109304. #endif
  109305. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  109306. # define VORBIS_FPU_CONTROL
  109307. typedef ogg_int16_t vorbis_fpu_control;
  109308. static __inline int vorbis_ftoi(double f){
  109309. int i;
  109310. __asm{
  109311. fld f
  109312. fistp i
  109313. }
  109314. return i;
  109315. }
  109316. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109317. }
  109318. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109319. }
  109320. #endif
  109321. #ifndef VORBIS_FPU_CONTROL
  109322. typedef int vorbis_fpu_control;
  109323. static int vorbis_ftoi(double f){
  109324. return (int)(f+.5);
  109325. }
  109326. /* We don't have special code for this compiler/arch, so do it the slow way */
  109327. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  109328. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  109329. #endif
  109330. #endif /* _OS_H */
  109331. /*** End of inlined file: os.h ***/
  109332. /* encode side bitrate tracking */
  109333. typedef struct bitrate_manager_state {
  109334. int managed;
  109335. long avg_reservoir;
  109336. long minmax_reservoir;
  109337. long avg_bitsper;
  109338. long min_bitsper;
  109339. long max_bitsper;
  109340. long short_per_long;
  109341. double avgfloat;
  109342. vorbis_block *vb;
  109343. int choice;
  109344. } bitrate_manager_state;
  109345. typedef struct bitrate_manager_info{
  109346. long avg_rate;
  109347. long min_rate;
  109348. long max_rate;
  109349. long reservoir_bits;
  109350. double reservoir_bias;
  109351. double slew_damp;
  109352. } bitrate_manager_info;
  109353. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  109354. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  109355. extern int vorbis_bitrate_managed(vorbis_block *vb);
  109356. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  109357. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  109358. #endif
  109359. /*** End of inlined file: bitrate.h ***/
  109360. static int ilog(unsigned int v){
  109361. int ret=0;
  109362. while(v){
  109363. ret++;
  109364. v>>=1;
  109365. }
  109366. return(ret);
  109367. }
  109368. static int ilog2(unsigned int v){
  109369. int ret=0;
  109370. if(v)--v;
  109371. while(v){
  109372. ret++;
  109373. v>>=1;
  109374. }
  109375. return(ret);
  109376. }
  109377. typedef struct private_state {
  109378. /* local lookup storage */
  109379. envelope_lookup *ve; /* envelope lookup */
  109380. int window[2];
  109381. vorbis_look_transform **transform[2]; /* block, type */
  109382. drft_lookup fft_look[2];
  109383. int modebits;
  109384. vorbis_look_floor **flr;
  109385. vorbis_look_residue **residue;
  109386. vorbis_look_psy *psy;
  109387. vorbis_look_psy_global *psy_g_look;
  109388. /* local storage, only used on the encoding side. This way the
  109389. application does not need to worry about freeing some packets'
  109390. memory and not others'; packet storage is always tracked.
  109391. Cleared next call to a _dsp_ function */
  109392. unsigned char *header;
  109393. unsigned char *header1;
  109394. unsigned char *header2;
  109395. bitrate_manager_state bms;
  109396. ogg_int64_t sample_count;
  109397. } private_state;
  109398. /* codec_setup_info contains all the setup information specific to the
  109399. specific compression/decompression mode in progress (eg,
  109400. psychoacoustic settings, channel setup, options, codebook
  109401. etc).
  109402. *********************************************************************/
  109403. /*** Start of inlined file: highlevel.h ***/
  109404. typedef struct highlevel_byblocktype {
  109405. double tone_mask_setting;
  109406. double tone_peaklimit_setting;
  109407. double noise_bias_setting;
  109408. double noise_compand_setting;
  109409. } highlevel_byblocktype;
  109410. typedef struct highlevel_encode_setup {
  109411. void *setup;
  109412. int set_in_stone;
  109413. double base_setting;
  109414. double long_setting;
  109415. double short_setting;
  109416. double impulse_noisetune;
  109417. int managed;
  109418. long bitrate_min;
  109419. long bitrate_av;
  109420. double bitrate_av_damp;
  109421. long bitrate_max;
  109422. long bitrate_reservoir;
  109423. double bitrate_reservoir_bias;
  109424. int impulse_block_p;
  109425. int noise_normalize_p;
  109426. double stereo_point_setting;
  109427. double lowpass_kHz;
  109428. double ath_floating_dB;
  109429. double ath_absolute_dB;
  109430. double amplitude_track_dBpersec;
  109431. double trigger_setting;
  109432. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  109433. } highlevel_encode_setup;
  109434. /*** End of inlined file: highlevel.h ***/
  109435. typedef struct codec_setup_info {
  109436. /* Vorbis supports only short and long blocks, but allows the
  109437. encoder to choose the sizes */
  109438. long blocksizes[2];
  109439. /* modes are the primary means of supporting on-the-fly different
  109440. blocksizes, different channel mappings (LR or M/A),
  109441. different residue backends, etc. Each mode consists of a
  109442. blocksize flag and a mapping (along with the mapping setup */
  109443. int modes;
  109444. int maps;
  109445. int floors;
  109446. int residues;
  109447. int books;
  109448. int psys; /* encode only */
  109449. vorbis_info_mode *mode_param[64];
  109450. int map_type[64];
  109451. vorbis_info_mapping *map_param[64];
  109452. int floor_type[64];
  109453. vorbis_info_floor *floor_param[64];
  109454. int residue_type[64];
  109455. vorbis_info_residue *residue_param[64];
  109456. static_codebook *book_param[256];
  109457. codebook *fullbooks;
  109458. vorbis_info_psy *psy_param[4]; /* encode only */
  109459. vorbis_info_psy_global psy_g_param;
  109460. bitrate_manager_info bi;
  109461. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  109462. highly redundant structure, but
  109463. improves clarity of program flow. */
  109464. int halfrate_flag; /* painless downsample for decode */
  109465. } codec_setup_info;
  109466. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  109467. extern void _vp_global_free(vorbis_look_psy_global *look);
  109468. #endif
  109469. /*** End of inlined file: codec_internal.h ***/
  109470. /*** Start of inlined file: registry.h ***/
  109471. #ifndef _V_REG_H_
  109472. #define _V_REG_H_
  109473. #define VI_TRANSFORMB 1
  109474. #define VI_WINDOWB 1
  109475. #define VI_TIMEB 1
  109476. #define VI_FLOORB 2
  109477. #define VI_RESB 3
  109478. #define VI_MAPB 1
  109479. extern vorbis_func_floor *_floor_P[];
  109480. extern vorbis_func_residue *_residue_P[];
  109481. extern vorbis_func_mapping *_mapping_P[];
  109482. #endif
  109483. /*** End of inlined file: registry.h ***/
  109484. /*** Start of inlined file: scales.h ***/
  109485. #ifndef _V_SCALES_H_
  109486. #define _V_SCALES_H_
  109487. #include <math.h>
  109488. /* 20log10(x) */
  109489. #define VORBIS_IEEE_FLOAT32 1
  109490. #ifdef VORBIS_IEEE_FLOAT32
  109491. static float unitnorm(float x){
  109492. union {
  109493. ogg_uint32_t i;
  109494. float f;
  109495. } ix;
  109496. ix.f = x;
  109497. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  109498. return ix.f;
  109499. }
  109500. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  109501. static float todB(const float *x){
  109502. union {
  109503. ogg_uint32_t i;
  109504. float f;
  109505. } ix;
  109506. ix.f = *x;
  109507. ix.i = ix.i&0x7fffffff;
  109508. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  109509. }
  109510. #define todB_nn(x) todB(x)
  109511. #else
  109512. static float unitnorm(float x){
  109513. if(x<0)return(-1.f);
  109514. return(1.f);
  109515. }
  109516. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  109517. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  109518. #endif
  109519. #define fromdB(x) (exp((x)*.11512925f))
  109520. /* The bark scale equations are approximations, since the original
  109521. table was somewhat hand rolled. The below are chosen to have the
  109522. best possible fit to the rolled tables, thus their somewhat odd
  109523. appearance (these are more accurate and over a longer range than
  109524. the oft-quoted bark equations found in the texts I have). The
  109525. approximations are valid from 0 - 30kHz (nyquist) or so.
  109526. all f in Hz, z in Bark */
  109527. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  109528. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  109529. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  109530. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  109531. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  109532. 0.0 */
  109533. #define toOC(n) (log(n)*1.442695f-5.965784f)
  109534. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  109535. #endif
  109536. /*** End of inlined file: scales.h ***/
  109537. int analysis_noisy=1;
  109538. /* decides between modes, dispatches to the appropriate mapping. */
  109539. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  109540. int ret,i;
  109541. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  109542. vb->glue_bits=0;
  109543. vb->time_bits=0;
  109544. vb->floor_bits=0;
  109545. vb->res_bits=0;
  109546. /* first things first. Make sure encode is ready */
  109547. for(i=0;i<PACKETBLOBS;i++)
  109548. oggpack_reset(vbi->packetblob[i]);
  109549. /* we only have one mapping type (0), and we let the mapping code
  109550. itself figure out what soft mode to use. This allows easier
  109551. bitrate management */
  109552. if((ret=_mapping_P[0]->forward(vb)))
  109553. return(ret);
  109554. if(op){
  109555. if(vorbis_bitrate_managed(vb))
  109556. /* The app is using a bitmanaged mode... but not using the
  109557. bitrate management interface. */
  109558. return(OV_EINVAL);
  109559. op->packet=oggpack_get_buffer(&vb->opb);
  109560. op->bytes=oggpack_bytes(&vb->opb);
  109561. op->b_o_s=0;
  109562. op->e_o_s=vb->eofflag;
  109563. op->granulepos=vb->granulepos;
  109564. op->packetno=vb->sequence; /* for sake of completeness */
  109565. }
  109566. return(0);
  109567. }
  109568. /* there was no great place to put this.... */
  109569. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  109570. int j;
  109571. FILE *of;
  109572. char buffer[80];
  109573. /* if(i==5870){*/
  109574. sprintf(buffer,"%s_%d.m",base,i);
  109575. of=fopen(buffer,"w");
  109576. if(!of)perror("failed to open data dump file");
  109577. for(j=0;j<n;j++){
  109578. if(bark){
  109579. float b=toBARK((4000.f*j/n)+.25);
  109580. fprintf(of,"%f ",b);
  109581. }else
  109582. if(off!=0)
  109583. fprintf(of,"%f ",(double)(j+off)/8000.);
  109584. else
  109585. fprintf(of,"%f ",(double)j);
  109586. if(dB){
  109587. float val;
  109588. if(v[j]==0.)
  109589. val=-140.;
  109590. else
  109591. val=todB(v+j);
  109592. fprintf(of,"%f\n",val);
  109593. }else{
  109594. fprintf(of,"%f\n",v[j]);
  109595. }
  109596. }
  109597. fclose(of);
  109598. /* } */
  109599. }
  109600. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109601. ogg_int64_t off){
  109602. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  109603. }
  109604. #endif
  109605. /*** End of inlined file: analysis.c ***/
  109606. /*** Start of inlined file: bitrate.c ***/
  109607. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109608. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109609. // tasks..
  109610. #if JUCE_MSVC
  109611. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109612. #endif
  109613. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109614. #if JUCE_USE_OGGVORBIS
  109615. #include <stdlib.h>
  109616. #include <string.h>
  109617. #include <math.h>
  109618. /* compute bitrate tracking setup */
  109619. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  109620. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  109621. bitrate_manager_info *bi=&ci->bi;
  109622. memset(bm,0,sizeof(*bm));
  109623. if(bi && (bi->reservoir_bits>0)){
  109624. long ratesamples=vi->rate;
  109625. int halfsamples=ci->blocksizes[0]>>1;
  109626. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  109627. bm->managed=1;
  109628. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  109629. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  109630. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  109631. bm->avgfloat=PACKETBLOBS/2;
  109632. /* not a necessary fix, but one that leads to a more balanced
  109633. typical initialization */
  109634. {
  109635. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  109636. bm->minmax_reservoir=desired_fill;
  109637. bm->avg_reservoir=desired_fill;
  109638. }
  109639. }
  109640. }
  109641. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  109642. memset(bm,0,sizeof(*bm));
  109643. return;
  109644. }
  109645. int vorbis_bitrate_managed(vorbis_block *vb){
  109646. vorbis_dsp_state *vd=vb->vd;
  109647. private_state *b=(private_state*)vd->backend_state;
  109648. bitrate_manager_state *bm=&b->bms;
  109649. if(bm && bm->managed)return(1);
  109650. return(0);
  109651. }
  109652. /* finish taking in the block we just processed */
  109653. int vorbis_bitrate_addblock(vorbis_block *vb){
  109654. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  109655. vorbis_dsp_state *vd=vb->vd;
  109656. private_state *b=(private_state*)vd->backend_state;
  109657. bitrate_manager_state *bm=&b->bms;
  109658. vorbis_info *vi=vd->vi;
  109659. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109660. bitrate_manager_info *bi=&ci->bi;
  109661. int choice=rint(bm->avgfloat);
  109662. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109663. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  109664. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  109665. int samples=ci->blocksizes[vb->W]>>1;
  109666. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  109667. if(!bm->managed){
  109668. /* not a bitrate managed stream, but for API simplicity, we'll
  109669. buffer the packet to keep the code path clean */
  109670. if(bm->vb)return(-1); /* one has been submitted without
  109671. being claimed */
  109672. bm->vb=vb;
  109673. return(0);
  109674. }
  109675. bm->vb=vb;
  109676. /* look ahead for avg floater */
  109677. if(bm->avg_bitsper>0){
  109678. double slew=0.;
  109679. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  109680. double slewlimit= 15./bi->slew_damp;
  109681. /* choosing a new floater:
  109682. if we're over target, we slew down
  109683. if we're under target, we slew up
  109684. choose slew as follows: look through packetblobs of this frame
  109685. and set slew as the first in the appropriate direction that
  109686. gives us the slew we want. This may mean no slew if delta is
  109687. already favorable.
  109688. Then limit slew to slew max */
  109689. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  109690. while(choice>0 && this_bits>avg_target_bits &&
  109691. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  109692. choice--;
  109693. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109694. }
  109695. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  109696. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  109697. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  109698. choice++;
  109699. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109700. }
  109701. }
  109702. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  109703. if(slew<-slewlimit)slew=-slewlimit;
  109704. if(slew>slewlimit)slew=slewlimit;
  109705. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  109706. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109707. }
  109708. /* enforce min(if used) on the current floater (if used) */
  109709. if(bm->min_bitsper>0){
  109710. /* do we need to force the bitrate up? */
  109711. if(this_bits<min_target_bits){
  109712. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  109713. choice++;
  109714. if(choice>=PACKETBLOBS)break;
  109715. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109716. }
  109717. }
  109718. }
  109719. /* enforce max (if used) on the current floater (if used) */
  109720. if(bm->max_bitsper>0){
  109721. /* do we need to force the bitrate down? */
  109722. if(this_bits>max_target_bits){
  109723. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  109724. choice--;
  109725. if(choice<0)break;
  109726. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109727. }
  109728. }
  109729. }
  109730. /* Choice of packetblobs now made based on floater, and min/max
  109731. requirements. Now boundary check extreme choices */
  109732. if(choice<0){
  109733. /* choosing a smaller packetblob is insufficient to trim bitrate.
  109734. frame will need to be truncated */
  109735. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  109736. bm->choice=choice=0;
  109737. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  109738. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  109739. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109740. }
  109741. }else{
  109742. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  109743. if(choice>=PACKETBLOBS)
  109744. choice=PACKETBLOBS-1;
  109745. bm->choice=choice;
  109746. /* prop up bitrate according to demand. pad this frame out with zeroes */
  109747. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  109748. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  109749. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109750. }
  109751. /* now we have the final packet and the final packet size. Update statistics */
  109752. /* min and max reservoir */
  109753. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  109754. if(max_target_bits>0 && this_bits>max_target_bits){
  109755. bm->minmax_reservoir+=(this_bits-max_target_bits);
  109756. }else if(min_target_bits>0 && this_bits<min_target_bits){
  109757. bm->minmax_reservoir+=(this_bits-min_target_bits);
  109758. }else{
  109759. /* inbetween; we want to take reservoir toward but not past desired_fill */
  109760. if(bm->minmax_reservoir>desired_fill){
  109761. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  109762. bm->minmax_reservoir+=(this_bits-max_target_bits);
  109763. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  109764. }else{
  109765. bm->minmax_reservoir=desired_fill;
  109766. }
  109767. }else{
  109768. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  109769. bm->minmax_reservoir+=(this_bits-min_target_bits);
  109770. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  109771. }else{
  109772. bm->minmax_reservoir=desired_fill;
  109773. }
  109774. }
  109775. }
  109776. }
  109777. /* avg reservoir */
  109778. if(bm->avg_bitsper>0){
  109779. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  109780. bm->avg_reservoir+=this_bits-avg_target_bits;
  109781. }
  109782. return(0);
  109783. }
  109784. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  109785. private_state *b=(private_state*)vd->backend_state;
  109786. bitrate_manager_state *bm=&b->bms;
  109787. vorbis_block *vb=bm->vb;
  109788. int choice=PACKETBLOBS/2;
  109789. if(!vb)return 0;
  109790. if(op){
  109791. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  109792. if(vorbis_bitrate_managed(vb))
  109793. choice=bm->choice;
  109794. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  109795. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  109796. op->b_o_s=0;
  109797. op->e_o_s=vb->eofflag;
  109798. op->granulepos=vb->granulepos;
  109799. op->packetno=vb->sequence; /* for sake of completeness */
  109800. }
  109801. bm->vb=0;
  109802. return(1);
  109803. }
  109804. #endif
  109805. /*** End of inlined file: bitrate.c ***/
  109806. /*** Start of inlined file: block.c ***/
  109807. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109808. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109809. // tasks..
  109810. #if JUCE_MSVC
  109811. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109812. #endif
  109813. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109814. #if JUCE_USE_OGGVORBIS
  109815. #include <stdio.h>
  109816. #include <stdlib.h>
  109817. #include <string.h>
  109818. /*** Start of inlined file: window.h ***/
  109819. #ifndef _V_WINDOW_
  109820. #define _V_WINDOW_
  109821. extern float *_vorbis_window_get(int n);
  109822. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  109823. int lW,int W,int nW);
  109824. #endif
  109825. /*** End of inlined file: window.h ***/
  109826. /*** Start of inlined file: lpc.h ***/
  109827. #ifndef _V_LPC_H_
  109828. #define _V_LPC_H_
  109829. /* simple linear scale LPC code */
  109830. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  109831. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  109832. float *data,long n);
  109833. #endif
  109834. /*** End of inlined file: lpc.h ***/
  109835. /* pcm accumulator examples (not exhaustive):
  109836. <-------------- lW ---------------->
  109837. <--------------- W ---------------->
  109838. : .....|..... _______________ |
  109839. : .''' | '''_--- | |\ |
  109840. :.....''' |_____--- '''......| | \_______|
  109841. :.................|__________________|_______|__|______|
  109842. |<------ Sl ------>| > Sr < |endW
  109843. |beginSl |endSl | |endSr
  109844. |beginW |endlW |beginSr
  109845. |< lW >|
  109846. <--------------- W ---------------->
  109847. | | .. ______________ |
  109848. | | ' `/ | ---_ |
  109849. |___.'___/`. | ---_____|
  109850. |_______|__|_______|_________________|
  109851. | >|Sl|< |<------ Sr ----->|endW
  109852. | | |endSl |beginSr |endSr
  109853. |beginW | |endlW
  109854. mult[0] |beginSl mult[n]
  109855. <-------------- lW ----------------->
  109856. |<--W-->|
  109857. : .............. ___ | |
  109858. : .''' |`/ \ | |
  109859. :.....''' |/`....\|...|
  109860. :.........................|___|___|___|
  109861. |Sl |Sr |endW
  109862. | | |endSr
  109863. | |beginSr
  109864. | |endSl
  109865. |beginSl
  109866. |beginW
  109867. */
  109868. /* block abstraction setup *********************************************/
  109869. #ifndef WORD_ALIGN
  109870. #define WORD_ALIGN 8
  109871. #endif
  109872. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  109873. int i;
  109874. memset(vb,0,sizeof(*vb));
  109875. vb->vd=v;
  109876. vb->localalloc=0;
  109877. vb->localstore=NULL;
  109878. if(v->analysisp){
  109879. vorbis_block_internal *vbi=(vorbis_block_internal*)
  109880. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  109881. vbi->ampmax=-9999;
  109882. for(i=0;i<PACKETBLOBS;i++){
  109883. if(i==PACKETBLOBS/2){
  109884. vbi->packetblob[i]=&vb->opb;
  109885. }else{
  109886. vbi->packetblob[i]=
  109887. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  109888. }
  109889. oggpack_writeinit(vbi->packetblob[i]);
  109890. }
  109891. }
  109892. return(0);
  109893. }
  109894. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  109895. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  109896. if(bytes+vb->localtop>vb->localalloc){
  109897. /* can't just _ogg_realloc... there are outstanding pointers */
  109898. if(vb->localstore){
  109899. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  109900. vb->totaluse+=vb->localtop;
  109901. link->next=vb->reap;
  109902. link->ptr=vb->localstore;
  109903. vb->reap=link;
  109904. }
  109905. /* highly conservative */
  109906. vb->localalloc=bytes;
  109907. vb->localstore=_ogg_malloc(vb->localalloc);
  109908. vb->localtop=0;
  109909. }
  109910. {
  109911. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  109912. vb->localtop+=bytes;
  109913. return ret;
  109914. }
  109915. }
  109916. /* reap the chain, pull the ripcord */
  109917. void _vorbis_block_ripcord(vorbis_block *vb){
  109918. /* reap the chain */
  109919. struct alloc_chain *reap=vb->reap;
  109920. while(reap){
  109921. struct alloc_chain *next=reap->next;
  109922. _ogg_free(reap->ptr);
  109923. memset(reap,0,sizeof(*reap));
  109924. _ogg_free(reap);
  109925. reap=next;
  109926. }
  109927. /* consolidate storage */
  109928. if(vb->totaluse){
  109929. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  109930. vb->localalloc+=vb->totaluse;
  109931. vb->totaluse=0;
  109932. }
  109933. /* pull the ripcord */
  109934. vb->localtop=0;
  109935. vb->reap=NULL;
  109936. }
  109937. int vorbis_block_clear(vorbis_block *vb){
  109938. int i;
  109939. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  109940. _vorbis_block_ripcord(vb);
  109941. if(vb->localstore)_ogg_free(vb->localstore);
  109942. if(vbi){
  109943. for(i=0;i<PACKETBLOBS;i++){
  109944. oggpack_writeclear(vbi->packetblob[i]);
  109945. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  109946. }
  109947. _ogg_free(vbi);
  109948. }
  109949. memset(vb,0,sizeof(*vb));
  109950. return(0);
  109951. }
  109952. /* Analysis side code, but directly related to blocking. Thus it's
  109953. here and not in analysis.c (which is for analysis transforms only).
  109954. The init is here because some of it is shared */
  109955. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  109956. int i;
  109957. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109958. private_state *b=NULL;
  109959. int hs;
  109960. if(ci==NULL) return 1;
  109961. hs=ci->halfrate_flag;
  109962. memset(v,0,sizeof(*v));
  109963. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  109964. v->vi=vi;
  109965. b->modebits=ilog2(ci->modes);
  109966. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  109967. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  109968. /* MDCT is tranform 0 */
  109969. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  109970. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  109971. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  109972. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  109973. /* Vorbis I uses only window type 0 */
  109974. b->window[0]=ilog2(ci->blocksizes[0])-6;
  109975. b->window[1]=ilog2(ci->blocksizes[1])-6;
  109976. if(encp){ /* encode/decode differ here */
  109977. /* analysis always needs an fft */
  109978. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  109979. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  109980. /* finish the codebooks */
  109981. if(!ci->fullbooks){
  109982. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  109983. for(i=0;i<ci->books;i++)
  109984. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  109985. }
  109986. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  109987. for(i=0;i<ci->psys;i++){
  109988. _vp_psy_init(b->psy+i,
  109989. ci->psy_param[i],
  109990. &ci->psy_g_param,
  109991. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  109992. vi->rate);
  109993. }
  109994. v->analysisp=1;
  109995. }else{
  109996. /* finish the codebooks */
  109997. if(!ci->fullbooks){
  109998. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  109999. for(i=0;i<ci->books;i++){
  110000. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110001. /* decode codebooks are now standalone after init */
  110002. vorbis_staticbook_destroy(ci->book_param[i]);
  110003. ci->book_param[i]=NULL;
  110004. }
  110005. }
  110006. }
  110007. /* initialize the storage vectors. blocksize[1] is small for encode,
  110008. but the correct size for decode */
  110009. v->pcm_storage=ci->blocksizes[1];
  110010. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110011. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110012. {
  110013. int i;
  110014. for(i=0;i<vi->channels;i++)
  110015. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110016. }
  110017. /* all 1 (large block) or 0 (small block) */
  110018. /* explicitly set for the sake of clarity */
  110019. v->lW=0; /* previous window size */
  110020. v->W=0; /* current window size */
  110021. /* all vector indexes */
  110022. v->centerW=ci->blocksizes[1]/2;
  110023. v->pcm_current=v->centerW;
  110024. /* initialize all the backend lookups */
  110025. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110026. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110027. for(i=0;i<ci->floors;i++)
  110028. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110029. look(v,ci->floor_param[i]);
  110030. for(i=0;i<ci->residues;i++)
  110031. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110032. look(v,ci->residue_param[i]);
  110033. return 0;
  110034. }
  110035. /* arbitrary settings and spec-mandated numbers get filled in here */
  110036. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110037. private_state *b=NULL;
  110038. if(_vds_shared_init(v,vi,1))return 1;
  110039. b=(private_state*)v->backend_state;
  110040. b->psy_g_look=_vp_global_look(vi);
  110041. /* Initialize the envelope state storage */
  110042. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110043. _ve_envelope_init(b->ve,vi);
  110044. vorbis_bitrate_init(vi,&b->bms);
  110045. /* compressed audio packets start after the headers
  110046. with sequence number 3 */
  110047. v->sequence=3;
  110048. return(0);
  110049. }
  110050. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110051. int i;
  110052. if(v){
  110053. vorbis_info *vi=v->vi;
  110054. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110055. private_state *b=(private_state*)v->backend_state;
  110056. if(b){
  110057. if(b->ve){
  110058. _ve_envelope_clear(b->ve);
  110059. _ogg_free(b->ve);
  110060. }
  110061. if(b->transform[0]){
  110062. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110063. _ogg_free(b->transform[0][0]);
  110064. _ogg_free(b->transform[0]);
  110065. }
  110066. if(b->transform[1]){
  110067. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110068. _ogg_free(b->transform[1][0]);
  110069. _ogg_free(b->transform[1]);
  110070. }
  110071. if(b->flr){
  110072. for(i=0;i<ci->floors;i++)
  110073. _floor_P[ci->floor_type[i]]->
  110074. free_look(b->flr[i]);
  110075. _ogg_free(b->flr);
  110076. }
  110077. if(b->residue){
  110078. for(i=0;i<ci->residues;i++)
  110079. _residue_P[ci->residue_type[i]]->
  110080. free_look(b->residue[i]);
  110081. _ogg_free(b->residue);
  110082. }
  110083. if(b->psy){
  110084. for(i=0;i<ci->psys;i++)
  110085. _vp_psy_clear(b->psy+i);
  110086. _ogg_free(b->psy);
  110087. }
  110088. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110089. vorbis_bitrate_clear(&b->bms);
  110090. drft_clear(&b->fft_look[0]);
  110091. drft_clear(&b->fft_look[1]);
  110092. }
  110093. if(v->pcm){
  110094. for(i=0;i<vi->channels;i++)
  110095. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110096. _ogg_free(v->pcm);
  110097. if(v->pcmret)_ogg_free(v->pcmret);
  110098. }
  110099. if(b){
  110100. /* free header, header1, header2 */
  110101. if(b->header)_ogg_free(b->header);
  110102. if(b->header1)_ogg_free(b->header1);
  110103. if(b->header2)_ogg_free(b->header2);
  110104. _ogg_free(b);
  110105. }
  110106. memset(v,0,sizeof(*v));
  110107. }
  110108. }
  110109. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110110. int i;
  110111. vorbis_info *vi=v->vi;
  110112. private_state *b=(private_state*)v->backend_state;
  110113. /* free header, header1, header2 */
  110114. if(b->header)_ogg_free(b->header);b->header=NULL;
  110115. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110116. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110117. /* Do we have enough storage space for the requested buffer? If not,
  110118. expand the PCM (and envelope) storage */
  110119. if(v->pcm_current+vals>=v->pcm_storage){
  110120. v->pcm_storage=v->pcm_current+vals*2;
  110121. for(i=0;i<vi->channels;i++){
  110122. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110123. }
  110124. }
  110125. for(i=0;i<vi->channels;i++)
  110126. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  110127. return(v->pcmret);
  110128. }
  110129. static void _preextrapolate_helper(vorbis_dsp_state *v){
  110130. int i;
  110131. int order=32;
  110132. float *lpc=(float*)alloca(order*sizeof(*lpc));
  110133. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  110134. long j;
  110135. v->preextrapolate=1;
  110136. if(v->pcm_current-v->centerW>order*2){ /* safety */
  110137. for(i=0;i<v->vi->channels;i++){
  110138. /* need to run the extrapolation in reverse! */
  110139. for(j=0;j<v->pcm_current;j++)
  110140. work[j]=v->pcm[i][v->pcm_current-j-1];
  110141. /* prime as above */
  110142. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  110143. /* run the predictor filter */
  110144. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  110145. order,
  110146. work+v->pcm_current-v->centerW,
  110147. v->centerW);
  110148. for(j=0;j<v->pcm_current;j++)
  110149. v->pcm[i][v->pcm_current-j-1]=work[j];
  110150. }
  110151. }
  110152. }
  110153. /* call with val<=0 to set eof */
  110154. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  110155. vorbis_info *vi=v->vi;
  110156. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110157. if(vals<=0){
  110158. int order=32;
  110159. int i;
  110160. float *lpc=(float*) alloca(order*sizeof(*lpc));
  110161. /* if it wasn't done earlier (very short sample) */
  110162. if(!v->preextrapolate)
  110163. _preextrapolate_helper(v);
  110164. /* We're encoding the end of the stream. Just make sure we have
  110165. [at least] a few full blocks of zeroes at the end. */
  110166. /* actually, we don't want zeroes; that could drop a large
  110167. amplitude off a cliff, creating spread spectrum noise that will
  110168. suck to encode. Extrapolate for the sake of cleanliness. */
  110169. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  110170. v->eofflag=v->pcm_current;
  110171. v->pcm_current+=ci->blocksizes[1]*3;
  110172. for(i=0;i<vi->channels;i++){
  110173. if(v->eofflag>order*2){
  110174. /* extrapolate with LPC to fill in */
  110175. long n;
  110176. /* make a predictor filter */
  110177. n=v->eofflag;
  110178. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  110179. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  110180. /* run the predictor filter */
  110181. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  110182. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  110183. }else{
  110184. /* not enough data to extrapolate (unlikely to happen due to
  110185. guarding the overlap, but bulletproof in case that
  110186. assumtion goes away). zeroes will do. */
  110187. memset(v->pcm[i]+v->eofflag,0,
  110188. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  110189. }
  110190. }
  110191. }else{
  110192. if(v->pcm_current+vals>v->pcm_storage)
  110193. return(OV_EINVAL);
  110194. v->pcm_current+=vals;
  110195. /* we may want to reverse extrapolate the beginning of a stream
  110196. too... in case we're beginning on a cliff! */
  110197. /* clumsy, but simple. It only runs once, so simple is good. */
  110198. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  110199. _preextrapolate_helper(v);
  110200. }
  110201. return(0);
  110202. }
  110203. /* do the deltas, envelope shaping, pre-echo and determine the size of
  110204. the next block on which to continue analysis */
  110205. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  110206. int i;
  110207. vorbis_info *vi=v->vi;
  110208. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110209. private_state *b=(private_state*)v->backend_state;
  110210. vorbis_look_psy_global *g=b->psy_g_look;
  110211. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  110212. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110213. /* check to see if we're started... */
  110214. if(!v->preextrapolate)return(0);
  110215. /* check to see if we're done... */
  110216. if(v->eofflag==-1)return(0);
  110217. /* By our invariant, we have lW, W and centerW set. Search for
  110218. the next boundary so we can determine nW (the next window size)
  110219. which lets us compute the shape of the current block's window */
  110220. /* we do an envelope search even on a single blocksize; we may still
  110221. be throwing more bits at impulses, and envelope search handles
  110222. marking impulses too. */
  110223. {
  110224. long bp=_ve_envelope_search(v);
  110225. if(bp==-1){
  110226. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  110227. full long block */
  110228. v->nW=0;
  110229. }else{
  110230. if(ci->blocksizes[0]==ci->blocksizes[1])
  110231. v->nW=0;
  110232. else
  110233. v->nW=bp;
  110234. }
  110235. }
  110236. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  110237. {
  110238. /* center of next block + next block maximum right side. */
  110239. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  110240. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  110241. although this check is
  110242. less strict that the
  110243. _ve_envelope_search,
  110244. the search is not run
  110245. if we only use one
  110246. block size */
  110247. }
  110248. /* fill in the block. Note that for a short window, lW and nW are *short*
  110249. regardless of actual settings in the stream */
  110250. _vorbis_block_ripcord(vb);
  110251. vb->lW=v->lW;
  110252. vb->W=v->W;
  110253. vb->nW=v->nW;
  110254. if(v->W){
  110255. if(!v->lW || !v->nW){
  110256. vbi->blocktype=BLOCKTYPE_TRANSITION;
  110257. /*fprintf(stderr,"-");*/
  110258. }else{
  110259. vbi->blocktype=BLOCKTYPE_LONG;
  110260. /*fprintf(stderr,"_");*/
  110261. }
  110262. }else{
  110263. if(_ve_envelope_mark(v)){
  110264. vbi->blocktype=BLOCKTYPE_IMPULSE;
  110265. /*fprintf(stderr,"|");*/
  110266. }else{
  110267. vbi->blocktype=BLOCKTYPE_PADDING;
  110268. /*fprintf(stderr,".");*/
  110269. }
  110270. }
  110271. vb->vd=v;
  110272. vb->sequence=v->sequence++;
  110273. vb->granulepos=v->granulepos;
  110274. vb->pcmend=ci->blocksizes[v->W];
  110275. /* copy the vectors; this uses the local storage in vb */
  110276. /* this tracks 'strongest peak' for later psychoacoustics */
  110277. /* moved to the global psy state; clean this mess up */
  110278. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  110279. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  110280. vbi->ampmax=g->ampmax;
  110281. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  110282. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  110283. for(i=0;i<vi->channels;i++){
  110284. vbi->pcmdelay[i]=
  110285. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110286. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110287. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  110288. /* before we added the delay
  110289. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  110290. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  110291. */
  110292. }
  110293. /* handle eof detection: eof==0 means that we've not yet received EOF
  110294. eof>0 marks the last 'real' sample in pcm[]
  110295. eof<0 'no more to do'; doesn't get here */
  110296. if(v->eofflag){
  110297. if(v->centerW>=v->eofflag){
  110298. v->eofflag=-1;
  110299. vb->eofflag=1;
  110300. return(1);
  110301. }
  110302. }
  110303. /* advance storage vectors and clean up */
  110304. {
  110305. int new_centerNext=ci->blocksizes[1]/2;
  110306. int movementW=centerNext-new_centerNext;
  110307. if(movementW>0){
  110308. _ve_envelope_shift(b->ve,movementW);
  110309. v->pcm_current-=movementW;
  110310. for(i=0;i<vi->channels;i++)
  110311. memmove(v->pcm[i],v->pcm[i]+movementW,
  110312. v->pcm_current*sizeof(*v->pcm[i]));
  110313. v->lW=v->W;
  110314. v->W=v->nW;
  110315. v->centerW=new_centerNext;
  110316. if(v->eofflag){
  110317. v->eofflag-=movementW;
  110318. if(v->eofflag<=0)v->eofflag=-1;
  110319. /* do not add padding to end of stream! */
  110320. if(v->centerW>=v->eofflag){
  110321. v->granulepos+=movementW-(v->centerW-v->eofflag);
  110322. }else{
  110323. v->granulepos+=movementW;
  110324. }
  110325. }else{
  110326. v->granulepos+=movementW;
  110327. }
  110328. }
  110329. }
  110330. /* done */
  110331. return(1);
  110332. }
  110333. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  110334. vorbis_info *vi=v->vi;
  110335. codec_setup_info *ci;
  110336. int hs;
  110337. if(!v->backend_state)return -1;
  110338. if(!vi)return -1;
  110339. ci=(codec_setup_info*) vi->codec_setup;
  110340. if(!ci)return -1;
  110341. hs=ci->halfrate_flag;
  110342. v->centerW=ci->blocksizes[1]>>(hs+1);
  110343. v->pcm_current=v->centerW>>hs;
  110344. v->pcm_returned=-1;
  110345. v->granulepos=-1;
  110346. v->sequence=-1;
  110347. v->eofflag=0;
  110348. ((private_state *)(v->backend_state))->sample_count=-1;
  110349. return(0);
  110350. }
  110351. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110352. if(_vds_shared_init(v,vi,0)) return 1;
  110353. vorbis_synthesis_restart(v);
  110354. return 0;
  110355. }
  110356. /* Unlike in analysis, the window is only partially applied for each
  110357. block. The time domain envelope is not yet handled at the point of
  110358. calling (as it relies on the previous block). */
  110359. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  110360. vorbis_info *vi=v->vi;
  110361. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110362. private_state *b=(private_state*)v->backend_state;
  110363. int hs=ci->halfrate_flag;
  110364. int i,j;
  110365. if(!vb)return(OV_EINVAL);
  110366. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  110367. v->lW=v->W;
  110368. v->W=vb->W;
  110369. v->nW=-1;
  110370. if((v->sequence==-1)||
  110371. (v->sequence+1 != vb->sequence)){
  110372. v->granulepos=-1; /* out of sequence; lose count */
  110373. b->sample_count=-1;
  110374. }
  110375. v->sequence=vb->sequence;
  110376. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  110377. was called on block */
  110378. int n=ci->blocksizes[v->W]>>(hs+1);
  110379. int n0=ci->blocksizes[0]>>(hs+1);
  110380. int n1=ci->blocksizes[1]>>(hs+1);
  110381. int thisCenter;
  110382. int prevCenter;
  110383. v->glue_bits+=vb->glue_bits;
  110384. v->time_bits+=vb->time_bits;
  110385. v->floor_bits+=vb->floor_bits;
  110386. v->res_bits+=vb->res_bits;
  110387. if(v->centerW){
  110388. thisCenter=n1;
  110389. prevCenter=0;
  110390. }else{
  110391. thisCenter=0;
  110392. prevCenter=n1;
  110393. }
  110394. /* v->pcm is now used like a two-stage double buffer. We don't want
  110395. to have to constantly shift *or* adjust memory usage. Don't
  110396. accept a new block until the old is shifted out */
  110397. for(j=0;j<vi->channels;j++){
  110398. /* the overlap/add section */
  110399. if(v->lW){
  110400. if(v->W){
  110401. /* large/large */
  110402. float *w=_vorbis_window_get(b->window[1]-hs);
  110403. float *pcm=v->pcm[j]+prevCenter;
  110404. float *p=vb->pcm[j];
  110405. for(i=0;i<n1;i++)
  110406. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  110407. }else{
  110408. /* large/small */
  110409. float *w=_vorbis_window_get(b->window[0]-hs);
  110410. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  110411. float *p=vb->pcm[j];
  110412. for(i=0;i<n0;i++)
  110413. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110414. }
  110415. }else{
  110416. if(v->W){
  110417. /* small/large */
  110418. float *w=_vorbis_window_get(b->window[0]-hs);
  110419. float *pcm=v->pcm[j]+prevCenter;
  110420. float *p=vb->pcm[j]+n1/2-n0/2;
  110421. for(i=0;i<n0;i++)
  110422. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110423. for(;i<n1/2+n0/2;i++)
  110424. pcm[i]=p[i];
  110425. }else{
  110426. /* small/small */
  110427. float *w=_vorbis_window_get(b->window[0]-hs);
  110428. float *pcm=v->pcm[j]+prevCenter;
  110429. float *p=vb->pcm[j];
  110430. for(i=0;i<n0;i++)
  110431. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110432. }
  110433. }
  110434. /* the copy section */
  110435. {
  110436. float *pcm=v->pcm[j]+thisCenter;
  110437. float *p=vb->pcm[j]+n;
  110438. for(i=0;i<n;i++)
  110439. pcm[i]=p[i];
  110440. }
  110441. }
  110442. if(v->centerW)
  110443. v->centerW=0;
  110444. else
  110445. v->centerW=n1;
  110446. /* deal with initial packet state; we do this using the explicit
  110447. pcm_returned==-1 flag otherwise we're sensitive to first block
  110448. being short or long */
  110449. if(v->pcm_returned==-1){
  110450. v->pcm_returned=thisCenter;
  110451. v->pcm_current=thisCenter;
  110452. }else{
  110453. v->pcm_returned=prevCenter;
  110454. v->pcm_current=prevCenter+
  110455. ((ci->blocksizes[v->lW]/4+
  110456. ci->blocksizes[v->W]/4)>>hs);
  110457. }
  110458. }
  110459. /* track the frame number... This is for convenience, but also
  110460. making sure our last packet doesn't end with added padding. If
  110461. the last packet is partial, the number of samples we'll have to
  110462. return will be past the vb->granulepos.
  110463. This is not foolproof! It will be confused if we begin
  110464. decoding at the last page after a seek or hole. In that case,
  110465. we don't have a starting point to judge where the last frame
  110466. is. For this reason, vorbisfile will always try to make sure
  110467. it reads the last two marked pages in proper sequence */
  110468. if(b->sample_count==-1){
  110469. b->sample_count=0;
  110470. }else{
  110471. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  110472. }
  110473. if(v->granulepos==-1){
  110474. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  110475. v->granulepos=vb->granulepos;
  110476. /* is this a short page? */
  110477. if(b->sample_count>v->granulepos){
  110478. /* corner case; if this is both the first and last audio page,
  110479. then spec says the end is cut, not beginning */
  110480. if(vb->eofflag){
  110481. /* trim the end */
  110482. /* no preceeding granulepos; assume we started at zero (we'd
  110483. have to in a short single-page stream) */
  110484. /* granulepos could be -1 due to a seek, but that would result
  110485. in a long count, not short count */
  110486. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  110487. }else{
  110488. /* trim the beginning */
  110489. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  110490. if(v->pcm_returned>v->pcm_current)
  110491. v->pcm_returned=v->pcm_current;
  110492. }
  110493. }
  110494. }
  110495. }else{
  110496. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  110497. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  110498. if(v->granulepos>vb->granulepos){
  110499. long extra=v->granulepos-vb->granulepos;
  110500. if(extra)
  110501. if(vb->eofflag){
  110502. /* partial last frame. Strip the extra samples off */
  110503. v->pcm_current-=extra>>hs;
  110504. } /* else {Shouldn't happen *unless* the bitstream is out of
  110505. spec. Either way, believe the bitstream } */
  110506. } /* else {Shouldn't happen *unless* the bitstream is out of
  110507. spec. Either way, believe the bitstream } */
  110508. v->granulepos=vb->granulepos;
  110509. }
  110510. }
  110511. /* Update, cleanup */
  110512. if(vb->eofflag)v->eofflag=1;
  110513. return(0);
  110514. }
  110515. /* pcm==NULL indicates we just want the pending samples, no more */
  110516. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  110517. vorbis_info *vi=v->vi;
  110518. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  110519. if(pcm){
  110520. int i;
  110521. for(i=0;i<vi->channels;i++)
  110522. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  110523. *pcm=v->pcmret;
  110524. }
  110525. return(v->pcm_current-v->pcm_returned);
  110526. }
  110527. return(0);
  110528. }
  110529. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  110530. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  110531. v->pcm_returned+=n;
  110532. return(0);
  110533. }
  110534. /* intended for use with a specific vorbisfile feature; we want access
  110535. to the [usually synthetic/postextrapolated] buffer and lapping at
  110536. the end of a decode cycle, specifically, a half-short-block worth.
  110537. This funtion works like pcmout above, except it will also expose
  110538. this implicit buffer data not normally decoded. */
  110539. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  110540. vorbis_info *vi=v->vi;
  110541. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110542. int hs=ci->halfrate_flag;
  110543. int n=ci->blocksizes[v->W]>>(hs+1);
  110544. int n0=ci->blocksizes[0]>>(hs+1);
  110545. int n1=ci->blocksizes[1]>>(hs+1);
  110546. int i,j;
  110547. if(v->pcm_returned<0)return 0;
  110548. /* our returned data ends at pcm_returned; because the synthesis pcm
  110549. buffer is a two-fragment ring, that means our data block may be
  110550. fragmented by buffering, wrapping or a short block not filling
  110551. out a buffer. To simplify things, we unfragment if it's at all
  110552. possibly needed. Otherwise, we'd need to call lapout more than
  110553. once as well as hold additional dsp state. Opt for
  110554. simplicity. */
  110555. /* centerW was advanced by blockin; it would be the center of the
  110556. *next* block */
  110557. if(v->centerW==n1){
  110558. /* the data buffer wraps; swap the halves */
  110559. /* slow, sure, small */
  110560. for(j=0;j<vi->channels;j++){
  110561. float *p=v->pcm[j];
  110562. for(i=0;i<n1;i++){
  110563. float temp=p[i];
  110564. p[i]=p[i+n1];
  110565. p[i+n1]=temp;
  110566. }
  110567. }
  110568. v->pcm_current-=n1;
  110569. v->pcm_returned-=n1;
  110570. v->centerW=0;
  110571. }
  110572. /* solidify buffer into contiguous space */
  110573. if((v->lW^v->W)==1){
  110574. /* long/short or short/long */
  110575. for(j=0;j<vi->channels;j++){
  110576. float *s=v->pcm[j];
  110577. float *d=v->pcm[j]+(n1-n0)/2;
  110578. for(i=(n1+n0)/2-1;i>=0;--i)
  110579. d[i]=s[i];
  110580. }
  110581. v->pcm_returned+=(n1-n0)/2;
  110582. v->pcm_current+=(n1-n0)/2;
  110583. }else{
  110584. if(v->lW==0){
  110585. /* short/short */
  110586. for(j=0;j<vi->channels;j++){
  110587. float *s=v->pcm[j];
  110588. float *d=v->pcm[j]+n1-n0;
  110589. for(i=n0-1;i>=0;--i)
  110590. d[i]=s[i];
  110591. }
  110592. v->pcm_returned+=n1-n0;
  110593. v->pcm_current+=n1-n0;
  110594. }
  110595. }
  110596. if(pcm){
  110597. int i;
  110598. for(i=0;i<vi->channels;i++)
  110599. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  110600. *pcm=v->pcmret;
  110601. }
  110602. return(n1+n-v->pcm_returned);
  110603. }
  110604. float *vorbis_window(vorbis_dsp_state *v,int W){
  110605. vorbis_info *vi=v->vi;
  110606. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  110607. int hs=ci->halfrate_flag;
  110608. private_state *b=(private_state*)v->backend_state;
  110609. if(b->window[W]-1<0)return NULL;
  110610. return _vorbis_window_get(b->window[W]-hs);
  110611. }
  110612. #endif
  110613. /*** End of inlined file: block.c ***/
  110614. /*** Start of inlined file: codebook.c ***/
  110615. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110616. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110617. // tasks..
  110618. #if JUCE_MSVC
  110619. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110620. #endif
  110621. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110622. #if JUCE_USE_OGGVORBIS
  110623. #include <stdlib.h>
  110624. #include <string.h>
  110625. #include <math.h>
  110626. /* packs the given codebook into the bitstream **************************/
  110627. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  110628. long i,j;
  110629. int ordered=0;
  110630. /* first the basic parameters */
  110631. oggpack_write(opb,0x564342,24);
  110632. oggpack_write(opb,c->dim,16);
  110633. oggpack_write(opb,c->entries,24);
  110634. /* pack the codewords. There are two packings; length ordered and
  110635. length random. Decide between the two now. */
  110636. for(i=1;i<c->entries;i++)
  110637. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  110638. if(i==c->entries)ordered=1;
  110639. if(ordered){
  110640. /* length ordered. We only need to say how many codewords of
  110641. each length. The actual codewords are generated
  110642. deterministically */
  110643. long count=0;
  110644. oggpack_write(opb,1,1); /* ordered */
  110645. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  110646. for(i=1;i<c->entries;i++){
  110647. long thisx=c->lengthlist[i];
  110648. long last=c->lengthlist[i-1];
  110649. if(thisx>last){
  110650. for(j=last;j<thisx;j++){
  110651. oggpack_write(opb,i-count,_ilog(c->entries-count));
  110652. count=i;
  110653. }
  110654. }
  110655. }
  110656. oggpack_write(opb,i-count,_ilog(c->entries-count));
  110657. }else{
  110658. /* length random. Again, we don't code the codeword itself, just
  110659. the length. This time, though, we have to encode each length */
  110660. oggpack_write(opb,0,1); /* unordered */
  110661. /* algortihmic mapping has use for 'unused entries', which we tag
  110662. here. The algorithmic mapping happens as usual, but the unused
  110663. entry has no codeword. */
  110664. for(i=0;i<c->entries;i++)
  110665. if(c->lengthlist[i]==0)break;
  110666. if(i==c->entries){
  110667. oggpack_write(opb,0,1); /* no unused entries */
  110668. for(i=0;i<c->entries;i++)
  110669. oggpack_write(opb,c->lengthlist[i]-1,5);
  110670. }else{
  110671. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  110672. for(i=0;i<c->entries;i++){
  110673. if(c->lengthlist[i]==0){
  110674. oggpack_write(opb,0,1);
  110675. }else{
  110676. oggpack_write(opb,1,1);
  110677. oggpack_write(opb,c->lengthlist[i]-1,5);
  110678. }
  110679. }
  110680. }
  110681. }
  110682. /* is the entry number the desired return value, or do we have a
  110683. mapping? If we have a mapping, what type? */
  110684. oggpack_write(opb,c->maptype,4);
  110685. switch(c->maptype){
  110686. case 0:
  110687. /* no mapping */
  110688. break;
  110689. case 1:case 2:
  110690. /* implicitly populated value mapping */
  110691. /* explicitly populated value mapping */
  110692. if(!c->quantlist){
  110693. /* no quantlist? error */
  110694. return(-1);
  110695. }
  110696. /* values that define the dequantization */
  110697. oggpack_write(opb,c->q_min,32);
  110698. oggpack_write(opb,c->q_delta,32);
  110699. oggpack_write(opb,c->q_quant-1,4);
  110700. oggpack_write(opb,c->q_sequencep,1);
  110701. {
  110702. int quantvals;
  110703. switch(c->maptype){
  110704. case 1:
  110705. /* a single column of (c->entries/c->dim) quantized values for
  110706. building a full value list algorithmically (square lattice) */
  110707. quantvals=_book_maptype1_quantvals(c);
  110708. break;
  110709. case 2:
  110710. /* every value (c->entries*c->dim total) specified explicitly */
  110711. quantvals=c->entries*c->dim;
  110712. break;
  110713. default: /* NOT_REACHABLE */
  110714. quantvals=-1;
  110715. }
  110716. /* quantized values */
  110717. for(i=0;i<quantvals;i++)
  110718. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  110719. }
  110720. break;
  110721. default:
  110722. /* error case; we don't have any other map types now */
  110723. return(-1);
  110724. }
  110725. return(0);
  110726. }
  110727. /* unpacks a codebook from the packet buffer into the codebook struct,
  110728. readies the codebook auxiliary structures for decode *************/
  110729. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  110730. long i,j;
  110731. memset(s,0,sizeof(*s));
  110732. s->allocedp=1;
  110733. /* make sure alignment is correct */
  110734. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  110735. /* first the basic parameters */
  110736. s->dim=oggpack_read(opb,16);
  110737. s->entries=oggpack_read(opb,24);
  110738. if(s->entries==-1)goto _eofout;
  110739. /* codeword ordering.... length ordered or unordered? */
  110740. switch((int)oggpack_read(opb,1)){
  110741. case 0:
  110742. /* unordered */
  110743. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  110744. /* allocated but unused entries? */
  110745. if(oggpack_read(opb,1)){
  110746. /* yes, unused entries */
  110747. for(i=0;i<s->entries;i++){
  110748. if(oggpack_read(opb,1)){
  110749. long num=oggpack_read(opb,5);
  110750. if(num==-1)goto _eofout;
  110751. s->lengthlist[i]=num+1;
  110752. }else
  110753. s->lengthlist[i]=0;
  110754. }
  110755. }else{
  110756. /* all entries used; no tagging */
  110757. for(i=0;i<s->entries;i++){
  110758. long num=oggpack_read(opb,5);
  110759. if(num==-1)goto _eofout;
  110760. s->lengthlist[i]=num+1;
  110761. }
  110762. }
  110763. break;
  110764. case 1:
  110765. /* ordered */
  110766. {
  110767. long length=oggpack_read(opb,5)+1;
  110768. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  110769. for(i=0;i<s->entries;){
  110770. long num=oggpack_read(opb,_ilog(s->entries-i));
  110771. if(num==-1)goto _eofout;
  110772. for(j=0;j<num && i<s->entries;j++,i++)
  110773. s->lengthlist[i]=length;
  110774. length++;
  110775. }
  110776. }
  110777. break;
  110778. default:
  110779. /* EOF */
  110780. return(-1);
  110781. }
  110782. /* Do we have a mapping to unpack? */
  110783. switch((s->maptype=oggpack_read(opb,4))){
  110784. case 0:
  110785. /* no mapping */
  110786. break;
  110787. case 1: case 2:
  110788. /* implicitly populated value mapping */
  110789. /* explicitly populated value mapping */
  110790. s->q_min=oggpack_read(opb,32);
  110791. s->q_delta=oggpack_read(opb,32);
  110792. s->q_quant=oggpack_read(opb,4)+1;
  110793. s->q_sequencep=oggpack_read(opb,1);
  110794. {
  110795. int quantvals=0;
  110796. switch(s->maptype){
  110797. case 1:
  110798. quantvals=_book_maptype1_quantvals(s);
  110799. break;
  110800. case 2:
  110801. quantvals=s->entries*s->dim;
  110802. break;
  110803. }
  110804. /* quantized values */
  110805. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  110806. for(i=0;i<quantvals;i++)
  110807. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  110808. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  110809. }
  110810. break;
  110811. default:
  110812. goto _errout;
  110813. }
  110814. /* all set */
  110815. return(0);
  110816. _errout:
  110817. _eofout:
  110818. vorbis_staticbook_clear(s);
  110819. return(-1);
  110820. }
  110821. /* returns the number of bits ************************************************/
  110822. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  110823. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  110824. return(book->c->lengthlist[a]);
  110825. }
  110826. /* One the encode side, our vector writers are each designed for a
  110827. specific purpose, and the encoder is not flexible without modification:
  110828. The LSP vector coder uses a single stage nearest-match with no
  110829. interleave, so no step and no error return. This is specced by floor0
  110830. and doesn't change.
  110831. Residue0 encoding interleaves, uses multiple stages, and each stage
  110832. peels of a specific amount of resolution from a lattice (thus we want
  110833. to match by threshold, not nearest match). Residue doesn't *have* to
  110834. be encoded that way, but to change it, one will need to add more
  110835. infrastructure on the encode side (decode side is specced and simpler) */
  110836. /* floor0 LSP (single stage, non interleaved, nearest match) */
  110837. /* returns entry number and *modifies a* to the quantization value *****/
  110838. int vorbis_book_errorv(codebook *book,float *a){
  110839. int dim=book->dim,k;
  110840. int best=_best(book,a,1);
  110841. for(k=0;k<dim;k++)
  110842. a[k]=(book->valuelist+best*dim)[k];
  110843. return(best);
  110844. }
  110845. /* returns the number of bits and *modifies a* to the quantization value *****/
  110846. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  110847. int k,dim=book->dim;
  110848. for(k=0;k<dim;k++)
  110849. a[k]=(book->valuelist+best*dim)[k];
  110850. return(vorbis_book_encode(book,best,b));
  110851. }
  110852. /* the 'eliminate the decode tree' optimization actually requires the
  110853. codewords to be MSb first, not LSb. This is an annoying inelegancy
  110854. (and one of the first places where carefully thought out design
  110855. turned out to be wrong; Vorbis II and future Ogg codecs should go
  110856. to an MSb bitpacker), but not actually the huge hit it appears to
  110857. be. The first-stage decode table catches most words so that
  110858. bitreverse is not in the main execution path. */
  110859. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  110860. int read=book->dec_maxlength;
  110861. long lo,hi;
  110862. long lok = oggpack_look(b,book->dec_firsttablen);
  110863. if (lok >= 0) {
  110864. long entry = book->dec_firsttable[lok];
  110865. if(entry&0x80000000UL){
  110866. lo=(entry>>15)&0x7fff;
  110867. hi=book->used_entries-(entry&0x7fff);
  110868. }else{
  110869. oggpack_adv(b, book->dec_codelengths[entry-1]);
  110870. return(entry-1);
  110871. }
  110872. }else{
  110873. lo=0;
  110874. hi=book->used_entries;
  110875. }
  110876. lok = oggpack_look(b, read);
  110877. while(lok<0 && read>1)
  110878. lok = oggpack_look(b, --read);
  110879. if(lok<0)return -1;
  110880. /* bisect search for the codeword in the ordered list */
  110881. {
  110882. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  110883. while(hi-lo>1){
  110884. long p=(hi-lo)>>1;
  110885. long test=book->codelist[lo+p]>testword;
  110886. lo+=p&(test-1);
  110887. hi-=p&(-test);
  110888. }
  110889. if(book->dec_codelengths[lo]<=read){
  110890. oggpack_adv(b, book->dec_codelengths[lo]);
  110891. return(lo);
  110892. }
  110893. }
  110894. oggpack_adv(b, read);
  110895. return(-1);
  110896. }
  110897. /* Decode side is specced and easier, because we don't need to find
  110898. matches using different criteria; we simply read and map. There are
  110899. two things we need to do 'depending':
  110900. We may need to support interleave. We don't really, but it's
  110901. convenient to do it here rather than rebuild the vector later.
  110902. Cascades may be additive or multiplicitive; this is not inherent in
  110903. the codebook, but set in the code using the codebook. Like
  110904. interleaving, it's easiest to do it here.
  110905. addmul==0 -> declarative (set the value)
  110906. addmul==1 -> additive
  110907. addmul==2 -> multiplicitive */
  110908. /* returns the [original, not compacted] entry number or -1 on eof *********/
  110909. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  110910. long packed_entry=decode_packed_entry_number(book,b);
  110911. if(packed_entry>=0)
  110912. return(book->dec_index[packed_entry]);
  110913. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  110914. return(packed_entry);
  110915. }
  110916. /* returns 0 on OK or -1 on eof *************************************/
  110917. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  110918. int step=n/book->dim;
  110919. long *entry = (long*)alloca(sizeof(*entry)*step);
  110920. float **t = (float**)alloca(sizeof(*t)*step);
  110921. int i,j,o;
  110922. for (i = 0; i < step; i++) {
  110923. entry[i]=decode_packed_entry_number(book,b);
  110924. if(entry[i]==-1)return(-1);
  110925. t[i] = book->valuelist+entry[i]*book->dim;
  110926. }
  110927. for(i=0,o=0;i<book->dim;i++,o+=step)
  110928. for (j=0;j<step;j++)
  110929. a[o+j]+=t[j][i];
  110930. return(0);
  110931. }
  110932. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  110933. int i,j,entry;
  110934. float *t;
  110935. if(book->dim>8){
  110936. for(i=0;i<n;){
  110937. entry = decode_packed_entry_number(book,b);
  110938. if(entry==-1)return(-1);
  110939. t = book->valuelist+entry*book->dim;
  110940. for (j=0;j<book->dim;)
  110941. a[i++]+=t[j++];
  110942. }
  110943. }else{
  110944. for(i=0;i<n;){
  110945. entry = decode_packed_entry_number(book,b);
  110946. if(entry==-1)return(-1);
  110947. t = book->valuelist+entry*book->dim;
  110948. j=0;
  110949. switch((int)book->dim){
  110950. case 8:
  110951. a[i++]+=t[j++];
  110952. case 7:
  110953. a[i++]+=t[j++];
  110954. case 6:
  110955. a[i++]+=t[j++];
  110956. case 5:
  110957. a[i++]+=t[j++];
  110958. case 4:
  110959. a[i++]+=t[j++];
  110960. case 3:
  110961. a[i++]+=t[j++];
  110962. case 2:
  110963. a[i++]+=t[j++];
  110964. case 1:
  110965. a[i++]+=t[j++];
  110966. case 0:
  110967. break;
  110968. }
  110969. }
  110970. }
  110971. return(0);
  110972. }
  110973. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  110974. int i,j,entry;
  110975. float *t;
  110976. for(i=0;i<n;){
  110977. entry = decode_packed_entry_number(book,b);
  110978. if(entry==-1)return(-1);
  110979. t = book->valuelist+entry*book->dim;
  110980. for (j=0;j<book->dim;)
  110981. a[i++]=t[j++];
  110982. }
  110983. return(0);
  110984. }
  110985. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  110986. oggpack_buffer *b,int n){
  110987. long i,j,entry;
  110988. int chptr=0;
  110989. for(i=offset/ch;i<(offset+n)/ch;){
  110990. entry = decode_packed_entry_number(book,b);
  110991. if(entry==-1)return(-1);
  110992. {
  110993. const float *t = book->valuelist+entry*book->dim;
  110994. for (j=0;j<book->dim;j++){
  110995. a[chptr++][i]+=t[j];
  110996. if(chptr==ch){
  110997. chptr=0;
  110998. i++;
  110999. }
  111000. }
  111001. }
  111002. }
  111003. return(0);
  111004. }
  111005. #ifdef _V_SELFTEST
  111006. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111007. number of vectors through (keeping track of the quantized values),
  111008. and decode using the unpacked book. quantized version of in should
  111009. exactly equal out */
  111010. #include <stdio.h>
  111011. #include "vorbis/book/lsp20_0.vqh"
  111012. #include "vorbis/book/res0a_13.vqh"
  111013. #define TESTSIZE 40
  111014. float test1[TESTSIZE]={
  111015. 0.105939f,
  111016. 0.215373f,
  111017. 0.429117f,
  111018. 0.587974f,
  111019. 0.181173f,
  111020. 0.296583f,
  111021. 0.515707f,
  111022. 0.715261f,
  111023. 0.162327f,
  111024. 0.263834f,
  111025. 0.342876f,
  111026. 0.406025f,
  111027. 0.103571f,
  111028. 0.223561f,
  111029. 0.368513f,
  111030. 0.540313f,
  111031. 0.136672f,
  111032. 0.395882f,
  111033. 0.587183f,
  111034. 0.652476f,
  111035. 0.114338f,
  111036. 0.417300f,
  111037. 0.525486f,
  111038. 0.698679f,
  111039. 0.147492f,
  111040. 0.324481f,
  111041. 0.643089f,
  111042. 0.757582f,
  111043. 0.139556f,
  111044. 0.215795f,
  111045. 0.324559f,
  111046. 0.399387f,
  111047. 0.120236f,
  111048. 0.267420f,
  111049. 0.446940f,
  111050. 0.608760f,
  111051. 0.115587f,
  111052. 0.287234f,
  111053. 0.571081f,
  111054. 0.708603f,
  111055. };
  111056. float test3[TESTSIZE]={
  111057. 0,1,-2,3,4,-5,6,7,8,9,
  111058. 8,-2,7,-1,4,6,8,3,1,-9,
  111059. 10,11,12,13,14,15,26,17,18,19,
  111060. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111061. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111062. &_vq_book_res0a_13,NULL};
  111063. float *testvec[]={test1,test3};
  111064. int main(){
  111065. oggpack_buffer write;
  111066. oggpack_buffer read;
  111067. long ptr=0,i;
  111068. oggpack_writeinit(&write);
  111069. fprintf(stderr,"Testing codebook abstraction...:\n");
  111070. while(testlist[ptr]){
  111071. codebook c;
  111072. static_codebook s;
  111073. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111074. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111075. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111076. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111077. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111078. /* pack the codebook, write the testvector */
  111079. oggpack_reset(&write);
  111080. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111081. we can write */
  111082. vorbis_staticbook_pack(testlist[ptr],&write);
  111083. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111084. for(i=0;i<TESTSIZE;i+=c.dim){
  111085. int best=_best(&c,qv+i,1);
  111086. vorbis_book_encodev(&c,best,qv+i,&write);
  111087. }
  111088. vorbis_book_clear(&c);
  111089. fprintf(stderr,"OK.\n");
  111090. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111091. /* transfer the write data to a read buffer and unpack/read */
  111092. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111093. if(vorbis_staticbook_unpack(&read,&s)){
  111094. fprintf(stderr,"Error unpacking codebook.\n");
  111095. exit(1);
  111096. }
  111097. if(vorbis_book_init_decode(&c,&s)){
  111098. fprintf(stderr,"Error initializing codebook.\n");
  111099. exit(1);
  111100. }
  111101. for(i=0;i<TESTSIZE;i+=c.dim)
  111102. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111103. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111104. exit(1);
  111105. }
  111106. for(i=0;i<TESTSIZE;i++)
  111107. if(fabs(qv[i]-iv[i])>.000001){
  111108. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111109. iv[i],qv[i],i);
  111110. exit(1);
  111111. }
  111112. fprintf(stderr,"OK\n");
  111113. ptr++;
  111114. }
  111115. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111116. exit(0);
  111117. }
  111118. #endif
  111119. #endif
  111120. /*** End of inlined file: codebook.c ***/
  111121. /*** Start of inlined file: envelope.c ***/
  111122. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111123. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111124. // tasks..
  111125. #if JUCE_MSVC
  111126. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111127. #endif
  111128. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111129. #if JUCE_USE_OGGVORBIS
  111130. #include <stdlib.h>
  111131. #include <string.h>
  111132. #include <stdio.h>
  111133. #include <math.h>
  111134. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  111135. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111136. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111137. int ch=vi->channels;
  111138. int i,j;
  111139. int n=e->winlength=128;
  111140. e->searchstep=64; /* not random */
  111141. e->minenergy=gi->preecho_minenergy;
  111142. e->ch=ch;
  111143. e->storage=128;
  111144. e->cursor=ci->blocksizes[1]/2;
  111145. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  111146. mdct_init(&e->mdct,n);
  111147. for(i=0;i<n;i++){
  111148. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  111149. e->mdct_win[i]*=e->mdct_win[i];
  111150. }
  111151. /* magic follows */
  111152. e->band[0].begin=2; e->band[0].end=4;
  111153. e->band[1].begin=4; e->band[1].end=5;
  111154. e->band[2].begin=6; e->band[2].end=6;
  111155. e->band[3].begin=9; e->band[3].end=8;
  111156. e->band[4].begin=13; e->band[4].end=8;
  111157. e->band[5].begin=17; e->band[5].end=8;
  111158. e->band[6].begin=22; e->band[6].end=8;
  111159. for(j=0;j<VE_BANDS;j++){
  111160. n=e->band[j].end;
  111161. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  111162. for(i=0;i<n;i++){
  111163. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  111164. e->band[j].total+=e->band[j].window[i];
  111165. }
  111166. e->band[j].total=1./e->band[j].total;
  111167. }
  111168. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  111169. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  111170. }
  111171. void _ve_envelope_clear(envelope_lookup *e){
  111172. int i;
  111173. mdct_clear(&e->mdct);
  111174. for(i=0;i<VE_BANDS;i++)
  111175. _ogg_free(e->band[i].window);
  111176. _ogg_free(e->mdct_win);
  111177. _ogg_free(e->filter);
  111178. _ogg_free(e->mark);
  111179. memset(e,0,sizeof(*e));
  111180. }
  111181. /* fairly straight threshhold-by-band based until we find something
  111182. that works better and isn't patented. */
  111183. static int _ve_amp(envelope_lookup *ve,
  111184. vorbis_info_psy_global *gi,
  111185. float *data,
  111186. envelope_band *bands,
  111187. envelope_filter_state *filters,
  111188. long pos){
  111189. long n=ve->winlength;
  111190. int ret=0;
  111191. long i,j;
  111192. float decay;
  111193. /* we want to have a 'minimum bar' for energy, else we're just
  111194. basing blocks on quantization noise that outweighs the signal
  111195. itself (for low power signals) */
  111196. float minV=ve->minenergy;
  111197. float *vec=(float*) alloca(n*sizeof(*vec));
  111198. /* stretch is used to gradually lengthen the number of windows
  111199. considered prevoius-to-potential-trigger */
  111200. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  111201. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  111202. if(penalty<0.f)penalty=0.f;
  111203. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  111204. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  111205. totalshift+pos*ve->searchstep);*/
  111206. /* window and transform */
  111207. for(i=0;i<n;i++)
  111208. vec[i]=data[i]*ve->mdct_win[i];
  111209. mdct_forward(&ve->mdct,vec,vec);
  111210. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  111211. /* near-DC spreading function; this has nothing to do with
  111212. psychoacoustics, just sidelobe leakage and window size */
  111213. {
  111214. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  111215. int ptr=filters->nearptr;
  111216. /* the accumulation is regularly refreshed from scratch to avoid
  111217. floating point creep */
  111218. if(ptr==0){
  111219. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  111220. filters->nearDC_partialacc=temp;
  111221. }else{
  111222. decay=filters->nearDC_acc+=temp;
  111223. filters->nearDC_partialacc+=temp;
  111224. }
  111225. filters->nearDC_acc-=filters->nearDC[ptr];
  111226. filters->nearDC[ptr]=temp;
  111227. decay*=(1./(VE_NEARDC+1));
  111228. filters->nearptr++;
  111229. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  111230. decay=todB(&decay)*.5-15.f;
  111231. }
  111232. /* perform spreading and limiting, also smooth the spectrum. yes,
  111233. the MDCT results in all real coefficients, but it still *behaves*
  111234. like real/imaginary pairs */
  111235. for(i=0;i<n/2;i+=2){
  111236. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  111237. val=todB(&val)*.5f;
  111238. if(val<decay)val=decay;
  111239. if(val<minV)val=minV;
  111240. vec[i>>1]=val;
  111241. decay-=8.;
  111242. }
  111243. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  111244. /* perform preecho/postecho triggering by band */
  111245. for(j=0;j<VE_BANDS;j++){
  111246. float acc=0.;
  111247. float valmax,valmin;
  111248. /* accumulate amplitude */
  111249. for(i=0;i<bands[j].end;i++)
  111250. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  111251. acc*=bands[j].total;
  111252. /* convert amplitude to delta */
  111253. {
  111254. int p,thisx=filters[j].ampptr;
  111255. float postmax,postmin,premax=-99999.f,premin=99999.f;
  111256. p=thisx;
  111257. p--;
  111258. if(p<0)p+=VE_AMP;
  111259. postmax=max(acc,filters[j].ampbuf[p]);
  111260. postmin=min(acc,filters[j].ampbuf[p]);
  111261. for(i=0;i<stretch;i++){
  111262. p--;
  111263. if(p<0)p+=VE_AMP;
  111264. premax=max(premax,filters[j].ampbuf[p]);
  111265. premin=min(premin,filters[j].ampbuf[p]);
  111266. }
  111267. valmin=postmin-premin;
  111268. valmax=postmax-premax;
  111269. /*filters[j].markers[pos]=valmax;*/
  111270. filters[j].ampbuf[thisx]=acc;
  111271. filters[j].ampptr++;
  111272. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  111273. }
  111274. /* look at min/max, decide trigger */
  111275. if(valmax>gi->preecho_thresh[j]+penalty){
  111276. ret|=1;
  111277. ret|=4;
  111278. }
  111279. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  111280. }
  111281. return(ret);
  111282. }
  111283. #if 0
  111284. static int seq=0;
  111285. static ogg_int64_t totalshift=-1024;
  111286. #endif
  111287. long _ve_envelope_search(vorbis_dsp_state *v){
  111288. vorbis_info *vi=v->vi;
  111289. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111290. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111291. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111292. long i,j;
  111293. int first=ve->current/ve->searchstep;
  111294. int last=v->pcm_current/ve->searchstep-VE_WIN;
  111295. if(first<0)first=0;
  111296. /* make sure we have enough storage to match the PCM */
  111297. if(last+VE_WIN+VE_POST>ve->storage){
  111298. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  111299. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  111300. }
  111301. for(j=first;j<last;j++){
  111302. int ret=0;
  111303. ve->stretch++;
  111304. if(ve->stretch>VE_MAXSTRETCH*2)
  111305. ve->stretch=VE_MAXSTRETCH*2;
  111306. for(i=0;i<ve->ch;i++){
  111307. float *pcm=v->pcm[i]+ve->searchstep*(j);
  111308. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  111309. }
  111310. ve->mark[j+VE_POST]=0;
  111311. if(ret&1){
  111312. ve->mark[j]=1;
  111313. ve->mark[j+1]=1;
  111314. }
  111315. if(ret&2){
  111316. ve->mark[j]=1;
  111317. if(j>0)ve->mark[j-1]=1;
  111318. }
  111319. if(ret&4)ve->stretch=-1;
  111320. }
  111321. ve->current=last*ve->searchstep;
  111322. {
  111323. long centerW=v->centerW;
  111324. long testW=
  111325. centerW+
  111326. ci->blocksizes[v->W]/4+
  111327. ci->blocksizes[1]/2+
  111328. ci->blocksizes[0]/4;
  111329. j=ve->cursor;
  111330. while(j<ve->current-(ve->searchstep)){/* account for postecho
  111331. working back one window */
  111332. if(j>=testW)return(1);
  111333. ve->cursor=j;
  111334. if(ve->mark[j/ve->searchstep]){
  111335. if(j>centerW){
  111336. #if 0
  111337. if(j>ve->curmark){
  111338. float *marker=alloca(v->pcm_current*sizeof(*marker));
  111339. int l,m;
  111340. memset(marker,0,sizeof(*marker)*v->pcm_current);
  111341. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  111342. seq,
  111343. (totalshift+ve->cursor)/44100.,
  111344. (totalshift+j)/44100.);
  111345. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  111346. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  111347. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  111348. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  111349. for(m=0;m<VE_BANDS;m++){
  111350. char buf[80];
  111351. sprintf(buf,"delL%d",m);
  111352. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  111353. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111354. }
  111355. for(m=0;m<VE_BANDS;m++){
  111356. char buf[80];
  111357. sprintf(buf,"delR%d",m);
  111358. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  111359. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111360. }
  111361. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  111362. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  111363. seq++;
  111364. }
  111365. #endif
  111366. ve->curmark=j;
  111367. if(j>=testW)return(1);
  111368. return(0);
  111369. }
  111370. }
  111371. j+=ve->searchstep;
  111372. }
  111373. }
  111374. return(-1);
  111375. }
  111376. int _ve_envelope_mark(vorbis_dsp_state *v){
  111377. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111378. vorbis_info *vi=v->vi;
  111379. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111380. long centerW=v->centerW;
  111381. long beginW=centerW-ci->blocksizes[v->W]/4;
  111382. long endW=centerW+ci->blocksizes[v->W]/4;
  111383. if(v->W){
  111384. beginW-=ci->blocksizes[v->lW]/4;
  111385. endW+=ci->blocksizes[v->nW]/4;
  111386. }else{
  111387. beginW-=ci->blocksizes[0]/4;
  111388. endW+=ci->blocksizes[0]/4;
  111389. }
  111390. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  111391. {
  111392. long first=beginW/ve->searchstep;
  111393. long last=endW/ve->searchstep;
  111394. long i;
  111395. for(i=first;i<last;i++)
  111396. if(ve->mark[i])return(1);
  111397. }
  111398. return(0);
  111399. }
  111400. void _ve_envelope_shift(envelope_lookup *e,long shift){
  111401. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  111402. ahead of ve->current */
  111403. int smallshift=shift/e->searchstep;
  111404. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  111405. #if 0
  111406. for(i=0;i<VE_BANDS*e->ch;i++)
  111407. memmove(e->filter[i].markers,
  111408. e->filter[i].markers+smallshift,
  111409. (1024-smallshift)*sizeof(*(*e->filter).markers));
  111410. totalshift+=shift;
  111411. #endif
  111412. e->current-=shift;
  111413. if(e->curmark>=0)
  111414. e->curmark-=shift;
  111415. e->cursor-=shift;
  111416. }
  111417. #endif
  111418. /*** End of inlined file: envelope.c ***/
  111419. /*** Start of inlined file: floor0.c ***/
  111420. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111421. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111422. // tasks..
  111423. #if JUCE_MSVC
  111424. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111425. #endif
  111426. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111427. #if JUCE_USE_OGGVORBIS
  111428. #include <stdlib.h>
  111429. #include <string.h>
  111430. #include <math.h>
  111431. /*** Start of inlined file: lsp.h ***/
  111432. #ifndef _V_LSP_H_
  111433. #define _V_LSP_H_
  111434. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  111435. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  111436. float *lsp,int m,
  111437. float amp,float ampoffset);
  111438. #endif
  111439. /*** End of inlined file: lsp.h ***/
  111440. #include <stdio.h>
  111441. typedef struct {
  111442. int ln;
  111443. int m;
  111444. int **linearmap;
  111445. int n[2];
  111446. vorbis_info_floor0 *vi;
  111447. long bits;
  111448. long frames;
  111449. } vorbis_look_floor0;
  111450. /***********************************************/
  111451. static void floor0_free_info(vorbis_info_floor *i){
  111452. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  111453. if(info){
  111454. memset(info,0,sizeof(*info));
  111455. _ogg_free(info);
  111456. }
  111457. }
  111458. static void floor0_free_look(vorbis_look_floor *i){
  111459. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111460. if(look){
  111461. if(look->linearmap){
  111462. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  111463. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  111464. _ogg_free(look->linearmap);
  111465. }
  111466. memset(look,0,sizeof(*look));
  111467. _ogg_free(look);
  111468. }
  111469. }
  111470. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  111471. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111472. int j;
  111473. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  111474. info->order=oggpack_read(opb,8);
  111475. info->rate=oggpack_read(opb,16);
  111476. info->barkmap=oggpack_read(opb,16);
  111477. info->ampbits=oggpack_read(opb,6);
  111478. info->ampdB=oggpack_read(opb,8);
  111479. info->numbooks=oggpack_read(opb,4)+1;
  111480. if(info->order<1)goto err_out;
  111481. if(info->rate<1)goto err_out;
  111482. if(info->barkmap<1)goto err_out;
  111483. if(info->numbooks<1)goto err_out;
  111484. for(j=0;j<info->numbooks;j++){
  111485. info->books[j]=oggpack_read(opb,8);
  111486. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  111487. }
  111488. return(info);
  111489. err_out:
  111490. floor0_free_info(info);
  111491. return(NULL);
  111492. }
  111493. /* initialize Bark scale and normalization lookups. We could do this
  111494. with static tables, but Vorbis allows a number of possible
  111495. combinations, so it's best to do it computationally.
  111496. The below is authoritative in terms of defining scale mapping.
  111497. Note that the scale depends on the sampling rate as well as the
  111498. linear block and mapping sizes */
  111499. static void floor0_map_lazy_init(vorbis_block *vb,
  111500. vorbis_info_floor *infoX,
  111501. vorbis_look_floor0 *look){
  111502. if(!look->linearmap[vb->W]){
  111503. vorbis_dsp_state *vd=vb->vd;
  111504. vorbis_info *vi=vd->vi;
  111505. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111506. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  111507. int W=vb->W;
  111508. int n=ci->blocksizes[W]/2,j;
  111509. /* we choose a scaling constant so that:
  111510. floor(bark(rate/2-1)*C)=mapped-1
  111511. floor(bark(rate/2)*C)=mapped */
  111512. float scale=look->ln/toBARK(info->rate/2.f);
  111513. /* the mapping from a linear scale to a smaller bark scale is
  111514. straightforward. We do *not* make sure that the linear mapping
  111515. does not skip bark-scale bins; the decoder simply skips them and
  111516. the encoder may do what it wishes in filling them. They're
  111517. necessary in some mapping combinations to keep the scale spacing
  111518. accurate */
  111519. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  111520. for(j=0;j<n;j++){
  111521. int val=floor( toBARK((info->rate/2.f)/n*j)
  111522. *scale); /* bark numbers represent band edges */
  111523. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  111524. look->linearmap[W][j]=val;
  111525. }
  111526. look->linearmap[W][j]=-1;
  111527. look->n[W]=n;
  111528. }
  111529. }
  111530. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  111531. vorbis_info_floor *i){
  111532. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  111533. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  111534. look->m=info->order;
  111535. look->ln=info->barkmap;
  111536. look->vi=info;
  111537. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  111538. return look;
  111539. }
  111540. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  111541. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111542. vorbis_info_floor0 *info=look->vi;
  111543. int j,k;
  111544. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  111545. if(ampraw>0){ /* also handles the -1 out of data case */
  111546. long maxval=(1<<info->ampbits)-1;
  111547. float amp=(float)ampraw/maxval*info->ampdB;
  111548. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  111549. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  111550. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  111551. codebook *b=ci->fullbooks+info->books[booknum];
  111552. float last=0.f;
  111553. /* the additional b->dim is a guard against any possible stack
  111554. smash; b->dim is provably more than we can overflow the
  111555. vector */
  111556. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  111557. for(j=0;j<look->m;j+=b->dim)
  111558. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  111559. for(j=0;j<look->m;){
  111560. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  111561. last=lsp[j-1];
  111562. }
  111563. lsp[look->m]=amp;
  111564. return(lsp);
  111565. }
  111566. }
  111567. eop:
  111568. return(NULL);
  111569. }
  111570. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  111571. void *memo,float *out){
  111572. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111573. vorbis_info_floor0 *info=look->vi;
  111574. floor0_map_lazy_init(vb,info,look);
  111575. if(memo){
  111576. float *lsp=(float *)memo;
  111577. float amp=lsp[look->m];
  111578. /* take the coefficients back to a spectral envelope curve */
  111579. vorbis_lsp_to_curve(out,
  111580. look->linearmap[vb->W],
  111581. look->n[vb->W],
  111582. look->ln,
  111583. lsp,look->m,amp,(float)info->ampdB);
  111584. return(1);
  111585. }
  111586. memset(out,0,sizeof(*out)*look->n[vb->W]);
  111587. return(0);
  111588. }
  111589. /* export hooks */
  111590. vorbis_func_floor floor0_exportbundle={
  111591. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  111592. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  111593. };
  111594. #endif
  111595. /*** End of inlined file: floor0.c ***/
  111596. /*** Start of inlined file: floor1.c ***/
  111597. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111598. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111599. // tasks..
  111600. #if JUCE_MSVC
  111601. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111602. #endif
  111603. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111604. #if JUCE_USE_OGGVORBIS
  111605. #include <stdlib.h>
  111606. #include <string.h>
  111607. #include <math.h>
  111608. #include <stdio.h>
  111609. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  111610. typedef struct {
  111611. int sorted_index[VIF_POSIT+2];
  111612. int forward_index[VIF_POSIT+2];
  111613. int reverse_index[VIF_POSIT+2];
  111614. int hineighbor[VIF_POSIT];
  111615. int loneighbor[VIF_POSIT];
  111616. int posts;
  111617. int n;
  111618. int quant_q;
  111619. vorbis_info_floor1 *vi;
  111620. long phrasebits;
  111621. long postbits;
  111622. long frames;
  111623. } vorbis_look_floor1;
  111624. typedef struct lsfit_acc{
  111625. long x0;
  111626. long x1;
  111627. long xa;
  111628. long ya;
  111629. long x2a;
  111630. long y2a;
  111631. long xya;
  111632. long an;
  111633. } lsfit_acc;
  111634. /***********************************************/
  111635. static void floor1_free_info(vorbis_info_floor *i){
  111636. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  111637. if(info){
  111638. memset(info,0,sizeof(*info));
  111639. _ogg_free(info);
  111640. }
  111641. }
  111642. static void floor1_free_look(vorbis_look_floor *i){
  111643. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  111644. if(look){
  111645. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  111646. (float)look->phrasebits/look->frames,
  111647. (float)look->postbits/look->frames,
  111648. (float)(look->postbits+look->phrasebits)/look->frames);*/
  111649. memset(look,0,sizeof(*look));
  111650. _ogg_free(look);
  111651. }
  111652. }
  111653. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  111654. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  111655. int j,k;
  111656. int count=0;
  111657. int rangebits;
  111658. int maxposit=info->postlist[1];
  111659. int maxclass=-1;
  111660. /* save out partitions */
  111661. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  111662. for(j=0;j<info->partitions;j++){
  111663. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  111664. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  111665. }
  111666. /* save out partition classes */
  111667. for(j=0;j<maxclass+1;j++){
  111668. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  111669. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  111670. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  111671. for(k=0;k<(1<<info->class_subs[j]);k++)
  111672. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  111673. }
  111674. /* save out the post list */
  111675. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  111676. oggpack_write(opb,ilog2(maxposit),4);
  111677. rangebits=ilog2(maxposit);
  111678. for(j=0,k=0;j<info->partitions;j++){
  111679. count+=info->class_dim[info->partitionclass[j]];
  111680. for(;k<count;k++)
  111681. oggpack_write(opb,info->postlist[k+2],rangebits);
  111682. }
  111683. }
  111684. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  111685. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111686. int j,k,count=0,maxclass=-1,rangebits;
  111687. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  111688. /* read partitions */
  111689. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  111690. for(j=0;j<info->partitions;j++){
  111691. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  111692. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  111693. }
  111694. /* read partition classes */
  111695. for(j=0;j<maxclass+1;j++){
  111696. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  111697. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  111698. if(info->class_subs[j]<0)
  111699. goto err_out;
  111700. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  111701. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  111702. goto err_out;
  111703. for(k=0;k<(1<<info->class_subs[j]);k++){
  111704. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  111705. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  111706. goto err_out;
  111707. }
  111708. }
  111709. /* read the post list */
  111710. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  111711. rangebits=oggpack_read(opb,4);
  111712. for(j=0,k=0;j<info->partitions;j++){
  111713. count+=info->class_dim[info->partitionclass[j]];
  111714. for(;k<count;k++){
  111715. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  111716. if(t<0 || t>=(1<<rangebits))
  111717. goto err_out;
  111718. }
  111719. }
  111720. info->postlist[0]=0;
  111721. info->postlist[1]=1<<rangebits;
  111722. return(info);
  111723. err_out:
  111724. floor1_free_info(info);
  111725. return(NULL);
  111726. }
  111727. static int icomp(const void *a,const void *b){
  111728. return(**(int **)a-**(int **)b);
  111729. }
  111730. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  111731. vorbis_info_floor *in){
  111732. int *sortpointer[VIF_POSIT+2];
  111733. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  111734. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  111735. int i,j,n=0;
  111736. look->vi=info;
  111737. look->n=info->postlist[1];
  111738. /* we drop each position value in-between already decoded values,
  111739. and use linear interpolation to predict each new value past the
  111740. edges. The positions are read in the order of the position
  111741. list... we precompute the bounding positions in the lookup. Of
  111742. course, the neighbors can change (if a position is declined), but
  111743. this is an initial mapping */
  111744. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  111745. n+=2;
  111746. look->posts=n;
  111747. /* also store a sorted position index */
  111748. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  111749. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  111750. /* points from sort order back to range number */
  111751. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  111752. /* points from range order to sorted position */
  111753. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  111754. /* we actually need the post values too */
  111755. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  111756. /* quantize values to multiplier spec */
  111757. switch(info->mult){
  111758. case 1: /* 1024 -> 256 */
  111759. look->quant_q=256;
  111760. break;
  111761. case 2: /* 1024 -> 128 */
  111762. look->quant_q=128;
  111763. break;
  111764. case 3: /* 1024 -> 86 */
  111765. look->quant_q=86;
  111766. break;
  111767. case 4: /* 1024 -> 64 */
  111768. look->quant_q=64;
  111769. break;
  111770. }
  111771. /* discover our neighbors for decode where we don't use fit flags
  111772. (that would push the neighbors outward) */
  111773. for(i=0;i<n-2;i++){
  111774. int lo=0;
  111775. int hi=1;
  111776. int lx=0;
  111777. int hx=look->n;
  111778. int currentx=info->postlist[i+2];
  111779. for(j=0;j<i+2;j++){
  111780. int x=info->postlist[j];
  111781. if(x>lx && x<currentx){
  111782. lo=j;
  111783. lx=x;
  111784. }
  111785. if(x<hx && x>currentx){
  111786. hi=j;
  111787. hx=x;
  111788. }
  111789. }
  111790. look->loneighbor[i]=lo;
  111791. look->hineighbor[i]=hi;
  111792. }
  111793. return(look);
  111794. }
  111795. static int render_point(int x0,int x1,int y0,int y1,int x){
  111796. y0&=0x7fff; /* mask off flag */
  111797. y1&=0x7fff;
  111798. {
  111799. int dy=y1-y0;
  111800. int adx=x1-x0;
  111801. int ady=abs(dy);
  111802. int err=ady*(x-x0);
  111803. int off=err/adx;
  111804. if(dy<0)return(y0-off);
  111805. return(y0+off);
  111806. }
  111807. }
  111808. static int vorbis_dBquant(const float *x){
  111809. int i= *x*7.3142857f+1023.5f;
  111810. if(i>1023)return(1023);
  111811. if(i<0)return(0);
  111812. return i;
  111813. }
  111814. static float FLOOR1_fromdB_LOOKUP[256]={
  111815. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  111816. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  111817. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  111818. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  111819. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  111820. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  111821. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  111822. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  111823. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  111824. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  111825. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  111826. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  111827. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  111828. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  111829. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  111830. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  111831. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  111832. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  111833. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  111834. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  111835. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  111836. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  111837. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  111838. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  111839. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  111840. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  111841. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  111842. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  111843. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  111844. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  111845. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  111846. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  111847. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  111848. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  111849. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  111850. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  111851. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  111852. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  111853. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  111854. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  111855. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  111856. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  111857. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  111858. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  111859. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  111860. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  111861. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  111862. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  111863. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  111864. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  111865. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  111866. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  111867. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  111868. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  111869. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  111870. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  111871. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  111872. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  111873. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  111874. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  111875. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  111876. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  111877. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  111878. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  111879. };
  111880. static void render_line(int x0,int x1,int y0,int y1,float *d){
  111881. int dy=y1-y0;
  111882. int adx=x1-x0;
  111883. int ady=abs(dy);
  111884. int base=dy/adx;
  111885. int sy=(dy<0?base-1:base+1);
  111886. int x=x0;
  111887. int y=y0;
  111888. int err=0;
  111889. ady-=abs(base*adx);
  111890. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  111891. while(++x<x1){
  111892. err=err+ady;
  111893. if(err>=adx){
  111894. err-=adx;
  111895. y+=sy;
  111896. }else{
  111897. y+=base;
  111898. }
  111899. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  111900. }
  111901. }
  111902. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  111903. int dy=y1-y0;
  111904. int adx=x1-x0;
  111905. int ady=abs(dy);
  111906. int base=dy/adx;
  111907. int sy=(dy<0?base-1:base+1);
  111908. int x=x0;
  111909. int y=y0;
  111910. int err=0;
  111911. ady-=abs(base*adx);
  111912. d[x]=y;
  111913. while(++x<x1){
  111914. err=err+ady;
  111915. if(err>=adx){
  111916. err-=adx;
  111917. y+=sy;
  111918. }else{
  111919. y+=base;
  111920. }
  111921. d[x]=y;
  111922. }
  111923. }
  111924. /* the floor has already been filtered to only include relevant sections */
  111925. static int accumulate_fit(const float *flr,const float *mdct,
  111926. int x0, int x1,lsfit_acc *a,
  111927. int n,vorbis_info_floor1 *info){
  111928. long i;
  111929. long xa=0,ya=0,x2a=0,y2a=0,xya=0,na=0, xb=0,yb=0,x2b=0,y2b=0,xyb=0,nb=0;
  111930. memset(a,0,sizeof(*a));
  111931. a->x0=x0;
  111932. a->x1=x1;
  111933. if(x1>=n)x1=n-1;
  111934. for(i=x0;i<=x1;i++){
  111935. int quantized=vorbis_dBquant(flr+i);
  111936. if(quantized){
  111937. if(mdct[i]+info->twofitatten>=flr[i]){
  111938. xa += i;
  111939. ya += quantized;
  111940. x2a += i*i;
  111941. y2a += quantized*quantized;
  111942. xya += i*quantized;
  111943. na++;
  111944. }else{
  111945. xb += i;
  111946. yb += quantized;
  111947. x2b += i*i;
  111948. y2b += quantized*quantized;
  111949. xyb += i*quantized;
  111950. nb++;
  111951. }
  111952. }
  111953. }
  111954. xb+=xa;
  111955. yb+=ya;
  111956. x2b+=x2a;
  111957. y2b+=y2a;
  111958. xyb+=xya;
  111959. nb+=na;
  111960. /* weight toward the actually used frequencies if we meet the threshhold */
  111961. {
  111962. int weight=nb*info->twofitweight/(na+1);
  111963. a->xa=xa*weight+xb;
  111964. a->ya=ya*weight+yb;
  111965. a->x2a=x2a*weight+x2b;
  111966. a->y2a=y2a*weight+y2b;
  111967. a->xya=xya*weight+xyb;
  111968. a->an=na*weight+nb;
  111969. }
  111970. return(na);
  111971. }
  111972. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  111973. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  111974. long x0=a[0].x0;
  111975. long x1=a[fits-1].x1;
  111976. for(i=0;i<fits;i++){
  111977. x+=a[i].xa;
  111978. y+=a[i].ya;
  111979. x2+=a[i].x2a;
  111980. y2+=a[i].y2a;
  111981. xy+=a[i].xya;
  111982. an+=a[i].an;
  111983. }
  111984. if(*y0>=0){
  111985. x+= x0;
  111986. y+= *y0;
  111987. x2+= x0 * x0;
  111988. y2+= *y0 * *y0;
  111989. xy+= *y0 * x0;
  111990. an++;
  111991. }
  111992. if(*y1>=0){
  111993. x+= x1;
  111994. y+= *y1;
  111995. x2+= x1 * x1;
  111996. y2+= *y1 * *y1;
  111997. xy+= *y1 * x1;
  111998. an++;
  111999. }
  112000. if(an){
  112001. /* need 64 bit multiplies, which C doesn't give portably as int */
  112002. double fx=x;
  112003. double fy=y;
  112004. double fx2=x2;
  112005. double fxy=xy;
  112006. double denom=1./(an*fx2-fx*fx);
  112007. double a=(fy*fx2-fxy*fx)*denom;
  112008. double b=(an*fxy-fx*fy)*denom;
  112009. *y0=rint(a+b*x0);
  112010. *y1=rint(a+b*x1);
  112011. /* limit to our range! */
  112012. if(*y0>1023)*y0=1023;
  112013. if(*y1>1023)*y1=1023;
  112014. if(*y0<0)*y0=0;
  112015. if(*y1<0)*y1=0;
  112016. }else{
  112017. *y0=0;
  112018. *y1=0;
  112019. }
  112020. }
  112021. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112022. long y=0;
  112023. int i;
  112024. for(i=0;i<fits && y==0;i++)
  112025. y+=a[i].ya;
  112026. *y0=*y1=y;
  112027. }*/
  112028. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112029. const float *mdct,
  112030. vorbis_info_floor1 *info){
  112031. int dy=y1-y0;
  112032. int adx=x1-x0;
  112033. int ady=abs(dy);
  112034. int base=dy/adx;
  112035. int sy=(dy<0?base-1:base+1);
  112036. int x=x0;
  112037. int y=y0;
  112038. int err=0;
  112039. int val=vorbis_dBquant(mask+x);
  112040. int mse=0;
  112041. int n=0;
  112042. ady-=abs(base*adx);
  112043. mse=(y-val);
  112044. mse*=mse;
  112045. n++;
  112046. if(mdct[x]+info->twofitatten>=mask[x]){
  112047. if(y+info->maxover<val)return(1);
  112048. if(y-info->maxunder>val)return(1);
  112049. }
  112050. while(++x<x1){
  112051. err=err+ady;
  112052. if(err>=adx){
  112053. err-=adx;
  112054. y+=sy;
  112055. }else{
  112056. y+=base;
  112057. }
  112058. val=vorbis_dBquant(mask+x);
  112059. mse+=((y-val)*(y-val));
  112060. n++;
  112061. if(mdct[x]+info->twofitatten>=mask[x]){
  112062. if(val){
  112063. if(y+info->maxover<val)return(1);
  112064. if(y-info->maxunder>val)return(1);
  112065. }
  112066. }
  112067. }
  112068. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112069. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112070. if(mse/n>info->maxerr)return(1);
  112071. return(0);
  112072. }
  112073. static int post_Y(int *A,int *B,int pos){
  112074. if(A[pos]<0)
  112075. return B[pos];
  112076. if(B[pos]<0)
  112077. return A[pos];
  112078. return (A[pos]+B[pos])>>1;
  112079. }
  112080. int *floor1_fit(vorbis_block *vb,void *look_,
  112081. const float *logmdct, /* in */
  112082. const float *logmask){
  112083. long i,j;
  112084. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112085. vorbis_info_floor1 *info=look->vi;
  112086. long n=look->n;
  112087. long posts=look->posts;
  112088. long nonzero=0;
  112089. lsfit_acc fits[VIF_POSIT+1];
  112090. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112091. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112092. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112093. int hineighbor[VIF_POSIT+2];
  112094. int *output=NULL;
  112095. int memo[VIF_POSIT+2];
  112096. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112097. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112098. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112099. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112100. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112101. /* quantize the relevant floor points and collect them into line fit
  112102. structures (one per minimal division) at the same time */
  112103. if(posts==0){
  112104. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112105. }else{
  112106. for(i=0;i<posts-1;i++)
  112107. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112108. look->sorted_index[i+1],fits+i,
  112109. n,info);
  112110. }
  112111. if(nonzero){
  112112. /* start by fitting the implicit base case.... */
  112113. int y0=-200;
  112114. int y1=-200;
  112115. fit_line(fits,posts-1,&y0,&y1);
  112116. fit_valueA[0]=y0;
  112117. fit_valueB[0]=y0;
  112118. fit_valueB[1]=y1;
  112119. fit_valueA[1]=y1;
  112120. /* Non degenerate case */
  112121. /* start progressive splitting. This is a greedy, non-optimal
  112122. algorithm, but simple and close enough to the best
  112123. answer. */
  112124. for(i=2;i<posts;i++){
  112125. int sortpos=look->reverse_index[i];
  112126. int ln=loneighbor[sortpos];
  112127. int hn=hineighbor[sortpos];
  112128. /* eliminate repeat searches of a particular range with a memo */
  112129. if(memo[ln]!=hn){
  112130. /* haven't performed this error search yet */
  112131. int lsortpos=look->reverse_index[ln];
  112132. int hsortpos=look->reverse_index[hn];
  112133. memo[ln]=hn;
  112134. {
  112135. /* A note: we want to bound/minimize *local*, not global, error */
  112136. int lx=info->postlist[ln];
  112137. int hx=info->postlist[hn];
  112138. int ly=post_Y(fit_valueA,fit_valueB,ln);
  112139. int hy=post_Y(fit_valueA,fit_valueB,hn);
  112140. if(ly==-1 || hy==-1){
  112141. exit(1);
  112142. }
  112143. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  112144. /* outside error bounds/begin search area. Split it. */
  112145. int ly0=-200;
  112146. int ly1=-200;
  112147. int hy0=-200;
  112148. int hy1=-200;
  112149. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  112150. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  112151. /* store new edge values */
  112152. fit_valueB[ln]=ly0;
  112153. if(ln==0)fit_valueA[ln]=ly0;
  112154. fit_valueA[i]=ly1;
  112155. fit_valueB[i]=hy0;
  112156. fit_valueA[hn]=hy1;
  112157. if(hn==1)fit_valueB[hn]=hy1;
  112158. if(ly1>=0 || hy0>=0){
  112159. /* store new neighbor values */
  112160. for(j=sortpos-1;j>=0;j--)
  112161. if(hineighbor[j]==hn)
  112162. hineighbor[j]=i;
  112163. else
  112164. break;
  112165. for(j=sortpos+1;j<posts;j++)
  112166. if(loneighbor[j]==ln)
  112167. loneighbor[j]=i;
  112168. else
  112169. break;
  112170. }
  112171. }else{
  112172. fit_valueA[i]=-200;
  112173. fit_valueB[i]=-200;
  112174. }
  112175. }
  112176. }
  112177. }
  112178. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112179. output[0]=post_Y(fit_valueA,fit_valueB,0);
  112180. output[1]=post_Y(fit_valueA,fit_valueB,1);
  112181. /* fill in posts marked as not using a fit; we will zero
  112182. back out to 'unused' when encoding them so long as curve
  112183. interpolation doesn't force them into use */
  112184. for(i=2;i<posts;i++){
  112185. int ln=look->loneighbor[i-2];
  112186. int hn=look->hineighbor[i-2];
  112187. int x0=info->postlist[ln];
  112188. int x1=info->postlist[hn];
  112189. int y0=output[ln];
  112190. int y1=output[hn];
  112191. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112192. int vx=post_Y(fit_valueA,fit_valueB,i);
  112193. if(vx>=0 && predicted!=vx){
  112194. output[i]=vx;
  112195. }else{
  112196. output[i]= predicted|0x8000;
  112197. }
  112198. }
  112199. }
  112200. return(output);
  112201. }
  112202. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  112203. int *A,int *B,
  112204. int del){
  112205. long i;
  112206. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  112207. long posts=look->posts;
  112208. int *output=NULL;
  112209. if(A && B){
  112210. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112211. for(i=0;i<posts;i++){
  112212. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  112213. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  112214. }
  112215. }
  112216. return(output);
  112217. }
  112218. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  112219. void*look_,
  112220. int *post,int *ilogmask){
  112221. long i,j;
  112222. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  112223. vorbis_info_floor1 *info=look->vi;
  112224. long posts=look->posts;
  112225. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112226. int out[VIF_POSIT+2];
  112227. static_codebook **sbooks=ci->book_param;
  112228. codebook *books=ci->fullbooks;
  112229. static long seq=0;
  112230. /* quantize values to multiplier spec */
  112231. if(post){
  112232. for(i=0;i<posts;i++){
  112233. int val=post[i]&0x7fff;
  112234. switch(info->mult){
  112235. case 1: /* 1024 -> 256 */
  112236. val>>=2;
  112237. break;
  112238. case 2: /* 1024 -> 128 */
  112239. val>>=3;
  112240. break;
  112241. case 3: /* 1024 -> 86 */
  112242. val/=12;
  112243. break;
  112244. case 4: /* 1024 -> 64 */
  112245. val>>=4;
  112246. break;
  112247. }
  112248. post[i]=val | (post[i]&0x8000);
  112249. }
  112250. out[0]=post[0];
  112251. out[1]=post[1];
  112252. /* find prediction values for each post and subtract them */
  112253. for(i=2;i<posts;i++){
  112254. int ln=look->loneighbor[i-2];
  112255. int hn=look->hineighbor[i-2];
  112256. int x0=info->postlist[ln];
  112257. int x1=info->postlist[hn];
  112258. int y0=post[ln];
  112259. int y1=post[hn];
  112260. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112261. if((post[i]&0x8000) || (predicted==post[i])){
  112262. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  112263. in interpolation */
  112264. out[i]=0;
  112265. }else{
  112266. int headroom=(look->quant_q-predicted<predicted?
  112267. look->quant_q-predicted:predicted);
  112268. int val=post[i]-predicted;
  112269. /* at this point the 'deviation' value is in the range +/- max
  112270. range, but the real, unique range can always be mapped to
  112271. only [0-maxrange). So we want to wrap the deviation into
  112272. this limited range, but do it in the way that least screws
  112273. an essentially gaussian probability distribution. */
  112274. if(val<0)
  112275. if(val<-headroom)
  112276. val=headroom-val-1;
  112277. else
  112278. val=-1-(val<<1);
  112279. else
  112280. if(val>=headroom)
  112281. val= val+headroom;
  112282. else
  112283. val<<=1;
  112284. out[i]=val;
  112285. post[ln]&=0x7fff;
  112286. post[hn]&=0x7fff;
  112287. }
  112288. }
  112289. /* we have everything we need. pack it out */
  112290. /* mark nontrivial floor */
  112291. oggpack_write(opb,1,1);
  112292. /* beginning/end post */
  112293. look->frames++;
  112294. look->postbits+=ilog(look->quant_q-1)*2;
  112295. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  112296. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  112297. /* partition by partition */
  112298. for(i=0,j=2;i<info->partitions;i++){
  112299. int classx=info->partitionclass[i];
  112300. int cdim=info->class_dim[classx];
  112301. int csubbits=info->class_subs[classx];
  112302. int csub=1<<csubbits;
  112303. int bookas[8]={0,0,0,0,0,0,0,0};
  112304. int cval=0;
  112305. int cshift=0;
  112306. int k,l;
  112307. /* generate the partition's first stage cascade value */
  112308. if(csubbits){
  112309. int maxval[8];
  112310. for(k=0;k<csub;k++){
  112311. int booknum=info->class_subbook[classx][k];
  112312. if(booknum<0){
  112313. maxval[k]=1;
  112314. }else{
  112315. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  112316. }
  112317. }
  112318. for(k=0;k<cdim;k++){
  112319. for(l=0;l<csub;l++){
  112320. int val=out[j+k];
  112321. if(val<maxval[l]){
  112322. bookas[k]=l;
  112323. break;
  112324. }
  112325. }
  112326. cval|= bookas[k]<<cshift;
  112327. cshift+=csubbits;
  112328. }
  112329. /* write it */
  112330. look->phrasebits+=
  112331. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  112332. #ifdef TRAIN_FLOOR1
  112333. {
  112334. FILE *of;
  112335. char buffer[80];
  112336. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  112337. vb->pcmend/2,posts-2,class);
  112338. of=fopen(buffer,"a");
  112339. fprintf(of,"%d\n",cval);
  112340. fclose(of);
  112341. }
  112342. #endif
  112343. }
  112344. /* write post values */
  112345. for(k=0;k<cdim;k++){
  112346. int book=info->class_subbook[classx][bookas[k]];
  112347. if(book>=0){
  112348. /* hack to allow training with 'bad' books */
  112349. if(out[j+k]<(books+book)->entries)
  112350. look->postbits+=vorbis_book_encode(books+book,
  112351. out[j+k],opb);
  112352. /*else
  112353. fprintf(stderr,"+!");*/
  112354. #ifdef TRAIN_FLOOR1
  112355. {
  112356. FILE *of;
  112357. char buffer[80];
  112358. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  112359. vb->pcmend/2,posts-2,class,bookas[k]);
  112360. of=fopen(buffer,"a");
  112361. fprintf(of,"%d\n",out[j+k]);
  112362. fclose(of);
  112363. }
  112364. #endif
  112365. }
  112366. }
  112367. j+=cdim;
  112368. }
  112369. {
  112370. /* generate quantized floor equivalent to what we'd unpack in decode */
  112371. /* render the lines */
  112372. int hx=0;
  112373. int lx=0;
  112374. int ly=post[0]*info->mult;
  112375. for(j=1;j<look->posts;j++){
  112376. int current=look->forward_index[j];
  112377. int hy=post[current]&0x7fff;
  112378. if(hy==post[current]){
  112379. hy*=info->mult;
  112380. hx=info->postlist[current];
  112381. render_line0(lx,hx,ly,hy,ilogmask);
  112382. lx=hx;
  112383. ly=hy;
  112384. }
  112385. }
  112386. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  112387. seq++;
  112388. return(1);
  112389. }
  112390. }else{
  112391. oggpack_write(opb,0,1);
  112392. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  112393. seq++;
  112394. return(0);
  112395. }
  112396. }
  112397. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  112398. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112399. vorbis_info_floor1 *info=look->vi;
  112400. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112401. int i,j,k;
  112402. codebook *books=ci->fullbooks;
  112403. /* unpack wrapped/predicted values from stream */
  112404. if(oggpack_read(&vb->opb,1)==1){
  112405. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  112406. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112407. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112408. /* partition by partition */
  112409. for(i=0,j=2;i<info->partitions;i++){
  112410. int classx=info->partitionclass[i];
  112411. int cdim=info->class_dim[classx];
  112412. int csubbits=info->class_subs[classx];
  112413. int csub=1<<csubbits;
  112414. int cval=0;
  112415. /* decode the partition's first stage cascade value */
  112416. if(csubbits){
  112417. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  112418. if(cval==-1)goto eop;
  112419. }
  112420. for(k=0;k<cdim;k++){
  112421. int book=info->class_subbook[classx][cval&(csub-1)];
  112422. cval>>=csubbits;
  112423. if(book>=0){
  112424. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  112425. goto eop;
  112426. }else{
  112427. fit_value[j+k]=0;
  112428. }
  112429. }
  112430. j+=cdim;
  112431. }
  112432. /* unwrap positive values and reconsitute via linear interpolation */
  112433. for(i=2;i<look->posts;i++){
  112434. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  112435. info->postlist[look->hineighbor[i-2]],
  112436. fit_value[look->loneighbor[i-2]],
  112437. fit_value[look->hineighbor[i-2]],
  112438. info->postlist[i]);
  112439. int hiroom=look->quant_q-predicted;
  112440. int loroom=predicted;
  112441. int room=(hiroom<loroom?hiroom:loroom)<<1;
  112442. int val=fit_value[i];
  112443. if(val){
  112444. if(val>=room){
  112445. if(hiroom>loroom){
  112446. val = val-loroom;
  112447. }else{
  112448. val = -1-(val-hiroom);
  112449. }
  112450. }else{
  112451. if(val&1){
  112452. val= -((val+1)>>1);
  112453. }else{
  112454. val>>=1;
  112455. }
  112456. }
  112457. fit_value[i]=val+predicted;
  112458. fit_value[look->loneighbor[i-2]]&=0x7fff;
  112459. fit_value[look->hineighbor[i-2]]&=0x7fff;
  112460. }else{
  112461. fit_value[i]=predicted|0x8000;
  112462. }
  112463. }
  112464. return(fit_value);
  112465. }
  112466. eop:
  112467. return(NULL);
  112468. }
  112469. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  112470. float *out){
  112471. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112472. vorbis_info_floor1 *info=look->vi;
  112473. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112474. int n=ci->blocksizes[vb->W]/2;
  112475. int j;
  112476. if(memo){
  112477. /* render the lines */
  112478. int *fit_value=(int *)memo;
  112479. int hx=0;
  112480. int lx=0;
  112481. int ly=fit_value[0]*info->mult;
  112482. for(j=1;j<look->posts;j++){
  112483. int current=look->forward_index[j];
  112484. int hy=fit_value[current]&0x7fff;
  112485. if(hy==fit_value[current]){
  112486. hy*=info->mult;
  112487. hx=info->postlist[current];
  112488. render_line(lx,hx,ly,hy,out);
  112489. lx=hx;
  112490. ly=hy;
  112491. }
  112492. }
  112493. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  112494. return(1);
  112495. }
  112496. memset(out,0,sizeof(*out)*n);
  112497. return(0);
  112498. }
  112499. /* export hooks */
  112500. vorbis_func_floor floor1_exportbundle={
  112501. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  112502. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  112503. };
  112504. #endif
  112505. /*** End of inlined file: floor1.c ***/
  112506. /*** Start of inlined file: info.c ***/
  112507. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112508. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112509. // tasks..
  112510. #if JUCE_MSVC
  112511. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112512. #endif
  112513. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112514. #if JUCE_USE_OGGVORBIS
  112515. /* general handling of the header and the vorbis_info structure (and
  112516. substructures) */
  112517. #include <stdlib.h>
  112518. #include <string.h>
  112519. #include <ctype.h>
  112520. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  112521. while(bytes--){
  112522. oggpack_write(o,*s++,8);
  112523. }
  112524. }
  112525. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  112526. while(bytes--){
  112527. *buf++=oggpack_read(o,8);
  112528. }
  112529. }
  112530. void vorbis_comment_init(vorbis_comment *vc){
  112531. memset(vc,0,sizeof(*vc));
  112532. }
  112533. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  112534. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  112535. (vc->comments+2)*sizeof(*vc->user_comments));
  112536. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  112537. (vc->comments+2)*sizeof(*vc->comment_lengths));
  112538. vc->comment_lengths[vc->comments]=strlen(comment);
  112539. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  112540. strcpy(vc->user_comments[vc->comments], comment);
  112541. vc->comments++;
  112542. vc->user_comments[vc->comments]=NULL;
  112543. }
  112544. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  112545. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  112546. strcpy(comment, tag);
  112547. strcat(comment, "=");
  112548. strcat(comment, contents);
  112549. vorbis_comment_add(vc, comment);
  112550. }
  112551. /* This is more or less the same as strncasecmp - but that doesn't exist
  112552. * everywhere, and this is a fairly trivial function, so we include it */
  112553. static int tagcompare(const char *s1, const char *s2, int n){
  112554. int c=0;
  112555. while(c < n){
  112556. if(toupper(s1[c]) != toupper(s2[c]))
  112557. return !0;
  112558. c++;
  112559. }
  112560. return 0;
  112561. }
  112562. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  112563. long i;
  112564. int found = 0;
  112565. int taglen = strlen(tag)+1; /* +1 for the = we append */
  112566. char *fulltag = (char*)alloca(taglen+ 1);
  112567. strcpy(fulltag, tag);
  112568. strcat(fulltag, "=");
  112569. for(i=0;i<vc->comments;i++){
  112570. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  112571. if(count == found)
  112572. /* We return a pointer to the data, not a copy */
  112573. return vc->user_comments[i] + taglen;
  112574. else
  112575. found++;
  112576. }
  112577. }
  112578. return NULL; /* didn't find anything */
  112579. }
  112580. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  112581. int i,count=0;
  112582. int taglen = strlen(tag)+1; /* +1 for the = we append */
  112583. char *fulltag = (char*)alloca(taglen+1);
  112584. strcpy(fulltag,tag);
  112585. strcat(fulltag, "=");
  112586. for(i=0;i<vc->comments;i++){
  112587. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  112588. count++;
  112589. }
  112590. return count;
  112591. }
  112592. void vorbis_comment_clear(vorbis_comment *vc){
  112593. if(vc){
  112594. long i;
  112595. for(i=0;i<vc->comments;i++)
  112596. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  112597. if(vc->user_comments)_ogg_free(vc->user_comments);
  112598. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  112599. if(vc->vendor)_ogg_free(vc->vendor);
  112600. }
  112601. memset(vc,0,sizeof(*vc));
  112602. }
  112603. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  112604. They may be equal, but short will never ge greater than long */
  112605. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  112606. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  112607. return ci ? ci->blocksizes[zo] : -1;
  112608. }
  112609. /* used by synthesis, which has a full, alloced vi */
  112610. void vorbis_info_init(vorbis_info *vi){
  112611. memset(vi,0,sizeof(*vi));
  112612. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  112613. }
  112614. void vorbis_info_clear(vorbis_info *vi){
  112615. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112616. int i;
  112617. if(ci){
  112618. for(i=0;i<ci->modes;i++)
  112619. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  112620. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  112621. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  112622. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  112623. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  112624. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  112625. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  112626. for(i=0;i<ci->books;i++){
  112627. if(ci->book_param[i]){
  112628. /* knows if the book was not alloced */
  112629. vorbis_staticbook_destroy(ci->book_param[i]);
  112630. }
  112631. if(ci->fullbooks)
  112632. vorbis_book_clear(ci->fullbooks+i);
  112633. }
  112634. if(ci->fullbooks)
  112635. _ogg_free(ci->fullbooks);
  112636. for(i=0;i<ci->psys;i++)
  112637. _vi_psy_free(ci->psy_param[i]);
  112638. _ogg_free(ci);
  112639. }
  112640. memset(vi,0,sizeof(*vi));
  112641. }
  112642. /* Header packing/unpacking ********************************************/
  112643. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  112644. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112645. if(!ci)return(OV_EFAULT);
  112646. vi->version=oggpack_read(opb,32);
  112647. if(vi->version!=0)return(OV_EVERSION);
  112648. vi->channels=oggpack_read(opb,8);
  112649. vi->rate=oggpack_read(opb,32);
  112650. vi->bitrate_upper=oggpack_read(opb,32);
  112651. vi->bitrate_nominal=oggpack_read(opb,32);
  112652. vi->bitrate_lower=oggpack_read(opb,32);
  112653. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  112654. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  112655. if(vi->rate<1)goto err_out;
  112656. if(vi->channels<1)goto err_out;
  112657. if(ci->blocksizes[0]<8)goto err_out;
  112658. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  112659. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  112660. return(0);
  112661. err_out:
  112662. vorbis_info_clear(vi);
  112663. return(OV_EBADHEADER);
  112664. }
  112665. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  112666. int i;
  112667. int vendorlen=oggpack_read(opb,32);
  112668. if(vendorlen<0)goto err_out;
  112669. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  112670. _v_readstring(opb,vc->vendor,vendorlen);
  112671. vc->comments=oggpack_read(opb,32);
  112672. if(vc->comments<0)goto err_out;
  112673. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  112674. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  112675. for(i=0;i<vc->comments;i++){
  112676. int len=oggpack_read(opb,32);
  112677. if(len<0)goto err_out;
  112678. vc->comment_lengths[i]=len;
  112679. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  112680. _v_readstring(opb,vc->user_comments[i],len);
  112681. }
  112682. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  112683. return(0);
  112684. err_out:
  112685. vorbis_comment_clear(vc);
  112686. return(OV_EBADHEADER);
  112687. }
  112688. /* all of the real encoding details are here. The modes, books,
  112689. everything */
  112690. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  112691. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112692. int i;
  112693. if(!ci)return(OV_EFAULT);
  112694. /* codebooks */
  112695. ci->books=oggpack_read(opb,8)+1;
  112696. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  112697. for(i=0;i<ci->books;i++){
  112698. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  112699. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  112700. }
  112701. /* time backend settings; hooks are unused */
  112702. {
  112703. int times=oggpack_read(opb,6)+1;
  112704. for(i=0;i<times;i++){
  112705. int test=oggpack_read(opb,16);
  112706. if(test<0 || test>=VI_TIMEB)goto err_out;
  112707. }
  112708. }
  112709. /* floor backend settings */
  112710. ci->floors=oggpack_read(opb,6)+1;
  112711. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  112712. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  112713. for(i=0;i<ci->floors;i++){
  112714. ci->floor_type[i]=oggpack_read(opb,16);
  112715. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  112716. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  112717. if(!ci->floor_param[i])goto err_out;
  112718. }
  112719. /* residue backend settings */
  112720. ci->residues=oggpack_read(opb,6)+1;
  112721. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  112722. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  112723. for(i=0;i<ci->residues;i++){
  112724. ci->residue_type[i]=oggpack_read(opb,16);
  112725. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  112726. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  112727. if(!ci->residue_param[i])goto err_out;
  112728. }
  112729. /* map backend settings */
  112730. ci->maps=oggpack_read(opb,6)+1;
  112731. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  112732. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  112733. for(i=0;i<ci->maps;i++){
  112734. ci->map_type[i]=oggpack_read(opb,16);
  112735. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  112736. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  112737. if(!ci->map_param[i])goto err_out;
  112738. }
  112739. /* mode settings */
  112740. ci->modes=oggpack_read(opb,6)+1;
  112741. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  112742. for(i=0;i<ci->modes;i++){
  112743. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  112744. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  112745. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  112746. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  112747. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  112748. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  112749. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  112750. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  112751. }
  112752. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  112753. return(0);
  112754. err_out:
  112755. vorbis_info_clear(vi);
  112756. return(OV_EBADHEADER);
  112757. }
  112758. /* The Vorbis header is in three packets; the initial small packet in
  112759. the first page that identifies basic parameters, a second packet
  112760. with bitstream comments and a third packet that holds the
  112761. codebook. */
  112762. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  112763. oggpack_buffer opb;
  112764. if(op){
  112765. oggpack_readinit(&opb,op->packet,op->bytes);
  112766. /* Which of the three types of header is this? */
  112767. /* Also verify header-ness, vorbis */
  112768. {
  112769. char buffer[6];
  112770. int packtype=oggpack_read(&opb,8);
  112771. memset(buffer,0,6);
  112772. _v_readstring(&opb,buffer,6);
  112773. if(memcmp(buffer,"vorbis",6)){
  112774. /* not a vorbis header */
  112775. return(OV_ENOTVORBIS);
  112776. }
  112777. switch(packtype){
  112778. case 0x01: /* least significant *bit* is read first */
  112779. if(!op->b_o_s){
  112780. /* Not the initial packet */
  112781. return(OV_EBADHEADER);
  112782. }
  112783. if(vi->rate!=0){
  112784. /* previously initialized info header */
  112785. return(OV_EBADHEADER);
  112786. }
  112787. return(_vorbis_unpack_info(vi,&opb));
  112788. case 0x03: /* least significant *bit* is read first */
  112789. if(vi->rate==0){
  112790. /* um... we didn't get the initial header */
  112791. return(OV_EBADHEADER);
  112792. }
  112793. return(_vorbis_unpack_comment(vc,&opb));
  112794. case 0x05: /* least significant *bit* is read first */
  112795. if(vi->rate==0 || vc->vendor==NULL){
  112796. /* um... we didn;t get the initial header or comments yet */
  112797. return(OV_EBADHEADER);
  112798. }
  112799. return(_vorbis_unpack_books(vi,&opb));
  112800. default:
  112801. /* Not a valid vorbis header type */
  112802. return(OV_EBADHEADER);
  112803. break;
  112804. }
  112805. }
  112806. }
  112807. return(OV_EBADHEADER);
  112808. }
  112809. /* pack side **********************************************************/
  112810. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  112811. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112812. if(!ci)return(OV_EFAULT);
  112813. /* preamble */
  112814. oggpack_write(opb,0x01,8);
  112815. _v_writestring(opb,"vorbis", 6);
  112816. /* basic information about the stream */
  112817. oggpack_write(opb,0x00,32);
  112818. oggpack_write(opb,vi->channels,8);
  112819. oggpack_write(opb,vi->rate,32);
  112820. oggpack_write(opb,vi->bitrate_upper,32);
  112821. oggpack_write(opb,vi->bitrate_nominal,32);
  112822. oggpack_write(opb,vi->bitrate_lower,32);
  112823. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  112824. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  112825. oggpack_write(opb,1,1);
  112826. return(0);
  112827. }
  112828. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  112829. char temp[]="Xiph.Org libVorbis I 20050304";
  112830. int bytes = strlen(temp);
  112831. /* preamble */
  112832. oggpack_write(opb,0x03,8);
  112833. _v_writestring(opb,"vorbis", 6);
  112834. /* vendor */
  112835. oggpack_write(opb,bytes,32);
  112836. _v_writestring(opb,temp, bytes);
  112837. /* comments */
  112838. oggpack_write(opb,vc->comments,32);
  112839. if(vc->comments){
  112840. int i;
  112841. for(i=0;i<vc->comments;i++){
  112842. if(vc->user_comments[i]){
  112843. oggpack_write(opb,vc->comment_lengths[i],32);
  112844. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  112845. }else{
  112846. oggpack_write(opb,0,32);
  112847. }
  112848. }
  112849. }
  112850. oggpack_write(opb,1,1);
  112851. return(0);
  112852. }
  112853. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  112854. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112855. int i;
  112856. if(!ci)return(OV_EFAULT);
  112857. oggpack_write(opb,0x05,8);
  112858. _v_writestring(opb,"vorbis", 6);
  112859. /* books */
  112860. oggpack_write(opb,ci->books-1,8);
  112861. for(i=0;i<ci->books;i++)
  112862. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  112863. /* times; hook placeholders */
  112864. oggpack_write(opb,0,6);
  112865. oggpack_write(opb,0,16);
  112866. /* floors */
  112867. oggpack_write(opb,ci->floors-1,6);
  112868. for(i=0;i<ci->floors;i++){
  112869. oggpack_write(opb,ci->floor_type[i],16);
  112870. if(_floor_P[ci->floor_type[i]]->pack)
  112871. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  112872. else
  112873. goto err_out;
  112874. }
  112875. /* residues */
  112876. oggpack_write(opb,ci->residues-1,6);
  112877. for(i=0;i<ci->residues;i++){
  112878. oggpack_write(opb,ci->residue_type[i],16);
  112879. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  112880. }
  112881. /* maps */
  112882. oggpack_write(opb,ci->maps-1,6);
  112883. for(i=0;i<ci->maps;i++){
  112884. oggpack_write(opb,ci->map_type[i],16);
  112885. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  112886. }
  112887. /* modes */
  112888. oggpack_write(opb,ci->modes-1,6);
  112889. for(i=0;i<ci->modes;i++){
  112890. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  112891. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  112892. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  112893. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  112894. }
  112895. oggpack_write(opb,1,1);
  112896. return(0);
  112897. err_out:
  112898. return(-1);
  112899. }
  112900. int vorbis_commentheader_out(vorbis_comment *vc,
  112901. ogg_packet *op){
  112902. oggpack_buffer opb;
  112903. oggpack_writeinit(&opb);
  112904. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  112905. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  112906. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  112907. op->bytes=oggpack_bytes(&opb);
  112908. op->b_o_s=0;
  112909. op->e_o_s=0;
  112910. op->granulepos=0;
  112911. op->packetno=1;
  112912. return 0;
  112913. }
  112914. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  112915. vorbis_comment *vc,
  112916. ogg_packet *op,
  112917. ogg_packet *op_comm,
  112918. ogg_packet *op_code){
  112919. int ret=OV_EIMPL;
  112920. vorbis_info *vi=v->vi;
  112921. oggpack_buffer opb;
  112922. private_state *b=(private_state*)v->backend_state;
  112923. if(!b){
  112924. ret=OV_EFAULT;
  112925. goto err_out;
  112926. }
  112927. /* first header packet **********************************************/
  112928. oggpack_writeinit(&opb);
  112929. if(_vorbis_pack_info(&opb,vi))goto err_out;
  112930. /* build the packet */
  112931. if(b->header)_ogg_free(b->header);
  112932. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  112933. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  112934. op->packet=b->header;
  112935. op->bytes=oggpack_bytes(&opb);
  112936. op->b_o_s=1;
  112937. op->e_o_s=0;
  112938. op->granulepos=0;
  112939. op->packetno=0;
  112940. /* second header packet (comments) **********************************/
  112941. oggpack_reset(&opb);
  112942. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  112943. if(b->header1)_ogg_free(b->header1);
  112944. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  112945. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  112946. op_comm->packet=b->header1;
  112947. op_comm->bytes=oggpack_bytes(&opb);
  112948. op_comm->b_o_s=0;
  112949. op_comm->e_o_s=0;
  112950. op_comm->granulepos=0;
  112951. op_comm->packetno=1;
  112952. /* third header packet (modes/codebooks) ****************************/
  112953. oggpack_reset(&opb);
  112954. if(_vorbis_pack_books(&opb,vi))goto err_out;
  112955. if(b->header2)_ogg_free(b->header2);
  112956. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  112957. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  112958. op_code->packet=b->header2;
  112959. op_code->bytes=oggpack_bytes(&opb);
  112960. op_code->b_o_s=0;
  112961. op_code->e_o_s=0;
  112962. op_code->granulepos=0;
  112963. op_code->packetno=2;
  112964. oggpack_writeclear(&opb);
  112965. return(0);
  112966. err_out:
  112967. oggpack_writeclear(&opb);
  112968. memset(op,0,sizeof(*op));
  112969. memset(op_comm,0,sizeof(*op_comm));
  112970. memset(op_code,0,sizeof(*op_code));
  112971. if(b->header)_ogg_free(b->header);
  112972. if(b->header1)_ogg_free(b->header1);
  112973. if(b->header2)_ogg_free(b->header2);
  112974. b->header=NULL;
  112975. b->header1=NULL;
  112976. b->header2=NULL;
  112977. return(ret);
  112978. }
  112979. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  112980. if(granulepos>=0)
  112981. return((double)granulepos/v->vi->rate);
  112982. return(-1);
  112983. }
  112984. #endif
  112985. /*** End of inlined file: info.c ***/
  112986. /*** Start of inlined file: lpc.c ***/
  112987. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  112988. are derived from code written by Jutta Degener and Carsten Bormann;
  112989. thus we include their copyright below. The entirety of this file
  112990. is freely redistributable on the condition that both of these
  112991. copyright notices are preserved without modification. */
  112992. /* Preserved Copyright: *********************************************/
  112993. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  112994. Technische Universita"t Berlin
  112995. Any use of this software is permitted provided that this notice is not
  112996. removed and that neither the authors nor the Technische Universita"t
  112997. Berlin are deemed to have made any representations as to the
  112998. suitability of this software for any purpose nor are held responsible
  112999. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113000. THIS SOFTWARE.
  113001. As a matter of courtesy, the authors request to be informed about uses
  113002. this software has found, about bugs in this software, and about any
  113003. improvements that may be of general interest.
  113004. Berlin, 28.11.1994
  113005. Jutta Degener
  113006. Carsten Bormann
  113007. *********************************************************************/
  113008. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113009. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113010. // tasks..
  113011. #if JUCE_MSVC
  113012. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113013. #endif
  113014. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113015. #if JUCE_USE_OGGVORBIS
  113016. #include <stdlib.h>
  113017. #include <string.h>
  113018. #include <math.h>
  113019. /* Autocorrelation LPC coeff generation algorithm invented by
  113020. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113021. /* Input : n elements of time doamin data
  113022. Output: m lpc coefficients, excitation energy */
  113023. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113024. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113025. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113026. double error;
  113027. int i,j;
  113028. /* autocorrelation, p+1 lag coefficients */
  113029. j=m+1;
  113030. while(j--){
  113031. double d=0; /* double needed for accumulator depth */
  113032. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113033. aut[j]=d;
  113034. }
  113035. /* Generate lpc coefficients from autocorr values */
  113036. error=aut[0];
  113037. for(i=0;i<m;i++){
  113038. double r= -aut[i+1];
  113039. if(error==0){
  113040. memset(lpci,0,m*sizeof(*lpci));
  113041. return 0;
  113042. }
  113043. /* Sum up this iteration's reflection coefficient; note that in
  113044. Vorbis we don't save it. If anyone wants to recycle this code
  113045. and needs reflection coefficients, save the results of 'r' from
  113046. each iteration. */
  113047. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113048. r/=error;
  113049. /* Update LPC coefficients and total error */
  113050. lpc[i]=r;
  113051. for(j=0;j<i/2;j++){
  113052. double tmp=lpc[j];
  113053. lpc[j]+=r*lpc[i-1-j];
  113054. lpc[i-1-j]+=r*tmp;
  113055. }
  113056. if(i%2)lpc[j]+=lpc[j]*r;
  113057. error*=1.f-r*r;
  113058. }
  113059. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113060. /* we need the error value to know how big an impulse to hit the
  113061. filter with later */
  113062. return error;
  113063. }
  113064. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113065. float *data,long n){
  113066. /* in: coeff[0...m-1] LPC coefficients
  113067. prime[0...m-1] initial values (allocated size of n+m-1)
  113068. out: data[0...n-1] data samples */
  113069. long i,j,o,p;
  113070. float y;
  113071. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113072. if(!prime)
  113073. for(i=0;i<m;i++)
  113074. work[i]=0.f;
  113075. else
  113076. for(i=0;i<m;i++)
  113077. work[i]=prime[i];
  113078. for(i=0;i<n;i++){
  113079. y=0;
  113080. o=i;
  113081. p=m;
  113082. for(j=0;j<m;j++)
  113083. y-=work[o++]*coeff[--p];
  113084. data[i]=work[o]=y;
  113085. }
  113086. }
  113087. #endif
  113088. /*** End of inlined file: lpc.c ***/
  113089. /*** Start of inlined file: lsp.c ***/
  113090. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113091. an iterative root polisher (CACM algorithm 283). It *is* possible
  113092. to confuse this algorithm into not converging; that should only
  113093. happen with absurdly closely spaced roots (very sharp peaks in the
  113094. LPC f response) which in turn should be impossible in our use of
  113095. the code. If this *does* happen anyway, it's a bug in the floor
  113096. finder; find the cause of the confusion (probably a single bin
  113097. spike or accidental near-float-limit resolution problems) and
  113098. correct it. */
  113099. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113100. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113101. // tasks..
  113102. #if JUCE_MSVC
  113103. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113104. #endif
  113105. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113106. #if JUCE_USE_OGGVORBIS
  113107. #include <math.h>
  113108. #include <string.h>
  113109. #include <stdlib.h>
  113110. /*** Start of inlined file: lookup.h ***/
  113111. #ifndef _V_LOOKUP_H_
  113112. #ifdef FLOAT_LOOKUP
  113113. extern float vorbis_coslook(float a);
  113114. extern float vorbis_invsqlook(float a);
  113115. extern float vorbis_invsq2explook(int a);
  113116. extern float vorbis_fromdBlook(float a);
  113117. #endif
  113118. #ifdef INT_LOOKUP
  113119. extern long vorbis_invsqlook_i(long a,long e);
  113120. extern long vorbis_coslook_i(long a);
  113121. extern float vorbis_fromdBlook_i(long a);
  113122. #endif
  113123. #endif
  113124. /*** End of inlined file: lookup.h ***/
  113125. /* three possible LSP to f curve functions; the exact computation
  113126. (float), a lookup based float implementation, and an integer
  113127. implementation. The float lookup is likely the optimal choice on
  113128. any machine with an FPU. The integer implementation is *not* fixed
  113129. point (due to the need for a large dynamic range and thus a
  113130. seperately tracked exponent) and thus much more complex than the
  113131. relatively simple float implementations. It's mostly for future
  113132. work on a fully fixed point implementation for processors like the
  113133. ARM family. */
  113134. /* undefine both for the 'old' but more precise implementation */
  113135. #define FLOAT_LOOKUP
  113136. #undef INT_LOOKUP
  113137. #ifdef FLOAT_LOOKUP
  113138. /*** Start of inlined file: lookup.c ***/
  113139. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113140. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113141. // tasks..
  113142. #if JUCE_MSVC
  113143. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113144. #endif
  113145. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113146. #if JUCE_USE_OGGVORBIS
  113147. #include <math.h>
  113148. /*** Start of inlined file: lookup.h ***/
  113149. #ifndef _V_LOOKUP_H_
  113150. #ifdef FLOAT_LOOKUP
  113151. extern float vorbis_coslook(float a);
  113152. extern float vorbis_invsqlook(float a);
  113153. extern float vorbis_invsq2explook(int a);
  113154. extern float vorbis_fromdBlook(float a);
  113155. #endif
  113156. #ifdef INT_LOOKUP
  113157. extern long vorbis_invsqlook_i(long a,long e);
  113158. extern long vorbis_coslook_i(long a);
  113159. extern float vorbis_fromdBlook_i(long a);
  113160. #endif
  113161. #endif
  113162. /*** End of inlined file: lookup.h ***/
  113163. /*** Start of inlined file: lookup_data.h ***/
  113164. #ifndef _V_LOOKUP_DATA_H_
  113165. #ifdef FLOAT_LOOKUP
  113166. #define COS_LOOKUP_SZ 128
  113167. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113168. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113169. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113170. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113171. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113172. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113173. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113174. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113175. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113176. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113177. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113178. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113179. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113180. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113181. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113182. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113183. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113184. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113185. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113186. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113187. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113188. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113189. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113190. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113191. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113192. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113193. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113194. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113195. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113196. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113197. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113198. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113199. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113200. -1.0000000000000f,
  113201. };
  113202. #define INVSQ_LOOKUP_SZ 32
  113203. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113204. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113205. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113206. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113207. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113208. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113209. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113210. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113211. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113212. 1.000000000000f,
  113213. };
  113214. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113215. #define INVSQ2EXP_LOOKUP_MAX 32
  113216. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113217. INVSQ2EXP_LOOKUP_MIN+1]={
  113218. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113219. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113220. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113221. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113222. 256.f, 181.019336f, 128.f, 90.50966799f,
  113223. 64.f, 45.254834f, 32.f, 22.627417f,
  113224. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113225. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113226. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113227. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113228. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113229. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113230. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113231. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113232. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113233. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113234. 1.525878906e-05f,
  113235. };
  113236. #endif
  113237. #define FROMdB_LOOKUP_SZ 35
  113238. #define FROMdB2_LOOKUP_SZ 32
  113239. #define FROMdB_SHIFT 5
  113240. #define FROMdB2_SHIFT 3
  113241. #define FROMdB2_MASK 31
  113242. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113243. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113244. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113245. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113246. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113247. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113248. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113249. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113250. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113251. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113252. };
  113253. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113254. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113255. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113256. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113257. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113258. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113259. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113260. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113261. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113262. };
  113263. #ifdef INT_LOOKUP
  113264. #define INVSQ_LOOKUP_I_SHIFT 10
  113265. #define INVSQ_LOOKUP_I_MASK 1023
  113266. static long INVSQ_LOOKUP_I[64+1]={
  113267. 92682l, 91966l, 91267l, 90583l,
  113268. 89915l, 89261l, 88621l, 87995l,
  113269. 87381l, 86781l, 86192l, 85616l,
  113270. 85051l, 84497l, 83953l, 83420l,
  113271. 82897l, 82384l, 81880l, 81385l,
  113272. 80899l, 80422l, 79953l, 79492l,
  113273. 79039l, 78594l, 78156l, 77726l,
  113274. 77302l, 76885l, 76475l, 76072l,
  113275. 75674l, 75283l, 74898l, 74519l,
  113276. 74146l, 73778l, 73415l, 73058l,
  113277. 72706l, 72359l, 72016l, 71679l,
  113278. 71347l, 71019l, 70695l, 70376l,
  113279. 70061l, 69750l, 69444l, 69141l,
  113280. 68842l, 68548l, 68256l, 67969l,
  113281. 67685l, 67405l, 67128l, 66855l,
  113282. 66585l, 66318l, 66054l, 65794l,
  113283. 65536l,
  113284. };
  113285. #define COS_LOOKUP_I_SHIFT 9
  113286. #define COS_LOOKUP_I_MASK 511
  113287. #define COS_LOOKUP_I_SZ 128
  113288. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113289. 16384l, 16379l, 16364l, 16340l,
  113290. 16305l, 16261l, 16207l, 16143l,
  113291. 16069l, 15986l, 15893l, 15791l,
  113292. 15679l, 15557l, 15426l, 15286l,
  113293. 15137l, 14978l, 14811l, 14635l,
  113294. 14449l, 14256l, 14053l, 13842l,
  113295. 13623l, 13395l, 13160l, 12916l,
  113296. 12665l, 12406l, 12140l, 11866l,
  113297. 11585l, 11297l, 11003l, 10702l,
  113298. 10394l, 10080l, 9760l, 9434l,
  113299. 9102l, 8765l, 8423l, 8076l,
  113300. 7723l, 7366l, 7005l, 6639l,
  113301. 6270l, 5897l, 5520l, 5139l,
  113302. 4756l, 4370l, 3981l, 3590l,
  113303. 3196l, 2801l, 2404l, 2006l,
  113304. 1606l, 1205l, 804l, 402l,
  113305. 0l, -401l, -803l, -1204l,
  113306. -1605l, -2005l, -2403l, -2800l,
  113307. -3195l, -3589l, -3980l, -4369l,
  113308. -4755l, -5138l, -5519l, -5896l,
  113309. -6269l, -6638l, -7004l, -7365l,
  113310. -7722l, -8075l, -8422l, -8764l,
  113311. -9101l, -9433l, -9759l, -10079l,
  113312. -10393l, -10701l, -11002l, -11296l,
  113313. -11584l, -11865l, -12139l, -12405l,
  113314. -12664l, -12915l, -13159l, -13394l,
  113315. -13622l, -13841l, -14052l, -14255l,
  113316. -14448l, -14634l, -14810l, -14977l,
  113317. -15136l, -15285l, -15425l, -15556l,
  113318. -15678l, -15790l, -15892l, -15985l,
  113319. -16068l, -16142l, -16206l, -16260l,
  113320. -16304l, -16339l, -16363l, -16378l,
  113321. -16383l,
  113322. };
  113323. #endif
  113324. #endif
  113325. /*** End of inlined file: lookup_data.h ***/
  113326. #ifdef FLOAT_LOOKUP
  113327. /* interpolated lookup based cos function, domain 0 to PI only */
  113328. float vorbis_coslook(float a){
  113329. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113330. int i=vorbis_ftoi(d-.5);
  113331. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113332. }
  113333. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113334. float vorbis_invsqlook(float a){
  113335. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113336. int i=vorbis_ftoi(d-.5f);
  113337. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113338. }
  113339. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113340. float vorbis_invsq2explook(int a){
  113341. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113342. }
  113343. #include <stdio.h>
  113344. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113345. float vorbis_fromdBlook(float a){
  113346. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113347. return (i<0)?1.f:
  113348. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113349. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113350. }
  113351. #endif
  113352. #ifdef INT_LOOKUP
  113353. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113354. 16.16 format
  113355. returns in m.8 format */
  113356. long vorbis_invsqlook_i(long a,long e){
  113357. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113358. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113359. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113360. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113361. d)>>16); /* result 1.16 */
  113362. e+=32;
  113363. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113364. e=(e>>1)-8;
  113365. return(val>>e);
  113366. }
  113367. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113368. /* a is in n.12 format */
  113369. float vorbis_fromdBlook_i(long a){
  113370. int i=(-a)>>(12-FROMdB2_SHIFT);
  113371. return (i<0)?1.f:
  113372. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113373. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113374. }
  113375. /* interpolated lookup based cos function, domain 0 to PI only */
  113376. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113377. long vorbis_coslook_i(long a){
  113378. int i=a>>COS_LOOKUP_I_SHIFT;
  113379. int d=a&COS_LOOKUP_I_MASK;
  113380. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113381. COS_LOOKUP_I_SHIFT);
  113382. }
  113383. #endif
  113384. #endif
  113385. /*** End of inlined file: lookup.c ***/
  113386. /* catch this in the build system; we #include for
  113387. compilers (like gcc) that can't inline across
  113388. modules */
  113389. /* side effect: changes *lsp to cosines of lsp */
  113390. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  113391. float amp,float ampoffset){
  113392. int i;
  113393. float wdel=M_PI/ln;
  113394. vorbis_fpu_control fpu;
  113395. (void) fpu; // to avoid an unused variable warning
  113396. vorbis_fpu_setround(&fpu);
  113397. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  113398. i=0;
  113399. while(i<n){
  113400. int k=map[i];
  113401. int qexp;
  113402. float p=.7071067812f;
  113403. float q=.7071067812f;
  113404. float w=vorbis_coslook(wdel*k);
  113405. float *ftmp=lsp;
  113406. int c=m>>1;
  113407. do{
  113408. q*=ftmp[0]-w;
  113409. p*=ftmp[1]-w;
  113410. ftmp+=2;
  113411. }while(--c);
  113412. if(m&1){
  113413. /* odd order filter; slightly assymetric */
  113414. /* the last coefficient */
  113415. q*=ftmp[0]-w;
  113416. q*=q;
  113417. p*=p*(1.f-w*w);
  113418. }else{
  113419. /* even order filter; still symmetric */
  113420. q*=q*(1.f+w);
  113421. p*=p*(1.f-w);
  113422. }
  113423. q=frexp(p+q,&qexp);
  113424. q=vorbis_fromdBlook(amp*
  113425. vorbis_invsqlook(q)*
  113426. vorbis_invsq2explook(qexp+m)-
  113427. ampoffset);
  113428. do{
  113429. curve[i++]*=q;
  113430. }while(map[i]==k);
  113431. }
  113432. vorbis_fpu_restore(fpu);
  113433. }
  113434. #else
  113435. #ifdef INT_LOOKUP
  113436. /*** Start of inlined file: lookup.c ***/
  113437. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113438. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113439. // tasks..
  113440. #if JUCE_MSVC
  113441. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113442. #endif
  113443. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113444. #if JUCE_USE_OGGVORBIS
  113445. #include <math.h>
  113446. /*** Start of inlined file: lookup.h ***/
  113447. #ifndef _V_LOOKUP_H_
  113448. #ifdef FLOAT_LOOKUP
  113449. extern float vorbis_coslook(float a);
  113450. extern float vorbis_invsqlook(float a);
  113451. extern float vorbis_invsq2explook(int a);
  113452. extern float vorbis_fromdBlook(float a);
  113453. #endif
  113454. #ifdef INT_LOOKUP
  113455. extern long vorbis_invsqlook_i(long a,long e);
  113456. extern long vorbis_coslook_i(long a);
  113457. extern float vorbis_fromdBlook_i(long a);
  113458. #endif
  113459. #endif
  113460. /*** End of inlined file: lookup.h ***/
  113461. /*** Start of inlined file: lookup_data.h ***/
  113462. #ifndef _V_LOOKUP_DATA_H_
  113463. #ifdef FLOAT_LOOKUP
  113464. #define COS_LOOKUP_SZ 128
  113465. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113466. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113467. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113468. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113469. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113470. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113471. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113472. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113473. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113474. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113475. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113476. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113477. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113478. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113479. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113480. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113481. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113482. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113483. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113484. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113485. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113486. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113487. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113488. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113489. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113490. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113491. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113492. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113493. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113494. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113495. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113496. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113497. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113498. -1.0000000000000f,
  113499. };
  113500. #define INVSQ_LOOKUP_SZ 32
  113501. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113502. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113503. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113504. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113505. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113506. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113507. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113508. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113509. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113510. 1.000000000000f,
  113511. };
  113512. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113513. #define INVSQ2EXP_LOOKUP_MAX 32
  113514. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113515. INVSQ2EXP_LOOKUP_MIN+1]={
  113516. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113517. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113518. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113519. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113520. 256.f, 181.019336f, 128.f, 90.50966799f,
  113521. 64.f, 45.254834f, 32.f, 22.627417f,
  113522. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113523. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113524. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113525. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113526. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113527. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113528. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113529. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113530. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113531. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113532. 1.525878906e-05f,
  113533. };
  113534. #endif
  113535. #define FROMdB_LOOKUP_SZ 35
  113536. #define FROMdB2_LOOKUP_SZ 32
  113537. #define FROMdB_SHIFT 5
  113538. #define FROMdB2_SHIFT 3
  113539. #define FROMdB2_MASK 31
  113540. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113541. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113542. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113543. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113544. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113545. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113546. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113547. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113548. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113549. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113550. };
  113551. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113552. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113553. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113554. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113555. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113556. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113557. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113558. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113559. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113560. };
  113561. #ifdef INT_LOOKUP
  113562. #define INVSQ_LOOKUP_I_SHIFT 10
  113563. #define INVSQ_LOOKUP_I_MASK 1023
  113564. static long INVSQ_LOOKUP_I[64+1]={
  113565. 92682l, 91966l, 91267l, 90583l,
  113566. 89915l, 89261l, 88621l, 87995l,
  113567. 87381l, 86781l, 86192l, 85616l,
  113568. 85051l, 84497l, 83953l, 83420l,
  113569. 82897l, 82384l, 81880l, 81385l,
  113570. 80899l, 80422l, 79953l, 79492l,
  113571. 79039l, 78594l, 78156l, 77726l,
  113572. 77302l, 76885l, 76475l, 76072l,
  113573. 75674l, 75283l, 74898l, 74519l,
  113574. 74146l, 73778l, 73415l, 73058l,
  113575. 72706l, 72359l, 72016l, 71679l,
  113576. 71347l, 71019l, 70695l, 70376l,
  113577. 70061l, 69750l, 69444l, 69141l,
  113578. 68842l, 68548l, 68256l, 67969l,
  113579. 67685l, 67405l, 67128l, 66855l,
  113580. 66585l, 66318l, 66054l, 65794l,
  113581. 65536l,
  113582. };
  113583. #define COS_LOOKUP_I_SHIFT 9
  113584. #define COS_LOOKUP_I_MASK 511
  113585. #define COS_LOOKUP_I_SZ 128
  113586. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113587. 16384l, 16379l, 16364l, 16340l,
  113588. 16305l, 16261l, 16207l, 16143l,
  113589. 16069l, 15986l, 15893l, 15791l,
  113590. 15679l, 15557l, 15426l, 15286l,
  113591. 15137l, 14978l, 14811l, 14635l,
  113592. 14449l, 14256l, 14053l, 13842l,
  113593. 13623l, 13395l, 13160l, 12916l,
  113594. 12665l, 12406l, 12140l, 11866l,
  113595. 11585l, 11297l, 11003l, 10702l,
  113596. 10394l, 10080l, 9760l, 9434l,
  113597. 9102l, 8765l, 8423l, 8076l,
  113598. 7723l, 7366l, 7005l, 6639l,
  113599. 6270l, 5897l, 5520l, 5139l,
  113600. 4756l, 4370l, 3981l, 3590l,
  113601. 3196l, 2801l, 2404l, 2006l,
  113602. 1606l, 1205l, 804l, 402l,
  113603. 0l, -401l, -803l, -1204l,
  113604. -1605l, -2005l, -2403l, -2800l,
  113605. -3195l, -3589l, -3980l, -4369l,
  113606. -4755l, -5138l, -5519l, -5896l,
  113607. -6269l, -6638l, -7004l, -7365l,
  113608. -7722l, -8075l, -8422l, -8764l,
  113609. -9101l, -9433l, -9759l, -10079l,
  113610. -10393l, -10701l, -11002l, -11296l,
  113611. -11584l, -11865l, -12139l, -12405l,
  113612. -12664l, -12915l, -13159l, -13394l,
  113613. -13622l, -13841l, -14052l, -14255l,
  113614. -14448l, -14634l, -14810l, -14977l,
  113615. -15136l, -15285l, -15425l, -15556l,
  113616. -15678l, -15790l, -15892l, -15985l,
  113617. -16068l, -16142l, -16206l, -16260l,
  113618. -16304l, -16339l, -16363l, -16378l,
  113619. -16383l,
  113620. };
  113621. #endif
  113622. #endif
  113623. /*** End of inlined file: lookup_data.h ***/
  113624. #ifdef FLOAT_LOOKUP
  113625. /* interpolated lookup based cos function, domain 0 to PI only */
  113626. float vorbis_coslook(float a){
  113627. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113628. int i=vorbis_ftoi(d-.5);
  113629. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113630. }
  113631. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113632. float vorbis_invsqlook(float a){
  113633. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113634. int i=vorbis_ftoi(d-.5f);
  113635. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113636. }
  113637. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113638. float vorbis_invsq2explook(int a){
  113639. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113640. }
  113641. #include <stdio.h>
  113642. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113643. float vorbis_fromdBlook(float a){
  113644. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113645. return (i<0)?1.f:
  113646. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113647. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113648. }
  113649. #endif
  113650. #ifdef INT_LOOKUP
  113651. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113652. 16.16 format
  113653. returns in m.8 format */
  113654. long vorbis_invsqlook_i(long a,long e){
  113655. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113656. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113657. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113658. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113659. d)>>16); /* result 1.16 */
  113660. e+=32;
  113661. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113662. e=(e>>1)-8;
  113663. return(val>>e);
  113664. }
  113665. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113666. /* a is in n.12 format */
  113667. float vorbis_fromdBlook_i(long a){
  113668. int i=(-a)>>(12-FROMdB2_SHIFT);
  113669. return (i<0)?1.f:
  113670. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113671. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113672. }
  113673. /* interpolated lookup based cos function, domain 0 to PI only */
  113674. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113675. long vorbis_coslook_i(long a){
  113676. int i=a>>COS_LOOKUP_I_SHIFT;
  113677. int d=a&COS_LOOKUP_I_MASK;
  113678. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113679. COS_LOOKUP_I_SHIFT);
  113680. }
  113681. #endif
  113682. #endif
  113683. /*** End of inlined file: lookup.c ***/
  113684. /* catch this in the build system; we #include for
  113685. compilers (like gcc) that can't inline across
  113686. modules */
  113687. static int MLOOP_1[64]={
  113688. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  113689. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  113690. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  113691. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  113692. };
  113693. static int MLOOP_2[64]={
  113694. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  113695. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  113696. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  113697. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  113698. };
  113699. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  113700. /* side effect: changes *lsp to cosines of lsp */
  113701. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  113702. float amp,float ampoffset){
  113703. /* 0 <= m < 256 */
  113704. /* set up for using all int later */
  113705. int i;
  113706. int ampoffseti=rint(ampoffset*4096.f);
  113707. int ampi=rint(amp*16.f);
  113708. long *ilsp=alloca(m*sizeof(*ilsp));
  113709. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  113710. i=0;
  113711. while(i<n){
  113712. int j,k=map[i];
  113713. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  113714. unsigned long qi=46341;
  113715. int qexp=0,shift;
  113716. long wi=vorbis_coslook_i(k*65536/ln);
  113717. qi*=labs(ilsp[0]-wi);
  113718. pi*=labs(ilsp[1]-wi);
  113719. for(j=3;j<m;j+=2){
  113720. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  113721. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  113722. shift=MLOOP_3[(pi|qi)>>16];
  113723. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  113724. pi=(pi>>shift)*labs(ilsp[j]-wi);
  113725. qexp+=shift;
  113726. }
  113727. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  113728. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  113729. shift=MLOOP_3[(pi|qi)>>16];
  113730. /* pi,qi normalized collectively, both tracked using qexp */
  113731. if(m&1){
  113732. /* odd order filter; slightly assymetric */
  113733. /* the last coefficient */
  113734. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  113735. pi=(pi>>shift)<<14;
  113736. qexp+=shift;
  113737. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  113738. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  113739. shift=MLOOP_3[(pi|qi)>>16];
  113740. pi>>=shift;
  113741. qi>>=shift;
  113742. qexp+=shift-14*((m+1)>>1);
  113743. pi=((pi*pi)>>16);
  113744. qi=((qi*qi)>>16);
  113745. qexp=qexp*2+m;
  113746. pi*=(1<<14)-((wi*wi)>>14);
  113747. qi+=pi>>14;
  113748. }else{
  113749. /* even order filter; still symmetric */
  113750. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  113751. worth tracking step by step */
  113752. pi>>=shift;
  113753. qi>>=shift;
  113754. qexp+=shift-7*m;
  113755. pi=((pi*pi)>>16);
  113756. qi=((qi*qi)>>16);
  113757. qexp=qexp*2+m;
  113758. pi*=(1<<14)-wi;
  113759. qi*=(1<<14)+wi;
  113760. qi=(qi+pi)>>14;
  113761. }
  113762. /* we've let the normalization drift because it wasn't important;
  113763. however, for the lookup, things must be normalized again. We
  113764. need at most one right shift or a number of left shifts */
  113765. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  113766. qi>>=1; qexp++;
  113767. }else
  113768. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  113769. qi<<=1; qexp--;
  113770. }
  113771. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  113772. vorbis_invsqlook_i(qi,qexp)-
  113773. /* m.8, m+n<=8 */
  113774. ampoffseti); /* 8.12[0] */
  113775. curve[i]*=amp;
  113776. while(map[++i]==k)curve[i]*=amp;
  113777. }
  113778. }
  113779. #else
  113780. /* old, nonoptimized but simple version for any poor sap who needs to
  113781. figure out what the hell this code does, or wants the other
  113782. fraction of a dB precision */
  113783. /* side effect: changes *lsp to cosines of lsp */
  113784. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  113785. float amp,float ampoffset){
  113786. int i;
  113787. float wdel=M_PI/ln;
  113788. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  113789. i=0;
  113790. while(i<n){
  113791. int j,k=map[i];
  113792. float p=.5f;
  113793. float q=.5f;
  113794. float w=2.f*cos(wdel*k);
  113795. for(j=1;j<m;j+=2){
  113796. q *= w-lsp[j-1];
  113797. p *= w-lsp[j];
  113798. }
  113799. if(j==m){
  113800. /* odd order filter; slightly assymetric */
  113801. /* the last coefficient */
  113802. q*=w-lsp[j-1];
  113803. p*=p*(4.f-w*w);
  113804. q*=q;
  113805. }else{
  113806. /* even order filter; still symmetric */
  113807. p*=p*(2.f-w);
  113808. q*=q*(2.f+w);
  113809. }
  113810. q=fromdB(amp/sqrt(p+q)-ampoffset);
  113811. curve[i]*=q;
  113812. while(map[++i]==k)curve[i]*=q;
  113813. }
  113814. }
  113815. #endif
  113816. #endif
  113817. static void cheby(float *g, int ord) {
  113818. int i, j;
  113819. g[0] *= .5f;
  113820. for(i=2; i<= ord; i++) {
  113821. for(j=ord; j >= i; j--) {
  113822. g[j-2] -= g[j];
  113823. g[j] += g[j];
  113824. }
  113825. }
  113826. }
  113827. static int comp(const void *a,const void *b){
  113828. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  113829. }
  113830. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  113831. but there are root sets for which it gets into limit cycles
  113832. (exacerbated by zero suppression) and fails. We can't afford to
  113833. fail, even if the failure is 1 in 100,000,000, so we now use
  113834. Laguerre and later polish with Newton-Raphson (which can then
  113835. afford to fail) */
  113836. #define EPSILON 10e-7
  113837. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  113838. int i,m;
  113839. double lastdelta=0.f;
  113840. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  113841. for(i=0;i<=ord;i++)defl[i]=a[i];
  113842. for(m=ord;m>0;m--){
  113843. double newx=0.f,delta;
  113844. /* iterate a root */
  113845. while(1){
  113846. double p=defl[m],pp=0.f,ppp=0.f,denom;
  113847. /* eval the polynomial and its first two derivatives */
  113848. for(i=m;i>0;i--){
  113849. ppp = newx*ppp + pp;
  113850. pp = newx*pp + p;
  113851. p = newx*p + defl[i-1];
  113852. }
  113853. /* Laguerre's method */
  113854. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  113855. if(denom<0)
  113856. return(-1); /* complex root! The LPC generator handed us a bad filter */
  113857. if(pp>0){
  113858. denom = pp + sqrt(denom);
  113859. if(denom<EPSILON)denom=EPSILON;
  113860. }else{
  113861. denom = pp - sqrt(denom);
  113862. if(denom>-(EPSILON))denom=-(EPSILON);
  113863. }
  113864. delta = m*p/denom;
  113865. newx -= delta;
  113866. if(delta<0.f)delta*=-1;
  113867. if(fabs(delta/newx)<10e-12)break;
  113868. lastdelta=delta;
  113869. }
  113870. r[m-1]=newx;
  113871. /* forward deflation */
  113872. for(i=m;i>0;i--)
  113873. defl[i-1]+=newx*defl[i];
  113874. defl++;
  113875. }
  113876. return(0);
  113877. }
  113878. /* for spit-and-polish only */
  113879. static int Newton_Raphson(float *a,int ord,float *r){
  113880. int i, k, count=0;
  113881. double error=1.f;
  113882. double *root=(double*)alloca(ord*sizeof(*root));
  113883. for(i=0; i<ord;i++) root[i] = r[i];
  113884. while(error>1e-20){
  113885. error=0;
  113886. for(i=0; i<ord; i++) { /* Update each point. */
  113887. double pp=0.,delta;
  113888. double rooti=root[i];
  113889. double p=a[ord];
  113890. for(k=ord-1; k>= 0; k--) {
  113891. pp= pp* rooti + p;
  113892. p = p * rooti + a[k];
  113893. }
  113894. delta = p/pp;
  113895. root[i] -= delta;
  113896. error+= delta*delta;
  113897. }
  113898. if(count>40)return(-1);
  113899. count++;
  113900. }
  113901. /* Replaced the original bubble sort with a real sort. With your
  113902. help, we can eliminate the bubble sort in our lifetime. --Monty */
  113903. for(i=0; i<ord;i++) r[i] = root[i];
  113904. return(0);
  113905. }
  113906. /* Convert lpc coefficients to lsp coefficients */
  113907. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  113908. int order2=(m+1)>>1;
  113909. int g1_order,g2_order;
  113910. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  113911. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  113912. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  113913. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  113914. int i;
  113915. /* even and odd are slightly different base cases */
  113916. g1_order=(m+1)>>1;
  113917. g2_order=(m) >>1;
  113918. /* Compute the lengths of the x polynomials. */
  113919. /* Compute the first half of K & R F1 & F2 polynomials. */
  113920. /* Compute half of the symmetric and antisymmetric polynomials. */
  113921. /* Remove the roots at +1 and -1. */
  113922. g1[g1_order] = 1.f;
  113923. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  113924. g2[g2_order] = 1.f;
  113925. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  113926. if(g1_order>g2_order){
  113927. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  113928. }else{
  113929. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  113930. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  113931. }
  113932. /* Convert into polynomials in cos(alpha) */
  113933. cheby(g1,g1_order);
  113934. cheby(g2,g2_order);
  113935. /* Find the roots of the 2 even polynomials.*/
  113936. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  113937. Laguerre_With_Deflation(g2,g2_order,g2r))
  113938. return(-1);
  113939. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  113940. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  113941. qsort(g1r,g1_order,sizeof(*g1r),comp);
  113942. qsort(g2r,g2_order,sizeof(*g2r),comp);
  113943. for(i=0;i<g1_order;i++)
  113944. lsp[i*2] = acos(g1r[i]);
  113945. for(i=0;i<g2_order;i++)
  113946. lsp[i*2+1] = acos(g2r[i]);
  113947. return(0);
  113948. }
  113949. #endif
  113950. /*** End of inlined file: lsp.c ***/
  113951. /*** Start of inlined file: mapping0.c ***/
  113952. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113953. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113954. // tasks..
  113955. #if JUCE_MSVC
  113956. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113957. #endif
  113958. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113959. #if JUCE_USE_OGGVORBIS
  113960. #include <stdlib.h>
  113961. #include <stdio.h>
  113962. #include <string.h>
  113963. #include <math.h>
  113964. /* simplistic, wasteful way of doing this (unique lookup for each
  113965. mode/submapping); there should be a central repository for
  113966. identical lookups. That will require minor work, so I'm putting it
  113967. off as low priority.
  113968. Why a lookup for each backend in a given mode? Because the
  113969. blocksize is set by the mode, and low backend lookups may require
  113970. parameters from other areas of the mode/mapping */
  113971. static void mapping0_free_info(vorbis_info_mapping *i){
  113972. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  113973. if(info){
  113974. memset(info,0,sizeof(*info));
  113975. _ogg_free(info);
  113976. }
  113977. }
  113978. static int ilog3(unsigned int v){
  113979. int ret=0;
  113980. if(v)--v;
  113981. while(v){
  113982. ret++;
  113983. v>>=1;
  113984. }
  113985. return(ret);
  113986. }
  113987. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  113988. oggpack_buffer *opb){
  113989. int i;
  113990. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  113991. /* another 'we meant to do it this way' hack... up to beta 4, we
  113992. packed 4 binary zeros here to signify one submapping in use. We
  113993. now redefine that to mean four bitflags that indicate use of
  113994. deeper features; bit0:submappings, bit1:coupling,
  113995. bit2,3:reserved. This is backward compatable with all actual uses
  113996. of the beta code. */
  113997. if(info->submaps>1){
  113998. oggpack_write(opb,1,1);
  113999. oggpack_write(opb,info->submaps-1,4);
  114000. }else
  114001. oggpack_write(opb,0,1);
  114002. if(info->coupling_steps>0){
  114003. oggpack_write(opb,1,1);
  114004. oggpack_write(opb,info->coupling_steps-1,8);
  114005. for(i=0;i<info->coupling_steps;i++){
  114006. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114007. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114008. }
  114009. }else
  114010. oggpack_write(opb,0,1);
  114011. oggpack_write(opb,0,2); /* 2,3:reserved */
  114012. /* we don't write the channel submappings if we only have one... */
  114013. if(info->submaps>1){
  114014. for(i=0;i<vi->channels;i++)
  114015. oggpack_write(opb,info->chmuxlist[i],4);
  114016. }
  114017. for(i=0;i<info->submaps;i++){
  114018. oggpack_write(opb,0,8); /* time submap unused */
  114019. oggpack_write(opb,info->floorsubmap[i],8);
  114020. oggpack_write(opb,info->residuesubmap[i],8);
  114021. }
  114022. }
  114023. /* also responsible for range checking */
  114024. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114025. int i;
  114026. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114027. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114028. memset(info,0,sizeof(*info));
  114029. if(oggpack_read(opb,1))
  114030. info->submaps=oggpack_read(opb,4)+1;
  114031. else
  114032. info->submaps=1;
  114033. if(oggpack_read(opb,1)){
  114034. info->coupling_steps=oggpack_read(opb,8)+1;
  114035. for(i=0;i<info->coupling_steps;i++){
  114036. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114037. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114038. if(testM<0 ||
  114039. testA<0 ||
  114040. testM==testA ||
  114041. testM>=vi->channels ||
  114042. testA>=vi->channels) goto err_out;
  114043. }
  114044. }
  114045. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114046. if(info->submaps>1){
  114047. for(i=0;i<vi->channels;i++){
  114048. info->chmuxlist[i]=oggpack_read(opb,4);
  114049. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114050. }
  114051. }
  114052. for(i=0;i<info->submaps;i++){
  114053. oggpack_read(opb,8); /* time submap unused */
  114054. info->floorsubmap[i]=oggpack_read(opb,8);
  114055. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114056. info->residuesubmap[i]=oggpack_read(opb,8);
  114057. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114058. }
  114059. return info;
  114060. err_out:
  114061. mapping0_free_info(info);
  114062. return(NULL);
  114063. }
  114064. #if 0
  114065. static long seq=0;
  114066. static ogg_int64_t total=0;
  114067. static float FLOOR1_fromdB_LOOKUP[256]={
  114068. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114069. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114070. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114071. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114072. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114073. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114074. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114075. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114076. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114077. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114078. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114079. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114080. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114081. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114082. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114083. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114084. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114085. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114086. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114087. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114088. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114089. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114090. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114091. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114092. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114093. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114094. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114095. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114096. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114097. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114098. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114099. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114100. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114101. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114102. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114103. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114104. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114105. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114106. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114107. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114108. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114109. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114110. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114111. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114112. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114113. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114114. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114115. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114116. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114117. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114118. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114119. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114120. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114121. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114122. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114123. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114124. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114125. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114126. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114127. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114128. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114129. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114130. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114131. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114132. };
  114133. #endif
  114134. extern int *floor1_fit(vorbis_block *vb,void *look,
  114135. const float *logmdct, /* in */
  114136. const float *logmask);
  114137. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  114138. int *A,int *B,
  114139. int del);
  114140. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  114141. void*look,
  114142. int *post,int *ilogmask);
  114143. static int mapping0_forward(vorbis_block *vb){
  114144. vorbis_dsp_state *vd=vb->vd;
  114145. vorbis_info *vi=vd->vi;
  114146. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114147. private_state *b=(private_state*)vb->vd->backend_state;
  114148. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  114149. int n=vb->pcmend;
  114150. int i,j,k;
  114151. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  114152. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  114153. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  114154. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  114155. float global_ampmax=vbi->ampmax;
  114156. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  114157. int blocktype=vbi->blocktype;
  114158. int modenumber=vb->W;
  114159. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  114160. vorbis_look_psy *psy_look=
  114161. b->psy+blocktype+(vb->W?2:0);
  114162. vb->mode=modenumber;
  114163. for(i=0;i<vi->channels;i++){
  114164. float scale=4.f/n;
  114165. float scale_dB;
  114166. float *pcm =vb->pcm[i];
  114167. float *logfft =pcm;
  114168. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114169. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  114170. todB estimation used on IEEE 754
  114171. compliant machines had a bug that
  114172. returned dB values about a third
  114173. of a decibel too high. The bug
  114174. was harmless because tunings
  114175. implicitly took that into
  114176. account. However, fixing the bug
  114177. in the estimator requires
  114178. changing all the tunings as well.
  114179. For now, it's easier to sync
  114180. things back up here, and
  114181. recalibrate the tunings in the
  114182. next major model upgrade. */
  114183. #if 0
  114184. if(vi->channels==2)
  114185. if(i==0)
  114186. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  114187. else
  114188. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  114189. #endif
  114190. /* window the PCM data */
  114191. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  114192. #if 0
  114193. if(vi->channels==2)
  114194. if(i==0)
  114195. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  114196. else
  114197. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  114198. #endif
  114199. /* transform the PCM data */
  114200. /* only MDCT right now.... */
  114201. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  114202. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  114203. drft_forward(&b->fft_look[vb->W],pcm);
  114204. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  114205. original todB estimation used on
  114206. IEEE 754 compliant machines had a
  114207. bug that returned dB values about
  114208. a third of a decibel too high.
  114209. The bug was harmless because
  114210. tunings implicitly took that into
  114211. account. However, fixing the bug
  114212. in the estimator requires
  114213. changing all the tunings as well.
  114214. For now, it's easier to sync
  114215. things back up here, and
  114216. recalibrate the tunings in the
  114217. next major model upgrade. */
  114218. local_ampmax[i]=logfft[0];
  114219. for(j=1;j<n-1;j+=2){
  114220. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  114221. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  114222. .345 is a hack; the original todB
  114223. estimation used on IEEE 754
  114224. compliant machines had a bug that
  114225. returned dB values about a third
  114226. of a decibel too high. The bug
  114227. was harmless because tunings
  114228. implicitly took that into
  114229. account. However, fixing the bug
  114230. in the estimator requires
  114231. changing all the tunings as well.
  114232. For now, it's easier to sync
  114233. things back up here, and
  114234. recalibrate the tunings in the
  114235. next major model upgrade. */
  114236. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  114237. }
  114238. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  114239. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  114240. #if 0
  114241. if(vi->channels==2){
  114242. if(i==0){
  114243. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  114244. }else{
  114245. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  114246. }
  114247. }
  114248. #endif
  114249. }
  114250. {
  114251. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  114252. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  114253. for(i=0;i<vi->channels;i++){
  114254. /* the encoder setup assumes that all the modes used by any
  114255. specific bitrate tweaking use the same floor */
  114256. int submap=info->chmuxlist[i];
  114257. /* the following makes things clearer to *me* anyway */
  114258. float *mdct =gmdct[i];
  114259. float *logfft =vb->pcm[i];
  114260. float *logmdct =logfft+n/2;
  114261. float *logmask =logfft;
  114262. vb->mode=modenumber;
  114263. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  114264. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  114265. for(j=0;j<n/2;j++)
  114266. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  114267. todB estimation used on IEEE 754
  114268. compliant machines had a bug that
  114269. returned dB values about a third
  114270. of a decibel too high. The bug
  114271. was harmless because tunings
  114272. implicitly took that into
  114273. account. However, fixing the bug
  114274. in the estimator requires
  114275. changing all the tunings as well.
  114276. For now, it's easier to sync
  114277. things back up here, and
  114278. recalibrate the tunings in the
  114279. next major model upgrade. */
  114280. #if 0
  114281. if(vi->channels==2){
  114282. if(i==0)
  114283. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  114284. else
  114285. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  114286. }else{
  114287. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  114288. }
  114289. #endif
  114290. /* first step; noise masking. Not only does 'noise masking'
  114291. give us curves from which we can decide how much resolution
  114292. to give noise parts of the spectrum, it also implicitly hands
  114293. us a tonality estimate (the larger the value in the
  114294. 'noise_depth' vector, the more tonal that area is) */
  114295. _vp_noisemask(psy_look,
  114296. logmdct,
  114297. noise); /* noise does not have by-frequency offset
  114298. bias applied yet */
  114299. #if 0
  114300. if(vi->channels==2){
  114301. if(i==0)
  114302. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  114303. else
  114304. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  114305. }
  114306. #endif
  114307. /* second step: 'all the other crap'; all the stuff that isn't
  114308. computed/fit for bitrate management goes in the second psy
  114309. vector. This includes tone masking, peak limiting and ATH */
  114310. _vp_tonemask(psy_look,
  114311. logfft,
  114312. tone,
  114313. global_ampmax,
  114314. local_ampmax[i]);
  114315. #if 0
  114316. if(vi->channels==2){
  114317. if(i==0)
  114318. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  114319. else
  114320. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  114321. }
  114322. #endif
  114323. /* third step; we offset the noise vectors, overlay tone
  114324. masking. We then do a floor1-specific line fit. If we're
  114325. performing bitrate management, the line fit is performed
  114326. multiple times for up/down tweakage on demand. */
  114327. #if 0
  114328. {
  114329. float aotuv[psy_look->n];
  114330. #endif
  114331. _vp_offset_and_mix(psy_look,
  114332. noise,
  114333. tone,
  114334. 1,
  114335. logmask,
  114336. mdct,
  114337. logmdct);
  114338. #if 0
  114339. if(vi->channels==2){
  114340. if(i==0)
  114341. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  114342. else
  114343. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  114344. }
  114345. }
  114346. #endif
  114347. #if 0
  114348. if(vi->channels==2){
  114349. if(i==0)
  114350. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  114351. else
  114352. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  114353. }
  114354. #endif
  114355. /* this algorithm is hardwired to floor 1 for now; abort out if
  114356. we're *not* floor1. This won't happen unless someone has
  114357. broken the encode setup lib. Guard it anyway. */
  114358. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  114359. floor_posts[i][PACKETBLOBS/2]=
  114360. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114361. logmdct,
  114362. logmask);
  114363. /* are we managing bitrate? If so, perform two more fits for
  114364. later rate tweaking (fits represent hi/lo) */
  114365. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  114366. /* higher rate by way of lower noise curve */
  114367. _vp_offset_and_mix(psy_look,
  114368. noise,
  114369. tone,
  114370. 2,
  114371. logmask,
  114372. mdct,
  114373. logmdct);
  114374. #if 0
  114375. if(vi->channels==2){
  114376. if(i==0)
  114377. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  114378. else
  114379. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  114380. }
  114381. #endif
  114382. floor_posts[i][PACKETBLOBS-1]=
  114383. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114384. logmdct,
  114385. logmask);
  114386. /* lower rate by way of higher noise curve */
  114387. _vp_offset_and_mix(psy_look,
  114388. noise,
  114389. tone,
  114390. 0,
  114391. logmask,
  114392. mdct,
  114393. logmdct);
  114394. #if 0
  114395. if(vi->channels==2)
  114396. if(i==0)
  114397. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  114398. else
  114399. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  114400. #endif
  114401. floor_posts[i][0]=
  114402. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114403. logmdct,
  114404. logmask);
  114405. /* we also interpolate a range of intermediate curves for
  114406. intermediate rates */
  114407. for(k=1;k<PACKETBLOBS/2;k++)
  114408. floor_posts[i][k]=
  114409. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  114410. floor_posts[i][0],
  114411. floor_posts[i][PACKETBLOBS/2],
  114412. k*65536/(PACKETBLOBS/2));
  114413. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  114414. floor_posts[i][k]=
  114415. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  114416. floor_posts[i][PACKETBLOBS/2],
  114417. floor_posts[i][PACKETBLOBS-1],
  114418. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  114419. }
  114420. }
  114421. }
  114422. vbi->ampmax=global_ampmax;
  114423. /*
  114424. the next phases are performed once for vbr-only and PACKETBLOB
  114425. times for bitrate managed modes.
  114426. 1) encode actual mode being used
  114427. 2) encode the floor for each channel, compute coded mask curve/res
  114428. 3) normalize and couple.
  114429. 4) encode residue
  114430. 5) save packet bytes to the packetblob vector
  114431. */
  114432. /* iterate over the many masking curve fits we've created */
  114433. {
  114434. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  114435. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  114436. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  114437. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  114438. float **mag_memo;
  114439. int **mag_sort;
  114440. if(info->coupling_steps){
  114441. mag_memo=_vp_quantize_couple_memo(vb,
  114442. &ci->psy_g_param,
  114443. psy_look,
  114444. info,
  114445. gmdct);
  114446. mag_sort=_vp_quantize_couple_sort(vb,
  114447. psy_look,
  114448. info,
  114449. mag_memo);
  114450. hf_reduction(&ci->psy_g_param,
  114451. psy_look,
  114452. info,
  114453. mag_memo);
  114454. }
  114455. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  114456. if(psy_look->vi->normal_channel_p){
  114457. for(i=0;i<vi->channels;i++){
  114458. float *mdct =gmdct[i];
  114459. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  114460. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  114461. }
  114462. }
  114463. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  114464. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  114465. k++){
  114466. oggpack_buffer *opb=vbi->packetblob[k];
  114467. /* start out our new packet blob with packet type and mode */
  114468. /* Encode the packet type */
  114469. oggpack_write(opb,0,1);
  114470. /* Encode the modenumber */
  114471. /* Encode frame mode, pre,post windowsize, then dispatch */
  114472. oggpack_write(opb,modenumber,b->modebits);
  114473. if(vb->W){
  114474. oggpack_write(opb,vb->lW,1);
  114475. oggpack_write(opb,vb->nW,1);
  114476. }
  114477. /* encode floor, compute masking curve, sep out residue */
  114478. for(i=0;i<vi->channels;i++){
  114479. int submap=info->chmuxlist[i];
  114480. float *mdct =gmdct[i];
  114481. float *res =vb->pcm[i];
  114482. int *ilogmask=ilogmaskch[i]=
  114483. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114484. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  114485. floor_posts[i][k],
  114486. ilogmask);
  114487. #if 0
  114488. {
  114489. char buf[80];
  114490. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  114491. float work[n/2];
  114492. for(j=0;j<n/2;j++)
  114493. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  114494. _analysis_output(buf,seq,work,n/2,1,1,0);
  114495. }
  114496. #endif
  114497. _vp_remove_floor(psy_look,
  114498. mdct,
  114499. ilogmask,
  114500. res,
  114501. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  114502. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  114503. #if 0
  114504. {
  114505. char buf[80];
  114506. float work[n/2];
  114507. for(j=0;j<n/2;j++)
  114508. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  114509. sprintf(buf,"resI%c%d",i?'R':'L',k);
  114510. _analysis_output(buf,seq,work,n/2,1,1,0);
  114511. }
  114512. #endif
  114513. }
  114514. /* our iteration is now based on masking curve, not prequant and
  114515. coupling. Only one prequant/coupling step */
  114516. /* quantize/couple */
  114517. /* incomplete implementation that assumes the tree is all depth
  114518. one, or no tree at all */
  114519. if(info->coupling_steps){
  114520. _vp_couple(k,
  114521. &ci->psy_g_param,
  114522. psy_look,
  114523. info,
  114524. vb->pcm,
  114525. mag_memo,
  114526. mag_sort,
  114527. ilogmaskch,
  114528. nonzero,
  114529. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  114530. }
  114531. /* classify and encode by submap */
  114532. for(i=0;i<info->submaps;i++){
  114533. int ch_in_bundle=0;
  114534. long **classifications;
  114535. int resnum=info->residuesubmap[i];
  114536. for(j=0;j<vi->channels;j++){
  114537. if(info->chmuxlist[j]==i){
  114538. zerobundle[ch_in_bundle]=0;
  114539. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  114540. res_bundle[ch_in_bundle]=vb->pcm[j];
  114541. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  114542. }
  114543. }
  114544. classifications=_residue_P[ci->residue_type[resnum]]->
  114545. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  114546. _residue_P[ci->residue_type[resnum]]->
  114547. forward(opb,vb,b->residue[resnum],
  114548. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  114549. }
  114550. /* ok, done encoding. Next protopacket. */
  114551. }
  114552. }
  114553. #if 0
  114554. seq++;
  114555. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  114556. #endif
  114557. return(0);
  114558. }
  114559. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  114560. vorbis_dsp_state *vd=vb->vd;
  114561. vorbis_info *vi=vd->vi;
  114562. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  114563. private_state *b=(private_state*)vd->backend_state;
  114564. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  114565. int i,j;
  114566. long n=vb->pcmend=ci->blocksizes[vb->W];
  114567. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  114568. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  114569. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  114570. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  114571. /* recover the spectral envelope; store it in the PCM vector for now */
  114572. for(i=0;i<vi->channels;i++){
  114573. int submap=info->chmuxlist[i];
  114574. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  114575. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  114576. if(floormemo[i])
  114577. nonzero[i]=1;
  114578. else
  114579. nonzero[i]=0;
  114580. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  114581. }
  114582. /* channel coupling can 'dirty' the nonzero listing */
  114583. for(i=0;i<info->coupling_steps;i++){
  114584. if(nonzero[info->coupling_mag[i]] ||
  114585. nonzero[info->coupling_ang[i]]){
  114586. nonzero[info->coupling_mag[i]]=1;
  114587. nonzero[info->coupling_ang[i]]=1;
  114588. }
  114589. }
  114590. /* recover the residue into our working vectors */
  114591. for(i=0;i<info->submaps;i++){
  114592. int ch_in_bundle=0;
  114593. for(j=0;j<vi->channels;j++){
  114594. if(info->chmuxlist[j]==i){
  114595. if(nonzero[j])
  114596. zerobundle[ch_in_bundle]=1;
  114597. else
  114598. zerobundle[ch_in_bundle]=0;
  114599. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  114600. }
  114601. }
  114602. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  114603. inverse(vb,b->residue[info->residuesubmap[i]],
  114604. pcmbundle,zerobundle,ch_in_bundle);
  114605. }
  114606. /* channel coupling */
  114607. for(i=info->coupling_steps-1;i>=0;i--){
  114608. float *pcmM=vb->pcm[info->coupling_mag[i]];
  114609. float *pcmA=vb->pcm[info->coupling_ang[i]];
  114610. for(j=0;j<n/2;j++){
  114611. float mag=pcmM[j];
  114612. float ang=pcmA[j];
  114613. if(mag>0)
  114614. if(ang>0){
  114615. pcmM[j]=mag;
  114616. pcmA[j]=mag-ang;
  114617. }else{
  114618. pcmA[j]=mag;
  114619. pcmM[j]=mag+ang;
  114620. }
  114621. else
  114622. if(ang>0){
  114623. pcmM[j]=mag;
  114624. pcmA[j]=mag+ang;
  114625. }else{
  114626. pcmA[j]=mag;
  114627. pcmM[j]=mag-ang;
  114628. }
  114629. }
  114630. }
  114631. /* compute and apply spectral envelope */
  114632. for(i=0;i<vi->channels;i++){
  114633. float *pcm=vb->pcm[i];
  114634. int submap=info->chmuxlist[i];
  114635. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  114636. inverse2(vb,b->flr[info->floorsubmap[submap]],
  114637. floormemo[i],pcm);
  114638. }
  114639. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  114640. /* only MDCT right now.... */
  114641. for(i=0;i<vi->channels;i++){
  114642. float *pcm=vb->pcm[i];
  114643. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  114644. }
  114645. /* all done! */
  114646. return(0);
  114647. }
  114648. /* export hooks */
  114649. vorbis_func_mapping mapping0_exportbundle={
  114650. &mapping0_pack,
  114651. &mapping0_unpack,
  114652. &mapping0_free_info,
  114653. &mapping0_forward,
  114654. &mapping0_inverse
  114655. };
  114656. #endif
  114657. /*** End of inlined file: mapping0.c ***/
  114658. /*** Start of inlined file: mdct.c ***/
  114659. /* this can also be run as an integer transform by uncommenting a
  114660. define in mdct.h; the integerization is a first pass and although
  114661. it's likely stable for Vorbis, the dynamic range is constrained and
  114662. roundoff isn't done (so it's noisy). Consider it functional, but
  114663. only a starting point. There's no point on a machine with an FPU */
  114664. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114665. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114666. // tasks..
  114667. #if JUCE_MSVC
  114668. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114669. #endif
  114670. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114671. #if JUCE_USE_OGGVORBIS
  114672. #include <stdio.h>
  114673. #include <stdlib.h>
  114674. #include <string.h>
  114675. #include <math.h>
  114676. /* build lookups for trig functions; also pre-figure scaling and
  114677. some window function algebra. */
  114678. void mdct_init(mdct_lookup *lookup,int n){
  114679. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  114680. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  114681. int i;
  114682. int n2=n>>1;
  114683. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  114684. lookup->n=n;
  114685. lookup->trig=T;
  114686. lookup->bitrev=bitrev;
  114687. /* trig lookups... */
  114688. for(i=0;i<n/4;i++){
  114689. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  114690. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  114691. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  114692. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  114693. }
  114694. for(i=0;i<n/8;i++){
  114695. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  114696. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  114697. }
  114698. /* bitreverse lookup... */
  114699. {
  114700. int mask=(1<<(log2n-1))-1,i,j;
  114701. int msb=1<<(log2n-2);
  114702. for(i=0;i<n/8;i++){
  114703. int acc=0;
  114704. for(j=0;msb>>j;j++)
  114705. if((msb>>j)&i)acc|=1<<j;
  114706. bitrev[i*2]=((~acc)&mask)-1;
  114707. bitrev[i*2+1]=acc;
  114708. }
  114709. }
  114710. lookup->scale=FLOAT_CONV(4.f/n);
  114711. }
  114712. /* 8 point butterfly (in place, 4 register) */
  114713. STIN void mdct_butterfly_8(DATA_TYPE *x){
  114714. REG_TYPE r0 = x[6] + x[2];
  114715. REG_TYPE r1 = x[6] - x[2];
  114716. REG_TYPE r2 = x[4] + x[0];
  114717. REG_TYPE r3 = x[4] - x[0];
  114718. x[6] = r0 + r2;
  114719. x[4] = r0 - r2;
  114720. r0 = x[5] - x[1];
  114721. r2 = x[7] - x[3];
  114722. x[0] = r1 + r0;
  114723. x[2] = r1 - r0;
  114724. r0 = x[5] + x[1];
  114725. r1 = x[7] + x[3];
  114726. x[3] = r2 + r3;
  114727. x[1] = r2 - r3;
  114728. x[7] = r1 + r0;
  114729. x[5] = r1 - r0;
  114730. }
  114731. /* 16 point butterfly (in place, 4 register) */
  114732. STIN void mdct_butterfly_16(DATA_TYPE *x){
  114733. REG_TYPE r0 = x[1] - x[9];
  114734. REG_TYPE r1 = x[0] - x[8];
  114735. x[8] += x[0];
  114736. x[9] += x[1];
  114737. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  114738. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  114739. r0 = x[3] - x[11];
  114740. r1 = x[10] - x[2];
  114741. x[10] += x[2];
  114742. x[11] += x[3];
  114743. x[2] = r0;
  114744. x[3] = r1;
  114745. r0 = x[12] - x[4];
  114746. r1 = x[13] - x[5];
  114747. x[12] += x[4];
  114748. x[13] += x[5];
  114749. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  114750. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  114751. r0 = x[14] - x[6];
  114752. r1 = x[15] - x[7];
  114753. x[14] += x[6];
  114754. x[15] += x[7];
  114755. x[6] = r0;
  114756. x[7] = r1;
  114757. mdct_butterfly_8(x);
  114758. mdct_butterfly_8(x+8);
  114759. }
  114760. /* 32 point butterfly (in place, 4 register) */
  114761. STIN void mdct_butterfly_32(DATA_TYPE *x){
  114762. REG_TYPE r0 = x[30] - x[14];
  114763. REG_TYPE r1 = x[31] - x[15];
  114764. x[30] += x[14];
  114765. x[31] += x[15];
  114766. x[14] = r0;
  114767. x[15] = r1;
  114768. r0 = x[28] - x[12];
  114769. r1 = x[29] - x[13];
  114770. x[28] += x[12];
  114771. x[29] += x[13];
  114772. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  114773. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  114774. r0 = x[26] - x[10];
  114775. r1 = x[27] - x[11];
  114776. x[26] += x[10];
  114777. x[27] += x[11];
  114778. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  114779. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  114780. r0 = x[24] - x[8];
  114781. r1 = x[25] - x[9];
  114782. x[24] += x[8];
  114783. x[25] += x[9];
  114784. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  114785. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  114786. r0 = x[22] - x[6];
  114787. r1 = x[7] - x[23];
  114788. x[22] += x[6];
  114789. x[23] += x[7];
  114790. x[6] = r1;
  114791. x[7] = r0;
  114792. r0 = x[4] - x[20];
  114793. r1 = x[5] - x[21];
  114794. x[20] += x[4];
  114795. x[21] += x[5];
  114796. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  114797. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  114798. r0 = x[2] - x[18];
  114799. r1 = x[3] - x[19];
  114800. x[18] += x[2];
  114801. x[19] += x[3];
  114802. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  114803. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  114804. r0 = x[0] - x[16];
  114805. r1 = x[1] - x[17];
  114806. x[16] += x[0];
  114807. x[17] += x[1];
  114808. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  114809. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  114810. mdct_butterfly_16(x);
  114811. mdct_butterfly_16(x+16);
  114812. }
  114813. /* N point first stage butterfly (in place, 2 register) */
  114814. STIN void mdct_butterfly_first(DATA_TYPE *T,
  114815. DATA_TYPE *x,
  114816. int points){
  114817. DATA_TYPE *x1 = x + points - 8;
  114818. DATA_TYPE *x2 = x + (points>>1) - 8;
  114819. REG_TYPE r0;
  114820. REG_TYPE r1;
  114821. do{
  114822. r0 = x1[6] - x2[6];
  114823. r1 = x1[7] - x2[7];
  114824. x1[6] += x2[6];
  114825. x1[7] += x2[7];
  114826. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  114827. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  114828. r0 = x1[4] - x2[4];
  114829. r1 = x1[5] - x2[5];
  114830. x1[4] += x2[4];
  114831. x1[5] += x2[5];
  114832. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  114833. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  114834. r0 = x1[2] - x2[2];
  114835. r1 = x1[3] - x2[3];
  114836. x1[2] += x2[2];
  114837. x1[3] += x2[3];
  114838. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  114839. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  114840. r0 = x1[0] - x2[0];
  114841. r1 = x1[1] - x2[1];
  114842. x1[0] += x2[0];
  114843. x1[1] += x2[1];
  114844. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  114845. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  114846. x1-=8;
  114847. x2-=8;
  114848. T+=16;
  114849. }while(x2>=x);
  114850. }
  114851. /* N/stage point generic N stage butterfly (in place, 2 register) */
  114852. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  114853. DATA_TYPE *x,
  114854. int points,
  114855. int trigint){
  114856. DATA_TYPE *x1 = x + points - 8;
  114857. DATA_TYPE *x2 = x + (points>>1) - 8;
  114858. REG_TYPE r0;
  114859. REG_TYPE r1;
  114860. do{
  114861. r0 = x1[6] - x2[6];
  114862. r1 = x1[7] - x2[7];
  114863. x1[6] += x2[6];
  114864. x1[7] += x2[7];
  114865. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  114866. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  114867. T+=trigint;
  114868. r0 = x1[4] - x2[4];
  114869. r1 = x1[5] - x2[5];
  114870. x1[4] += x2[4];
  114871. x1[5] += x2[5];
  114872. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  114873. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  114874. T+=trigint;
  114875. r0 = x1[2] - x2[2];
  114876. r1 = x1[3] - x2[3];
  114877. x1[2] += x2[2];
  114878. x1[3] += x2[3];
  114879. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  114880. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  114881. T+=trigint;
  114882. r0 = x1[0] - x2[0];
  114883. r1 = x1[1] - x2[1];
  114884. x1[0] += x2[0];
  114885. x1[1] += x2[1];
  114886. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  114887. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  114888. T+=trigint;
  114889. x1-=8;
  114890. x2-=8;
  114891. }while(x2>=x);
  114892. }
  114893. STIN void mdct_butterflies(mdct_lookup *init,
  114894. DATA_TYPE *x,
  114895. int points){
  114896. DATA_TYPE *T=init->trig;
  114897. int stages=init->log2n-5;
  114898. int i,j;
  114899. if(--stages>0){
  114900. mdct_butterfly_first(T,x,points);
  114901. }
  114902. for(i=1;--stages>0;i++){
  114903. for(j=0;j<(1<<i);j++)
  114904. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  114905. }
  114906. for(j=0;j<points;j+=32)
  114907. mdct_butterfly_32(x+j);
  114908. }
  114909. void mdct_clear(mdct_lookup *l){
  114910. if(l){
  114911. if(l->trig)_ogg_free(l->trig);
  114912. if(l->bitrev)_ogg_free(l->bitrev);
  114913. memset(l,0,sizeof(*l));
  114914. }
  114915. }
  114916. STIN void mdct_bitreverse(mdct_lookup *init,
  114917. DATA_TYPE *x){
  114918. int n = init->n;
  114919. int *bit = init->bitrev;
  114920. DATA_TYPE *w0 = x;
  114921. DATA_TYPE *w1 = x = w0+(n>>1);
  114922. DATA_TYPE *T = init->trig+n;
  114923. do{
  114924. DATA_TYPE *x0 = x+bit[0];
  114925. DATA_TYPE *x1 = x+bit[1];
  114926. REG_TYPE r0 = x0[1] - x1[1];
  114927. REG_TYPE r1 = x0[0] + x1[0];
  114928. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  114929. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  114930. w1 -= 4;
  114931. r0 = HALVE(x0[1] + x1[1]);
  114932. r1 = HALVE(x0[0] - x1[0]);
  114933. w0[0] = r0 + r2;
  114934. w1[2] = r0 - r2;
  114935. w0[1] = r1 + r3;
  114936. w1[3] = r3 - r1;
  114937. x0 = x+bit[2];
  114938. x1 = x+bit[3];
  114939. r0 = x0[1] - x1[1];
  114940. r1 = x0[0] + x1[0];
  114941. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  114942. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  114943. r0 = HALVE(x0[1] + x1[1]);
  114944. r1 = HALVE(x0[0] - x1[0]);
  114945. w0[2] = r0 + r2;
  114946. w1[0] = r0 - r2;
  114947. w0[3] = r1 + r3;
  114948. w1[1] = r3 - r1;
  114949. T += 4;
  114950. bit += 4;
  114951. w0 += 4;
  114952. }while(w0<w1);
  114953. }
  114954. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  114955. int n=init->n;
  114956. int n2=n>>1;
  114957. int n4=n>>2;
  114958. /* rotate */
  114959. DATA_TYPE *iX = in+n2-7;
  114960. DATA_TYPE *oX = out+n2+n4;
  114961. DATA_TYPE *T = init->trig+n4;
  114962. do{
  114963. oX -= 4;
  114964. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  114965. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  114966. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  114967. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  114968. iX -= 8;
  114969. T += 4;
  114970. }while(iX>=in);
  114971. iX = in+n2-8;
  114972. oX = out+n2+n4;
  114973. T = init->trig+n4;
  114974. do{
  114975. T -= 4;
  114976. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  114977. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  114978. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  114979. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  114980. iX -= 8;
  114981. oX += 4;
  114982. }while(iX>=in);
  114983. mdct_butterflies(init,out+n2,n2);
  114984. mdct_bitreverse(init,out);
  114985. /* roatate + window */
  114986. {
  114987. DATA_TYPE *oX1=out+n2+n4;
  114988. DATA_TYPE *oX2=out+n2+n4;
  114989. DATA_TYPE *iX =out;
  114990. T =init->trig+n2;
  114991. do{
  114992. oX1-=4;
  114993. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  114994. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  114995. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  114996. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  114997. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  114998. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  114999. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115000. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115001. oX2+=4;
  115002. iX += 8;
  115003. T += 8;
  115004. }while(iX<oX1);
  115005. iX=out+n2+n4;
  115006. oX1=out+n4;
  115007. oX2=oX1;
  115008. do{
  115009. oX1-=4;
  115010. iX-=4;
  115011. oX2[0] = -(oX1[3] = iX[3]);
  115012. oX2[1] = -(oX1[2] = iX[2]);
  115013. oX2[2] = -(oX1[1] = iX[1]);
  115014. oX2[3] = -(oX1[0] = iX[0]);
  115015. oX2+=4;
  115016. }while(oX2<iX);
  115017. iX=out+n2+n4;
  115018. oX1=out+n2+n4;
  115019. oX2=out+n2;
  115020. do{
  115021. oX1-=4;
  115022. oX1[0]= iX[3];
  115023. oX1[1]= iX[2];
  115024. oX1[2]= iX[1];
  115025. oX1[3]= iX[0];
  115026. iX+=4;
  115027. }while(oX1>oX2);
  115028. }
  115029. }
  115030. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115031. int n=init->n;
  115032. int n2=n>>1;
  115033. int n4=n>>2;
  115034. int n8=n>>3;
  115035. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115036. DATA_TYPE *w2=w+n2;
  115037. /* rotate */
  115038. /* window + rotate + step 1 */
  115039. REG_TYPE r0;
  115040. REG_TYPE r1;
  115041. DATA_TYPE *x0=in+n2+n4;
  115042. DATA_TYPE *x1=x0+1;
  115043. DATA_TYPE *T=init->trig+n2;
  115044. int i=0;
  115045. for(i=0;i<n8;i+=2){
  115046. x0 -=4;
  115047. T-=2;
  115048. r0= x0[2] + x1[0];
  115049. r1= x0[0] + x1[2];
  115050. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115051. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115052. x1 +=4;
  115053. }
  115054. x1=in+1;
  115055. for(;i<n2-n8;i+=2){
  115056. T-=2;
  115057. x0 -=4;
  115058. r0= x0[2] - x1[0];
  115059. r1= x0[0] - x1[2];
  115060. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115061. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115062. x1 +=4;
  115063. }
  115064. x0=in+n;
  115065. for(;i<n2;i+=2){
  115066. T-=2;
  115067. x0 -=4;
  115068. r0= -x0[2] - x1[0];
  115069. r1= -x0[0] - x1[2];
  115070. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115071. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115072. x1 +=4;
  115073. }
  115074. mdct_butterflies(init,w+n2,n2);
  115075. mdct_bitreverse(init,w);
  115076. /* roatate + window */
  115077. T=init->trig+n2;
  115078. x0=out+n2;
  115079. for(i=0;i<n4;i++){
  115080. x0--;
  115081. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115082. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115083. w+=2;
  115084. T+=2;
  115085. }
  115086. }
  115087. #endif
  115088. /*** End of inlined file: mdct.c ***/
  115089. /*** Start of inlined file: psy.c ***/
  115090. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115091. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115092. // tasks..
  115093. #if JUCE_MSVC
  115094. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115095. #endif
  115096. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115097. #if JUCE_USE_OGGVORBIS
  115098. #include <stdlib.h>
  115099. #include <math.h>
  115100. #include <string.h>
  115101. /*** Start of inlined file: masking.h ***/
  115102. #ifndef _V_MASKING_H_
  115103. #define _V_MASKING_H_
  115104. /* more detailed ATH; the bass if flat to save stressing the floor
  115105. overly for only a bin or two of savings. */
  115106. #define MAX_ATH 88
  115107. static float ATH[]={
  115108. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115109. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115110. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115111. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115112. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115113. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115114. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115115. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115116. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115117. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115118. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115119. };
  115120. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115121. replaced by an empirically collected data set. The previously
  115122. published values were, far too often, simply on crack. */
  115123. #define EHMER_OFFSET 16
  115124. #define EHMER_MAX 56
  115125. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  115126. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  115127. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  115128. for collection of these curves) */
  115129. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  115130. /* 62.5 Hz */
  115131. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  115132. -60, -60, -60, -60, -62, -62, -65, -73,
  115133. -69, -68, -68, -67, -70, -70, -72, -74,
  115134. -75, -79, -79, -80, -83, -88, -93, -100,
  115135. -110, -999, -999, -999, -999, -999, -999, -999,
  115136. -999, -999, -999, -999, -999, -999, -999, -999,
  115137. -999, -999, -999, -999, -999, -999, -999, -999},
  115138. { -48, -48, -48, -48, -48, -48, -48, -48,
  115139. -48, -48, -48, -48, -48, -53, -61, -66,
  115140. -66, -68, -67, -70, -76, -76, -72, -73,
  115141. -75, -76, -78, -79, -83, -88, -93, -100,
  115142. -110, -999, -999, -999, -999, -999, -999, -999,
  115143. -999, -999, -999, -999, -999, -999, -999, -999,
  115144. -999, -999, -999, -999, -999, -999, -999, -999},
  115145. { -37, -37, -37, -37, -37, -37, -37, -37,
  115146. -38, -40, -42, -46, -48, -53, -55, -62,
  115147. -65, -58, -56, -56, -61, -60, -65, -67,
  115148. -69, -71, -77, -77, -78, -80, -82, -84,
  115149. -88, -93, -98, -106, -112, -999, -999, -999,
  115150. -999, -999, -999, -999, -999, -999, -999, -999,
  115151. -999, -999, -999, -999, -999, -999, -999, -999},
  115152. { -25, -25, -25, -25, -25, -25, -25, -25,
  115153. -25, -26, -27, -29, -32, -38, -48, -52,
  115154. -52, -50, -48, -48, -51, -52, -54, -60,
  115155. -67, -67, -66, -68, -69, -73, -73, -76,
  115156. -80, -81, -81, -85, -85, -86, -88, -93,
  115157. -100, -110, -999, -999, -999, -999, -999, -999,
  115158. -999, -999, -999, -999, -999, -999, -999, -999},
  115159. { -16, -16, -16, -16, -16, -16, -16, -16,
  115160. -17, -19, -20, -22, -26, -28, -31, -40,
  115161. -47, -39, -39, -40, -42, -43, -47, -51,
  115162. -57, -52, -55, -55, -60, -58, -62, -63,
  115163. -70, -67, -69, -72, -73, -77, -80, -82,
  115164. -83, -87, -90, -94, -98, -104, -115, -999,
  115165. -999, -999, -999, -999, -999, -999, -999, -999},
  115166. { -8, -8, -8, -8, -8, -8, -8, -8,
  115167. -8, -8, -10, -11, -15, -19, -25, -30,
  115168. -34, -31, -30, -31, -29, -32, -35, -42,
  115169. -48, -42, -44, -46, -50, -50, -51, -52,
  115170. -59, -54, -55, -55, -58, -62, -63, -66,
  115171. -72, -73, -76, -75, -78, -80, -80, -81,
  115172. -84, -88, -90, -94, -98, -101, -106, -110}},
  115173. /* 88Hz */
  115174. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  115175. -66, -66, -66, -66, -66, -67, -67, -67,
  115176. -76, -72, -71, -74, -76, -76, -75, -78,
  115177. -79, -79, -81, -83, -86, -89, -93, -97,
  115178. -100, -105, -110, -999, -999, -999, -999, -999,
  115179. -999, -999, -999, -999, -999, -999, -999, -999,
  115180. -999, -999, -999, -999, -999, -999, -999, -999},
  115181. { -47, -47, -47, -47, -47, -47, -47, -47,
  115182. -47, -47, -47, -48, -51, -55, -59, -66,
  115183. -66, -66, -67, -66, -68, -69, -70, -74,
  115184. -79, -77, -77, -78, -80, -81, -82, -84,
  115185. -86, -88, -91, -95, -100, -108, -116, -999,
  115186. -999, -999, -999, -999, -999, -999, -999, -999,
  115187. -999, -999, -999, -999, -999, -999, -999, -999},
  115188. { -36, -36, -36, -36, -36, -36, -36, -36,
  115189. -36, -37, -37, -41, -44, -48, -51, -58,
  115190. -62, -60, -57, -59, -59, -60, -63, -65,
  115191. -72, -71, -70, -72, -74, -77, -76, -78,
  115192. -81, -81, -80, -83, -86, -91, -96, -100,
  115193. -105, -110, -999, -999, -999, -999, -999, -999,
  115194. -999, -999, -999, -999, -999, -999, -999, -999},
  115195. { -28, -28, -28, -28, -28, -28, -28, -28,
  115196. -28, -30, -32, -32, -33, -35, -41, -49,
  115197. -50, -49, -47, -48, -48, -52, -51, -57,
  115198. -65, -61, -59, -61, -64, -69, -70, -74,
  115199. -77, -77, -78, -81, -84, -85, -87, -90,
  115200. -92, -96, -100, -107, -112, -999, -999, -999,
  115201. -999, -999, -999, -999, -999, -999, -999, -999},
  115202. { -19, -19, -19, -19, -19, -19, -19, -19,
  115203. -20, -21, -23, -27, -30, -35, -36, -41,
  115204. -46, -44, -42, -40, -41, -41, -43, -48,
  115205. -55, -53, -52, -53, -56, -59, -58, -60,
  115206. -67, -66, -69, -71, -72, -75, -79, -81,
  115207. -84, -87, -90, -93, -97, -101, -107, -114,
  115208. -999, -999, -999, -999, -999, -999, -999, -999},
  115209. { -9, -9, -9, -9, -9, -9, -9, -9,
  115210. -11, -12, -12, -15, -16, -20, -23, -30,
  115211. -37, -34, -33, -34, -31, -32, -32, -38,
  115212. -47, -44, -41, -40, -47, -49, -46, -46,
  115213. -58, -50, -50, -54, -58, -62, -64, -67,
  115214. -67, -70, -72, -76, -79, -83, -87, -91,
  115215. -96, -100, -104, -110, -999, -999, -999, -999}},
  115216. /* 125 Hz */
  115217. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  115218. -62, -62, -63, -64, -66, -67, -66, -68,
  115219. -75, -72, -76, -75, -76, -78, -79, -82,
  115220. -84, -85, -90, -94, -101, -110, -999, -999,
  115221. -999, -999, -999, -999, -999, -999, -999, -999,
  115222. -999, -999, -999, -999, -999, -999, -999, -999,
  115223. -999, -999, -999, -999, -999, -999, -999, -999},
  115224. { -59, -59, -59, -59, -59, -59, -59, -59,
  115225. -59, -59, -59, -60, -60, -61, -63, -66,
  115226. -71, -68, -70, -70, -71, -72, -72, -75,
  115227. -81, -78, -79, -82, -83, -86, -90, -97,
  115228. -103, -113, -999, -999, -999, -999, -999, -999,
  115229. -999, -999, -999, -999, -999, -999, -999, -999,
  115230. -999, -999, -999, -999, -999, -999, -999, -999},
  115231. { -53, -53, -53, -53, -53, -53, -53, -53,
  115232. -53, -54, -55, -57, -56, -57, -55, -61,
  115233. -65, -60, -60, -62, -63, -63, -66, -68,
  115234. -74, -73, -75, -75, -78, -80, -80, -82,
  115235. -85, -90, -96, -101, -108, -999, -999, -999,
  115236. -999, -999, -999, -999, -999, -999, -999, -999,
  115237. -999, -999, -999, -999, -999, -999, -999, -999},
  115238. { -46, -46, -46, -46, -46, -46, -46, -46,
  115239. -46, -46, -47, -47, -47, -47, -48, -51,
  115240. -57, -51, -49, -50, -51, -53, -54, -59,
  115241. -66, -60, -62, -67, -67, -70, -72, -75,
  115242. -76, -78, -81, -85, -88, -94, -97, -104,
  115243. -112, -999, -999, -999, -999, -999, -999, -999,
  115244. -999, -999, -999, -999, -999, -999, -999, -999},
  115245. { -36, -36, -36, -36, -36, -36, -36, -36,
  115246. -39, -41, -42, -42, -39, -38, -41, -43,
  115247. -52, -44, -40, -39, -37, -37, -40, -47,
  115248. -54, -50, -48, -50, -55, -61, -59, -62,
  115249. -66, -66, -66, -69, -69, -73, -74, -74,
  115250. -75, -77, -79, -82, -87, -91, -95, -100,
  115251. -108, -115, -999, -999, -999, -999, -999, -999},
  115252. { -28, -26, -24, -22, -20, -20, -23, -29,
  115253. -30, -31, -28, -27, -28, -28, -28, -35,
  115254. -40, -33, -32, -29, -30, -30, -30, -37,
  115255. -45, -41, -37, -38, -45, -47, -47, -48,
  115256. -53, -49, -48, -50, -49, -49, -51, -52,
  115257. -58, -56, -57, -56, -60, -61, -62, -70,
  115258. -72, -74, -78, -83, -88, -93, -100, -106}},
  115259. /* 177 Hz */
  115260. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115261. -999, -110, -105, -100, -95, -91, -87, -83,
  115262. -80, -78, -76, -78, -78, -81, -83, -85,
  115263. -86, -85, -86, -87, -90, -97, -107, -999,
  115264. -999, -999, -999, -999, -999, -999, -999, -999,
  115265. -999, -999, -999, -999, -999, -999, -999, -999,
  115266. -999, -999, -999, -999, -999, -999, -999, -999},
  115267. {-999, -999, -999, -110, -105, -100, -95, -90,
  115268. -85, -81, -77, -73, -70, -67, -67, -68,
  115269. -75, -73, -70, -69, -70, -72, -75, -79,
  115270. -84, -83, -84, -86, -88, -89, -89, -93,
  115271. -98, -105, -112, -999, -999, -999, -999, -999,
  115272. -999, -999, -999, -999, -999, -999, -999, -999,
  115273. -999, -999, -999, -999, -999, -999, -999, -999},
  115274. {-105, -100, -95, -90, -85, -80, -76, -71,
  115275. -68, -68, -65, -63, -63, -62, -62, -64,
  115276. -65, -64, -61, -62, -63, -64, -66, -68,
  115277. -73, -73, -74, -75, -76, -81, -83, -85,
  115278. -88, -89, -92, -95, -100, -108, -999, -999,
  115279. -999, -999, -999, -999, -999, -999, -999, -999,
  115280. -999, -999, -999, -999, -999, -999, -999, -999},
  115281. { -80, -75, -71, -68, -65, -63, -62, -61,
  115282. -61, -61, -61, -59, -56, -57, -53, -50,
  115283. -58, -52, -50, -50, -52, -53, -54, -58,
  115284. -67, -63, -67, -68, -72, -75, -78, -80,
  115285. -81, -81, -82, -85, -89, -90, -93, -97,
  115286. -101, -107, -114, -999, -999, -999, -999, -999,
  115287. -999, -999, -999, -999, -999, -999, -999, -999},
  115288. { -65, -61, -59, -57, -56, -55, -55, -56,
  115289. -56, -57, -55, -53, -52, -47, -44, -44,
  115290. -50, -44, -41, -39, -39, -42, -40, -46,
  115291. -51, -49, -50, -53, -54, -63, -60, -61,
  115292. -62, -66, -66, -66, -70, -73, -74, -75,
  115293. -76, -75, -79, -85, -89, -91, -96, -102,
  115294. -110, -999, -999, -999, -999, -999, -999, -999},
  115295. { -52, -50, -49, -49, -48, -48, -48, -49,
  115296. -50, -50, -49, -46, -43, -39, -35, -33,
  115297. -38, -36, -32, -29, -32, -32, -32, -35,
  115298. -44, -39, -38, -38, -46, -50, -45, -46,
  115299. -53, -50, -50, -50, -54, -54, -53, -53,
  115300. -56, -57, -59, -66, -70, -72, -74, -79,
  115301. -83, -85, -90, -97, -114, -999, -999, -999}},
  115302. /* 250 Hz */
  115303. {{-999, -999, -999, -999, -999, -999, -110, -105,
  115304. -100, -95, -90, -86, -80, -75, -75, -79,
  115305. -80, -79, -80, -81, -82, -88, -95, -103,
  115306. -110, -999, -999, -999, -999, -999, -999, -999,
  115307. -999, -999, -999, -999, -999, -999, -999, -999,
  115308. -999, -999, -999, -999, -999, -999, -999, -999,
  115309. -999, -999, -999, -999, -999, -999, -999, -999},
  115310. {-999, -999, -999, -999, -108, -103, -98, -93,
  115311. -88, -83, -79, -78, -75, -71, -67, -68,
  115312. -73, -73, -72, -73, -75, -77, -80, -82,
  115313. -88, -93, -100, -107, -114, -999, -999, -999,
  115314. -999, -999, -999, -999, -999, -999, -999, -999,
  115315. -999, -999, -999, -999, -999, -999, -999, -999,
  115316. -999, -999, -999, -999, -999, -999, -999, -999},
  115317. {-999, -999, -999, -110, -105, -101, -96, -90,
  115318. -86, -81, -77, -73, -69, -66, -61, -62,
  115319. -66, -64, -62, -65, -66, -70, -72, -76,
  115320. -81, -80, -84, -90, -95, -102, -110, -999,
  115321. -999, -999, -999, -999, -999, -999, -999, -999,
  115322. -999, -999, -999, -999, -999, -999, -999, -999,
  115323. -999, -999, -999, -999, -999, -999, -999, -999},
  115324. {-999, -999, -999, -107, -103, -97, -92, -88,
  115325. -83, -79, -74, -70, -66, -59, -53, -58,
  115326. -62, -55, -54, -54, -54, -58, -61, -62,
  115327. -72, -70, -72, -75, -78, -80, -81, -80,
  115328. -83, -83, -88, -93, -100, -107, -115, -999,
  115329. -999, -999, -999, -999, -999, -999, -999, -999,
  115330. -999, -999, -999, -999, -999, -999, -999, -999},
  115331. {-999, -999, -999, -105, -100, -95, -90, -85,
  115332. -80, -75, -70, -66, -62, -56, -48, -44,
  115333. -48, -46, -46, -43, -46, -48, -48, -51,
  115334. -58, -58, -59, -60, -62, -62, -61, -61,
  115335. -65, -64, -65, -68, -70, -74, -75, -78,
  115336. -81, -86, -95, -110, -999, -999, -999, -999,
  115337. -999, -999, -999, -999, -999, -999, -999, -999},
  115338. {-999, -999, -105, -100, -95, -90, -85, -80,
  115339. -75, -70, -65, -61, -55, -49, -39, -33,
  115340. -40, -35, -32, -38, -40, -33, -35, -37,
  115341. -46, -41, -45, -44, -46, -42, -45, -46,
  115342. -52, -50, -50, -50, -54, -54, -55, -57,
  115343. -62, -64, -66, -68, -70, -76, -81, -90,
  115344. -100, -110, -999, -999, -999, -999, -999, -999}},
  115345. /* 354 hz */
  115346. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115347. -105, -98, -90, -85, -82, -83, -80, -78,
  115348. -84, -79, -80, -83, -87, -89, -91, -93,
  115349. -99, -106, -117, -999, -999, -999, -999, -999,
  115350. -999, -999, -999, -999, -999, -999, -999, -999,
  115351. -999, -999, -999, -999, -999, -999, -999, -999,
  115352. -999, -999, -999, -999, -999, -999, -999, -999},
  115353. {-999, -999, -999, -999, -999, -999, -999, -999,
  115354. -105, -98, -90, -85, -80, -75, -70, -68,
  115355. -74, -72, -74, -77, -80, -82, -85, -87,
  115356. -92, -89, -91, -95, -100, -106, -112, -999,
  115357. -999, -999, -999, -999, -999, -999, -999, -999,
  115358. -999, -999, -999, -999, -999, -999, -999, -999,
  115359. -999, -999, -999, -999, -999, -999, -999, -999},
  115360. {-999, -999, -999, -999, -999, -999, -999, -999,
  115361. -105, -98, -90, -83, -75, -71, -63, -64,
  115362. -67, -62, -64, -67, -70, -73, -77, -81,
  115363. -84, -83, -85, -89, -90, -93, -98, -104,
  115364. -109, -114, -999, -999, -999, -999, -999, -999,
  115365. -999, -999, -999, -999, -999, -999, -999, -999,
  115366. -999, -999, -999, -999, -999, -999, -999, -999},
  115367. {-999, -999, -999, -999, -999, -999, -999, -999,
  115368. -103, -96, -88, -81, -75, -68, -58, -54,
  115369. -56, -54, -56, -56, -58, -60, -63, -66,
  115370. -74, -69, -72, -72, -75, -74, -77, -81,
  115371. -81, -82, -84, -87, -93, -96, -99, -104,
  115372. -110, -999, -999, -999, -999, -999, -999, -999,
  115373. -999, -999, -999, -999, -999, -999, -999, -999},
  115374. {-999, -999, -999, -999, -999, -108, -102, -96,
  115375. -91, -85, -80, -74, -68, -60, -51, -46,
  115376. -48, -46, -43, -45, -47, -47, -49, -48,
  115377. -56, -53, -55, -58, -57, -63, -58, -60,
  115378. -66, -64, -67, -70, -70, -74, -77, -84,
  115379. -86, -89, -91, -93, -94, -101, -109, -118,
  115380. -999, -999, -999, -999, -999, -999, -999, -999},
  115381. {-999, -999, -999, -108, -103, -98, -93, -88,
  115382. -83, -78, -73, -68, -60, -53, -44, -35,
  115383. -38, -38, -34, -34, -36, -40, -41, -44,
  115384. -51, -45, -46, -47, -46, -54, -50, -49,
  115385. -50, -50, -50, -51, -54, -57, -58, -60,
  115386. -66, -66, -66, -64, -65, -68, -77, -82,
  115387. -87, -95, -110, -999, -999, -999, -999, -999}},
  115388. /* 500 Hz */
  115389. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115390. -107, -102, -97, -92, -87, -83, -78, -75,
  115391. -82, -79, -83, -85, -89, -92, -95, -98,
  115392. -101, -105, -109, -113, -999, -999, -999, -999,
  115393. -999, -999, -999, -999, -999, -999, -999, -999,
  115394. -999, -999, -999, -999, -999, -999, -999, -999,
  115395. -999, -999, -999, -999, -999, -999, -999, -999},
  115396. {-999, -999, -999, -999, -999, -999, -999, -106,
  115397. -100, -95, -90, -86, -81, -78, -74, -69,
  115398. -74, -74, -76, -79, -83, -84, -86, -89,
  115399. -92, -97, -93, -100, -103, -107, -110, -999,
  115400. -999, -999, -999, -999, -999, -999, -999, -999,
  115401. -999, -999, -999, -999, -999, -999, -999, -999,
  115402. -999, -999, -999, -999, -999, -999, -999, -999},
  115403. {-999, -999, -999, -999, -999, -999, -106, -100,
  115404. -95, -90, -87, -83, -80, -75, -69, -60,
  115405. -66, -66, -68, -70, -74, -78, -79, -81,
  115406. -81, -83, -84, -87, -93, -96, -99, -103,
  115407. -107, -110, -999, -999, -999, -999, -999, -999,
  115408. -999, -999, -999, -999, -999, -999, -999, -999,
  115409. -999, -999, -999, -999, -999, -999, -999, -999},
  115410. {-999, -999, -999, -999, -999, -108, -103, -98,
  115411. -93, -89, -85, -82, -78, -71, -62, -55,
  115412. -58, -58, -54, -54, -55, -59, -61, -62,
  115413. -70, -66, -66, -67, -70, -72, -75, -78,
  115414. -84, -84, -84, -88, -91, -90, -95, -98,
  115415. -102, -103, -106, -110, -999, -999, -999, -999,
  115416. -999, -999, -999, -999, -999, -999, -999, -999},
  115417. {-999, -999, -999, -999, -108, -103, -98, -94,
  115418. -90, -87, -82, -79, -73, -67, -58, -47,
  115419. -50, -45, -41, -45, -48, -44, -44, -49,
  115420. -54, -51, -48, -47, -49, -50, -51, -57,
  115421. -58, -60, -63, -69, -70, -69, -71, -74,
  115422. -78, -82, -90, -95, -101, -105, -110, -999,
  115423. -999, -999, -999, -999, -999, -999, -999, -999},
  115424. {-999, -999, -999, -105, -101, -97, -93, -90,
  115425. -85, -80, -77, -72, -65, -56, -48, -37,
  115426. -40, -36, -34, -40, -50, -47, -38, -41,
  115427. -47, -38, -35, -39, -38, -43, -40, -45,
  115428. -50, -45, -44, -47, -50, -55, -48, -48,
  115429. -52, -66, -70, -76, -82, -90, -97, -105,
  115430. -110, -999, -999, -999, -999, -999, -999, -999}},
  115431. /* 707 Hz */
  115432. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115433. -999, -108, -103, -98, -93, -86, -79, -76,
  115434. -83, -81, -85, -87, -89, -93, -98, -102,
  115435. -107, -112, -999, -999, -999, -999, -999, -999,
  115436. -999, -999, -999, -999, -999, -999, -999, -999,
  115437. -999, -999, -999, -999, -999, -999, -999, -999,
  115438. -999, -999, -999, -999, -999, -999, -999, -999},
  115439. {-999, -999, -999, -999, -999, -999, -999, -999,
  115440. -999, -108, -103, -98, -93, -86, -79, -71,
  115441. -77, -74, -77, -79, -81, -84, -85, -90,
  115442. -92, -93, -92, -98, -101, -108, -112, -999,
  115443. -999, -999, -999, -999, -999, -999, -999, -999,
  115444. -999, -999, -999, -999, -999, -999, -999, -999,
  115445. -999, -999, -999, -999, -999, -999, -999, -999},
  115446. {-999, -999, -999, -999, -999, -999, -999, -999,
  115447. -108, -103, -98, -93, -87, -78, -68, -65,
  115448. -66, -62, -65, -67, -70, -73, -75, -78,
  115449. -82, -82, -83, -84, -91, -93, -98, -102,
  115450. -106, -110, -999, -999, -999, -999, -999, -999,
  115451. -999, -999, -999, -999, -999, -999, -999, -999,
  115452. -999, -999, -999, -999, -999, -999, -999, -999},
  115453. {-999, -999, -999, -999, -999, -999, -999, -999,
  115454. -105, -100, -95, -90, -82, -74, -62, -57,
  115455. -58, -56, -51, -52, -52, -54, -54, -58,
  115456. -66, -59, -60, -63, -66, -69, -73, -79,
  115457. -83, -84, -80, -81, -81, -82, -88, -92,
  115458. -98, -105, -113, -999, -999, -999, -999, -999,
  115459. -999, -999, -999, -999, -999, -999, -999, -999},
  115460. {-999, -999, -999, -999, -999, -999, -999, -107,
  115461. -102, -97, -92, -84, -79, -69, -57, -47,
  115462. -52, -47, -44, -45, -50, -52, -42, -42,
  115463. -53, -43, -43, -48, -51, -56, -55, -52,
  115464. -57, -59, -61, -62, -67, -71, -78, -83,
  115465. -86, -94, -98, -103, -110, -999, -999, -999,
  115466. -999, -999, -999, -999, -999, -999, -999, -999},
  115467. {-999, -999, -999, -999, -999, -999, -105, -100,
  115468. -95, -90, -84, -78, -70, -61, -51, -41,
  115469. -40, -38, -40, -46, -52, -51, -41, -40,
  115470. -46, -40, -38, -38, -41, -46, -41, -46,
  115471. -47, -43, -43, -45, -41, -45, -56, -67,
  115472. -68, -83, -87, -90, -95, -102, -107, -113,
  115473. -999, -999, -999, -999, -999, -999, -999, -999}},
  115474. /* 1000 Hz */
  115475. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115476. -999, -109, -105, -101, -96, -91, -84, -77,
  115477. -82, -82, -85, -89, -94, -100, -106, -110,
  115478. -999, -999, -999, -999, -999, -999, -999, -999,
  115479. -999, -999, -999, -999, -999, -999, -999, -999,
  115480. -999, -999, -999, -999, -999, -999, -999, -999,
  115481. -999, -999, -999, -999, -999, -999, -999, -999},
  115482. {-999, -999, -999, -999, -999, -999, -999, -999,
  115483. -999, -106, -103, -98, -92, -85, -80, -71,
  115484. -75, -72, -76, -80, -84, -86, -89, -93,
  115485. -100, -107, -113, -999, -999, -999, -999, -999,
  115486. -999, -999, -999, -999, -999, -999, -999, -999,
  115487. -999, -999, -999, -999, -999, -999, -999, -999,
  115488. -999, -999, -999, -999, -999, -999, -999, -999},
  115489. {-999, -999, -999, -999, -999, -999, -999, -107,
  115490. -104, -101, -97, -92, -88, -84, -80, -64,
  115491. -66, -63, -64, -66, -69, -73, -77, -83,
  115492. -83, -86, -91, -98, -104, -111, -999, -999,
  115493. -999, -999, -999, -999, -999, -999, -999, -999,
  115494. -999, -999, -999, -999, -999, -999, -999, -999,
  115495. -999, -999, -999, -999, -999, -999, -999, -999},
  115496. {-999, -999, -999, -999, -999, -999, -999, -107,
  115497. -104, -101, -97, -92, -90, -84, -74, -57,
  115498. -58, -52, -55, -54, -50, -52, -50, -52,
  115499. -63, -62, -69, -76, -77, -78, -78, -79,
  115500. -82, -88, -94, -100, -106, -111, -999, -999,
  115501. -999, -999, -999, -999, -999, -999, -999, -999,
  115502. -999, -999, -999, -999, -999, -999, -999, -999},
  115503. {-999, -999, -999, -999, -999, -999, -106, -102,
  115504. -98, -95, -90, -85, -83, -78, -70, -50,
  115505. -50, -41, -44, -49, -47, -50, -50, -44,
  115506. -55, -46, -47, -48, -48, -54, -49, -49,
  115507. -58, -62, -71, -81, -87, -92, -97, -102,
  115508. -108, -114, -999, -999, -999, -999, -999, -999,
  115509. -999, -999, -999, -999, -999, -999, -999, -999},
  115510. {-999, -999, -999, -999, -999, -999, -106, -102,
  115511. -98, -95, -90, -85, -83, -78, -70, -45,
  115512. -43, -41, -47, -50, -51, -50, -49, -45,
  115513. -47, -41, -44, -41, -39, -43, -38, -37,
  115514. -40, -41, -44, -50, -58, -65, -73, -79,
  115515. -85, -92, -97, -101, -105, -109, -113, -999,
  115516. -999, -999, -999, -999, -999, -999, -999, -999}},
  115517. /* 1414 Hz */
  115518. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115519. -999, -999, -999, -107, -100, -95, -87, -81,
  115520. -85, -83, -88, -93, -100, -107, -114, -999,
  115521. -999, -999, -999, -999, -999, -999, -999, -999,
  115522. -999, -999, -999, -999, -999, -999, -999, -999,
  115523. -999, -999, -999, -999, -999, -999, -999, -999,
  115524. -999, -999, -999, -999, -999, -999, -999, -999},
  115525. {-999, -999, -999, -999, -999, -999, -999, -999,
  115526. -999, -999, -107, -101, -95, -88, -83, -76,
  115527. -73, -72, -79, -84, -90, -95, -100, -105,
  115528. -110, -115, -999, -999, -999, -999, -999, -999,
  115529. -999, -999, -999, -999, -999, -999, -999, -999,
  115530. -999, -999, -999, -999, -999, -999, -999, -999,
  115531. -999, -999, -999, -999, -999, -999, -999, -999},
  115532. {-999, -999, -999, -999, -999, -999, -999, -999,
  115533. -999, -999, -104, -98, -92, -87, -81, -70,
  115534. -65, -62, -67, -71, -74, -80, -85, -91,
  115535. -95, -99, -103, -108, -111, -114, -999, -999,
  115536. -999, -999, -999, -999, -999, -999, -999, -999,
  115537. -999, -999, -999, -999, -999, -999, -999, -999,
  115538. -999, -999, -999, -999, -999, -999, -999, -999},
  115539. {-999, -999, -999, -999, -999, -999, -999, -999,
  115540. -999, -999, -103, -97, -90, -85, -76, -60,
  115541. -56, -54, -60, -62, -61, -56, -63, -65,
  115542. -73, -74, -77, -75, -78, -81, -86, -87,
  115543. -88, -91, -94, -98, -103, -110, -999, -999,
  115544. -999, -999, -999, -999, -999, -999, -999, -999,
  115545. -999, -999, -999, -999, -999, -999, -999, -999},
  115546. {-999, -999, -999, -999, -999, -999, -999, -105,
  115547. -100, -97, -92, -86, -81, -79, -70, -57,
  115548. -51, -47, -51, -58, -60, -56, -53, -50,
  115549. -58, -52, -50, -50, -53, -55, -64, -69,
  115550. -71, -85, -82, -78, -81, -85, -95, -102,
  115551. -112, -999, -999, -999, -999, -999, -999, -999,
  115552. -999, -999, -999, -999, -999, -999, -999, -999},
  115553. {-999, -999, -999, -999, -999, -999, -999, -105,
  115554. -100, -97, -92, -85, -83, -79, -72, -49,
  115555. -40, -43, -43, -54, -56, -51, -50, -40,
  115556. -43, -38, -36, -35, -37, -38, -37, -44,
  115557. -54, -60, -57, -60, -70, -75, -84, -92,
  115558. -103, -112, -999, -999, -999, -999, -999, -999,
  115559. -999, -999, -999, -999, -999, -999, -999, -999}},
  115560. /* 2000 Hz */
  115561. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115562. -999, -999, -999, -110, -102, -95, -89, -82,
  115563. -83, -84, -90, -92, -99, -107, -113, -999,
  115564. -999, -999, -999, -999, -999, -999, -999, -999,
  115565. -999, -999, -999, -999, -999, -999, -999, -999,
  115566. -999, -999, -999, -999, -999, -999, -999, -999,
  115567. -999, -999, -999, -999, -999, -999, -999, -999},
  115568. {-999, -999, -999, -999, -999, -999, -999, -999,
  115569. -999, -999, -107, -101, -95, -89, -83, -72,
  115570. -74, -78, -85, -88, -88, -90, -92, -98,
  115571. -105, -111, -999, -999, -999, -999, -999, -999,
  115572. -999, -999, -999, -999, -999, -999, -999, -999,
  115573. -999, -999, -999, -999, -999, -999, -999, -999,
  115574. -999, -999, -999, -999, -999, -999, -999, -999},
  115575. {-999, -999, -999, -999, -999, -999, -999, -999,
  115576. -999, -109, -103, -97, -93, -87, -81, -70,
  115577. -70, -67, -75, -73, -76, -79, -81, -83,
  115578. -88, -89, -97, -103, -110, -999, -999, -999,
  115579. -999, -999, -999, -999, -999, -999, -999, -999,
  115580. -999, -999, -999, -999, -999, -999, -999, -999,
  115581. -999, -999, -999, -999, -999, -999, -999, -999},
  115582. {-999, -999, -999, -999, -999, -999, -999, -999,
  115583. -999, -107, -100, -94, -88, -83, -75, -63,
  115584. -59, -59, -63, -66, -60, -62, -67, -67,
  115585. -77, -76, -81, -88, -86, -92, -96, -102,
  115586. -109, -116, -999, -999, -999, -999, -999, -999,
  115587. -999, -999, -999, -999, -999, -999, -999, -999,
  115588. -999, -999, -999, -999, -999, -999, -999, -999},
  115589. {-999, -999, -999, -999, -999, -999, -999, -999,
  115590. -999, -105, -98, -92, -86, -81, -73, -56,
  115591. -52, -47, -55, -60, -58, -52, -51, -45,
  115592. -49, -50, -53, -54, -61, -71, -70, -69,
  115593. -78, -79, -87, -90, -96, -104, -112, -999,
  115594. -999, -999, -999, -999, -999, -999, -999, -999,
  115595. -999, -999, -999, -999, -999, -999, -999, -999},
  115596. {-999, -999, -999, -999, -999, -999, -999, -999,
  115597. -999, -103, -96, -90, -86, -78, -70, -51,
  115598. -42, -47, -48, -55, -54, -54, -53, -42,
  115599. -35, -28, -33, -38, -37, -44, -47, -49,
  115600. -54, -63, -68, -78, -82, -89, -94, -99,
  115601. -104, -109, -114, -999, -999, -999, -999, -999,
  115602. -999, -999, -999, -999, -999, -999, -999, -999}},
  115603. /* 2828 Hz */
  115604. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115605. -999, -999, -999, -999, -110, -100, -90, -79,
  115606. -85, -81, -82, -82, -89, -94, -99, -103,
  115607. -109, -115, -999, -999, -999, -999, -999, -999,
  115608. -999, -999, -999, -999, -999, -999, -999, -999,
  115609. -999, -999, -999, -999, -999, -999, -999, -999,
  115610. -999, -999, -999, -999, -999, -999, -999, -999},
  115611. {-999, -999, -999, -999, -999, -999, -999, -999,
  115612. -999, -999, -999, -999, -105, -97, -85, -72,
  115613. -74, -70, -70, -70, -76, -85, -91, -93,
  115614. -97, -103, -109, -115, -999, -999, -999, -999,
  115615. -999, -999, -999, -999, -999, -999, -999, -999,
  115616. -999, -999, -999, -999, -999, -999, -999, -999,
  115617. -999, -999, -999, -999, -999, -999, -999, -999},
  115618. {-999, -999, -999, -999, -999, -999, -999, -999,
  115619. -999, -999, -999, -999, -112, -93, -81, -68,
  115620. -62, -60, -60, -57, -63, -70, -77, -82,
  115621. -90, -93, -98, -104, -109, -113, -999, -999,
  115622. -999, -999, -999, -999, -999, -999, -999, -999,
  115623. -999, -999, -999, -999, -999, -999, -999, -999,
  115624. -999, -999, -999, -999, -999, -999, -999, -999},
  115625. {-999, -999, -999, -999, -999, -999, -999, -999,
  115626. -999, -999, -999, -113, -100, -93, -84, -63,
  115627. -58, -48, -53, -54, -52, -52, -57, -64,
  115628. -66, -76, -83, -81, -85, -85, -90, -95,
  115629. -98, -101, -103, -106, -108, -111, -999, -999,
  115630. -999, -999, -999, -999, -999, -999, -999, -999,
  115631. -999, -999, -999, -999, -999, -999, -999, -999},
  115632. {-999, -999, -999, -999, -999, -999, -999, -999,
  115633. -999, -999, -999, -105, -95, -86, -74, -53,
  115634. -50, -38, -43, -49, -43, -42, -39, -39,
  115635. -46, -52, -57, -56, -72, -69, -74, -81,
  115636. -87, -92, -94, -97, -99, -102, -105, -108,
  115637. -999, -999, -999, -999, -999, -999, -999, -999,
  115638. -999, -999, -999, -999, -999, -999, -999, -999},
  115639. {-999, -999, -999, -999, -999, -999, -999, -999,
  115640. -999, -999, -108, -99, -90, -76, -66, -45,
  115641. -43, -41, -44, -47, -43, -47, -40, -30,
  115642. -31, -31, -39, -33, -40, -41, -43, -53,
  115643. -59, -70, -73, -77, -79, -82, -84, -87,
  115644. -999, -999, -999, -999, -999, -999, -999, -999,
  115645. -999, -999, -999, -999, -999, -999, -999, -999}},
  115646. /* 4000 Hz */
  115647. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115648. -999, -999, -999, -999, -999, -110, -91, -76,
  115649. -75, -85, -93, -98, -104, -110, -999, -999,
  115650. -999, -999, -999, -999, -999, -999, -999, -999,
  115651. -999, -999, -999, -999, -999, -999, -999, -999,
  115652. -999, -999, -999, -999, -999, -999, -999, -999,
  115653. -999, -999, -999, -999, -999, -999, -999, -999},
  115654. {-999, -999, -999, -999, -999, -999, -999, -999,
  115655. -999, -999, -999, -999, -999, -110, -91, -70,
  115656. -70, -75, -86, -89, -94, -98, -101, -106,
  115657. -110, -999, -999, -999, -999, -999, -999, -999,
  115658. -999, -999, -999, -999, -999, -999, -999, -999,
  115659. -999, -999, -999, -999, -999, -999, -999, -999,
  115660. -999, -999, -999, -999, -999, -999, -999, -999},
  115661. {-999, -999, -999, -999, -999, -999, -999, -999,
  115662. -999, -999, -999, -999, -110, -95, -80, -60,
  115663. -65, -64, -74, -83, -88, -91, -95, -99,
  115664. -103, -107, -110, -999, -999, -999, -999, -999,
  115665. -999, -999, -999, -999, -999, -999, -999, -999,
  115666. -999, -999, -999, -999, -999, -999, -999, -999,
  115667. -999, -999, -999, -999, -999, -999, -999, -999},
  115668. {-999, -999, -999, -999, -999, -999, -999, -999,
  115669. -999, -999, -999, -999, -110, -95, -80, -58,
  115670. -55, -49, -66, -68, -71, -78, -78, -80,
  115671. -88, -85, -89, -97, -100, -105, -110, -999,
  115672. -999, -999, -999, -999, -999, -999, -999, -999,
  115673. -999, -999, -999, -999, -999, -999, -999, -999,
  115674. -999, -999, -999, -999, -999, -999, -999, -999},
  115675. {-999, -999, -999, -999, -999, -999, -999, -999,
  115676. -999, -999, -999, -999, -110, -95, -80, -53,
  115677. -52, -41, -59, -59, -49, -58, -56, -63,
  115678. -86, -79, -90, -93, -98, -103, -107, -112,
  115679. -999, -999, -999, -999, -999, -999, -999, -999,
  115680. -999, -999, -999, -999, -999, -999, -999, -999,
  115681. -999, -999, -999, -999, -999, -999, -999, -999},
  115682. {-999, -999, -999, -999, -999, -999, -999, -999,
  115683. -999, -999, -999, -110, -97, -91, -73, -45,
  115684. -40, -33, -53, -61, -49, -54, -50, -50,
  115685. -60, -52, -67, -74, -81, -92, -96, -100,
  115686. -105, -110, -999, -999, -999, -999, -999, -999,
  115687. -999, -999, -999, -999, -999, -999, -999, -999,
  115688. -999, -999, -999, -999, -999, -999, -999, -999}},
  115689. /* 5657 Hz */
  115690. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115691. -999, -999, -999, -113, -106, -99, -92, -77,
  115692. -80, -88, -97, -106, -115, -999, -999, -999,
  115693. -999, -999, -999, -999, -999, -999, -999, -999,
  115694. -999, -999, -999, -999, -999, -999, -999, -999,
  115695. -999, -999, -999, -999, -999, -999, -999, -999,
  115696. -999, -999, -999, -999, -999, -999, -999, -999},
  115697. {-999, -999, -999, -999, -999, -999, -999, -999,
  115698. -999, -999, -116, -109, -102, -95, -89, -74,
  115699. -72, -88, -87, -95, -102, -109, -116, -999,
  115700. -999, -999, -999, -999, -999, -999, -999, -999,
  115701. -999, -999, -999, -999, -999, -999, -999, -999,
  115702. -999, -999, -999, -999, -999, -999, -999, -999,
  115703. -999, -999, -999, -999, -999, -999, -999, -999},
  115704. {-999, -999, -999, -999, -999, -999, -999, -999,
  115705. -999, -999, -116, -109, -102, -95, -89, -75,
  115706. -66, -74, -77, -78, -86, -87, -90, -96,
  115707. -105, -115, -999, -999, -999, -999, -999, -999,
  115708. -999, -999, -999, -999, -999, -999, -999, -999,
  115709. -999, -999, -999, -999, -999, -999, -999, -999,
  115710. -999, -999, -999, -999, -999, -999, -999, -999},
  115711. {-999, -999, -999, -999, -999, -999, -999, -999,
  115712. -999, -999, -115, -108, -101, -94, -88, -66,
  115713. -56, -61, -70, -65, -78, -72, -83, -84,
  115714. -93, -98, -105, -110, -999, -999, -999, -999,
  115715. -999, -999, -999, -999, -999, -999, -999, -999,
  115716. -999, -999, -999, -999, -999, -999, -999, -999,
  115717. -999, -999, -999, -999, -999, -999, -999, -999},
  115718. {-999, -999, -999, -999, -999, -999, -999, -999,
  115719. -999, -999, -110, -105, -95, -89, -82, -57,
  115720. -52, -52, -59, -56, -59, -58, -69, -67,
  115721. -88, -82, -82, -89, -94, -100, -108, -999,
  115722. -999, -999, -999, -999, -999, -999, -999, -999,
  115723. -999, -999, -999, -999, -999, -999, -999, -999,
  115724. -999, -999, -999, -999, -999, -999, -999, -999},
  115725. {-999, -999, -999, -999, -999, -999, -999, -999,
  115726. -999, -110, -101, -96, -90, -83, -77, -54,
  115727. -43, -38, -50, -48, -52, -48, -42, -42,
  115728. -51, -52, -53, -59, -65, -71, -78, -85,
  115729. -95, -999, -999, -999, -999, -999, -999, -999,
  115730. -999, -999, -999, -999, -999, -999, -999, -999,
  115731. -999, -999, -999, -999, -999, -999, -999, -999}},
  115732. /* 8000 Hz */
  115733. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115734. -999, -999, -999, -999, -120, -105, -86, -68,
  115735. -78, -79, -90, -100, -110, -999, -999, -999,
  115736. -999, -999, -999, -999, -999, -999, -999, -999,
  115737. -999, -999, -999, -999, -999, -999, -999, -999,
  115738. -999, -999, -999, -999, -999, -999, -999, -999,
  115739. -999, -999, -999, -999, -999, -999, -999, -999},
  115740. {-999, -999, -999, -999, -999, -999, -999, -999,
  115741. -999, -999, -999, -999, -120, -105, -86, -66,
  115742. -73, -77, -88, -96, -105, -115, -999, -999,
  115743. -999, -999, -999, -999, -999, -999, -999, -999,
  115744. -999, -999, -999, -999, -999, -999, -999, -999,
  115745. -999, -999, -999, -999, -999, -999, -999, -999,
  115746. -999, -999, -999, -999, -999, -999, -999, -999},
  115747. {-999, -999, -999, -999, -999, -999, -999, -999,
  115748. -999, -999, -999, -120, -105, -92, -80, -61,
  115749. -64, -68, -80, -87, -92, -100, -110, -999,
  115750. -999, -999, -999, -999, -999, -999, -999, -999,
  115751. -999, -999, -999, -999, -999, -999, -999, -999,
  115752. -999, -999, -999, -999, -999, -999, -999, -999,
  115753. -999, -999, -999, -999, -999, -999, -999, -999},
  115754. {-999, -999, -999, -999, -999, -999, -999, -999,
  115755. -999, -999, -999, -120, -104, -91, -79, -52,
  115756. -60, -54, -64, -69, -77, -80, -82, -84,
  115757. -85, -87, -88, -90, -999, -999, -999, -999,
  115758. -999, -999, -999, -999, -999, -999, -999, -999,
  115759. -999, -999, -999, -999, -999, -999, -999, -999,
  115760. -999, -999, -999, -999, -999, -999, -999, -999},
  115761. {-999, -999, -999, -999, -999, -999, -999, -999,
  115762. -999, -999, -999, -118, -100, -87, -77, -49,
  115763. -50, -44, -58, -61, -61, -67, -65, -62,
  115764. -62, -62, -65, -68, -999, -999, -999, -999,
  115765. -999, -999, -999, -999, -999, -999, -999, -999,
  115766. -999, -999, -999, -999, -999, -999, -999, -999,
  115767. -999, -999, -999, -999, -999, -999, -999, -999},
  115768. {-999, -999, -999, -999, -999, -999, -999, -999,
  115769. -999, -999, -999, -115, -98, -84, -62, -49,
  115770. -44, -38, -46, -49, -49, -46, -39, -37,
  115771. -39, -40, -42, -43, -999, -999, -999, -999,
  115772. -999, -999, -999, -999, -999, -999, -999, -999,
  115773. -999, -999, -999, -999, -999, -999, -999, -999,
  115774. -999, -999, -999, -999, -999, -999, -999, -999}},
  115775. /* 11314 Hz */
  115776. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115777. -999, -999, -999, -999, -999, -110, -88, -74,
  115778. -77, -82, -82, -85, -90, -94, -99, -104,
  115779. -999, -999, -999, -999, -999, -999, -999, -999,
  115780. -999, -999, -999, -999, -999, -999, -999, -999,
  115781. -999, -999, -999, -999, -999, -999, -999, -999,
  115782. -999, -999, -999, -999, -999, -999, -999, -999},
  115783. {-999, -999, -999, -999, -999, -999, -999, -999,
  115784. -999, -999, -999, -999, -999, -110, -88, -66,
  115785. -70, -81, -80, -81, -84, -88, -91, -93,
  115786. -999, -999, -999, -999, -999, -999, -999, -999,
  115787. -999, -999, -999, -999, -999, -999, -999, -999,
  115788. -999, -999, -999, -999, -999, -999, -999, -999,
  115789. -999, -999, -999, -999, -999, -999, -999, -999},
  115790. {-999, -999, -999, -999, -999, -999, -999, -999,
  115791. -999, -999, -999, -999, -999, -110, -88, -61,
  115792. -63, -70, -71, -74, -77, -80, -83, -85,
  115793. -999, -999, -999, -999, -999, -999, -999, -999,
  115794. -999, -999, -999, -999, -999, -999, -999, -999,
  115795. -999, -999, -999, -999, -999, -999, -999, -999,
  115796. -999, -999, -999, -999, -999, -999, -999, -999},
  115797. {-999, -999, -999, -999, -999, -999, -999, -999,
  115798. -999, -999, -999, -999, -999, -110, -86, -62,
  115799. -63, -62, -62, -58, -52, -50, -50, -52,
  115800. -54, -999, -999, -999, -999, -999, -999, -999,
  115801. -999, -999, -999, -999, -999, -999, -999, -999,
  115802. -999, -999, -999, -999, -999, -999, -999, -999,
  115803. -999, -999, -999, -999, -999, -999, -999, -999},
  115804. {-999, -999, -999, -999, -999, -999, -999, -999,
  115805. -999, -999, -999, -999, -118, -108, -84, -53,
  115806. -50, -50, -50, -55, -47, -45, -40, -40,
  115807. -40, -999, -999, -999, -999, -999, -999, -999,
  115808. -999, -999, -999, -999, -999, -999, -999, -999,
  115809. -999, -999, -999, -999, -999, -999, -999, -999,
  115810. -999, -999, -999, -999, -999, -999, -999, -999},
  115811. {-999, -999, -999, -999, -999, -999, -999, -999,
  115812. -999, -999, -999, -999, -118, -100, -73, -43,
  115813. -37, -42, -43, -53, -38, -37, -35, -35,
  115814. -38, -999, -999, -999, -999, -999, -999, -999,
  115815. -999, -999, -999, -999, -999, -999, -999, -999,
  115816. -999, -999, -999, -999, -999, -999, -999, -999,
  115817. -999, -999, -999, -999, -999, -999, -999, -999}},
  115818. /* 16000 Hz */
  115819. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115820. -999, -999, -999, -110, -100, -91, -84, -74,
  115821. -80, -80, -80, -80, -80, -999, -999, -999,
  115822. -999, -999, -999, -999, -999, -999, -999, -999,
  115823. -999, -999, -999, -999, -999, -999, -999, -999,
  115824. -999, -999, -999, -999, -999, -999, -999, -999,
  115825. -999, -999, -999, -999, -999, -999, -999, -999},
  115826. {-999, -999, -999, -999, -999, -999, -999, -999,
  115827. -999, -999, -999, -110, -100, -91, -84, -74,
  115828. -68, -68, -68, -68, -68, -999, -999, -999,
  115829. -999, -999, -999, -999, -999, -999, -999, -999,
  115830. -999, -999, -999, -999, -999, -999, -999, -999,
  115831. -999, -999, -999, -999, -999, -999, -999, -999,
  115832. -999, -999, -999, -999, -999, -999, -999, -999},
  115833. {-999, -999, -999, -999, -999, -999, -999, -999,
  115834. -999, -999, -999, -110, -100, -86, -78, -70,
  115835. -60, -45, -30, -21, -999, -999, -999, -999,
  115836. -999, -999, -999, -999, -999, -999, -999, -999,
  115837. -999, -999, -999, -999, -999, -999, -999, -999,
  115838. -999, -999, -999, -999, -999, -999, -999, -999,
  115839. -999, -999, -999, -999, -999, -999, -999, -999},
  115840. {-999, -999, -999, -999, -999, -999, -999, -999,
  115841. -999, -999, -999, -110, -100, -87, -78, -67,
  115842. -48, -38, -29, -21, -999, -999, -999, -999,
  115843. -999, -999, -999, -999, -999, -999, -999, -999,
  115844. -999, -999, -999, -999, -999, -999, -999, -999,
  115845. -999, -999, -999, -999, -999, -999, -999, -999,
  115846. -999, -999, -999, -999, -999, -999, -999, -999},
  115847. {-999, -999, -999, -999, -999, -999, -999, -999,
  115848. -999, -999, -999, -110, -100, -86, -69, -56,
  115849. -45, -35, -33, -29, -999, -999, -999, -999,
  115850. -999, -999, -999, -999, -999, -999, -999, -999,
  115851. -999, -999, -999, -999, -999, -999, -999, -999,
  115852. -999, -999, -999, -999, -999, -999, -999, -999,
  115853. -999, -999, -999, -999, -999, -999, -999, -999},
  115854. {-999, -999, -999, -999, -999, -999, -999, -999,
  115855. -999, -999, -999, -110, -100, -83, -71, -48,
  115856. -27, -38, -37, -34, -999, -999, -999, -999,
  115857. -999, -999, -999, -999, -999, -999, -999, -999,
  115858. -999, -999, -999, -999, -999, -999, -999, -999,
  115859. -999, -999, -999, -999, -999, -999, -999, -999,
  115860. -999, -999, -999, -999, -999, -999, -999, -999}}
  115861. };
  115862. #endif
  115863. /*** End of inlined file: masking.h ***/
  115864. #define NEGINF -9999.f
  115865. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  115866. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  115867. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  115868. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115869. vorbis_info_psy_global *gi=&ci->psy_g_param;
  115870. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  115871. look->channels=vi->channels;
  115872. look->ampmax=-9999.;
  115873. look->gi=gi;
  115874. return(look);
  115875. }
  115876. void _vp_global_free(vorbis_look_psy_global *look){
  115877. if(look){
  115878. memset(look,0,sizeof(*look));
  115879. _ogg_free(look);
  115880. }
  115881. }
  115882. void _vi_gpsy_free(vorbis_info_psy_global *i){
  115883. if(i){
  115884. memset(i,0,sizeof(*i));
  115885. _ogg_free(i);
  115886. }
  115887. }
  115888. void _vi_psy_free(vorbis_info_psy *i){
  115889. if(i){
  115890. memset(i,0,sizeof(*i));
  115891. _ogg_free(i);
  115892. }
  115893. }
  115894. static void min_curve(float *c,
  115895. float *c2){
  115896. int i;
  115897. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  115898. }
  115899. static void max_curve(float *c,
  115900. float *c2){
  115901. int i;
  115902. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  115903. }
  115904. static void attenuate_curve(float *c,float att){
  115905. int i;
  115906. for(i=0;i<EHMER_MAX;i++)
  115907. c[i]+=att;
  115908. }
  115909. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  115910. float center_boost, float center_decay_rate){
  115911. int i,j,k,m;
  115912. float ath[EHMER_MAX];
  115913. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  115914. float athc[P_LEVELS][EHMER_MAX];
  115915. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  115916. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  115917. memset(workc,0,sizeof(workc));
  115918. for(i=0;i<P_BANDS;i++){
  115919. /* we add back in the ATH to avoid low level curves falling off to
  115920. -infinity and unnecessarily cutting off high level curves in the
  115921. curve limiting (last step). */
  115922. /* A half-band's settings must be valid over the whole band, and
  115923. it's better to mask too little than too much */
  115924. int ath_offset=i*4;
  115925. for(j=0;j<EHMER_MAX;j++){
  115926. float min=999.;
  115927. for(k=0;k<4;k++)
  115928. if(j+k+ath_offset<MAX_ATH){
  115929. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  115930. }else{
  115931. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  115932. }
  115933. ath[j]=min;
  115934. }
  115935. /* copy curves into working space, replicate the 50dB curve to 30
  115936. and 40, replicate the 100dB curve to 110 */
  115937. for(j=0;j<6;j++)
  115938. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  115939. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  115940. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  115941. /* apply centered curve boost/decay */
  115942. for(j=0;j<P_LEVELS;j++){
  115943. for(k=0;k<EHMER_MAX;k++){
  115944. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  115945. if(adj<0. && center_boost>0)adj=0.;
  115946. if(adj>0. && center_boost<0)adj=0.;
  115947. workc[i][j][k]+=adj;
  115948. }
  115949. }
  115950. /* normalize curves so the driving amplitude is 0dB */
  115951. /* make temp curves with the ATH overlayed */
  115952. for(j=0;j<P_LEVELS;j++){
  115953. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  115954. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  115955. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  115956. max_curve(athc[j],workc[i][j]);
  115957. }
  115958. /* Now limit the louder curves.
  115959. the idea is this: We don't know what the playback attenuation
  115960. will be; 0dB SL moves every time the user twiddles the volume
  115961. knob. So that means we have to use a single 'most pessimal' curve
  115962. for all masking amplitudes, right? Wrong. The *loudest* sound
  115963. can be in (we assume) a range of ...+100dB] SL. However, sounds
  115964. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  115965. etc... */
  115966. for(j=1;j<P_LEVELS;j++){
  115967. min_curve(athc[j],athc[j-1]);
  115968. min_curve(workc[i][j],athc[j]);
  115969. }
  115970. }
  115971. for(i=0;i<P_BANDS;i++){
  115972. int hi_curve,lo_curve,bin;
  115973. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  115974. /* low frequency curves are measured with greater resolution than
  115975. the MDCT/FFT will actually give us; we want the curve applied
  115976. to the tone data to be pessimistic and thus apply the minimum
  115977. masking possible for a given bin. That means that a single bin
  115978. could span more than one octave and that the curve will be a
  115979. composite of multiple octaves. It also may mean that a single
  115980. bin may span > an eighth of an octave and that the eighth
  115981. octave values may also be composited. */
  115982. /* which octave curves will we be compositing? */
  115983. bin=floor(fromOC(i*.5)/binHz);
  115984. lo_curve= ceil(toOC(bin*binHz+1)*2);
  115985. hi_curve= floor(toOC((bin+1)*binHz)*2);
  115986. if(lo_curve>i)lo_curve=i;
  115987. if(lo_curve<0)lo_curve=0;
  115988. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  115989. for(m=0;m<P_LEVELS;m++){
  115990. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  115991. for(j=0;j<n;j++)brute_buffer[j]=999.;
  115992. /* render the curve into bins, then pull values back into curve.
  115993. The point is that any inherent subsampling aliasing results in
  115994. a safe minimum */
  115995. for(k=lo_curve;k<=hi_curve;k++){
  115996. int l=0;
  115997. for(j=0;j<EHMER_MAX;j++){
  115998. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  115999. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116000. if(lo_bin<0)lo_bin=0;
  116001. if(lo_bin>n)lo_bin=n;
  116002. if(lo_bin<l)l=lo_bin;
  116003. if(hi_bin<0)hi_bin=0;
  116004. if(hi_bin>n)hi_bin=n;
  116005. for(;l<hi_bin && l<n;l++)
  116006. if(brute_buffer[l]>workc[k][m][j])
  116007. brute_buffer[l]=workc[k][m][j];
  116008. }
  116009. for(;l<n;l++)
  116010. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116011. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116012. }
  116013. /* be equally paranoid about being valid up to next half ocatve */
  116014. if(i+1<P_BANDS){
  116015. int l=0;
  116016. k=i+1;
  116017. for(j=0;j<EHMER_MAX;j++){
  116018. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116019. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116020. if(lo_bin<0)lo_bin=0;
  116021. if(lo_bin>n)lo_bin=n;
  116022. if(lo_bin<l)l=lo_bin;
  116023. if(hi_bin<0)hi_bin=0;
  116024. if(hi_bin>n)hi_bin=n;
  116025. for(;l<hi_bin && l<n;l++)
  116026. if(brute_buffer[l]>workc[k][m][j])
  116027. brute_buffer[l]=workc[k][m][j];
  116028. }
  116029. for(;l<n;l++)
  116030. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116031. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116032. }
  116033. for(j=0;j<EHMER_MAX;j++){
  116034. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116035. if(bin<0){
  116036. ret[i][m][j+2]=-999.;
  116037. }else{
  116038. if(bin>=n){
  116039. ret[i][m][j+2]=-999.;
  116040. }else{
  116041. ret[i][m][j+2]=brute_buffer[bin];
  116042. }
  116043. }
  116044. }
  116045. /* add fenceposts */
  116046. for(j=0;j<EHMER_OFFSET;j++)
  116047. if(ret[i][m][j+2]>-200.f)break;
  116048. ret[i][m][0]=j;
  116049. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116050. if(ret[i][m][j+2]>-200.f)
  116051. break;
  116052. ret[i][m][1]=j;
  116053. }
  116054. }
  116055. return(ret);
  116056. }
  116057. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116058. vorbis_info_psy_global *gi,int n,long rate){
  116059. long i,j,lo=-99,hi=1;
  116060. long maxoc;
  116061. memset(p,0,sizeof(*p));
  116062. p->eighth_octave_lines=gi->eighth_octave_lines;
  116063. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116064. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116065. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116066. p->total_octave_lines=maxoc-p->firstoc+1;
  116067. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116068. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116069. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116070. p->vi=vi;
  116071. p->n=n;
  116072. p->rate=rate;
  116073. /* AoTuV HF weighting */
  116074. p->m_val = 1.;
  116075. if(rate < 26000) p->m_val = 0;
  116076. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116077. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116078. /* set up the lookups for a given blocksize and sample rate */
  116079. for(i=0,j=0;i<MAX_ATH-1;i++){
  116080. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116081. float base=ATH[i];
  116082. if(j<endpos){
  116083. float delta=(ATH[i+1]-base)/(endpos-j);
  116084. for(;j<endpos && j<n;j++){
  116085. p->ath[j]=base+100.;
  116086. base+=delta;
  116087. }
  116088. }
  116089. }
  116090. for(i=0;i<n;i++){
  116091. float bark=toBARK(rate/(2*n)*i);
  116092. for(;lo+vi->noisewindowlomin<i &&
  116093. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116094. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116095. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116096. p->bark[i]=((lo-1)<<16)+(hi-1);
  116097. }
  116098. for(i=0;i<n;i++)
  116099. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116100. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116101. vi->tone_centerboost,vi->tone_decay);
  116102. /* set up rolling noise median */
  116103. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116104. for(i=0;i<P_NOISECURVES;i++)
  116105. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116106. for(i=0;i<n;i++){
  116107. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116108. int inthalfoc;
  116109. float del;
  116110. if(halfoc<0)halfoc=0;
  116111. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116112. inthalfoc=(int)halfoc;
  116113. del=halfoc-inthalfoc;
  116114. for(j=0;j<P_NOISECURVES;j++)
  116115. p->noiseoffset[j][i]=
  116116. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116117. p->vi->noiseoff[j][inthalfoc+1]*del;
  116118. }
  116119. #if 0
  116120. {
  116121. static int ls=0;
  116122. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116123. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116124. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  116125. }
  116126. #endif
  116127. }
  116128. void _vp_psy_clear(vorbis_look_psy *p){
  116129. int i,j;
  116130. if(p){
  116131. if(p->ath)_ogg_free(p->ath);
  116132. if(p->octave)_ogg_free(p->octave);
  116133. if(p->bark)_ogg_free(p->bark);
  116134. if(p->tonecurves){
  116135. for(i=0;i<P_BANDS;i++){
  116136. for(j=0;j<P_LEVELS;j++){
  116137. _ogg_free(p->tonecurves[i][j]);
  116138. }
  116139. _ogg_free(p->tonecurves[i]);
  116140. }
  116141. _ogg_free(p->tonecurves);
  116142. }
  116143. if(p->noiseoffset){
  116144. for(i=0;i<P_NOISECURVES;i++){
  116145. _ogg_free(p->noiseoffset[i]);
  116146. }
  116147. _ogg_free(p->noiseoffset);
  116148. }
  116149. memset(p,0,sizeof(*p));
  116150. }
  116151. }
  116152. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  116153. static void seed_curve(float *seed,
  116154. const float **curves,
  116155. float amp,
  116156. int oc, int n,
  116157. int linesper,float dBoffset){
  116158. int i,post1;
  116159. int seedptr;
  116160. const float *posts,*curve;
  116161. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  116162. choice=max(choice,0);
  116163. choice=min(choice,P_LEVELS-1);
  116164. posts=curves[choice];
  116165. curve=posts+2;
  116166. post1=(int)posts[1];
  116167. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  116168. for(i=posts[0];i<post1;i++){
  116169. if(seedptr>0){
  116170. float lin=amp+curve[i];
  116171. if(seed[seedptr]<lin)seed[seedptr]=lin;
  116172. }
  116173. seedptr+=linesper;
  116174. if(seedptr>=n)break;
  116175. }
  116176. }
  116177. static void seed_loop(vorbis_look_psy *p,
  116178. const float ***curves,
  116179. const float *f,
  116180. const float *flr,
  116181. float *seed,
  116182. float specmax){
  116183. vorbis_info_psy *vi=p->vi;
  116184. long n=p->n,i;
  116185. float dBoffset=vi->max_curve_dB-specmax;
  116186. /* prime the working vector with peak values */
  116187. for(i=0;i<n;i++){
  116188. float max=f[i];
  116189. long oc=p->octave[i];
  116190. while(i+1<n && p->octave[i+1]==oc){
  116191. i++;
  116192. if(f[i]>max)max=f[i];
  116193. }
  116194. if(max+6.f>flr[i]){
  116195. oc=oc>>p->shiftoc;
  116196. if(oc>=P_BANDS)oc=P_BANDS-1;
  116197. if(oc<0)oc=0;
  116198. seed_curve(seed,
  116199. curves[oc],
  116200. max,
  116201. p->octave[i]-p->firstoc,
  116202. p->total_octave_lines,
  116203. p->eighth_octave_lines,
  116204. dBoffset);
  116205. }
  116206. }
  116207. }
  116208. static void seed_chase(float *seeds, int linesper, long n){
  116209. long *posstack=(long*)alloca(n*sizeof(*posstack));
  116210. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  116211. long stack=0;
  116212. long pos=0;
  116213. long i;
  116214. for(i=0;i<n;i++){
  116215. if(stack<2){
  116216. posstack[stack]=i;
  116217. ampstack[stack++]=seeds[i];
  116218. }else{
  116219. while(1){
  116220. if(seeds[i]<ampstack[stack-1]){
  116221. posstack[stack]=i;
  116222. ampstack[stack++]=seeds[i];
  116223. break;
  116224. }else{
  116225. if(i<posstack[stack-1]+linesper){
  116226. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  116227. i<posstack[stack-2]+linesper){
  116228. /* we completely overlap, making stack-1 irrelevant. pop it */
  116229. stack--;
  116230. continue;
  116231. }
  116232. }
  116233. posstack[stack]=i;
  116234. ampstack[stack++]=seeds[i];
  116235. break;
  116236. }
  116237. }
  116238. }
  116239. }
  116240. /* the stack now contains only the positions that are relevant. Scan
  116241. 'em straight through */
  116242. for(i=0;i<stack;i++){
  116243. long endpos;
  116244. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  116245. endpos=posstack[i+1];
  116246. }else{
  116247. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  116248. discarded in short frames */
  116249. }
  116250. if(endpos>n)endpos=n;
  116251. for(;pos<endpos;pos++)
  116252. seeds[pos]=ampstack[i];
  116253. }
  116254. /* there. Linear time. I now remember this was on a problem set I
  116255. had in Grad Skool... I didn't solve it at the time ;-) */
  116256. }
  116257. /* bleaugh, this is more complicated than it needs to be */
  116258. #include<stdio.h>
  116259. static void max_seeds(vorbis_look_psy *p,
  116260. float *seed,
  116261. float *flr){
  116262. long n=p->total_octave_lines;
  116263. int linesper=p->eighth_octave_lines;
  116264. long linpos=0;
  116265. long pos;
  116266. seed_chase(seed,linesper,n); /* for masking */
  116267. pos=p->octave[0]-p->firstoc-(linesper>>1);
  116268. while(linpos+1<p->n){
  116269. float minV=seed[pos];
  116270. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  116271. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  116272. while(pos+1<=end){
  116273. pos++;
  116274. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  116275. minV=seed[pos];
  116276. }
  116277. end=pos+p->firstoc;
  116278. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  116279. if(flr[linpos]<minV)flr[linpos]=minV;
  116280. }
  116281. {
  116282. float minV=seed[p->total_octave_lines-1];
  116283. for(;linpos<p->n;linpos++)
  116284. if(flr[linpos]<minV)flr[linpos]=minV;
  116285. }
  116286. }
  116287. static void bark_noise_hybridmp(int n,const long *b,
  116288. const float *f,
  116289. float *noise,
  116290. const float offset,
  116291. const int fixed){
  116292. float *N=(float*) alloca(n*sizeof(*N));
  116293. float *X=(float*) alloca(n*sizeof(*N));
  116294. float *XX=(float*) alloca(n*sizeof(*N));
  116295. float *Y=(float*) alloca(n*sizeof(*N));
  116296. float *XY=(float*) alloca(n*sizeof(*N));
  116297. float tN, tX, tXX, tY, tXY;
  116298. int i;
  116299. int lo, hi;
  116300. float R, A, B, D;
  116301. float w, x, y;
  116302. tN = tX = tXX = tY = tXY = 0.f;
  116303. y = f[0] + offset;
  116304. if (y < 1.f) y = 1.f;
  116305. w = y * y * .5;
  116306. tN += w;
  116307. tX += w;
  116308. tY += w * y;
  116309. N[0] = tN;
  116310. X[0] = tX;
  116311. XX[0] = tXX;
  116312. Y[0] = tY;
  116313. XY[0] = tXY;
  116314. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  116315. y = f[i] + offset;
  116316. if (y < 1.f) y = 1.f;
  116317. w = y * y;
  116318. tN += w;
  116319. tX += w * x;
  116320. tXX += w * x * x;
  116321. tY += w * y;
  116322. tXY += w * x * y;
  116323. N[i] = tN;
  116324. X[i] = tX;
  116325. XX[i] = tXX;
  116326. Y[i] = tY;
  116327. XY[i] = tXY;
  116328. }
  116329. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116330. lo = b[i] >> 16;
  116331. if( lo>=0 ) break;
  116332. hi = b[i] & 0xffff;
  116333. tN = N[hi] + N[-lo];
  116334. tX = X[hi] - X[-lo];
  116335. tXX = XX[hi] + XX[-lo];
  116336. tY = Y[hi] + Y[-lo];
  116337. tXY = XY[hi] - XY[-lo];
  116338. A = tY * tXX - tX * tXY;
  116339. B = tN * tXY - tX * tY;
  116340. D = tN * tXX - tX * tX;
  116341. R = (A + x * B) / D;
  116342. if (R < 0.f)
  116343. R = 0.f;
  116344. noise[i] = R - offset;
  116345. }
  116346. for ( ;; i++, x += 1.f) {
  116347. lo = b[i] >> 16;
  116348. hi = b[i] & 0xffff;
  116349. if(hi>=n)break;
  116350. tN = N[hi] - N[lo];
  116351. tX = X[hi] - X[lo];
  116352. tXX = XX[hi] - XX[lo];
  116353. tY = Y[hi] - Y[lo];
  116354. tXY = XY[hi] - XY[lo];
  116355. A = tY * tXX - tX * tXY;
  116356. B = tN * tXY - tX * tY;
  116357. D = tN * tXX - tX * tX;
  116358. R = (A + x * B) / D;
  116359. if (R < 0.f) R = 0.f;
  116360. noise[i] = R - offset;
  116361. }
  116362. for ( ; i < n; i++, x += 1.f) {
  116363. R = (A + x * B) / D;
  116364. if (R < 0.f) R = 0.f;
  116365. noise[i] = R - offset;
  116366. }
  116367. if (fixed <= 0) return;
  116368. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116369. hi = i + fixed / 2;
  116370. lo = hi - fixed;
  116371. if(lo>=0)break;
  116372. tN = N[hi] + N[-lo];
  116373. tX = X[hi] - X[-lo];
  116374. tXX = XX[hi] + XX[-lo];
  116375. tY = Y[hi] + Y[-lo];
  116376. tXY = XY[hi] - XY[-lo];
  116377. A = tY * tXX - tX * tXY;
  116378. B = tN * tXY - tX * tY;
  116379. D = tN * tXX - tX * tX;
  116380. R = (A + x * B) / D;
  116381. if (R - offset < noise[i]) noise[i] = R - offset;
  116382. }
  116383. for ( ;; i++, x += 1.f) {
  116384. hi = i + fixed / 2;
  116385. lo = hi - fixed;
  116386. if(hi>=n)break;
  116387. tN = N[hi] - N[lo];
  116388. tX = X[hi] - X[lo];
  116389. tXX = XX[hi] - XX[lo];
  116390. tY = Y[hi] - Y[lo];
  116391. tXY = XY[hi] - XY[lo];
  116392. A = tY * tXX - tX * tXY;
  116393. B = tN * tXY - tX * tY;
  116394. D = tN * tXX - tX * tX;
  116395. R = (A + x * B) / D;
  116396. if (R - offset < noise[i]) noise[i] = R - offset;
  116397. }
  116398. for ( ; i < n; i++, x += 1.f) {
  116399. R = (A + x * B) / D;
  116400. if (R - offset < noise[i]) noise[i] = R - offset;
  116401. }
  116402. }
  116403. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  116404. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  116405. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  116406. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  116407. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  116408. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  116409. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  116410. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  116411. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  116412. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  116413. 973377.F, 913981.F, 858210.F, 805842.F,
  116414. 756669.F, 710497.F, 667142.F, 626433.F,
  116415. 588208.F, 552316.F, 518613.F, 486967.F,
  116416. 457252.F, 429351.F, 403152.F, 378551.F,
  116417. 355452.F, 333762.F, 313396.F, 294273.F,
  116418. 276316.F, 259455.F, 243623.F, 228757.F,
  116419. 214798.F, 201691.F, 189384.F, 177828.F,
  116420. 166977.F, 156788.F, 147221.F, 138237.F,
  116421. 129802.F, 121881.F, 114444.F, 107461.F,
  116422. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  116423. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  116424. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  116425. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  116426. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  116427. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  116428. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  116429. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  116430. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  116431. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  116432. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  116433. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  116434. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  116435. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  116436. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  116437. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  116438. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  116439. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  116440. 1084.32F, 1018.15F, 956.024F, 897.687F,
  116441. 842.910F, 791.475F, 743.179F, 697.830F,
  116442. 655.249F, 615.265F, 577.722F, 542.469F,
  116443. 509.367F, 478.286F, 449.101F, 421.696F,
  116444. 395.964F, 371.803F, 349.115F, 327.812F,
  116445. 307.809F, 289.026F, 271.390F, 254.830F,
  116446. 239.280F, 224.679F, 210.969F, 198.096F,
  116447. 186.008F, 174.658F, 164.000F, 153.993F,
  116448. 144.596F, 135.773F, 127.488F, 119.708F,
  116449. 112.404F, 105.545F, 99.1046F, 93.0572F,
  116450. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  116451. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  116452. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  116453. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  116454. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  116455. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  116456. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  116457. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  116458. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  116459. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  116460. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  116461. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  116462. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  116463. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  116464. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  116465. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  116466. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  116467. 1.20790F, 1.13419F, 1.06499F, 1.F
  116468. };
  116469. void _vp_remove_floor(vorbis_look_psy *p,
  116470. float *mdct,
  116471. int *codedflr,
  116472. float *residue,
  116473. int sliding_lowpass){
  116474. int i,n=p->n;
  116475. if(sliding_lowpass>n)sliding_lowpass=n;
  116476. for(i=0;i<sliding_lowpass;i++){
  116477. residue[i]=
  116478. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  116479. }
  116480. for(;i<n;i++)
  116481. residue[i]=0.;
  116482. }
  116483. void _vp_noisemask(vorbis_look_psy *p,
  116484. float *logmdct,
  116485. float *logmask){
  116486. int i,n=p->n;
  116487. float *work=(float*) alloca(n*sizeof(*work));
  116488. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  116489. 140.,-1);
  116490. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  116491. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  116492. p->vi->noisewindowfixed);
  116493. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  116494. #if 0
  116495. {
  116496. static int seq=0;
  116497. float work2[n];
  116498. for(i=0;i<n;i++){
  116499. work2[i]=logmask[i]+work[i];
  116500. }
  116501. if(seq&1)
  116502. _analysis_output("median2R",seq/2,work,n,1,0,0);
  116503. else
  116504. _analysis_output("median2L",seq/2,work,n,1,0,0);
  116505. if(seq&1)
  116506. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  116507. else
  116508. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  116509. seq++;
  116510. }
  116511. #endif
  116512. for(i=0;i<n;i++){
  116513. int dB=logmask[i]+.5;
  116514. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  116515. if(dB<0)dB=0;
  116516. logmask[i]= work[i]+p->vi->noisecompand[dB];
  116517. }
  116518. }
  116519. void _vp_tonemask(vorbis_look_psy *p,
  116520. float *logfft,
  116521. float *logmask,
  116522. float global_specmax,
  116523. float local_specmax){
  116524. int i,n=p->n;
  116525. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  116526. float att=local_specmax+p->vi->ath_adjatt;
  116527. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  116528. /* set the ATH (floating below localmax, not global max by a
  116529. specified att) */
  116530. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  116531. for(i=0;i<n;i++)
  116532. logmask[i]=p->ath[i]+att;
  116533. /* tone masking */
  116534. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  116535. max_seeds(p,seed,logmask);
  116536. }
  116537. void _vp_offset_and_mix(vorbis_look_psy *p,
  116538. float *noise,
  116539. float *tone,
  116540. int offset_select,
  116541. float *logmask,
  116542. float *mdct,
  116543. float *logmdct){
  116544. int i,n=p->n;
  116545. float de, coeffi, cx;/* AoTuV */
  116546. float toneatt=p->vi->tone_masteratt[offset_select];
  116547. cx = p->m_val;
  116548. for(i=0;i<n;i++){
  116549. float val= noise[i]+p->noiseoffset[offset_select][i];
  116550. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  116551. logmask[i]=max(val,tone[i]+toneatt);
  116552. /* AoTuV */
  116553. /** @ M1 **
  116554. The following codes improve a noise problem.
  116555. A fundamental idea uses the value of masking and carries out
  116556. the relative compensation of the MDCT.
  116557. However, this code is not perfect and all noise problems cannot be solved.
  116558. by Aoyumi @ 2004/04/18
  116559. */
  116560. if(offset_select == 1) {
  116561. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  116562. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  116563. if(val > coeffi){
  116564. /* mdct value is > -17.2 dB below floor */
  116565. de = 1.0-((val-coeffi)*0.005*cx);
  116566. /* pro-rated attenuation:
  116567. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  116568. -0.77 dB boost if mdct value is 0dB (relative to floor)
  116569. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  116570. etc... */
  116571. if(de < 0) de = 0.0001;
  116572. }else
  116573. /* mdct value is <= -17.2 dB below floor */
  116574. de = 1.0-((val-coeffi)*0.0003*cx);
  116575. /* pro-rated attenuation:
  116576. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  116577. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  116578. etc... */
  116579. mdct[i] *= de;
  116580. }
  116581. }
  116582. }
  116583. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  116584. vorbis_info *vi=vd->vi;
  116585. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116586. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116587. int n=ci->blocksizes[vd->W]/2;
  116588. float secs=(float)n/vi->rate;
  116589. amp+=secs*gi->ampmax_att_per_sec;
  116590. if(amp<-9999)amp=-9999;
  116591. return(amp);
  116592. }
  116593. static void couple_lossless(float A, float B,
  116594. float *qA, float *qB){
  116595. int test1=fabs(*qA)>fabs(*qB);
  116596. test1-= fabs(*qA)<fabs(*qB);
  116597. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  116598. if(test1==1){
  116599. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  116600. }else{
  116601. float temp=*qB;
  116602. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  116603. *qA=temp;
  116604. }
  116605. if(*qB>fabs(*qA)*1.9999f){
  116606. *qB= -fabs(*qA)*2.f;
  116607. *qA= -*qA;
  116608. }
  116609. }
  116610. static float hypot_lookup[32]={
  116611. -0.009935, -0.011245, -0.012726, -0.014397,
  116612. -0.016282, -0.018407, -0.020800, -0.023494,
  116613. -0.026522, -0.029923, -0.033737, -0.038010,
  116614. -0.042787, -0.048121, -0.054064, -0.060671,
  116615. -0.068000, -0.076109, -0.085054, -0.094892,
  116616. -0.105675, -0.117451, -0.130260, -0.144134,
  116617. -0.159093, -0.175146, -0.192286, -0.210490,
  116618. -0.229718, -0.249913, -0.271001, -0.292893};
  116619. static void precomputed_couple_point(float premag,
  116620. int floorA,int floorB,
  116621. float *mag, float *ang){
  116622. int test=(floorA>floorB)-1;
  116623. int offset=31-abs(floorA-floorB);
  116624. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  116625. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  116626. *mag=premag*floormag;
  116627. *ang=0.f;
  116628. }
  116629. /* just like below, this is currently set up to only do
  116630. single-step-depth coupling. Otherwise, we'd have to do more
  116631. copying (which will be inevitable later) */
  116632. /* doing the real circular magnitude calculation is audibly superior
  116633. to (A+B)/sqrt(2) */
  116634. static float dipole_hypot(float a, float b){
  116635. if(a>0.){
  116636. if(b>0.)return sqrt(a*a+b*b);
  116637. if(a>-b)return sqrt(a*a-b*b);
  116638. return -sqrt(b*b-a*a);
  116639. }
  116640. if(b<0.)return -sqrt(a*a+b*b);
  116641. if(-a>b)return -sqrt(a*a-b*b);
  116642. return sqrt(b*b-a*a);
  116643. }
  116644. static float round_hypot(float a, float b){
  116645. if(a>0.){
  116646. if(b>0.)return sqrt(a*a+b*b);
  116647. if(a>-b)return sqrt(a*a+b*b);
  116648. return -sqrt(b*b+a*a);
  116649. }
  116650. if(b<0.)return -sqrt(a*a+b*b);
  116651. if(-a>b)return -sqrt(a*a+b*b);
  116652. return sqrt(b*b+a*a);
  116653. }
  116654. /* revert to round hypot for now */
  116655. float **_vp_quantize_couple_memo(vorbis_block *vb,
  116656. vorbis_info_psy_global *g,
  116657. vorbis_look_psy *p,
  116658. vorbis_info_mapping0 *vi,
  116659. float **mdct){
  116660. int i,j,n=p->n;
  116661. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  116662. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  116663. for(i=0;i<vi->coupling_steps;i++){
  116664. float *mdctM=mdct[vi->coupling_mag[i]];
  116665. float *mdctA=mdct[vi->coupling_ang[i]];
  116666. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  116667. for(j=0;j<limit;j++)
  116668. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  116669. for(;j<n;j++)
  116670. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  116671. }
  116672. return(ret);
  116673. }
  116674. /* this is for per-channel noise normalization */
  116675. static int apsort(const void *a, const void *b){
  116676. float f1=fabs(**(float**)a);
  116677. float f2=fabs(**(float**)b);
  116678. return (f1<f2)-(f1>f2);
  116679. }
  116680. int **_vp_quantize_couple_sort(vorbis_block *vb,
  116681. vorbis_look_psy *p,
  116682. vorbis_info_mapping0 *vi,
  116683. float **mags){
  116684. if(p->vi->normal_point_p){
  116685. int i,j,k,n=p->n;
  116686. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  116687. int partition=p->vi->normal_partition;
  116688. float **work=(float**) alloca(sizeof(*work)*partition);
  116689. for(i=0;i<vi->coupling_steps;i++){
  116690. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  116691. for(j=0;j<n;j+=partition){
  116692. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  116693. qsort(work,partition,sizeof(*work),apsort);
  116694. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  116695. }
  116696. }
  116697. return(ret);
  116698. }
  116699. return(NULL);
  116700. }
  116701. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  116702. float *magnitudes,int *sortedindex){
  116703. int i,j,n=p->n;
  116704. vorbis_info_psy *vi=p->vi;
  116705. int partition=vi->normal_partition;
  116706. float **work=(float**) alloca(sizeof(*work)*partition);
  116707. int start=vi->normal_start;
  116708. for(j=start;j<n;j+=partition){
  116709. if(j+partition>n)partition=n-j;
  116710. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  116711. qsort(work,partition,sizeof(*work),apsort);
  116712. for(i=0;i<partition;i++){
  116713. sortedindex[i+j-start]=work[i]-magnitudes;
  116714. }
  116715. }
  116716. }
  116717. void _vp_noise_normalize(vorbis_look_psy *p,
  116718. float *in,float *out,int *sortedindex){
  116719. int flag=0,i,j=0,n=p->n;
  116720. vorbis_info_psy *vi=p->vi;
  116721. int partition=vi->normal_partition;
  116722. int start=vi->normal_start;
  116723. if(start>n)start=n;
  116724. if(vi->normal_channel_p){
  116725. for(;j<start;j++)
  116726. out[j]=rint(in[j]);
  116727. for(;j+partition<=n;j+=partition){
  116728. float acc=0.;
  116729. int k;
  116730. for(i=j;i<j+partition;i++)
  116731. acc+=in[i]*in[i];
  116732. for(i=0;i<partition;i++){
  116733. k=sortedindex[i+j-start];
  116734. if(in[k]*in[k]>=.25f){
  116735. out[k]=rint(in[k]);
  116736. acc-=in[k]*in[k];
  116737. flag=1;
  116738. }else{
  116739. if(acc<vi->normal_thresh)break;
  116740. out[k]=unitnorm(in[k]);
  116741. acc-=1.;
  116742. }
  116743. }
  116744. for(;i<partition;i++){
  116745. k=sortedindex[i+j-start];
  116746. out[k]=0.;
  116747. }
  116748. }
  116749. }
  116750. for(;j<n;j++)
  116751. out[j]=rint(in[j]);
  116752. }
  116753. void _vp_couple(int blobno,
  116754. vorbis_info_psy_global *g,
  116755. vorbis_look_psy *p,
  116756. vorbis_info_mapping0 *vi,
  116757. float **res,
  116758. float **mag_memo,
  116759. int **mag_sort,
  116760. int **ifloor,
  116761. int *nonzero,
  116762. int sliding_lowpass){
  116763. int i,j,k,n=p->n;
  116764. /* perform any requested channel coupling */
  116765. /* point stereo can only be used in a first stage (in this encoder)
  116766. because of the dependency on floor lookups */
  116767. for(i=0;i<vi->coupling_steps;i++){
  116768. /* once we're doing multistage coupling in which a channel goes
  116769. through more than one coupling step, the floor vector
  116770. magnitudes will also have to be recalculated an propogated
  116771. along with PCM. Right now, we're not (that will wait until 5.1
  116772. most likely), so the code isn't here yet. The memory management
  116773. here is all assuming single depth couplings anyway. */
  116774. /* make sure coupling a zero and a nonzero channel results in two
  116775. nonzero channels. */
  116776. if(nonzero[vi->coupling_mag[i]] ||
  116777. nonzero[vi->coupling_ang[i]]){
  116778. float *rM=res[vi->coupling_mag[i]];
  116779. float *rA=res[vi->coupling_ang[i]];
  116780. float *qM=rM+n;
  116781. float *qA=rA+n;
  116782. int *floorM=ifloor[vi->coupling_mag[i]];
  116783. int *floorA=ifloor[vi->coupling_ang[i]];
  116784. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  116785. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  116786. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  116787. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  116788. int pointlimit=limit;
  116789. nonzero[vi->coupling_mag[i]]=1;
  116790. nonzero[vi->coupling_ang[i]]=1;
  116791. /* The threshold of a stereo is changed with the size of n */
  116792. if(n > 1000)
  116793. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  116794. for(j=0;j<p->n;j+=partition){
  116795. float acc=0.f;
  116796. for(k=0;k<partition;k++){
  116797. int l=k+j;
  116798. if(l<sliding_lowpass){
  116799. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  116800. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  116801. precomputed_couple_point(mag_memo[i][l],
  116802. floorM[l],floorA[l],
  116803. qM+l,qA+l);
  116804. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  116805. }else{
  116806. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  116807. }
  116808. }else{
  116809. qM[l]=0.;
  116810. qA[l]=0.;
  116811. }
  116812. }
  116813. if(p->vi->normal_point_p){
  116814. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  116815. int l=mag_sort[i][j+k];
  116816. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  116817. qM[l]=unitnorm(qM[l]);
  116818. acc-=1.f;
  116819. }
  116820. }
  116821. }
  116822. }
  116823. }
  116824. }
  116825. }
  116826. /* AoTuV */
  116827. /** @ M2 **
  116828. The boost problem by the combination of noise normalization and point stereo is eased.
  116829. However, this is a temporary patch.
  116830. by Aoyumi @ 2004/04/18
  116831. */
  116832. void hf_reduction(vorbis_info_psy_global *g,
  116833. vorbis_look_psy *p,
  116834. vorbis_info_mapping0 *vi,
  116835. float **mdct){
  116836. int i,j,n=p->n, de=0.3*p->m_val;
  116837. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  116838. for(i=0; i<vi->coupling_steps; i++){
  116839. /* for(j=start; j<limit; j++){} // ???*/
  116840. for(j=limit; j<n; j++)
  116841. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  116842. }
  116843. }
  116844. #endif
  116845. /*** End of inlined file: psy.c ***/
  116846. /*** Start of inlined file: registry.c ***/
  116847. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116848. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116849. // tasks..
  116850. #if JUCE_MSVC
  116851. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116852. #endif
  116853. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116854. #if JUCE_USE_OGGVORBIS
  116855. /* seems like major overkill now; the backend numbers will grow into
  116856. the infrastructure soon enough */
  116857. extern vorbis_func_floor floor0_exportbundle;
  116858. extern vorbis_func_floor floor1_exportbundle;
  116859. extern vorbis_func_residue residue0_exportbundle;
  116860. extern vorbis_func_residue residue1_exportbundle;
  116861. extern vorbis_func_residue residue2_exportbundle;
  116862. extern vorbis_func_mapping mapping0_exportbundle;
  116863. vorbis_func_floor *_floor_P[]={
  116864. &floor0_exportbundle,
  116865. &floor1_exportbundle,
  116866. };
  116867. vorbis_func_residue *_residue_P[]={
  116868. &residue0_exportbundle,
  116869. &residue1_exportbundle,
  116870. &residue2_exportbundle,
  116871. };
  116872. vorbis_func_mapping *_mapping_P[]={
  116873. &mapping0_exportbundle,
  116874. };
  116875. #endif
  116876. /*** End of inlined file: registry.c ***/
  116877. /*** Start of inlined file: res0.c ***/
  116878. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  116879. encode/decode loops are coded for clarity and performance is not
  116880. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  116881. it's slow. */
  116882. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116883. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116884. // tasks..
  116885. #if JUCE_MSVC
  116886. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116887. #endif
  116888. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116889. #if JUCE_USE_OGGVORBIS
  116890. #include <stdlib.h>
  116891. #include <string.h>
  116892. #include <math.h>
  116893. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  116894. #include <stdio.h>
  116895. #endif
  116896. typedef struct {
  116897. vorbis_info_residue0 *info;
  116898. int parts;
  116899. int stages;
  116900. codebook *fullbooks;
  116901. codebook *phrasebook;
  116902. codebook ***partbooks;
  116903. int partvals;
  116904. int **decodemap;
  116905. long postbits;
  116906. long phrasebits;
  116907. long frames;
  116908. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  116909. int train_seq;
  116910. long *training_data[8][64];
  116911. float training_max[8][64];
  116912. float training_min[8][64];
  116913. float tmin;
  116914. float tmax;
  116915. #endif
  116916. } vorbis_look_residue0;
  116917. void res0_free_info(vorbis_info_residue *i){
  116918. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  116919. if(info){
  116920. memset(info,0,sizeof(*info));
  116921. _ogg_free(info);
  116922. }
  116923. }
  116924. void res0_free_look(vorbis_look_residue *i){
  116925. int j;
  116926. if(i){
  116927. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  116928. #ifdef TRAIN_RES
  116929. {
  116930. int j,k,l;
  116931. for(j=0;j<look->parts;j++){
  116932. /*fprintf(stderr,"partition %d: ",j);*/
  116933. for(k=0;k<8;k++)
  116934. if(look->training_data[k][j]){
  116935. char buffer[80];
  116936. FILE *of;
  116937. codebook *statebook=look->partbooks[j][k];
  116938. /* long and short into the same bucket by current convention */
  116939. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  116940. of=fopen(buffer,"a");
  116941. for(l=0;l<statebook->entries;l++)
  116942. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  116943. fclose(of);
  116944. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  116945. look->training_min[k][j],look->training_max[k][j]);*/
  116946. _ogg_free(look->training_data[k][j]);
  116947. look->training_data[k][j]=NULL;
  116948. }
  116949. /*fprintf(stderr,"\n");*/
  116950. }
  116951. }
  116952. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  116953. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  116954. (float)look->phrasebits/look->frames,
  116955. (float)look->postbits/look->frames,
  116956. (float)(look->postbits+look->phrasebits)/look->frames);*/
  116957. #endif
  116958. /*vorbis_info_residue0 *info=look->info;
  116959. fprintf(stderr,
  116960. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  116961. "(%g/frame) \n",look->frames,look->phrasebits,
  116962. look->resbitsflat,
  116963. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  116964. for(j=0;j<look->parts;j++){
  116965. long acc=0;
  116966. fprintf(stderr,"\t[%d] == ",j);
  116967. for(k=0;k<look->stages;k++)
  116968. if((info->secondstages[j]>>k)&1){
  116969. fprintf(stderr,"%ld,",look->resbits[j][k]);
  116970. acc+=look->resbits[j][k];
  116971. }
  116972. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  116973. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  116974. }
  116975. fprintf(stderr,"\n");*/
  116976. for(j=0;j<look->parts;j++)
  116977. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  116978. _ogg_free(look->partbooks);
  116979. for(j=0;j<look->partvals;j++)
  116980. _ogg_free(look->decodemap[j]);
  116981. _ogg_free(look->decodemap);
  116982. memset(look,0,sizeof(*look));
  116983. _ogg_free(look);
  116984. }
  116985. }
  116986. static int icount(unsigned int v){
  116987. int ret=0;
  116988. while(v){
  116989. ret+=v&1;
  116990. v>>=1;
  116991. }
  116992. return(ret);
  116993. }
  116994. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  116995. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  116996. int j,acc=0;
  116997. oggpack_write(opb,info->begin,24);
  116998. oggpack_write(opb,info->end,24);
  116999. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117000. code with a partitioned book */
  117001. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117002. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117003. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117004. bitmask of one indicates this partition class has bits to write
  117005. this pass */
  117006. for(j=0;j<info->partitions;j++){
  117007. if(ilog(info->secondstages[j])>3){
  117008. /* yes, this is a minor hack due to not thinking ahead */
  117009. oggpack_write(opb,info->secondstages[j],3);
  117010. oggpack_write(opb,1,1);
  117011. oggpack_write(opb,info->secondstages[j]>>3,5);
  117012. }else
  117013. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117014. acc+=icount(info->secondstages[j]);
  117015. }
  117016. for(j=0;j<acc;j++)
  117017. oggpack_write(opb,info->booklist[j],8);
  117018. }
  117019. /* vorbis_info is for range checking */
  117020. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117021. int j,acc=0;
  117022. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117023. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117024. info->begin=oggpack_read(opb,24);
  117025. info->end=oggpack_read(opb,24);
  117026. info->grouping=oggpack_read(opb,24)+1;
  117027. info->partitions=oggpack_read(opb,6)+1;
  117028. info->groupbook=oggpack_read(opb,8);
  117029. for(j=0;j<info->partitions;j++){
  117030. int cascade=oggpack_read(opb,3);
  117031. if(oggpack_read(opb,1))
  117032. cascade|=(oggpack_read(opb,5)<<3);
  117033. info->secondstages[j]=cascade;
  117034. acc+=icount(cascade);
  117035. }
  117036. for(j=0;j<acc;j++)
  117037. info->booklist[j]=oggpack_read(opb,8);
  117038. if(info->groupbook>=ci->books)goto errout;
  117039. for(j=0;j<acc;j++)
  117040. if(info->booklist[j]>=ci->books)goto errout;
  117041. return(info);
  117042. errout:
  117043. res0_free_info(info);
  117044. return(NULL);
  117045. }
  117046. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117047. vorbis_info_residue *vr){
  117048. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117049. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117050. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117051. int j,k,acc=0;
  117052. int dim;
  117053. int maxstage=0;
  117054. look->info=info;
  117055. look->parts=info->partitions;
  117056. look->fullbooks=ci->fullbooks;
  117057. look->phrasebook=ci->fullbooks+info->groupbook;
  117058. dim=look->phrasebook->dim;
  117059. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117060. for(j=0;j<look->parts;j++){
  117061. int stages=ilog(info->secondstages[j]);
  117062. if(stages){
  117063. if(stages>maxstage)maxstage=stages;
  117064. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117065. for(k=0;k<stages;k++)
  117066. if(info->secondstages[j]&(1<<k)){
  117067. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117068. #ifdef TRAIN_RES
  117069. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117070. sizeof(***look->training_data));
  117071. #endif
  117072. }
  117073. }
  117074. }
  117075. look->partvals=rint(pow((float)look->parts,(float)dim));
  117076. look->stages=maxstage;
  117077. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117078. for(j=0;j<look->partvals;j++){
  117079. long val=j;
  117080. long mult=look->partvals/look->parts;
  117081. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117082. for(k=0;k<dim;k++){
  117083. long deco=val/mult;
  117084. val-=deco*mult;
  117085. mult/=look->parts;
  117086. look->decodemap[j][k]=deco;
  117087. }
  117088. }
  117089. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117090. {
  117091. static int train_seq=0;
  117092. look->train_seq=train_seq++;
  117093. }
  117094. #endif
  117095. return(look);
  117096. }
  117097. /* break an abstraction and copy some code for performance purposes */
  117098. static int local_book_besterror(codebook *book,float *a){
  117099. int dim=book->dim,i,k,o;
  117100. int best=0;
  117101. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117102. /* find the quant val of each scalar */
  117103. for(k=0,o=dim;k<dim;++k){
  117104. float val=a[--o];
  117105. i=tt->threshvals>>1;
  117106. if(val<tt->quantthresh[i]){
  117107. if(val<tt->quantthresh[i-1]){
  117108. for(--i;i>0;--i)
  117109. if(val>=tt->quantthresh[i-1])
  117110. break;
  117111. }
  117112. }else{
  117113. for(++i;i<tt->threshvals-1;++i)
  117114. if(val<tt->quantthresh[i])break;
  117115. }
  117116. best=(best*tt->quantvals)+tt->quantmap[i];
  117117. }
  117118. /* regular lattices are easy :-) */
  117119. if(book->c->lengthlist[best]<=0){
  117120. const static_codebook *c=book->c;
  117121. int i,j;
  117122. float bestf=0.f;
  117123. float *e=book->valuelist;
  117124. best=-1;
  117125. for(i=0;i<book->entries;i++){
  117126. if(c->lengthlist[i]>0){
  117127. float thisx=0.f;
  117128. for(j=0;j<dim;j++){
  117129. float val=(e[j]-a[j]);
  117130. thisx+=val*val;
  117131. }
  117132. if(best==-1 || thisx<bestf){
  117133. bestf=thisx;
  117134. best=i;
  117135. }
  117136. }
  117137. e+=dim;
  117138. }
  117139. }
  117140. {
  117141. float *ptr=book->valuelist+best*dim;
  117142. for(i=0;i<dim;i++)
  117143. *a++ -= *ptr++;
  117144. }
  117145. return(best);
  117146. }
  117147. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  117148. codebook *book,long *acc){
  117149. int i,bits=0;
  117150. int dim=book->dim;
  117151. int step=n/dim;
  117152. for(i=0;i<step;i++){
  117153. int entry=local_book_besterror(book,vec+i*dim);
  117154. #ifdef TRAIN_RES
  117155. acc[entry]++;
  117156. #endif
  117157. bits+=vorbis_book_encode(book,entry,opb);
  117158. }
  117159. return(bits);
  117160. }
  117161. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  117162. float **in,int ch){
  117163. long i,j,k;
  117164. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117165. vorbis_info_residue0 *info=look->info;
  117166. /* move all this setup out later */
  117167. int samples_per_partition=info->grouping;
  117168. int possible_partitions=info->partitions;
  117169. int n=info->end-info->begin;
  117170. int partvals=n/samples_per_partition;
  117171. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  117172. float scale=100./samples_per_partition;
  117173. /* we find the partition type for each partition of each
  117174. channel. We'll go back and do the interleaved encoding in a
  117175. bit. For now, clarity */
  117176. for(i=0;i<ch;i++){
  117177. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  117178. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  117179. }
  117180. for(i=0;i<partvals;i++){
  117181. int offset=i*samples_per_partition+info->begin;
  117182. for(j=0;j<ch;j++){
  117183. float max=0.;
  117184. float ent=0.;
  117185. for(k=0;k<samples_per_partition;k++){
  117186. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  117187. ent+=fabs(rint(in[j][offset+k]));
  117188. }
  117189. ent*=scale;
  117190. for(k=0;k<possible_partitions-1;k++)
  117191. if(max<=info->classmetric1[k] &&
  117192. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  117193. break;
  117194. partword[j][i]=k;
  117195. }
  117196. }
  117197. #ifdef TRAIN_RESAUX
  117198. {
  117199. FILE *of;
  117200. char buffer[80];
  117201. for(i=0;i<ch;i++){
  117202. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117203. of=fopen(buffer,"a");
  117204. for(j=0;j<partvals;j++)
  117205. fprintf(of,"%ld, ",partword[i][j]);
  117206. fprintf(of,"\n");
  117207. fclose(of);
  117208. }
  117209. }
  117210. #endif
  117211. look->frames++;
  117212. return(partword);
  117213. }
  117214. /* designed for stereo or other modes where the partition size is an
  117215. integer multiple of the number of channels encoded in the current
  117216. submap */
  117217. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  117218. int ch){
  117219. long i,j,k,l;
  117220. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117221. vorbis_info_residue0 *info=look->info;
  117222. /* move all this setup out later */
  117223. int samples_per_partition=info->grouping;
  117224. int possible_partitions=info->partitions;
  117225. int n=info->end-info->begin;
  117226. int partvals=n/samples_per_partition;
  117227. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  117228. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117229. FILE *of;
  117230. char buffer[80];
  117231. #endif
  117232. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  117233. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  117234. for(i=0,l=info->begin/ch;i<partvals;i++){
  117235. float magmax=0.f;
  117236. float angmax=0.f;
  117237. for(j=0;j<samples_per_partition;j+=ch){
  117238. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  117239. for(k=1;k<ch;k++)
  117240. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  117241. l++;
  117242. }
  117243. for(j=0;j<possible_partitions-1;j++)
  117244. if(magmax<=info->classmetric1[j] &&
  117245. angmax<=info->classmetric2[j])
  117246. break;
  117247. partword[0][i]=j;
  117248. }
  117249. #ifdef TRAIN_RESAUX
  117250. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117251. of=fopen(buffer,"a");
  117252. for(i=0;i<partvals;i++)
  117253. fprintf(of,"%ld, ",partword[0][i]);
  117254. fprintf(of,"\n");
  117255. fclose(of);
  117256. #endif
  117257. look->frames++;
  117258. return(partword);
  117259. }
  117260. static int _01forward(oggpack_buffer *opb,
  117261. vorbis_block *vb,vorbis_look_residue *vl,
  117262. float **in,int ch,
  117263. long **partword,
  117264. int (*encode)(oggpack_buffer *,float *,int,
  117265. codebook *,long *)){
  117266. long i,j,k,s;
  117267. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117268. vorbis_info_residue0 *info=look->info;
  117269. /* move all this setup out later */
  117270. int samples_per_partition=info->grouping;
  117271. int possible_partitions=info->partitions;
  117272. int partitions_per_word=look->phrasebook->dim;
  117273. int n=info->end-info->begin;
  117274. int partvals=n/samples_per_partition;
  117275. long resbits[128];
  117276. long resvals[128];
  117277. #ifdef TRAIN_RES
  117278. for(i=0;i<ch;i++)
  117279. for(j=info->begin;j<info->end;j++){
  117280. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  117281. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  117282. }
  117283. #endif
  117284. memset(resbits,0,sizeof(resbits));
  117285. memset(resvals,0,sizeof(resvals));
  117286. /* we code the partition words for each channel, then the residual
  117287. words for a partition per channel until we've written all the
  117288. residual words for that partition word. Then write the next
  117289. partition channel words... */
  117290. for(s=0;s<look->stages;s++){
  117291. for(i=0;i<partvals;){
  117292. /* first we encode a partition codeword for each channel */
  117293. if(s==0){
  117294. for(j=0;j<ch;j++){
  117295. long val=partword[j][i];
  117296. for(k=1;k<partitions_per_word;k++){
  117297. val*=possible_partitions;
  117298. if(i+k<partvals)
  117299. val+=partword[j][i+k];
  117300. }
  117301. /* training hack */
  117302. if(val<look->phrasebook->entries)
  117303. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  117304. #if 0 /*def TRAIN_RES*/
  117305. else
  117306. fprintf(stderr,"!");
  117307. #endif
  117308. }
  117309. }
  117310. /* now we encode interleaved residual values for the partitions */
  117311. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  117312. long offset=i*samples_per_partition+info->begin;
  117313. for(j=0;j<ch;j++){
  117314. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  117315. if(info->secondstages[partword[j][i]]&(1<<s)){
  117316. codebook *statebook=look->partbooks[partword[j][i]][s];
  117317. if(statebook){
  117318. int ret;
  117319. long *accumulator=NULL;
  117320. #ifdef TRAIN_RES
  117321. accumulator=look->training_data[s][partword[j][i]];
  117322. {
  117323. int l;
  117324. float *samples=in[j]+offset;
  117325. for(l=0;l<samples_per_partition;l++){
  117326. if(samples[l]<look->training_min[s][partword[j][i]])
  117327. look->training_min[s][partword[j][i]]=samples[l];
  117328. if(samples[l]>look->training_max[s][partword[j][i]])
  117329. look->training_max[s][partword[j][i]]=samples[l];
  117330. }
  117331. }
  117332. #endif
  117333. ret=encode(opb,in[j]+offset,samples_per_partition,
  117334. statebook,accumulator);
  117335. look->postbits+=ret;
  117336. resbits[partword[j][i]]+=ret;
  117337. }
  117338. }
  117339. }
  117340. }
  117341. }
  117342. }
  117343. /*{
  117344. long total=0;
  117345. long totalbits=0;
  117346. fprintf(stderr,"%d :: ",vb->mode);
  117347. for(k=0;k<possible_partitions;k++){
  117348. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  117349. total+=resvals[k];
  117350. totalbits+=resbits[k];
  117351. }
  117352. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  117353. }*/
  117354. return(0);
  117355. }
  117356. /* a truncated packet here just means 'stop working'; it's not an error */
  117357. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117358. float **in,int ch,
  117359. long (*decodepart)(codebook *, float *,
  117360. oggpack_buffer *,int)){
  117361. long i,j,k,l,s;
  117362. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117363. vorbis_info_residue0 *info=look->info;
  117364. /* move all this setup out later */
  117365. int samples_per_partition=info->grouping;
  117366. int partitions_per_word=look->phrasebook->dim;
  117367. int n=info->end-info->begin;
  117368. int partvals=n/samples_per_partition;
  117369. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117370. int ***partword=(int***)alloca(ch*sizeof(*partword));
  117371. for(j=0;j<ch;j++)
  117372. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  117373. for(s=0;s<look->stages;s++){
  117374. /* each loop decodes on partition codeword containing
  117375. partitions_pre_word partitions */
  117376. for(i=0,l=0;i<partvals;l++){
  117377. if(s==0){
  117378. /* fetch the partition word for each channel */
  117379. for(j=0;j<ch;j++){
  117380. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117381. if(temp==-1)goto eopbreak;
  117382. partword[j][l]=look->decodemap[temp];
  117383. if(partword[j][l]==NULL)goto errout;
  117384. }
  117385. }
  117386. /* now we decode residual values for the partitions */
  117387. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  117388. for(j=0;j<ch;j++){
  117389. long offset=info->begin+i*samples_per_partition;
  117390. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  117391. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  117392. if(stagebook){
  117393. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  117394. samples_per_partition)==-1)goto eopbreak;
  117395. }
  117396. }
  117397. }
  117398. }
  117399. }
  117400. errout:
  117401. eopbreak:
  117402. return(0);
  117403. }
  117404. #if 0
  117405. /* residue 0 and 1 are just slight variants of one another. 0 is
  117406. interleaved, 1 is not */
  117407. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  117408. float **in,int *nonzero,int ch){
  117409. /* we encode only the nonzero parts of a bundle */
  117410. int i,used=0;
  117411. for(i=0;i<ch;i++)
  117412. if(nonzero[i])
  117413. in[used++]=in[i];
  117414. if(used)
  117415. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  117416. return(_01class(vb,vl,in,used));
  117417. else
  117418. return(0);
  117419. }
  117420. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  117421. float **in,float **out,int *nonzero,int ch,
  117422. long **partword){
  117423. /* we encode only the nonzero parts of a bundle */
  117424. int i,j,used=0,n=vb->pcmend/2;
  117425. for(i=0;i<ch;i++)
  117426. if(nonzero[i]){
  117427. if(out)
  117428. for(j=0;j<n;j++)
  117429. out[i][j]+=in[i][j];
  117430. in[used++]=in[i];
  117431. }
  117432. if(used){
  117433. int ret=_01forward(vb,vl,in,used,partword,
  117434. _interleaved_encodepart);
  117435. if(out){
  117436. used=0;
  117437. for(i=0;i<ch;i++)
  117438. if(nonzero[i]){
  117439. for(j=0;j<n;j++)
  117440. out[i][j]-=in[used][j];
  117441. used++;
  117442. }
  117443. }
  117444. return(ret);
  117445. }else{
  117446. return(0);
  117447. }
  117448. }
  117449. #endif
  117450. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117451. float **in,int *nonzero,int ch){
  117452. int i,used=0;
  117453. for(i=0;i<ch;i++)
  117454. if(nonzero[i])
  117455. in[used++]=in[i];
  117456. if(used)
  117457. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  117458. else
  117459. return(0);
  117460. }
  117461. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  117462. float **in,float **out,int *nonzero,int ch,
  117463. long **partword){
  117464. int i,j,used=0,n=vb->pcmend/2;
  117465. for(i=0;i<ch;i++)
  117466. if(nonzero[i]){
  117467. if(out)
  117468. for(j=0;j<n;j++)
  117469. out[i][j]+=in[i][j];
  117470. in[used++]=in[i];
  117471. }
  117472. if(used){
  117473. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  117474. if(out){
  117475. used=0;
  117476. for(i=0;i<ch;i++)
  117477. if(nonzero[i]){
  117478. for(j=0;j<n;j++)
  117479. out[i][j]-=in[used][j];
  117480. used++;
  117481. }
  117482. }
  117483. return(ret);
  117484. }else{
  117485. return(0);
  117486. }
  117487. }
  117488. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  117489. float **in,int *nonzero,int ch){
  117490. int i,used=0;
  117491. for(i=0;i<ch;i++)
  117492. if(nonzero[i])
  117493. in[used++]=in[i];
  117494. if(used)
  117495. return(_01class(vb,vl,in,used));
  117496. else
  117497. return(0);
  117498. }
  117499. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117500. float **in,int *nonzero,int ch){
  117501. int i,used=0;
  117502. for(i=0;i<ch;i++)
  117503. if(nonzero[i])
  117504. in[used++]=in[i];
  117505. if(used)
  117506. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  117507. else
  117508. return(0);
  117509. }
  117510. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  117511. float **in,int *nonzero,int ch){
  117512. int i,used=0;
  117513. for(i=0;i<ch;i++)
  117514. if(nonzero[i])used++;
  117515. if(used)
  117516. return(_2class(vb,vl,in,ch));
  117517. else
  117518. return(0);
  117519. }
  117520. /* res2 is slightly more different; all the channels are interleaved
  117521. into a single vector and encoded. */
  117522. int res2_forward(oggpack_buffer *opb,
  117523. vorbis_block *vb,vorbis_look_residue *vl,
  117524. float **in,float **out,int *nonzero,int ch,
  117525. long **partword){
  117526. long i,j,k,n=vb->pcmend/2,used=0;
  117527. /* don't duplicate the code; use a working vector hack for now and
  117528. reshape ourselves into a single channel res1 */
  117529. /* ugly; reallocs for each coupling pass :-( */
  117530. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  117531. for(i=0;i<ch;i++){
  117532. float *pcm=in[i];
  117533. if(nonzero[i])used++;
  117534. for(j=0,k=i;j<n;j++,k+=ch)
  117535. work[k]=pcm[j];
  117536. }
  117537. if(used){
  117538. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  117539. /* update the sofar vector */
  117540. if(out){
  117541. for(i=0;i<ch;i++){
  117542. float *pcm=in[i];
  117543. float *sofar=out[i];
  117544. for(j=0,k=i;j<n;j++,k+=ch)
  117545. sofar[j]+=pcm[j]-work[k];
  117546. }
  117547. }
  117548. return(ret);
  117549. }else{
  117550. return(0);
  117551. }
  117552. }
  117553. /* duplicate code here as speed is somewhat more important */
  117554. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117555. float **in,int *nonzero,int ch){
  117556. long i,k,l,s;
  117557. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117558. vorbis_info_residue0 *info=look->info;
  117559. /* move all this setup out later */
  117560. int samples_per_partition=info->grouping;
  117561. int partitions_per_word=look->phrasebook->dim;
  117562. int n=info->end-info->begin;
  117563. int partvals=n/samples_per_partition;
  117564. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117565. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  117566. for(i=0;i<ch;i++)if(nonzero[i])break;
  117567. if(i==ch)return(0); /* no nonzero vectors */
  117568. for(s=0;s<look->stages;s++){
  117569. for(i=0,l=0;i<partvals;l++){
  117570. if(s==0){
  117571. /* fetch the partition word */
  117572. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117573. if(temp==-1)goto eopbreak;
  117574. partword[l]=look->decodemap[temp];
  117575. if(partword[l]==NULL)goto errout;
  117576. }
  117577. /* now we decode residual values for the partitions */
  117578. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  117579. if(info->secondstages[partword[l][k]]&(1<<s)){
  117580. codebook *stagebook=look->partbooks[partword[l][k]][s];
  117581. if(stagebook){
  117582. if(vorbis_book_decodevv_add(stagebook,in,
  117583. i*samples_per_partition+info->begin,ch,
  117584. &vb->opb,samples_per_partition)==-1)
  117585. goto eopbreak;
  117586. }
  117587. }
  117588. }
  117589. }
  117590. errout:
  117591. eopbreak:
  117592. return(0);
  117593. }
  117594. vorbis_func_residue residue0_exportbundle={
  117595. NULL,
  117596. &res0_unpack,
  117597. &res0_look,
  117598. &res0_free_info,
  117599. &res0_free_look,
  117600. NULL,
  117601. NULL,
  117602. &res0_inverse
  117603. };
  117604. vorbis_func_residue residue1_exportbundle={
  117605. &res0_pack,
  117606. &res0_unpack,
  117607. &res0_look,
  117608. &res0_free_info,
  117609. &res0_free_look,
  117610. &res1_class,
  117611. &res1_forward,
  117612. &res1_inverse
  117613. };
  117614. vorbis_func_residue residue2_exportbundle={
  117615. &res0_pack,
  117616. &res0_unpack,
  117617. &res0_look,
  117618. &res0_free_info,
  117619. &res0_free_look,
  117620. &res2_class,
  117621. &res2_forward,
  117622. &res2_inverse
  117623. };
  117624. #endif
  117625. /*** End of inlined file: res0.c ***/
  117626. /*** Start of inlined file: sharedbook.c ***/
  117627. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117628. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117629. // tasks..
  117630. #if JUCE_MSVC
  117631. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117632. #endif
  117633. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117634. #if JUCE_USE_OGGVORBIS
  117635. #include <stdlib.h>
  117636. #include <math.h>
  117637. #include <string.h>
  117638. /**** pack/unpack helpers ******************************************/
  117639. int _ilog(unsigned int v){
  117640. int ret=0;
  117641. while(v){
  117642. ret++;
  117643. v>>=1;
  117644. }
  117645. return(ret);
  117646. }
  117647. /* 32 bit float (not IEEE; nonnormalized mantissa +
  117648. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  117649. Why not IEEE? It's just not that important here. */
  117650. #define VQ_FEXP 10
  117651. #define VQ_FMAN 21
  117652. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  117653. /* doesn't currently guard under/overflow */
  117654. long _float32_pack(float val){
  117655. int sign=0;
  117656. long exp;
  117657. long mant;
  117658. if(val<0){
  117659. sign=0x80000000;
  117660. val= -val;
  117661. }
  117662. exp= floor(log(val)/log(2.f));
  117663. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  117664. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  117665. return(sign|exp|mant);
  117666. }
  117667. float _float32_unpack(long val){
  117668. double mant=val&0x1fffff;
  117669. int sign=val&0x80000000;
  117670. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  117671. if(sign)mant= -mant;
  117672. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  117673. }
  117674. /* given a list of word lengths, generate a list of codewords. Works
  117675. for length ordered or unordered, always assigns the lowest valued
  117676. codewords first. Extended to handle unused entries (length 0) */
  117677. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  117678. long i,j,count=0;
  117679. ogg_uint32_t marker[33];
  117680. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  117681. memset(marker,0,sizeof(marker));
  117682. for(i=0;i<n;i++){
  117683. long length=l[i];
  117684. if(length>0){
  117685. ogg_uint32_t entry=marker[length];
  117686. /* when we claim a node for an entry, we also claim the nodes
  117687. below it (pruning off the imagined tree that may have dangled
  117688. from it) as well as blocking the use of any nodes directly
  117689. above for leaves */
  117690. /* update ourself */
  117691. if(length<32 && (entry>>length)){
  117692. /* error condition; the lengths must specify an overpopulated tree */
  117693. _ogg_free(r);
  117694. return(NULL);
  117695. }
  117696. r[count++]=entry;
  117697. /* Look to see if the next shorter marker points to the node
  117698. above. if so, update it and repeat. */
  117699. {
  117700. for(j=length;j>0;j--){
  117701. if(marker[j]&1){
  117702. /* have to jump branches */
  117703. if(j==1)
  117704. marker[1]++;
  117705. else
  117706. marker[j]=marker[j-1]<<1;
  117707. break; /* invariant says next upper marker would already
  117708. have been moved if it was on the same path */
  117709. }
  117710. marker[j]++;
  117711. }
  117712. }
  117713. /* prune the tree; the implicit invariant says all the longer
  117714. markers were dangling from our just-taken node. Dangle them
  117715. from our *new* node. */
  117716. for(j=length+1;j<33;j++)
  117717. if((marker[j]>>1) == entry){
  117718. entry=marker[j];
  117719. marker[j]=marker[j-1]<<1;
  117720. }else
  117721. break;
  117722. }else
  117723. if(sparsecount==0)count++;
  117724. }
  117725. /* bitreverse the words because our bitwise packer/unpacker is LSb
  117726. endian */
  117727. for(i=0,count=0;i<n;i++){
  117728. ogg_uint32_t temp=0;
  117729. for(j=0;j<l[i];j++){
  117730. temp<<=1;
  117731. temp|=(r[count]>>j)&1;
  117732. }
  117733. if(sparsecount){
  117734. if(l[i])
  117735. r[count++]=temp;
  117736. }else
  117737. r[count++]=temp;
  117738. }
  117739. return(r);
  117740. }
  117741. /* there might be a straightforward one-line way to do the below
  117742. that's portable and totally safe against roundoff, but I haven't
  117743. thought of it. Therefore, we opt on the side of caution */
  117744. long _book_maptype1_quantvals(const static_codebook *b){
  117745. long vals=floor(pow((float)b->entries,1.f/b->dim));
  117746. /* the above *should* be reliable, but we'll not assume that FP is
  117747. ever reliable when bitstream sync is at stake; verify via integer
  117748. means that vals really is the greatest value of dim for which
  117749. vals^b->bim <= b->entries */
  117750. /* treat the above as an initial guess */
  117751. while(1){
  117752. long acc=1;
  117753. long acc1=1;
  117754. int i;
  117755. for(i=0;i<b->dim;i++){
  117756. acc*=vals;
  117757. acc1*=vals+1;
  117758. }
  117759. if(acc<=b->entries && acc1>b->entries){
  117760. return(vals);
  117761. }else{
  117762. if(acc>b->entries){
  117763. vals--;
  117764. }else{
  117765. vals++;
  117766. }
  117767. }
  117768. }
  117769. }
  117770. /* unpack the quantized list of values for encode/decode ***********/
  117771. /* we need to deal with two map types: in map type 1, the values are
  117772. generated algorithmically (each column of the vector counts through
  117773. the values in the quant vector). in map type 2, all the values came
  117774. in in an explicit list. Both value lists must be unpacked */
  117775. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  117776. long j,k,count=0;
  117777. if(b->maptype==1 || b->maptype==2){
  117778. int quantvals;
  117779. float mindel=_float32_unpack(b->q_min);
  117780. float delta=_float32_unpack(b->q_delta);
  117781. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  117782. /* maptype 1 and 2 both use a quantized value vector, but
  117783. different sizes */
  117784. switch(b->maptype){
  117785. case 1:
  117786. /* most of the time, entries%dimensions == 0, but we need to be
  117787. well defined. We define that the possible vales at each
  117788. scalar is values == entries/dim. If entries%dim != 0, we'll
  117789. have 'too few' values (values*dim<entries), which means that
  117790. we'll have 'left over' entries; left over entries use zeroed
  117791. values (and are wasted). So don't generate codebooks like
  117792. that */
  117793. quantvals=_book_maptype1_quantvals(b);
  117794. for(j=0;j<b->entries;j++){
  117795. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  117796. float last=0.f;
  117797. int indexdiv=1;
  117798. for(k=0;k<b->dim;k++){
  117799. int index= (j/indexdiv)%quantvals;
  117800. float val=b->quantlist[index];
  117801. val=fabs(val)*delta+mindel+last;
  117802. if(b->q_sequencep)last=val;
  117803. if(sparsemap)
  117804. r[sparsemap[count]*b->dim+k]=val;
  117805. else
  117806. r[count*b->dim+k]=val;
  117807. indexdiv*=quantvals;
  117808. }
  117809. count++;
  117810. }
  117811. }
  117812. break;
  117813. case 2:
  117814. for(j=0;j<b->entries;j++){
  117815. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  117816. float last=0.f;
  117817. for(k=0;k<b->dim;k++){
  117818. float val=b->quantlist[j*b->dim+k];
  117819. val=fabs(val)*delta+mindel+last;
  117820. if(b->q_sequencep)last=val;
  117821. if(sparsemap)
  117822. r[sparsemap[count]*b->dim+k]=val;
  117823. else
  117824. r[count*b->dim+k]=val;
  117825. }
  117826. count++;
  117827. }
  117828. }
  117829. break;
  117830. }
  117831. return(r);
  117832. }
  117833. return(NULL);
  117834. }
  117835. void vorbis_staticbook_clear(static_codebook *b){
  117836. if(b->allocedp){
  117837. if(b->quantlist)_ogg_free(b->quantlist);
  117838. if(b->lengthlist)_ogg_free(b->lengthlist);
  117839. if(b->nearest_tree){
  117840. _ogg_free(b->nearest_tree->ptr0);
  117841. _ogg_free(b->nearest_tree->ptr1);
  117842. _ogg_free(b->nearest_tree->p);
  117843. _ogg_free(b->nearest_tree->q);
  117844. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  117845. _ogg_free(b->nearest_tree);
  117846. }
  117847. if(b->thresh_tree){
  117848. _ogg_free(b->thresh_tree->quantthresh);
  117849. _ogg_free(b->thresh_tree->quantmap);
  117850. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  117851. _ogg_free(b->thresh_tree);
  117852. }
  117853. memset(b,0,sizeof(*b));
  117854. }
  117855. }
  117856. void vorbis_staticbook_destroy(static_codebook *b){
  117857. if(b->allocedp){
  117858. vorbis_staticbook_clear(b);
  117859. _ogg_free(b);
  117860. }
  117861. }
  117862. void vorbis_book_clear(codebook *b){
  117863. /* static book is not cleared; we're likely called on the lookup and
  117864. the static codebook belongs to the info struct */
  117865. if(b->valuelist)_ogg_free(b->valuelist);
  117866. if(b->codelist)_ogg_free(b->codelist);
  117867. if(b->dec_index)_ogg_free(b->dec_index);
  117868. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  117869. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  117870. memset(b,0,sizeof(*b));
  117871. }
  117872. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  117873. memset(c,0,sizeof(*c));
  117874. c->c=s;
  117875. c->entries=s->entries;
  117876. c->used_entries=s->entries;
  117877. c->dim=s->dim;
  117878. c->codelist=_make_words(s->lengthlist,s->entries,0);
  117879. c->valuelist=_book_unquantize(s,s->entries,NULL);
  117880. return(0);
  117881. }
  117882. static int sort32a(const void *a,const void *b){
  117883. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  117884. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  117885. }
  117886. /* decode codebook arrangement is more heavily optimized than encode */
  117887. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  117888. int i,j,n=0,tabn;
  117889. int *sortindex;
  117890. memset(c,0,sizeof(*c));
  117891. /* count actually used entries */
  117892. for(i=0;i<s->entries;i++)
  117893. if(s->lengthlist[i]>0)
  117894. n++;
  117895. c->entries=s->entries;
  117896. c->used_entries=n;
  117897. c->dim=s->dim;
  117898. /* two different remappings go on here.
  117899. First, we collapse the likely sparse codebook down only to
  117900. actually represented values/words. This collapsing needs to be
  117901. indexed as map-valueless books are used to encode original entry
  117902. positions as integers.
  117903. Second, we reorder all vectors, including the entry index above,
  117904. by sorted bitreversed codeword to allow treeless decode. */
  117905. {
  117906. /* perform sort */
  117907. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  117908. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  117909. if(codes==NULL)goto err_out;
  117910. for(i=0;i<n;i++){
  117911. codes[i]=ogg_bitreverse(codes[i]);
  117912. codep[i]=codes+i;
  117913. }
  117914. qsort(codep,n,sizeof(*codep),sort32a);
  117915. sortindex=(int*)alloca(n*sizeof(*sortindex));
  117916. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  117917. /* the index is a reverse index */
  117918. for(i=0;i<n;i++){
  117919. int position=codep[i]-codes;
  117920. sortindex[position]=i;
  117921. }
  117922. for(i=0;i<n;i++)
  117923. c->codelist[sortindex[i]]=codes[i];
  117924. _ogg_free(codes);
  117925. }
  117926. c->valuelist=_book_unquantize(s,n,sortindex);
  117927. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  117928. for(n=0,i=0;i<s->entries;i++)
  117929. if(s->lengthlist[i]>0)
  117930. c->dec_index[sortindex[n++]]=i;
  117931. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  117932. for(n=0,i=0;i<s->entries;i++)
  117933. if(s->lengthlist[i]>0)
  117934. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  117935. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  117936. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  117937. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  117938. tabn=1<<c->dec_firsttablen;
  117939. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  117940. c->dec_maxlength=0;
  117941. for(i=0;i<n;i++){
  117942. if(c->dec_maxlength<c->dec_codelengths[i])
  117943. c->dec_maxlength=c->dec_codelengths[i];
  117944. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  117945. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  117946. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  117947. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  117948. }
  117949. }
  117950. /* now fill in 'unused' entries in the firsttable with hi/lo search
  117951. hints for the non-direct-hits */
  117952. {
  117953. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  117954. long lo=0,hi=0;
  117955. for(i=0;i<tabn;i++){
  117956. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  117957. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  117958. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  117959. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  117960. /* we only actually have 15 bits per hint to play with here.
  117961. In order to overflow gracefully (nothing breaks, efficiency
  117962. just drops), encode as the difference from the extremes. */
  117963. {
  117964. unsigned long loval=lo;
  117965. unsigned long hival=n-hi;
  117966. if(loval>0x7fff)loval=0x7fff;
  117967. if(hival>0x7fff)hival=0x7fff;
  117968. c->dec_firsttable[ogg_bitreverse(word)]=
  117969. 0x80000000UL | (loval<<15) | hival;
  117970. }
  117971. }
  117972. }
  117973. }
  117974. return(0);
  117975. err_out:
  117976. vorbis_book_clear(c);
  117977. return(-1);
  117978. }
  117979. static float _dist(int el,float *ref, float *b,int step){
  117980. int i;
  117981. float acc=0.f;
  117982. for(i=0;i<el;i++){
  117983. float val=(ref[i]-b[i*step]);
  117984. acc+=val*val;
  117985. }
  117986. return(acc);
  117987. }
  117988. int _best(codebook *book, float *a, int step){
  117989. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117990. #if 0
  117991. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  117992. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  117993. #endif
  117994. int dim=book->dim;
  117995. int k,o;
  117996. /*int savebest=-1;
  117997. float saverr;*/
  117998. /* do we have a threshhold encode hint? */
  117999. if(tt){
  118000. int index=0,i;
  118001. /* find the quant val of each scalar */
  118002. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118003. i=tt->threshvals>>1;
  118004. if(a[o]<tt->quantthresh[i]){
  118005. for(;i>0;i--)
  118006. if(a[o]>=tt->quantthresh[i-1])
  118007. break;
  118008. }else{
  118009. for(i++;i<tt->threshvals-1;i++)
  118010. if(a[o]<tt->quantthresh[i])break;
  118011. }
  118012. index=(index*tt->quantvals)+tt->quantmap[i];
  118013. }
  118014. /* regular lattices are easy :-) */
  118015. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118016. use a decision tree after all
  118017. and fall through*/
  118018. return(index);
  118019. }
  118020. #if 0
  118021. /* do we have a pigeonhole encode hint? */
  118022. if(pt){
  118023. const static_codebook *c=book->c;
  118024. int i,besti=-1;
  118025. float best=0.f;
  118026. int entry=0;
  118027. /* dealing with sequentialness is a pain in the ass */
  118028. if(c->q_sequencep){
  118029. int pv;
  118030. long mul=1;
  118031. float qlast=0;
  118032. for(k=0,o=0;k<dim;k++,o+=step){
  118033. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118034. if(pv<0 || pv>=pt->mapentries)break;
  118035. entry+=pt->pigeonmap[pv]*mul;
  118036. mul*=pt->quantvals;
  118037. qlast+=pv*pt->del+pt->min;
  118038. }
  118039. }else{
  118040. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118041. int pv=(int)((a[o]-pt->min)/pt->del);
  118042. if(pv<0 || pv>=pt->mapentries)break;
  118043. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118044. }
  118045. }
  118046. /* must be within the pigeonholable range; if we quant outside (or
  118047. in an entry that we define no list for), brute force it */
  118048. if(k==dim && pt->fitlength[entry]){
  118049. /* search the abbreviated list */
  118050. long *list=pt->fitlist+pt->fitmap[entry];
  118051. for(i=0;i<pt->fitlength[entry];i++){
  118052. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118053. if(besti==-1 || this<best){
  118054. best=this;
  118055. besti=list[i];
  118056. }
  118057. }
  118058. return(besti);
  118059. }
  118060. }
  118061. if(nt){
  118062. /* optimized using the decision tree */
  118063. while(1){
  118064. float c=0.f;
  118065. float *p=book->valuelist+nt->p[ptr];
  118066. float *q=book->valuelist+nt->q[ptr];
  118067. for(k=0,o=0;k<dim;k++,o+=step)
  118068. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118069. if(c>0.f) /* in A */
  118070. ptr= -nt->ptr0[ptr];
  118071. else /* in B */
  118072. ptr= -nt->ptr1[ptr];
  118073. if(ptr<=0)break;
  118074. }
  118075. return(-ptr);
  118076. }
  118077. #endif
  118078. /* brute force it! */
  118079. {
  118080. const static_codebook *c=book->c;
  118081. int i,besti=-1;
  118082. float best=0.f;
  118083. float *e=book->valuelist;
  118084. for(i=0;i<book->entries;i++){
  118085. if(c->lengthlist[i]>0){
  118086. float thisx=_dist(dim,e,a,step);
  118087. if(besti==-1 || thisx<best){
  118088. best=thisx;
  118089. besti=i;
  118090. }
  118091. }
  118092. e+=dim;
  118093. }
  118094. /*if(savebest!=-1 && savebest!=besti){
  118095. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118096. "original:");
  118097. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118098. fprintf(stderr,"\n"
  118099. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118100. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118101. (book->valuelist+savebest*dim)[i]);
  118102. fprintf(stderr,"\n"
  118103. "bruteforce (entry %d, err %g):",besti,best);
  118104. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118105. (book->valuelist+besti*dim)[i]);
  118106. fprintf(stderr,"\n");
  118107. }*/
  118108. return(besti);
  118109. }
  118110. }
  118111. long vorbis_book_codeword(codebook *book,int entry){
  118112. if(book->c) /* only use with encode; decode optimizations are
  118113. allowed to break this */
  118114. return book->codelist[entry];
  118115. return -1;
  118116. }
  118117. long vorbis_book_codelen(codebook *book,int entry){
  118118. if(book->c) /* only use with encode; decode optimizations are
  118119. allowed to break this */
  118120. return book->c->lengthlist[entry];
  118121. return -1;
  118122. }
  118123. #ifdef _V_SELFTEST
  118124. /* Unit tests of the dequantizer; this stuff will be OK
  118125. cross-platform, I simply want to be sure that special mapping cases
  118126. actually work properly; a bug could go unnoticed for a while */
  118127. #include <stdio.h>
  118128. /* cases:
  118129. no mapping
  118130. full, explicit mapping
  118131. algorithmic mapping
  118132. nonsequential
  118133. sequential
  118134. */
  118135. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  118136. static long partial_quantlist1[]={0,7,2};
  118137. /* no mapping */
  118138. static_codebook test1={
  118139. 4,16,
  118140. NULL,
  118141. 0,
  118142. 0,0,0,0,
  118143. NULL,
  118144. NULL,NULL
  118145. };
  118146. static float *test1_result=NULL;
  118147. /* linear, full mapping, nonsequential */
  118148. static_codebook test2={
  118149. 4,3,
  118150. NULL,
  118151. 2,
  118152. -533200896,1611661312,4,0,
  118153. full_quantlist1,
  118154. NULL,NULL
  118155. };
  118156. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  118157. /* linear, full mapping, sequential */
  118158. static_codebook test3={
  118159. 4,3,
  118160. NULL,
  118161. 2,
  118162. -533200896,1611661312,4,1,
  118163. full_quantlist1,
  118164. NULL,NULL
  118165. };
  118166. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  118167. /* linear, algorithmic mapping, nonsequential */
  118168. static_codebook test4={
  118169. 3,27,
  118170. NULL,
  118171. 1,
  118172. -533200896,1611661312,4,0,
  118173. partial_quantlist1,
  118174. NULL,NULL
  118175. };
  118176. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  118177. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  118178. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  118179. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  118180. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  118181. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  118182. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  118183. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  118184. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  118185. /* linear, algorithmic mapping, sequential */
  118186. static_codebook test5={
  118187. 3,27,
  118188. NULL,
  118189. 1,
  118190. -533200896,1611661312,4,1,
  118191. partial_quantlist1,
  118192. NULL,NULL
  118193. };
  118194. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  118195. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  118196. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  118197. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  118198. -3, 1, 5, 4, 8,12, -1, 3, 7,
  118199. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  118200. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  118201. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  118202. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  118203. void run_test(static_codebook *b,float *comp){
  118204. float *out=_book_unquantize(b,b->entries,NULL);
  118205. int i;
  118206. if(comp){
  118207. if(!out){
  118208. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  118209. exit(1);
  118210. }
  118211. for(i=0;i<b->entries*b->dim;i++)
  118212. if(fabs(out[i]-comp[i])>.0001){
  118213. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  118214. "position %d, %g != %g\n",i,out[i],comp[i]);
  118215. exit(1);
  118216. }
  118217. }else{
  118218. if(out){
  118219. fprintf(stderr,"_book_unquantize returned a value array: \n"
  118220. " correct result should have been NULL\n");
  118221. exit(1);
  118222. }
  118223. }
  118224. }
  118225. int main(){
  118226. /* run the nine dequant tests, and compare to the hand-rolled results */
  118227. fprintf(stderr,"Dequant test 1... ");
  118228. run_test(&test1,test1_result);
  118229. fprintf(stderr,"OK\nDequant test 2... ");
  118230. run_test(&test2,test2_result);
  118231. fprintf(stderr,"OK\nDequant test 3... ");
  118232. run_test(&test3,test3_result);
  118233. fprintf(stderr,"OK\nDequant test 4... ");
  118234. run_test(&test4,test4_result);
  118235. fprintf(stderr,"OK\nDequant test 5... ");
  118236. run_test(&test5,test5_result);
  118237. fprintf(stderr,"OK\n\n");
  118238. return(0);
  118239. }
  118240. #endif
  118241. #endif
  118242. /*** End of inlined file: sharedbook.c ***/
  118243. /*** Start of inlined file: smallft.c ***/
  118244. /* FFT implementation from OggSquish, minus cosine transforms,
  118245. * minus all but radix 2/4 case. In Vorbis we only need this
  118246. * cut-down version.
  118247. *
  118248. * To do more than just power-of-two sized vectors, see the full
  118249. * version I wrote for NetLib.
  118250. *
  118251. * Note that the packing is a little strange; rather than the FFT r/i
  118252. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  118253. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  118254. * FORTRAN version
  118255. */
  118256. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118257. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118258. // tasks..
  118259. #if JUCE_MSVC
  118260. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118261. #endif
  118262. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118263. #if JUCE_USE_OGGVORBIS
  118264. #include <stdlib.h>
  118265. #include <string.h>
  118266. #include <math.h>
  118267. static void drfti1(int n, float *wa, int *ifac){
  118268. static int ntryh[4] = { 4,2,3,5 };
  118269. static float tpi = 6.28318530717958648f;
  118270. float arg,argh,argld,fi;
  118271. int ntry=0,i,j=-1;
  118272. int k1, l1, l2, ib;
  118273. int ld, ii, ip, is, nq, nr;
  118274. int ido, ipm, nfm1;
  118275. int nl=n;
  118276. int nf=0;
  118277. L101:
  118278. j++;
  118279. if (j < 4)
  118280. ntry=ntryh[j];
  118281. else
  118282. ntry+=2;
  118283. L104:
  118284. nq=nl/ntry;
  118285. nr=nl-ntry*nq;
  118286. if (nr!=0) goto L101;
  118287. nf++;
  118288. ifac[nf+1]=ntry;
  118289. nl=nq;
  118290. if(ntry!=2)goto L107;
  118291. if(nf==1)goto L107;
  118292. for (i=1;i<nf;i++){
  118293. ib=nf-i+1;
  118294. ifac[ib+1]=ifac[ib];
  118295. }
  118296. ifac[2] = 2;
  118297. L107:
  118298. if(nl!=1)goto L104;
  118299. ifac[0]=n;
  118300. ifac[1]=nf;
  118301. argh=tpi/n;
  118302. is=0;
  118303. nfm1=nf-1;
  118304. l1=1;
  118305. if(nfm1==0)return;
  118306. for (k1=0;k1<nfm1;k1++){
  118307. ip=ifac[k1+2];
  118308. ld=0;
  118309. l2=l1*ip;
  118310. ido=n/l2;
  118311. ipm=ip-1;
  118312. for (j=0;j<ipm;j++){
  118313. ld+=l1;
  118314. i=is;
  118315. argld=(float)ld*argh;
  118316. fi=0.f;
  118317. for (ii=2;ii<ido;ii+=2){
  118318. fi+=1.f;
  118319. arg=fi*argld;
  118320. wa[i++]=cos(arg);
  118321. wa[i++]=sin(arg);
  118322. }
  118323. is+=ido;
  118324. }
  118325. l1=l2;
  118326. }
  118327. }
  118328. static void fdrffti(int n, float *wsave, int *ifac){
  118329. if (n == 1) return;
  118330. drfti1(n, wsave+n, ifac);
  118331. }
  118332. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  118333. int i,k;
  118334. float ti2,tr2;
  118335. int t0,t1,t2,t3,t4,t5,t6;
  118336. t1=0;
  118337. t0=(t2=l1*ido);
  118338. t3=ido<<1;
  118339. for(k=0;k<l1;k++){
  118340. ch[t1<<1]=cc[t1]+cc[t2];
  118341. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  118342. t1+=ido;
  118343. t2+=ido;
  118344. }
  118345. if(ido<2)return;
  118346. if(ido==2)goto L105;
  118347. t1=0;
  118348. t2=t0;
  118349. for(k=0;k<l1;k++){
  118350. t3=t2;
  118351. t4=(t1<<1)+(ido<<1);
  118352. t5=t1;
  118353. t6=t1+t1;
  118354. for(i=2;i<ido;i+=2){
  118355. t3+=2;
  118356. t4-=2;
  118357. t5+=2;
  118358. t6+=2;
  118359. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118360. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118361. ch[t6]=cc[t5]+ti2;
  118362. ch[t4]=ti2-cc[t5];
  118363. ch[t6-1]=cc[t5-1]+tr2;
  118364. ch[t4-1]=cc[t5-1]-tr2;
  118365. }
  118366. t1+=ido;
  118367. t2+=ido;
  118368. }
  118369. if(ido%2==1)return;
  118370. L105:
  118371. t3=(t2=(t1=ido)-1);
  118372. t2+=t0;
  118373. for(k=0;k<l1;k++){
  118374. ch[t1]=-cc[t2];
  118375. ch[t1-1]=cc[t3];
  118376. t1+=ido<<1;
  118377. t2+=ido;
  118378. t3+=ido;
  118379. }
  118380. }
  118381. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  118382. float *wa2,float *wa3){
  118383. static float hsqt2 = .70710678118654752f;
  118384. int i,k,t0,t1,t2,t3,t4,t5,t6;
  118385. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  118386. t0=l1*ido;
  118387. t1=t0;
  118388. t4=t1<<1;
  118389. t2=t1+(t1<<1);
  118390. t3=0;
  118391. for(k=0;k<l1;k++){
  118392. tr1=cc[t1]+cc[t2];
  118393. tr2=cc[t3]+cc[t4];
  118394. ch[t5=t3<<2]=tr1+tr2;
  118395. ch[(ido<<2)+t5-1]=tr2-tr1;
  118396. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  118397. ch[t5]=cc[t2]-cc[t1];
  118398. t1+=ido;
  118399. t2+=ido;
  118400. t3+=ido;
  118401. t4+=ido;
  118402. }
  118403. if(ido<2)return;
  118404. if(ido==2)goto L105;
  118405. t1=0;
  118406. for(k=0;k<l1;k++){
  118407. t2=t1;
  118408. t4=t1<<2;
  118409. t5=(t6=ido<<1)+t4;
  118410. for(i=2;i<ido;i+=2){
  118411. t3=(t2+=2);
  118412. t4+=2;
  118413. t5-=2;
  118414. t3+=t0;
  118415. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118416. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118417. t3+=t0;
  118418. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  118419. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  118420. t3+=t0;
  118421. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  118422. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  118423. tr1=cr2+cr4;
  118424. tr4=cr4-cr2;
  118425. ti1=ci2+ci4;
  118426. ti4=ci2-ci4;
  118427. ti2=cc[t2]+ci3;
  118428. ti3=cc[t2]-ci3;
  118429. tr2=cc[t2-1]+cr3;
  118430. tr3=cc[t2-1]-cr3;
  118431. ch[t4-1]=tr1+tr2;
  118432. ch[t4]=ti1+ti2;
  118433. ch[t5-1]=tr3-ti4;
  118434. ch[t5]=tr4-ti3;
  118435. ch[t4+t6-1]=ti4+tr3;
  118436. ch[t4+t6]=tr4+ti3;
  118437. ch[t5+t6-1]=tr2-tr1;
  118438. ch[t5+t6]=ti1-ti2;
  118439. }
  118440. t1+=ido;
  118441. }
  118442. if(ido&1)return;
  118443. L105:
  118444. t2=(t1=t0+ido-1)+(t0<<1);
  118445. t3=ido<<2;
  118446. t4=ido;
  118447. t5=ido<<1;
  118448. t6=ido;
  118449. for(k=0;k<l1;k++){
  118450. ti1=-hsqt2*(cc[t1]+cc[t2]);
  118451. tr1=hsqt2*(cc[t1]-cc[t2]);
  118452. ch[t4-1]=tr1+cc[t6-1];
  118453. ch[t4+t5-1]=cc[t6-1]-tr1;
  118454. ch[t4]=ti1-cc[t1+t0];
  118455. ch[t4+t5]=ti1+cc[t1+t0];
  118456. t1+=ido;
  118457. t2+=ido;
  118458. t4+=t3;
  118459. t6+=ido;
  118460. }
  118461. }
  118462. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  118463. float *c2,float *ch,float *ch2,float *wa){
  118464. static float tpi=6.283185307179586f;
  118465. int idij,ipph,i,j,k,l,ic,ik,is;
  118466. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  118467. float dc2,ai1,ai2,ar1,ar2,ds2;
  118468. int nbd;
  118469. float dcp,arg,dsp,ar1h,ar2h;
  118470. int idp2,ipp2;
  118471. arg=tpi/(float)ip;
  118472. dcp=cos(arg);
  118473. dsp=sin(arg);
  118474. ipph=(ip+1)>>1;
  118475. ipp2=ip;
  118476. idp2=ido;
  118477. nbd=(ido-1)>>1;
  118478. t0=l1*ido;
  118479. t10=ip*ido;
  118480. if(ido==1)goto L119;
  118481. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  118482. t1=0;
  118483. for(j=1;j<ip;j++){
  118484. t1+=t0;
  118485. t2=t1;
  118486. for(k=0;k<l1;k++){
  118487. ch[t2]=c1[t2];
  118488. t2+=ido;
  118489. }
  118490. }
  118491. is=-ido;
  118492. t1=0;
  118493. if(nbd>l1){
  118494. for(j=1;j<ip;j++){
  118495. t1+=t0;
  118496. is+=ido;
  118497. t2= -ido+t1;
  118498. for(k=0;k<l1;k++){
  118499. idij=is-1;
  118500. t2+=ido;
  118501. t3=t2;
  118502. for(i=2;i<ido;i+=2){
  118503. idij+=2;
  118504. t3+=2;
  118505. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  118506. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  118507. }
  118508. }
  118509. }
  118510. }else{
  118511. for(j=1;j<ip;j++){
  118512. is+=ido;
  118513. idij=is-1;
  118514. t1+=t0;
  118515. t2=t1;
  118516. for(i=2;i<ido;i+=2){
  118517. idij+=2;
  118518. t2+=2;
  118519. t3=t2;
  118520. for(k=0;k<l1;k++){
  118521. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  118522. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  118523. t3+=ido;
  118524. }
  118525. }
  118526. }
  118527. }
  118528. t1=0;
  118529. t2=ipp2*t0;
  118530. if(nbd<l1){
  118531. for(j=1;j<ipph;j++){
  118532. t1+=t0;
  118533. t2-=t0;
  118534. t3=t1;
  118535. t4=t2;
  118536. for(i=2;i<ido;i+=2){
  118537. t3+=2;
  118538. t4+=2;
  118539. t5=t3-ido;
  118540. t6=t4-ido;
  118541. for(k=0;k<l1;k++){
  118542. t5+=ido;
  118543. t6+=ido;
  118544. c1[t5-1]=ch[t5-1]+ch[t6-1];
  118545. c1[t6-1]=ch[t5]-ch[t6];
  118546. c1[t5]=ch[t5]+ch[t6];
  118547. c1[t6]=ch[t6-1]-ch[t5-1];
  118548. }
  118549. }
  118550. }
  118551. }else{
  118552. for(j=1;j<ipph;j++){
  118553. t1+=t0;
  118554. t2-=t0;
  118555. t3=t1;
  118556. t4=t2;
  118557. for(k=0;k<l1;k++){
  118558. t5=t3;
  118559. t6=t4;
  118560. for(i=2;i<ido;i+=2){
  118561. t5+=2;
  118562. t6+=2;
  118563. c1[t5-1]=ch[t5-1]+ch[t6-1];
  118564. c1[t6-1]=ch[t5]-ch[t6];
  118565. c1[t5]=ch[t5]+ch[t6];
  118566. c1[t6]=ch[t6-1]-ch[t5-1];
  118567. }
  118568. t3+=ido;
  118569. t4+=ido;
  118570. }
  118571. }
  118572. }
  118573. L119:
  118574. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  118575. t1=0;
  118576. t2=ipp2*idl1;
  118577. for(j=1;j<ipph;j++){
  118578. t1+=t0;
  118579. t2-=t0;
  118580. t3=t1-ido;
  118581. t4=t2-ido;
  118582. for(k=0;k<l1;k++){
  118583. t3+=ido;
  118584. t4+=ido;
  118585. c1[t3]=ch[t3]+ch[t4];
  118586. c1[t4]=ch[t4]-ch[t3];
  118587. }
  118588. }
  118589. ar1=1.f;
  118590. ai1=0.f;
  118591. t1=0;
  118592. t2=ipp2*idl1;
  118593. t3=(ip-1)*idl1;
  118594. for(l=1;l<ipph;l++){
  118595. t1+=idl1;
  118596. t2-=idl1;
  118597. ar1h=dcp*ar1-dsp*ai1;
  118598. ai1=dcp*ai1+dsp*ar1;
  118599. ar1=ar1h;
  118600. t4=t1;
  118601. t5=t2;
  118602. t6=t3;
  118603. t7=idl1;
  118604. for(ik=0;ik<idl1;ik++){
  118605. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  118606. ch2[t5++]=ai1*c2[t6++];
  118607. }
  118608. dc2=ar1;
  118609. ds2=ai1;
  118610. ar2=ar1;
  118611. ai2=ai1;
  118612. t4=idl1;
  118613. t5=(ipp2-1)*idl1;
  118614. for(j=2;j<ipph;j++){
  118615. t4+=idl1;
  118616. t5-=idl1;
  118617. ar2h=dc2*ar2-ds2*ai2;
  118618. ai2=dc2*ai2+ds2*ar2;
  118619. ar2=ar2h;
  118620. t6=t1;
  118621. t7=t2;
  118622. t8=t4;
  118623. t9=t5;
  118624. for(ik=0;ik<idl1;ik++){
  118625. ch2[t6++]+=ar2*c2[t8++];
  118626. ch2[t7++]+=ai2*c2[t9++];
  118627. }
  118628. }
  118629. }
  118630. t1=0;
  118631. for(j=1;j<ipph;j++){
  118632. t1+=idl1;
  118633. t2=t1;
  118634. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  118635. }
  118636. if(ido<l1)goto L132;
  118637. t1=0;
  118638. t2=0;
  118639. for(k=0;k<l1;k++){
  118640. t3=t1;
  118641. t4=t2;
  118642. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  118643. t1+=ido;
  118644. t2+=t10;
  118645. }
  118646. goto L135;
  118647. L132:
  118648. for(i=0;i<ido;i++){
  118649. t1=i;
  118650. t2=i;
  118651. for(k=0;k<l1;k++){
  118652. cc[t2]=ch[t1];
  118653. t1+=ido;
  118654. t2+=t10;
  118655. }
  118656. }
  118657. L135:
  118658. t1=0;
  118659. t2=ido<<1;
  118660. t3=0;
  118661. t4=ipp2*t0;
  118662. for(j=1;j<ipph;j++){
  118663. t1+=t2;
  118664. t3+=t0;
  118665. t4-=t0;
  118666. t5=t1;
  118667. t6=t3;
  118668. t7=t4;
  118669. for(k=0;k<l1;k++){
  118670. cc[t5-1]=ch[t6];
  118671. cc[t5]=ch[t7];
  118672. t5+=t10;
  118673. t6+=ido;
  118674. t7+=ido;
  118675. }
  118676. }
  118677. if(ido==1)return;
  118678. if(nbd<l1)goto L141;
  118679. t1=-ido;
  118680. t3=0;
  118681. t4=0;
  118682. t5=ipp2*t0;
  118683. for(j=1;j<ipph;j++){
  118684. t1+=t2;
  118685. t3+=t2;
  118686. t4+=t0;
  118687. t5-=t0;
  118688. t6=t1;
  118689. t7=t3;
  118690. t8=t4;
  118691. t9=t5;
  118692. for(k=0;k<l1;k++){
  118693. for(i=2;i<ido;i+=2){
  118694. ic=idp2-i;
  118695. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  118696. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  118697. cc[i+t7]=ch[i+t8]+ch[i+t9];
  118698. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  118699. }
  118700. t6+=t10;
  118701. t7+=t10;
  118702. t8+=ido;
  118703. t9+=ido;
  118704. }
  118705. }
  118706. return;
  118707. L141:
  118708. t1=-ido;
  118709. t3=0;
  118710. t4=0;
  118711. t5=ipp2*t0;
  118712. for(j=1;j<ipph;j++){
  118713. t1+=t2;
  118714. t3+=t2;
  118715. t4+=t0;
  118716. t5-=t0;
  118717. for(i=2;i<ido;i+=2){
  118718. t6=idp2+t1-i;
  118719. t7=i+t3;
  118720. t8=i+t4;
  118721. t9=i+t5;
  118722. for(k=0;k<l1;k++){
  118723. cc[t7-1]=ch[t8-1]+ch[t9-1];
  118724. cc[t6-1]=ch[t8-1]-ch[t9-1];
  118725. cc[t7]=ch[t8]+ch[t9];
  118726. cc[t6]=ch[t9]-ch[t8];
  118727. t6+=t10;
  118728. t7+=t10;
  118729. t8+=ido;
  118730. t9+=ido;
  118731. }
  118732. }
  118733. }
  118734. }
  118735. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  118736. int i,k1,l1,l2;
  118737. int na,kh,nf;
  118738. int ip,iw,ido,idl1,ix2,ix3;
  118739. nf=ifac[1];
  118740. na=1;
  118741. l2=n;
  118742. iw=n;
  118743. for(k1=0;k1<nf;k1++){
  118744. kh=nf-k1;
  118745. ip=ifac[kh+1];
  118746. l1=l2/ip;
  118747. ido=n/l2;
  118748. idl1=ido*l1;
  118749. iw-=(ip-1)*ido;
  118750. na=1-na;
  118751. if(ip!=4)goto L102;
  118752. ix2=iw+ido;
  118753. ix3=ix2+ido;
  118754. if(na!=0)
  118755. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  118756. else
  118757. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  118758. goto L110;
  118759. L102:
  118760. if(ip!=2)goto L104;
  118761. if(na!=0)goto L103;
  118762. dradf2(ido,l1,c,ch,wa+iw-1);
  118763. goto L110;
  118764. L103:
  118765. dradf2(ido,l1,ch,c,wa+iw-1);
  118766. goto L110;
  118767. L104:
  118768. if(ido==1)na=1-na;
  118769. if(na!=0)goto L109;
  118770. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  118771. na=1;
  118772. goto L110;
  118773. L109:
  118774. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  118775. na=0;
  118776. L110:
  118777. l2=l1;
  118778. }
  118779. if(na==1)return;
  118780. for(i=0;i<n;i++)c[i]=ch[i];
  118781. }
  118782. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  118783. int i,k,t0,t1,t2,t3,t4,t5,t6;
  118784. float ti2,tr2;
  118785. t0=l1*ido;
  118786. t1=0;
  118787. t2=0;
  118788. t3=(ido<<1)-1;
  118789. for(k=0;k<l1;k++){
  118790. ch[t1]=cc[t2]+cc[t3+t2];
  118791. ch[t1+t0]=cc[t2]-cc[t3+t2];
  118792. t2=(t1+=ido)<<1;
  118793. }
  118794. if(ido<2)return;
  118795. if(ido==2)goto L105;
  118796. t1=0;
  118797. t2=0;
  118798. for(k=0;k<l1;k++){
  118799. t3=t1;
  118800. t5=(t4=t2)+(ido<<1);
  118801. t6=t0+t1;
  118802. for(i=2;i<ido;i+=2){
  118803. t3+=2;
  118804. t4+=2;
  118805. t5-=2;
  118806. t6+=2;
  118807. ch[t3-1]=cc[t4-1]+cc[t5-1];
  118808. tr2=cc[t4-1]-cc[t5-1];
  118809. ch[t3]=cc[t4]-cc[t5];
  118810. ti2=cc[t4]+cc[t5];
  118811. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  118812. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  118813. }
  118814. t2=(t1+=ido)<<1;
  118815. }
  118816. if(ido%2==1)return;
  118817. L105:
  118818. t1=ido-1;
  118819. t2=ido-1;
  118820. for(k=0;k<l1;k++){
  118821. ch[t1]=cc[t2]+cc[t2];
  118822. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  118823. t1+=ido;
  118824. t2+=ido<<1;
  118825. }
  118826. }
  118827. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  118828. float *wa2){
  118829. static float taur = -.5f;
  118830. static float taui = .8660254037844386f;
  118831. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  118832. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  118833. t0=l1*ido;
  118834. t1=0;
  118835. t2=t0<<1;
  118836. t3=ido<<1;
  118837. t4=ido+(ido<<1);
  118838. t5=0;
  118839. for(k=0;k<l1;k++){
  118840. tr2=cc[t3-1]+cc[t3-1];
  118841. cr2=cc[t5]+(taur*tr2);
  118842. ch[t1]=cc[t5]+tr2;
  118843. ci3=taui*(cc[t3]+cc[t3]);
  118844. ch[t1+t0]=cr2-ci3;
  118845. ch[t1+t2]=cr2+ci3;
  118846. t1+=ido;
  118847. t3+=t4;
  118848. t5+=t4;
  118849. }
  118850. if(ido==1)return;
  118851. t1=0;
  118852. t3=ido<<1;
  118853. for(k=0;k<l1;k++){
  118854. t7=t1+(t1<<1);
  118855. t6=(t5=t7+t3);
  118856. t8=t1;
  118857. t10=(t9=t1+t0)+t0;
  118858. for(i=2;i<ido;i+=2){
  118859. t5+=2;
  118860. t6-=2;
  118861. t7+=2;
  118862. t8+=2;
  118863. t9+=2;
  118864. t10+=2;
  118865. tr2=cc[t5-1]+cc[t6-1];
  118866. cr2=cc[t7-1]+(taur*tr2);
  118867. ch[t8-1]=cc[t7-1]+tr2;
  118868. ti2=cc[t5]-cc[t6];
  118869. ci2=cc[t7]+(taur*ti2);
  118870. ch[t8]=cc[t7]+ti2;
  118871. cr3=taui*(cc[t5-1]-cc[t6-1]);
  118872. ci3=taui*(cc[t5]+cc[t6]);
  118873. dr2=cr2-ci3;
  118874. dr3=cr2+ci3;
  118875. di2=ci2+cr3;
  118876. di3=ci2-cr3;
  118877. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  118878. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  118879. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  118880. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  118881. }
  118882. t1+=ido;
  118883. }
  118884. }
  118885. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  118886. float *wa2,float *wa3){
  118887. static float sqrt2=1.414213562373095f;
  118888. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  118889. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  118890. t0=l1*ido;
  118891. t1=0;
  118892. t2=ido<<2;
  118893. t3=0;
  118894. t6=ido<<1;
  118895. for(k=0;k<l1;k++){
  118896. t4=t3+t6;
  118897. t5=t1;
  118898. tr3=cc[t4-1]+cc[t4-1];
  118899. tr4=cc[t4]+cc[t4];
  118900. tr1=cc[t3]-cc[(t4+=t6)-1];
  118901. tr2=cc[t3]+cc[t4-1];
  118902. ch[t5]=tr2+tr3;
  118903. ch[t5+=t0]=tr1-tr4;
  118904. ch[t5+=t0]=tr2-tr3;
  118905. ch[t5+=t0]=tr1+tr4;
  118906. t1+=ido;
  118907. t3+=t2;
  118908. }
  118909. if(ido<2)return;
  118910. if(ido==2)goto L105;
  118911. t1=0;
  118912. for(k=0;k<l1;k++){
  118913. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  118914. t7=t1;
  118915. for(i=2;i<ido;i+=2){
  118916. t2+=2;
  118917. t3+=2;
  118918. t4-=2;
  118919. t5-=2;
  118920. t7+=2;
  118921. ti1=cc[t2]+cc[t5];
  118922. ti2=cc[t2]-cc[t5];
  118923. ti3=cc[t3]-cc[t4];
  118924. tr4=cc[t3]+cc[t4];
  118925. tr1=cc[t2-1]-cc[t5-1];
  118926. tr2=cc[t2-1]+cc[t5-1];
  118927. ti4=cc[t3-1]-cc[t4-1];
  118928. tr3=cc[t3-1]+cc[t4-1];
  118929. ch[t7-1]=tr2+tr3;
  118930. cr3=tr2-tr3;
  118931. ch[t7]=ti2+ti3;
  118932. ci3=ti2-ti3;
  118933. cr2=tr1-tr4;
  118934. cr4=tr1+tr4;
  118935. ci2=ti1+ti4;
  118936. ci4=ti1-ti4;
  118937. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  118938. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  118939. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  118940. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  118941. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  118942. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  118943. }
  118944. t1+=ido;
  118945. }
  118946. if(ido%2 == 1)return;
  118947. L105:
  118948. t1=ido;
  118949. t2=ido<<2;
  118950. t3=ido-1;
  118951. t4=ido+(ido<<1);
  118952. for(k=0;k<l1;k++){
  118953. t5=t3;
  118954. ti1=cc[t1]+cc[t4];
  118955. ti2=cc[t4]-cc[t1];
  118956. tr1=cc[t1-1]-cc[t4-1];
  118957. tr2=cc[t1-1]+cc[t4-1];
  118958. ch[t5]=tr2+tr2;
  118959. ch[t5+=t0]=sqrt2*(tr1-ti1);
  118960. ch[t5+=t0]=ti2+ti2;
  118961. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  118962. t3+=ido;
  118963. t1+=t2;
  118964. t4+=t2;
  118965. }
  118966. }
  118967. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  118968. float *c2,float *ch,float *ch2,float *wa){
  118969. static float tpi=6.283185307179586f;
  118970. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  118971. t11,t12;
  118972. float dc2,ai1,ai2,ar1,ar2,ds2;
  118973. int nbd;
  118974. float dcp,arg,dsp,ar1h,ar2h;
  118975. int ipp2;
  118976. t10=ip*ido;
  118977. t0=l1*ido;
  118978. arg=tpi/(float)ip;
  118979. dcp=cos(arg);
  118980. dsp=sin(arg);
  118981. nbd=(ido-1)>>1;
  118982. ipp2=ip;
  118983. ipph=(ip+1)>>1;
  118984. if(ido<l1)goto L103;
  118985. t1=0;
  118986. t2=0;
  118987. for(k=0;k<l1;k++){
  118988. t3=t1;
  118989. t4=t2;
  118990. for(i=0;i<ido;i++){
  118991. ch[t3]=cc[t4];
  118992. t3++;
  118993. t4++;
  118994. }
  118995. t1+=ido;
  118996. t2+=t10;
  118997. }
  118998. goto L106;
  118999. L103:
  119000. t1=0;
  119001. for(i=0;i<ido;i++){
  119002. t2=t1;
  119003. t3=t1;
  119004. for(k=0;k<l1;k++){
  119005. ch[t2]=cc[t3];
  119006. t2+=ido;
  119007. t3+=t10;
  119008. }
  119009. t1++;
  119010. }
  119011. L106:
  119012. t1=0;
  119013. t2=ipp2*t0;
  119014. t7=(t5=ido<<1);
  119015. for(j=1;j<ipph;j++){
  119016. t1+=t0;
  119017. t2-=t0;
  119018. t3=t1;
  119019. t4=t2;
  119020. t6=t5;
  119021. for(k=0;k<l1;k++){
  119022. ch[t3]=cc[t6-1]+cc[t6-1];
  119023. ch[t4]=cc[t6]+cc[t6];
  119024. t3+=ido;
  119025. t4+=ido;
  119026. t6+=t10;
  119027. }
  119028. t5+=t7;
  119029. }
  119030. if (ido == 1)goto L116;
  119031. if(nbd<l1)goto L112;
  119032. t1=0;
  119033. t2=ipp2*t0;
  119034. t7=0;
  119035. for(j=1;j<ipph;j++){
  119036. t1+=t0;
  119037. t2-=t0;
  119038. t3=t1;
  119039. t4=t2;
  119040. t7+=(ido<<1);
  119041. t8=t7;
  119042. for(k=0;k<l1;k++){
  119043. t5=t3;
  119044. t6=t4;
  119045. t9=t8;
  119046. t11=t8;
  119047. for(i=2;i<ido;i+=2){
  119048. t5+=2;
  119049. t6+=2;
  119050. t9+=2;
  119051. t11-=2;
  119052. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119053. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119054. ch[t5]=cc[t9]-cc[t11];
  119055. ch[t6]=cc[t9]+cc[t11];
  119056. }
  119057. t3+=ido;
  119058. t4+=ido;
  119059. t8+=t10;
  119060. }
  119061. }
  119062. goto L116;
  119063. L112:
  119064. t1=0;
  119065. t2=ipp2*t0;
  119066. t7=0;
  119067. for(j=1;j<ipph;j++){
  119068. t1+=t0;
  119069. t2-=t0;
  119070. t3=t1;
  119071. t4=t2;
  119072. t7+=(ido<<1);
  119073. t8=t7;
  119074. t9=t7;
  119075. for(i=2;i<ido;i+=2){
  119076. t3+=2;
  119077. t4+=2;
  119078. t8+=2;
  119079. t9-=2;
  119080. t5=t3;
  119081. t6=t4;
  119082. t11=t8;
  119083. t12=t9;
  119084. for(k=0;k<l1;k++){
  119085. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119086. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119087. ch[t5]=cc[t11]-cc[t12];
  119088. ch[t6]=cc[t11]+cc[t12];
  119089. t5+=ido;
  119090. t6+=ido;
  119091. t11+=t10;
  119092. t12+=t10;
  119093. }
  119094. }
  119095. }
  119096. L116:
  119097. ar1=1.f;
  119098. ai1=0.f;
  119099. t1=0;
  119100. t9=(t2=ipp2*idl1);
  119101. t3=(ip-1)*idl1;
  119102. for(l=1;l<ipph;l++){
  119103. t1+=idl1;
  119104. t2-=idl1;
  119105. ar1h=dcp*ar1-dsp*ai1;
  119106. ai1=dcp*ai1+dsp*ar1;
  119107. ar1=ar1h;
  119108. t4=t1;
  119109. t5=t2;
  119110. t6=0;
  119111. t7=idl1;
  119112. t8=t3;
  119113. for(ik=0;ik<idl1;ik++){
  119114. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119115. c2[t5++]=ai1*ch2[t8++];
  119116. }
  119117. dc2=ar1;
  119118. ds2=ai1;
  119119. ar2=ar1;
  119120. ai2=ai1;
  119121. t6=idl1;
  119122. t7=t9-idl1;
  119123. for(j=2;j<ipph;j++){
  119124. t6+=idl1;
  119125. t7-=idl1;
  119126. ar2h=dc2*ar2-ds2*ai2;
  119127. ai2=dc2*ai2+ds2*ar2;
  119128. ar2=ar2h;
  119129. t4=t1;
  119130. t5=t2;
  119131. t11=t6;
  119132. t12=t7;
  119133. for(ik=0;ik<idl1;ik++){
  119134. c2[t4++]+=ar2*ch2[t11++];
  119135. c2[t5++]+=ai2*ch2[t12++];
  119136. }
  119137. }
  119138. }
  119139. t1=0;
  119140. for(j=1;j<ipph;j++){
  119141. t1+=idl1;
  119142. t2=t1;
  119143. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  119144. }
  119145. t1=0;
  119146. t2=ipp2*t0;
  119147. for(j=1;j<ipph;j++){
  119148. t1+=t0;
  119149. t2-=t0;
  119150. t3=t1;
  119151. t4=t2;
  119152. for(k=0;k<l1;k++){
  119153. ch[t3]=c1[t3]-c1[t4];
  119154. ch[t4]=c1[t3]+c1[t4];
  119155. t3+=ido;
  119156. t4+=ido;
  119157. }
  119158. }
  119159. if(ido==1)goto L132;
  119160. if(nbd<l1)goto L128;
  119161. t1=0;
  119162. t2=ipp2*t0;
  119163. for(j=1;j<ipph;j++){
  119164. t1+=t0;
  119165. t2-=t0;
  119166. t3=t1;
  119167. t4=t2;
  119168. for(k=0;k<l1;k++){
  119169. t5=t3;
  119170. t6=t4;
  119171. for(i=2;i<ido;i+=2){
  119172. t5+=2;
  119173. t6+=2;
  119174. ch[t5-1]=c1[t5-1]-c1[t6];
  119175. ch[t6-1]=c1[t5-1]+c1[t6];
  119176. ch[t5]=c1[t5]+c1[t6-1];
  119177. ch[t6]=c1[t5]-c1[t6-1];
  119178. }
  119179. t3+=ido;
  119180. t4+=ido;
  119181. }
  119182. }
  119183. goto L132;
  119184. L128:
  119185. t1=0;
  119186. t2=ipp2*t0;
  119187. for(j=1;j<ipph;j++){
  119188. t1+=t0;
  119189. t2-=t0;
  119190. t3=t1;
  119191. t4=t2;
  119192. for(i=2;i<ido;i+=2){
  119193. t3+=2;
  119194. t4+=2;
  119195. t5=t3;
  119196. t6=t4;
  119197. for(k=0;k<l1;k++){
  119198. ch[t5-1]=c1[t5-1]-c1[t6];
  119199. ch[t6-1]=c1[t5-1]+c1[t6];
  119200. ch[t5]=c1[t5]+c1[t6-1];
  119201. ch[t6]=c1[t5]-c1[t6-1];
  119202. t5+=ido;
  119203. t6+=ido;
  119204. }
  119205. }
  119206. }
  119207. L132:
  119208. if(ido==1)return;
  119209. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119210. t1=0;
  119211. for(j=1;j<ip;j++){
  119212. t2=(t1+=t0);
  119213. for(k=0;k<l1;k++){
  119214. c1[t2]=ch[t2];
  119215. t2+=ido;
  119216. }
  119217. }
  119218. if(nbd>l1)goto L139;
  119219. is= -ido-1;
  119220. t1=0;
  119221. for(j=1;j<ip;j++){
  119222. is+=ido;
  119223. t1+=t0;
  119224. idij=is;
  119225. t2=t1;
  119226. for(i=2;i<ido;i+=2){
  119227. t2+=2;
  119228. idij+=2;
  119229. t3=t2;
  119230. for(k=0;k<l1;k++){
  119231. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119232. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119233. t3+=ido;
  119234. }
  119235. }
  119236. }
  119237. return;
  119238. L139:
  119239. is= -ido-1;
  119240. t1=0;
  119241. for(j=1;j<ip;j++){
  119242. is+=ido;
  119243. t1+=t0;
  119244. t2=t1;
  119245. for(k=0;k<l1;k++){
  119246. idij=is;
  119247. t3=t2;
  119248. for(i=2;i<ido;i+=2){
  119249. idij+=2;
  119250. t3+=2;
  119251. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119252. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119253. }
  119254. t2+=ido;
  119255. }
  119256. }
  119257. }
  119258. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  119259. int i,k1,l1,l2;
  119260. int na;
  119261. int nf,ip,iw,ix2,ix3,ido,idl1;
  119262. nf=ifac[1];
  119263. na=0;
  119264. l1=1;
  119265. iw=1;
  119266. for(k1=0;k1<nf;k1++){
  119267. ip=ifac[k1 + 2];
  119268. l2=ip*l1;
  119269. ido=n/l2;
  119270. idl1=ido*l1;
  119271. if(ip!=4)goto L103;
  119272. ix2=iw+ido;
  119273. ix3=ix2+ido;
  119274. if(na!=0)
  119275. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119276. else
  119277. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119278. na=1-na;
  119279. goto L115;
  119280. L103:
  119281. if(ip!=2)goto L106;
  119282. if(na!=0)
  119283. dradb2(ido,l1,ch,c,wa+iw-1);
  119284. else
  119285. dradb2(ido,l1,c,ch,wa+iw-1);
  119286. na=1-na;
  119287. goto L115;
  119288. L106:
  119289. if(ip!=3)goto L109;
  119290. ix2=iw+ido;
  119291. if(na!=0)
  119292. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  119293. else
  119294. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  119295. na=1-na;
  119296. goto L115;
  119297. L109:
  119298. /* The radix five case can be translated later..... */
  119299. /* if(ip!=5)goto L112;
  119300. ix2=iw+ido;
  119301. ix3=ix2+ido;
  119302. ix4=ix3+ido;
  119303. if(na!=0)
  119304. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119305. else
  119306. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119307. na=1-na;
  119308. goto L115;
  119309. L112:*/
  119310. if(na!=0)
  119311. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119312. else
  119313. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119314. if(ido==1)na=1-na;
  119315. L115:
  119316. l1=l2;
  119317. iw+=(ip-1)*ido;
  119318. }
  119319. if(na==0)return;
  119320. for(i=0;i<n;i++)c[i]=ch[i];
  119321. }
  119322. void drft_forward(drft_lookup *l,float *data){
  119323. if(l->n==1)return;
  119324. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119325. }
  119326. void drft_backward(drft_lookup *l,float *data){
  119327. if (l->n==1)return;
  119328. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119329. }
  119330. void drft_init(drft_lookup *l,int n){
  119331. l->n=n;
  119332. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  119333. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  119334. fdrffti(n, l->trigcache, l->splitcache);
  119335. }
  119336. void drft_clear(drft_lookup *l){
  119337. if(l){
  119338. if(l->trigcache)_ogg_free(l->trigcache);
  119339. if(l->splitcache)_ogg_free(l->splitcache);
  119340. memset(l,0,sizeof(*l));
  119341. }
  119342. }
  119343. #endif
  119344. /*** End of inlined file: smallft.c ***/
  119345. /*** Start of inlined file: synthesis.c ***/
  119346. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119347. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119348. // tasks..
  119349. #if JUCE_MSVC
  119350. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119351. #endif
  119352. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119353. #if JUCE_USE_OGGVORBIS
  119354. #include <stdio.h>
  119355. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  119356. vorbis_dsp_state *vd=vb->vd;
  119357. private_state *b=(private_state*)vd->backend_state;
  119358. vorbis_info *vi=vd->vi;
  119359. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  119360. oggpack_buffer *opb=&vb->opb;
  119361. int type,mode,i;
  119362. /* first things first. Make sure decode is ready */
  119363. _vorbis_block_ripcord(vb);
  119364. oggpack_readinit(opb,op->packet,op->bytes);
  119365. /* Check the packet type */
  119366. if(oggpack_read(opb,1)!=0){
  119367. /* Oops. This is not an audio data packet */
  119368. return(OV_ENOTAUDIO);
  119369. }
  119370. /* read our mode and pre/post windowsize */
  119371. mode=oggpack_read(opb,b->modebits);
  119372. if(mode==-1)return(OV_EBADPACKET);
  119373. vb->mode=mode;
  119374. vb->W=ci->mode_param[mode]->blockflag;
  119375. if(vb->W){
  119376. /* this doesn;t get mapped through mode selection as it's used
  119377. only for window selection */
  119378. vb->lW=oggpack_read(opb,1);
  119379. vb->nW=oggpack_read(opb,1);
  119380. if(vb->nW==-1) return(OV_EBADPACKET);
  119381. }else{
  119382. vb->lW=0;
  119383. vb->nW=0;
  119384. }
  119385. /* more setup */
  119386. vb->granulepos=op->granulepos;
  119387. vb->sequence=op->packetno;
  119388. vb->eofflag=op->e_o_s;
  119389. /* alloc pcm passback storage */
  119390. vb->pcmend=ci->blocksizes[vb->W];
  119391. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  119392. for(i=0;i<vi->channels;i++)
  119393. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  119394. /* unpack_header enforces range checking */
  119395. type=ci->map_type[ci->mode_param[mode]->mapping];
  119396. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  119397. mapping]));
  119398. }
  119399. /* used to track pcm position without actually performing decode.
  119400. Useful for sequential 'fast forward' */
  119401. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  119402. vorbis_dsp_state *vd=vb->vd;
  119403. private_state *b=(private_state*)vd->backend_state;
  119404. vorbis_info *vi=vd->vi;
  119405. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119406. oggpack_buffer *opb=&vb->opb;
  119407. int mode;
  119408. /* first things first. Make sure decode is ready */
  119409. _vorbis_block_ripcord(vb);
  119410. oggpack_readinit(opb,op->packet,op->bytes);
  119411. /* Check the packet type */
  119412. if(oggpack_read(opb,1)!=0){
  119413. /* Oops. This is not an audio data packet */
  119414. return(OV_ENOTAUDIO);
  119415. }
  119416. /* read our mode and pre/post windowsize */
  119417. mode=oggpack_read(opb,b->modebits);
  119418. if(mode==-1)return(OV_EBADPACKET);
  119419. vb->mode=mode;
  119420. vb->W=ci->mode_param[mode]->blockflag;
  119421. if(vb->W){
  119422. vb->lW=oggpack_read(opb,1);
  119423. vb->nW=oggpack_read(opb,1);
  119424. if(vb->nW==-1) return(OV_EBADPACKET);
  119425. }else{
  119426. vb->lW=0;
  119427. vb->nW=0;
  119428. }
  119429. /* more setup */
  119430. vb->granulepos=op->granulepos;
  119431. vb->sequence=op->packetno;
  119432. vb->eofflag=op->e_o_s;
  119433. /* no pcm */
  119434. vb->pcmend=0;
  119435. vb->pcm=NULL;
  119436. return(0);
  119437. }
  119438. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  119439. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119440. oggpack_buffer opb;
  119441. int mode;
  119442. oggpack_readinit(&opb,op->packet,op->bytes);
  119443. /* Check the packet type */
  119444. if(oggpack_read(&opb,1)!=0){
  119445. /* Oops. This is not an audio data packet */
  119446. return(OV_ENOTAUDIO);
  119447. }
  119448. {
  119449. int modebits=0;
  119450. int v=ci->modes;
  119451. while(v>1){
  119452. modebits++;
  119453. v>>=1;
  119454. }
  119455. /* read our mode and pre/post windowsize */
  119456. mode=oggpack_read(&opb,modebits);
  119457. }
  119458. if(mode==-1)return(OV_EBADPACKET);
  119459. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  119460. }
  119461. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  119462. /* set / clear half-sample-rate mode */
  119463. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119464. /* right now, our MDCT can't handle < 64 sample windows. */
  119465. if(ci->blocksizes[0]<=64 && flag)return -1;
  119466. ci->halfrate_flag=(flag?1:0);
  119467. return 0;
  119468. }
  119469. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  119470. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119471. return ci->halfrate_flag;
  119472. }
  119473. #endif
  119474. /*** End of inlined file: synthesis.c ***/
  119475. /*** Start of inlined file: vorbisenc.c ***/
  119476. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119477. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119478. // tasks..
  119479. #if JUCE_MSVC
  119480. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119481. #endif
  119482. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119483. #if JUCE_USE_OGGVORBIS
  119484. #include <stdlib.h>
  119485. #include <string.h>
  119486. #include <math.h>
  119487. /* careful with this; it's using static array sizing to make managing
  119488. all the modes a little less annoying. If we use a residue backend
  119489. with > 12 partition types, or a different division of iteration,
  119490. this needs to be updated. */
  119491. typedef struct {
  119492. static_codebook *books[12][3];
  119493. } static_bookblock;
  119494. typedef struct {
  119495. int res_type;
  119496. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  119497. vorbis_info_residue0 *res;
  119498. static_codebook *book_aux;
  119499. static_codebook *book_aux_managed;
  119500. static_bookblock *books_base;
  119501. static_bookblock *books_base_managed;
  119502. } vorbis_residue_template;
  119503. typedef struct {
  119504. vorbis_info_mapping0 *map;
  119505. vorbis_residue_template *res;
  119506. } vorbis_mapping_template;
  119507. typedef struct vp_adjblock{
  119508. int block[P_BANDS];
  119509. } vp_adjblock;
  119510. typedef struct {
  119511. int data[NOISE_COMPAND_LEVELS];
  119512. } compandblock;
  119513. /* high level configuration information for setting things up
  119514. step-by-step with the detailed vorbis_encode_ctl interface.
  119515. There's a fair amount of redundancy such that interactive setup
  119516. does not directly deal with any vorbis_info or codec_setup_info
  119517. initialization; it's all stored (until full init) in this highlevel
  119518. setup, then flushed out to the real codec setup structs later. */
  119519. typedef struct {
  119520. int att[P_NOISECURVES];
  119521. float boost;
  119522. float decay;
  119523. } att3;
  119524. typedef struct { int data[P_NOISECURVES]; } adj3;
  119525. typedef struct {
  119526. int pre[PACKETBLOBS];
  119527. int post[PACKETBLOBS];
  119528. float kHz[PACKETBLOBS];
  119529. float lowpasskHz[PACKETBLOBS];
  119530. } adj_stereo;
  119531. typedef struct {
  119532. int lo;
  119533. int hi;
  119534. int fixed;
  119535. } noiseguard;
  119536. typedef struct {
  119537. int data[P_NOISECURVES][17];
  119538. } noise3;
  119539. typedef struct {
  119540. int mappings;
  119541. double *rate_mapping;
  119542. double *quality_mapping;
  119543. int coupling_restriction;
  119544. long samplerate_min_restriction;
  119545. long samplerate_max_restriction;
  119546. int *blocksize_short;
  119547. int *blocksize_long;
  119548. att3 *psy_tone_masteratt;
  119549. int *psy_tone_0dB;
  119550. int *psy_tone_dBsuppress;
  119551. vp_adjblock *psy_tone_adj_impulse;
  119552. vp_adjblock *psy_tone_adj_long;
  119553. vp_adjblock *psy_tone_adj_other;
  119554. noiseguard *psy_noiseguards;
  119555. noise3 *psy_noise_bias_impulse;
  119556. noise3 *psy_noise_bias_padding;
  119557. noise3 *psy_noise_bias_trans;
  119558. noise3 *psy_noise_bias_long;
  119559. int *psy_noise_dBsuppress;
  119560. compandblock *psy_noise_compand;
  119561. double *psy_noise_compand_short_mapping;
  119562. double *psy_noise_compand_long_mapping;
  119563. int *psy_noise_normal_start[2];
  119564. int *psy_noise_normal_partition[2];
  119565. double *psy_noise_normal_thresh;
  119566. int *psy_ath_float;
  119567. int *psy_ath_abs;
  119568. double *psy_lowpass;
  119569. vorbis_info_psy_global *global_params;
  119570. double *global_mapping;
  119571. adj_stereo *stereo_modes;
  119572. static_codebook ***floor_books;
  119573. vorbis_info_floor1 *floor_params;
  119574. int *floor_short_mapping;
  119575. int *floor_long_mapping;
  119576. vorbis_mapping_template *maps;
  119577. } ve_setup_data_template;
  119578. /* a few static coder conventions */
  119579. static vorbis_info_mode _mode_template[2]={
  119580. {0,0,0,0},
  119581. {1,0,0,1}
  119582. };
  119583. static vorbis_info_mapping0 _map_nominal[2]={
  119584. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  119585. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  119586. };
  119587. /*** Start of inlined file: setup_44.h ***/
  119588. /*** Start of inlined file: floor_all.h ***/
  119589. /*** Start of inlined file: floor_books.h ***/
  119590. static long _huff_lengthlist_line_256x7_0sub1[] = {
  119591. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  119592. };
  119593. static static_codebook _huff_book_line_256x7_0sub1 = {
  119594. 1, 9,
  119595. _huff_lengthlist_line_256x7_0sub1,
  119596. 0, 0, 0, 0, 0,
  119597. NULL,
  119598. NULL,
  119599. NULL,
  119600. NULL,
  119601. 0
  119602. };
  119603. static long _huff_lengthlist_line_256x7_0sub2[] = {
  119604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  119605. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  119606. };
  119607. static static_codebook _huff_book_line_256x7_0sub2 = {
  119608. 1, 25,
  119609. _huff_lengthlist_line_256x7_0sub2,
  119610. 0, 0, 0, 0, 0,
  119611. NULL,
  119612. NULL,
  119613. NULL,
  119614. NULL,
  119615. 0
  119616. };
  119617. static long _huff_lengthlist_line_256x7_0sub3[] = {
  119618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  119620. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  119621. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  119622. };
  119623. static static_codebook _huff_book_line_256x7_0sub3 = {
  119624. 1, 64,
  119625. _huff_lengthlist_line_256x7_0sub3,
  119626. 0, 0, 0, 0, 0,
  119627. NULL,
  119628. NULL,
  119629. NULL,
  119630. NULL,
  119631. 0
  119632. };
  119633. static long _huff_lengthlist_line_256x7_1sub1[] = {
  119634. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  119635. };
  119636. static static_codebook _huff_book_line_256x7_1sub1 = {
  119637. 1, 9,
  119638. _huff_lengthlist_line_256x7_1sub1,
  119639. 0, 0, 0, 0, 0,
  119640. NULL,
  119641. NULL,
  119642. NULL,
  119643. NULL,
  119644. 0
  119645. };
  119646. static long _huff_lengthlist_line_256x7_1sub2[] = {
  119647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  119648. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  119649. };
  119650. static static_codebook _huff_book_line_256x7_1sub2 = {
  119651. 1, 25,
  119652. _huff_lengthlist_line_256x7_1sub2,
  119653. 0, 0, 0, 0, 0,
  119654. NULL,
  119655. NULL,
  119656. NULL,
  119657. NULL,
  119658. 0
  119659. };
  119660. static long _huff_lengthlist_line_256x7_1sub3[] = {
  119661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  119663. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119664. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  119665. };
  119666. static static_codebook _huff_book_line_256x7_1sub3 = {
  119667. 1, 64,
  119668. _huff_lengthlist_line_256x7_1sub3,
  119669. 0, 0, 0, 0, 0,
  119670. NULL,
  119671. NULL,
  119672. NULL,
  119673. NULL,
  119674. 0
  119675. };
  119676. static long _huff_lengthlist_line_256x7_class0[] = {
  119677. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  119678. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  119679. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  119680. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  119681. };
  119682. static static_codebook _huff_book_line_256x7_class0 = {
  119683. 1, 64,
  119684. _huff_lengthlist_line_256x7_class0,
  119685. 0, 0, 0, 0, 0,
  119686. NULL,
  119687. NULL,
  119688. NULL,
  119689. NULL,
  119690. 0
  119691. };
  119692. static long _huff_lengthlist_line_256x7_class1[] = {
  119693. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  119694. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  119695. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  119696. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  119697. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  119698. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  119699. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  119700. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  119701. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  119702. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  119703. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  119704. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  119705. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  119706. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  119707. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  119708. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  119709. };
  119710. static static_codebook _huff_book_line_256x7_class1 = {
  119711. 1, 256,
  119712. _huff_lengthlist_line_256x7_class1,
  119713. 0, 0, 0, 0, 0,
  119714. NULL,
  119715. NULL,
  119716. NULL,
  119717. NULL,
  119718. 0
  119719. };
  119720. static long _huff_lengthlist_line_512x17_0sub0[] = {
  119721. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  119722. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  119723. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  119724. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  119725. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  119726. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  119727. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  119728. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  119729. };
  119730. static static_codebook _huff_book_line_512x17_0sub0 = {
  119731. 1, 128,
  119732. _huff_lengthlist_line_512x17_0sub0,
  119733. 0, 0, 0, 0, 0,
  119734. NULL,
  119735. NULL,
  119736. NULL,
  119737. NULL,
  119738. 0
  119739. };
  119740. static long _huff_lengthlist_line_512x17_1sub0[] = {
  119741. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  119742. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  119743. };
  119744. static static_codebook _huff_book_line_512x17_1sub0 = {
  119745. 1, 32,
  119746. _huff_lengthlist_line_512x17_1sub0,
  119747. 0, 0, 0, 0, 0,
  119748. NULL,
  119749. NULL,
  119750. NULL,
  119751. NULL,
  119752. 0
  119753. };
  119754. static long _huff_lengthlist_line_512x17_1sub1[] = {
  119755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119757. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  119758. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  119759. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  119760. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  119761. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  119762. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  119763. };
  119764. static static_codebook _huff_book_line_512x17_1sub1 = {
  119765. 1, 128,
  119766. _huff_lengthlist_line_512x17_1sub1,
  119767. 0, 0, 0, 0, 0,
  119768. NULL,
  119769. NULL,
  119770. NULL,
  119771. NULL,
  119772. 0
  119773. };
  119774. static long _huff_lengthlist_line_512x17_2sub1[] = {
  119775. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  119776. 5, 3,
  119777. };
  119778. static static_codebook _huff_book_line_512x17_2sub1 = {
  119779. 1, 18,
  119780. _huff_lengthlist_line_512x17_2sub1,
  119781. 0, 0, 0, 0, 0,
  119782. NULL,
  119783. NULL,
  119784. NULL,
  119785. NULL,
  119786. 0
  119787. };
  119788. static long _huff_lengthlist_line_512x17_2sub2[] = {
  119789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119790. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  119791. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  119792. 9, 8,
  119793. };
  119794. static static_codebook _huff_book_line_512x17_2sub2 = {
  119795. 1, 50,
  119796. _huff_lengthlist_line_512x17_2sub2,
  119797. 0, 0, 0, 0, 0,
  119798. NULL,
  119799. NULL,
  119800. NULL,
  119801. NULL,
  119802. 0
  119803. };
  119804. static long _huff_lengthlist_line_512x17_2sub3[] = {
  119805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119808. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  119809. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  119810. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119811. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119812. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119813. };
  119814. static static_codebook _huff_book_line_512x17_2sub3 = {
  119815. 1, 128,
  119816. _huff_lengthlist_line_512x17_2sub3,
  119817. 0, 0, 0, 0, 0,
  119818. NULL,
  119819. NULL,
  119820. NULL,
  119821. NULL,
  119822. 0
  119823. };
  119824. static long _huff_lengthlist_line_512x17_3sub1[] = {
  119825. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  119826. 5, 5,
  119827. };
  119828. static static_codebook _huff_book_line_512x17_3sub1 = {
  119829. 1, 18,
  119830. _huff_lengthlist_line_512x17_3sub1,
  119831. 0, 0, 0, 0, 0,
  119832. NULL,
  119833. NULL,
  119834. NULL,
  119835. NULL,
  119836. 0
  119837. };
  119838. static long _huff_lengthlist_line_512x17_3sub2[] = {
  119839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119840. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  119841. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  119842. 11,14,
  119843. };
  119844. static static_codebook _huff_book_line_512x17_3sub2 = {
  119845. 1, 50,
  119846. _huff_lengthlist_line_512x17_3sub2,
  119847. 0, 0, 0, 0, 0,
  119848. NULL,
  119849. NULL,
  119850. NULL,
  119851. NULL,
  119852. 0
  119853. };
  119854. static long _huff_lengthlist_line_512x17_3sub3[] = {
  119855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119858. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  119859. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119860. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119861. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119862. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119863. };
  119864. static static_codebook _huff_book_line_512x17_3sub3 = {
  119865. 1, 128,
  119866. _huff_lengthlist_line_512x17_3sub3,
  119867. 0, 0, 0, 0, 0,
  119868. NULL,
  119869. NULL,
  119870. NULL,
  119871. NULL,
  119872. 0
  119873. };
  119874. static long _huff_lengthlist_line_512x17_class1[] = {
  119875. 1, 2, 3, 6, 5, 4, 7, 7,
  119876. };
  119877. static static_codebook _huff_book_line_512x17_class1 = {
  119878. 1, 8,
  119879. _huff_lengthlist_line_512x17_class1,
  119880. 0, 0, 0, 0, 0,
  119881. NULL,
  119882. NULL,
  119883. NULL,
  119884. NULL,
  119885. 0
  119886. };
  119887. static long _huff_lengthlist_line_512x17_class2[] = {
  119888. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  119889. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  119890. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  119891. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  119892. };
  119893. static static_codebook _huff_book_line_512x17_class2 = {
  119894. 1, 64,
  119895. _huff_lengthlist_line_512x17_class2,
  119896. 0, 0, 0, 0, 0,
  119897. NULL,
  119898. NULL,
  119899. NULL,
  119900. NULL,
  119901. 0
  119902. };
  119903. static long _huff_lengthlist_line_512x17_class3[] = {
  119904. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  119905. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  119906. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  119907. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  119908. };
  119909. static static_codebook _huff_book_line_512x17_class3 = {
  119910. 1, 64,
  119911. _huff_lengthlist_line_512x17_class3,
  119912. 0, 0, 0, 0, 0,
  119913. NULL,
  119914. NULL,
  119915. NULL,
  119916. NULL,
  119917. 0
  119918. };
  119919. static long _huff_lengthlist_line_128x4_class0[] = {
  119920. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  119921. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  119922. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  119923. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  119924. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  119925. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  119926. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  119927. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  119928. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  119929. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  119930. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  119931. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  119932. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  119933. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  119934. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  119935. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  119936. };
  119937. static static_codebook _huff_book_line_128x4_class0 = {
  119938. 1, 256,
  119939. _huff_lengthlist_line_128x4_class0,
  119940. 0, 0, 0, 0, 0,
  119941. NULL,
  119942. NULL,
  119943. NULL,
  119944. NULL,
  119945. 0
  119946. };
  119947. static long _huff_lengthlist_line_128x4_0sub0[] = {
  119948. 2, 2, 2, 2,
  119949. };
  119950. static static_codebook _huff_book_line_128x4_0sub0 = {
  119951. 1, 4,
  119952. _huff_lengthlist_line_128x4_0sub0,
  119953. 0, 0, 0, 0, 0,
  119954. NULL,
  119955. NULL,
  119956. NULL,
  119957. NULL,
  119958. 0
  119959. };
  119960. static long _huff_lengthlist_line_128x4_0sub1[] = {
  119961. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  119962. };
  119963. static static_codebook _huff_book_line_128x4_0sub1 = {
  119964. 1, 10,
  119965. _huff_lengthlist_line_128x4_0sub1,
  119966. 0, 0, 0, 0, 0,
  119967. NULL,
  119968. NULL,
  119969. NULL,
  119970. NULL,
  119971. 0
  119972. };
  119973. static long _huff_lengthlist_line_128x4_0sub2[] = {
  119974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  119975. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  119976. };
  119977. static static_codebook _huff_book_line_128x4_0sub2 = {
  119978. 1, 25,
  119979. _huff_lengthlist_line_128x4_0sub2,
  119980. 0, 0, 0, 0, 0,
  119981. NULL,
  119982. NULL,
  119983. NULL,
  119984. NULL,
  119985. 0
  119986. };
  119987. static long _huff_lengthlist_line_128x4_0sub3[] = {
  119988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  119990. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  119991. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  119992. };
  119993. static static_codebook _huff_book_line_128x4_0sub3 = {
  119994. 1, 64,
  119995. _huff_lengthlist_line_128x4_0sub3,
  119996. 0, 0, 0, 0, 0,
  119997. NULL,
  119998. NULL,
  119999. NULL,
  120000. NULL,
  120001. 0
  120002. };
  120003. static long _huff_lengthlist_line_256x4_class0[] = {
  120004. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120005. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120006. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120007. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120008. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120009. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120010. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120011. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120012. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120013. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120014. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120015. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120016. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120017. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120018. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120019. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120020. };
  120021. static static_codebook _huff_book_line_256x4_class0 = {
  120022. 1, 256,
  120023. _huff_lengthlist_line_256x4_class0,
  120024. 0, 0, 0, 0, 0,
  120025. NULL,
  120026. NULL,
  120027. NULL,
  120028. NULL,
  120029. 0
  120030. };
  120031. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120032. 2, 2, 2, 2,
  120033. };
  120034. static static_codebook _huff_book_line_256x4_0sub0 = {
  120035. 1, 4,
  120036. _huff_lengthlist_line_256x4_0sub0,
  120037. 0, 0, 0, 0, 0,
  120038. NULL,
  120039. NULL,
  120040. NULL,
  120041. NULL,
  120042. 0
  120043. };
  120044. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120045. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120046. };
  120047. static static_codebook _huff_book_line_256x4_0sub1 = {
  120048. 1, 10,
  120049. _huff_lengthlist_line_256x4_0sub1,
  120050. 0, 0, 0, 0, 0,
  120051. NULL,
  120052. NULL,
  120053. NULL,
  120054. NULL,
  120055. 0
  120056. };
  120057. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120059. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120060. };
  120061. static static_codebook _huff_book_line_256x4_0sub2 = {
  120062. 1, 25,
  120063. _huff_lengthlist_line_256x4_0sub2,
  120064. 0, 0, 0, 0, 0,
  120065. NULL,
  120066. NULL,
  120067. NULL,
  120068. NULL,
  120069. 0
  120070. };
  120071. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120074. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120075. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120076. };
  120077. static static_codebook _huff_book_line_256x4_0sub3 = {
  120078. 1, 64,
  120079. _huff_lengthlist_line_256x4_0sub3,
  120080. 0, 0, 0, 0, 0,
  120081. NULL,
  120082. NULL,
  120083. NULL,
  120084. NULL,
  120085. 0
  120086. };
  120087. static long _huff_lengthlist_line_128x7_class0[] = {
  120088. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120089. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120090. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120091. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120092. };
  120093. static static_codebook _huff_book_line_128x7_class0 = {
  120094. 1, 64,
  120095. _huff_lengthlist_line_128x7_class0,
  120096. 0, 0, 0, 0, 0,
  120097. NULL,
  120098. NULL,
  120099. NULL,
  120100. NULL,
  120101. 0
  120102. };
  120103. static long _huff_lengthlist_line_128x7_class1[] = {
  120104. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120105. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120106. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120107. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120108. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120109. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120110. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120111. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120112. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120113. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120114. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120115. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120116. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120117. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120118. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120119. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120120. };
  120121. static static_codebook _huff_book_line_128x7_class1 = {
  120122. 1, 256,
  120123. _huff_lengthlist_line_128x7_class1,
  120124. 0, 0, 0, 0, 0,
  120125. NULL,
  120126. NULL,
  120127. NULL,
  120128. NULL,
  120129. 0
  120130. };
  120131. static long _huff_lengthlist_line_128x7_0sub1[] = {
  120132. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  120133. };
  120134. static static_codebook _huff_book_line_128x7_0sub1 = {
  120135. 1, 9,
  120136. _huff_lengthlist_line_128x7_0sub1,
  120137. 0, 0, 0, 0, 0,
  120138. NULL,
  120139. NULL,
  120140. NULL,
  120141. NULL,
  120142. 0
  120143. };
  120144. static long _huff_lengthlist_line_128x7_0sub2[] = {
  120145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  120146. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  120147. };
  120148. static static_codebook _huff_book_line_128x7_0sub2 = {
  120149. 1, 25,
  120150. _huff_lengthlist_line_128x7_0sub2,
  120151. 0, 0, 0, 0, 0,
  120152. NULL,
  120153. NULL,
  120154. NULL,
  120155. NULL,
  120156. 0
  120157. };
  120158. static long _huff_lengthlist_line_128x7_0sub3[] = {
  120159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  120161. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120162. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  120163. };
  120164. static static_codebook _huff_book_line_128x7_0sub3 = {
  120165. 1, 64,
  120166. _huff_lengthlist_line_128x7_0sub3,
  120167. 0, 0, 0, 0, 0,
  120168. NULL,
  120169. NULL,
  120170. NULL,
  120171. NULL,
  120172. 0
  120173. };
  120174. static long _huff_lengthlist_line_128x7_1sub1[] = {
  120175. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  120176. };
  120177. static static_codebook _huff_book_line_128x7_1sub1 = {
  120178. 1, 9,
  120179. _huff_lengthlist_line_128x7_1sub1,
  120180. 0, 0, 0, 0, 0,
  120181. NULL,
  120182. NULL,
  120183. NULL,
  120184. NULL,
  120185. 0
  120186. };
  120187. static long _huff_lengthlist_line_128x7_1sub2[] = {
  120188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  120189. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  120190. };
  120191. static static_codebook _huff_book_line_128x7_1sub2 = {
  120192. 1, 25,
  120193. _huff_lengthlist_line_128x7_1sub2,
  120194. 0, 0, 0, 0, 0,
  120195. NULL,
  120196. NULL,
  120197. NULL,
  120198. NULL,
  120199. 0
  120200. };
  120201. static long _huff_lengthlist_line_128x7_1sub3[] = {
  120202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  120204. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  120205. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  120206. };
  120207. static static_codebook _huff_book_line_128x7_1sub3 = {
  120208. 1, 64,
  120209. _huff_lengthlist_line_128x7_1sub3,
  120210. 0, 0, 0, 0, 0,
  120211. NULL,
  120212. NULL,
  120213. NULL,
  120214. NULL,
  120215. 0
  120216. };
  120217. static long _huff_lengthlist_line_128x11_class1[] = {
  120218. 1, 6, 3, 7, 2, 4, 5, 7,
  120219. };
  120220. static static_codebook _huff_book_line_128x11_class1 = {
  120221. 1, 8,
  120222. _huff_lengthlist_line_128x11_class1,
  120223. 0, 0, 0, 0, 0,
  120224. NULL,
  120225. NULL,
  120226. NULL,
  120227. NULL,
  120228. 0
  120229. };
  120230. static long _huff_lengthlist_line_128x11_class2[] = {
  120231. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  120232. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  120233. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  120234. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  120235. };
  120236. static static_codebook _huff_book_line_128x11_class2 = {
  120237. 1, 64,
  120238. _huff_lengthlist_line_128x11_class2,
  120239. 0, 0, 0, 0, 0,
  120240. NULL,
  120241. NULL,
  120242. NULL,
  120243. NULL,
  120244. 0
  120245. };
  120246. static long _huff_lengthlist_line_128x11_class3[] = {
  120247. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  120248. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  120249. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  120250. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  120251. };
  120252. static static_codebook _huff_book_line_128x11_class3 = {
  120253. 1, 64,
  120254. _huff_lengthlist_line_128x11_class3,
  120255. 0, 0, 0, 0, 0,
  120256. NULL,
  120257. NULL,
  120258. NULL,
  120259. NULL,
  120260. 0
  120261. };
  120262. static long _huff_lengthlist_line_128x11_0sub0[] = {
  120263. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120264. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  120265. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  120266. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  120267. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  120268. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  120269. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  120270. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120271. };
  120272. static static_codebook _huff_book_line_128x11_0sub0 = {
  120273. 1, 128,
  120274. _huff_lengthlist_line_128x11_0sub0,
  120275. 0, 0, 0, 0, 0,
  120276. NULL,
  120277. NULL,
  120278. NULL,
  120279. NULL,
  120280. 0
  120281. };
  120282. static long _huff_lengthlist_line_128x11_1sub0[] = {
  120283. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  120284. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  120285. };
  120286. static static_codebook _huff_book_line_128x11_1sub0 = {
  120287. 1, 32,
  120288. _huff_lengthlist_line_128x11_1sub0,
  120289. 0, 0, 0, 0, 0,
  120290. NULL,
  120291. NULL,
  120292. NULL,
  120293. NULL,
  120294. 0
  120295. };
  120296. static long _huff_lengthlist_line_128x11_1sub1[] = {
  120297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120299. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120300. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  120301. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  120302. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  120303. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  120304. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  120305. };
  120306. static static_codebook _huff_book_line_128x11_1sub1 = {
  120307. 1, 128,
  120308. _huff_lengthlist_line_128x11_1sub1,
  120309. 0, 0, 0, 0, 0,
  120310. NULL,
  120311. NULL,
  120312. NULL,
  120313. NULL,
  120314. 0
  120315. };
  120316. static long _huff_lengthlist_line_128x11_2sub1[] = {
  120317. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  120318. 5, 5,
  120319. };
  120320. static static_codebook _huff_book_line_128x11_2sub1 = {
  120321. 1, 18,
  120322. _huff_lengthlist_line_128x11_2sub1,
  120323. 0, 0, 0, 0, 0,
  120324. NULL,
  120325. NULL,
  120326. NULL,
  120327. NULL,
  120328. 0
  120329. };
  120330. static long _huff_lengthlist_line_128x11_2sub2[] = {
  120331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120332. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  120333. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  120334. 8,11,
  120335. };
  120336. static static_codebook _huff_book_line_128x11_2sub2 = {
  120337. 1, 50,
  120338. _huff_lengthlist_line_128x11_2sub2,
  120339. 0, 0, 0, 0, 0,
  120340. NULL,
  120341. NULL,
  120342. NULL,
  120343. NULL,
  120344. 0
  120345. };
  120346. static long _huff_lengthlist_line_128x11_2sub3[] = {
  120347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120350. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  120351. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120352. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120353. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120354. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120355. };
  120356. static static_codebook _huff_book_line_128x11_2sub3 = {
  120357. 1, 128,
  120358. _huff_lengthlist_line_128x11_2sub3,
  120359. 0, 0, 0, 0, 0,
  120360. NULL,
  120361. NULL,
  120362. NULL,
  120363. NULL,
  120364. 0
  120365. };
  120366. static long _huff_lengthlist_line_128x11_3sub1[] = {
  120367. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  120368. 5, 4,
  120369. };
  120370. static static_codebook _huff_book_line_128x11_3sub1 = {
  120371. 1, 18,
  120372. _huff_lengthlist_line_128x11_3sub1,
  120373. 0, 0, 0, 0, 0,
  120374. NULL,
  120375. NULL,
  120376. NULL,
  120377. NULL,
  120378. 0
  120379. };
  120380. static long _huff_lengthlist_line_128x11_3sub2[] = {
  120381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120382. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  120383. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  120384. 12, 6,
  120385. };
  120386. static static_codebook _huff_book_line_128x11_3sub2 = {
  120387. 1, 50,
  120388. _huff_lengthlist_line_128x11_3sub2,
  120389. 0, 0, 0, 0, 0,
  120390. NULL,
  120391. NULL,
  120392. NULL,
  120393. NULL,
  120394. 0
  120395. };
  120396. static long _huff_lengthlist_line_128x11_3sub3[] = {
  120397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120400. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  120401. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  120402. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120403. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120404. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  120405. };
  120406. static static_codebook _huff_book_line_128x11_3sub3 = {
  120407. 1, 128,
  120408. _huff_lengthlist_line_128x11_3sub3,
  120409. 0, 0, 0, 0, 0,
  120410. NULL,
  120411. NULL,
  120412. NULL,
  120413. NULL,
  120414. 0
  120415. };
  120416. static long _huff_lengthlist_line_128x17_class1[] = {
  120417. 1, 3, 4, 7, 2, 5, 6, 7,
  120418. };
  120419. static static_codebook _huff_book_line_128x17_class1 = {
  120420. 1, 8,
  120421. _huff_lengthlist_line_128x17_class1,
  120422. 0, 0, 0, 0, 0,
  120423. NULL,
  120424. NULL,
  120425. NULL,
  120426. NULL,
  120427. 0
  120428. };
  120429. static long _huff_lengthlist_line_128x17_class2[] = {
  120430. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  120431. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  120432. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  120433. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120434. };
  120435. static static_codebook _huff_book_line_128x17_class2 = {
  120436. 1, 64,
  120437. _huff_lengthlist_line_128x17_class2,
  120438. 0, 0, 0, 0, 0,
  120439. NULL,
  120440. NULL,
  120441. NULL,
  120442. NULL,
  120443. 0
  120444. };
  120445. static long _huff_lengthlist_line_128x17_class3[] = {
  120446. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  120447. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  120448. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  120449. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  120450. };
  120451. static static_codebook _huff_book_line_128x17_class3 = {
  120452. 1, 64,
  120453. _huff_lengthlist_line_128x17_class3,
  120454. 0, 0, 0, 0, 0,
  120455. NULL,
  120456. NULL,
  120457. NULL,
  120458. NULL,
  120459. 0
  120460. };
  120461. static long _huff_lengthlist_line_128x17_0sub0[] = {
  120462. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120463. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  120464. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  120465. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  120466. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  120467. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  120468. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  120469. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120470. };
  120471. static static_codebook _huff_book_line_128x17_0sub0 = {
  120472. 1, 128,
  120473. _huff_lengthlist_line_128x17_0sub0,
  120474. 0, 0, 0, 0, 0,
  120475. NULL,
  120476. NULL,
  120477. NULL,
  120478. NULL,
  120479. 0
  120480. };
  120481. static long _huff_lengthlist_line_128x17_1sub0[] = {
  120482. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120483. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  120484. };
  120485. static static_codebook _huff_book_line_128x17_1sub0 = {
  120486. 1, 32,
  120487. _huff_lengthlist_line_128x17_1sub0,
  120488. 0, 0, 0, 0, 0,
  120489. NULL,
  120490. NULL,
  120491. NULL,
  120492. NULL,
  120493. 0
  120494. };
  120495. static long _huff_lengthlist_line_128x17_1sub1[] = {
  120496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120498. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  120499. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  120500. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  120501. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  120502. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  120503. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  120504. };
  120505. static static_codebook _huff_book_line_128x17_1sub1 = {
  120506. 1, 128,
  120507. _huff_lengthlist_line_128x17_1sub1,
  120508. 0, 0, 0, 0, 0,
  120509. NULL,
  120510. NULL,
  120511. NULL,
  120512. NULL,
  120513. 0
  120514. };
  120515. static long _huff_lengthlist_line_128x17_2sub1[] = {
  120516. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  120517. 9, 4,
  120518. };
  120519. static static_codebook _huff_book_line_128x17_2sub1 = {
  120520. 1, 18,
  120521. _huff_lengthlist_line_128x17_2sub1,
  120522. 0, 0, 0, 0, 0,
  120523. NULL,
  120524. NULL,
  120525. NULL,
  120526. NULL,
  120527. 0
  120528. };
  120529. static long _huff_lengthlist_line_128x17_2sub2[] = {
  120530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120531. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  120532. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  120533. 13,13,
  120534. };
  120535. static static_codebook _huff_book_line_128x17_2sub2 = {
  120536. 1, 50,
  120537. _huff_lengthlist_line_128x17_2sub2,
  120538. 0, 0, 0, 0, 0,
  120539. NULL,
  120540. NULL,
  120541. NULL,
  120542. NULL,
  120543. 0
  120544. };
  120545. static long _huff_lengthlist_line_128x17_2sub3[] = {
  120546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120549. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120550. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  120551. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120552. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120553. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120554. };
  120555. static static_codebook _huff_book_line_128x17_2sub3 = {
  120556. 1, 128,
  120557. _huff_lengthlist_line_128x17_2sub3,
  120558. 0, 0, 0, 0, 0,
  120559. NULL,
  120560. NULL,
  120561. NULL,
  120562. NULL,
  120563. 0
  120564. };
  120565. static long _huff_lengthlist_line_128x17_3sub1[] = {
  120566. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  120567. 6, 4,
  120568. };
  120569. static static_codebook _huff_book_line_128x17_3sub1 = {
  120570. 1, 18,
  120571. _huff_lengthlist_line_128x17_3sub1,
  120572. 0, 0, 0, 0, 0,
  120573. NULL,
  120574. NULL,
  120575. NULL,
  120576. NULL,
  120577. 0
  120578. };
  120579. static long _huff_lengthlist_line_128x17_3sub2[] = {
  120580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120581. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120582. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  120583. 10, 8,
  120584. };
  120585. static static_codebook _huff_book_line_128x17_3sub2 = {
  120586. 1, 50,
  120587. _huff_lengthlist_line_128x17_3sub2,
  120588. 0, 0, 0, 0, 0,
  120589. NULL,
  120590. NULL,
  120591. NULL,
  120592. NULL,
  120593. 0
  120594. };
  120595. static long _huff_lengthlist_line_128x17_3sub3[] = {
  120596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120599. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  120600. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  120601. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120604. };
  120605. static static_codebook _huff_book_line_128x17_3sub3 = {
  120606. 1, 128,
  120607. _huff_lengthlist_line_128x17_3sub3,
  120608. 0, 0, 0, 0, 0,
  120609. NULL,
  120610. NULL,
  120611. NULL,
  120612. NULL,
  120613. 0
  120614. };
  120615. static long _huff_lengthlist_line_1024x27_class1[] = {
  120616. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  120617. };
  120618. static static_codebook _huff_book_line_1024x27_class1 = {
  120619. 1, 16,
  120620. _huff_lengthlist_line_1024x27_class1,
  120621. 0, 0, 0, 0, 0,
  120622. NULL,
  120623. NULL,
  120624. NULL,
  120625. NULL,
  120626. 0
  120627. };
  120628. static long _huff_lengthlist_line_1024x27_class2[] = {
  120629. 1, 4, 2, 6, 3, 7, 5, 7,
  120630. };
  120631. static static_codebook _huff_book_line_1024x27_class2 = {
  120632. 1, 8,
  120633. _huff_lengthlist_line_1024x27_class2,
  120634. 0, 0, 0, 0, 0,
  120635. NULL,
  120636. NULL,
  120637. NULL,
  120638. NULL,
  120639. 0
  120640. };
  120641. static long _huff_lengthlist_line_1024x27_class3[] = {
  120642. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  120643. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  120644. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  120645. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  120646. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  120647. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  120648. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  120649. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  120650. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  120651. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  120652. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  120653. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120654. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  120655. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  120656. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  120657. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120658. };
  120659. static static_codebook _huff_book_line_1024x27_class3 = {
  120660. 1, 256,
  120661. _huff_lengthlist_line_1024x27_class3,
  120662. 0, 0, 0, 0, 0,
  120663. NULL,
  120664. NULL,
  120665. NULL,
  120666. NULL,
  120667. 0
  120668. };
  120669. static long _huff_lengthlist_line_1024x27_class4[] = {
  120670. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  120671. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  120672. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  120673. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  120674. };
  120675. static static_codebook _huff_book_line_1024x27_class4 = {
  120676. 1, 64,
  120677. _huff_lengthlist_line_1024x27_class4,
  120678. 0, 0, 0, 0, 0,
  120679. NULL,
  120680. NULL,
  120681. NULL,
  120682. NULL,
  120683. 0
  120684. };
  120685. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  120686. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120687. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  120688. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  120689. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  120690. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  120691. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  120692. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  120693. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  120694. };
  120695. static static_codebook _huff_book_line_1024x27_0sub0 = {
  120696. 1, 128,
  120697. _huff_lengthlist_line_1024x27_0sub0,
  120698. 0, 0, 0, 0, 0,
  120699. NULL,
  120700. NULL,
  120701. NULL,
  120702. NULL,
  120703. 0
  120704. };
  120705. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  120706. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  120707. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  120708. };
  120709. static static_codebook _huff_book_line_1024x27_1sub0 = {
  120710. 1, 32,
  120711. _huff_lengthlist_line_1024x27_1sub0,
  120712. 0, 0, 0, 0, 0,
  120713. NULL,
  120714. NULL,
  120715. NULL,
  120716. NULL,
  120717. 0
  120718. };
  120719. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  120720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120722. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  120723. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  120724. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  120725. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  120726. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  120727. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  120728. };
  120729. static static_codebook _huff_book_line_1024x27_1sub1 = {
  120730. 1, 128,
  120731. _huff_lengthlist_line_1024x27_1sub1,
  120732. 0, 0, 0, 0, 0,
  120733. NULL,
  120734. NULL,
  120735. NULL,
  120736. NULL,
  120737. 0
  120738. };
  120739. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  120740. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120741. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  120742. };
  120743. static static_codebook _huff_book_line_1024x27_2sub0 = {
  120744. 1, 32,
  120745. _huff_lengthlist_line_1024x27_2sub0,
  120746. 0, 0, 0, 0, 0,
  120747. NULL,
  120748. NULL,
  120749. NULL,
  120750. NULL,
  120751. 0
  120752. };
  120753. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  120754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120756. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  120757. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  120758. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  120759. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  120760. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  120761. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  120762. };
  120763. static static_codebook _huff_book_line_1024x27_2sub1 = {
  120764. 1, 128,
  120765. _huff_lengthlist_line_1024x27_2sub1,
  120766. 0, 0, 0, 0, 0,
  120767. NULL,
  120768. NULL,
  120769. NULL,
  120770. NULL,
  120771. 0
  120772. };
  120773. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  120774. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  120775. 5, 5,
  120776. };
  120777. static static_codebook _huff_book_line_1024x27_3sub1 = {
  120778. 1, 18,
  120779. _huff_lengthlist_line_1024x27_3sub1,
  120780. 0, 0, 0, 0, 0,
  120781. NULL,
  120782. NULL,
  120783. NULL,
  120784. NULL,
  120785. 0
  120786. };
  120787. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  120788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120789. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  120790. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  120791. 9,11,
  120792. };
  120793. static static_codebook _huff_book_line_1024x27_3sub2 = {
  120794. 1, 50,
  120795. _huff_lengthlist_line_1024x27_3sub2,
  120796. 0, 0, 0, 0, 0,
  120797. NULL,
  120798. NULL,
  120799. NULL,
  120800. NULL,
  120801. 0
  120802. };
  120803. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  120804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120807. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  120808. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  120809. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  120810. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  120811. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  120812. };
  120813. static static_codebook _huff_book_line_1024x27_3sub3 = {
  120814. 1, 128,
  120815. _huff_lengthlist_line_1024x27_3sub3,
  120816. 0, 0, 0, 0, 0,
  120817. NULL,
  120818. NULL,
  120819. NULL,
  120820. NULL,
  120821. 0
  120822. };
  120823. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  120824. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  120825. 5, 4,
  120826. };
  120827. static static_codebook _huff_book_line_1024x27_4sub1 = {
  120828. 1, 18,
  120829. _huff_lengthlist_line_1024x27_4sub1,
  120830. 0, 0, 0, 0, 0,
  120831. NULL,
  120832. NULL,
  120833. NULL,
  120834. NULL,
  120835. 0
  120836. };
  120837. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  120838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120839. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  120840. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  120841. 9,12,
  120842. };
  120843. static static_codebook _huff_book_line_1024x27_4sub2 = {
  120844. 1, 50,
  120845. _huff_lengthlist_line_1024x27_4sub2,
  120846. 0, 0, 0, 0, 0,
  120847. NULL,
  120848. NULL,
  120849. NULL,
  120850. NULL,
  120851. 0
  120852. };
  120853. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  120854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120857. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  120858. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  120859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120860. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120861. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  120862. };
  120863. static static_codebook _huff_book_line_1024x27_4sub3 = {
  120864. 1, 128,
  120865. _huff_lengthlist_line_1024x27_4sub3,
  120866. 0, 0, 0, 0, 0,
  120867. NULL,
  120868. NULL,
  120869. NULL,
  120870. NULL,
  120871. 0
  120872. };
  120873. static long _huff_lengthlist_line_2048x27_class1[] = {
  120874. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  120875. };
  120876. static static_codebook _huff_book_line_2048x27_class1 = {
  120877. 1, 16,
  120878. _huff_lengthlist_line_2048x27_class1,
  120879. 0, 0, 0, 0, 0,
  120880. NULL,
  120881. NULL,
  120882. NULL,
  120883. NULL,
  120884. 0
  120885. };
  120886. static long _huff_lengthlist_line_2048x27_class2[] = {
  120887. 1, 2, 3, 6, 4, 7, 5, 7,
  120888. };
  120889. static static_codebook _huff_book_line_2048x27_class2 = {
  120890. 1, 8,
  120891. _huff_lengthlist_line_2048x27_class2,
  120892. 0, 0, 0, 0, 0,
  120893. NULL,
  120894. NULL,
  120895. NULL,
  120896. NULL,
  120897. 0
  120898. };
  120899. static long _huff_lengthlist_line_2048x27_class3[] = {
  120900. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  120901. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  120902. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  120903. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  120904. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  120905. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  120906. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  120907. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  120908. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  120909. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  120910. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  120911. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  120912. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  120913. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  120914. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  120915. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  120916. };
  120917. static static_codebook _huff_book_line_2048x27_class3 = {
  120918. 1, 256,
  120919. _huff_lengthlist_line_2048x27_class3,
  120920. 0, 0, 0, 0, 0,
  120921. NULL,
  120922. NULL,
  120923. NULL,
  120924. NULL,
  120925. 0
  120926. };
  120927. static long _huff_lengthlist_line_2048x27_class4[] = {
  120928. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  120929. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  120930. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  120931. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  120932. };
  120933. static static_codebook _huff_book_line_2048x27_class4 = {
  120934. 1, 64,
  120935. _huff_lengthlist_line_2048x27_class4,
  120936. 0, 0, 0, 0, 0,
  120937. NULL,
  120938. NULL,
  120939. NULL,
  120940. NULL,
  120941. 0
  120942. };
  120943. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  120944. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120945. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  120946. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  120947. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  120948. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  120949. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  120950. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  120951. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  120952. };
  120953. static static_codebook _huff_book_line_2048x27_0sub0 = {
  120954. 1, 128,
  120955. _huff_lengthlist_line_2048x27_0sub0,
  120956. 0, 0, 0, 0, 0,
  120957. NULL,
  120958. NULL,
  120959. NULL,
  120960. NULL,
  120961. 0
  120962. };
  120963. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  120964. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  120965. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  120966. };
  120967. static static_codebook _huff_book_line_2048x27_1sub0 = {
  120968. 1, 32,
  120969. _huff_lengthlist_line_2048x27_1sub0,
  120970. 0, 0, 0, 0, 0,
  120971. NULL,
  120972. NULL,
  120973. NULL,
  120974. NULL,
  120975. 0
  120976. };
  120977. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  120978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120980. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  120981. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  120982. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  120983. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  120984. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  120985. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  120986. };
  120987. static static_codebook _huff_book_line_2048x27_1sub1 = {
  120988. 1, 128,
  120989. _huff_lengthlist_line_2048x27_1sub1,
  120990. 0, 0, 0, 0, 0,
  120991. NULL,
  120992. NULL,
  120993. NULL,
  120994. NULL,
  120995. 0
  120996. };
  120997. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  120998. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120999. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121000. };
  121001. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121002. 1, 32,
  121003. _huff_lengthlist_line_2048x27_2sub0,
  121004. 0, 0, 0, 0, 0,
  121005. NULL,
  121006. NULL,
  121007. NULL,
  121008. NULL,
  121009. 0
  121010. };
  121011. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121014. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121015. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121016. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121017. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121018. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121019. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121020. };
  121021. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121022. 1, 128,
  121023. _huff_lengthlist_line_2048x27_2sub1,
  121024. 0, 0, 0, 0, 0,
  121025. NULL,
  121026. NULL,
  121027. NULL,
  121028. NULL,
  121029. 0
  121030. };
  121031. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121032. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121033. 5, 5,
  121034. };
  121035. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121036. 1, 18,
  121037. _huff_lengthlist_line_2048x27_3sub1,
  121038. 0, 0, 0, 0, 0,
  121039. NULL,
  121040. NULL,
  121041. NULL,
  121042. NULL,
  121043. 0
  121044. };
  121045. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121047. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121048. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121049. 10,12,
  121050. };
  121051. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121052. 1, 50,
  121053. _huff_lengthlist_line_2048x27_3sub2,
  121054. 0, 0, 0, 0, 0,
  121055. NULL,
  121056. NULL,
  121057. NULL,
  121058. NULL,
  121059. 0
  121060. };
  121061. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  121062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121065. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121066. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121067. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121068. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121069. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121070. };
  121071. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121072. 1, 128,
  121073. _huff_lengthlist_line_2048x27_3sub3,
  121074. 0, 0, 0, 0, 0,
  121075. NULL,
  121076. NULL,
  121077. NULL,
  121078. NULL,
  121079. 0
  121080. };
  121081. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121082. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121083. 4, 5,
  121084. };
  121085. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121086. 1, 18,
  121087. _huff_lengthlist_line_2048x27_4sub1,
  121088. 0, 0, 0, 0, 0,
  121089. NULL,
  121090. NULL,
  121091. NULL,
  121092. NULL,
  121093. 0
  121094. };
  121095. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121097. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121098. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121099. 10,10,
  121100. };
  121101. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121102. 1, 50,
  121103. _huff_lengthlist_line_2048x27_4sub2,
  121104. 0, 0, 0, 0, 0,
  121105. NULL,
  121106. NULL,
  121107. NULL,
  121108. NULL,
  121109. 0
  121110. };
  121111. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  121112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121115. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121116. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121117. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121118. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121119. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121120. };
  121121. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121122. 1, 128,
  121123. _huff_lengthlist_line_2048x27_4sub3,
  121124. 0, 0, 0, 0, 0,
  121125. NULL,
  121126. NULL,
  121127. NULL,
  121128. NULL,
  121129. 0
  121130. };
  121131. static long _huff_lengthlist_line_256x4low_class0[] = {
  121132. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  121133. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  121134. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  121135. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  121136. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  121137. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  121138. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  121139. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  121140. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  121141. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  121142. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  121143. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  121144. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  121145. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  121146. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  121147. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  121148. };
  121149. static static_codebook _huff_book_line_256x4low_class0 = {
  121150. 1, 256,
  121151. _huff_lengthlist_line_256x4low_class0,
  121152. 0, 0, 0, 0, 0,
  121153. NULL,
  121154. NULL,
  121155. NULL,
  121156. NULL,
  121157. 0
  121158. };
  121159. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  121160. 1, 3, 2, 3,
  121161. };
  121162. static static_codebook _huff_book_line_256x4low_0sub0 = {
  121163. 1, 4,
  121164. _huff_lengthlist_line_256x4low_0sub0,
  121165. 0, 0, 0, 0, 0,
  121166. NULL,
  121167. NULL,
  121168. NULL,
  121169. NULL,
  121170. 0
  121171. };
  121172. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  121173. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  121174. };
  121175. static static_codebook _huff_book_line_256x4low_0sub1 = {
  121176. 1, 10,
  121177. _huff_lengthlist_line_256x4low_0sub1,
  121178. 0, 0, 0, 0, 0,
  121179. NULL,
  121180. NULL,
  121181. NULL,
  121182. NULL,
  121183. 0
  121184. };
  121185. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  121186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  121187. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  121188. };
  121189. static static_codebook _huff_book_line_256x4low_0sub2 = {
  121190. 1, 25,
  121191. _huff_lengthlist_line_256x4low_0sub2,
  121192. 0, 0, 0, 0, 0,
  121193. NULL,
  121194. NULL,
  121195. NULL,
  121196. NULL,
  121197. 0
  121198. };
  121199. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  121200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  121202. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  121203. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  121204. };
  121205. static static_codebook _huff_book_line_256x4low_0sub3 = {
  121206. 1, 64,
  121207. _huff_lengthlist_line_256x4low_0sub3,
  121208. 0, 0, 0, 0, 0,
  121209. NULL,
  121210. NULL,
  121211. NULL,
  121212. NULL,
  121213. 0
  121214. };
  121215. /*** End of inlined file: floor_books.h ***/
  121216. static static_codebook *_floor_128x4_books[]={
  121217. &_huff_book_line_128x4_class0,
  121218. &_huff_book_line_128x4_0sub0,
  121219. &_huff_book_line_128x4_0sub1,
  121220. &_huff_book_line_128x4_0sub2,
  121221. &_huff_book_line_128x4_0sub3,
  121222. };
  121223. static static_codebook *_floor_256x4_books[]={
  121224. &_huff_book_line_256x4_class0,
  121225. &_huff_book_line_256x4_0sub0,
  121226. &_huff_book_line_256x4_0sub1,
  121227. &_huff_book_line_256x4_0sub2,
  121228. &_huff_book_line_256x4_0sub3,
  121229. };
  121230. static static_codebook *_floor_128x7_books[]={
  121231. &_huff_book_line_128x7_class0,
  121232. &_huff_book_line_128x7_class1,
  121233. &_huff_book_line_128x7_0sub1,
  121234. &_huff_book_line_128x7_0sub2,
  121235. &_huff_book_line_128x7_0sub3,
  121236. &_huff_book_line_128x7_1sub1,
  121237. &_huff_book_line_128x7_1sub2,
  121238. &_huff_book_line_128x7_1sub3,
  121239. };
  121240. static static_codebook *_floor_256x7_books[]={
  121241. &_huff_book_line_256x7_class0,
  121242. &_huff_book_line_256x7_class1,
  121243. &_huff_book_line_256x7_0sub1,
  121244. &_huff_book_line_256x7_0sub2,
  121245. &_huff_book_line_256x7_0sub3,
  121246. &_huff_book_line_256x7_1sub1,
  121247. &_huff_book_line_256x7_1sub2,
  121248. &_huff_book_line_256x7_1sub3,
  121249. };
  121250. static static_codebook *_floor_128x11_books[]={
  121251. &_huff_book_line_128x11_class1,
  121252. &_huff_book_line_128x11_class2,
  121253. &_huff_book_line_128x11_class3,
  121254. &_huff_book_line_128x11_0sub0,
  121255. &_huff_book_line_128x11_1sub0,
  121256. &_huff_book_line_128x11_1sub1,
  121257. &_huff_book_line_128x11_2sub1,
  121258. &_huff_book_line_128x11_2sub2,
  121259. &_huff_book_line_128x11_2sub3,
  121260. &_huff_book_line_128x11_3sub1,
  121261. &_huff_book_line_128x11_3sub2,
  121262. &_huff_book_line_128x11_3sub3,
  121263. };
  121264. static static_codebook *_floor_128x17_books[]={
  121265. &_huff_book_line_128x17_class1,
  121266. &_huff_book_line_128x17_class2,
  121267. &_huff_book_line_128x17_class3,
  121268. &_huff_book_line_128x17_0sub0,
  121269. &_huff_book_line_128x17_1sub0,
  121270. &_huff_book_line_128x17_1sub1,
  121271. &_huff_book_line_128x17_2sub1,
  121272. &_huff_book_line_128x17_2sub2,
  121273. &_huff_book_line_128x17_2sub3,
  121274. &_huff_book_line_128x17_3sub1,
  121275. &_huff_book_line_128x17_3sub2,
  121276. &_huff_book_line_128x17_3sub3,
  121277. };
  121278. static static_codebook *_floor_256x4low_books[]={
  121279. &_huff_book_line_256x4low_class0,
  121280. &_huff_book_line_256x4low_0sub0,
  121281. &_huff_book_line_256x4low_0sub1,
  121282. &_huff_book_line_256x4low_0sub2,
  121283. &_huff_book_line_256x4low_0sub3,
  121284. };
  121285. static static_codebook *_floor_1024x27_books[]={
  121286. &_huff_book_line_1024x27_class1,
  121287. &_huff_book_line_1024x27_class2,
  121288. &_huff_book_line_1024x27_class3,
  121289. &_huff_book_line_1024x27_class4,
  121290. &_huff_book_line_1024x27_0sub0,
  121291. &_huff_book_line_1024x27_1sub0,
  121292. &_huff_book_line_1024x27_1sub1,
  121293. &_huff_book_line_1024x27_2sub0,
  121294. &_huff_book_line_1024x27_2sub1,
  121295. &_huff_book_line_1024x27_3sub1,
  121296. &_huff_book_line_1024x27_3sub2,
  121297. &_huff_book_line_1024x27_3sub3,
  121298. &_huff_book_line_1024x27_4sub1,
  121299. &_huff_book_line_1024x27_4sub2,
  121300. &_huff_book_line_1024x27_4sub3,
  121301. };
  121302. static static_codebook *_floor_2048x27_books[]={
  121303. &_huff_book_line_2048x27_class1,
  121304. &_huff_book_line_2048x27_class2,
  121305. &_huff_book_line_2048x27_class3,
  121306. &_huff_book_line_2048x27_class4,
  121307. &_huff_book_line_2048x27_0sub0,
  121308. &_huff_book_line_2048x27_1sub0,
  121309. &_huff_book_line_2048x27_1sub1,
  121310. &_huff_book_line_2048x27_2sub0,
  121311. &_huff_book_line_2048x27_2sub1,
  121312. &_huff_book_line_2048x27_3sub1,
  121313. &_huff_book_line_2048x27_3sub2,
  121314. &_huff_book_line_2048x27_3sub3,
  121315. &_huff_book_line_2048x27_4sub1,
  121316. &_huff_book_line_2048x27_4sub2,
  121317. &_huff_book_line_2048x27_4sub3,
  121318. };
  121319. static static_codebook *_floor_512x17_books[]={
  121320. &_huff_book_line_512x17_class1,
  121321. &_huff_book_line_512x17_class2,
  121322. &_huff_book_line_512x17_class3,
  121323. &_huff_book_line_512x17_0sub0,
  121324. &_huff_book_line_512x17_1sub0,
  121325. &_huff_book_line_512x17_1sub1,
  121326. &_huff_book_line_512x17_2sub1,
  121327. &_huff_book_line_512x17_2sub2,
  121328. &_huff_book_line_512x17_2sub3,
  121329. &_huff_book_line_512x17_3sub1,
  121330. &_huff_book_line_512x17_3sub2,
  121331. &_huff_book_line_512x17_3sub3,
  121332. };
  121333. static static_codebook **_floor_books[10]={
  121334. _floor_128x4_books,
  121335. _floor_256x4_books,
  121336. _floor_128x7_books,
  121337. _floor_256x7_books,
  121338. _floor_128x11_books,
  121339. _floor_128x17_books,
  121340. _floor_256x4low_books,
  121341. _floor_1024x27_books,
  121342. _floor_2048x27_books,
  121343. _floor_512x17_books,
  121344. };
  121345. static vorbis_info_floor1 _floor[10]={
  121346. /* 128 x 4 */
  121347. {
  121348. 1,{0},{4},{2},{0},
  121349. {{1,2,3,4}},
  121350. 4,{0,128, 33,8,16,70},
  121351. 60,30,500, 1.,18., -1
  121352. },
  121353. /* 256 x 4 */
  121354. {
  121355. 1,{0},{4},{2},{0},
  121356. {{1,2,3,4}},
  121357. 4,{0,256, 66,16,32,140},
  121358. 60,30,500, 1.,18., -1
  121359. },
  121360. /* 128 x 7 */
  121361. {
  121362. 2,{0,1},{3,4},{2,2},{0,1},
  121363. {{-1,2,3,4},{-1,5,6,7}},
  121364. 4,{0,128, 14,4,58, 2,8,28,90},
  121365. 60,30,500, 1.,18., -1
  121366. },
  121367. /* 256 x 7 */
  121368. {
  121369. 2,{0,1},{3,4},{2,2},{0,1},
  121370. {{-1,2,3,4},{-1,5,6,7}},
  121371. 4,{0,256, 28,8,116, 4,16,56,180},
  121372. 60,30,500, 1.,18., -1
  121373. },
  121374. /* 128 x 11 */
  121375. {
  121376. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121377. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121378. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  121379. 60,30,500, 1,18., -1
  121380. },
  121381. /* 128 x 17 */
  121382. {
  121383. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121384. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121385. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  121386. 60,30,500, 1,18., -1
  121387. },
  121388. /* 256 x 4 (low bitrate version) */
  121389. {
  121390. 1,{0},{4},{2},{0},
  121391. {{1,2,3,4}},
  121392. 4,{0,256, 66,16,32,140},
  121393. 60,30,500, 1.,18., -1
  121394. },
  121395. /* 1024 x 27 */
  121396. {
  121397. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  121398. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  121399. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  121400. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  121401. 60,30,500, 3,18., -1 /* lowpass */
  121402. },
  121403. /* 2048 x 27 */
  121404. {
  121405. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  121406. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  121407. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  121408. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  121409. 60,30,500, 3,18., -1 /* lowpass */
  121410. },
  121411. /* 512 x 17 */
  121412. {
  121413. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121414. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121415. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  121416. 7,23,39, 55,79,110, 156,232,360},
  121417. 60,30,500, 1,18., -1 /* lowpass! */
  121418. },
  121419. };
  121420. /*** End of inlined file: floor_all.h ***/
  121421. /*** Start of inlined file: residue_44.h ***/
  121422. /*** Start of inlined file: res_books_stereo.h ***/
  121423. static long _vq_quantlist__16c0_s_p1_0[] = {
  121424. 1,
  121425. 0,
  121426. 2,
  121427. };
  121428. static long _vq_lengthlist__16c0_s_p1_0[] = {
  121429. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121430. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121434. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  121435. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121439. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121440. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  121475. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  121476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  121480. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  121481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  121485. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  121486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121520. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  121521. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121525. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  121526. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  121527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121530. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  121531. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  121532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121839. 0,
  121840. };
  121841. static float _vq_quantthresh__16c0_s_p1_0[] = {
  121842. -0.5, 0.5,
  121843. };
  121844. static long _vq_quantmap__16c0_s_p1_0[] = {
  121845. 1, 0, 2,
  121846. };
  121847. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  121848. _vq_quantthresh__16c0_s_p1_0,
  121849. _vq_quantmap__16c0_s_p1_0,
  121850. 3,
  121851. 3
  121852. };
  121853. static static_codebook _16c0_s_p1_0 = {
  121854. 8, 6561,
  121855. _vq_lengthlist__16c0_s_p1_0,
  121856. 1, -535822336, 1611661312, 2, 0,
  121857. _vq_quantlist__16c0_s_p1_0,
  121858. NULL,
  121859. &_vq_auxt__16c0_s_p1_0,
  121860. NULL,
  121861. 0
  121862. };
  121863. static long _vq_quantlist__16c0_s_p2_0[] = {
  121864. 2,
  121865. 1,
  121866. 3,
  121867. 0,
  121868. 4,
  121869. };
  121870. static long _vq_lengthlist__16c0_s_p2_0[] = {
  121871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121910. 0,
  121911. };
  121912. static float _vq_quantthresh__16c0_s_p2_0[] = {
  121913. -1.5, -0.5, 0.5, 1.5,
  121914. };
  121915. static long _vq_quantmap__16c0_s_p2_0[] = {
  121916. 3, 1, 0, 2, 4,
  121917. };
  121918. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  121919. _vq_quantthresh__16c0_s_p2_0,
  121920. _vq_quantmap__16c0_s_p2_0,
  121921. 5,
  121922. 5
  121923. };
  121924. static static_codebook _16c0_s_p2_0 = {
  121925. 4, 625,
  121926. _vq_lengthlist__16c0_s_p2_0,
  121927. 1, -533725184, 1611661312, 3, 0,
  121928. _vq_quantlist__16c0_s_p2_0,
  121929. NULL,
  121930. &_vq_auxt__16c0_s_p2_0,
  121931. NULL,
  121932. 0
  121933. };
  121934. static long _vq_quantlist__16c0_s_p3_0[] = {
  121935. 2,
  121936. 1,
  121937. 3,
  121938. 0,
  121939. 4,
  121940. };
  121941. static long _vq_lengthlist__16c0_s_p3_0[] = {
  121942. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  121944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121945. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  121947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121948. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  121949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121981. 0,
  121982. };
  121983. static float _vq_quantthresh__16c0_s_p3_0[] = {
  121984. -1.5, -0.5, 0.5, 1.5,
  121985. };
  121986. static long _vq_quantmap__16c0_s_p3_0[] = {
  121987. 3, 1, 0, 2, 4,
  121988. };
  121989. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  121990. _vq_quantthresh__16c0_s_p3_0,
  121991. _vq_quantmap__16c0_s_p3_0,
  121992. 5,
  121993. 5
  121994. };
  121995. static static_codebook _16c0_s_p3_0 = {
  121996. 4, 625,
  121997. _vq_lengthlist__16c0_s_p3_0,
  121998. 1, -533725184, 1611661312, 3, 0,
  121999. _vq_quantlist__16c0_s_p3_0,
  122000. NULL,
  122001. &_vq_auxt__16c0_s_p3_0,
  122002. NULL,
  122003. 0
  122004. };
  122005. static long _vq_quantlist__16c0_s_p4_0[] = {
  122006. 4,
  122007. 3,
  122008. 5,
  122009. 2,
  122010. 6,
  122011. 1,
  122012. 7,
  122013. 0,
  122014. 8,
  122015. };
  122016. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122017. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122018. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122019. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122020. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122021. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122022. 0,
  122023. };
  122024. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122025. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122026. };
  122027. static long _vq_quantmap__16c0_s_p4_0[] = {
  122028. 7, 5, 3, 1, 0, 2, 4, 6,
  122029. 8,
  122030. };
  122031. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122032. _vq_quantthresh__16c0_s_p4_0,
  122033. _vq_quantmap__16c0_s_p4_0,
  122034. 9,
  122035. 9
  122036. };
  122037. static static_codebook _16c0_s_p4_0 = {
  122038. 2, 81,
  122039. _vq_lengthlist__16c0_s_p4_0,
  122040. 1, -531628032, 1611661312, 4, 0,
  122041. _vq_quantlist__16c0_s_p4_0,
  122042. NULL,
  122043. &_vq_auxt__16c0_s_p4_0,
  122044. NULL,
  122045. 0
  122046. };
  122047. static long _vq_quantlist__16c0_s_p5_0[] = {
  122048. 4,
  122049. 3,
  122050. 5,
  122051. 2,
  122052. 6,
  122053. 1,
  122054. 7,
  122055. 0,
  122056. 8,
  122057. };
  122058. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122059. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122060. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122061. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122062. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122063. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122064. 10,
  122065. };
  122066. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122067. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122068. };
  122069. static long _vq_quantmap__16c0_s_p5_0[] = {
  122070. 7, 5, 3, 1, 0, 2, 4, 6,
  122071. 8,
  122072. };
  122073. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122074. _vq_quantthresh__16c0_s_p5_0,
  122075. _vq_quantmap__16c0_s_p5_0,
  122076. 9,
  122077. 9
  122078. };
  122079. static static_codebook _16c0_s_p5_0 = {
  122080. 2, 81,
  122081. _vq_lengthlist__16c0_s_p5_0,
  122082. 1, -531628032, 1611661312, 4, 0,
  122083. _vq_quantlist__16c0_s_p5_0,
  122084. NULL,
  122085. &_vq_auxt__16c0_s_p5_0,
  122086. NULL,
  122087. 0
  122088. };
  122089. static long _vq_quantlist__16c0_s_p6_0[] = {
  122090. 8,
  122091. 7,
  122092. 9,
  122093. 6,
  122094. 10,
  122095. 5,
  122096. 11,
  122097. 4,
  122098. 12,
  122099. 3,
  122100. 13,
  122101. 2,
  122102. 14,
  122103. 1,
  122104. 15,
  122105. 0,
  122106. 16,
  122107. };
  122108. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122109. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122110. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122111. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122112. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122113. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122114. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122115. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122116. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122117. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122118. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122119. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122120. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122121. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122122. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122123. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122124. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  122125. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  122126. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  122127. 14,
  122128. };
  122129. static float _vq_quantthresh__16c0_s_p6_0[] = {
  122130. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122131. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122132. };
  122133. static long _vq_quantmap__16c0_s_p6_0[] = {
  122134. 15, 13, 11, 9, 7, 5, 3, 1,
  122135. 0, 2, 4, 6, 8, 10, 12, 14,
  122136. 16,
  122137. };
  122138. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  122139. _vq_quantthresh__16c0_s_p6_0,
  122140. _vq_quantmap__16c0_s_p6_0,
  122141. 17,
  122142. 17
  122143. };
  122144. static static_codebook _16c0_s_p6_0 = {
  122145. 2, 289,
  122146. _vq_lengthlist__16c0_s_p6_0,
  122147. 1, -529530880, 1611661312, 5, 0,
  122148. _vq_quantlist__16c0_s_p6_0,
  122149. NULL,
  122150. &_vq_auxt__16c0_s_p6_0,
  122151. NULL,
  122152. 0
  122153. };
  122154. static long _vq_quantlist__16c0_s_p7_0[] = {
  122155. 1,
  122156. 0,
  122157. 2,
  122158. };
  122159. static long _vq_lengthlist__16c0_s_p7_0[] = {
  122160. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  122161. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  122162. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  122163. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  122164. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  122165. 13,
  122166. };
  122167. static float _vq_quantthresh__16c0_s_p7_0[] = {
  122168. -5.5, 5.5,
  122169. };
  122170. static long _vq_quantmap__16c0_s_p7_0[] = {
  122171. 1, 0, 2,
  122172. };
  122173. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  122174. _vq_quantthresh__16c0_s_p7_0,
  122175. _vq_quantmap__16c0_s_p7_0,
  122176. 3,
  122177. 3
  122178. };
  122179. static static_codebook _16c0_s_p7_0 = {
  122180. 4, 81,
  122181. _vq_lengthlist__16c0_s_p7_0,
  122182. 1, -529137664, 1618345984, 2, 0,
  122183. _vq_quantlist__16c0_s_p7_0,
  122184. NULL,
  122185. &_vq_auxt__16c0_s_p7_0,
  122186. NULL,
  122187. 0
  122188. };
  122189. static long _vq_quantlist__16c0_s_p7_1[] = {
  122190. 5,
  122191. 4,
  122192. 6,
  122193. 3,
  122194. 7,
  122195. 2,
  122196. 8,
  122197. 1,
  122198. 9,
  122199. 0,
  122200. 10,
  122201. };
  122202. static long _vq_lengthlist__16c0_s_p7_1[] = {
  122203. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  122204. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  122205. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  122206. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  122207. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  122208. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  122209. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  122210. 11,11,11, 9, 9, 9, 9,10,10,
  122211. };
  122212. static float _vq_quantthresh__16c0_s_p7_1[] = {
  122213. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122214. 3.5, 4.5,
  122215. };
  122216. static long _vq_quantmap__16c0_s_p7_1[] = {
  122217. 9, 7, 5, 3, 1, 0, 2, 4,
  122218. 6, 8, 10,
  122219. };
  122220. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  122221. _vq_quantthresh__16c0_s_p7_1,
  122222. _vq_quantmap__16c0_s_p7_1,
  122223. 11,
  122224. 11
  122225. };
  122226. static static_codebook _16c0_s_p7_1 = {
  122227. 2, 121,
  122228. _vq_lengthlist__16c0_s_p7_1,
  122229. 1, -531365888, 1611661312, 4, 0,
  122230. _vq_quantlist__16c0_s_p7_1,
  122231. NULL,
  122232. &_vq_auxt__16c0_s_p7_1,
  122233. NULL,
  122234. 0
  122235. };
  122236. static long _vq_quantlist__16c0_s_p8_0[] = {
  122237. 6,
  122238. 5,
  122239. 7,
  122240. 4,
  122241. 8,
  122242. 3,
  122243. 9,
  122244. 2,
  122245. 10,
  122246. 1,
  122247. 11,
  122248. 0,
  122249. 12,
  122250. };
  122251. static long _vq_lengthlist__16c0_s_p8_0[] = {
  122252. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  122253. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  122254. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  122255. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  122256. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  122257. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  122258. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  122259. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  122260. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  122261. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  122262. 0,12,13,13,12,13,14,14,14,
  122263. };
  122264. static float _vq_quantthresh__16c0_s_p8_0[] = {
  122265. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122266. 12.5, 17.5, 22.5, 27.5,
  122267. };
  122268. static long _vq_quantmap__16c0_s_p8_0[] = {
  122269. 11, 9, 7, 5, 3, 1, 0, 2,
  122270. 4, 6, 8, 10, 12,
  122271. };
  122272. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  122273. _vq_quantthresh__16c0_s_p8_0,
  122274. _vq_quantmap__16c0_s_p8_0,
  122275. 13,
  122276. 13
  122277. };
  122278. static static_codebook _16c0_s_p8_0 = {
  122279. 2, 169,
  122280. _vq_lengthlist__16c0_s_p8_0,
  122281. 1, -526516224, 1616117760, 4, 0,
  122282. _vq_quantlist__16c0_s_p8_0,
  122283. NULL,
  122284. &_vq_auxt__16c0_s_p8_0,
  122285. NULL,
  122286. 0
  122287. };
  122288. static long _vq_quantlist__16c0_s_p8_1[] = {
  122289. 2,
  122290. 1,
  122291. 3,
  122292. 0,
  122293. 4,
  122294. };
  122295. static long _vq_lengthlist__16c0_s_p8_1[] = {
  122296. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  122297. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122298. };
  122299. static float _vq_quantthresh__16c0_s_p8_1[] = {
  122300. -1.5, -0.5, 0.5, 1.5,
  122301. };
  122302. static long _vq_quantmap__16c0_s_p8_1[] = {
  122303. 3, 1, 0, 2, 4,
  122304. };
  122305. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  122306. _vq_quantthresh__16c0_s_p8_1,
  122307. _vq_quantmap__16c0_s_p8_1,
  122308. 5,
  122309. 5
  122310. };
  122311. static static_codebook _16c0_s_p8_1 = {
  122312. 2, 25,
  122313. _vq_lengthlist__16c0_s_p8_1,
  122314. 1, -533725184, 1611661312, 3, 0,
  122315. _vq_quantlist__16c0_s_p8_1,
  122316. NULL,
  122317. &_vq_auxt__16c0_s_p8_1,
  122318. NULL,
  122319. 0
  122320. };
  122321. static long _vq_quantlist__16c0_s_p9_0[] = {
  122322. 1,
  122323. 0,
  122324. 2,
  122325. };
  122326. static long _vq_lengthlist__16c0_s_p9_0[] = {
  122327. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122328. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122329. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122330. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122331. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122332. 7,
  122333. };
  122334. static float _vq_quantthresh__16c0_s_p9_0[] = {
  122335. -157.5, 157.5,
  122336. };
  122337. static long _vq_quantmap__16c0_s_p9_0[] = {
  122338. 1, 0, 2,
  122339. };
  122340. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  122341. _vq_quantthresh__16c0_s_p9_0,
  122342. _vq_quantmap__16c0_s_p9_0,
  122343. 3,
  122344. 3
  122345. };
  122346. static static_codebook _16c0_s_p9_0 = {
  122347. 4, 81,
  122348. _vq_lengthlist__16c0_s_p9_0,
  122349. 1, -518803456, 1628680192, 2, 0,
  122350. _vq_quantlist__16c0_s_p9_0,
  122351. NULL,
  122352. &_vq_auxt__16c0_s_p9_0,
  122353. NULL,
  122354. 0
  122355. };
  122356. static long _vq_quantlist__16c0_s_p9_1[] = {
  122357. 7,
  122358. 6,
  122359. 8,
  122360. 5,
  122361. 9,
  122362. 4,
  122363. 10,
  122364. 3,
  122365. 11,
  122366. 2,
  122367. 12,
  122368. 1,
  122369. 13,
  122370. 0,
  122371. 14,
  122372. };
  122373. static long _vq_lengthlist__16c0_s_p9_1[] = {
  122374. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  122375. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  122376. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  122377. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  122378. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122379. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122380. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122381. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122382. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122383. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122384. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122385. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122386. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122387. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122388. 10,
  122389. };
  122390. static float _vq_quantthresh__16c0_s_p9_1[] = {
  122391. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122392. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122393. };
  122394. static long _vq_quantmap__16c0_s_p9_1[] = {
  122395. 13, 11, 9, 7, 5, 3, 1, 0,
  122396. 2, 4, 6, 8, 10, 12, 14,
  122397. };
  122398. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  122399. _vq_quantthresh__16c0_s_p9_1,
  122400. _vq_quantmap__16c0_s_p9_1,
  122401. 15,
  122402. 15
  122403. };
  122404. static static_codebook _16c0_s_p9_1 = {
  122405. 2, 225,
  122406. _vq_lengthlist__16c0_s_p9_1,
  122407. 1, -520986624, 1620377600, 4, 0,
  122408. _vq_quantlist__16c0_s_p9_1,
  122409. NULL,
  122410. &_vq_auxt__16c0_s_p9_1,
  122411. NULL,
  122412. 0
  122413. };
  122414. static long _vq_quantlist__16c0_s_p9_2[] = {
  122415. 10,
  122416. 9,
  122417. 11,
  122418. 8,
  122419. 12,
  122420. 7,
  122421. 13,
  122422. 6,
  122423. 14,
  122424. 5,
  122425. 15,
  122426. 4,
  122427. 16,
  122428. 3,
  122429. 17,
  122430. 2,
  122431. 18,
  122432. 1,
  122433. 19,
  122434. 0,
  122435. 20,
  122436. };
  122437. static long _vq_lengthlist__16c0_s_p9_2[] = {
  122438. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  122439. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  122440. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  122441. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  122442. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  122443. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  122444. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  122445. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  122446. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  122447. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  122448. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  122449. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  122450. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  122451. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  122452. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  122453. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  122454. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  122455. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  122456. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  122457. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  122458. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  122459. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  122460. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  122461. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  122462. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  122463. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  122464. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  122465. 10,11,10,10,11, 9,10,10,10,
  122466. };
  122467. static float _vq_quantthresh__16c0_s_p9_2[] = {
  122468. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122469. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122470. 6.5, 7.5, 8.5, 9.5,
  122471. };
  122472. static long _vq_quantmap__16c0_s_p9_2[] = {
  122473. 19, 17, 15, 13, 11, 9, 7, 5,
  122474. 3, 1, 0, 2, 4, 6, 8, 10,
  122475. 12, 14, 16, 18, 20,
  122476. };
  122477. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  122478. _vq_quantthresh__16c0_s_p9_2,
  122479. _vq_quantmap__16c0_s_p9_2,
  122480. 21,
  122481. 21
  122482. };
  122483. static static_codebook _16c0_s_p9_2 = {
  122484. 2, 441,
  122485. _vq_lengthlist__16c0_s_p9_2,
  122486. 1, -529268736, 1611661312, 5, 0,
  122487. _vq_quantlist__16c0_s_p9_2,
  122488. NULL,
  122489. &_vq_auxt__16c0_s_p9_2,
  122490. NULL,
  122491. 0
  122492. };
  122493. static long _huff_lengthlist__16c0_s_single[] = {
  122494. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  122495. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  122496. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  122497. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  122498. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  122499. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  122500. 16,16,18,18,
  122501. };
  122502. static static_codebook _huff_book__16c0_s_single = {
  122503. 2, 100,
  122504. _huff_lengthlist__16c0_s_single,
  122505. 0, 0, 0, 0, 0,
  122506. NULL,
  122507. NULL,
  122508. NULL,
  122509. NULL,
  122510. 0
  122511. };
  122512. static long _huff_lengthlist__16c1_s_long[] = {
  122513. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  122514. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  122515. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  122516. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  122517. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  122518. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  122519. 12,11,11,13,
  122520. };
  122521. static static_codebook _huff_book__16c1_s_long = {
  122522. 2, 100,
  122523. _huff_lengthlist__16c1_s_long,
  122524. 0, 0, 0, 0, 0,
  122525. NULL,
  122526. NULL,
  122527. NULL,
  122528. NULL,
  122529. 0
  122530. };
  122531. static long _vq_quantlist__16c1_s_p1_0[] = {
  122532. 1,
  122533. 0,
  122534. 2,
  122535. };
  122536. static long _vq_lengthlist__16c1_s_p1_0[] = {
  122537. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122538. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122543. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  122548. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  122583. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122588. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122593. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122629. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  122634. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  122639. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0,
  122948. };
  122949. static float _vq_quantthresh__16c1_s_p1_0[] = {
  122950. -0.5, 0.5,
  122951. };
  122952. static long _vq_quantmap__16c1_s_p1_0[] = {
  122953. 1, 0, 2,
  122954. };
  122955. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  122956. _vq_quantthresh__16c1_s_p1_0,
  122957. _vq_quantmap__16c1_s_p1_0,
  122958. 3,
  122959. 3
  122960. };
  122961. static static_codebook _16c1_s_p1_0 = {
  122962. 8, 6561,
  122963. _vq_lengthlist__16c1_s_p1_0,
  122964. 1, -535822336, 1611661312, 2, 0,
  122965. _vq_quantlist__16c1_s_p1_0,
  122966. NULL,
  122967. &_vq_auxt__16c1_s_p1_0,
  122968. NULL,
  122969. 0
  122970. };
  122971. static long _vq_quantlist__16c1_s_p2_0[] = {
  122972. 2,
  122973. 1,
  122974. 3,
  122975. 0,
  122976. 4,
  122977. };
  122978. static long _vq_lengthlist__16c1_s_p2_0[] = {
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0,
  123019. };
  123020. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123021. -1.5, -0.5, 0.5, 1.5,
  123022. };
  123023. static long _vq_quantmap__16c1_s_p2_0[] = {
  123024. 3, 1, 0, 2, 4,
  123025. };
  123026. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123027. _vq_quantthresh__16c1_s_p2_0,
  123028. _vq_quantmap__16c1_s_p2_0,
  123029. 5,
  123030. 5
  123031. };
  123032. static static_codebook _16c1_s_p2_0 = {
  123033. 4, 625,
  123034. _vq_lengthlist__16c1_s_p2_0,
  123035. 1, -533725184, 1611661312, 3, 0,
  123036. _vq_quantlist__16c1_s_p2_0,
  123037. NULL,
  123038. &_vq_auxt__16c1_s_p2_0,
  123039. NULL,
  123040. 0
  123041. };
  123042. static long _vq_quantlist__16c1_s_p3_0[] = {
  123043. 2,
  123044. 1,
  123045. 3,
  123046. 0,
  123047. 4,
  123048. };
  123049. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123050. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0,
  123090. };
  123091. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123092. -1.5, -0.5, 0.5, 1.5,
  123093. };
  123094. static long _vq_quantmap__16c1_s_p3_0[] = {
  123095. 3, 1, 0, 2, 4,
  123096. };
  123097. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123098. _vq_quantthresh__16c1_s_p3_0,
  123099. _vq_quantmap__16c1_s_p3_0,
  123100. 5,
  123101. 5
  123102. };
  123103. static static_codebook _16c1_s_p3_0 = {
  123104. 4, 625,
  123105. _vq_lengthlist__16c1_s_p3_0,
  123106. 1, -533725184, 1611661312, 3, 0,
  123107. _vq_quantlist__16c1_s_p3_0,
  123108. NULL,
  123109. &_vq_auxt__16c1_s_p3_0,
  123110. NULL,
  123111. 0
  123112. };
  123113. static long _vq_quantlist__16c1_s_p4_0[] = {
  123114. 4,
  123115. 3,
  123116. 5,
  123117. 2,
  123118. 6,
  123119. 1,
  123120. 7,
  123121. 0,
  123122. 8,
  123123. };
  123124. static long _vq_lengthlist__16c1_s_p4_0[] = {
  123125. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123126. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123127. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123128. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  123129. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0,
  123131. };
  123132. static float _vq_quantthresh__16c1_s_p4_0[] = {
  123133. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123134. };
  123135. static long _vq_quantmap__16c1_s_p4_0[] = {
  123136. 7, 5, 3, 1, 0, 2, 4, 6,
  123137. 8,
  123138. };
  123139. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  123140. _vq_quantthresh__16c1_s_p4_0,
  123141. _vq_quantmap__16c1_s_p4_0,
  123142. 9,
  123143. 9
  123144. };
  123145. static static_codebook _16c1_s_p4_0 = {
  123146. 2, 81,
  123147. _vq_lengthlist__16c1_s_p4_0,
  123148. 1, -531628032, 1611661312, 4, 0,
  123149. _vq_quantlist__16c1_s_p4_0,
  123150. NULL,
  123151. &_vq_auxt__16c1_s_p4_0,
  123152. NULL,
  123153. 0
  123154. };
  123155. static long _vq_quantlist__16c1_s_p5_0[] = {
  123156. 4,
  123157. 3,
  123158. 5,
  123159. 2,
  123160. 6,
  123161. 1,
  123162. 7,
  123163. 0,
  123164. 8,
  123165. };
  123166. static long _vq_lengthlist__16c1_s_p5_0[] = {
  123167. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123168. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  123169. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123170. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123171. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123172. 10,
  123173. };
  123174. static float _vq_quantthresh__16c1_s_p5_0[] = {
  123175. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123176. };
  123177. static long _vq_quantmap__16c1_s_p5_0[] = {
  123178. 7, 5, 3, 1, 0, 2, 4, 6,
  123179. 8,
  123180. };
  123181. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  123182. _vq_quantthresh__16c1_s_p5_0,
  123183. _vq_quantmap__16c1_s_p5_0,
  123184. 9,
  123185. 9
  123186. };
  123187. static static_codebook _16c1_s_p5_0 = {
  123188. 2, 81,
  123189. _vq_lengthlist__16c1_s_p5_0,
  123190. 1, -531628032, 1611661312, 4, 0,
  123191. _vq_quantlist__16c1_s_p5_0,
  123192. NULL,
  123193. &_vq_auxt__16c1_s_p5_0,
  123194. NULL,
  123195. 0
  123196. };
  123197. static long _vq_quantlist__16c1_s_p6_0[] = {
  123198. 8,
  123199. 7,
  123200. 9,
  123201. 6,
  123202. 10,
  123203. 5,
  123204. 11,
  123205. 4,
  123206. 12,
  123207. 3,
  123208. 13,
  123209. 2,
  123210. 14,
  123211. 1,
  123212. 15,
  123213. 0,
  123214. 16,
  123215. };
  123216. static long _vq_lengthlist__16c1_s_p6_0[] = {
  123217. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  123218. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123219. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123220. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  123221. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  123222. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123223. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123224. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123225. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123226. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123227. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123228. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  123229. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  123230. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123231. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  123232. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  123233. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123235. 14,
  123236. };
  123237. static float _vq_quantthresh__16c1_s_p6_0[] = {
  123238. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123239. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123240. };
  123241. static long _vq_quantmap__16c1_s_p6_0[] = {
  123242. 15, 13, 11, 9, 7, 5, 3, 1,
  123243. 0, 2, 4, 6, 8, 10, 12, 14,
  123244. 16,
  123245. };
  123246. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  123247. _vq_quantthresh__16c1_s_p6_0,
  123248. _vq_quantmap__16c1_s_p6_0,
  123249. 17,
  123250. 17
  123251. };
  123252. static static_codebook _16c1_s_p6_0 = {
  123253. 2, 289,
  123254. _vq_lengthlist__16c1_s_p6_0,
  123255. 1, -529530880, 1611661312, 5, 0,
  123256. _vq_quantlist__16c1_s_p6_0,
  123257. NULL,
  123258. &_vq_auxt__16c1_s_p6_0,
  123259. NULL,
  123260. 0
  123261. };
  123262. static long _vq_quantlist__16c1_s_p7_0[] = {
  123263. 1,
  123264. 0,
  123265. 2,
  123266. };
  123267. static long _vq_lengthlist__16c1_s_p7_0[] = {
  123268. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  123269. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123270. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  123271. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  123272. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  123273. 11,
  123274. };
  123275. static float _vq_quantthresh__16c1_s_p7_0[] = {
  123276. -5.5, 5.5,
  123277. };
  123278. static long _vq_quantmap__16c1_s_p7_0[] = {
  123279. 1, 0, 2,
  123280. };
  123281. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  123282. _vq_quantthresh__16c1_s_p7_0,
  123283. _vq_quantmap__16c1_s_p7_0,
  123284. 3,
  123285. 3
  123286. };
  123287. static static_codebook _16c1_s_p7_0 = {
  123288. 4, 81,
  123289. _vq_lengthlist__16c1_s_p7_0,
  123290. 1, -529137664, 1618345984, 2, 0,
  123291. _vq_quantlist__16c1_s_p7_0,
  123292. NULL,
  123293. &_vq_auxt__16c1_s_p7_0,
  123294. NULL,
  123295. 0
  123296. };
  123297. static long _vq_quantlist__16c1_s_p7_1[] = {
  123298. 5,
  123299. 4,
  123300. 6,
  123301. 3,
  123302. 7,
  123303. 2,
  123304. 8,
  123305. 1,
  123306. 9,
  123307. 0,
  123308. 10,
  123309. };
  123310. static long _vq_lengthlist__16c1_s_p7_1[] = {
  123311. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  123312. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  123313. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123314. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  123315. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  123316. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  123317. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  123318. 10,10,10, 8, 8, 8, 8, 9, 9,
  123319. };
  123320. static float _vq_quantthresh__16c1_s_p7_1[] = {
  123321. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123322. 3.5, 4.5,
  123323. };
  123324. static long _vq_quantmap__16c1_s_p7_1[] = {
  123325. 9, 7, 5, 3, 1, 0, 2, 4,
  123326. 6, 8, 10,
  123327. };
  123328. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  123329. _vq_quantthresh__16c1_s_p7_1,
  123330. _vq_quantmap__16c1_s_p7_1,
  123331. 11,
  123332. 11
  123333. };
  123334. static static_codebook _16c1_s_p7_1 = {
  123335. 2, 121,
  123336. _vq_lengthlist__16c1_s_p7_1,
  123337. 1, -531365888, 1611661312, 4, 0,
  123338. _vq_quantlist__16c1_s_p7_1,
  123339. NULL,
  123340. &_vq_auxt__16c1_s_p7_1,
  123341. NULL,
  123342. 0
  123343. };
  123344. static long _vq_quantlist__16c1_s_p8_0[] = {
  123345. 6,
  123346. 5,
  123347. 7,
  123348. 4,
  123349. 8,
  123350. 3,
  123351. 9,
  123352. 2,
  123353. 10,
  123354. 1,
  123355. 11,
  123356. 0,
  123357. 12,
  123358. };
  123359. static long _vq_lengthlist__16c1_s_p8_0[] = {
  123360. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  123361. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  123362. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  123363. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  123364. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  123365. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123366. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  123367. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  123368. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  123369. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  123370. 0,12,12,12,12,13,13,14,15,
  123371. };
  123372. static float _vq_quantthresh__16c1_s_p8_0[] = {
  123373. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123374. 12.5, 17.5, 22.5, 27.5,
  123375. };
  123376. static long _vq_quantmap__16c1_s_p8_0[] = {
  123377. 11, 9, 7, 5, 3, 1, 0, 2,
  123378. 4, 6, 8, 10, 12,
  123379. };
  123380. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  123381. _vq_quantthresh__16c1_s_p8_0,
  123382. _vq_quantmap__16c1_s_p8_0,
  123383. 13,
  123384. 13
  123385. };
  123386. static static_codebook _16c1_s_p8_0 = {
  123387. 2, 169,
  123388. _vq_lengthlist__16c1_s_p8_0,
  123389. 1, -526516224, 1616117760, 4, 0,
  123390. _vq_quantlist__16c1_s_p8_0,
  123391. NULL,
  123392. &_vq_auxt__16c1_s_p8_0,
  123393. NULL,
  123394. 0
  123395. };
  123396. static long _vq_quantlist__16c1_s_p8_1[] = {
  123397. 2,
  123398. 1,
  123399. 3,
  123400. 0,
  123401. 4,
  123402. };
  123403. static long _vq_lengthlist__16c1_s_p8_1[] = {
  123404. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  123405. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  123406. };
  123407. static float _vq_quantthresh__16c1_s_p8_1[] = {
  123408. -1.5, -0.5, 0.5, 1.5,
  123409. };
  123410. static long _vq_quantmap__16c1_s_p8_1[] = {
  123411. 3, 1, 0, 2, 4,
  123412. };
  123413. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  123414. _vq_quantthresh__16c1_s_p8_1,
  123415. _vq_quantmap__16c1_s_p8_1,
  123416. 5,
  123417. 5
  123418. };
  123419. static static_codebook _16c1_s_p8_1 = {
  123420. 2, 25,
  123421. _vq_lengthlist__16c1_s_p8_1,
  123422. 1, -533725184, 1611661312, 3, 0,
  123423. _vq_quantlist__16c1_s_p8_1,
  123424. NULL,
  123425. &_vq_auxt__16c1_s_p8_1,
  123426. NULL,
  123427. 0
  123428. };
  123429. static long _vq_quantlist__16c1_s_p9_0[] = {
  123430. 6,
  123431. 5,
  123432. 7,
  123433. 4,
  123434. 8,
  123435. 3,
  123436. 9,
  123437. 2,
  123438. 10,
  123439. 1,
  123440. 11,
  123441. 0,
  123442. 12,
  123443. };
  123444. static long _vq_lengthlist__16c1_s_p9_0[] = {
  123445. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123446. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123447. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123448. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123449. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123450. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123451. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123452. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123453. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123454. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123455. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123456. };
  123457. static float _vq_quantthresh__16c1_s_p9_0[] = {
  123458. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  123459. 787.5, 1102.5, 1417.5, 1732.5,
  123460. };
  123461. static long _vq_quantmap__16c1_s_p9_0[] = {
  123462. 11, 9, 7, 5, 3, 1, 0, 2,
  123463. 4, 6, 8, 10, 12,
  123464. };
  123465. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  123466. _vq_quantthresh__16c1_s_p9_0,
  123467. _vq_quantmap__16c1_s_p9_0,
  123468. 13,
  123469. 13
  123470. };
  123471. static static_codebook _16c1_s_p9_0 = {
  123472. 2, 169,
  123473. _vq_lengthlist__16c1_s_p9_0,
  123474. 1, -513964032, 1628680192, 4, 0,
  123475. _vq_quantlist__16c1_s_p9_0,
  123476. NULL,
  123477. &_vq_auxt__16c1_s_p9_0,
  123478. NULL,
  123479. 0
  123480. };
  123481. static long _vq_quantlist__16c1_s_p9_1[] = {
  123482. 7,
  123483. 6,
  123484. 8,
  123485. 5,
  123486. 9,
  123487. 4,
  123488. 10,
  123489. 3,
  123490. 11,
  123491. 2,
  123492. 12,
  123493. 1,
  123494. 13,
  123495. 0,
  123496. 14,
  123497. };
  123498. static long _vq_lengthlist__16c1_s_p9_1[] = {
  123499. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  123500. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  123501. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  123502. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  123503. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  123504. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  123505. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  123506. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  123507. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123508. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  123509. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123510. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123511. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  123512. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123513. 13,
  123514. };
  123515. static float _vq_quantthresh__16c1_s_p9_1[] = {
  123516. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123517. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123518. };
  123519. static long _vq_quantmap__16c1_s_p9_1[] = {
  123520. 13, 11, 9, 7, 5, 3, 1, 0,
  123521. 2, 4, 6, 8, 10, 12, 14,
  123522. };
  123523. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  123524. _vq_quantthresh__16c1_s_p9_1,
  123525. _vq_quantmap__16c1_s_p9_1,
  123526. 15,
  123527. 15
  123528. };
  123529. static static_codebook _16c1_s_p9_1 = {
  123530. 2, 225,
  123531. _vq_lengthlist__16c1_s_p9_1,
  123532. 1, -520986624, 1620377600, 4, 0,
  123533. _vq_quantlist__16c1_s_p9_1,
  123534. NULL,
  123535. &_vq_auxt__16c1_s_p9_1,
  123536. NULL,
  123537. 0
  123538. };
  123539. static long _vq_quantlist__16c1_s_p9_2[] = {
  123540. 10,
  123541. 9,
  123542. 11,
  123543. 8,
  123544. 12,
  123545. 7,
  123546. 13,
  123547. 6,
  123548. 14,
  123549. 5,
  123550. 15,
  123551. 4,
  123552. 16,
  123553. 3,
  123554. 17,
  123555. 2,
  123556. 18,
  123557. 1,
  123558. 19,
  123559. 0,
  123560. 20,
  123561. };
  123562. static long _vq_lengthlist__16c1_s_p9_2[] = {
  123563. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  123564. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  123565. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  123566. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  123567. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  123568. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  123569. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  123570. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  123571. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  123572. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  123573. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  123574. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  123575. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  123576. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  123577. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  123578. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  123579. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  123580. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  123581. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  123582. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  123583. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  123584. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  123585. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  123586. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  123587. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  123588. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  123589. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  123590. 11,11,11,11,12,11,11,12,11,
  123591. };
  123592. static float _vq_quantthresh__16c1_s_p9_2[] = {
  123593. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123594. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123595. 6.5, 7.5, 8.5, 9.5,
  123596. };
  123597. static long _vq_quantmap__16c1_s_p9_2[] = {
  123598. 19, 17, 15, 13, 11, 9, 7, 5,
  123599. 3, 1, 0, 2, 4, 6, 8, 10,
  123600. 12, 14, 16, 18, 20,
  123601. };
  123602. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  123603. _vq_quantthresh__16c1_s_p9_2,
  123604. _vq_quantmap__16c1_s_p9_2,
  123605. 21,
  123606. 21
  123607. };
  123608. static static_codebook _16c1_s_p9_2 = {
  123609. 2, 441,
  123610. _vq_lengthlist__16c1_s_p9_2,
  123611. 1, -529268736, 1611661312, 5, 0,
  123612. _vq_quantlist__16c1_s_p9_2,
  123613. NULL,
  123614. &_vq_auxt__16c1_s_p9_2,
  123615. NULL,
  123616. 0
  123617. };
  123618. static long _huff_lengthlist__16c1_s_short[] = {
  123619. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  123620. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  123621. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  123622. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  123623. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  123624. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  123625. 9, 9,10,13,
  123626. };
  123627. static static_codebook _huff_book__16c1_s_short = {
  123628. 2, 100,
  123629. _huff_lengthlist__16c1_s_short,
  123630. 0, 0, 0, 0, 0,
  123631. NULL,
  123632. NULL,
  123633. NULL,
  123634. NULL,
  123635. 0
  123636. };
  123637. static long _huff_lengthlist__16c2_s_long[] = {
  123638. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  123639. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  123640. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  123641. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  123642. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  123643. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  123644. 14,14,16,18,
  123645. };
  123646. static static_codebook _huff_book__16c2_s_long = {
  123647. 2, 100,
  123648. _huff_lengthlist__16c2_s_long,
  123649. 0, 0, 0, 0, 0,
  123650. NULL,
  123651. NULL,
  123652. NULL,
  123653. NULL,
  123654. 0
  123655. };
  123656. static long _vq_quantlist__16c2_s_p1_0[] = {
  123657. 1,
  123658. 0,
  123659. 2,
  123660. };
  123661. static long _vq_lengthlist__16c2_s_p1_0[] = {
  123662. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  123663. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0,
  123668. };
  123669. static float _vq_quantthresh__16c2_s_p1_0[] = {
  123670. -0.5, 0.5,
  123671. };
  123672. static long _vq_quantmap__16c2_s_p1_0[] = {
  123673. 1, 0, 2,
  123674. };
  123675. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  123676. _vq_quantthresh__16c2_s_p1_0,
  123677. _vq_quantmap__16c2_s_p1_0,
  123678. 3,
  123679. 3
  123680. };
  123681. static static_codebook _16c2_s_p1_0 = {
  123682. 4, 81,
  123683. _vq_lengthlist__16c2_s_p1_0,
  123684. 1, -535822336, 1611661312, 2, 0,
  123685. _vq_quantlist__16c2_s_p1_0,
  123686. NULL,
  123687. &_vq_auxt__16c2_s_p1_0,
  123688. NULL,
  123689. 0
  123690. };
  123691. static long _vq_quantlist__16c2_s_p2_0[] = {
  123692. 2,
  123693. 1,
  123694. 3,
  123695. 0,
  123696. 4,
  123697. };
  123698. static long _vq_lengthlist__16c2_s_p2_0[] = {
  123699. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  123700. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  123701. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  123702. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  123703. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  123704. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  123705. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  123706. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  123712. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  123713. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  123714. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  123720. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  123721. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  123722. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  123728. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  123729. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  123730. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  123735. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  123736. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  123737. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  123738. 13,
  123739. };
  123740. static float _vq_quantthresh__16c2_s_p2_0[] = {
  123741. -1.5, -0.5, 0.5, 1.5,
  123742. };
  123743. static long _vq_quantmap__16c2_s_p2_0[] = {
  123744. 3, 1, 0, 2, 4,
  123745. };
  123746. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  123747. _vq_quantthresh__16c2_s_p2_0,
  123748. _vq_quantmap__16c2_s_p2_0,
  123749. 5,
  123750. 5
  123751. };
  123752. static static_codebook _16c2_s_p2_0 = {
  123753. 4, 625,
  123754. _vq_lengthlist__16c2_s_p2_0,
  123755. 1, -533725184, 1611661312, 3, 0,
  123756. _vq_quantlist__16c2_s_p2_0,
  123757. NULL,
  123758. &_vq_auxt__16c2_s_p2_0,
  123759. NULL,
  123760. 0
  123761. };
  123762. static long _vq_quantlist__16c2_s_p3_0[] = {
  123763. 4,
  123764. 3,
  123765. 5,
  123766. 2,
  123767. 6,
  123768. 1,
  123769. 7,
  123770. 0,
  123771. 8,
  123772. };
  123773. static long _vq_lengthlist__16c2_s_p3_0[] = {
  123774. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  123775. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  123776. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  123777. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0,
  123780. };
  123781. static float _vq_quantthresh__16c2_s_p3_0[] = {
  123782. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123783. };
  123784. static long _vq_quantmap__16c2_s_p3_0[] = {
  123785. 7, 5, 3, 1, 0, 2, 4, 6,
  123786. 8,
  123787. };
  123788. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  123789. _vq_quantthresh__16c2_s_p3_0,
  123790. _vq_quantmap__16c2_s_p3_0,
  123791. 9,
  123792. 9
  123793. };
  123794. static static_codebook _16c2_s_p3_0 = {
  123795. 2, 81,
  123796. _vq_lengthlist__16c2_s_p3_0,
  123797. 1, -531628032, 1611661312, 4, 0,
  123798. _vq_quantlist__16c2_s_p3_0,
  123799. NULL,
  123800. &_vq_auxt__16c2_s_p3_0,
  123801. NULL,
  123802. 0
  123803. };
  123804. static long _vq_quantlist__16c2_s_p4_0[] = {
  123805. 8,
  123806. 7,
  123807. 9,
  123808. 6,
  123809. 10,
  123810. 5,
  123811. 11,
  123812. 4,
  123813. 12,
  123814. 3,
  123815. 13,
  123816. 2,
  123817. 14,
  123818. 1,
  123819. 15,
  123820. 0,
  123821. 16,
  123822. };
  123823. static long _vq_lengthlist__16c2_s_p4_0[] = {
  123824. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  123825. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  123826. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  123827. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  123828. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  123829. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  123830. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  123831. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  123832. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  123833. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0,
  123843. };
  123844. static float _vq_quantthresh__16c2_s_p4_0[] = {
  123845. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123846. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123847. };
  123848. static long _vq_quantmap__16c2_s_p4_0[] = {
  123849. 15, 13, 11, 9, 7, 5, 3, 1,
  123850. 0, 2, 4, 6, 8, 10, 12, 14,
  123851. 16,
  123852. };
  123853. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  123854. _vq_quantthresh__16c2_s_p4_0,
  123855. _vq_quantmap__16c2_s_p4_0,
  123856. 17,
  123857. 17
  123858. };
  123859. static static_codebook _16c2_s_p4_0 = {
  123860. 2, 289,
  123861. _vq_lengthlist__16c2_s_p4_0,
  123862. 1, -529530880, 1611661312, 5, 0,
  123863. _vq_quantlist__16c2_s_p4_0,
  123864. NULL,
  123865. &_vq_auxt__16c2_s_p4_0,
  123866. NULL,
  123867. 0
  123868. };
  123869. static long _vq_quantlist__16c2_s_p5_0[] = {
  123870. 1,
  123871. 0,
  123872. 2,
  123873. };
  123874. static long _vq_lengthlist__16c2_s_p5_0[] = {
  123875. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  123876. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  123877. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  123878. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  123879. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  123880. 12,
  123881. };
  123882. static float _vq_quantthresh__16c2_s_p5_0[] = {
  123883. -5.5, 5.5,
  123884. };
  123885. static long _vq_quantmap__16c2_s_p5_0[] = {
  123886. 1, 0, 2,
  123887. };
  123888. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  123889. _vq_quantthresh__16c2_s_p5_0,
  123890. _vq_quantmap__16c2_s_p5_0,
  123891. 3,
  123892. 3
  123893. };
  123894. static static_codebook _16c2_s_p5_0 = {
  123895. 4, 81,
  123896. _vq_lengthlist__16c2_s_p5_0,
  123897. 1, -529137664, 1618345984, 2, 0,
  123898. _vq_quantlist__16c2_s_p5_0,
  123899. NULL,
  123900. &_vq_auxt__16c2_s_p5_0,
  123901. NULL,
  123902. 0
  123903. };
  123904. static long _vq_quantlist__16c2_s_p5_1[] = {
  123905. 5,
  123906. 4,
  123907. 6,
  123908. 3,
  123909. 7,
  123910. 2,
  123911. 8,
  123912. 1,
  123913. 9,
  123914. 0,
  123915. 10,
  123916. };
  123917. static long _vq_lengthlist__16c2_s_p5_1[] = {
  123918. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  123919. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  123920. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  123921. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  123922. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  123923. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  123924. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  123925. 11,11,11, 7, 7, 8, 8, 8, 8,
  123926. };
  123927. static float _vq_quantthresh__16c2_s_p5_1[] = {
  123928. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123929. 3.5, 4.5,
  123930. };
  123931. static long _vq_quantmap__16c2_s_p5_1[] = {
  123932. 9, 7, 5, 3, 1, 0, 2, 4,
  123933. 6, 8, 10,
  123934. };
  123935. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  123936. _vq_quantthresh__16c2_s_p5_1,
  123937. _vq_quantmap__16c2_s_p5_1,
  123938. 11,
  123939. 11
  123940. };
  123941. static static_codebook _16c2_s_p5_1 = {
  123942. 2, 121,
  123943. _vq_lengthlist__16c2_s_p5_1,
  123944. 1, -531365888, 1611661312, 4, 0,
  123945. _vq_quantlist__16c2_s_p5_1,
  123946. NULL,
  123947. &_vq_auxt__16c2_s_p5_1,
  123948. NULL,
  123949. 0
  123950. };
  123951. static long _vq_quantlist__16c2_s_p6_0[] = {
  123952. 6,
  123953. 5,
  123954. 7,
  123955. 4,
  123956. 8,
  123957. 3,
  123958. 9,
  123959. 2,
  123960. 10,
  123961. 1,
  123962. 11,
  123963. 0,
  123964. 12,
  123965. };
  123966. static long _vq_lengthlist__16c2_s_p6_0[] = {
  123967. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  123968. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  123969. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  123970. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  123971. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  123972. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. };
  123979. static float _vq_quantthresh__16c2_s_p6_0[] = {
  123980. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123981. 12.5, 17.5, 22.5, 27.5,
  123982. };
  123983. static long _vq_quantmap__16c2_s_p6_0[] = {
  123984. 11, 9, 7, 5, 3, 1, 0, 2,
  123985. 4, 6, 8, 10, 12,
  123986. };
  123987. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  123988. _vq_quantthresh__16c2_s_p6_0,
  123989. _vq_quantmap__16c2_s_p6_0,
  123990. 13,
  123991. 13
  123992. };
  123993. static static_codebook _16c2_s_p6_0 = {
  123994. 2, 169,
  123995. _vq_lengthlist__16c2_s_p6_0,
  123996. 1, -526516224, 1616117760, 4, 0,
  123997. _vq_quantlist__16c2_s_p6_0,
  123998. NULL,
  123999. &_vq_auxt__16c2_s_p6_0,
  124000. NULL,
  124001. 0
  124002. };
  124003. static long _vq_quantlist__16c2_s_p6_1[] = {
  124004. 2,
  124005. 1,
  124006. 3,
  124007. 0,
  124008. 4,
  124009. };
  124010. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124011. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124012. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124013. };
  124014. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124015. -1.5, -0.5, 0.5, 1.5,
  124016. };
  124017. static long _vq_quantmap__16c2_s_p6_1[] = {
  124018. 3, 1, 0, 2, 4,
  124019. };
  124020. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124021. _vq_quantthresh__16c2_s_p6_1,
  124022. _vq_quantmap__16c2_s_p6_1,
  124023. 5,
  124024. 5
  124025. };
  124026. static static_codebook _16c2_s_p6_1 = {
  124027. 2, 25,
  124028. _vq_lengthlist__16c2_s_p6_1,
  124029. 1, -533725184, 1611661312, 3, 0,
  124030. _vq_quantlist__16c2_s_p6_1,
  124031. NULL,
  124032. &_vq_auxt__16c2_s_p6_1,
  124033. NULL,
  124034. 0
  124035. };
  124036. static long _vq_quantlist__16c2_s_p7_0[] = {
  124037. 6,
  124038. 5,
  124039. 7,
  124040. 4,
  124041. 8,
  124042. 3,
  124043. 9,
  124044. 2,
  124045. 10,
  124046. 1,
  124047. 11,
  124048. 0,
  124049. 12,
  124050. };
  124051. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124052. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124053. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124054. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124055. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124056. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124057. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124058. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124059. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124060. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124061. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124062. 18,13,14,13,13,14,13,15,14,
  124063. };
  124064. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124065. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124066. 27.5, 38.5, 49.5, 60.5,
  124067. };
  124068. static long _vq_quantmap__16c2_s_p7_0[] = {
  124069. 11, 9, 7, 5, 3, 1, 0, 2,
  124070. 4, 6, 8, 10, 12,
  124071. };
  124072. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124073. _vq_quantthresh__16c2_s_p7_0,
  124074. _vq_quantmap__16c2_s_p7_0,
  124075. 13,
  124076. 13
  124077. };
  124078. static static_codebook _16c2_s_p7_0 = {
  124079. 2, 169,
  124080. _vq_lengthlist__16c2_s_p7_0,
  124081. 1, -523206656, 1618345984, 4, 0,
  124082. _vq_quantlist__16c2_s_p7_0,
  124083. NULL,
  124084. &_vq_auxt__16c2_s_p7_0,
  124085. NULL,
  124086. 0
  124087. };
  124088. static long _vq_quantlist__16c2_s_p7_1[] = {
  124089. 5,
  124090. 4,
  124091. 6,
  124092. 3,
  124093. 7,
  124094. 2,
  124095. 8,
  124096. 1,
  124097. 9,
  124098. 0,
  124099. 10,
  124100. };
  124101. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124102. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124103. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124104. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124105. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124106. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124107. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124108. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124109. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124110. };
  124111. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124112. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124113. 3.5, 4.5,
  124114. };
  124115. static long _vq_quantmap__16c2_s_p7_1[] = {
  124116. 9, 7, 5, 3, 1, 0, 2, 4,
  124117. 6, 8, 10,
  124118. };
  124119. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124120. _vq_quantthresh__16c2_s_p7_1,
  124121. _vq_quantmap__16c2_s_p7_1,
  124122. 11,
  124123. 11
  124124. };
  124125. static static_codebook _16c2_s_p7_1 = {
  124126. 2, 121,
  124127. _vq_lengthlist__16c2_s_p7_1,
  124128. 1, -531365888, 1611661312, 4, 0,
  124129. _vq_quantlist__16c2_s_p7_1,
  124130. NULL,
  124131. &_vq_auxt__16c2_s_p7_1,
  124132. NULL,
  124133. 0
  124134. };
  124135. static long _vq_quantlist__16c2_s_p8_0[] = {
  124136. 7,
  124137. 6,
  124138. 8,
  124139. 5,
  124140. 9,
  124141. 4,
  124142. 10,
  124143. 3,
  124144. 11,
  124145. 2,
  124146. 12,
  124147. 1,
  124148. 13,
  124149. 0,
  124150. 14,
  124151. };
  124152. static long _vq_lengthlist__16c2_s_p8_0[] = {
  124153. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  124154. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  124155. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  124156. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  124157. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  124158. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  124159. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  124160. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  124161. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  124162. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  124163. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  124164. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  124165. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  124166. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  124167. 13,
  124168. };
  124169. static float _vq_quantthresh__16c2_s_p8_0[] = {
  124170. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124171. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124172. };
  124173. static long _vq_quantmap__16c2_s_p8_0[] = {
  124174. 13, 11, 9, 7, 5, 3, 1, 0,
  124175. 2, 4, 6, 8, 10, 12, 14,
  124176. };
  124177. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  124178. _vq_quantthresh__16c2_s_p8_0,
  124179. _vq_quantmap__16c2_s_p8_0,
  124180. 15,
  124181. 15
  124182. };
  124183. static static_codebook _16c2_s_p8_0 = {
  124184. 2, 225,
  124185. _vq_lengthlist__16c2_s_p8_0,
  124186. 1, -520986624, 1620377600, 4, 0,
  124187. _vq_quantlist__16c2_s_p8_0,
  124188. NULL,
  124189. &_vq_auxt__16c2_s_p8_0,
  124190. NULL,
  124191. 0
  124192. };
  124193. static long _vq_quantlist__16c2_s_p8_1[] = {
  124194. 10,
  124195. 9,
  124196. 11,
  124197. 8,
  124198. 12,
  124199. 7,
  124200. 13,
  124201. 6,
  124202. 14,
  124203. 5,
  124204. 15,
  124205. 4,
  124206. 16,
  124207. 3,
  124208. 17,
  124209. 2,
  124210. 18,
  124211. 1,
  124212. 19,
  124213. 0,
  124214. 20,
  124215. };
  124216. static long _vq_lengthlist__16c2_s_p8_1[] = {
  124217. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  124218. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  124219. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  124220. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  124221. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  124222. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  124223. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  124224. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  124225. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  124226. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  124227. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  124228. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  124229. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  124230. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  124231. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  124232. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  124233. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  124234. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  124235. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  124236. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  124237. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  124238. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  124239. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  124240. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  124241. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  124242. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  124243. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  124244. 10,11,10,10,10,10,10,10,10,
  124245. };
  124246. static float _vq_quantthresh__16c2_s_p8_1[] = {
  124247. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124248. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124249. 6.5, 7.5, 8.5, 9.5,
  124250. };
  124251. static long _vq_quantmap__16c2_s_p8_1[] = {
  124252. 19, 17, 15, 13, 11, 9, 7, 5,
  124253. 3, 1, 0, 2, 4, 6, 8, 10,
  124254. 12, 14, 16, 18, 20,
  124255. };
  124256. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  124257. _vq_quantthresh__16c2_s_p8_1,
  124258. _vq_quantmap__16c2_s_p8_1,
  124259. 21,
  124260. 21
  124261. };
  124262. static static_codebook _16c2_s_p8_1 = {
  124263. 2, 441,
  124264. _vq_lengthlist__16c2_s_p8_1,
  124265. 1, -529268736, 1611661312, 5, 0,
  124266. _vq_quantlist__16c2_s_p8_1,
  124267. NULL,
  124268. &_vq_auxt__16c2_s_p8_1,
  124269. NULL,
  124270. 0
  124271. };
  124272. static long _vq_quantlist__16c2_s_p9_0[] = {
  124273. 6,
  124274. 5,
  124275. 7,
  124276. 4,
  124277. 8,
  124278. 3,
  124279. 9,
  124280. 2,
  124281. 10,
  124282. 1,
  124283. 11,
  124284. 0,
  124285. 12,
  124286. };
  124287. static long _vq_lengthlist__16c2_s_p9_0[] = {
  124288. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124289. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124290. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124291. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124292. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124293. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124294. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124295. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124296. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124297. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124298. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124299. };
  124300. static float _vq_quantthresh__16c2_s_p9_0[] = {
  124301. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  124302. 2327.5, 3258.5, 4189.5, 5120.5,
  124303. };
  124304. static long _vq_quantmap__16c2_s_p9_0[] = {
  124305. 11, 9, 7, 5, 3, 1, 0, 2,
  124306. 4, 6, 8, 10, 12,
  124307. };
  124308. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  124309. _vq_quantthresh__16c2_s_p9_0,
  124310. _vq_quantmap__16c2_s_p9_0,
  124311. 13,
  124312. 13
  124313. };
  124314. static static_codebook _16c2_s_p9_0 = {
  124315. 2, 169,
  124316. _vq_lengthlist__16c2_s_p9_0,
  124317. 1, -510275072, 1631393792, 4, 0,
  124318. _vq_quantlist__16c2_s_p9_0,
  124319. NULL,
  124320. &_vq_auxt__16c2_s_p9_0,
  124321. NULL,
  124322. 0
  124323. };
  124324. static long _vq_quantlist__16c2_s_p9_1[] = {
  124325. 8,
  124326. 7,
  124327. 9,
  124328. 6,
  124329. 10,
  124330. 5,
  124331. 11,
  124332. 4,
  124333. 12,
  124334. 3,
  124335. 13,
  124336. 2,
  124337. 14,
  124338. 1,
  124339. 15,
  124340. 0,
  124341. 16,
  124342. };
  124343. static long _vq_lengthlist__16c2_s_p9_1[] = {
  124344. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  124345. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  124346. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  124347. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  124348. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  124349. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  124350. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  124351. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  124352. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  124353. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  124354. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124355. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124356. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124357. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124358. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124359. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  124360. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  124361. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124362. 10,
  124363. };
  124364. static float _vq_quantthresh__16c2_s_p9_1[] = {
  124365. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  124366. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  124367. };
  124368. static long _vq_quantmap__16c2_s_p9_1[] = {
  124369. 15, 13, 11, 9, 7, 5, 3, 1,
  124370. 0, 2, 4, 6, 8, 10, 12, 14,
  124371. 16,
  124372. };
  124373. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  124374. _vq_quantthresh__16c2_s_p9_1,
  124375. _vq_quantmap__16c2_s_p9_1,
  124376. 17,
  124377. 17
  124378. };
  124379. static static_codebook _16c2_s_p9_1 = {
  124380. 2, 289,
  124381. _vq_lengthlist__16c2_s_p9_1,
  124382. 1, -518488064, 1622704128, 5, 0,
  124383. _vq_quantlist__16c2_s_p9_1,
  124384. NULL,
  124385. &_vq_auxt__16c2_s_p9_1,
  124386. NULL,
  124387. 0
  124388. };
  124389. static long _vq_quantlist__16c2_s_p9_2[] = {
  124390. 13,
  124391. 12,
  124392. 14,
  124393. 11,
  124394. 15,
  124395. 10,
  124396. 16,
  124397. 9,
  124398. 17,
  124399. 8,
  124400. 18,
  124401. 7,
  124402. 19,
  124403. 6,
  124404. 20,
  124405. 5,
  124406. 21,
  124407. 4,
  124408. 22,
  124409. 3,
  124410. 23,
  124411. 2,
  124412. 24,
  124413. 1,
  124414. 25,
  124415. 0,
  124416. 26,
  124417. };
  124418. static long _vq_lengthlist__16c2_s_p9_2[] = {
  124419. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  124420. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  124421. };
  124422. static float _vq_quantthresh__16c2_s_p9_2[] = {
  124423. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  124424. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124425. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  124426. 11.5, 12.5,
  124427. };
  124428. static long _vq_quantmap__16c2_s_p9_2[] = {
  124429. 25, 23, 21, 19, 17, 15, 13, 11,
  124430. 9, 7, 5, 3, 1, 0, 2, 4,
  124431. 6, 8, 10, 12, 14, 16, 18, 20,
  124432. 22, 24, 26,
  124433. };
  124434. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  124435. _vq_quantthresh__16c2_s_p9_2,
  124436. _vq_quantmap__16c2_s_p9_2,
  124437. 27,
  124438. 27
  124439. };
  124440. static static_codebook _16c2_s_p9_2 = {
  124441. 1, 27,
  124442. _vq_lengthlist__16c2_s_p9_2,
  124443. 1, -528875520, 1611661312, 5, 0,
  124444. _vq_quantlist__16c2_s_p9_2,
  124445. NULL,
  124446. &_vq_auxt__16c2_s_p9_2,
  124447. NULL,
  124448. 0
  124449. };
  124450. static long _huff_lengthlist__16c2_s_short[] = {
  124451. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  124452. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  124453. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  124454. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  124455. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  124456. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  124457. 15,12,14,14,
  124458. };
  124459. static static_codebook _huff_book__16c2_s_short = {
  124460. 2, 100,
  124461. _huff_lengthlist__16c2_s_short,
  124462. 0, 0, 0, 0, 0,
  124463. NULL,
  124464. NULL,
  124465. NULL,
  124466. NULL,
  124467. 0
  124468. };
  124469. static long _vq_quantlist__8c0_s_p1_0[] = {
  124470. 1,
  124471. 0,
  124472. 2,
  124473. };
  124474. static long _vq_lengthlist__8c0_s_p1_0[] = {
  124475. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124476. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124480. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  124481. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124485. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124486. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  124521. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  124522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  124526. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  124527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  124531. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  124532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124566. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  124567. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124571. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  124572. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  124573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124576. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  124577. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  124578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0,
  124886. };
  124887. static float _vq_quantthresh__8c0_s_p1_0[] = {
  124888. -0.5, 0.5,
  124889. };
  124890. static long _vq_quantmap__8c0_s_p1_0[] = {
  124891. 1, 0, 2,
  124892. };
  124893. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  124894. _vq_quantthresh__8c0_s_p1_0,
  124895. _vq_quantmap__8c0_s_p1_0,
  124896. 3,
  124897. 3
  124898. };
  124899. static static_codebook _8c0_s_p1_0 = {
  124900. 8, 6561,
  124901. _vq_lengthlist__8c0_s_p1_0,
  124902. 1, -535822336, 1611661312, 2, 0,
  124903. _vq_quantlist__8c0_s_p1_0,
  124904. NULL,
  124905. &_vq_auxt__8c0_s_p1_0,
  124906. NULL,
  124907. 0
  124908. };
  124909. static long _vq_quantlist__8c0_s_p2_0[] = {
  124910. 2,
  124911. 1,
  124912. 3,
  124913. 0,
  124914. 4,
  124915. };
  124916. static long _vq_lengthlist__8c0_s_p2_0[] = {
  124917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0,
  124957. };
  124958. static float _vq_quantthresh__8c0_s_p2_0[] = {
  124959. -1.5, -0.5, 0.5, 1.5,
  124960. };
  124961. static long _vq_quantmap__8c0_s_p2_0[] = {
  124962. 3, 1, 0, 2, 4,
  124963. };
  124964. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  124965. _vq_quantthresh__8c0_s_p2_0,
  124966. _vq_quantmap__8c0_s_p2_0,
  124967. 5,
  124968. 5
  124969. };
  124970. static static_codebook _8c0_s_p2_0 = {
  124971. 4, 625,
  124972. _vq_lengthlist__8c0_s_p2_0,
  124973. 1, -533725184, 1611661312, 3, 0,
  124974. _vq_quantlist__8c0_s_p2_0,
  124975. NULL,
  124976. &_vq_auxt__8c0_s_p2_0,
  124977. NULL,
  124978. 0
  124979. };
  124980. static long _vq_quantlist__8c0_s_p3_0[] = {
  124981. 2,
  124982. 1,
  124983. 3,
  124984. 0,
  124985. 4,
  124986. };
  124987. static long _vq_lengthlist__8c0_s_p3_0[] = {
  124988. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  124990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124991. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  124993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124994. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  124995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125027. 0,
  125028. };
  125029. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125030. -1.5, -0.5, 0.5, 1.5,
  125031. };
  125032. static long _vq_quantmap__8c0_s_p3_0[] = {
  125033. 3, 1, 0, 2, 4,
  125034. };
  125035. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125036. _vq_quantthresh__8c0_s_p3_0,
  125037. _vq_quantmap__8c0_s_p3_0,
  125038. 5,
  125039. 5
  125040. };
  125041. static static_codebook _8c0_s_p3_0 = {
  125042. 4, 625,
  125043. _vq_lengthlist__8c0_s_p3_0,
  125044. 1, -533725184, 1611661312, 3, 0,
  125045. _vq_quantlist__8c0_s_p3_0,
  125046. NULL,
  125047. &_vq_auxt__8c0_s_p3_0,
  125048. NULL,
  125049. 0
  125050. };
  125051. static long _vq_quantlist__8c0_s_p4_0[] = {
  125052. 4,
  125053. 3,
  125054. 5,
  125055. 2,
  125056. 6,
  125057. 1,
  125058. 7,
  125059. 0,
  125060. 8,
  125061. };
  125062. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125063. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125064. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125065. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125066. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125067. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125068. 0,
  125069. };
  125070. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125071. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125072. };
  125073. static long _vq_quantmap__8c0_s_p4_0[] = {
  125074. 7, 5, 3, 1, 0, 2, 4, 6,
  125075. 8,
  125076. };
  125077. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125078. _vq_quantthresh__8c0_s_p4_0,
  125079. _vq_quantmap__8c0_s_p4_0,
  125080. 9,
  125081. 9
  125082. };
  125083. static static_codebook _8c0_s_p4_0 = {
  125084. 2, 81,
  125085. _vq_lengthlist__8c0_s_p4_0,
  125086. 1, -531628032, 1611661312, 4, 0,
  125087. _vq_quantlist__8c0_s_p4_0,
  125088. NULL,
  125089. &_vq_auxt__8c0_s_p4_0,
  125090. NULL,
  125091. 0
  125092. };
  125093. static long _vq_quantlist__8c0_s_p5_0[] = {
  125094. 4,
  125095. 3,
  125096. 5,
  125097. 2,
  125098. 6,
  125099. 1,
  125100. 7,
  125101. 0,
  125102. 8,
  125103. };
  125104. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125105. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125106. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125107. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125108. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125109. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125110. 10,
  125111. };
  125112. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125113. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125114. };
  125115. static long _vq_quantmap__8c0_s_p5_0[] = {
  125116. 7, 5, 3, 1, 0, 2, 4, 6,
  125117. 8,
  125118. };
  125119. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125120. _vq_quantthresh__8c0_s_p5_0,
  125121. _vq_quantmap__8c0_s_p5_0,
  125122. 9,
  125123. 9
  125124. };
  125125. static static_codebook _8c0_s_p5_0 = {
  125126. 2, 81,
  125127. _vq_lengthlist__8c0_s_p5_0,
  125128. 1, -531628032, 1611661312, 4, 0,
  125129. _vq_quantlist__8c0_s_p5_0,
  125130. NULL,
  125131. &_vq_auxt__8c0_s_p5_0,
  125132. NULL,
  125133. 0
  125134. };
  125135. static long _vq_quantlist__8c0_s_p6_0[] = {
  125136. 8,
  125137. 7,
  125138. 9,
  125139. 6,
  125140. 10,
  125141. 5,
  125142. 11,
  125143. 4,
  125144. 12,
  125145. 3,
  125146. 13,
  125147. 2,
  125148. 14,
  125149. 1,
  125150. 15,
  125151. 0,
  125152. 16,
  125153. };
  125154. static long _vq_lengthlist__8c0_s_p6_0[] = {
  125155. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  125156. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125157. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125158. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  125159. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  125160. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  125161. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  125162. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  125163. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  125164. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125165. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  125166. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  125167. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  125168. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  125169. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  125170. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  125171. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  125172. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  125173. 14,
  125174. };
  125175. static float _vq_quantthresh__8c0_s_p6_0[] = {
  125176. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125177. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125178. };
  125179. static long _vq_quantmap__8c0_s_p6_0[] = {
  125180. 15, 13, 11, 9, 7, 5, 3, 1,
  125181. 0, 2, 4, 6, 8, 10, 12, 14,
  125182. 16,
  125183. };
  125184. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  125185. _vq_quantthresh__8c0_s_p6_0,
  125186. _vq_quantmap__8c0_s_p6_0,
  125187. 17,
  125188. 17
  125189. };
  125190. static static_codebook _8c0_s_p6_0 = {
  125191. 2, 289,
  125192. _vq_lengthlist__8c0_s_p6_0,
  125193. 1, -529530880, 1611661312, 5, 0,
  125194. _vq_quantlist__8c0_s_p6_0,
  125195. NULL,
  125196. &_vq_auxt__8c0_s_p6_0,
  125197. NULL,
  125198. 0
  125199. };
  125200. static long _vq_quantlist__8c0_s_p7_0[] = {
  125201. 1,
  125202. 0,
  125203. 2,
  125204. };
  125205. static long _vq_lengthlist__8c0_s_p7_0[] = {
  125206. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  125207. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  125208. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  125209. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  125210. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  125211. 10,
  125212. };
  125213. static float _vq_quantthresh__8c0_s_p7_0[] = {
  125214. -5.5, 5.5,
  125215. };
  125216. static long _vq_quantmap__8c0_s_p7_0[] = {
  125217. 1, 0, 2,
  125218. };
  125219. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  125220. _vq_quantthresh__8c0_s_p7_0,
  125221. _vq_quantmap__8c0_s_p7_0,
  125222. 3,
  125223. 3
  125224. };
  125225. static static_codebook _8c0_s_p7_0 = {
  125226. 4, 81,
  125227. _vq_lengthlist__8c0_s_p7_0,
  125228. 1, -529137664, 1618345984, 2, 0,
  125229. _vq_quantlist__8c0_s_p7_0,
  125230. NULL,
  125231. &_vq_auxt__8c0_s_p7_0,
  125232. NULL,
  125233. 0
  125234. };
  125235. static long _vq_quantlist__8c0_s_p7_1[] = {
  125236. 5,
  125237. 4,
  125238. 6,
  125239. 3,
  125240. 7,
  125241. 2,
  125242. 8,
  125243. 1,
  125244. 9,
  125245. 0,
  125246. 10,
  125247. };
  125248. static long _vq_lengthlist__8c0_s_p7_1[] = {
  125249. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  125250. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  125251. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  125252. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  125253. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  125254. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  125255. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  125256. 10,10,10, 9, 9, 9,10,10,10,
  125257. };
  125258. static float _vq_quantthresh__8c0_s_p7_1[] = {
  125259. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125260. 3.5, 4.5,
  125261. };
  125262. static long _vq_quantmap__8c0_s_p7_1[] = {
  125263. 9, 7, 5, 3, 1, 0, 2, 4,
  125264. 6, 8, 10,
  125265. };
  125266. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  125267. _vq_quantthresh__8c0_s_p7_1,
  125268. _vq_quantmap__8c0_s_p7_1,
  125269. 11,
  125270. 11
  125271. };
  125272. static static_codebook _8c0_s_p7_1 = {
  125273. 2, 121,
  125274. _vq_lengthlist__8c0_s_p7_1,
  125275. 1, -531365888, 1611661312, 4, 0,
  125276. _vq_quantlist__8c0_s_p7_1,
  125277. NULL,
  125278. &_vq_auxt__8c0_s_p7_1,
  125279. NULL,
  125280. 0
  125281. };
  125282. static long _vq_quantlist__8c0_s_p8_0[] = {
  125283. 6,
  125284. 5,
  125285. 7,
  125286. 4,
  125287. 8,
  125288. 3,
  125289. 9,
  125290. 2,
  125291. 10,
  125292. 1,
  125293. 11,
  125294. 0,
  125295. 12,
  125296. };
  125297. static long _vq_lengthlist__8c0_s_p8_0[] = {
  125298. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  125299. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  125300. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  125301. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  125302. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  125303. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  125304. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  125305. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  125306. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  125307. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  125308. 0, 0,13,13,11,13,13,11,12,
  125309. };
  125310. static float _vq_quantthresh__8c0_s_p8_0[] = {
  125311. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125312. 12.5, 17.5, 22.5, 27.5,
  125313. };
  125314. static long _vq_quantmap__8c0_s_p8_0[] = {
  125315. 11, 9, 7, 5, 3, 1, 0, 2,
  125316. 4, 6, 8, 10, 12,
  125317. };
  125318. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  125319. _vq_quantthresh__8c0_s_p8_0,
  125320. _vq_quantmap__8c0_s_p8_0,
  125321. 13,
  125322. 13
  125323. };
  125324. static static_codebook _8c0_s_p8_0 = {
  125325. 2, 169,
  125326. _vq_lengthlist__8c0_s_p8_0,
  125327. 1, -526516224, 1616117760, 4, 0,
  125328. _vq_quantlist__8c0_s_p8_0,
  125329. NULL,
  125330. &_vq_auxt__8c0_s_p8_0,
  125331. NULL,
  125332. 0
  125333. };
  125334. static long _vq_quantlist__8c0_s_p8_1[] = {
  125335. 2,
  125336. 1,
  125337. 3,
  125338. 0,
  125339. 4,
  125340. };
  125341. static long _vq_lengthlist__8c0_s_p8_1[] = {
  125342. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  125343. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  125344. };
  125345. static float _vq_quantthresh__8c0_s_p8_1[] = {
  125346. -1.5, -0.5, 0.5, 1.5,
  125347. };
  125348. static long _vq_quantmap__8c0_s_p8_1[] = {
  125349. 3, 1, 0, 2, 4,
  125350. };
  125351. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  125352. _vq_quantthresh__8c0_s_p8_1,
  125353. _vq_quantmap__8c0_s_p8_1,
  125354. 5,
  125355. 5
  125356. };
  125357. static static_codebook _8c0_s_p8_1 = {
  125358. 2, 25,
  125359. _vq_lengthlist__8c0_s_p8_1,
  125360. 1, -533725184, 1611661312, 3, 0,
  125361. _vq_quantlist__8c0_s_p8_1,
  125362. NULL,
  125363. &_vq_auxt__8c0_s_p8_1,
  125364. NULL,
  125365. 0
  125366. };
  125367. static long _vq_quantlist__8c0_s_p9_0[] = {
  125368. 1,
  125369. 0,
  125370. 2,
  125371. };
  125372. static long _vq_lengthlist__8c0_s_p9_0[] = {
  125373. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125374. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125375. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125376. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125377. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125378. 7,
  125379. };
  125380. static float _vq_quantthresh__8c0_s_p9_0[] = {
  125381. -157.5, 157.5,
  125382. };
  125383. static long _vq_quantmap__8c0_s_p9_0[] = {
  125384. 1, 0, 2,
  125385. };
  125386. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  125387. _vq_quantthresh__8c0_s_p9_0,
  125388. _vq_quantmap__8c0_s_p9_0,
  125389. 3,
  125390. 3
  125391. };
  125392. static static_codebook _8c0_s_p9_0 = {
  125393. 4, 81,
  125394. _vq_lengthlist__8c0_s_p9_0,
  125395. 1, -518803456, 1628680192, 2, 0,
  125396. _vq_quantlist__8c0_s_p9_0,
  125397. NULL,
  125398. &_vq_auxt__8c0_s_p9_0,
  125399. NULL,
  125400. 0
  125401. };
  125402. static long _vq_quantlist__8c0_s_p9_1[] = {
  125403. 7,
  125404. 6,
  125405. 8,
  125406. 5,
  125407. 9,
  125408. 4,
  125409. 10,
  125410. 3,
  125411. 11,
  125412. 2,
  125413. 12,
  125414. 1,
  125415. 13,
  125416. 0,
  125417. 14,
  125418. };
  125419. static long _vq_lengthlist__8c0_s_p9_1[] = {
  125420. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  125421. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  125422. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  125423. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  125424. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  125425. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  125426. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125427. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125428. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125429. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125430. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125431. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125432. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125433. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125434. 11,
  125435. };
  125436. static float _vq_quantthresh__8c0_s_p9_1[] = {
  125437. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125438. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125439. };
  125440. static long _vq_quantmap__8c0_s_p9_1[] = {
  125441. 13, 11, 9, 7, 5, 3, 1, 0,
  125442. 2, 4, 6, 8, 10, 12, 14,
  125443. };
  125444. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  125445. _vq_quantthresh__8c0_s_p9_1,
  125446. _vq_quantmap__8c0_s_p9_1,
  125447. 15,
  125448. 15
  125449. };
  125450. static static_codebook _8c0_s_p9_1 = {
  125451. 2, 225,
  125452. _vq_lengthlist__8c0_s_p9_1,
  125453. 1, -520986624, 1620377600, 4, 0,
  125454. _vq_quantlist__8c0_s_p9_1,
  125455. NULL,
  125456. &_vq_auxt__8c0_s_p9_1,
  125457. NULL,
  125458. 0
  125459. };
  125460. static long _vq_quantlist__8c0_s_p9_2[] = {
  125461. 10,
  125462. 9,
  125463. 11,
  125464. 8,
  125465. 12,
  125466. 7,
  125467. 13,
  125468. 6,
  125469. 14,
  125470. 5,
  125471. 15,
  125472. 4,
  125473. 16,
  125474. 3,
  125475. 17,
  125476. 2,
  125477. 18,
  125478. 1,
  125479. 19,
  125480. 0,
  125481. 20,
  125482. };
  125483. static long _vq_lengthlist__8c0_s_p9_2[] = {
  125484. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  125485. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  125486. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  125487. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  125488. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  125489. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  125490. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  125491. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  125492. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  125493. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  125494. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  125495. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  125496. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  125497. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  125498. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  125499. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  125500. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  125501. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  125502. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  125503. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  125504. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  125505. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  125506. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  125507. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  125508. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  125509. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  125510. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  125511. 10,11, 9,11,10, 9,10, 9,10,
  125512. };
  125513. static float _vq_quantthresh__8c0_s_p9_2[] = {
  125514. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125515. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125516. 6.5, 7.5, 8.5, 9.5,
  125517. };
  125518. static long _vq_quantmap__8c0_s_p9_2[] = {
  125519. 19, 17, 15, 13, 11, 9, 7, 5,
  125520. 3, 1, 0, 2, 4, 6, 8, 10,
  125521. 12, 14, 16, 18, 20,
  125522. };
  125523. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  125524. _vq_quantthresh__8c0_s_p9_2,
  125525. _vq_quantmap__8c0_s_p9_2,
  125526. 21,
  125527. 21
  125528. };
  125529. static static_codebook _8c0_s_p9_2 = {
  125530. 2, 441,
  125531. _vq_lengthlist__8c0_s_p9_2,
  125532. 1, -529268736, 1611661312, 5, 0,
  125533. _vq_quantlist__8c0_s_p9_2,
  125534. NULL,
  125535. &_vq_auxt__8c0_s_p9_2,
  125536. NULL,
  125537. 0
  125538. };
  125539. static long _huff_lengthlist__8c0_s_single[] = {
  125540. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  125541. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  125542. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  125543. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  125544. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  125545. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  125546. 17,16,17,17,
  125547. };
  125548. static static_codebook _huff_book__8c0_s_single = {
  125549. 2, 100,
  125550. _huff_lengthlist__8c0_s_single,
  125551. 0, 0, 0, 0, 0,
  125552. NULL,
  125553. NULL,
  125554. NULL,
  125555. NULL,
  125556. 0
  125557. };
  125558. static long _vq_quantlist__8c1_s_p1_0[] = {
  125559. 1,
  125560. 0,
  125561. 2,
  125562. };
  125563. static long _vq_lengthlist__8c1_s_p1_0[] = {
  125564. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125565. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125569. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125570. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125574. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  125575. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125610. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  125615. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125620. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125656. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  125661. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  125666. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0,
  125975. };
  125976. static float _vq_quantthresh__8c1_s_p1_0[] = {
  125977. -0.5, 0.5,
  125978. };
  125979. static long _vq_quantmap__8c1_s_p1_0[] = {
  125980. 1, 0, 2,
  125981. };
  125982. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  125983. _vq_quantthresh__8c1_s_p1_0,
  125984. _vq_quantmap__8c1_s_p1_0,
  125985. 3,
  125986. 3
  125987. };
  125988. static static_codebook _8c1_s_p1_0 = {
  125989. 8, 6561,
  125990. _vq_lengthlist__8c1_s_p1_0,
  125991. 1, -535822336, 1611661312, 2, 0,
  125992. _vq_quantlist__8c1_s_p1_0,
  125993. NULL,
  125994. &_vq_auxt__8c1_s_p1_0,
  125995. NULL,
  125996. 0
  125997. };
  125998. static long _vq_quantlist__8c1_s_p2_0[] = {
  125999. 2,
  126000. 1,
  126001. 3,
  126002. 0,
  126003. 4,
  126004. };
  126005. static long _vq_lengthlist__8c1_s_p2_0[] = {
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0,
  126046. };
  126047. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126048. -1.5, -0.5, 0.5, 1.5,
  126049. };
  126050. static long _vq_quantmap__8c1_s_p2_0[] = {
  126051. 3, 1, 0, 2, 4,
  126052. };
  126053. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126054. _vq_quantthresh__8c1_s_p2_0,
  126055. _vq_quantmap__8c1_s_p2_0,
  126056. 5,
  126057. 5
  126058. };
  126059. static static_codebook _8c1_s_p2_0 = {
  126060. 4, 625,
  126061. _vq_lengthlist__8c1_s_p2_0,
  126062. 1, -533725184, 1611661312, 3, 0,
  126063. _vq_quantlist__8c1_s_p2_0,
  126064. NULL,
  126065. &_vq_auxt__8c1_s_p2_0,
  126066. NULL,
  126067. 0
  126068. };
  126069. static long _vq_quantlist__8c1_s_p3_0[] = {
  126070. 2,
  126071. 1,
  126072. 3,
  126073. 0,
  126074. 4,
  126075. };
  126076. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126077. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0,
  126117. };
  126118. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126119. -1.5, -0.5, 0.5, 1.5,
  126120. };
  126121. static long _vq_quantmap__8c1_s_p3_0[] = {
  126122. 3, 1, 0, 2, 4,
  126123. };
  126124. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  126125. _vq_quantthresh__8c1_s_p3_0,
  126126. _vq_quantmap__8c1_s_p3_0,
  126127. 5,
  126128. 5
  126129. };
  126130. static static_codebook _8c1_s_p3_0 = {
  126131. 4, 625,
  126132. _vq_lengthlist__8c1_s_p3_0,
  126133. 1, -533725184, 1611661312, 3, 0,
  126134. _vq_quantlist__8c1_s_p3_0,
  126135. NULL,
  126136. &_vq_auxt__8c1_s_p3_0,
  126137. NULL,
  126138. 0
  126139. };
  126140. static long _vq_quantlist__8c1_s_p4_0[] = {
  126141. 4,
  126142. 3,
  126143. 5,
  126144. 2,
  126145. 6,
  126146. 1,
  126147. 7,
  126148. 0,
  126149. 8,
  126150. };
  126151. static long _vq_lengthlist__8c1_s_p4_0[] = {
  126152. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126153. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126154. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126155. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126156. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0,
  126158. };
  126159. static float _vq_quantthresh__8c1_s_p4_0[] = {
  126160. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126161. };
  126162. static long _vq_quantmap__8c1_s_p4_0[] = {
  126163. 7, 5, 3, 1, 0, 2, 4, 6,
  126164. 8,
  126165. };
  126166. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  126167. _vq_quantthresh__8c1_s_p4_0,
  126168. _vq_quantmap__8c1_s_p4_0,
  126169. 9,
  126170. 9
  126171. };
  126172. static static_codebook _8c1_s_p4_0 = {
  126173. 2, 81,
  126174. _vq_lengthlist__8c1_s_p4_0,
  126175. 1, -531628032, 1611661312, 4, 0,
  126176. _vq_quantlist__8c1_s_p4_0,
  126177. NULL,
  126178. &_vq_auxt__8c1_s_p4_0,
  126179. NULL,
  126180. 0
  126181. };
  126182. static long _vq_quantlist__8c1_s_p5_0[] = {
  126183. 4,
  126184. 3,
  126185. 5,
  126186. 2,
  126187. 6,
  126188. 1,
  126189. 7,
  126190. 0,
  126191. 8,
  126192. };
  126193. static long _vq_lengthlist__8c1_s_p5_0[] = {
  126194. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  126195. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  126196. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  126197. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  126198. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126199. 10,
  126200. };
  126201. static float _vq_quantthresh__8c1_s_p5_0[] = {
  126202. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126203. };
  126204. static long _vq_quantmap__8c1_s_p5_0[] = {
  126205. 7, 5, 3, 1, 0, 2, 4, 6,
  126206. 8,
  126207. };
  126208. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  126209. _vq_quantthresh__8c1_s_p5_0,
  126210. _vq_quantmap__8c1_s_p5_0,
  126211. 9,
  126212. 9
  126213. };
  126214. static static_codebook _8c1_s_p5_0 = {
  126215. 2, 81,
  126216. _vq_lengthlist__8c1_s_p5_0,
  126217. 1, -531628032, 1611661312, 4, 0,
  126218. _vq_quantlist__8c1_s_p5_0,
  126219. NULL,
  126220. &_vq_auxt__8c1_s_p5_0,
  126221. NULL,
  126222. 0
  126223. };
  126224. static long _vq_quantlist__8c1_s_p6_0[] = {
  126225. 8,
  126226. 7,
  126227. 9,
  126228. 6,
  126229. 10,
  126230. 5,
  126231. 11,
  126232. 4,
  126233. 12,
  126234. 3,
  126235. 13,
  126236. 2,
  126237. 14,
  126238. 1,
  126239. 15,
  126240. 0,
  126241. 16,
  126242. };
  126243. static long _vq_lengthlist__8c1_s_p6_0[] = {
  126244. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  126245. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126246. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126247. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  126248. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  126249. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  126250. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  126251. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  126252. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  126253. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126254. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  126255. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  126256. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  126257. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  126258. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  126259. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  126260. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  126262. 14,
  126263. };
  126264. static float _vq_quantthresh__8c1_s_p6_0[] = {
  126265. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126266. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126267. };
  126268. static long _vq_quantmap__8c1_s_p6_0[] = {
  126269. 15, 13, 11, 9, 7, 5, 3, 1,
  126270. 0, 2, 4, 6, 8, 10, 12, 14,
  126271. 16,
  126272. };
  126273. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  126274. _vq_quantthresh__8c1_s_p6_0,
  126275. _vq_quantmap__8c1_s_p6_0,
  126276. 17,
  126277. 17
  126278. };
  126279. static static_codebook _8c1_s_p6_0 = {
  126280. 2, 289,
  126281. _vq_lengthlist__8c1_s_p6_0,
  126282. 1, -529530880, 1611661312, 5, 0,
  126283. _vq_quantlist__8c1_s_p6_0,
  126284. NULL,
  126285. &_vq_auxt__8c1_s_p6_0,
  126286. NULL,
  126287. 0
  126288. };
  126289. static long _vq_quantlist__8c1_s_p7_0[] = {
  126290. 1,
  126291. 0,
  126292. 2,
  126293. };
  126294. static long _vq_lengthlist__8c1_s_p7_0[] = {
  126295. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  126296. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  126297. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  126298. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  126299. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  126300. 9,
  126301. };
  126302. static float _vq_quantthresh__8c1_s_p7_0[] = {
  126303. -5.5, 5.5,
  126304. };
  126305. static long _vq_quantmap__8c1_s_p7_0[] = {
  126306. 1, 0, 2,
  126307. };
  126308. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  126309. _vq_quantthresh__8c1_s_p7_0,
  126310. _vq_quantmap__8c1_s_p7_0,
  126311. 3,
  126312. 3
  126313. };
  126314. static static_codebook _8c1_s_p7_0 = {
  126315. 4, 81,
  126316. _vq_lengthlist__8c1_s_p7_0,
  126317. 1, -529137664, 1618345984, 2, 0,
  126318. _vq_quantlist__8c1_s_p7_0,
  126319. NULL,
  126320. &_vq_auxt__8c1_s_p7_0,
  126321. NULL,
  126322. 0
  126323. };
  126324. static long _vq_quantlist__8c1_s_p7_1[] = {
  126325. 5,
  126326. 4,
  126327. 6,
  126328. 3,
  126329. 7,
  126330. 2,
  126331. 8,
  126332. 1,
  126333. 9,
  126334. 0,
  126335. 10,
  126336. };
  126337. static long _vq_lengthlist__8c1_s_p7_1[] = {
  126338. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  126339. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  126340. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  126341. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126342. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126343. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126344. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  126345. 10,10,10, 8, 8, 8, 8, 8, 8,
  126346. };
  126347. static float _vq_quantthresh__8c1_s_p7_1[] = {
  126348. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126349. 3.5, 4.5,
  126350. };
  126351. static long _vq_quantmap__8c1_s_p7_1[] = {
  126352. 9, 7, 5, 3, 1, 0, 2, 4,
  126353. 6, 8, 10,
  126354. };
  126355. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  126356. _vq_quantthresh__8c1_s_p7_1,
  126357. _vq_quantmap__8c1_s_p7_1,
  126358. 11,
  126359. 11
  126360. };
  126361. static static_codebook _8c1_s_p7_1 = {
  126362. 2, 121,
  126363. _vq_lengthlist__8c1_s_p7_1,
  126364. 1, -531365888, 1611661312, 4, 0,
  126365. _vq_quantlist__8c1_s_p7_1,
  126366. NULL,
  126367. &_vq_auxt__8c1_s_p7_1,
  126368. NULL,
  126369. 0
  126370. };
  126371. static long _vq_quantlist__8c1_s_p8_0[] = {
  126372. 6,
  126373. 5,
  126374. 7,
  126375. 4,
  126376. 8,
  126377. 3,
  126378. 9,
  126379. 2,
  126380. 10,
  126381. 1,
  126382. 11,
  126383. 0,
  126384. 12,
  126385. };
  126386. static long _vq_lengthlist__8c1_s_p8_0[] = {
  126387. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  126388. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126389. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126390. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126391. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  126392. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  126393. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  126394. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  126395. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  126396. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  126397. 0,12,12,11,10,12,11,13,12,
  126398. };
  126399. static float _vq_quantthresh__8c1_s_p8_0[] = {
  126400. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126401. 12.5, 17.5, 22.5, 27.5,
  126402. };
  126403. static long _vq_quantmap__8c1_s_p8_0[] = {
  126404. 11, 9, 7, 5, 3, 1, 0, 2,
  126405. 4, 6, 8, 10, 12,
  126406. };
  126407. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  126408. _vq_quantthresh__8c1_s_p8_0,
  126409. _vq_quantmap__8c1_s_p8_0,
  126410. 13,
  126411. 13
  126412. };
  126413. static static_codebook _8c1_s_p8_0 = {
  126414. 2, 169,
  126415. _vq_lengthlist__8c1_s_p8_0,
  126416. 1, -526516224, 1616117760, 4, 0,
  126417. _vq_quantlist__8c1_s_p8_0,
  126418. NULL,
  126419. &_vq_auxt__8c1_s_p8_0,
  126420. NULL,
  126421. 0
  126422. };
  126423. static long _vq_quantlist__8c1_s_p8_1[] = {
  126424. 2,
  126425. 1,
  126426. 3,
  126427. 0,
  126428. 4,
  126429. };
  126430. static long _vq_lengthlist__8c1_s_p8_1[] = {
  126431. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  126432. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  126433. };
  126434. static float _vq_quantthresh__8c1_s_p8_1[] = {
  126435. -1.5, -0.5, 0.5, 1.5,
  126436. };
  126437. static long _vq_quantmap__8c1_s_p8_1[] = {
  126438. 3, 1, 0, 2, 4,
  126439. };
  126440. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  126441. _vq_quantthresh__8c1_s_p8_1,
  126442. _vq_quantmap__8c1_s_p8_1,
  126443. 5,
  126444. 5
  126445. };
  126446. static static_codebook _8c1_s_p8_1 = {
  126447. 2, 25,
  126448. _vq_lengthlist__8c1_s_p8_1,
  126449. 1, -533725184, 1611661312, 3, 0,
  126450. _vq_quantlist__8c1_s_p8_1,
  126451. NULL,
  126452. &_vq_auxt__8c1_s_p8_1,
  126453. NULL,
  126454. 0
  126455. };
  126456. static long _vq_quantlist__8c1_s_p9_0[] = {
  126457. 6,
  126458. 5,
  126459. 7,
  126460. 4,
  126461. 8,
  126462. 3,
  126463. 9,
  126464. 2,
  126465. 10,
  126466. 1,
  126467. 11,
  126468. 0,
  126469. 12,
  126470. };
  126471. static long _vq_lengthlist__8c1_s_p9_0[] = {
  126472. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  126473. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  126474. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126475. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126476. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126477. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126478. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126479. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126480. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126481. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126482. 10,10,10,10,10, 9, 9, 9, 9,
  126483. };
  126484. static float _vq_quantthresh__8c1_s_p9_0[] = {
  126485. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  126486. 787.5, 1102.5, 1417.5, 1732.5,
  126487. };
  126488. static long _vq_quantmap__8c1_s_p9_0[] = {
  126489. 11, 9, 7, 5, 3, 1, 0, 2,
  126490. 4, 6, 8, 10, 12,
  126491. };
  126492. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  126493. _vq_quantthresh__8c1_s_p9_0,
  126494. _vq_quantmap__8c1_s_p9_0,
  126495. 13,
  126496. 13
  126497. };
  126498. static static_codebook _8c1_s_p9_0 = {
  126499. 2, 169,
  126500. _vq_lengthlist__8c1_s_p9_0,
  126501. 1, -513964032, 1628680192, 4, 0,
  126502. _vq_quantlist__8c1_s_p9_0,
  126503. NULL,
  126504. &_vq_auxt__8c1_s_p9_0,
  126505. NULL,
  126506. 0
  126507. };
  126508. static long _vq_quantlist__8c1_s_p9_1[] = {
  126509. 7,
  126510. 6,
  126511. 8,
  126512. 5,
  126513. 9,
  126514. 4,
  126515. 10,
  126516. 3,
  126517. 11,
  126518. 2,
  126519. 12,
  126520. 1,
  126521. 13,
  126522. 0,
  126523. 14,
  126524. };
  126525. static long _vq_lengthlist__8c1_s_p9_1[] = {
  126526. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  126527. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  126528. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  126529. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  126530. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  126531. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  126532. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  126533. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  126534. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  126535. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  126536. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  126537. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  126538. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  126539. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  126540. 15,
  126541. };
  126542. static float _vq_quantthresh__8c1_s_p9_1[] = {
  126543. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126544. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126545. };
  126546. static long _vq_quantmap__8c1_s_p9_1[] = {
  126547. 13, 11, 9, 7, 5, 3, 1, 0,
  126548. 2, 4, 6, 8, 10, 12, 14,
  126549. };
  126550. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  126551. _vq_quantthresh__8c1_s_p9_1,
  126552. _vq_quantmap__8c1_s_p9_1,
  126553. 15,
  126554. 15
  126555. };
  126556. static static_codebook _8c1_s_p9_1 = {
  126557. 2, 225,
  126558. _vq_lengthlist__8c1_s_p9_1,
  126559. 1, -520986624, 1620377600, 4, 0,
  126560. _vq_quantlist__8c1_s_p9_1,
  126561. NULL,
  126562. &_vq_auxt__8c1_s_p9_1,
  126563. NULL,
  126564. 0
  126565. };
  126566. static long _vq_quantlist__8c1_s_p9_2[] = {
  126567. 10,
  126568. 9,
  126569. 11,
  126570. 8,
  126571. 12,
  126572. 7,
  126573. 13,
  126574. 6,
  126575. 14,
  126576. 5,
  126577. 15,
  126578. 4,
  126579. 16,
  126580. 3,
  126581. 17,
  126582. 2,
  126583. 18,
  126584. 1,
  126585. 19,
  126586. 0,
  126587. 20,
  126588. };
  126589. static long _vq_lengthlist__8c1_s_p9_2[] = {
  126590. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  126591. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  126592. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  126593. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  126594. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126595. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  126596. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  126597. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  126598. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  126599. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  126600. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  126601. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  126602. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  126603. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  126604. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  126605. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  126606. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126607. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  126608. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  126609. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  126610. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126611. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  126612. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  126613. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126614. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  126615. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  126616. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  126617. 10,10,10,10,10,10,10,10,10,
  126618. };
  126619. static float _vq_quantthresh__8c1_s_p9_2[] = {
  126620. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126621. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126622. 6.5, 7.5, 8.5, 9.5,
  126623. };
  126624. static long _vq_quantmap__8c1_s_p9_2[] = {
  126625. 19, 17, 15, 13, 11, 9, 7, 5,
  126626. 3, 1, 0, 2, 4, 6, 8, 10,
  126627. 12, 14, 16, 18, 20,
  126628. };
  126629. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  126630. _vq_quantthresh__8c1_s_p9_2,
  126631. _vq_quantmap__8c1_s_p9_2,
  126632. 21,
  126633. 21
  126634. };
  126635. static static_codebook _8c1_s_p9_2 = {
  126636. 2, 441,
  126637. _vq_lengthlist__8c1_s_p9_2,
  126638. 1, -529268736, 1611661312, 5, 0,
  126639. _vq_quantlist__8c1_s_p9_2,
  126640. NULL,
  126641. &_vq_auxt__8c1_s_p9_2,
  126642. NULL,
  126643. 0
  126644. };
  126645. static long _huff_lengthlist__8c1_s_single[] = {
  126646. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  126647. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  126648. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  126649. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  126650. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  126651. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  126652. 9, 7, 7, 8,
  126653. };
  126654. static static_codebook _huff_book__8c1_s_single = {
  126655. 2, 100,
  126656. _huff_lengthlist__8c1_s_single,
  126657. 0, 0, 0, 0, 0,
  126658. NULL,
  126659. NULL,
  126660. NULL,
  126661. NULL,
  126662. 0
  126663. };
  126664. static long _huff_lengthlist__44c2_s_long[] = {
  126665. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  126666. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  126667. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  126668. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  126669. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  126670. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  126671. 10, 8, 8, 9,
  126672. };
  126673. static static_codebook _huff_book__44c2_s_long = {
  126674. 2, 100,
  126675. _huff_lengthlist__44c2_s_long,
  126676. 0, 0, 0, 0, 0,
  126677. NULL,
  126678. NULL,
  126679. NULL,
  126680. NULL,
  126681. 0
  126682. };
  126683. static long _vq_quantlist__44c2_s_p1_0[] = {
  126684. 1,
  126685. 0,
  126686. 2,
  126687. };
  126688. static long _vq_lengthlist__44c2_s_p1_0[] = {
  126689. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  126690. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126694. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  126695. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126699. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  126700. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126735. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  126740. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  126745. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126781. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  126786. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126791. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0,
  127100. };
  127101. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127102. -0.5, 0.5,
  127103. };
  127104. static long _vq_quantmap__44c2_s_p1_0[] = {
  127105. 1, 0, 2,
  127106. };
  127107. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127108. _vq_quantthresh__44c2_s_p1_0,
  127109. _vq_quantmap__44c2_s_p1_0,
  127110. 3,
  127111. 3
  127112. };
  127113. static static_codebook _44c2_s_p1_0 = {
  127114. 8, 6561,
  127115. _vq_lengthlist__44c2_s_p1_0,
  127116. 1, -535822336, 1611661312, 2, 0,
  127117. _vq_quantlist__44c2_s_p1_0,
  127118. NULL,
  127119. &_vq_auxt__44c2_s_p1_0,
  127120. NULL,
  127121. 0
  127122. };
  127123. static long _vq_quantlist__44c2_s_p2_0[] = {
  127124. 2,
  127125. 1,
  127126. 3,
  127127. 0,
  127128. 4,
  127129. };
  127130. static long _vq_lengthlist__44c2_s_p2_0[] = {
  127131. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  127132. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127133. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  127134. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  127135. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  127141. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  127142. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  127143. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  127149. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  127150. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  127157. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  127158. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0,
  127171. };
  127172. static float _vq_quantthresh__44c2_s_p2_0[] = {
  127173. -1.5, -0.5, 0.5, 1.5,
  127174. };
  127175. static long _vq_quantmap__44c2_s_p2_0[] = {
  127176. 3, 1, 0, 2, 4,
  127177. };
  127178. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  127179. _vq_quantthresh__44c2_s_p2_0,
  127180. _vq_quantmap__44c2_s_p2_0,
  127181. 5,
  127182. 5
  127183. };
  127184. static static_codebook _44c2_s_p2_0 = {
  127185. 4, 625,
  127186. _vq_lengthlist__44c2_s_p2_0,
  127187. 1, -533725184, 1611661312, 3, 0,
  127188. _vq_quantlist__44c2_s_p2_0,
  127189. NULL,
  127190. &_vq_auxt__44c2_s_p2_0,
  127191. NULL,
  127192. 0
  127193. };
  127194. static long _vq_quantlist__44c2_s_p3_0[] = {
  127195. 2,
  127196. 1,
  127197. 3,
  127198. 0,
  127199. 4,
  127200. };
  127201. static long _vq_lengthlist__44c2_s_p3_0[] = {
  127202. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0,
  127242. };
  127243. static float _vq_quantthresh__44c2_s_p3_0[] = {
  127244. -1.5, -0.5, 0.5, 1.5,
  127245. };
  127246. static long _vq_quantmap__44c2_s_p3_0[] = {
  127247. 3, 1, 0, 2, 4,
  127248. };
  127249. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  127250. _vq_quantthresh__44c2_s_p3_0,
  127251. _vq_quantmap__44c2_s_p3_0,
  127252. 5,
  127253. 5
  127254. };
  127255. static static_codebook _44c2_s_p3_0 = {
  127256. 4, 625,
  127257. _vq_lengthlist__44c2_s_p3_0,
  127258. 1, -533725184, 1611661312, 3, 0,
  127259. _vq_quantlist__44c2_s_p3_0,
  127260. NULL,
  127261. &_vq_auxt__44c2_s_p3_0,
  127262. NULL,
  127263. 0
  127264. };
  127265. static long _vq_quantlist__44c2_s_p4_0[] = {
  127266. 4,
  127267. 3,
  127268. 5,
  127269. 2,
  127270. 6,
  127271. 1,
  127272. 7,
  127273. 0,
  127274. 8,
  127275. };
  127276. static long _vq_lengthlist__44c2_s_p4_0[] = {
  127277. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  127278. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  127279. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  127280. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  127281. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0,
  127283. };
  127284. static float _vq_quantthresh__44c2_s_p4_0[] = {
  127285. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127286. };
  127287. static long _vq_quantmap__44c2_s_p4_0[] = {
  127288. 7, 5, 3, 1, 0, 2, 4, 6,
  127289. 8,
  127290. };
  127291. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  127292. _vq_quantthresh__44c2_s_p4_0,
  127293. _vq_quantmap__44c2_s_p4_0,
  127294. 9,
  127295. 9
  127296. };
  127297. static static_codebook _44c2_s_p4_0 = {
  127298. 2, 81,
  127299. _vq_lengthlist__44c2_s_p4_0,
  127300. 1, -531628032, 1611661312, 4, 0,
  127301. _vq_quantlist__44c2_s_p4_0,
  127302. NULL,
  127303. &_vq_auxt__44c2_s_p4_0,
  127304. NULL,
  127305. 0
  127306. };
  127307. static long _vq_quantlist__44c2_s_p5_0[] = {
  127308. 4,
  127309. 3,
  127310. 5,
  127311. 2,
  127312. 6,
  127313. 1,
  127314. 7,
  127315. 0,
  127316. 8,
  127317. };
  127318. static long _vq_lengthlist__44c2_s_p5_0[] = {
  127319. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  127320. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  127321. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  127322. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  127323. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  127324. 11,
  127325. };
  127326. static float _vq_quantthresh__44c2_s_p5_0[] = {
  127327. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127328. };
  127329. static long _vq_quantmap__44c2_s_p5_0[] = {
  127330. 7, 5, 3, 1, 0, 2, 4, 6,
  127331. 8,
  127332. };
  127333. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  127334. _vq_quantthresh__44c2_s_p5_0,
  127335. _vq_quantmap__44c2_s_p5_0,
  127336. 9,
  127337. 9
  127338. };
  127339. static static_codebook _44c2_s_p5_0 = {
  127340. 2, 81,
  127341. _vq_lengthlist__44c2_s_p5_0,
  127342. 1, -531628032, 1611661312, 4, 0,
  127343. _vq_quantlist__44c2_s_p5_0,
  127344. NULL,
  127345. &_vq_auxt__44c2_s_p5_0,
  127346. NULL,
  127347. 0
  127348. };
  127349. static long _vq_quantlist__44c2_s_p6_0[] = {
  127350. 8,
  127351. 7,
  127352. 9,
  127353. 6,
  127354. 10,
  127355. 5,
  127356. 11,
  127357. 4,
  127358. 12,
  127359. 3,
  127360. 13,
  127361. 2,
  127362. 14,
  127363. 1,
  127364. 15,
  127365. 0,
  127366. 16,
  127367. };
  127368. static long _vq_lengthlist__44c2_s_p6_0[] = {
  127369. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  127370. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127371. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  127372. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  127373. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  127374. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  127375. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  127376. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127377. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127378. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127379. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127380. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  127381. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127382. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127383. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127384. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  127385. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127386. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127387. 14,
  127388. };
  127389. static float _vq_quantthresh__44c2_s_p6_0[] = {
  127390. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127391. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127392. };
  127393. static long _vq_quantmap__44c2_s_p6_0[] = {
  127394. 15, 13, 11, 9, 7, 5, 3, 1,
  127395. 0, 2, 4, 6, 8, 10, 12, 14,
  127396. 16,
  127397. };
  127398. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  127399. _vq_quantthresh__44c2_s_p6_0,
  127400. _vq_quantmap__44c2_s_p6_0,
  127401. 17,
  127402. 17
  127403. };
  127404. static static_codebook _44c2_s_p6_0 = {
  127405. 2, 289,
  127406. _vq_lengthlist__44c2_s_p6_0,
  127407. 1, -529530880, 1611661312, 5, 0,
  127408. _vq_quantlist__44c2_s_p6_0,
  127409. NULL,
  127410. &_vq_auxt__44c2_s_p6_0,
  127411. NULL,
  127412. 0
  127413. };
  127414. static long _vq_quantlist__44c2_s_p7_0[] = {
  127415. 1,
  127416. 0,
  127417. 2,
  127418. };
  127419. static long _vq_lengthlist__44c2_s_p7_0[] = {
  127420. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127421. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  127422. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127423. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  127424. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  127425. 11,
  127426. };
  127427. static float _vq_quantthresh__44c2_s_p7_0[] = {
  127428. -5.5, 5.5,
  127429. };
  127430. static long _vq_quantmap__44c2_s_p7_0[] = {
  127431. 1, 0, 2,
  127432. };
  127433. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  127434. _vq_quantthresh__44c2_s_p7_0,
  127435. _vq_quantmap__44c2_s_p7_0,
  127436. 3,
  127437. 3
  127438. };
  127439. static static_codebook _44c2_s_p7_0 = {
  127440. 4, 81,
  127441. _vq_lengthlist__44c2_s_p7_0,
  127442. 1, -529137664, 1618345984, 2, 0,
  127443. _vq_quantlist__44c2_s_p7_0,
  127444. NULL,
  127445. &_vq_auxt__44c2_s_p7_0,
  127446. NULL,
  127447. 0
  127448. };
  127449. static long _vq_quantlist__44c2_s_p7_1[] = {
  127450. 5,
  127451. 4,
  127452. 6,
  127453. 3,
  127454. 7,
  127455. 2,
  127456. 8,
  127457. 1,
  127458. 9,
  127459. 0,
  127460. 10,
  127461. };
  127462. static long _vq_lengthlist__44c2_s_p7_1[] = {
  127463. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  127464. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  127465. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127466. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  127467. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127468. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127469. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  127470. 10,10,10, 8, 8, 8, 8, 8, 8,
  127471. };
  127472. static float _vq_quantthresh__44c2_s_p7_1[] = {
  127473. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127474. 3.5, 4.5,
  127475. };
  127476. static long _vq_quantmap__44c2_s_p7_1[] = {
  127477. 9, 7, 5, 3, 1, 0, 2, 4,
  127478. 6, 8, 10,
  127479. };
  127480. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  127481. _vq_quantthresh__44c2_s_p7_1,
  127482. _vq_quantmap__44c2_s_p7_1,
  127483. 11,
  127484. 11
  127485. };
  127486. static static_codebook _44c2_s_p7_1 = {
  127487. 2, 121,
  127488. _vq_lengthlist__44c2_s_p7_1,
  127489. 1, -531365888, 1611661312, 4, 0,
  127490. _vq_quantlist__44c2_s_p7_1,
  127491. NULL,
  127492. &_vq_auxt__44c2_s_p7_1,
  127493. NULL,
  127494. 0
  127495. };
  127496. static long _vq_quantlist__44c2_s_p8_0[] = {
  127497. 6,
  127498. 5,
  127499. 7,
  127500. 4,
  127501. 8,
  127502. 3,
  127503. 9,
  127504. 2,
  127505. 10,
  127506. 1,
  127507. 11,
  127508. 0,
  127509. 12,
  127510. };
  127511. static long _vq_lengthlist__44c2_s_p8_0[] = {
  127512. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  127513. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  127514. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127515. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127516. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  127517. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  127518. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  127519. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  127520. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  127521. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  127522. 0,12,12,12,12,13,12,14,14,
  127523. };
  127524. static float _vq_quantthresh__44c2_s_p8_0[] = {
  127525. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127526. 12.5, 17.5, 22.5, 27.5,
  127527. };
  127528. static long _vq_quantmap__44c2_s_p8_0[] = {
  127529. 11, 9, 7, 5, 3, 1, 0, 2,
  127530. 4, 6, 8, 10, 12,
  127531. };
  127532. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  127533. _vq_quantthresh__44c2_s_p8_0,
  127534. _vq_quantmap__44c2_s_p8_0,
  127535. 13,
  127536. 13
  127537. };
  127538. static static_codebook _44c2_s_p8_0 = {
  127539. 2, 169,
  127540. _vq_lengthlist__44c2_s_p8_0,
  127541. 1, -526516224, 1616117760, 4, 0,
  127542. _vq_quantlist__44c2_s_p8_0,
  127543. NULL,
  127544. &_vq_auxt__44c2_s_p8_0,
  127545. NULL,
  127546. 0
  127547. };
  127548. static long _vq_quantlist__44c2_s_p8_1[] = {
  127549. 2,
  127550. 1,
  127551. 3,
  127552. 0,
  127553. 4,
  127554. };
  127555. static long _vq_lengthlist__44c2_s_p8_1[] = {
  127556. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  127557. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127558. };
  127559. static float _vq_quantthresh__44c2_s_p8_1[] = {
  127560. -1.5, -0.5, 0.5, 1.5,
  127561. };
  127562. static long _vq_quantmap__44c2_s_p8_1[] = {
  127563. 3, 1, 0, 2, 4,
  127564. };
  127565. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  127566. _vq_quantthresh__44c2_s_p8_1,
  127567. _vq_quantmap__44c2_s_p8_1,
  127568. 5,
  127569. 5
  127570. };
  127571. static static_codebook _44c2_s_p8_1 = {
  127572. 2, 25,
  127573. _vq_lengthlist__44c2_s_p8_1,
  127574. 1, -533725184, 1611661312, 3, 0,
  127575. _vq_quantlist__44c2_s_p8_1,
  127576. NULL,
  127577. &_vq_auxt__44c2_s_p8_1,
  127578. NULL,
  127579. 0
  127580. };
  127581. static long _vq_quantlist__44c2_s_p9_0[] = {
  127582. 6,
  127583. 5,
  127584. 7,
  127585. 4,
  127586. 8,
  127587. 3,
  127588. 9,
  127589. 2,
  127590. 10,
  127591. 1,
  127592. 11,
  127593. 0,
  127594. 12,
  127595. };
  127596. static long _vq_lengthlist__44c2_s_p9_0[] = {
  127597. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  127598. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  127599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127600. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  127601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127604. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127607. 11,11,11,11,11,11,11,11,11,
  127608. };
  127609. static float _vq_quantthresh__44c2_s_p9_0[] = {
  127610. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  127611. 552.5, 773.5, 994.5, 1215.5,
  127612. };
  127613. static long _vq_quantmap__44c2_s_p9_0[] = {
  127614. 11, 9, 7, 5, 3, 1, 0, 2,
  127615. 4, 6, 8, 10, 12,
  127616. };
  127617. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  127618. _vq_quantthresh__44c2_s_p9_0,
  127619. _vq_quantmap__44c2_s_p9_0,
  127620. 13,
  127621. 13
  127622. };
  127623. static static_codebook _44c2_s_p9_0 = {
  127624. 2, 169,
  127625. _vq_lengthlist__44c2_s_p9_0,
  127626. 1, -514541568, 1627103232, 4, 0,
  127627. _vq_quantlist__44c2_s_p9_0,
  127628. NULL,
  127629. &_vq_auxt__44c2_s_p9_0,
  127630. NULL,
  127631. 0
  127632. };
  127633. static long _vq_quantlist__44c2_s_p9_1[] = {
  127634. 6,
  127635. 5,
  127636. 7,
  127637. 4,
  127638. 8,
  127639. 3,
  127640. 9,
  127641. 2,
  127642. 10,
  127643. 1,
  127644. 11,
  127645. 0,
  127646. 12,
  127647. };
  127648. static long _vq_lengthlist__44c2_s_p9_1[] = {
  127649. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  127650. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  127651. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  127652. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  127653. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  127654. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  127655. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  127656. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  127657. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  127658. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  127659. 17,13,12,12,10,13,11,14,14,
  127660. };
  127661. static float _vq_quantthresh__44c2_s_p9_1[] = {
  127662. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  127663. 42.5, 59.5, 76.5, 93.5,
  127664. };
  127665. static long _vq_quantmap__44c2_s_p9_1[] = {
  127666. 11, 9, 7, 5, 3, 1, 0, 2,
  127667. 4, 6, 8, 10, 12,
  127668. };
  127669. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  127670. _vq_quantthresh__44c2_s_p9_1,
  127671. _vq_quantmap__44c2_s_p9_1,
  127672. 13,
  127673. 13
  127674. };
  127675. static static_codebook _44c2_s_p9_1 = {
  127676. 2, 169,
  127677. _vq_lengthlist__44c2_s_p9_1,
  127678. 1, -522616832, 1620115456, 4, 0,
  127679. _vq_quantlist__44c2_s_p9_1,
  127680. NULL,
  127681. &_vq_auxt__44c2_s_p9_1,
  127682. NULL,
  127683. 0
  127684. };
  127685. static long _vq_quantlist__44c2_s_p9_2[] = {
  127686. 8,
  127687. 7,
  127688. 9,
  127689. 6,
  127690. 10,
  127691. 5,
  127692. 11,
  127693. 4,
  127694. 12,
  127695. 3,
  127696. 13,
  127697. 2,
  127698. 14,
  127699. 1,
  127700. 15,
  127701. 0,
  127702. 16,
  127703. };
  127704. static long _vq_lengthlist__44c2_s_p9_2[] = {
  127705. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  127706. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  127707. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  127708. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  127709. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  127710. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  127711. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  127712. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  127713. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  127714. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  127715. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  127716. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  127717. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  127718. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  127719. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  127720. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  127721. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  127722. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  127723. 10,
  127724. };
  127725. static float _vq_quantthresh__44c2_s_p9_2[] = {
  127726. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127727. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127728. };
  127729. static long _vq_quantmap__44c2_s_p9_2[] = {
  127730. 15, 13, 11, 9, 7, 5, 3, 1,
  127731. 0, 2, 4, 6, 8, 10, 12, 14,
  127732. 16,
  127733. };
  127734. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  127735. _vq_quantthresh__44c2_s_p9_2,
  127736. _vq_quantmap__44c2_s_p9_2,
  127737. 17,
  127738. 17
  127739. };
  127740. static static_codebook _44c2_s_p9_2 = {
  127741. 2, 289,
  127742. _vq_lengthlist__44c2_s_p9_2,
  127743. 1, -529530880, 1611661312, 5, 0,
  127744. _vq_quantlist__44c2_s_p9_2,
  127745. NULL,
  127746. &_vq_auxt__44c2_s_p9_2,
  127747. NULL,
  127748. 0
  127749. };
  127750. static long _huff_lengthlist__44c2_s_short[] = {
  127751. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  127752. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  127753. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  127754. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  127755. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  127756. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  127757. 6, 8, 9,12,
  127758. };
  127759. static static_codebook _huff_book__44c2_s_short = {
  127760. 2, 100,
  127761. _huff_lengthlist__44c2_s_short,
  127762. 0, 0, 0, 0, 0,
  127763. NULL,
  127764. NULL,
  127765. NULL,
  127766. NULL,
  127767. 0
  127768. };
  127769. static long _huff_lengthlist__44c3_s_long[] = {
  127770. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  127771. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  127772. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  127773. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  127774. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  127775. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  127776. 9, 8, 8, 8,
  127777. };
  127778. static static_codebook _huff_book__44c3_s_long = {
  127779. 2, 100,
  127780. _huff_lengthlist__44c3_s_long,
  127781. 0, 0, 0, 0, 0,
  127782. NULL,
  127783. NULL,
  127784. NULL,
  127785. NULL,
  127786. 0
  127787. };
  127788. static long _vq_quantlist__44c3_s_p1_0[] = {
  127789. 1,
  127790. 0,
  127791. 2,
  127792. };
  127793. static long _vq_lengthlist__44c3_s_p1_0[] = {
  127794. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127795. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127799. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127800. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127804. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127805. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127840. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127845. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127850. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127886. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127891. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127896. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0,
  128205. };
  128206. static float _vq_quantthresh__44c3_s_p1_0[] = {
  128207. -0.5, 0.5,
  128208. };
  128209. static long _vq_quantmap__44c3_s_p1_0[] = {
  128210. 1, 0, 2,
  128211. };
  128212. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  128213. _vq_quantthresh__44c3_s_p1_0,
  128214. _vq_quantmap__44c3_s_p1_0,
  128215. 3,
  128216. 3
  128217. };
  128218. static static_codebook _44c3_s_p1_0 = {
  128219. 8, 6561,
  128220. _vq_lengthlist__44c3_s_p1_0,
  128221. 1, -535822336, 1611661312, 2, 0,
  128222. _vq_quantlist__44c3_s_p1_0,
  128223. NULL,
  128224. &_vq_auxt__44c3_s_p1_0,
  128225. NULL,
  128226. 0
  128227. };
  128228. static long _vq_quantlist__44c3_s_p2_0[] = {
  128229. 2,
  128230. 1,
  128231. 3,
  128232. 0,
  128233. 4,
  128234. };
  128235. static long _vq_lengthlist__44c3_s_p2_0[] = {
  128236. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128237. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  128238. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128239. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  128240. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  128246. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  128247. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  128248. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  128254. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  128255. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  128262. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  128263. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0,
  128276. };
  128277. static float _vq_quantthresh__44c3_s_p2_0[] = {
  128278. -1.5, -0.5, 0.5, 1.5,
  128279. };
  128280. static long _vq_quantmap__44c3_s_p2_0[] = {
  128281. 3, 1, 0, 2, 4,
  128282. };
  128283. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  128284. _vq_quantthresh__44c3_s_p2_0,
  128285. _vq_quantmap__44c3_s_p2_0,
  128286. 5,
  128287. 5
  128288. };
  128289. static static_codebook _44c3_s_p2_0 = {
  128290. 4, 625,
  128291. _vq_lengthlist__44c3_s_p2_0,
  128292. 1, -533725184, 1611661312, 3, 0,
  128293. _vq_quantlist__44c3_s_p2_0,
  128294. NULL,
  128295. &_vq_auxt__44c3_s_p2_0,
  128296. NULL,
  128297. 0
  128298. };
  128299. static long _vq_quantlist__44c3_s_p3_0[] = {
  128300. 2,
  128301. 1,
  128302. 3,
  128303. 0,
  128304. 4,
  128305. };
  128306. static long _vq_lengthlist__44c3_s_p3_0[] = {
  128307. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0,
  128347. };
  128348. static float _vq_quantthresh__44c3_s_p3_0[] = {
  128349. -1.5, -0.5, 0.5, 1.5,
  128350. };
  128351. static long _vq_quantmap__44c3_s_p3_0[] = {
  128352. 3, 1, 0, 2, 4,
  128353. };
  128354. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  128355. _vq_quantthresh__44c3_s_p3_0,
  128356. _vq_quantmap__44c3_s_p3_0,
  128357. 5,
  128358. 5
  128359. };
  128360. static static_codebook _44c3_s_p3_0 = {
  128361. 4, 625,
  128362. _vq_lengthlist__44c3_s_p3_0,
  128363. 1, -533725184, 1611661312, 3, 0,
  128364. _vq_quantlist__44c3_s_p3_0,
  128365. NULL,
  128366. &_vq_auxt__44c3_s_p3_0,
  128367. NULL,
  128368. 0
  128369. };
  128370. static long _vq_quantlist__44c3_s_p4_0[] = {
  128371. 4,
  128372. 3,
  128373. 5,
  128374. 2,
  128375. 6,
  128376. 1,
  128377. 7,
  128378. 0,
  128379. 8,
  128380. };
  128381. static long _vq_lengthlist__44c3_s_p4_0[] = {
  128382. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  128383. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  128384. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  128385. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  128386. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0,
  128388. };
  128389. static float _vq_quantthresh__44c3_s_p4_0[] = {
  128390. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128391. };
  128392. static long _vq_quantmap__44c3_s_p4_0[] = {
  128393. 7, 5, 3, 1, 0, 2, 4, 6,
  128394. 8,
  128395. };
  128396. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  128397. _vq_quantthresh__44c3_s_p4_0,
  128398. _vq_quantmap__44c3_s_p4_0,
  128399. 9,
  128400. 9
  128401. };
  128402. static static_codebook _44c3_s_p4_0 = {
  128403. 2, 81,
  128404. _vq_lengthlist__44c3_s_p4_0,
  128405. 1, -531628032, 1611661312, 4, 0,
  128406. _vq_quantlist__44c3_s_p4_0,
  128407. NULL,
  128408. &_vq_auxt__44c3_s_p4_0,
  128409. NULL,
  128410. 0
  128411. };
  128412. static long _vq_quantlist__44c3_s_p5_0[] = {
  128413. 4,
  128414. 3,
  128415. 5,
  128416. 2,
  128417. 6,
  128418. 1,
  128419. 7,
  128420. 0,
  128421. 8,
  128422. };
  128423. static long _vq_lengthlist__44c3_s_p5_0[] = {
  128424. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  128425. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  128426. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  128427. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  128428. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  128429. 11,
  128430. };
  128431. static float _vq_quantthresh__44c3_s_p5_0[] = {
  128432. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128433. };
  128434. static long _vq_quantmap__44c3_s_p5_0[] = {
  128435. 7, 5, 3, 1, 0, 2, 4, 6,
  128436. 8,
  128437. };
  128438. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  128439. _vq_quantthresh__44c3_s_p5_0,
  128440. _vq_quantmap__44c3_s_p5_0,
  128441. 9,
  128442. 9
  128443. };
  128444. static static_codebook _44c3_s_p5_0 = {
  128445. 2, 81,
  128446. _vq_lengthlist__44c3_s_p5_0,
  128447. 1, -531628032, 1611661312, 4, 0,
  128448. _vq_quantlist__44c3_s_p5_0,
  128449. NULL,
  128450. &_vq_auxt__44c3_s_p5_0,
  128451. NULL,
  128452. 0
  128453. };
  128454. static long _vq_quantlist__44c3_s_p6_0[] = {
  128455. 8,
  128456. 7,
  128457. 9,
  128458. 6,
  128459. 10,
  128460. 5,
  128461. 11,
  128462. 4,
  128463. 12,
  128464. 3,
  128465. 13,
  128466. 2,
  128467. 14,
  128468. 1,
  128469. 15,
  128470. 0,
  128471. 16,
  128472. };
  128473. static long _vq_lengthlist__44c3_s_p6_0[] = {
  128474. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128475. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128476. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  128477. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128478. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128479. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128480. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  128481. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128482. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128483. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  128484. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  128485. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  128486. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  128487. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  128488. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  128489. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  128490. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  128491. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  128492. 13,
  128493. };
  128494. static float _vq_quantthresh__44c3_s_p6_0[] = {
  128495. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128496. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128497. };
  128498. static long _vq_quantmap__44c3_s_p6_0[] = {
  128499. 15, 13, 11, 9, 7, 5, 3, 1,
  128500. 0, 2, 4, 6, 8, 10, 12, 14,
  128501. 16,
  128502. };
  128503. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  128504. _vq_quantthresh__44c3_s_p6_0,
  128505. _vq_quantmap__44c3_s_p6_0,
  128506. 17,
  128507. 17
  128508. };
  128509. static static_codebook _44c3_s_p6_0 = {
  128510. 2, 289,
  128511. _vq_lengthlist__44c3_s_p6_0,
  128512. 1, -529530880, 1611661312, 5, 0,
  128513. _vq_quantlist__44c3_s_p6_0,
  128514. NULL,
  128515. &_vq_auxt__44c3_s_p6_0,
  128516. NULL,
  128517. 0
  128518. };
  128519. static long _vq_quantlist__44c3_s_p7_0[] = {
  128520. 1,
  128521. 0,
  128522. 2,
  128523. };
  128524. static long _vq_lengthlist__44c3_s_p7_0[] = {
  128525. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128526. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  128527. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128528. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  128529. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  128530. 10,
  128531. };
  128532. static float _vq_quantthresh__44c3_s_p7_0[] = {
  128533. -5.5, 5.5,
  128534. };
  128535. static long _vq_quantmap__44c3_s_p7_0[] = {
  128536. 1, 0, 2,
  128537. };
  128538. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  128539. _vq_quantthresh__44c3_s_p7_0,
  128540. _vq_quantmap__44c3_s_p7_0,
  128541. 3,
  128542. 3
  128543. };
  128544. static static_codebook _44c3_s_p7_0 = {
  128545. 4, 81,
  128546. _vq_lengthlist__44c3_s_p7_0,
  128547. 1, -529137664, 1618345984, 2, 0,
  128548. _vq_quantlist__44c3_s_p7_0,
  128549. NULL,
  128550. &_vq_auxt__44c3_s_p7_0,
  128551. NULL,
  128552. 0
  128553. };
  128554. static long _vq_quantlist__44c3_s_p7_1[] = {
  128555. 5,
  128556. 4,
  128557. 6,
  128558. 3,
  128559. 7,
  128560. 2,
  128561. 8,
  128562. 1,
  128563. 9,
  128564. 0,
  128565. 10,
  128566. };
  128567. static long _vq_lengthlist__44c3_s_p7_1[] = {
  128568. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  128569. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  128570. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  128571. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  128572. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128573. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128574. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  128575. 10,10,10, 8, 8, 8, 8, 8, 8,
  128576. };
  128577. static float _vq_quantthresh__44c3_s_p7_1[] = {
  128578. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128579. 3.5, 4.5,
  128580. };
  128581. static long _vq_quantmap__44c3_s_p7_1[] = {
  128582. 9, 7, 5, 3, 1, 0, 2, 4,
  128583. 6, 8, 10,
  128584. };
  128585. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  128586. _vq_quantthresh__44c3_s_p7_1,
  128587. _vq_quantmap__44c3_s_p7_1,
  128588. 11,
  128589. 11
  128590. };
  128591. static static_codebook _44c3_s_p7_1 = {
  128592. 2, 121,
  128593. _vq_lengthlist__44c3_s_p7_1,
  128594. 1, -531365888, 1611661312, 4, 0,
  128595. _vq_quantlist__44c3_s_p7_1,
  128596. NULL,
  128597. &_vq_auxt__44c3_s_p7_1,
  128598. NULL,
  128599. 0
  128600. };
  128601. static long _vq_quantlist__44c3_s_p8_0[] = {
  128602. 6,
  128603. 5,
  128604. 7,
  128605. 4,
  128606. 8,
  128607. 3,
  128608. 9,
  128609. 2,
  128610. 10,
  128611. 1,
  128612. 11,
  128613. 0,
  128614. 12,
  128615. };
  128616. static long _vq_lengthlist__44c3_s_p8_0[] = {
  128617. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  128618. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  128619. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128620. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128621. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  128622. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128623. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  128624. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  128625. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  128626. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  128627. 0,13,13,12,12,13,12,14,13,
  128628. };
  128629. static float _vq_quantthresh__44c3_s_p8_0[] = {
  128630. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128631. 12.5, 17.5, 22.5, 27.5,
  128632. };
  128633. static long _vq_quantmap__44c3_s_p8_0[] = {
  128634. 11, 9, 7, 5, 3, 1, 0, 2,
  128635. 4, 6, 8, 10, 12,
  128636. };
  128637. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  128638. _vq_quantthresh__44c3_s_p8_0,
  128639. _vq_quantmap__44c3_s_p8_0,
  128640. 13,
  128641. 13
  128642. };
  128643. static static_codebook _44c3_s_p8_0 = {
  128644. 2, 169,
  128645. _vq_lengthlist__44c3_s_p8_0,
  128646. 1, -526516224, 1616117760, 4, 0,
  128647. _vq_quantlist__44c3_s_p8_0,
  128648. NULL,
  128649. &_vq_auxt__44c3_s_p8_0,
  128650. NULL,
  128651. 0
  128652. };
  128653. static long _vq_quantlist__44c3_s_p8_1[] = {
  128654. 2,
  128655. 1,
  128656. 3,
  128657. 0,
  128658. 4,
  128659. };
  128660. static long _vq_lengthlist__44c3_s_p8_1[] = {
  128661. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  128662. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128663. };
  128664. static float _vq_quantthresh__44c3_s_p8_1[] = {
  128665. -1.5, -0.5, 0.5, 1.5,
  128666. };
  128667. static long _vq_quantmap__44c3_s_p8_1[] = {
  128668. 3, 1, 0, 2, 4,
  128669. };
  128670. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  128671. _vq_quantthresh__44c3_s_p8_1,
  128672. _vq_quantmap__44c3_s_p8_1,
  128673. 5,
  128674. 5
  128675. };
  128676. static static_codebook _44c3_s_p8_1 = {
  128677. 2, 25,
  128678. _vq_lengthlist__44c3_s_p8_1,
  128679. 1, -533725184, 1611661312, 3, 0,
  128680. _vq_quantlist__44c3_s_p8_1,
  128681. NULL,
  128682. &_vq_auxt__44c3_s_p8_1,
  128683. NULL,
  128684. 0
  128685. };
  128686. static long _vq_quantlist__44c3_s_p9_0[] = {
  128687. 6,
  128688. 5,
  128689. 7,
  128690. 4,
  128691. 8,
  128692. 3,
  128693. 9,
  128694. 2,
  128695. 10,
  128696. 1,
  128697. 11,
  128698. 0,
  128699. 12,
  128700. };
  128701. static long _vq_lengthlist__44c3_s_p9_0[] = {
  128702. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128703. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  128704. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128705. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  128706. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128707. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128708. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128709. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128710. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  128711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128712. 11,11,11,11,11,11,11,11,11,
  128713. };
  128714. static float _vq_quantthresh__44c3_s_p9_0[] = {
  128715. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  128716. 637.5, 892.5, 1147.5, 1402.5,
  128717. };
  128718. static long _vq_quantmap__44c3_s_p9_0[] = {
  128719. 11, 9, 7, 5, 3, 1, 0, 2,
  128720. 4, 6, 8, 10, 12,
  128721. };
  128722. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  128723. _vq_quantthresh__44c3_s_p9_0,
  128724. _vq_quantmap__44c3_s_p9_0,
  128725. 13,
  128726. 13
  128727. };
  128728. static static_codebook _44c3_s_p9_0 = {
  128729. 2, 169,
  128730. _vq_lengthlist__44c3_s_p9_0,
  128731. 1, -514332672, 1627381760, 4, 0,
  128732. _vq_quantlist__44c3_s_p9_0,
  128733. NULL,
  128734. &_vq_auxt__44c3_s_p9_0,
  128735. NULL,
  128736. 0
  128737. };
  128738. static long _vq_quantlist__44c3_s_p9_1[] = {
  128739. 7,
  128740. 6,
  128741. 8,
  128742. 5,
  128743. 9,
  128744. 4,
  128745. 10,
  128746. 3,
  128747. 11,
  128748. 2,
  128749. 12,
  128750. 1,
  128751. 13,
  128752. 0,
  128753. 14,
  128754. };
  128755. static long _vq_lengthlist__44c3_s_p9_1[] = {
  128756. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  128757. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  128758. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  128759. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  128760. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  128761. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  128762. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  128763. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  128764. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  128765. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  128766. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  128767. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  128768. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  128769. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  128770. 15,
  128771. };
  128772. static float _vq_quantthresh__44c3_s_p9_1[] = {
  128773. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  128774. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  128775. };
  128776. static long _vq_quantmap__44c3_s_p9_1[] = {
  128777. 13, 11, 9, 7, 5, 3, 1, 0,
  128778. 2, 4, 6, 8, 10, 12, 14,
  128779. };
  128780. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  128781. _vq_quantthresh__44c3_s_p9_1,
  128782. _vq_quantmap__44c3_s_p9_1,
  128783. 15,
  128784. 15
  128785. };
  128786. static static_codebook _44c3_s_p9_1 = {
  128787. 2, 225,
  128788. _vq_lengthlist__44c3_s_p9_1,
  128789. 1, -522338304, 1620115456, 4, 0,
  128790. _vq_quantlist__44c3_s_p9_1,
  128791. NULL,
  128792. &_vq_auxt__44c3_s_p9_1,
  128793. NULL,
  128794. 0
  128795. };
  128796. static long _vq_quantlist__44c3_s_p9_2[] = {
  128797. 8,
  128798. 7,
  128799. 9,
  128800. 6,
  128801. 10,
  128802. 5,
  128803. 11,
  128804. 4,
  128805. 12,
  128806. 3,
  128807. 13,
  128808. 2,
  128809. 14,
  128810. 1,
  128811. 15,
  128812. 0,
  128813. 16,
  128814. };
  128815. static long _vq_lengthlist__44c3_s_p9_2[] = {
  128816. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128817. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  128818. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  128819. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128820. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  128821. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128822. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  128823. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  128824. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  128825. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  128826. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  128827. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  128828. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  128829. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  128830. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  128831. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  128832. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  128833. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  128834. 10,
  128835. };
  128836. static float _vq_quantthresh__44c3_s_p9_2[] = {
  128837. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128838. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128839. };
  128840. static long _vq_quantmap__44c3_s_p9_2[] = {
  128841. 15, 13, 11, 9, 7, 5, 3, 1,
  128842. 0, 2, 4, 6, 8, 10, 12, 14,
  128843. 16,
  128844. };
  128845. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  128846. _vq_quantthresh__44c3_s_p9_2,
  128847. _vq_quantmap__44c3_s_p9_2,
  128848. 17,
  128849. 17
  128850. };
  128851. static static_codebook _44c3_s_p9_2 = {
  128852. 2, 289,
  128853. _vq_lengthlist__44c3_s_p9_2,
  128854. 1, -529530880, 1611661312, 5, 0,
  128855. _vq_quantlist__44c3_s_p9_2,
  128856. NULL,
  128857. &_vq_auxt__44c3_s_p9_2,
  128858. NULL,
  128859. 0
  128860. };
  128861. static long _huff_lengthlist__44c3_s_short[] = {
  128862. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  128863. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  128864. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  128865. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  128866. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  128867. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  128868. 6, 8, 9,11,
  128869. };
  128870. static static_codebook _huff_book__44c3_s_short = {
  128871. 2, 100,
  128872. _huff_lengthlist__44c3_s_short,
  128873. 0, 0, 0, 0, 0,
  128874. NULL,
  128875. NULL,
  128876. NULL,
  128877. NULL,
  128878. 0
  128879. };
  128880. static long _huff_lengthlist__44c4_s_long[] = {
  128881. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  128882. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  128883. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  128884. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  128885. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  128886. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  128887. 9, 8, 7, 7,
  128888. };
  128889. static static_codebook _huff_book__44c4_s_long = {
  128890. 2, 100,
  128891. _huff_lengthlist__44c4_s_long,
  128892. 0, 0, 0, 0, 0,
  128893. NULL,
  128894. NULL,
  128895. NULL,
  128896. NULL,
  128897. 0
  128898. };
  128899. static long _vq_quantlist__44c4_s_p1_0[] = {
  128900. 1,
  128901. 0,
  128902. 2,
  128903. };
  128904. static long _vq_lengthlist__44c4_s_p1_0[] = {
  128905. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128906. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128910. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128911. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128915. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128916. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128951. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128956. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128961. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128996. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128997. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129001. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129002. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129007. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0,
  129316. };
  129317. static float _vq_quantthresh__44c4_s_p1_0[] = {
  129318. -0.5, 0.5,
  129319. };
  129320. static long _vq_quantmap__44c4_s_p1_0[] = {
  129321. 1, 0, 2,
  129322. };
  129323. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  129324. _vq_quantthresh__44c4_s_p1_0,
  129325. _vq_quantmap__44c4_s_p1_0,
  129326. 3,
  129327. 3
  129328. };
  129329. static static_codebook _44c4_s_p1_0 = {
  129330. 8, 6561,
  129331. _vq_lengthlist__44c4_s_p1_0,
  129332. 1, -535822336, 1611661312, 2, 0,
  129333. _vq_quantlist__44c4_s_p1_0,
  129334. NULL,
  129335. &_vq_auxt__44c4_s_p1_0,
  129336. NULL,
  129337. 0
  129338. };
  129339. static long _vq_quantlist__44c4_s_p2_0[] = {
  129340. 2,
  129341. 1,
  129342. 3,
  129343. 0,
  129344. 4,
  129345. };
  129346. static long _vq_lengthlist__44c4_s_p2_0[] = {
  129347. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129348. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129349. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129350. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129351. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  129357. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129358. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129359. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129365. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129366. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129373. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129374. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0,
  129387. };
  129388. static float _vq_quantthresh__44c4_s_p2_0[] = {
  129389. -1.5, -0.5, 0.5, 1.5,
  129390. };
  129391. static long _vq_quantmap__44c4_s_p2_0[] = {
  129392. 3, 1, 0, 2, 4,
  129393. };
  129394. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  129395. _vq_quantthresh__44c4_s_p2_0,
  129396. _vq_quantmap__44c4_s_p2_0,
  129397. 5,
  129398. 5
  129399. };
  129400. static static_codebook _44c4_s_p2_0 = {
  129401. 4, 625,
  129402. _vq_lengthlist__44c4_s_p2_0,
  129403. 1, -533725184, 1611661312, 3, 0,
  129404. _vq_quantlist__44c4_s_p2_0,
  129405. NULL,
  129406. &_vq_auxt__44c4_s_p2_0,
  129407. NULL,
  129408. 0
  129409. };
  129410. static long _vq_quantlist__44c4_s_p3_0[] = {
  129411. 2,
  129412. 1,
  129413. 3,
  129414. 0,
  129415. 4,
  129416. };
  129417. static long _vq_lengthlist__44c4_s_p3_0[] = {
  129418. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0,
  129458. };
  129459. static float _vq_quantthresh__44c4_s_p3_0[] = {
  129460. -1.5, -0.5, 0.5, 1.5,
  129461. };
  129462. static long _vq_quantmap__44c4_s_p3_0[] = {
  129463. 3, 1, 0, 2, 4,
  129464. };
  129465. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  129466. _vq_quantthresh__44c4_s_p3_0,
  129467. _vq_quantmap__44c4_s_p3_0,
  129468. 5,
  129469. 5
  129470. };
  129471. static static_codebook _44c4_s_p3_0 = {
  129472. 4, 625,
  129473. _vq_lengthlist__44c4_s_p3_0,
  129474. 1, -533725184, 1611661312, 3, 0,
  129475. _vq_quantlist__44c4_s_p3_0,
  129476. NULL,
  129477. &_vq_auxt__44c4_s_p3_0,
  129478. NULL,
  129479. 0
  129480. };
  129481. static long _vq_quantlist__44c4_s_p4_0[] = {
  129482. 4,
  129483. 3,
  129484. 5,
  129485. 2,
  129486. 6,
  129487. 1,
  129488. 7,
  129489. 0,
  129490. 8,
  129491. };
  129492. static long _vq_lengthlist__44c4_s_p4_0[] = {
  129493. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129494. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129495. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129496. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129497. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0,
  129499. };
  129500. static float _vq_quantthresh__44c4_s_p4_0[] = {
  129501. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129502. };
  129503. static long _vq_quantmap__44c4_s_p4_0[] = {
  129504. 7, 5, 3, 1, 0, 2, 4, 6,
  129505. 8,
  129506. };
  129507. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  129508. _vq_quantthresh__44c4_s_p4_0,
  129509. _vq_quantmap__44c4_s_p4_0,
  129510. 9,
  129511. 9
  129512. };
  129513. static static_codebook _44c4_s_p4_0 = {
  129514. 2, 81,
  129515. _vq_lengthlist__44c4_s_p4_0,
  129516. 1, -531628032, 1611661312, 4, 0,
  129517. _vq_quantlist__44c4_s_p4_0,
  129518. NULL,
  129519. &_vq_auxt__44c4_s_p4_0,
  129520. NULL,
  129521. 0
  129522. };
  129523. static long _vq_quantlist__44c4_s_p5_0[] = {
  129524. 4,
  129525. 3,
  129526. 5,
  129527. 2,
  129528. 6,
  129529. 1,
  129530. 7,
  129531. 0,
  129532. 8,
  129533. };
  129534. static long _vq_lengthlist__44c4_s_p5_0[] = {
  129535. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129536. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  129537. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  129538. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  129539. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  129540. 10,
  129541. };
  129542. static float _vq_quantthresh__44c4_s_p5_0[] = {
  129543. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129544. };
  129545. static long _vq_quantmap__44c4_s_p5_0[] = {
  129546. 7, 5, 3, 1, 0, 2, 4, 6,
  129547. 8,
  129548. };
  129549. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  129550. _vq_quantthresh__44c4_s_p5_0,
  129551. _vq_quantmap__44c4_s_p5_0,
  129552. 9,
  129553. 9
  129554. };
  129555. static static_codebook _44c4_s_p5_0 = {
  129556. 2, 81,
  129557. _vq_lengthlist__44c4_s_p5_0,
  129558. 1, -531628032, 1611661312, 4, 0,
  129559. _vq_quantlist__44c4_s_p5_0,
  129560. NULL,
  129561. &_vq_auxt__44c4_s_p5_0,
  129562. NULL,
  129563. 0
  129564. };
  129565. static long _vq_quantlist__44c4_s_p6_0[] = {
  129566. 8,
  129567. 7,
  129568. 9,
  129569. 6,
  129570. 10,
  129571. 5,
  129572. 11,
  129573. 4,
  129574. 12,
  129575. 3,
  129576. 13,
  129577. 2,
  129578. 14,
  129579. 1,
  129580. 15,
  129581. 0,
  129582. 16,
  129583. };
  129584. static long _vq_lengthlist__44c4_s_p6_0[] = {
  129585. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  129586. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  129587. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  129588. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129589. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129590. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129591. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129592. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129593. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129594. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  129595. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  129596. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  129597. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  129598. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  129599. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129600. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129601. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  129602. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  129603. 13,
  129604. };
  129605. static float _vq_quantthresh__44c4_s_p6_0[] = {
  129606. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129607. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129608. };
  129609. static long _vq_quantmap__44c4_s_p6_0[] = {
  129610. 15, 13, 11, 9, 7, 5, 3, 1,
  129611. 0, 2, 4, 6, 8, 10, 12, 14,
  129612. 16,
  129613. };
  129614. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  129615. _vq_quantthresh__44c4_s_p6_0,
  129616. _vq_quantmap__44c4_s_p6_0,
  129617. 17,
  129618. 17
  129619. };
  129620. static static_codebook _44c4_s_p6_0 = {
  129621. 2, 289,
  129622. _vq_lengthlist__44c4_s_p6_0,
  129623. 1, -529530880, 1611661312, 5, 0,
  129624. _vq_quantlist__44c4_s_p6_0,
  129625. NULL,
  129626. &_vq_auxt__44c4_s_p6_0,
  129627. NULL,
  129628. 0
  129629. };
  129630. static long _vq_quantlist__44c4_s_p7_0[] = {
  129631. 1,
  129632. 0,
  129633. 2,
  129634. };
  129635. static long _vq_lengthlist__44c4_s_p7_0[] = {
  129636. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129637. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129638. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129639. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  129640. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129641. 10,
  129642. };
  129643. static float _vq_quantthresh__44c4_s_p7_0[] = {
  129644. -5.5, 5.5,
  129645. };
  129646. static long _vq_quantmap__44c4_s_p7_0[] = {
  129647. 1, 0, 2,
  129648. };
  129649. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  129650. _vq_quantthresh__44c4_s_p7_0,
  129651. _vq_quantmap__44c4_s_p7_0,
  129652. 3,
  129653. 3
  129654. };
  129655. static static_codebook _44c4_s_p7_0 = {
  129656. 4, 81,
  129657. _vq_lengthlist__44c4_s_p7_0,
  129658. 1, -529137664, 1618345984, 2, 0,
  129659. _vq_quantlist__44c4_s_p7_0,
  129660. NULL,
  129661. &_vq_auxt__44c4_s_p7_0,
  129662. NULL,
  129663. 0
  129664. };
  129665. static long _vq_quantlist__44c4_s_p7_1[] = {
  129666. 5,
  129667. 4,
  129668. 6,
  129669. 3,
  129670. 7,
  129671. 2,
  129672. 8,
  129673. 1,
  129674. 9,
  129675. 0,
  129676. 10,
  129677. };
  129678. static long _vq_lengthlist__44c4_s_p7_1[] = {
  129679. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129680. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129681. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129682. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  129683. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  129684. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129685. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129686. 10,10,10, 8, 8, 8, 8, 9, 9,
  129687. };
  129688. static float _vq_quantthresh__44c4_s_p7_1[] = {
  129689. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129690. 3.5, 4.5,
  129691. };
  129692. static long _vq_quantmap__44c4_s_p7_1[] = {
  129693. 9, 7, 5, 3, 1, 0, 2, 4,
  129694. 6, 8, 10,
  129695. };
  129696. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  129697. _vq_quantthresh__44c4_s_p7_1,
  129698. _vq_quantmap__44c4_s_p7_1,
  129699. 11,
  129700. 11
  129701. };
  129702. static static_codebook _44c4_s_p7_1 = {
  129703. 2, 121,
  129704. _vq_lengthlist__44c4_s_p7_1,
  129705. 1, -531365888, 1611661312, 4, 0,
  129706. _vq_quantlist__44c4_s_p7_1,
  129707. NULL,
  129708. &_vq_auxt__44c4_s_p7_1,
  129709. NULL,
  129710. 0
  129711. };
  129712. static long _vq_quantlist__44c4_s_p8_0[] = {
  129713. 6,
  129714. 5,
  129715. 7,
  129716. 4,
  129717. 8,
  129718. 3,
  129719. 9,
  129720. 2,
  129721. 10,
  129722. 1,
  129723. 11,
  129724. 0,
  129725. 12,
  129726. };
  129727. static long _vq_lengthlist__44c4_s_p8_0[] = {
  129728. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129729. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  129730. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129731. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129732. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  129733. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  129734. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  129735. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129736. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  129737. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  129738. 0,13,12,12,12,12,12,13,13,
  129739. };
  129740. static float _vq_quantthresh__44c4_s_p8_0[] = {
  129741. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129742. 12.5, 17.5, 22.5, 27.5,
  129743. };
  129744. static long _vq_quantmap__44c4_s_p8_0[] = {
  129745. 11, 9, 7, 5, 3, 1, 0, 2,
  129746. 4, 6, 8, 10, 12,
  129747. };
  129748. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  129749. _vq_quantthresh__44c4_s_p8_0,
  129750. _vq_quantmap__44c4_s_p8_0,
  129751. 13,
  129752. 13
  129753. };
  129754. static static_codebook _44c4_s_p8_0 = {
  129755. 2, 169,
  129756. _vq_lengthlist__44c4_s_p8_0,
  129757. 1, -526516224, 1616117760, 4, 0,
  129758. _vq_quantlist__44c4_s_p8_0,
  129759. NULL,
  129760. &_vq_auxt__44c4_s_p8_0,
  129761. NULL,
  129762. 0
  129763. };
  129764. static long _vq_quantlist__44c4_s_p8_1[] = {
  129765. 2,
  129766. 1,
  129767. 3,
  129768. 0,
  129769. 4,
  129770. };
  129771. static long _vq_lengthlist__44c4_s_p8_1[] = {
  129772. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  129773. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129774. };
  129775. static float _vq_quantthresh__44c4_s_p8_1[] = {
  129776. -1.5, -0.5, 0.5, 1.5,
  129777. };
  129778. static long _vq_quantmap__44c4_s_p8_1[] = {
  129779. 3, 1, 0, 2, 4,
  129780. };
  129781. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  129782. _vq_quantthresh__44c4_s_p8_1,
  129783. _vq_quantmap__44c4_s_p8_1,
  129784. 5,
  129785. 5
  129786. };
  129787. static static_codebook _44c4_s_p8_1 = {
  129788. 2, 25,
  129789. _vq_lengthlist__44c4_s_p8_1,
  129790. 1, -533725184, 1611661312, 3, 0,
  129791. _vq_quantlist__44c4_s_p8_1,
  129792. NULL,
  129793. &_vq_auxt__44c4_s_p8_1,
  129794. NULL,
  129795. 0
  129796. };
  129797. static long _vq_quantlist__44c4_s_p9_0[] = {
  129798. 6,
  129799. 5,
  129800. 7,
  129801. 4,
  129802. 8,
  129803. 3,
  129804. 9,
  129805. 2,
  129806. 10,
  129807. 1,
  129808. 11,
  129809. 0,
  129810. 12,
  129811. };
  129812. static long _vq_lengthlist__44c4_s_p9_0[] = {
  129813. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  129814. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  129815. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129816. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129817. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129818. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129819. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129820. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129821. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129822. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129823. 12,12,12,12,12,12,12,12,12,
  129824. };
  129825. static float _vq_quantthresh__44c4_s_p9_0[] = {
  129826. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  129827. 787.5, 1102.5, 1417.5, 1732.5,
  129828. };
  129829. static long _vq_quantmap__44c4_s_p9_0[] = {
  129830. 11, 9, 7, 5, 3, 1, 0, 2,
  129831. 4, 6, 8, 10, 12,
  129832. };
  129833. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  129834. _vq_quantthresh__44c4_s_p9_0,
  129835. _vq_quantmap__44c4_s_p9_0,
  129836. 13,
  129837. 13
  129838. };
  129839. static static_codebook _44c4_s_p9_0 = {
  129840. 2, 169,
  129841. _vq_lengthlist__44c4_s_p9_0,
  129842. 1, -513964032, 1628680192, 4, 0,
  129843. _vq_quantlist__44c4_s_p9_0,
  129844. NULL,
  129845. &_vq_auxt__44c4_s_p9_0,
  129846. NULL,
  129847. 0
  129848. };
  129849. static long _vq_quantlist__44c4_s_p9_1[] = {
  129850. 7,
  129851. 6,
  129852. 8,
  129853. 5,
  129854. 9,
  129855. 4,
  129856. 10,
  129857. 3,
  129858. 11,
  129859. 2,
  129860. 12,
  129861. 1,
  129862. 13,
  129863. 0,
  129864. 14,
  129865. };
  129866. static long _vq_lengthlist__44c4_s_p9_1[] = {
  129867. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  129868. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  129869. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  129870. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  129871. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  129872. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  129873. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  129874. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  129875. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  129876. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  129877. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  129878. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  129879. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  129880. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  129881. 15,
  129882. };
  129883. static float _vq_quantthresh__44c4_s_p9_1[] = {
  129884. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129885. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129886. };
  129887. static long _vq_quantmap__44c4_s_p9_1[] = {
  129888. 13, 11, 9, 7, 5, 3, 1, 0,
  129889. 2, 4, 6, 8, 10, 12, 14,
  129890. };
  129891. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  129892. _vq_quantthresh__44c4_s_p9_1,
  129893. _vq_quantmap__44c4_s_p9_1,
  129894. 15,
  129895. 15
  129896. };
  129897. static static_codebook _44c4_s_p9_1 = {
  129898. 2, 225,
  129899. _vq_lengthlist__44c4_s_p9_1,
  129900. 1, -520986624, 1620377600, 4, 0,
  129901. _vq_quantlist__44c4_s_p9_1,
  129902. NULL,
  129903. &_vq_auxt__44c4_s_p9_1,
  129904. NULL,
  129905. 0
  129906. };
  129907. static long _vq_quantlist__44c4_s_p9_2[] = {
  129908. 10,
  129909. 9,
  129910. 11,
  129911. 8,
  129912. 12,
  129913. 7,
  129914. 13,
  129915. 6,
  129916. 14,
  129917. 5,
  129918. 15,
  129919. 4,
  129920. 16,
  129921. 3,
  129922. 17,
  129923. 2,
  129924. 18,
  129925. 1,
  129926. 19,
  129927. 0,
  129928. 20,
  129929. };
  129930. static long _vq_lengthlist__44c4_s_p9_2[] = {
  129931. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  129932. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  129933. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  129934. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129935. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  129936. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  129937. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  129938. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  129939. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  129940. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  129941. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  129942. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  129943. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  129944. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  129945. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  129946. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  129947. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  129948. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  129949. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  129950. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  129951. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  129952. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  129953. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  129954. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  129955. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  129956. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  129957. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  129958. 10,10,10,10,10,10,10,10,10,
  129959. };
  129960. static float _vq_quantthresh__44c4_s_p9_2[] = {
  129961. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129962. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129963. 6.5, 7.5, 8.5, 9.5,
  129964. };
  129965. static long _vq_quantmap__44c4_s_p9_2[] = {
  129966. 19, 17, 15, 13, 11, 9, 7, 5,
  129967. 3, 1, 0, 2, 4, 6, 8, 10,
  129968. 12, 14, 16, 18, 20,
  129969. };
  129970. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  129971. _vq_quantthresh__44c4_s_p9_2,
  129972. _vq_quantmap__44c4_s_p9_2,
  129973. 21,
  129974. 21
  129975. };
  129976. static static_codebook _44c4_s_p9_2 = {
  129977. 2, 441,
  129978. _vq_lengthlist__44c4_s_p9_2,
  129979. 1, -529268736, 1611661312, 5, 0,
  129980. _vq_quantlist__44c4_s_p9_2,
  129981. NULL,
  129982. &_vq_auxt__44c4_s_p9_2,
  129983. NULL,
  129984. 0
  129985. };
  129986. static long _huff_lengthlist__44c4_s_short[] = {
  129987. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  129988. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  129989. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  129990. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  129991. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  129992. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  129993. 7, 9,12,17,
  129994. };
  129995. static static_codebook _huff_book__44c4_s_short = {
  129996. 2, 100,
  129997. _huff_lengthlist__44c4_s_short,
  129998. 0, 0, 0, 0, 0,
  129999. NULL,
  130000. NULL,
  130001. NULL,
  130002. NULL,
  130003. 0
  130004. };
  130005. static long _huff_lengthlist__44c5_s_long[] = {
  130006. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130007. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130008. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130009. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130010. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130011. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130012. 9, 8, 7, 7,
  130013. };
  130014. static static_codebook _huff_book__44c5_s_long = {
  130015. 2, 100,
  130016. _huff_lengthlist__44c5_s_long,
  130017. 0, 0, 0, 0, 0,
  130018. NULL,
  130019. NULL,
  130020. NULL,
  130021. NULL,
  130022. 0
  130023. };
  130024. static long _vq_quantlist__44c5_s_p1_0[] = {
  130025. 1,
  130026. 0,
  130027. 2,
  130028. };
  130029. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130030. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130031. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130035. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130036. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130041. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130076. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130081. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130086. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130122. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130127. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130132. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0,
  130441. };
  130442. static float _vq_quantthresh__44c5_s_p1_0[] = {
  130443. -0.5, 0.5,
  130444. };
  130445. static long _vq_quantmap__44c5_s_p1_0[] = {
  130446. 1, 0, 2,
  130447. };
  130448. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  130449. _vq_quantthresh__44c5_s_p1_0,
  130450. _vq_quantmap__44c5_s_p1_0,
  130451. 3,
  130452. 3
  130453. };
  130454. static static_codebook _44c5_s_p1_0 = {
  130455. 8, 6561,
  130456. _vq_lengthlist__44c5_s_p1_0,
  130457. 1, -535822336, 1611661312, 2, 0,
  130458. _vq_quantlist__44c5_s_p1_0,
  130459. NULL,
  130460. &_vq_auxt__44c5_s_p1_0,
  130461. NULL,
  130462. 0
  130463. };
  130464. static long _vq_quantlist__44c5_s_p2_0[] = {
  130465. 2,
  130466. 1,
  130467. 3,
  130468. 0,
  130469. 4,
  130470. };
  130471. static long _vq_lengthlist__44c5_s_p2_0[] = {
  130472. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130473. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  130474. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130475. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  130476. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  130482. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  130483. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  130484. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  130490. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  130491. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  130498. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  130499. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0,
  130512. };
  130513. static float _vq_quantthresh__44c5_s_p2_0[] = {
  130514. -1.5, -0.5, 0.5, 1.5,
  130515. };
  130516. static long _vq_quantmap__44c5_s_p2_0[] = {
  130517. 3, 1, 0, 2, 4,
  130518. };
  130519. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  130520. _vq_quantthresh__44c5_s_p2_0,
  130521. _vq_quantmap__44c5_s_p2_0,
  130522. 5,
  130523. 5
  130524. };
  130525. static static_codebook _44c5_s_p2_0 = {
  130526. 4, 625,
  130527. _vq_lengthlist__44c5_s_p2_0,
  130528. 1, -533725184, 1611661312, 3, 0,
  130529. _vq_quantlist__44c5_s_p2_0,
  130530. NULL,
  130531. &_vq_auxt__44c5_s_p2_0,
  130532. NULL,
  130533. 0
  130534. };
  130535. static long _vq_quantlist__44c5_s_p3_0[] = {
  130536. 2,
  130537. 1,
  130538. 3,
  130539. 0,
  130540. 4,
  130541. };
  130542. static long _vq_lengthlist__44c5_s_p3_0[] = {
  130543. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0,
  130583. };
  130584. static float _vq_quantthresh__44c5_s_p3_0[] = {
  130585. -1.5, -0.5, 0.5, 1.5,
  130586. };
  130587. static long _vq_quantmap__44c5_s_p3_0[] = {
  130588. 3, 1, 0, 2, 4,
  130589. };
  130590. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  130591. _vq_quantthresh__44c5_s_p3_0,
  130592. _vq_quantmap__44c5_s_p3_0,
  130593. 5,
  130594. 5
  130595. };
  130596. static static_codebook _44c5_s_p3_0 = {
  130597. 4, 625,
  130598. _vq_lengthlist__44c5_s_p3_0,
  130599. 1, -533725184, 1611661312, 3, 0,
  130600. _vq_quantlist__44c5_s_p3_0,
  130601. NULL,
  130602. &_vq_auxt__44c5_s_p3_0,
  130603. NULL,
  130604. 0
  130605. };
  130606. static long _vq_quantlist__44c5_s_p4_0[] = {
  130607. 4,
  130608. 3,
  130609. 5,
  130610. 2,
  130611. 6,
  130612. 1,
  130613. 7,
  130614. 0,
  130615. 8,
  130616. };
  130617. static long _vq_lengthlist__44c5_s_p4_0[] = {
  130618. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130619. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130620. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130621. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  130622. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0,
  130624. };
  130625. static float _vq_quantthresh__44c5_s_p4_0[] = {
  130626. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130627. };
  130628. static long _vq_quantmap__44c5_s_p4_0[] = {
  130629. 7, 5, 3, 1, 0, 2, 4, 6,
  130630. 8,
  130631. };
  130632. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  130633. _vq_quantthresh__44c5_s_p4_0,
  130634. _vq_quantmap__44c5_s_p4_0,
  130635. 9,
  130636. 9
  130637. };
  130638. static static_codebook _44c5_s_p4_0 = {
  130639. 2, 81,
  130640. _vq_lengthlist__44c5_s_p4_0,
  130641. 1, -531628032, 1611661312, 4, 0,
  130642. _vq_quantlist__44c5_s_p4_0,
  130643. NULL,
  130644. &_vq_auxt__44c5_s_p4_0,
  130645. NULL,
  130646. 0
  130647. };
  130648. static long _vq_quantlist__44c5_s_p5_0[] = {
  130649. 4,
  130650. 3,
  130651. 5,
  130652. 2,
  130653. 6,
  130654. 1,
  130655. 7,
  130656. 0,
  130657. 8,
  130658. };
  130659. static long _vq_lengthlist__44c5_s_p5_0[] = {
  130660. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130661. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130662. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  130663. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130664. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  130665. 10,
  130666. };
  130667. static float _vq_quantthresh__44c5_s_p5_0[] = {
  130668. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130669. };
  130670. static long _vq_quantmap__44c5_s_p5_0[] = {
  130671. 7, 5, 3, 1, 0, 2, 4, 6,
  130672. 8,
  130673. };
  130674. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  130675. _vq_quantthresh__44c5_s_p5_0,
  130676. _vq_quantmap__44c5_s_p5_0,
  130677. 9,
  130678. 9
  130679. };
  130680. static static_codebook _44c5_s_p5_0 = {
  130681. 2, 81,
  130682. _vq_lengthlist__44c5_s_p5_0,
  130683. 1, -531628032, 1611661312, 4, 0,
  130684. _vq_quantlist__44c5_s_p5_0,
  130685. NULL,
  130686. &_vq_auxt__44c5_s_p5_0,
  130687. NULL,
  130688. 0
  130689. };
  130690. static long _vq_quantlist__44c5_s_p6_0[] = {
  130691. 8,
  130692. 7,
  130693. 9,
  130694. 6,
  130695. 10,
  130696. 5,
  130697. 11,
  130698. 4,
  130699. 12,
  130700. 3,
  130701. 13,
  130702. 2,
  130703. 14,
  130704. 1,
  130705. 15,
  130706. 0,
  130707. 16,
  130708. };
  130709. static long _vq_lengthlist__44c5_s_p6_0[] = {
  130710. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  130711. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130712. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130713. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130714. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130715. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  130716. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  130717. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  130718. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130719. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  130720. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  130721. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  130722. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  130723. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  130724. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  130725. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130726. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  130727. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  130728. 13,
  130729. };
  130730. static float _vq_quantthresh__44c5_s_p6_0[] = {
  130731. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130732. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130733. };
  130734. static long _vq_quantmap__44c5_s_p6_0[] = {
  130735. 15, 13, 11, 9, 7, 5, 3, 1,
  130736. 0, 2, 4, 6, 8, 10, 12, 14,
  130737. 16,
  130738. };
  130739. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  130740. _vq_quantthresh__44c5_s_p6_0,
  130741. _vq_quantmap__44c5_s_p6_0,
  130742. 17,
  130743. 17
  130744. };
  130745. static static_codebook _44c5_s_p6_0 = {
  130746. 2, 289,
  130747. _vq_lengthlist__44c5_s_p6_0,
  130748. 1, -529530880, 1611661312, 5, 0,
  130749. _vq_quantlist__44c5_s_p6_0,
  130750. NULL,
  130751. &_vq_auxt__44c5_s_p6_0,
  130752. NULL,
  130753. 0
  130754. };
  130755. static long _vq_quantlist__44c5_s_p7_0[] = {
  130756. 1,
  130757. 0,
  130758. 2,
  130759. };
  130760. static long _vq_lengthlist__44c5_s_p7_0[] = {
  130761. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130762. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130763. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130764. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130765. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130766. 10,
  130767. };
  130768. static float _vq_quantthresh__44c5_s_p7_0[] = {
  130769. -5.5, 5.5,
  130770. };
  130771. static long _vq_quantmap__44c5_s_p7_0[] = {
  130772. 1, 0, 2,
  130773. };
  130774. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  130775. _vq_quantthresh__44c5_s_p7_0,
  130776. _vq_quantmap__44c5_s_p7_0,
  130777. 3,
  130778. 3
  130779. };
  130780. static static_codebook _44c5_s_p7_0 = {
  130781. 4, 81,
  130782. _vq_lengthlist__44c5_s_p7_0,
  130783. 1, -529137664, 1618345984, 2, 0,
  130784. _vq_quantlist__44c5_s_p7_0,
  130785. NULL,
  130786. &_vq_auxt__44c5_s_p7_0,
  130787. NULL,
  130788. 0
  130789. };
  130790. static long _vq_quantlist__44c5_s_p7_1[] = {
  130791. 5,
  130792. 4,
  130793. 6,
  130794. 3,
  130795. 7,
  130796. 2,
  130797. 8,
  130798. 1,
  130799. 9,
  130800. 0,
  130801. 10,
  130802. };
  130803. static long _vq_lengthlist__44c5_s_p7_1[] = {
  130804. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  130805. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130806. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130807. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  130808. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130809. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  130810. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  130811. 10,10,10, 8, 8, 8, 8, 8, 8,
  130812. };
  130813. static float _vq_quantthresh__44c5_s_p7_1[] = {
  130814. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130815. 3.5, 4.5,
  130816. };
  130817. static long _vq_quantmap__44c5_s_p7_1[] = {
  130818. 9, 7, 5, 3, 1, 0, 2, 4,
  130819. 6, 8, 10,
  130820. };
  130821. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  130822. _vq_quantthresh__44c5_s_p7_1,
  130823. _vq_quantmap__44c5_s_p7_1,
  130824. 11,
  130825. 11
  130826. };
  130827. static static_codebook _44c5_s_p7_1 = {
  130828. 2, 121,
  130829. _vq_lengthlist__44c5_s_p7_1,
  130830. 1, -531365888, 1611661312, 4, 0,
  130831. _vq_quantlist__44c5_s_p7_1,
  130832. NULL,
  130833. &_vq_auxt__44c5_s_p7_1,
  130834. NULL,
  130835. 0
  130836. };
  130837. static long _vq_quantlist__44c5_s_p8_0[] = {
  130838. 6,
  130839. 5,
  130840. 7,
  130841. 4,
  130842. 8,
  130843. 3,
  130844. 9,
  130845. 2,
  130846. 10,
  130847. 1,
  130848. 11,
  130849. 0,
  130850. 12,
  130851. };
  130852. static long _vq_lengthlist__44c5_s_p8_0[] = {
  130853. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130854. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  130855. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130856. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130857. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  130858. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  130859. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  130860. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130861. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  130862. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130863. 0,12,12,12,12,12,12,13,13,
  130864. };
  130865. static float _vq_quantthresh__44c5_s_p8_0[] = {
  130866. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130867. 12.5, 17.5, 22.5, 27.5,
  130868. };
  130869. static long _vq_quantmap__44c5_s_p8_0[] = {
  130870. 11, 9, 7, 5, 3, 1, 0, 2,
  130871. 4, 6, 8, 10, 12,
  130872. };
  130873. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  130874. _vq_quantthresh__44c5_s_p8_0,
  130875. _vq_quantmap__44c5_s_p8_0,
  130876. 13,
  130877. 13
  130878. };
  130879. static static_codebook _44c5_s_p8_0 = {
  130880. 2, 169,
  130881. _vq_lengthlist__44c5_s_p8_0,
  130882. 1, -526516224, 1616117760, 4, 0,
  130883. _vq_quantlist__44c5_s_p8_0,
  130884. NULL,
  130885. &_vq_auxt__44c5_s_p8_0,
  130886. NULL,
  130887. 0
  130888. };
  130889. static long _vq_quantlist__44c5_s_p8_1[] = {
  130890. 2,
  130891. 1,
  130892. 3,
  130893. 0,
  130894. 4,
  130895. };
  130896. static long _vq_lengthlist__44c5_s_p8_1[] = {
  130897. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  130898. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130899. };
  130900. static float _vq_quantthresh__44c5_s_p8_1[] = {
  130901. -1.5, -0.5, 0.5, 1.5,
  130902. };
  130903. static long _vq_quantmap__44c5_s_p8_1[] = {
  130904. 3, 1, 0, 2, 4,
  130905. };
  130906. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  130907. _vq_quantthresh__44c5_s_p8_1,
  130908. _vq_quantmap__44c5_s_p8_1,
  130909. 5,
  130910. 5
  130911. };
  130912. static static_codebook _44c5_s_p8_1 = {
  130913. 2, 25,
  130914. _vq_lengthlist__44c5_s_p8_1,
  130915. 1, -533725184, 1611661312, 3, 0,
  130916. _vq_quantlist__44c5_s_p8_1,
  130917. NULL,
  130918. &_vq_auxt__44c5_s_p8_1,
  130919. NULL,
  130920. 0
  130921. };
  130922. static long _vq_quantlist__44c5_s_p9_0[] = {
  130923. 7,
  130924. 6,
  130925. 8,
  130926. 5,
  130927. 9,
  130928. 4,
  130929. 10,
  130930. 3,
  130931. 11,
  130932. 2,
  130933. 12,
  130934. 1,
  130935. 13,
  130936. 0,
  130937. 14,
  130938. };
  130939. static long _vq_lengthlist__44c5_s_p9_0[] = {
  130940. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  130941. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  130942. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130943. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130944. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130945. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130946. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130947. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130948. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130949. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130950. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130951. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130952. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  130953. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  130954. 12,
  130955. };
  130956. static float _vq_quantthresh__44c5_s_p9_0[] = {
  130957. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  130958. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  130959. };
  130960. static long _vq_quantmap__44c5_s_p9_0[] = {
  130961. 13, 11, 9, 7, 5, 3, 1, 0,
  130962. 2, 4, 6, 8, 10, 12, 14,
  130963. };
  130964. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  130965. _vq_quantthresh__44c5_s_p9_0,
  130966. _vq_quantmap__44c5_s_p9_0,
  130967. 15,
  130968. 15
  130969. };
  130970. static static_codebook _44c5_s_p9_0 = {
  130971. 2, 225,
  130972. _vq_lengthlist__44c5_s_p9_0,
  130973. 1, -512522752, 1628852224, 4, 0,
  130974. _vq_quantlist__44c5_s_p9_0,
  130975. NULL,
  130976. &_vq_auxt__44c5_s_p9_0,
  130977. NULL,
  130978. 0
  130979. };
  130980. static long _vq_quantlist__44c5_s_p9_1[] = {
  130981. 8,
  130982. 7,
  130983. 9,
  130984. 6,
  130985. 10,
  130986. 5,
  130987. 11,
  130988. 4,
  130989. 12,
  130990. 3,
  130991. 13,
  130992. 2,
  130993. 14,
  130994. 1,
  130995. 15,
  130996. 0,
  130997. 16,
  130998. };
  130999. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131000. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131001. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131002. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131003. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131004. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131005. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131006. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131007. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131008. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131009. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131010. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131011. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131012. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131013. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131014. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131015. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131016. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131017. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131018. 15,
  131019. };
  131020. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131021. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131022. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131023. };
  131024. static long _vq_quantmap__44c5_s_p9_1[] = {
  131025. 15, 13, 11, 9, 7, 5, 3, 1,
  131026. 0, 2, 4, 6, 8, 10, 12, 14,
  131027. 16,
  131028. };
  131029. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131030. _vq_quantthresh__44c5_s_p9_1,
  131031. _vq_quantmap__44c5_s_p9_1,
  131032. 17,
  131033. 17
  131034. };
  131035. static static_codebook _44c5_s_p9_1 = {
  131036. 2, 289,
  131037. _vq_lengthlist__44c5_s_p9_1,
  131038. 1, -520814592, 1620377600, 5, 0,
  131039. _vq_quantlist__44c5_s_p9_1,
  131040. NULL,
  131041. &_vq_auxt__44c5_s_p9_1,
  131042. NULL,
  131043. 0
  131044. };
  131045. static long _vq_quantlist__44c5_s_p9_2[] = {
  131046. 10,
  131047. 9,
  131048. 11,
  131049. 8,
  131050. 12,
  131051. 7,
  131052. 13,
  131053. 6,
  131054. 14,
  131055. 5,
  131056. 15,
  131057. 4,
  131058. 16,
  131059. 3,
  131060. 17,
  131061. 2,
  131062. 18,
  131063. 1,
  131064. 19,
  131065. 0,
  131066. 20,
  131067. };
  131068. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131069. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131070. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131071. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131072. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131073. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131074. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131075. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131076. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131077. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131078. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131079. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131080. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131081. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131082. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131083. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131084. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131085. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131086. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131087. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131088. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131089. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131090. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131091. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131092. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131093. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131094. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131095. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131096. 10,10,10,10,10,10,10,10,10,
  131097. };
  131098. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131099. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131100. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131101. 6.5, 7.5, 8.5, 9.5,
  131102. };
  131103. static long _vq_quantmap__44c5_s_p9_2[] = {
  131104. 19, 17, 15, 13, 11, 9, 7, 5,
  131105. 3, 1, 0, 2, 4, 6, 8, 10,
  131106. 12, 14, 16, 18, 20,
  131107. };
  131108. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131109. _vq_quantthresh__44c5_s_p9_2,
  131110. _vq_quantmap__44c5_s_p9_2,
  131111. 21,
  131112. 21
  131113. };
  131114. static static_codebook _44c5_s_p9_2 = {
  131115. 2, 441,
  131116. _vq_lengthlist__44c5_s_p9_2,
  131117. 1, -529268736, 1611661312, 5, 0,
  131118. _vq_quantlist__44c5_s_p9_2,
  131119. NULL,
  131120. &_vq_auxt__44c5_s_p9_2,
  131121. NULL,
  131122. 0
  131123. };
  131124. static long _huff_lengthlist__44c5_s_short[] = {
  131125. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  131126. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  131127. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  131128. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  131129. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  131130. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  131131. 6, 8,11,16,
  131132. };
  131133. static static_codebook _huff_book__44c5_s_short = {
  131134. 2, 100,
  131135. _huff_lengthlist__44c5_s_short,
  131136. 0, 0, 0, 0, 0,
  131137. NULL,
  131138. NULL,
  131139. NULL,
  131140. NULL,
  131141. 0
  131142. };
  131143. static long _huff_lengthlist__44c6_s_long[] = {
  131144. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  131145. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  131146. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  131147. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  131148. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  131149. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  131150. 11,10,10,12,
  131151. };
  131152. static static_codebook _huff_book__44c6_s_long = {
  131153. 2, 100,
  131154. _huff_lengthlist__44c6_s_long,
  131155. 0, 0, 0, 0, 0,
  131156. NULL,
  131157. NULL,
  131158. NULL,
  131159. NULL,
  131160. 0
  131161. };
  131162. static long _vq_quantlist__44c6_s_p1_0[] = {
  131163. 1,
  131164. 0,
  131165. 2,
  131166. };
  131167. static long _vq_lengthlist__44c6_s_p1_0[] = {
  131168. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  131169. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131171. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131172. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  131173. 8,
  131174. };
  131175. static float _vq_quantthresh__44c6_s_p1_0[] = {
  131176. -0.5, 0.5,
  131177. };
  131178. static long _vq_quantmap__44c6_s_p1_0[] = {
  131179. 1, 0, 2,
  131180. };
  131181. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  131182. _vq_quantthresh__44c6_s_p1_0,
  131183. _vq_quantmap__44c6_s_p1_0,
  131184. 3,
  131185. 3
  131186. };
  131187. static static_codebook _44c6_s_p1_0 = {
  131188. 4, 81,
  131189. _vq_lengthlist__44c6_s_p1_0,
  131190. 1, -535822336, 1611661312, 2, 0,
  131191. _vq_quantlist__44c6_s_p1_0,
  131192. NULL,
  131193. &_vq_auxt__44c6_s_p1_0,
  131194. NULL,
  131195. 0
  131196. };
  131197. static long _vq_quantlist__44c6_s_p2_0[] = {
  131198. 2,
  131199. 1,
  131200. 3,
  131201. 0,
  131202. 4,
  131203. };
  131204. static long _vq_lengthlist__44c6_s_p2_0[] = {
  131205. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131206. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  131207. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  131208. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  131209. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  131210. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  131211. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  131212. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  131215. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  131216. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  131217. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  131218. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  131219. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  131220. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  131223. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  131224. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  131225. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  131226. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  131227. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  131228. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  131231. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  131232. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  131233. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  131234. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  131235. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  131236. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131241. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  131242. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  131243. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  131244. 13,
  131245. };
  131246. static float _vq_quantthresh__44c6_s_p2_0[] = {
  131247. -1.5, -0.5, 0.5, 1.5,
  131248. };
  131249. static long _vq_quantmap__44c6_s_p2_0[] = {
  131250. 3, 1, 0, 2, 4,
  131251. };
  131252. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  131253. _vq_quantthresh__44c6_s_p2_0,
  131254. _vq_quantmap__44c6_s_p2_0,
  131255. 5,
  131256. 5
  131257. };
  131258. static static_codebook _44c6_s_p2_0 = {
  131259. 4, 625,
  131260. _vq_lengthlist__44c6_s_p2_0,
  131261. 1, -533725184, 1611661312, 3, 0,
  131262. _vq_quantlist__44c6_s_p2_0,
  131263. NULL,
  131264. &_vq_auxt__44c6_s_p2_0,
  131265. NULL,
  131266. 0
  131267. };
  131268. static long _vq_quantlist__44c6_s_p3_0[] = {
  131269. 4,
  131270. 3,
  131271. 5,
  131272. 2,
  131273. 6,
  131274. 1,
  131275. 7,
  131276. 0,
  131277. 8,
  131278. };
  131279. static long _vq_lengthlist__44c6_s_p3_0[] = {
  131280. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131281. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  131282. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  131283. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0,
  131286. };
  131287. static float _vq_quantthresh__44c6_s_p3_0[] = {
  131288. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131289. };
  131290. static long _vq_quantmap__44c6_s_p3_0[] = {
  131291. 7, 5, 3, 1, 0, 2, 4, 6,
  131292. 8,
  131293. };
  131294. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  131295. _vq_quantthresh__44c6_s_p3_0,
  131296. _vq_quantmap__44c6_s_p3_0,
  131297. 9,
  131298. 9
  131299. };
  131300. static static_codebook _44c6_s_p3_0 = {
  131301. 2, 81,
  131302. _vq_lengthlist__44c6_s_p3_0,
  131303. 1, -531628032, 1611661312, 4, 0,
  131304. _vq_quantlist__44c6_s_p3_0,
  131305. NULL,
  131306. &_vq_auxt__44c6_s_p3_0,
  131307. NULL,
  131308. 0
  131309. };
  131310. static long _vq_quantlist__44c6_s_p4_0[] = {
  131311. 8,
  131312. 7,
  131313. 9,
  131314. 6,
  131315. 10,
  131316. 5,
  131317. 11,
  131318. 4,
  131319. 12,
  131320. 3,
  131321. 13,
  131322. 2,
  131323. 14,
  131324. 1,
  131325. 15,
  131326. 0,
  131327. 16,
  131328. };
  131329. static long _vq_lengthlist__44c6_s_p4_0[] = {
  131330. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  131331. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  131332. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  131333. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131334. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131335. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131336. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  131337. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131338. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  131339. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0,
  131349. };
  131350. static float _vq_quantthresh__44c6_s_p4_0[] = {
  131351. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131352. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131353. };
  131354. static long _vq_quantmap__44c6_s_p4_0[] = {
  131355. 15, 13, 11, 9, 7, 5, 3, 1,
  131356. 0, 2, 4, 6, 8, 10, 12, 14,
  131357. 16,
  131358. };
  131359. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  131360. _vq_quantthresh__44c6_s_p4_0,
  131361. _vq_quantmap__44c6_s_p4_0,
  131362. 17,
  131363. 17
  131364. };
  131365. static static_codebook _44c6_s_p4_0 = {
  131366. 2, 289,
  131367. _vq_lengthlist__44c6_s_p4_0,
  131368. 1, -529530880, 1611661312, 5, 0,
  131369. _vq_quantlist__44c6_s_p4_0,
  131370. NULL,
  131371. &_vq_auxt__44c6_s_p4_0,
  131372. NULL,
  131373. 0
  131374. };
  131375. static long _vq_quantlist__44c6_s_p5_0[] = {
  131376. 1,
  131377. 0,
  131378. 2,
  131379. };
  131380. static long _vq_lengthlist__44c6_s_p5_0[] = {
  131381. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  131382. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  131383. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  131384. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  131385. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  131386. 12,
  131387. };
  131388. static float _vq_quantthresh__44c6_s_p5_0[] = {
  131389. -5.5, 5.5,
  131390. };
  131391. static long _vq_quantmap__44c6_s_p5_0[] = {
  131392. 1, 0, 2,
  131393. };
  131394. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  131395. _vq_quantthresh__44c6_s_p5_0,
  131396. _vq_quantmap__44c6_s_p5_0,
  131397. 3,
  131398. 3
  131399. };
  131400. static static_codebook _44c6_s_p5_0 = {
  131401. 4, 81,
  131402. _vq_lengthlist__44c6_s_p5_0,
  131403. 1, -529137664, 1618345984, 2, 0,
  131404. _vq_quantlist__44c6_s_p5_0,
  131405. NULL,
  131406. &_vq_auxt__44c6_s_p5_0,
  131407. NULL,
  131408. 0
  131409. };
  131410. static long _vq_quantlist__44c6_s_p5_1[] = {
  131411. 5,
  131412. 4,
  131413. 6,
  131414. 3,
  131415. 7,
  131416. 2,
  131417. 8,
  131418. 1,
  131419. 9,
  131420. 0,
  131421. 10,
  131422. };
  131423. static long _vq_lengthlist__44c6_s_p5_1[] = {
  131424. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  131425. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  131426. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  131427. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  131428. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  131429. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  131430. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  131431. 11,10,10, 7, 7, 8, 8, 8, 8,
  131432. };
  131433. static float _vq_quantthresh__44c6_s_p5_1[] = {
  131434. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131435. 3.5, 4.5,
  131436. };
  131437. static long _vq_quantmap__44c6_s_p5_1[] = {
  131438. 9, 7, 5, 3, 1, 0, 2, 4,
  131439. 6, 8, 10,
  131440. };
  131441. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  131442. _vq_quantthresh__44c6_s_p5_1,
  131443. _vq_quantmap__44c6_s_p5_1,
  131444. 11,
  131445. 11
  131446. };
  131447. static static_codebook _44c6_s_p5_1 = {
  131448. 2, 121,
  131449. _vq_lengthlist__44c6_s_p5_1,
  131450. 1, -531365888, 1611661312, 4, 0,
  131451. _vq_quantlist__44c6_s_p5_1,
  131452. NULL,
  131453. &_vq_auxt__44c6_s_p5_1,
  131454. NULL,
  131455. 0
  131456. };
  131457. static long _vq_quantlist__44c6_s_p6_0[] = {
  131458. 6,
  131459. 5,
  131460. 7,
  131461. 4,
  131462. 8,
  131463. 3,
  131464. 9,
  131465. 2,
  131466. 10,
  131467. 1,
  131468. 11,
  131469. 0,
  131470. 12,
  131471. };
  131472. static long _vq_lengthlist__44c6_s_p6_0[] = {
  131473. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  131474. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  131475. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  131476. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  131477. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  131478. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. };
  131485. static float _vq_quantthresh__44c6_s_p6_0[] = {
  131486. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131487. 12.5, 17.5, 22.5, 27.5,
  131488. };
  131489. static long _vq_quantmap__44c6_s_p6_0[] = {
  131490. 11, 9, 7, 5, 3, 1, 0, 2,
  131491. 4, 6, 8, 10, 12,
  131492. };
  131493. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  131494. _vq_quantthresh__44c6_s_p6_0,
  131495. _vq_quantmap__44c6_s_p6_0,
  131496. 13,
  131497. 13
  131498. };
  131499. static static_codebook _44c6_s_p6_0 = {
  131500. 2, 169,
  131501. _vq_lengthlist__44c6_s_p6_0,
  131502. 1, -526516224, 1616117760, 4, 0,
  131503. _vq_quantlist__44c6_s_p6_0,
  131504. NULL,
  131505. &_vq_auxt__44c6_s_p6_0,
  131506. NULL,
  131507. 0
  131508. };
  131509. static long _vq_quantlist__44c6_s_p6_1[] = {
  131510. 2,
  131511. 1,
  131512. 3,
  131513. 0,
  131514. 4,
  131515. };
  131516. static long _vq_lengthlist__44c6_s_p6_1[] = {
  131517. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  131518. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131519. };
  131520. static float _vq_quantthresh__44c6_s_p6_1[] = {
  131521. -1.5, -0.5, 0.5, 1.5,
  131522. };
  131523. static long _vq_quantmap__44c6_s_p6_1[] = {
  131524. 3, 1, 0, 2, 4,
  131525. };
  131526. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  131527. _vq_quantthresh__44c6_s_p6_1,
  131528. _vq_quantmap__44c6_s_p6_1,
  131529. 5,
  131530. 5
  131531. };
  131532. static static_codebook _44c6_s_p6_1 = {
  131533. 2, 25,
  131534. _vq_lengthlist__44c6_s_p6_1,
  131535. 1, -533725184, 1611661312, 3, 0,
  131536. _vq_quantlist__44c6_s_p6_1,
  131537. NULL,
  131538. &_vq_auxt__44c6_s_p6_1,
  131539. NULL,
  131540. 0
  131541. };
  131542. static long _vq_quantlist__44c6_s_p7_0[] = {
  131543. 6,
  131544. 5,
  131545. 7,
  131546. 4,
  131547. 8,
  131548. 3,
  131549. 9,
  131550. 2,
  131551. 10,
  131552. 1,
  131553. 11,
  131554. 0,
  131555. 12,
  131556. };
  131557. static long _vq_lengthlist__44c6_s_p7_0[] = {
  131558. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  131559. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  131560. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  131561. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  131562. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  131563. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  131564. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  131565. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  131566. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  131567. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  131568. 20,13,13,13,13,13,13,14,14,
  131569. };
  131570. static float _vq_quantthresh__44c6_s_p7_0[] = {
  131571. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  131572. 27.5, 38.5, 49.5, 60.5,
  131573. };
  131574. static long _vq_quantmap__44c6_s_p7_0[] = {
  131575. 11, 9, 7, 5, 3, 1, 0, 2,
  131576. 4, 6, 8, 10, 12,
  131577. };
  131578. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  131579. _vq_quantthresh__44c6_s_p7_0,
  131580. _vq_quantmap__44c6_s_p7_0,
  131581. 13,
  131582. 13
  131583. };
  131584. static static_codebook _44c6_s_p7_0 = {
  131585. 2, 169,
  131586. _vq_lengthlist__44c6_s_p7_0,
  131587. 1, -523206656, 1618345984, 4, 0,
  131588. _vq_quantlist__44c6_s_p7_0,
  131589. NULL,
  131590. &_vq_auxt__44c6_s_p7_0,
  131591. NULL,
  131592. 0
  131593. };
  131594. static long _vq_quantlist__44c6_s_p7_1[] = {
  131595. 5,
  131596. 4,
  131597. 6,
  131598. 3,
  131599. 7,
  131600. 2,
  131601. 8,
  131602. 1,
  131603. 9,
  131604. 0,
  131605. 10,
  131606. };
  131607. static long _vq_lengthlist__44c6_s_p7_1[] = {
  131608. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  131609. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  131610. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  131611. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  131612. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  131613. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  131614. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  131615. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  131616. };
  131617. static float _vq_quantthresh__44c6_s_p7_1[] = {
  131618. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131619. 3.5, 4.5,
  131620. };
  131621. static long _vq_quantmap__44c6_s_p7_1[] = {
  131622. 9, 7, 5, 3, 1, 0, 2, 4,
  131623. 6, 8, 10,
  131624. };
  131625. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  131626. _vq_quantthresh__44c6_s_p7_1,
  131627. _vq_quantmap__44c6_s_p7_1,
  131628. 11,
  131629. 11
  131630. };
  131631. static static_codebook _44c6_s_p7_1 = {
  131632. 2, 121,
  131633. _vq_lengthlist__44c6_s_p7_1,
  131634. 1, -531365888, 1611661312, 4, 0,
  131635. _vq_quantlist__44c6_s_p7_1,
  131636. NULL,
  131637. &_vq_auxt__44c6_s_p7_1,
  131638. NULL,
  131639. 0
  131640. };
  131641. static long _vq_quantlist__44c6_s_p8_0[] = {
  131642. 7,
  131643. 6,
  131644. 8,
  131645. 5,
  131646. 9,
  131647. 4,
  131648. 10,
  131649. 3,
  131650. 11,
  131651. 2,
  131652. 12,
  131653. 1,
  131654. 13,
  131655. 0,
  131656. 14,
  131657. };
  131658. static long _vq_lengthlist__44c6_s_p8_0[] = {
  131659. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  131660. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  131661. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  131662. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  131663. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  131664. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  131665. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  131666. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  131667. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  131668. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  131669. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  131670. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  131671. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  131672. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  131673. 14,
  131674. };
  131675. static float _vq_quantthresh__44c6_s_p8_0[] = {
  131676. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131677. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131678. };
  131679. static long _vq_quantmap__44c6_s_p8_0[] = {
  131680. 13, 11, 9, 7, 5, 3, 1, 0,
  131681. 2, 4, 6, 8, 10, 12, 14,
  131682. };
  131683. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  131684. _vq_quantthresh__44c6_s_p8_0,
  131685. _vq_quantmap__44c6_s_p8_0,
  131686. 15,
  131687. 15
  131688. };
  131689. static static_codebook _44c6_s_p8_0 = {
  131690. 2, 225,
  131691. _vq_lengthlist__44c6_s_p8_0,
  131692. 1, -520986624, 1620377600, 4, 0,
  131693. _vq_quantlist__44c6_s_p8_0,
  131694. NULL,
  131695. &_vq_auxt__44c6_s_p8_0,
  131696. NULL,
  131697. 0
  131698. };
  131699. static long _vq_quantlist__44c6_s_p8_1[] = {
  131700. 10,
  131701. 9,
  131702. 11,
  131703. 8,
  131704. 12,
  131705. 7,
  131706. 13,
  131707. 6,
  131708. 14,
  131709. 5,
  131710. 15,
  131711. 4,
  131712. 16,
  131713. 3,
  131714. 17,
  131715. 2,
  131716. 18,
  131717. 1,
  131718. 19,
  131719. 0,
  131720. 20,
  131721. };
  131722. static long _vq_lengthlist__44c6_s_p8_1[] = {
  131723. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  131724. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  131725. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131726. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131727. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131728. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  131729. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  131730. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  131731. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131732. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131733. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  131734. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  131735. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  131736. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  131737. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  131738. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  131739. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  131740. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  131741. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  131742. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  131743. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  131744. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131745. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131746. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131747. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  131748. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  131749. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  131750. 10,10,10,10,10,10,10,10,10,
  131751. };
  131752. static float _vq_quantthresh__44c6_s_p8_1[] = {
  131753. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131754. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131755. 6.5, 7.5, 8.5, 9.5,
  131756. };
  131757. static long _vq_quantmap__44c6_s_p8_1[] = {
  131758. 19, 17, 15, 13, 11, 9, 7, 5,
  131759. 3, 1, 0, 2, 4, 6, 8, 10,
  131760. 12, 14, 16, 18, 20,
  131761. };
  131762. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  131763. _vq_quantthresh__44c6_s_p8_1,
  131764. _vq_quantmap__44c6_s_p8_1,
  131765. 21,
  131766. 21
  131767. };
  131768. static static_codebook _44c6_s_p8_1 = {
  131769. 2, 441,
  131770. _vq_lengthlist__44c6_s_p8_1,
  131771. 1, -529268736, 1611661312, 5, 0,
  131772. _vq_quantlist__44c6_s_p8_1,
  131773. NULL,
  131774. &_vq_auxt__44c6_s_p8_1,
  131775. NULL,
  131776. 0
  131777. };
  131778. static long _vq_quantlist__44c6_s_p9_0[] = {
  131779. 6,
  131780. 5,
  131781. 7,
  131782. 4,
  131783. 8,
  131784. 3,
  131785. 9,
  131786. 2,
  131787. 10,
  131788. 1,
  131789. 11,
  131790. 0,
  131791. 12,
  131792. };
  131793. static long _vq_lengthlist__44c6_s_p9_0[] = {
  131794. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  131795. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  131796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131797. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  131798. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131799. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131800. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131801. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131802. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131803. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131804. 10,10,10,10,10,10,10,10,10,
  131805. };
  131806. static float _vq_quantthresh__44c6_s_p9_0[] = {
  131807. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  131808. 1592.5, 2229.5, 2866.5, 3503.5,
  131809. };
  131810. static long _vq_quantmap__44c6_s_p9_0[] = {
  131811. 11, 9, 7, 5, 3, 1, 0, 2,
  131812. 4, 6, 8, 10, 12,
  131813. };
  131814. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  131815. _vq_quantthresh__44c6_s_p9_0,
  131816. _vq_quantmap__44c6_s_p9_0,
  131817. 13,
  131818. 13
  131819. };
  131820. static static_codebook _44c6_s_p9_0 = {
  131821. 2, 169,
  131822. _vq_lengthlist__44c6_s_p9_0,
  131823. 1, -511845376, 1630791680, 4, 0,
  131824. _vq_quantlist__44c6_s_p9_0,
  131825. NULL,
  131826. &_vq_auxt__44c6_s_p9_0,
  131827. NULL,
  131828. 0
  131829. };
  131830. static long _vq_quantlist__44c6_s_p9_1[] = {
  131831. 6,
  131832. 5,
  131833. 7,
  131834. 4,
  131835. 8,
  131836. 3,
  131837. 9,
  131838. 2,
  131839. 10,
  131840. 1,
  131841. 11,
  131842. 0,
  131843. 12,
  131844. };
  131845. static long _vq_lengthlist__44c6_s_p9_1[] = {
  131846. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  131847. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  131848. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  131849. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  131850. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  131851. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  131852. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  131853. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  131854. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  131855. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  131856. 15,12,10,11,11,13,11,12,13,
  131857. };
  131858. static float _vq_quantthresh__44c6_s_p9_1[] = {
  131859. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  131860. 122.5, 171.5, 220.5, 269.5,
  131861. };
  131862. static long _vq_quantmap__44c6_s_p9_1[] = {
  131863. 11, 9, 7, 5, 3, 1, 0, 2,
  131864. 4, 6, 8, 10, 12,
  131865. };
  131866. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  131867. _vq_quantthresh__44c6_s_p9_1,
  131868. _vq_quantmap__44c6_s_p9_1,
  131869. 13,
  131870. 13
  131871. };
  131872. static static_codebook _44c6_s_p9_1 = {
  131873. 2, 169,
  131874. _vq_lengthlist__44c6_s_p9_1,
  131875. 1, -518889472, 1622704128, 4, 0,
  131876. _vq_quantlist__44c6_s_p9_1,
  131877. NULL,
  131878. &_vq_auxt__44c6_s_p9_1,
  131879. NULL,
  131880. 0
  131881. };
  131882. static long _vq_quantlist__44c6_s_p9_2[] = {
  131883. 24,
  131884. 23,
  131885. 25,
  131886. 22,
  131887. 26,
  131888. 21,
  131889. 27,
  131890. 20,
  131891. 28,
  131892. 19,
  131893. 29,
  131894. 18,
  131895. 30,
  131896. 17,
  131897. 31,
  131898. 16,
  131899. 32,
  131900. 15,
  131901. 33,
  131902. 14,
  131903. 34,
  131904. 13,
  131905. 35,
  131906. 12,
  131907. 36,
  131908. 11,
  131909. 37,
  131910. 10,
  131911. 38,
  131912. 9,
  131913. 39,
  131914. 8,
  131915. 40,
  131916. 7,
  131917. 41,
  131918. 6,
  131919. 42,
  131920. 5,
  131921. 43,
  131922. 4,
  131923. 44,
  131924. 3,
  131925. 45,
  131926. 2,
  131927. 46,
  131928. 1,
  131929. 47,
  131930. 0,
  131931. 48,
  131932. };
  131933. static long _vq_lengthlist__44c6_s_p9_2[] = {
  131934. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  131935. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131936. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131937. 7,
  131938. };
  131939. static float _vq_quantthresh__44c6_s_p9_2[] = {
  131940. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  131941. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  131942. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131943. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131944. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  131945. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  131946. };
  131947. static long _vq_quantmap__44c6_s_p9_2[] = {
  131948. 47, 45, 43, 41, 39, 37, 35, 33,
  131949. 31, 29, 27, 25, 23, 21, 19, 17,
  131950. 15, 13, 11, 9, 7, 5, 3, 1,
  131951. 0, 2, 4, 6, 8, 10, 12, 14,
  131952. 16, 18, 20, 22, 24, 26, 28, 30,
  131953. 32, 34, 36, 38, 40, 42, 44, 46,
  131954. 48,
  131955. };
  131956. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  131957. _vq_quantthresh__44c6_s_p9_2,
  131958. _vq_quantmap__44c6_s_p9_2,
  131959. 49,
  131960. 49
  131961. };
  131962. static static_codebook _44c6_s_p9_2 = {
  131963. 1, 49,
  131964. _vq_lengthlist__44c6_s_p9_2,
  131965. 1, -526909440, 1611661312, 6, 0,
  131966. _vq_quantlist__44c6_s_p9_2,
  131967. NULL,
  131968. &_vq_auxt__44c6_s_p9_2,
  131969. NULL,
  131970. 0
  131971. };
  131972. static long _huff_lengthlist__44c6_s_short[] = {
  131973. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  131974. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  131975. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  131976. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  131977. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  131978. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  131979. 9,10,17,18,
  131980. };
  131981. static static_codebook _huff_book__44c6_s_short = {
  131982. 2, 100,
  131983. _huff_lengthlist__44c6_s_short,
  131984. 0, 0, 0, 0, 0,
  131985. NULL,
  131986. NULL,
  131987. NULL,
  131988. NULL,
  131989. 0
  131990. };
  131991. static long _huff_lengthlist__44c7_s_long[] = {
  131992. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  131993. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  131994. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  131995. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  131996. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  131997. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  131998. 11,10,10,12,
  131999. };
  132000. static static_codebook _huff_book__44c7_s_long = {
  132001. 2, 100,
  132002. _huff_lengthlist__44c7_s_long,
  132003. 0, 0, 0, 0, 0,
  132004. NULL,
  132005. NULL,
  132006. NULL,
  132007. NULL,
  132008. 0
  132009. };
  132010. static long _vq_quantlist__44c7_s_p1_0[] = {
  132011. 1,
  132012. 0,
  132013. 2,
  132014. };
  132015. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132016. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132017. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132018. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132019. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132020. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132021. 8,
  132022. };
  132023. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132024. -0.5, 0.5,
  132025. };
  132026. static long _vq_quantmap__44c7_s_p1_0[] = {
  132027. 1, 0, 2,
  132028. };
  132029. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132030. _vq_quantthresh__44c7_s_p1_0,
  132031. _vq_quantmap__44c7_s_p1_0,
  132032. 3,
  132033. 3
  132034. };
  132035. static static_codebook _44c7_s_p1_0 = {
  132036. 4, 81,
  132037. _vq_lengthlist__44c7_s_p1_0,
  132038. 1, -535822336, 1611661312, 2, 0,
  132039. _vq_quantlist__44c7_s_p1_0,
  132040. NULL,
  132041. &_vq_auxt__44c7_s_p1_0,
  132042. NULL,
  132043. 0
  132044. };
  132045. static long _vq_quantlist__44c7_s_p2_0[] = {
  132046. 2,
  132047. 1,
  132048. 3,
  132049. 0,
  132050. 4,
  132051. };
  132052. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132053. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132054. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132055. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132056. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132057. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132058. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132059. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132060. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132062. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132063. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132064. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132065. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132066. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132067. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132068. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132070. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132071. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132072. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132073. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132074. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132075. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132076. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132078. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132079. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132080. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132081. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132082. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132083. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132084. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132089. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132090. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132091. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132092. 13,
  132093. };
  132094. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132095. -1.5, -0.5, 0.5, 1.5,
  132096. };
  132097. static long _vq_quantmap__44c7_s_p2_0[] = {
  132098. 3, 1, 0, 2, 4,
  132099. };
  132100. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132101. _vq_quantthresh__44c7_s_p2_0,
  132102. _vq_quantmap__44c7_s_p2_0,
  132103. 5,
  132104. 5
  132105. };
  132106. static static_codebook _44c7_s_p2_0 = {
  132107. 4, 625,
  132108. _vq_lengthlist__44c7_s_p2_0,
  132109. 1, -533725184, 1611661312, 3, 0,
  132110. _vq_quantlist__44c7_s_p2_0,
  132111. NULL,
  132112. &_vq_auxt__44c7_s_p2_0,
  132113. NULL,
  132114. 0
  132115. };
  132116. static long _vq_quantlist__44c7_s_p3_0[] = {
  132117. 4,
  132118. 3,
  132119. 5,
  132120. 2,
  132121. 6,
  132122. 1,
  132123. 7,
  132124. 0,
  132125. 8,
  132126. };
  132127. static long _vq_lengthlist__44c7_s_p3_0[] = {
  132128. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132129. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132130. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132131. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132133. 0,
  132134. };
  132135. static float _vq_quantthresh__44c7_s_p3_0[] = {
  132136. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132137. };
  132138. static long _vq_quantmap__44c7_s_p3_0[] = {
  132139. 7, 5, 3, 1, 0, 2, 4, 6,
  132140. 8,
  132141. };
  132142. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  132143. _vq_quantthresh__44c7_s_p3_0,
  132144. _vq_quantmap__44c7_s_p3_0,
  132145. 9,
  132146. 9
  132147. };
  132148. static static_codebook _44c7_s_p3_0 = {
  132149. 2, 81,
  132150. _vq_lengthlist__44c7_s_p3_0,
  132151. 1, -531628032, 1611661312, 4, 0,
  132152. _vq_quantlist__44c7_s_p3_0,
  132153. NULL,
  132154. &_vq_auxt__44c7_s_p3_0,
  132155. NULL,
  132156. 0
  132157. };
  132158. static long _vq_quantlist__44c7_s_p4_0[] = {
  132159. 8,
  132160. 7,
  132161. 9,
  132162. 6,
  132163. 10,
  132164. 5,
  132165. 11,
  132166. 4,
  132167. 12,
  132168. 3,
  132169. 13,
  132170. 2,
  132171. 14,
  132172. 1,
  132173. 15,
  132174. 0,
  132175. 16,
  132176. };
  132177. static long _vq_lengthlist__44c7_s_p4_0[] = {
  132178. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132179. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  132180. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132181. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  132182. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  132183. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  132184. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  132185. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132186. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132187. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  132188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132196. 0,
  132197. };
  132198. static float _vq_quantthresh__44c7_s_p4_0[] = {
  132199. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132200. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132201. };
  132202. static long _vq_quantmap__44c7_s_p4_0[] = {
  132203. 15, 13, 11, 9, 7, 5, 3, 1,
  132204. 0, 2, 4, 6, 8, 10, 12, 14,
  132205. 16,
  132206. };
  132207. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  132208. _vq_quantthresh__44c7_s_p4_0,
  132209. _vq_quantmap__44c7_s_p4_0,
  132210. 17,
  132211. 17
  132212. };
  132213. static static_codebook _44c7_s_p4_0 = {
  132214. 2, 289,
  132215. _vq_lengthlist__44c7_s_p4_0,
  132216. 1, -529530880, 1611661312, 5, 0,
  132217. _vq_quantlist__44c7_s_p4_0,
  132218. NULL,
  132219. &_vq_auxt__44c7_s_p4_0,
  132220. NULL,
  132221. 0
  132222. };
  132223. static long _vq_quantlist__44c7_s_p5_0[] = {
  132224. 1,
  132225. 0,
  132226. 2,
  132227. };
  132228. static long _vq_lengthlist__44c7_s_p5_0[] = {
  132229. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  132230. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  132231. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  132232. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132233. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  132234. 12,
  132235. };
  132236. static float _vq_quantthresh__44c7_s_p5_0[] = {
  132237. -5.5, 5.5,
  132238. };
  132239. static long _vq_quantmap__44c7_s_p5_0[] = {
  132240. 1, 0, 2,
  132241. };
  132242. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  132243. _vq_quantthresh__44c7_s_p5_0,
  132244. _vq_quantmap__44c7_s_p5_0,
  132245. 3,
  132246. 3
  132247. };
  132248. static static_codebook _44c7_s_p5_0 = {
  132249. 4, 81,
  132250. _vq_lengthlist__44c7_s_p5_0,
  132251. 1, -529137664, 1618345984, 2, 0,
  132252. _vq_quantlist__44c7_s_p5_0,
  132253. NULL,
  132254. &_vq_auxt__44c7_s_p5_0,
  132255. NULL,
  132256. 0
  132257. };
  132258. static long _vq_quantlist__44c7_s_p5_1[] = {
  132259. 5,
  132260. 4,
  132261. 6,
  132262. 3,
  132263. 7,
  132264. 2,
  132265. 8,
  132266. 1,
  132267. 9,
  132268. 0,
  132269. 10,
  132270. };
  132271. static long _vq_lengthlist__44c7_s_p5_1[] = {
  132272. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132273. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  132274. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  132275. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  132276. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  132277. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  132278. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  132279. 11,11,11, 7, 7, 8, 8, 8, 8,
  132280. };
  132281. static float _vq_quantthresh__44c7_s_p5_1[] = {
  132282. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132283. 3.5, 4.5,
  132284. };
  132285. static long _vq_quantmap__44c7_s_p5_1[] = {
  132286. 9, 7, 5, 3, 1, 0, 2, 4,
  132287. 6, 8, 10,
  132288. };
  132289. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  132290. _vq_quantthresh__44c7_s_p5_1,
  132291. _vq_quantmap__44c7_s_p5_1,
  132292. 11,
  132293. 11
  132294. };
  132295. static static_codebook _44c7_s_p5_1 = {
  132296. 2, 121,
  132297. _vq_lengthlist__44c7_s_p5_1,
  132298. 1, -531365888, 1611661312, 4, 0,
  132299. _vq_quantlist__44c7_s_p5_1,
  132300. NULL,
  132301. &_vq_auxt__44c7_s_p5_1,
  132302. NULL,
  132303. 0
  132304. };
  132305. static long _vq_quantlist__44c7_s_p6_0[] = {
  132306. 6,
  132307. 5,
  132308. 7,
  132309. 4,
  132310. 8,
  132311. 3,
  132312. 9,
  132313. 2,
  132314. 10,
  132315. 1,
  132316. 11,
  132317. 0,
  132318. 12,
  132319. };
  132320. static long _vq_lengthlist__44c7_s_p6_0[] = {
  132321. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  132322. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  132323. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  132324. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  132325. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  132326. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  132327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132331. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132332. };
  132333. static float _vq_quantthresh__44c7_s_p6_0[] = {
  132334. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132335. 12.5, 17.5, 22.5, 27.5,
  132336. };
  132337. static long _vq_quantmap__44c7_s_p6_0[] = {
  132338. 11, 9, 7, 5, 3, 1, 0, 2,
  132339. 4, 6, 8, 10, 12,
  132340. };
  132341. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  132342. _vq_quantthresh__44c7_s_p6_0,
  132343. _vq_quantmap__44c7_s_p6_0,
  132344. 13,
  132345. 13
  132346. };
  132347. static static_codebook _44c7_s_p6_0 = {
  132348. 2, 169,
  132349. _vq_lengthlist__44c7_s_p6_0,
  132350. 1, -526516224, 1616117760, 4, 0,
  132351. _vq_quantlist__44c7_s_p6_0,
  132352. NULL,
  132353. &_vq_auxt__44c7_s_p6_0,
  132354. NULL,
  132355. 0
  132356. };
  132357. static long _vq_quantlist__44c7_s_p6_1[] = {
  132358. 2,
  132359. 1,
  132360. 3,
  132361. 0,
  132362. 4,
  132363. };
  132364. static long _vq_lengthlist__44c7_s_p6_1[] = {
  132365. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132366. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132367. };
  132368. static float _vq_quantthresh__44c7_s_p6_1[] = {
  132369. -1.5, -0.5, 0.5, 1.5,
  132370. };
  132371. static long _vq_quantmap__44c7_s_p6_1[] = {
  132372. 3, 1, 0, 2, 4,
  132373. };
  132374. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  132375. _vq_quantthresh__44c7_s_p6_1,
  132376. _vq_quantmap__44c7_s_p6_1,
  132377. 5,
  132378. 5
  132379. };
  132380. static static_codebook _44c7_s_p6_1 = {
  132381. 2, 25,
  132382. _vq_lengthlist__44c7_s_p6_1,
  132383. 1, -533725184, 1611661312, 3, 0,
  132384. _vq_quantlist__44c7_s_p6_1,
  132385. NULL,
  132386. &_vq_auxt__44c7_s_p6_1,
  132387. NULL,
  132388. 0
  132389. };
  132390. static long _vq_quantlist__44c7_s_p7_0[] = {
  132391. 6,
  132392. 5,
  132393. 7,
  132394. 4,
  132395. 8,
  132396. 3,
  132397. 9,
  132398. 2,
  132399. 10,
  132400. 1,
  132401. 11,
  132402. 0,
  132403. 12,
  132404. };
  132405. static long _vq_lengthlist__44c7_s_p7_0[] = {
  132406. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  132407. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  132408. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  132409. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  132410. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  132411. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  132412. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  132413. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  132414. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  132415. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  132416. 19,13,13,13,13,14,14,15,15,
  132417. };
  132418. static float _vq_quantthresh__44c7_s_p7_0[] = {
  132419. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132420. 27.5, 38.5, 49.5, 60.5,
  132421. };
  132422. static long _vq_quantmap__44c7_s_p7_0[] = {
  132423. 11, 9, 7, 5, 3, 1, 0, 2,
  132424. 4, 6, 8, 10, 12,
  132425. };
  132426. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  132427. _vq_quantthresh__44c7_s_p7_0,
  132428. _vq_quantmap__44c7_s_p7_0,
  132429. 13,
  132430. 13
  132431. };
  132432. static static_codebook _44c7_s_p7_0 = {
  132433. 2, 169,
  132434. _vq_lengthlist__44c7_s_p7_0,
  132435. 1, -523206656, 1618345984, 4, 0,
  132436. _vq_quantlist__44c7_s_p7_0,
  132437. NULL,
  132438. &_vq_auxt__44c7_s_p7_0,
  132439. NULL,
  132440. 0
  132441. };
  132442. static long _vq_quantlist__44c7_s_p7_1[] = {
  132443. 5,
  132444. 4,
  132445. 6,
  132446. 3,
  132447. 7,
  132448. 2,
  132449. 8,
  132450. 1,
  132451. 9,
  132452. 0,
  132453. 10,
  132454. };
  132455. static long _vq_lengthlist__44c7_s_p7_1[] = {
  132456. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  132457. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  132458. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  132459. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132460. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  132461. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  132462. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  132463. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132464. };
  132465. static float _vq_quantthresh__44c7_s_p7_1[] = {
  132466. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132467. 3.5, 4.5,
  132468. };
  132469. static long _vq_quantmap__44c7_s_p7_1[] = {
  132470. 9, 7, 5, 3, 1, 0, 2, 4,
  132471. 6, 8, 10,
  132472. };
  132473. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  132474. _vq_quantthresh__44c7_s_p7_1,
  132475. _vq_quantmap__44c7_s_p7_1,
  132476. 11,
  132477. 11
  132478. };
  132479. static static_codebook _44c7_s_p7_1 = {
  132480. 2, 121,
  132481. _vq_lengthlist__44c7_s_p7_1,
  132482. 1, -531365888, 1611661312, 4, 0,
  132483. _vq_quantlist__44c7_s_p7_1,
  132484. NULL,
  132485. &_vq_auxt__44c7_s_p7_1,
  132486. NULL,
  132487. 0
  132488. };
  132489. static long _vq_quantlist__44c7_s_p8_0[] = {
  132490. 7,
  132491. 6,
  132492. 8,
  132493. 5,
  132494. 9,
  132495. 4,
  132496. 10,
  132497. 3,
  132498. 11,
  132499. 2,
  132500. 12,
  132501. 1,
  132502. 13,
  132503. 0,
  132504. 14,
  132505. };
  132506. static long _vq_lengthlist__44c7_s_p8_0[] = {
  132507. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  132508. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  132509. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  132510. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  132511. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  132512. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  132513. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  132514. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  132515. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  132516. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  132517. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  132518. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  132519. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  132520. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  132521. 14,
  132522. };
  132523. static float _vq_quantthresh__44c7_s_p8_0[] = {
  132524. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132525. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132526. };
  132527. static long _vq_quantmap__44c7_s_p8_0[] = {
  132528. 13, 11, 9, 7, 5, 3, 1, 0,
  132529. 2, 4, 6, 8, 10, 12, 14,
  132530. };
  132531. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  132532. _vq_quantthresh__44c7_s_p8_0,
  132533. _vq_quantmap__44c7_s_p8_0,
  132534. 15,
  132535. 15
  132536. };
  132537. static static_codebook _44c7_s_p8_0 = {
  132538. 2, 225,
  132539. _vq_lengthlist__44c7_s_p8_0,
  132540. 1, -520986624, 1620377600, 4, 0,
  132541. _vq_quantlist__44c7_s_p8_0,
  132542. NULL,
  132543. &_vq_auxt__44c7_s_p8_0,
  132544. NULL,
  132545. 0
  132546. };
  132547. static long _vq_quantlist__44c7_s_p8_1[] = {
  132548. 10,
  132549. 9,
  132550. 11,
  132551. 8,
  132552. 12,
  132553. 7,
  132554. 13,
  132555. 6,
  132556. 14,
  132557. 5,
  132558. 15,
  132559. 4,
  132560. 16,
  132561. 3,
  132562. 17,
  132563. 2,
  132564. 18,
  132565. 1,
  132566. 19,
  132567. 0,
  132568. 20,
  132569. };
  132570. static long _vq_lengthlist__44c7_s_p8_1[] = {
  132571. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  132572. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  132573. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132574. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132575. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132576. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  132577. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  132578. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  132579. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132580. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132581. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  132582. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  132583. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  132584. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  132585. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  132586. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  132587. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  132588. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132589. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  132590. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  132591. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  132592. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  132593. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  132594. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  132595. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  132596. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  132597. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  132598. 10,10,10,10,10,10,10,10,10,
  132599. };
  132600. static float _vq_quantthresh__44c7_s_p8_1[] = {
  132601. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132602. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132603. 6.5, 7.5, 8.5, 9.5,
  132604. };
  132605. static long _vq_quantmap__44c7_s_p8_1[] = {
  132606. 19, 17, 15, 13, 11, 9, 7, 5,
  132607. 3, 1, 0, 2, 4, 6, 8, 10,
  132608. 12, 14, 16, 18, 20,
  132609. };
  132610. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  132611. _vq_quantthresh__44c7_s_p8_1,
  132612. _vq_quantmap__44c7_s_p8_1,
  132613. 21,
  132614. 21
  132615. };
  132616. static static_codebook _44c7_s_p8_1 = {
  132617. 2, 441,
  132618. _vq_lengthlist__44c7_s_p8_1,
  132619. 1, -529268736, 1611661312, 5, 0,
  132620. _vq_quantlist__44c7_s_p8_1,
  132621. NULL,
  132622. &_vq_auxt__44c7_s_p8_1,
  132623. NULL,
  132624. 0
  132625. };
  132626. static long _vq_quantlist__44c7_s_p9_0[] = {
  132627. 6,
  132628. 5,
  132629. 7,
  132630. 4,
  132631. 8,
  132632. 3,
  132633. 9,
  132634. 2,
  132635. 10,
  132636. 1,
  132637. 11,
  132638. 0,
  132639. 12,
  132640. };
  132641. static long _vq_lengthlist__44c7_s_p9_0[] = {
  132642. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  132643. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  132644. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132645. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132648. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132649. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132650. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132652. 11,11,11,11,11,11,11,11,11,
  132653. };
  132654. static float _vq_quantthresh__44c7_s_p9_0[] = {
  132655. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132656. 1592.5, 2229.5, 2866.5, 3503.5,
  132657. };
  132658. static long _vq_quantmap__44c7_s_p9_0[] = {
  132659. 11, 9, 7, 5, 3, 1, 0, 2,
  132660. 4, 6, 8, 10, 12,
  132661. };
  132662. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  132663. _vq_quantthresh__44c7_s_p9_0,
  132664. _vq_quantmap__44c7_s_p9_0,
  132665. 13,
  132666. 13
  132667. };
  132668. static static_codebook _44c7_s_p9_0 = {
  132669. 2, 169,
  132670. _vq_lengthlist__44c7_s_p9_0,
  132671. 1, -511845376, 1630791680, 4, 0,
  132672. _vq_quantlist__44c7_s_p9_0,
  132673. NULL,
  132674. &_vq_auxt__44c7_s_p9_0,
  132675. NULL,
  132676. 0
  132677. };
  132678. static long _vq_quantlist__44c7_s_p9_1[] = {
  132679. 6,
  132680. 5,
  132681. 7,
  132682. 4,
  132683. 8,
  132684. 3,
  132685. 9,
  132686. 2,
  132687. 10,
  132688. 1,
  132689. 11,
  132690. 0,
  132691. 12,
  132692. };
  132693. static long _vq_lengthlist__44c7_s_p9_1[] = {
  132694. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132695. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  132696. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  132697. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  132698. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  132699. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  132700. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  132701. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  132702. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  132703. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  132704. 15,11,11,10,10,12,12,12,12,
  132705. };
  132706. static float _vq_quantthresh__44c7_s_p9_1[] = {
  132707. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132708. 122.5, 171.5, 220.5, 269.5,
  132709. };
  132710. static long _vq_quantmap__44c7_s_p9_1[] = {
  132711. 11, 9, 7, 5, 3, 1, 0, 2,
  132712. 4, 6, 8, 10, 12,
  132713. };
  132714. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  132715. _vq_quantthresh__44c7_s_p9_1,
  132716. _vq_quantmap__44c7_s_p9_1,
  132717. 13,
  132718. 13
  132719. };
  132720. static static_codebook _44c7_s_p9_1 = {
  132721. 2, 169,
  132722. _vq_lengthlist__44c7_s_p9_1,
  132723. 1, -518889472, 1622704128, 4, 0,
  132724. _vq_quantlist__44c7_s_p9_1,
  132725. NULL,
  132726. &_vq_auxt__44c7_s_p9_1,
  132727. NULL,
  132728. 0
  132729. };
  132730. static long _vq_quantlist__44c7_s_p9_2[] = {
  132731. 24,
  132732. 23,
  132733. 25,
  132734. 22,
  132735. 26,
  132736. 21,
  132737. 27,
  132738. 20,
  132739. 28,
  132740. 19,
  132741. 29,
  132742. 18,
  132743. 30,
  132744. 17,
  132745. 31,
  132746. 16,
  132747. 32,
  132748. 15,
  132749. 33,
  132750. 14,
  132751. 34,
  132752. 13,
  132753. 35,
  132754. 12,
  132755. 36,
  132756. 11,
  132757. 37,
  132758. 10,
  132759. 38,
  132760. 9,
  132761. 39,
  132762. 8,
  132763. 40,
  132764. 7,
  132765. 41,
  132766. 6,
  132767. 42,
  132768. 5,
  132769. 43,
  132770. 4,
  132771. 44,
  132772. 3,
  132773. 45,
  132774. 2,
  132775. 46,
  132776. 1,
  132777. 47,
  132778. 0,
  132779. 48,
  132780. };
  132781. static long _vq_lengthlist__44c7_s_p9_2[] = {
  132782. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132783. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132784. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132785. 7,
  132786. };
  132787. static float _vq_quantthresh__44c7_s_p9_2[] = {
  132788. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132789. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132790. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132791. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132792. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132793. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132794. };
  132795. static long _vq_quantmap__44c7_s_p9_2[] = {
  132796. 47, 45, 43, 41, 39, 37, 35, 33,
  132797. 31, 29, 27, 25, 23, 21, 19, 17,
  132798. 15, 13, 11, 9, 7, 5, 3, 1,
  132799. 0, 2, 4, 6, 8, 10, 12, 14,
  132800. 16, 18, 20, 22, 24, 26, 28, 30,
  132801. 32, 34, 36, 38, 40, 42, 44, 46,
  132802. 48,
  132803. };
  132804. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  132805. _vq_quantthresh__44c7_s_p9_2,
  132806. _vq_quantmap__44c7_s_p9_2,
  132807. 49,
  132808. 49
  132809. };
  132810. static static_codebook _44c7_s_p9_2 = {
  132811. 1, 49,
  132812. _vq_lengthlist__44c7_s_p9_2,
  132813. 1, -526909440, 1611661312, 6, 0,
  132814. _vq_quantlist__44c7_s_p9_2,
  132815. NULL,
  132816. &_vq_auxt__44c7_s_p9_2,
  132817. NULL,
  132818. 0
  132819. };
  132820. static long _huff_lengthlist__44c7_s_short[] = {
  132821. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  132822. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  132823. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  132824. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  132825. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  132826. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  132827. 10, 9,11,14,
  132828. };
  132829. static static_codebook _huff_book__44c7_s_short = {
  132830. 2, 100,
  132831. _huff_lengthlist__44c7_s_short,
  132832. 0, 0, 0, 0, 0,
  132833. NULL,
  132834. NULL,
  132835. NULL,
  132836. NULL,
  132837. 0
  132838. };
  132839. static long _huff_lengthlist__44c8_s_long[] = {
  132840. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  132841. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  132842. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  132843. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  132844. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  132845. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  132846. 11, 9, 9,10,
  132847. };
  132848. static static_codebook _huff_book__44c8_s_long = {
  132849. 2, 100,
  132850. _huff_lengthlist__44c8_s_long,
  132851. 0, 0, 0, 0, 0,
  132852. NULL,
  132853. NULL,
  132854. NULL,
  132855. NULL,
  132856. 0
  132857. };
  132858. static long _vq_quantlist__44c8_s_p1_0[] = {
  132859. 1,
  132860. 0,
  132861. 2,
  132862. };
  132863. static long _vq_lengthlist__44c8_s_p1_0[] = {
  132864. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  132865. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132866. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132867. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132868. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132869. 8,
  132870. };
  132871. static float _vq_quantthresh__44c8_s_p1_0[] = {
  132872. -0.5, 0.5,
  132873. };
  132874. static long _vq_quantmap__44c8_s_p1_0[] = {
  132875. 1, 0, 2,
  132876. };
  132877. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  132878. _vq_quantthresh__44c8_s_p1_0,
  132879. _vq_quantmap__44c8_s_p1_0,
  132880. 3,
  132881. 3
  132882. };
  132883. static static_codebook _44c8_s_p1_0 = {
  132884. 4, 81,
  132885. _vq_lengthlist__44c8_s_p1_0,
  132886. 1, -535822336, 1611661312, 2, 0,
  132887. _vq_quantlist__44c8_s_p1_0,
  132888. NULL,
  132889. &_vq_auxt__44c8_s_p1_0,
  132890. NULL,
  132891. 0
  132892. };
  132893. static long _vq_quantlist__44c8_s_p2_0[] = {
  132894. 2,
  132895. 1,
  132896. 3,
  132897. 0,
  132898. 4,
  132899. };
  132900. static long _vq_lengthlist__44c8_s_p2_0[] = {
  132901. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132902. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132903. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132904. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  132905. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132906. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  132907. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  132908. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132910. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132911. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  132912. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132913. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  132914. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  132915. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  132916. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  132917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132918. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  132919. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  132920. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  132921. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  132922. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  132923. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  132924. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132926. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132927. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  132928. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132929. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  132930. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  132931. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  132932. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132937. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  132938. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132939. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  132940. 13,
  132941. };
  132942. static float _vq_quantthresh__44c8_s_p2_0[] = {
  132943. -1.5, -0.5, 0.5, 1.5,
  132944. };
  132945. static long _vq_quantmap__44c8_s_p2_0[] = {
  132946. 3, 1, 0, 2, 4,
  132947. };
  132948. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  132949. _vq_quantthresh__44c8_s_p2_0,
  132950. _vq_quantmap__44c8_s_p2_0,
  132951. 5,
  132952. 5
  132953. };
  132954. static static_codebook _44c8_s_p2_0 = {
  132955. 4, 625,
  132956. _vq_lengthlist__44c8_s_p2_0,
  132957. 1, -533725184, 1611661312, 3, 0,
  132958. _vq_quantlist__44c8_s_p2_0,
  132959. NULL,
  132960. &_vq_auxt__44c8_s_p2_0,
  132961. NULL,
  132962. 0
  132963. };
  132964. static long _vq_quantlist__44c8_s_p3_0[] = {
  132965. 4,
  132966. 3,
  132967. 5,
  132968. 2,
  132969. 6,
  132970. 1,
  132971. 7,
  132972. 0,
  132973. 8,
  132974. };
  132975. static long _vq_lengthlist__44c8_s_p3_0[] = {
  132976. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132977. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132978. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132979. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132981. 0,
  132982. };
  132983. static float _vq_quantthresh__44c8_s_p3_0[] = {
  132984. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132985. };
  132986. static long _vq_quantmap__44c8_s_p3_0[] = {
  132987. 7, 5, 3, 1, 0, 2, 4, 6,
  132988. 8,
  132989. };
  132990. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  132991. _vq_quantthresh__44c8_s_p3_0,
  132992. _vq_quantmap__44c8_s_p3_0,
  132993. 9,
  132994. 9
  132995. };
  132996. static static_codebook _44c8_s_p3_0 = {
  132997. 2, 81,
  132998. _vq_lengthlist__44c8_s_p3_0,
  132999. 1, -531628032, 1611661312, 4, 0,
  133000. _vq_quantlist__44c8_s_p3_0,
  133001. NULL,
  133002. &_vq_auxt__44c8_s_p3_0,
  133003. NULL,
  133004. 0
  133005. };
  133006. static long _vq_quantlist__44c8_s_p4_0[] = {
  133007. 8,
  133008. 7,
  133009. 9,
  133010. 6,
  133011. 10,
  133012. 5,
  133013. 11,
  133014. 4,
  133015. 12,
  133016. 3,
  133017. 13,
  133018. 2,
  133019. 14,
  133020. 1,
  133021. 15,
  133022. 0,
  133023. 16,
  133024. };
  133025. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133026. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133027. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133028. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133029. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133030. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133031. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133032. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133033. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133034. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133035. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133044. 0,
  133045. };
  133046. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133047. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133048. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133049. };
  133050. static long _vq_quantmap__44c8_s_p4_0[] = {
  133051. 15, 13, 11, 9, 7, 5, 3, 1,
  133052. 0, 2, 4, 6, 8, 10, 12, 14,
  133053. 16,
  133054. };
  133055. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133056. _vq_quantthresh__44c8_s_p4_0,
  133057. _vq_quantmap__44c8_s_p4_0,
  133058. 17,
  133059. 17
  133060. };
  133061. static static_codebook _44c8_s_p4_0 = {
  133062. 2, 289,
  133063. _vq_lengthlist__44c8_s_p4_0,
  133064. 1, -529530880, 1611661312, 5, 0,
  133065. _vq_quantlist__44c8_s_p4_0,
  133066. NULL,
  133067. &_vq_auxt__44c8_s_p4_0,
  133068. NULL,
  133069. 0
  133070. };
  133071. static long _vq_quantlist__44c8_s_p5_0[] = {
  133072. 1,
  133073. 0,
  133074. 2,
  133075. };
  133076. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133077. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133078. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133079. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133080. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133081. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133082. 12,
  133083. };
  133084. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133085. -5.5, 5.5,
  133086. };
  133087. static long _vq_quantmap__44c8_s_p5_0[] = {
  133088. 1, 0, 2,
  133089. };
  133090. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133091. _vq_quantthresh__44c8_s_p5_0,
  133092. _vq_quantmap__44c8_s_p5_0,
  133093. 3,
  133094. 3
  133095. };
  133096. static static_codebook _44c8_s_p5_0 = {
  133097. 4, 81,
  133098. _vq_lengthlist__44c8_s_p5_0,
  133099. 1, -529137664, 1618345984, 2, 0,
  133100. _vq_quantlist__44c8_s_p5_0,
  133101. NULL,
  133102. &_vq_auxt__44c8_s_p5_0,
  133103. NULL,
  133104. 0
  133105. };
  133106. static long _vq_quantlist__44c8_s_p5_1[] = {
  133107. 5,
  133108. 4,
  133109. 6,
  133110. 3,
  133111. 7,
  133112. 2,
  133113. 8,
  133114. 1,
  133115. 9,
  133116. 0,
  133117. 10,
  133118. };
  133119. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133120. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133121. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133122. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133123. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133124. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  133125. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  133126. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  133127. 11,11,11, 7, 7, 7, 7, 8, 8,
  133128. };
  133129. static float _vq_quantthresh__44c8_s_p5_1[] = {
  133130. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133131. 3.5, 4.5,
  133132. };
  133133. static long _vq_quantmap__44c8_s_p5_1[] = {
  133134. 9, 7, 5, 3, 1, 0, 2, 4,
  133135. 6, 8, 10,
  133136. };
  133137. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  133138. _vq_quantthresh__44c8_s_p5_1,
  133139. _vq_quantmap__44c8_s_p5_1,
  133140. 11,
  133141. 11
  133142. };
  133143. static static_codebook _44c8_s_p5_1 = {
  133144. 2, 121,
  133145. _vq_lengthlist__44c8_s_p5_1,
  133146. 1, -531365888, 1611661312, 4, 0,
  133147. _vq_quantlist__44c8_s_p5_1,
  133148. NULL,
  133149. &_vq_auxt__44c8_s_p5_1,
  133150. NULL,
  133151. 0
  133152. };
  133153. static long _vq_quantlist__44c8_s_p6_0[] = {
  133154. 6,
  133155. 5,
  133156. 7,
  133157. 4,
  133158. 8,
  133159. 3,
  133160. 9,
  133161. 2,
  133162. 10,
  133163. 1,
  133164. 11,
  133165. 0,
  133166. 12,
  133167. };
  133168. static long _vq_lengthlist__44c8_s_p6_0[] = {
  133169. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  133170. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  133171. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  133172. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  133173. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  133174. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  133175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133179. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133180. };
  133181. static float _vq_quantthresh__44c8_s_p6_0[] = {
  133182. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133183. 12.5, 17.5, 22.5, 27.5,
  133184. };
  133185. static long _vq_quantmap__44c8_s_p6_0[] = {
  133186. 11, 9, 7, 5, 3, 1, 0, 2,
  133187. 4, 6, 8, 10, 12,
  133188. };
  133189. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  133190. _vq_quantthresh__44c8_s_p6_0,
  133191. _vq_quantmap__44c8_s_p6_0,
  133192. 13,
  133193. 13
  133194. };
  133195. static static_codebook _44c8_s_p6_0 = {
  133196. 2, 169,
  133197. _vq_lengthlist__44c8_s_p6_0,
  133198. 1, -526516224, 1616117760, 4, 0,
  133199. _vq_quantlist__44c8_s_p6_0,
  133200. NULL,
  133201. &_vq_auxt__44c8_s_p6_0,
  133202. NULL,
  133203. 0
  133204. };
  133205. static long _vq_quantlist__44c8_s_p6_1[] = {
  133206. 2,
  133207. 1,
  133208. 3,
  133209. 0,
  133210. 4,
  133211. };
  133212. static long _vq_lengthlist__44c8_s_p6_1[] = {
  133213. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133214. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133215. };
  133216. static float _vq_quantthresh__44c8_s_p6_1[] = {
  133217. -1.5, -0.5, 0.5, 1.5,
  133218. };
  133219. static long _vq_quantmap__44c8_s_p6_1[] = {
  133220. 3, 1, 0, 2, 4,
  133221. };
  133222. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  133223. _vq_quantthresh__44c8_s_p6_1,
  133224. _vq_quantmap__44c8_s_p6_1,
  133225. 5,
  133226. 5
  133227. };
  133228. static static_codebook _44c8_s_p6_1 = {
  133229. 2, 25,
  133230. _vq_lengthlist__44c8_s_p6_1,
  133231. 1, -533725184, 1611661312, 3, 0,
  133232. _vq_quantlist__44c8_s_p6_1,
  133233. NULL,
  133234. &_vq_auxt__44c8_s_p6_1,
  133235. NULL,
  133236. 0
  133237. };
  133238. static long _vq_quantlist__44c8_s_p7_0[] = {
  133239. 6,
  133240. 5,
  133241. 7,
  133242. 4,
  133243. 8,
  133244. 3,
  133245. 9,
  133246. 2,
  133247. 10,
  133248. 1,
  133249. 11,
  133250. 0,
  133251. 12,
  133252. };
  133253. static long _vq_lengthlist__44c8_s_p7_0[] = {
  133254. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  133255. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133256. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  133257. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  133258. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  133259. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  133260. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  133261. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  133262. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  133263. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  133264. 20,13,13,13,13,14,13,15,15,
  133265. };
  133266. static float _vq_quantthresh__44c8_s_p7_0[] = {
  133267. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133268. 27.5, 38.5, 49.5, 60.5,
  133269. };
  133270. static long _vq_quantmap__44c8_s_p7_0[] = {
  133271. 11, 9, 7, 5, 3, 1, 0, 2,
  133272. 4, 6, 8, 10, 12,
  133273. };
  133274. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  133275. _vq_quantthresh__44c8_s_p7_0,
  133276. _vq_quantmap__44c8_s_p7_0,
  133277. 13,
  133278. 13
  133279. };
  133280. static static_codebook _44c8_s_p7_0 = {
  133281. 2, 169,
  133282. _vq_lengthlist__44c8_s_p7_0,
  133283. 1, -523206656, 1618345984, 4, 0,
  133284. _vq_quantlist__44c8_s_p7_0,
  133285. NULL,
  133286. &_vq_auxt__44c8_s_p7_0,
  133287. NULL,
  133288. 0
  133289. };
  133290. static long _vq_quantlist__44c8_s_p7_1[] = {
  133291. 5,
  133292. 4,
  133293. 6,
  133294. 3,
  133295. 7,
  133296. 2,
  133297. 8,
  133298. 1,
  133299. 9,
  133300. 0,
  133301. 10,
  133302. };
  133303. static long _vq_lengthlist__44c8_s_p7_1[] = {
  133304. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  133305. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  133306. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133307. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133308. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133309. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133310. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133311. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133312. };
  133313. static float _vq_quantthresh__44c8_s_p7_1[] = {
  133314. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133315. 3.5, 4.5,
  133316. };
  133317. static long _vq_quantmap__44c8_s_p7_1[] = {
  133318. 9, 7, 5, 3, 1, 0, 2, 4,
  133319. 6, 8, 10,
  133320. };
  133321. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  133322. _vq_quantthresh__44c8_s_p7_1,
  133323. _vq_quantmap__44c8_s_p7_1,
  133324. 11,
  133325. 11
  133326. };
  133327. static static_codebook _44c8_s_p7_1 = {
  133328. 2, 121,
  133329. _vq_lengthlist__44c8_s_p7_1,
  133330. 1, -531365888, 1611661312, 4, 0,
  133331. _vq_quantlist__44c8_s_p7_1,
  133332. NULL,
  133333. &_vq_auxt__44c8_s_p7_1,
  133334. NULL,
  133335. 0
  133336. };
  133337. static long _vq_quantlist__44c8_s_p8_0[] = {
  133338. 7,
  133339. 6,
  133340. 8,
  133341. 5,
  133342. 9,
  133343. 4,
  133344. 10,
  133345. 3,
  133346. 11,
  133347. 2,
  133348. 12,
  133349. 1,
  133350. 13,
  133351. 0,
  133352. 14,
  133353. };
  133354. static long _vq_lengthlist__44c8_s_p8_0[] = {
  133355. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  133356. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  133357. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  133358. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  133359. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  133360. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  133361. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  133362. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  133363. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  133364. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  133365. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  133366. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133367. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  133368. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  133369. 15,
  133370. };
  133371. static float _vq_quantthresh__44c8_s_p8_0[] = {
  133372. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133373. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133374. };
  133375. static long _vq_quantmap__44c8_s_p8_0[] = {
  133376. 13, 11, 9, 7, 5, 3, 1, 0,
  133377. 2, 4, 6, 8, 10, 12, 14,
  133378. };
  133379. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  133380. _vq_quantthresh__44c8_s_p8_0,
  133381. _vq_quantmap__44c8_s_p8_0,
  133382. 15,
  133383. 15
  133384. };
  133385. static static_codebook _44c8_s_p8_0 = {
  133386. 2, 225,
  133387. _vq_lengthlist__44c8_s_p8_0,
  133388. 1, -520986624, 1620377600, 4, 0,
  133389. _vq_quantlist__44c8_s_p8_0,
  133390. NULL,
  133391. &_vq_auxt__44c8_s_p8_0,
  133392. NULL,
  133393. 0
  133394. };
  133395. static long _vq_quantlist__44c8_s_p8_1[] = {
  133396. 10,
  133397. 9,
  133398. 11,
  133399. 8,
  133400. 12,
  133401. 7,
  133402. 13,
  133403. 6,
  133404. 14,
  133405. 5,
  133406. 15,
  133407. 4,
  133408. 16,
  133409. 3,
  133410. 17,
  133411. 2,
  133412. 18,
  133413. 1,
  133414. 19,
  133415. 0,
  133416. 20,
  133417. };
  133418. static long _vq_lengthlist__44c8_s_p8_1[] = {
  133419. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133420. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133421. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133422. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133423. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133424. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133425. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133426. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133427. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133428. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133429. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  133430. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  133431. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  133432. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133433. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  133434. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  133435. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  133436. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  133437. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  133438. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  133439. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  133440. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  133441. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  133442. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  133443. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  133444. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  133445. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  133446. 10, 9, 9,10,10, 9,10, 9, 9,
  133447. };
  133448. static float _vq_quantthresh__44c8_s_p8_1[] = {
  133449. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133450. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133451. 6.5, 7.5, 8.5, 9.5,
  133452. };
  133453. static long _vq_quantmap__44c8_s_p8_1[] = {
  133454. 19, 17, 15, 13, 11, 9, 7, 5,
  133455. 3, 1, 0, 2, 4, 6, 8, 10,
  133456. 12, 14, 16, 18, 20,
  133457. };
  133458. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  133459. _vq_quantthresh__44c8_s_p8_1,
  133460. _vq_quantmap__44c8_s_p8_1,
  133461. 21,
  133462. 21
  133463. };
  133464. static static_codebook _44c8_s_p8_1 = {
  133465. 2, 441,
  133466. _vq_lengthlist__44c8_s_p8_1,
  133467. 1, -529268736, 1611661312, 5, 0,
  133468. _vq_quantlist__44c8_s_p8_1,
  133469. NULL,
  133470. &_vq_auxt__44c8_s_p8_1,
  133471. NULL,
  133472. 0
  133473. };
  133474. static long _vq_quantlist__44c8_s_p9_0[] = {
  133475. 8,
  133476. 7,
  133477. 9,
  133478. 6,
  133479. 10,
  133480. 5,
  133481. 11,
  133482. 4,
  133483. 12,
  133484. 3,
  133485. 13,
  133486. 2,
  133487. 14,
  133488. 1,
  133489. 15,
  133490. 0,
  133491. 16,
  133492. };
  133493. static long _vq_lengthlist__44c8_s_p9_0[] = {
  133494. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133495. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  133496. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  133497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133502. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133503. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133504. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133508. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133509. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133510. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133511. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133512. 10,
  133513. };
  133514. static float _vq_quantthresh__44c8_s_p9_0[] = {
  133515. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  133516. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  133517. };
  133518. static long _vq_quantmap__44c8_s_p9_0[] = {
  133519. 15, 13, 11, 9, 7, 5, 3, 1,
  133520. 0, 2, 4, 6, 8, 10, 12, 14,
  133521. 16,
  133522. };
  133523. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  133524. _vq_quantthresh__44c8_s_p9_0,
  133525. _vq_quantmap__44c8_s_p9_0,
  133526. 17,
  133527. 17
  133528. };
  133529. static static_codebook _44c8_s_p9_0 = {
  133530. 2, 289,
  133531. _vq_lengthlist__44c8_s_p9_0,
  133532. 1, -509798400, 1631393792, 5, 0,
  133533. _vq_quantlist__44c8_s_p9_0,
  133534. NULL,
  133535. &_vq_auxt__44c8_s_p9_0,
  133536. NULL,
  133537. 0
  133538. };
  133539. static long _vq_quantlist__44c8_s_p9_1[] = {
  133540. 9,
  133541. 8,
  133542. 10,
  133543. 7,
  133544. 11,
  133545. 6,
  133546. 12,
  133547. 5,
  133548. 13,
  133549. 4,
  133550. 14,
  133551. 3,
  133552. 15,
  133553. 2,
  133554. 16,
  133555. 1,
  133556. 17,
  133557. 0,
  133558. 18,
  133559. };
  133560. static long _vq_lengthlist__44c8_s_p9_1[] = {
  133561. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  133562. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  133563. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  133564. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  133565. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  133566. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  133567. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  133568. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  133569. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  133570. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  133571. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  133572. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  133573. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  133574. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  133575. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  133576. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  133577. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  133578. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  133579. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  133580. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  133581. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  133582. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  133583. 14,13,13,14,14,15,14,15,14,
  133584. };
  133585. static float _vq_quantthresh__44c8_s_p9_1[] = {
  133586. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  133587. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  133588. 367.5, 416.5,
  133589. };
  133590. static long _vq_quantmap__44c8_s_p9_1[] = {
  133591. 17, 15, 13, 11, 9, 7, 5, 3,
  133592. 1, 0, 2, 4, 6, 8, 10, 12,
  133593. 14, 16, 18,
  133594. };
  133595. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  133596. _vq_quantthresh__44c8_s_p9_1,
  133597. _vq_quantmap__44c8_s_p9_1,
  133598. 19,
  133599. 19
  133600. };
  133601. static static_codebook _44c8_s_p9_1 = {
  133602. 2, 361,
  133603. _vq_lengthlist__44c8_s_p9_1,
  133604. 1, -518287360, 1622704128, 5, 0,
  133605. _vq_quantlist__44c8_s_p9_1,
  133606. NULL,
  133607. &_vq_auxt__44c8_s_p9_1,
  133608. NULL,
  133609. 0
  133610. };
  133611. static long _vq_quantlist__44c8_s_p9_2[] = {
  133612. 24,
  133613. 23,
  133614. 25,
  133615. 22,
  133616. 26,
  133617. 21,
  133618. 27,
  133619. 20,
  133620. 28,
  133621. 19,
  133622. 29,
  133623. 18,
  133624. 30,
  133625. 17,
  133626. 31,
  133627. 16,
  133628. 32,
  133629. 15,
  133630. 33,
  133631. 14,
  133632. 34,
  133633. 13,
  133634. 35,
  133635. 12,
  133636. 36,
  133637. 11,
  133638. 37,
  133639. 10,
  133640. 38,
  133641. 9,
  133642. 39,
  133643. 8,
  133644. 40,
  133645. 7,
  133646. 41,
  133647. 6,
  133648. 42,
  133649. 5,
  133650. 43,
  133651. 4,
  133652. 44,
  133653. 3,
  133654. 45,
  133655. 2,
  133656. 46,
  133657. 1,
  133658. 47,
  133659. 0,
  133660. 48,
  133661. };
  133662. static long _vq_lengthlist__44c8_s_p9_2[] = {
  133663. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  133664. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133665. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133666. 7,
  133667. };
  133668. static float _vq_quantthresh__44c8_s_p9_2[] = {
  133669. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133670. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133671. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133672. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133673. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133674. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133675. };
  133676. static long _vq_quantmap__44c8_s_p9_2[] = {
  133677. 47, 45, 43, 41, 39, 37, 35, 33,
  133678. 31, 29, 27, 25, 23, 21, 19, 17,
  133679. 15, 13, 11, 9, 7, 5, 3, 1,
  133680. 0, 2, 4, 6, 8, 10, 12, 14,
  133681. 16, 18, 20, 22, 24, 26, 28, 30,
  133682. 32, 34, 36, 38, 40, 42, 44, 46,
  133683. 48,
  133684. };
  133685. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  133686. _vq_quantthresh__44c8_s_p9_2,
  133687. _vq_quantmap__44c8_s_p9_2,
  133688. 49,
  133689. 49
  133690. };
  133691. static static_codebook _44c8_s_p9_2 = {
  133692. 1, 49,
  133693. _vq_lengthlist__44c8_s_p9_2,
  133694. 1, -526909440, 1611661312, 6, 0,
  133695. _vq_quantlist__44c8_s_p9_2,
  133696. NULL,
  133697. &_vq_auxt__44c8_s_p9_2,
  133698. NULL,
  133699. 0
  133700. };
  133701. static long _huff_lengthlist__44c8_s_short[] = {
  133702. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  133703. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  133704. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  133705. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  133706. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  133707. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  133708. 10, 9,11,14,
  133709. };
  133710. static static_codebook _huff_book__44c8_s_short = {
  133711. 2, 100,
  133712. _huff_lengthlist__44c8_s_short,
  133713. 0, 0, 0, 0, 0,
  133714. NULL,
  133715. NULL,
  133716. NULL,
  133717. NULL,
  133718. 0
  133719. };
  133720. static long _huff_lengthlist__44c9_s_long[] = {
  133721. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  133722. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  133723. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  133724. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  133725. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  133726. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  133727. 10, 9, 8, 9,
  133728. };
  133729. static static_codebook _huff_book__44c9_s_long = {
  133730. 2, 100,
  133731. _huff_lengthlist__44c9_s_long,
  133732. 0, 0, 0, 0, 0,
  133733. NULL,
  133734. NULL,
  133735. NULL,
  133736. NULL,
  133737. 0
  133738. };
  133739. static long _vq_quantlist__44c9_s_p1_0[] = {
  133740. 1,
  133741. 0,
  133742. 2,
  133743. };
  133744. static long _vq_lengthlist__44c9_s_p1_0[] = {
  133745. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  133746. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133747. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  133748. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133749. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  133750. 7,
  133751. };
  133752. static float _vq_quantthresh__44c9_s_p1_0[] = {
  133753. -0.5, 0.5,
  133754. };
  133755. static long _vq_quantmap__44c9_s_p1_0[] = {
  133756. 1, 0, 2,
  133757. };
  133758. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  133759. _vq_quantthresh__44c9_s_p1_0,
  133760. _vq_quantmap__44c9_s_p1_0,
  133761. 3,
  133762. 3
  133763. };
  133764. static static_codebook _44c9_s_p1_0 = {
  133765. 4, 81,
  133766. _vq_lengthlist__44c9_s_p1_0,
  133767. 1, -535822336, 1611661312, 2, 0,
  133768. _vq_quantlist__44c9_s_p1_0,
  133769. NULL,
  133770. &_vq_auxt__44c9_s_p1_0,
  133771. NULL,
  133772. 0
  133773. };
  133774. static long _vq_quantlist__44c9_s_p2_0[] = {
  133775. 2,
  133776. 1,
  133777. 3,
  133778. 0,
  133779. 4,
  133780. };
  133781. static long _vq_lengthlist__44c9_s_p2_0[] = {
  133782. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133783. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  133784. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  133785. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  133786. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  133787. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  133788. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  133789. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  133790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133791. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  133792. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  133793. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  133794. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  133795. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  133796. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  133797. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  133798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133799. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  133800. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  133801. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  133802. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  133803. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  133804. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  133805. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133807. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  133808. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  133809. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  133810. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  133811. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  133812. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  133813. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133818. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  133819. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  133820. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  133821. 12,
  133822. };
  133823. static float _vq_quantthresh__44c9_s_p2_0[] = {
  133824. -1.5, -0.5, 0.5, 1.5,
  133825. };
  133826. static long _vq_quantmap__44c9_s_p2_0[] = {
  133827. 3, 1, 0, 2, 4,
  133828. };
  133829. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  133830. _vq_quantthresh__44c9_s_p2_0,
  133831. _vq_quantmap__44c9_s_p2_0,
  133832. 5,
  133833. 5
  133834. };
  133835. static static_codebook _44c9_s_p2_0 = {
  133836. 4, 625,
  133837. _vq_lengthlist__44c9_s_p2_0,
  133838. 1, -533725184, 1611661312, 3, 0,
  133839. _vq_quantlist__44c9_s_p2_0,
  133840. NULL,
  133841. &_vq_auxt__44c9_s_p2_0,
  133842. NULL,
  133843. 0
  133844. };
  133845. static long _vq_quantlist__44c9_s_p3_0[] = {
  133846. 4,
  133847. 3,
  133848. 5,
  133849. 2,
  133850. 6,
  133851. 1,
  133852. 7,
  133853. 0,
  133854. 8,
  133855. };
  133856. static long _vq_lengthlist__44c9_s_p3_0[] = {
  133857. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  133858. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  133859. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  133860. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  133861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133862. 0,
  133863. };
  133864. static float _vq_quantthresh__44c9_s_p3_0[] = {
  133865. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133866. };
  133867. static long _vq_quantmap__44c9_s_p3_0[] = {
  133868. 7, 5, 3, 1, 0, 2, 4, 6,
  133869. 8,
  133870. };
  133871. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  133872. _vq_quantthresh__44c9_s_p3_0,
  133873. _vq_quantmap__44c9_s_p3_0,
  133874. 9,
  133875. 9
  133876. };
  133877. static static_codebook _44c9_s_p3_0 = {
  133878. 2, 81,
  133879. _vq_lengthlist__44c9_s_p3_0,
  133880. 1, -531628032, 1611661312, 4, 0,
  133881. _vq_quantlist__44c9_s_p3_0,
  133882. NULL,
  133883. &_vq_auxt__44c9_s_p3_0,
  133884. NULL,
  133885. 0
  133886. };
  133887. static long _vq_quantlist__44c9_s_p4_0[] = {
  133888. 8,
  133889. 7,
  133890. 9,
  133891. 6,
  133892. 10,
  133893. 5,
  133894. 11,
  133895. 4,
  133896. 12,
  133897. 3,
  133898. 13,
  133899. 2,
  133900. 14,
  133901. 1,
  133902. 15,
  133903. 0,
  133904. 16,
  133905. };
  133906. static long _vq_lengthlist__44c9_s_p4_0[] = {
  133907. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  133908. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  133909. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  133910. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  133911. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  133912. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  133913. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  133914. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133915. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133916. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  133917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133925. 0,
  133926. };
  133927. static float _vq_quantthresh__44c9_s_p4_0[] = {
  133928. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133929. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133930. };
  133931. static long _vq_quantmap__44c9_s_p4_0[] = {
  133932. 15, 13, 11, 9, 7, 5, 3, 1,
  133933. 0, 2, 4, 6, 8, 10, 12, 14,
  133934. 16,
  133935. };
  133936. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  133937. _vq_quantthresh__44c9_s_p4_0,
  133938. _vq_quantmap__44c9_s_p4_0,
  133939. 17,
  133940. 17
  133941. };
  133942. static static_codebook _44c9_s_p4_0 = {
  133943. 2, 289,
  133944. _vq_lengthlist__44c9_s_p4_0,
  133945. 1, -529530880, 1611661312, 5, 0,
  133946. _vq_quantlist__44c9_s_p4_0,
  133947. NULL,
  133948. &_vq_auxt__44c9_s_p4_0,
  133949. NULL,
  133950. 0
  133951. };
  133952. static long _vq_quantlist__44c9_s_p5_0[] = {
  133953. 1,
  133954. 0,
  133955. 2,
  133956. };
  133957. static long _vq_lengthlist__44c9_s_p5_0[] = {
  133958. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  133959. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  133960. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  133961. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  133962. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  133963. 12,
  133964. };
  133965. static float _vq_quantthresh__44c9_s_p5_0[] = {
  133966. -5.5, 5.5,
  133967. };
  133968. static long _vq_quantmap__44c9_s_p5_0[] = {
  133969. 1, 0, 2,
  133970. };
  133971. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  133972. _vq_quantthresh__44c9_s_p5_0,
  133973. _vq_quantmap__44c9_s_p5_0,
  133974. 3,
  133975. 3
  133976. };
  133977. static static_codebook _44c9_s_p5_0 = {
  133978. 4, 81,
  133979. _vq_lengthlist__44c9_s_p5_0,
  133980. 1, -529137664, 1618345984, 2, 0,
  133981. _vq_quantlist__44c9_s_p5_0,
  133982. NULL,
  133983. &_vq_auxt__44c9_s_p5_0,
  133984. NULL,
  133985. 0
  133986. };
  133987. static long _vq_quantlist__44c9_s_p5_1[] = {
  133988. 5,
  133989. 4,
  133990. 6,
  133991. 3,
  133992. 7,
  133993. 2,
  133994. 8,
  133995. 1,
  133996. 9,
  133997. 0,
  133998. 10,
  133999. };
  134000. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134001. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134002. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134003. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134004. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134005. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134006. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134007. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134008. 11,11,11, 7, 7, 7, 7, 7, 7,
  134009. };
  134010. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134011. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134012. 3.5, 4.5,
  134013. };
  134014. static long _vq_quantmap__44c9_s_p5_1[] = {
  134015. 9, 7, 5, 3, 1, 0, 2, 4,
  134016. 6, 8, 10,
  134017. };
  134018. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134019. _vq_quantthresh__44c9_s_p5_1,
  134020. _vq_quantmap__44c9_s_p5_1,
  134021. 11,
  134022. 11
  134023. };
  134024. static static_codebook _44c9_s_p5_1 = {
  134025. 2, 121,
  134026. _vq_lengthlist__44c9_s_p5_1,
  134027. 1, -531365888, 1611661312, 4, 0,
  134028. _vq_quantlist__44c9_s_p5_1,
  134029. NULL,
  134030. &_vq_auxt__44c9_s_p5_1,
  134031. NULL,
  134032. 0
  134033. };
  134034. static long _vq_quantlist__44c9_s_p6_0[] = {
  134035. 6,
  134036. 5,
  134037. 7,
  134038. 4,
  134039. 8,
  134040. 3,
  134041. 9,
  134042. 2,
  134043. 10,
  134044. 1,
  134045. 11,
  134046. 0,
  134047. 12,
  134048. };
  134049. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134050. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134051. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134052. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134053. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134054. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134055. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  134056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134060. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134061. };
  134062. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134063. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134064. 12.5, 17.5, 22.5, 27.5,
  134065. };
  134066. static long _vq_quantmap__44c9_s_p6_0[] = {
  134067. 11, 9, 7, 5, 3, 1, 0, 2,
  134068. 4, 6, 8, 10, 12,
  134069. };
  134070. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134071. _vq_quantthresh__44c9_s_p6_0,
  134072. _vq_quantmap__44c9_s_p6_0,
  134073. 13,
  134074. 13
  134075. };
  134076. static static_codebook _44c9_s_p6_0 = {
  134077. 2, 169,
  134078. _vq_lengthlist__44c9_s_p6_0,
  134079. 1, -526516224, 1616117760, 4, 0,
  134080. _vq_quantlist__44c9_s_p6_0,
  134081. NULL,
  134082. &_vq_auxt__44c9_s_p6_0,
  134083. NULL,
  134084. 0
  134085. };
  134086. static long _vq_quantlist__44c9_s_p6_1[] = {
  134087. 2,
  134088. 1,
  134089. 3,
  134090. 0,
  134091. 4,
  134092. };
  134093. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134094. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134095. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134096. };
  134097. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134098. -1.5, -0.5, 0.5, 1.5,
  134099. };
  134100. static long _vq_quantmap__44c9_s_p6_1[] = {
  134101. 3, 1, 0, 2, 4,
  134102. };
  134103. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134104. _vq_quantthresh__44c9_s_p6_1,
  134105. _vq_quantmap__44c9_s_p6_1,
  134106. 5,
  134107. 5
  134108. };
  134109. static static_codebook _44c9_s_p6_1 = {
  134110. 2, 25,
  134111. _vq_lengthlist__44c9_s_p6_1,
  134112. 1, -533725184, 1611661312, 3, 0,
  134113. _vq_quantlist__44c9_s_p6_1,
  134114. NULL,
  134115. &_vq_auxt__44c9_s_p6_1,
  134116. NULL,
  134117. 0
  134118. };
  134119. static long _vq_quantlist__44c9_s_p7_0[] = {
  134120. 6,
  134121. 5,
  134122. 7,
  134123. 4,
  134124. 8,
  134125. 3,
  134126. 9,
  134127. 2,
  134128. 10,
  134129. 1,
  134130. 11,
  134131. 0,
  134132. 12,
  134133. };
  134134. static long _vq_lengthlist__44c9_s_p7_0[] = {
  134135. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  134136. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  134137. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  134138. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  134139. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  134140. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  134141. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  134142. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  134143. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  134144. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  134145. 19,12,12,12,12,13,13,14,14,
  134146. };
  134147. static float _vq_quantthresh__44c9_s_p7_0[] = {
  134148. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134149. 27.5, 38.5, 49.5, 60.5,
  134150. };
  134151. static long _vq_quantmap__44c9_s_p7_0[] = {
  134152. 11, 9, 7, 5, 3, 1, 0, 2,
  134153. 4, 6, 8, 10, 12,
  134154. };
  134155. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  134156. _vq_quantthresh__44c9_s_p7_0,
  134157. _vq_quantmap__44c9_s_p7_0,
  134158. 13,
  134159. 13
  134160. };
  134161. static static_codebook _44c9_s_p7_0 = {
  134162. 2, 169,
  134163. _vq_lengthlist__44c9_s_p7_0,
  134164. 1, -523206656, 1618345984, 4, 0,
  134165. _vq_quantlist__44c9_s_p7_0,
  134166. NULL,
  134167. &_vq_auxt__44c9_s_p7_0,
  134168. NULL,
  134169. 0
  134170. };
  134171. static long _vq_quantlist__44c9_s_p7_1[] = {
  134172. 5,
  134173. 4,
  134174. 6,
  134175. 3,
  134176. 7,
  134177. 2,
  134178. 8,
  134179. 1,
  134180. 9,
  134181. 0,
  134182. 10,
  134183. };
  134184. static long _vq_lengthlist__44c9_s_p7_1[] = {
  134185. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  134186. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134187. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  134188. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134189. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134190. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134191. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134192. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134193. };
  134194. static float _vq_quantthresh__44c9_s_p7_1[] = {
  134195. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134196. 3.5, 4.5,
  134197. };
  134198. static long _vq_quantmap__44c9_s_p7_1[] = {
  134199. 9, 7, 5, 3, 1, 0, 2, 4,
  134200. 6, 8, 10,
  134201. };
  134202. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  134203. _vq_quantthresh__44c9_s_p7_1,
  134204. _vq_quantmap__44c9_s_p7_1,
  134205. 11,
  134206. 11
  134207. };
  134208. static static_codebook _44c9_s_p7_1 = {
  134209. 2, 121,
  134210. _vq_lengthlist__44c9_s_p7_1,
  134211. 1, -531365888, 1611661312, 4, 0,
  134212. _vq_quantlist__44c9_s_p7_1,
  134213. NULL,
  134214. &_vq_auxt__44c9_s_p7_1,
  134215. NULL,
  134216. 0
  134217. };
  134218. static long _vq_quantlist__44c9_s_p8_0[] = {
  134219. 7,
  134220. 6,
  134221. 8,
  134222. 5,
  134223. 9,
  134224. 4,
  134225. 10,
  134226. 3,
  134227. 11,
  134228. 2,
  134229. 12,
  134230. 1,
  134231. 13,
  134232. 0,
  134233. 14,
  134234. };
  134235. static long _vq_lengthlist__44c9_s_p8_0[] = {
  134236. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  134237. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  134238. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  134239. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  134240. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  134241. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  134242. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  134243. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  134244. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  134245. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  134246. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  134247. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  134248. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  134249. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  134250. 14,
  134251. };
  134252. static float _vq_quantthresh__44c9_s_p8_0[] = {
  134253. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134254. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134255. };
  134256. static long _vq_quantmap__44c9_s_p8_0[] = {
  134257. 13, 11, 9, 7, 5, 3, 1, 0,
  134258. 2, 4, 6, 8, 10, 12, 14,
  134259. };
  134260. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  134261. _vq_quantthresh__44c9_s_p8_0,
  134262. _vq_quantmap__44c9_s_p8_0,
  134263. 15,
  134264. 15
  134265. };
  134266. static static_codebook _44c9_s_p8_0 = {
  134267. 2, 225,
  134268. _vq_lengthlist__44c9_s_p8_0,
  134269. 1, -520986624, 1620377600, 4, 0,
  134270. _vq_quantlist__44c9_s_p8_0,
  134271. NULL,
  134272. &_vq_auxt__44c9_s_p8_0,
  134273. NULL,
  134274. 0
  134275. };
  134276. static long _vq_quantlist__44c9_s_p8_1[] = {
  134277. 10,
  134278. 9,
  134279. 11,
  134280. 8,
  134281. 12,
  134282. 7,
  134283. 13,
  134284. 6,
  134285. 14,
  134286. 5,
  134287. 15,
  134288. 4,
  134289. 16,
  134290. 3,
  134291. 17,
  134292. 2,
  134293. 18,
  134294. 1,
  134295. 19,
  134296. 0,
  134297. 20,
  134298. };
  134299. static long _vq_lengthlist__44c9_s_p8_1[] = {
  134300. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134301. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134302. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134303. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134304. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134305. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134306. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  134307. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134308. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134309. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134310. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134311. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134312. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134313. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134314. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134315. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  134316. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  134317. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  134318. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  134319. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134320. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134321. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  134322. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  134323. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134324. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  134325. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  134326. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  134327. 9, 9, 9,10, 9, 9, 9, 9, 9,
  134328. };
  134329. static float _vq_quantthresh__44c9_s_p8_1[] = {
  134330. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134331. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134332. 6.5, 7.5, 8.5, 9.5,
  134333. };
  134334. static long _vq_quantmap__44c9_s_p8_1[] = {
  134335. 19, 17, 15, 13, 11, 9, 7, 5,
  134336. 3, 1, 0, 2, 4, 6, 8, 10,
  134337. 12, 14, 16, 18, 20,
  134338. };
  134339. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  134340. _vq_quantthresh__44c9_s_p8_1,
  134341. _vq_quantmap__44c9_s_p8_1,
  134342. 21,
  134343. 21
  134344. };
  134345. static static_codebook _44c9_s_p8_1 = {
  134346. 2, 441,
  134347. _vq_lengthlist__44c9_s_p8_1,
  134348. 1, -529268736, 1611661312, 5, 0,
  134349. _vq_quantlist__44c9_s_p8_1,
  134350. NULL,
  134351. &_vq_auxt__44c9_s_p8_1,
  134352. NULL,
  134353. 0
  134354. };
  134355. static long _vq_quantlist__44c9_s_p9_0[] = {
  134356. 9,
  134357. 8,
  134358. 10,
  134359. 7,
  134360. 11,
  134361. 6,
  134362. 12,
  134363. 5,
  134364. 13,
  134365. 4,
  134366. 14,
  134367. 3,
  134368. 15,
  134369. 2,
  134370. 16,
  134371. 1,
  134372. 17,
  134373. 0,
  134374. 18,
  134375. };
  134376. static long _vq_lengthlist__44c9_s_p9_0[] = {
  134377. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134378. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  134379. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  134380. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  134381. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134382. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134383. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134384. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134385. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134386. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134387. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134388. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134389. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134390. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134391. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134392. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134393. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  134394. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134395. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134396. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134397. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134398. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134399. 11,11,11,11,11,11,11,11,11,
  134400. };
  134401. static float _vq_quantthresh__44c9_s_p9_0[] = {
  134402. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  134403. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  134404. 6982.5, 7913.5,
  134405. };
  134406. static long _vq_quantmap__44c9_s_p9_0[] = {
  134407. 17, 15, 13, 11, 9, 7, 5, 3,
  134408. 1, 0, 2, 4, 6, 8, 10, 12,
  134409. 14, 16, 18,
  134410. };
  134411. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  134412. _vq_quantthresh__44c9_s_p9_0,
  134413. _vq_quantmap__44c9_s_p9_0,
  134414. 19,
  134415. 19
  134416. };
  134417. static static_codebook _44c9_s_p9_0 = {
  134418. 2, 361,
  134419. _vq_lengthlist__44c9_s_p9_0,
  134420. 1, -508535424, 1631393792, 5, 0,
  134421. _vq_quantlist__44c9_s_p9_0,
  134422. NULL,
  134423. &_vq_auxt__44c9_s_p9_0,
  134424. NULL,
  134425. 0
  134426. };
  134427. static long _vq_quantlist__44c9_s_p9_1[] = {
  134428. 9,
  134429. 8,
  134430. 10,
  134431. 7,
  134432. 11,
  134433. 6,
  134434. 12,
  134435. 5,
  134436. 13,
  134437. 4,
  134438. 14,
  134439. 3,
  134440. 15,
  134441. 2,
  134442. 16,
  134443. 1,
  134444. 17,
  134445. 0,
  134446. 18,
  134447. };
  134448. static long _vq_lengthlist__44c9_s_p9_1[] = {
  134449. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  134450. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  134451. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  134452. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  134453. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  134454. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  134455. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  134456. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  134457. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  134458. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  134459. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  134460. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  134461. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  134462. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  134463. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  134464. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  134465. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  134466. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  134467. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  134468. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  134469. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  134470. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  134471. 13,13,13,14,13,14,15,15,15,
  134472. };
  134473. static float _vq_quantthresh__44c9_s_p9_1[] = {
  134474. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134475. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134476. 367.5, 416.5,
  134477. };
  134478. static long _vq_quantmap__44c9_s_p9_1[] = {
  134479. 17, 15, 13, 11, 9, 7, 5, 3,
  134480. 1, 0, 2, 4, 6, 8, 10, 12,
  134481. 14, 16, 18,
  134482. };
  134483. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  134484. _vq_quantthresh__44c9_s_p9_1,
  134485. _vq_quantmap__44c9_s_p9_1,
  134486. 19,
  134487. 19
  134488. };
  134489. static static_codebook _44c9_s_p9_1 = {
  134490. 2, 361,
  134491. _vq_lengthlist__44c9_s_p9_1,
  134492. 1, -518287360, 1622704128, 5, 0,
  134493. _vq_quantlist__44c9_s_p9_1,
  134494. NULL,
  134495. &_vq_auxt__44c9_s_p9_1,
  134496. NULL,
  134497. 0
  134498. };
  134499. static long _vq_quantlist__44c9_s_p9_2[] = {
  134500. 24,
  134501. 23,
  134502. 25,
  134503. 22,
  134504. 26,
  134505. 21,
  134506. 27,
  134507. 20,
  134508. 28,
  134509. 19,
  134510. 29,
  134511. 18,
  134512. 30,
  134513. 17,
  134514. 31,
  134515. 16,
  134516. 32,
  134517. 15,
  134518. 33,
  134519. 14,
  134520. 34,
  134521. 13,
  134522. 35,
  134523. 12,
  134524. 36,
  134525. 11,
  134526. 37,
  134527. 10,
  134528. 38,
  134529. 9,
  134530. 39,
  134531. 8,
  134532. 40,
  134533. 7,
  134534. 41,
  134535. 6,
  134536. 42,
  134537. 5,
  134538. 43,
  134539. 4,
  134540. 44,
  134541. 3,
  134542. 45,
  134543. 2,
  134544. 46,
  134545. 1,
  134546. 47,
  134547. 0,
  134548. 48,
  134549. };
  134550. static long _vq_lengthlist__44c9_s_p9_2[] = {
  134551. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134552. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134553. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134554. 7,
  134555. };
  134556. static float _vq_quantthresh__44c9_s_p9_2[] = {
  134557. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134558. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134559. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134560. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134561. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134562. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134563. };
  134564. static long _vq_quantmap__44c9_s_p9_2[] = {
  134565. 47, 45, 43, 41, 39, 37, 35, 33,
  134566. 31, 29, 27, 25, 23, 21, 19, 17,
  134567. 15, 13, 11, 9, 7, 5, 3, 1,
  134568. 0, 2, 4, 6, 8, 10, 12, 14,
  134569. 16, 18, 20, 22, 24, 26, 28, 30,
  134570. 32, 34, 36, 38, 40, 42, 44, 46,
  134571. 48,
  134572. };
  134573. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  134574. _vq_quantthresh__44c9_s_p9_2,
  134575. _vq_quantmap__44c9_s_p9_2,
  134576. 49,
  134577. 49
  134578. };
  134579. static static_codebook _44c9_s_p9_2 = {
  134580. 1, 49,
  134581. _vq_lengthlist__44c9_s_p9_2,
  134582. 1, -526909440, 1611661312, 6, 0,
  134583. _vq_quantlist__44c9_s_p9_2,
  134584. NULL,
  134585. &_vq_auxt__44c9_s_p9_2,
  134586. NULL,
  134587. 0
  134588. };
  134589. static long _huff_lengthlist__44c9_s_short[] = {
  134590. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  134591. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  134592. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  134593. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  134594. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  134595. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  134596. 9, 8,10,13,
  134597. };
  134598. static static_codebook _huff_book__44c9_s_short = {
  134599. 2, 100,
  134600. _huff_lengthlist__44c9_s_short,
  134601. 0, 0, 0, 0, 0,
  134602. NULL,
  134603. NULL,
  134604. NULL,
  134605. NULL,
  134606. 0
  134607. };
  134608. static long _huff_lengthlist__44c0_s_long[] = {
  134609. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  134610. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  134611. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  134612. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  134613. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  134614. 12,
  134615. };
  134616. static static_codebook _huff_book__44c0_s_long = {
  134617. 2, 81,
  134618. _huff_lengthlist__44c0_s_long,
  134619. 0, 0, 0, 0, 0,
  134620. NULL,
  134621. NULL,
  134622. NULL,
  134623. NULL,
  134624. 0
  134625. };
  134626. static long _vq_quantlist__44c0_s_p1_0[] = {
  134627. 1,
  134628. 0,
  134629. 2,
  134630. };
  134631. static long _vq_lengthlist__44c0_s_p1_0[] = {
  134632. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134633. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134637. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134638. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134642. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134643. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134678. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134683. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  134684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134688. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  134689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134723. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134724. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134728. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  134729. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  134730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134733. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  134734. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  134735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135042. 0,
  135043. };
  135044. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135045. -0.5, 0.5,
  135046. };
  135047. static long _vq_quantmap__44c0_s_p1_0[] = {
  135048. 1, 0, 2,
  135049. };
  135050. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135051. _vq_quantthresh__44c0_s_p1_0,
  135052. _vq_quantmap__44c0_s_p1_0,
  135053. 3,
  135054. 3
  135055. };
  135056. static static_codebook _44c0_s_p1_0 = {
  135057. 8, 6561,
  135058. _vq_lengthlist__44c0_s_p1_0,
  135059. 1, -535822336, 1611661312, 2, 0,
  135060. _vq_quantlist__44c0_s_p1_0,
  135061. NULL,
  135062. &_vq_auxt__44c0_s_p1_0,
  135063. NULL,
  135064. 0
  135065. };
  135066. static long _vq_quantlist__44c0_s_p2_0[] = {
  135067. 2,
  135068. 1,
  135069. 3,
  135070. 0,
  135071. 4,
  135072. };
  135073. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135074. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135077. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135080. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135113. 0,
  135114. };
  135115. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135116. -1.5, -0.5, 0.5, 1.5,
  135117. };
  135118. static long _vq_quantmap__44c0_s_p2_0[] = {
  135119. 3, 1, 0, 2, 4,
  135120. };
  135121. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135122. _vq_quantthresh__44c0_s_p2_0,
  135123. _vq_quantmap__44c0_s_p2_0,
  135124. 5,
  135125. 5
  135126. };
  135127. static static_codebook _44c0_s_p2_0 = {
  135128. 4, 625,
  135129. _vq_lengthlist__44c0_s_p2_0,
  135130. 1, -533725184, 1611661312, 3, 0,
  135131. _vq_quantlist__44c0_s_p2_0,
  135132. NULL,
  135133. &_vq_auxt__44c0_s_p2_0,
  135134. NULL,
  135135. 0
  135136. };
  135137. static long _vq_quantlist__44c0_s_p3_0[] = {
  135138. 4,
  135139. 3,
  135140. 5,
  135141. 2,
  135142. 6,
  135143. 1,
  135144. 7,
  135145. 0,
  135146. 8,
  135147. };
  135148. static long _vq_lengthlist__44c0_s_p3_0[] = {
  135149. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135150. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135151. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135152. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135153. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135154. 0,
  135155. };
  135156. static float _vq_quantthresh__44c0_s_p3_0[] = {
  135157. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135158. };
  135159. static long _vq_quantmap__44c0_s_p3_0[] = {
  135160. 7, 5, 3, 1, 0, 2, 4, 6,
  135161. 8,
  135162. };
  135163. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  135164. _vq_quantthresh__44c0_s_p3_0,
  135165. _vq_quantmap__44c0_s_p3_0,
  135166. 9,
  135167. 9
  135168. };
  135169. static static_codebook _44c0_s_p3_0 = {
  135170. 2, 81,
  135171. _vq_lengthlist__44c0_s_p3_0,
  135172. 1, -531628032, 1611661312, 4, 0,
  135173. _vq_quantlist__44c0_s_p3_0,
  135174. NULL,
  135175. &_vq_auxt__44c0_s_p3_0,
  135176. NULL,
  135177. 0
  135178. };
  135179. static long _vq_quantlist__44c0_s_p4_0[] = {
  135180. 4,
  135181. 3,
  135182. 5,
  135183. 2,
  135184. 6,
  135185. 1,
  135186. 7,
  135187. 0,
  135188. 8,
  135189. };
  135190. static long _vq_lengthlist__44c0_s_p4_0[] = {
  135191. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135192. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135193. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  135194. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  135195. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  135196. 10,
  135197. };
  135198. static float _vq_quantthresh__44c0_s_p4_0[] = {
  135199. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135200. };
  135201. static long _vq_quantmap__44c0_s_p4_0[] = {
  135202. 7, 5, 3, 1, 0, 2, 4, 6,
  135203. 8,
  135204. };
  135205. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  135206. _vq_quantthresh__44c0_s_p4_0,
  135207. _vq_quantmap__44c0_s_p4_0,
  135208. 9,
  135209. 9
  135210. };
  135211. static static_codebook _44c0_s_p4_0 = {
  135212. 2, 81,
  135213. _vq_lengthlist__44c0_s_p4_0,
  135214. 1, -531628032, 1611661312, 4, 0,
  135215. _vq_quantlist__44c0_s_p4_0,
  135216. NULL,
  135217. &_vq_auxt__44c0_s_p4_0,
  135218. NULL,
  135219. 0
  135220. };
  135221. static long _vq_quantlist__44c0_s_p5_0[] = {
  135222. 8,
  135223. 7,
  135224. 9,
  135225. 6,
  135226. 10,
  135227. 5,
  135228. 11,
  135229. 4,
  135230. 12,
  135231. 3,
  135232. 13,
  135233. 2,
  135234. 14,
  135235. 1,
  135236. 15,
  135237. 0,
  135238. 16,
  135239. };
  135240. static long _vq_lengthlist__44c0_s_p5_0[] = {
  135241. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135242. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  135243. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135244. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135245. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135246. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  135247. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  135248. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135249. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135250. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  135251. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135252. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135253. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  135254. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  135255. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  135256. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  135257. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  135258. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135259. 14,
  135260. };
  135261. static float _vq_quantthresh__44c0_s_p5_0[] = {
  135262. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135263. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135264. };
  135265. static long _vq_quantmap__44c0_s_p5_0[] = {
  135266. 15, 13, 11, 9, 7, 5, 3, 1,
  135267. 0, 2, 4, 6, 8, 10, 12, 14,
  135268. 16,
  135269. };
  135270. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  135271. _vq_quantthresh__44c0_s_p5_0,
  135272. _vq_quantmap__44c0_s_p5_0,
  135273. 17,
  135274. 17
  135275. };
  135276. static static_codebook _44c0_s_p5_0 = {
  135277. 2, 289,
  135278. _vq_lengthlist__44c0_s_p5_0,
  135279. 1, -529530880, 1611661312, 5, 0,
  135280. _vq_quantlist__44c0_s_p5_0,
  135281. NULL,
  135282. &_vq_auxt__44c0_s_p5_0,
  135283. NULL,
  135284. 0
  135285. };
  135286. static long _vq_quantlist__44c0_s_p6_0[] = {
  135287. 1,
  135288. 0,
  135289. 2,
  135290. };
  135291. static long _vq_lengthlist__44c0_s_p6_0[] = {
  135292. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  135293. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  135294. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  135295. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  135296. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  135297. 10,
  135298. };
  135299. static float _vq_quantthresh__44c0_s_p6_0[] = {
  135300. -5.5, 5.5,
  135301. };
  135302. static long _vq_quantmap__44c0_s_p6_0[] = {
  135303. 1, 0, 2,
  135304. };
  135305. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  135306. _vq_quantthresh__44c0_s_p6_0,
  135307. _vq_quantmap__44c0_s_p6_0,
  135308. 3,
  135309. 3
  135310. };
  135311. static static_codebook _44c0_s_p6_0 = {
  135312. 4, 81,
  135313. _vq_lengthlist__44c0_s_p6_0,
  135314. 1, -529137664, 1618345984, 2, 0,
  135315. _vq_quantlist__44c0_s_p6_0,
  135316. NULL,
  135317. &_vq_auxt__44c0_s_p6_0,
  135318. NULL,
  135319. 0
  135320. };
  135321. static long _vq_quantlist__44c0_s_p6_1[] = {
  135322. 5,
  135323. 4,
  135324. 6,
  135325. 3,
  135326. 7,
  135327. 2,
  135328. 8,
  135329. 1,
  135330. 9,
  135331. 0,
  135332. 10,
  135333. };
  135334. static long _vq_lengthlist__44c0_s_p6_1[] = {
  135335. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  135336. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135337. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135338. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  135339. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135340. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135341. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135342. 10,10,10, 8, 8, 8, 8, 8, 8,
  135343. };
  135344. static float _vq_quantthresh__44c0_s_p6_1[] = {
  135345. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135346. 3.5, 4.5,
  135347. };
  135348. static long _vq_quantmap__44c0_s_p6_1[] = {
  135349. 9, 7, 5, 3, 1, 0, 2, 4,
  135350. 6, 8, 10,
  135351. };
  135352. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  135353. _vq_quantthresh__44c0_s_p6_1,
  135354. _vq_quantmap__44c0_s_p6_1,
  135355. 11,
  135356. 11
  135357. };
  135358. static static_codebook _44c0_s_p6_1 = {
  135359. 2, 121,
  135360. _vq_lengthlist__44c0_s_p6_1,
  135361. 1, -531365888, 1611661312, 4, 0,
  135362. _vq_quantlist__44c0_s_p6_1,
  135363. NULL,
  135364. &_vq_auxt__44c0_s_p6_1,
  135365. NULL,
  135366. 0
  135367. };
  135368. static long _vq_quantlist__44c0_s_p7_0[] = {
  135369. 6,
  135370. 5,
  135371. 7,
  135372. 4,
  135373. 8,
  135374. 3,
  135375. 9,
  135376. 2,
  135377. 10,
  135378. 1,
  135379. 11,
  135380. 0,
  135381. 12,
  135382. };
  135383. static long _vq_lengthlist__44c0_s_p7_0[] = {
  135384. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  135385. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  135386. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135387. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135388. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  135389. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  135390. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  135391. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135392. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135393. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  135394. 0,12,12,11,11,12,12,13,13,
  135395. };
  135396. static float _vq_quantthresh__44c0_s_p7_0[] = {
  135397. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135398. 12.5, 17.5, 22.5, 27.5,
  135399. };
  135400. static long _vq_quantmap__44c0_s_p7_0[] = {
  135401. 11, 9, 7, 5, 3, 1, 0, 2,
  135402. 4, 6, 8, 10, 12,
  135403. };
  135404. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  135405. _vq_quantthresh__44c0_s_p7_0,
  135406. _vq_quantmap__44c0_s_p7_0,
  135407. 13,
  135408. 13
  135409. };
  135410. static static_codebook _44c0_s_p7_0 = {
  135411. 2, 169,
  135412. _vq_lengthlist__44c0_s_p7_0,
  135413. 1, -526516224, 1616117760, 4, 0,
  135414. _vq_quantlist__44c0_s_p7_0,
  135415. NULL,
  135416. &_vq_auxt__44c0_s_p7_0,
  135417. NULL,
  135418. 0
  135419. };
  135420. static long _vq_quantlist__44c0_s_p7_1[] = {
  135421. 2,
  135422. 1,
  135423. 3,
  135424. 0,
  135425. 4,
  135426. };
  135427. static long _vq_lengthlist__44c0_s_p7_1[] = {
  135428. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135429. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135430. };
  135431. static float _vq_quantthresh__44c0_s_p7_1[] = {
  135432. -1.5, -0.5, 0.5, 1.5,
  135433. };
  135434. static long _vq_quantmap__44c0_s_p7_1[] = {
  135435. 3, 1, 0, 2, 4,
  135436. };
  135437. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  135438. _vq_quantthresh__44c0_s_p7_1,
  135439. _vq_quantmap__44c0_s_p7_1,
  135440. 5,
  135441. 5
  135442. };
  135443. static static_codebook _44c0_s_p7_1 = {
  135444. 2, 25,
  135445. _vq_lengthlist__44c0_s_p7_1,
  135446. 1, -533725184, 1611661312, 3, 0,
  135447. _vq_quantlist__44c0_s_p7_1,
  135448. NULL,
  135449. &_vq_auxt__44c0_s_p7_1,
  135450. NULL,
  135451. 0
  135452. };
  135453. static long _vq_quantlist__44c0_s_p8_0[] = {
  135454. 2,
  135455. 1,
  135456. 3,
  135457. 0,
  135458. 4,
  135459. };
  135460. static long _vq_lengthlist__44c0_s_p8_0[] = {
  135461. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  135462. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135463. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135464. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135465. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135466. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135467. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135468. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  135469. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135470. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135471. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135472. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135473. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  135474. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135475. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135476. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  135477. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135478. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135479. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135480. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135481. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135482. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135483. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135500. 11,
  135501. };
  135502. static float _vq_quantthresh__44c0_s_p8_0[] = {
  135503. -331.5, -110.5, 110.5, 331.5,
  135504. };
  135505. static long _vq_quantmap__44c0_s_p8_0[] = {
  135506. 3, 1, 0, 2, 4,
  135507. };
  135508. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  135509. _vq_quantthresh__44c0_s_p8_0,
  135510. _vq_quantmap__44c0_s_p8_0,
  135511. 5,
  135512. 5
  135513. };
  135514. static static_codebook _44c0_s_p8_0 = {
  135515. 4, 625,
  135516. _vq_lengthlist__44c0_s_p8_0,
  135517. 1, -518283264, 1627103232, 3, 0,
  135518. _vq_quantlist__44c0_s_p8_0,
  135519. NULL,
  135520. &_vq_auxt__44c0_s_p8_0,
  135521. NULL,
  135522. 0
  135523. };
  135524. static long _vq_quantlist__44c0_s_p8_1[] = {
  135525. 6,
  135526. 5,
  135527. 7,
  135528. 4,
  135529. 8,
  135530. 3,
  135531. 9,
  135532. 2,
  135533. 10,
  135534. 1,
  135535. 11,
  135536. 0,
  135537. 12,
  135538. };
  135539. static long _vq_lengthlist__44c0_s_p8_1[] = {
  135540. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  135541. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  135542. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  135543. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  135544. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  135545. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  135546. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  135547. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  135548. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  135549. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  135550. 16,13,13,12,12,14,14,15,13,
  135551. };
  135552. static float _vq_quantthresh__44c0_s_p8_1[] = {
  135553. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135554. 42.5, 59.5, 76.5, 93.5,
  135555. };
  135556. static long _vq_quantmap__44c0_s_p8_1[] = {
  135557. 11, 9, 7, 5, 3, 1, 0, 2,
  135558. 4, 6, 8, 10, 12,
  135559. };
  135560. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  135561. _vq_quantthresh__44c0_s_p8_1,
  135562. _vq_quantmap__44c0_s_p8_1,
  135563. 13,
  135564. 13
  135565. };
  135566. static static_codebook _44c0_s_p8_1 = {
  135567. 2, 169,
  135568. _vq_lengthlist__44c0_s_p8_1,
  135569. 1, -522616832, 1620115456, 4, 0,
  135570. _vq_quantlist__44c0_s_p8_1,
  135571. NULL,
  135572. &_vq_auxt__44c0_s_p8_1,
  135573. NULL,
  135574. 0
  135575. };
  135576. static long _vq_quantlist__44c0_s_p8_2[] = {
  135577. 8,
  135578. 7,
  135579. 9,
  135580. 6,
  135581. 10,
  135582. 5,
  135583. 11,
  135584. 4,
  135585. 12,
  135586. 3,
  135587. 13,
  135588. 2,
  135589. 14,
  135590. 1,
  135591. 15,
  135592. 0,
  135593. 16,
  135594. };
  135595. static long _vq_lengthlist__44c0_s_p8_2[] = {
  135596. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135597. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  135598. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135599. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  135600. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  135601. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  135602. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  135603. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  135604. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  135605. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  135606. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  135607. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  135608. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  135609. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135610. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  135611. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  135612. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  135613. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  135614. 10,
  135615. };
  135616. static float _vq_quantthresh__44c0_s_p8_2[] = {
  135617. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135618. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135619. };
  135620. static long _vq_quantmap__44c0_s_p8_2[] = {
  135621. 15, 13, 11, 9, 7, 5, 3, 1,
  135622. 0, 2, 4, 6, 8, 10, 12, 14,
  135623. 16,
  135624. };
  135625. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  135626. _vq_quantthresh__44c0_s_p8_2,
  135627. _vq_quantmap__44c0_s_p8_2,
  135628. 17,
  135629. 17
  135630. };
  135631. static static_codebook _44c0_s_p8_2 = {
  135632. 2, 289,
  135633. _vq_lengthlist__44c0_s_p8_2,
  135634. 1, -529530880, 1611661312, 5, 0,
  135635. _vq_quantlist__44c0_s_p8_2,
  135636. NULL,
  135637. &_vq_auxt__44c0_s_p8_2,
  135638. NULL,
  135639. 0
  135640. };
  135641. static long _huff_lengthlist__44c0_s_short[] = {
  135642. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  135643. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  135644. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  135645. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  135646. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  135647. 12,
  135648. };
  135649. static static_codebook _huff_book__44c0_s_short = {
  135650. 2, 81,
  135651. _huff_lengthlist__44c0_s_short,
  135652. 0, 0, 0, 0, 0,
  135653. NULL,
  135654. NULL,
  135655. NULL,
  135656. NULL,
  135657. 0
  135658. };
  135659. static long _huff_lengthlist__44c0_sm_long[] = {
  135660. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  135661. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  135662. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  135663. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  135664. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  135665. 13,
  135666. };
  135667. static static_codebook _huff_book__44c0_sm_long = {
  135668. 2, 81,
  135669. _huff_lengthlist__44c0_sm_long,
  135670. 0, 0, 0, 0, 0,
  135671. NULL,
  135672. NULL,
  135673. NULL,
  135674. NULL,
  135675. 0
  135676. };
  135677. static long _vq_quantlist__44c0_sm_p1_0[] = {
  135678. 1,
  135679. 0,
  135680. 2,
  135681. };
  135682. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  135683. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135684. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135688. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135689. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135693. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  135694. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  135729. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135734. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135739. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135774. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135775. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135779. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135780. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  135781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135784. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135785. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  135786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0,
  136094. };
  136095. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136096. -0.5, 0.5,
  136097. };
  136098. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136099. 1, 0, 2,
  136100. };
  136101. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136102. _vq_quantthresh__44c0_sm_p1_0,
  136103. _vq_quantmap__44c0_sm_p1_0,
  136104. 3,
  136105. 3
  136106. };
  136107. static static_codebook _44c0_sm_p1_0 = {
  136108. 8, 6561,
  136109. _vq_lengthlist__44c0_sm_p1_0,
  136110. 1, -535822336, 1611661312, 2, 0,
  136111. _vq_quantlist__44c0_sm_p1_0,
  136112. NULL,
  136113. &_vq_auxt__44c0_sm_p1_0,
  136114. NULL,
  136115. 0
  136116. };
  136117. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136118. 2,
  136119. 1,
  136120. 3,
  136121. 0,
  136122. 4,
  136123. };
  136124. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  136125. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0,
  136165. };
  136166. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  136167. -1.5, -0.5, 0.5, 1.5,
  136168. };
  136169. static long _vq_quantmap__44c0_sm_p2_0[] = {
  136170. 3, 1, 0, 2, 4,
  136171. };
  136172. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  136173. _vq_quantthresh__44c0_sm_p2_0,
  136174. _vq_quantmap__44c0_sm_p2_0,
  136175. 5,
  136176. 5
  136177. };
  136178. static static_codebook _44c0_sm_p2_0 = {
  136179. 4, 625,
  136180. _vq_lengthlist__44c0_sm_p2_0,
  136181. 1, -533725184, 1611661312, 3, 0,
  136182. _vq_quantlist__44c0_sm_p2_0,
  136183. NULL,
  136184. &_vq_auxt__44c0_sm_p2_0,
  136185. NULL,
  136186. 0
  136187. };
  136188. static long _vq_quantlist__44c0_sm_p3_0[] = {
  136189. 4,
  136190. 3,
  136191. 5,
  136192. 2,
  136193. 6,
  136194. 1,
  136195. 7,
  136196. 0,
  136197. 8,
  136198. };
  136199. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  136200. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  136201. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  136202. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  136203. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  136204. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0,
  136206. };
  136207. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  136208. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136209. };
  136210. static long _vq_quantmap__44c0_sm_p3_0[] = {
  136211. 7, 5, 3, 1, 0, 2, 4, 6,
  136212. 8,
  136213. };
  136214. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  136215. _vq_quantthresh__44c0_sm_p3_0,
  136216. _vq_quantmap__44c0_sm_p3_0,
  136217. 9,
  136218. 9
  136219. };
  136220. static static_codebook _44c0_sm_p3_0 = {
  136221. 2, 81,
  136222. _vq_lengthlist__44c0_sm_p3_0,
  136223. 1, -531628032, 1611661312, 4, 0,
  136224. _vq_quantlist__44c0_sm_p3_0,
  136225. NULL,
  136226. &_vq_auxt__44c0_sm_p3_0,
  136227. NULL,
  136228. 0
  136229. };
  136230. static long _vq_quantlist__44c0_sm_p4_0[] = {
  136231. 4,
  136232. 3,
  136233. 5,
  136234. 2,
  136235. 6,
  136236. 1,
  136237. 7,
  136238. 0,
  136239. 8,
  136240. };
  136241. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  136242. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  136243. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136244. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136245. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  136246. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  136247. 11,
  136248. };
  136249. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  136250. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136251. };
  136252. static long _vq_quantmap__44c0_sm_p4_0[] = {
  136253. 7, 5, 3, 1, 0, 2, 4, 6,
  136254. 8,
  136255. };
  136256. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  136257. _vq_quantthresh__44c0_sm_p4_0,
  136258. _vq_quantmap__44c0_sm_p4_0,
  136259. 9,
  136260. 9
  136261. };
  136262. static static_codebook _44c0_sm_p4_0 = {
  136263. 2, 81,
  136264. _vq_lengthlist__44c0_sm_p4_0,
  136265. 1, -531628032, 1611661312, 4, 0,
  136266. _vq_quantlist__44c0_sm_p4_0,
  136267. NULL,
  136268. &_vq_auxt__44c0_sm_p4_0,
  136269. NULL,
  136270. 0
  136271. };
  136272. static long _vq_quantlist__44c0_sm_p5_0[] = {
  136273. 8,
  136274. 7,
  136275. 9,
  136276. 6,
  136277. 10,
  136278. 5,
  136279. 11,
  136280. 4,
  136281. 12,
  136282. 3,
  136283. 13,
  136284. 2,
  136285. 14,
  136286. 1,
  136287. 15,
  136288. 0,
  136289. 16,
  136290. };
  136291. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  136292. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  136293. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  136294. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136295. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  136296. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  136297. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  136298. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  136299. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136300. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  136301. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136302. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136303. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136304. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  136305. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  136306. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  136307. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  136308. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136310. 14,
  136311. };
  136312. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  136313. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136314. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136315. };
  136316. static long _vq_quantmap__44c0_sm_p5_0[] = {
  136317. 15, 13, 11, 9, 7, 5, 3, 1,
  136318. 0, 2, 4, 6, 8, 10, 12, 14,
  136319. 16,
  136320. };
  136321. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  136322. _vq_quantthresh__44c0_sm_p5_0,
  136323. _vq_quantmap__44c0_sm_p5_0,
  136324. 17,
  136325. 17
  136326. };
  136327. static static_codebook _44c0_sm_p5_0 = {
  136328. 2, 289,
  136329. _vq_lengthlist__44c0_sm_p5_0,
  136330. 1, -529530880, 1611661312, 5, 0,
  136331. _vq_quantlist__44c0_sm_p5_0,
  136332. NULL,
  136333. &_vq_auxt__44c0_sm_p5_0,
  136334. NULL,
  136335. 0
  136336. };
  136337. static long _vq_quantlist__44c0_sm_p6_0[] = {
  136338. 1,
  136339. 0,
  136340. 2,
  136341. };
  136342. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  136343. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136344. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136345. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136346. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  136347. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136348. 11,
  136349. };
  136350. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  136351. -5.5, 5.5,
  136352. };
  136353. static long _vq_quantmap__44c0_sm_p6_0[] = {
  136354. 1, 0, 2,
  136355. };
  136356. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  136357. _vq_quantthresh__44c0_sm_p6_0,
  136358. _vq_quantmap__44c0_sm_p6_0,
  136359. 3,
  136360. 3
  136361. };
  136362. static static_codebook _44c0_sm_p6_0 = {
  136363. 4, 81,
  136364. _vq_lengthlist__44c0_sm_p6_0,
  136365. 1, -529137664, 1618345984, 2, 0,
  136366. _vq_quantlist__44c0_sm_p6_0,
  136367. NULL,
  136368. &_vq_auxt__44c0_sm_p6_0,
  136369. NULL,
  136370. 0
  136371. };
  136372. static long _vq_quantlist__44c0_sm_p6_1[] = {
  136373. 5,
  136374. 4,
  136375. 6,
  136376. 3,
  136377. 7,
  136378. 2,
  136379. 8,
  136380. 1,
  136381. 9,
  136382. 0,
  136383. 10,
  136384. };
  136385. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  136386. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  136387. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136388. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136389. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  136390. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  136391. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136392. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136393. 10,10,10, 8, 8, 8, 8, 8, 8,
  136394. };
  136395. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  136396. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136397. 3.5, 4.5,
  136398. };
  136399. static long _vq_quantmap__44c0_sm_p6_1[] = {
  136400. 9, 7, 5, 3, 1, 0, 2, 4,
  136401. 6, 8, 10,
  136402. };
  136403. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  136404. _vq_quantthresh__44c0_sm_p6_1,
  136405. _vq_quantmap__44c0_sm_p6_1,
  136406. 11,
  136407. 11
  136408. };
  136409. static static_codebook _44c0_sm_p6_1 = {
  136410. 2, 121,
  136411. _vq_lengthlist__44c0_sm_p6_1,
  136412. 1, -531365888, 1611661312, 4, 0,
  136413. _vq_quantlist__44c0_sm_p6_1,
  136414. NULL,
  136415. &_vq_auxt__44c0_sm_p6_1,
  136416. NULL,
  136417. 0
  136418. };
  136419. static long _vq_quantlist__44c0_sm_p7_0[] = {
  136420. 6,
  136421. 5,
  136422. 7,
  136423. 4,
  136424. 8,
  136425. 3,
  136426. 9,
  136427. 2,
  136428. 10,
  136429. 1,
  136430. 11,
  136431. 0,
  136432. 12,
  136433. };
  136434. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  136435. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136436. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  136437. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136438. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136439. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136440. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  136441. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136442. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136443. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136444. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  136445. 0,12,12,11,11,13,12,14,14,
  136446. };
  136447. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  136448. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136449. 12.5, 17.5, 22.5, 27.5,
  136450. };
  136451. static long _vq_quantmap__44c0_sm_p7_0[] = {
  136452. 11, 9, 7, 5, 3, 1, 0, 2,
  136453. 4, 6, 8, 10, 12,
  136454. };
  136455. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  136456. _vq_quantthresh__44c0_sm_p7_0,
  136457. _vq_quantmap__44c0_sm_p7_0,
  136458. 13,
  136459. 13
  136460. };
  136461. static static_codebook _44c0_sm_p7_0 = {
  136462. 2, 169,
  136463. _vq_lengthlist__44c0_sm_p7_0,
  136464. 1, -526516224, 1616117760, 4, 0,
  136465. _vq_quantlist__44c0_sm_p7_0,
  136466. NULL,
  136467. &_vq_auxt__44c0_sm_p7_0,
  136468. NULL,
  136469. 0
  136470. };
  136471. static long _vq_quantlist__44c0_sm_p7_1[] = {
  136472. 2,
  136473. 1,
  136474. 3,
  136475. 0,
  136476. 4,
  136477. };
  136478. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  136479. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136480. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136481. };
  136482. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  136483. -1.5, -0.5, 0.5, 1.5,
  136484. };
  136485. static long _vq_quantmap__44c0_sm_p7_1[] = {
  136486. 3, 1, 0, 2, 4,
  136487. };
  136488. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  136489. _vq_quantthresh__44c0_sm_p7_1,
  136490. _vq_quantmap__44c0_sm_p7_1,
  136491. 5,
  136492. 5
  136493. };
  136494. static static_codebook _44c0_sm_p7_1 = {
  136495. 2, 25,
  136496. _vq_lengthlist__44c0_sm_p7_1,
  136497. 1, -533725184, 1611661312, 3, 0,
  136498. _vq_quantlist__44c0_sm_p7_1,
  136499. NULL,
  136500. &_vq_auxt__44c0_sm_p7_1,
  136501. NULL,
  136502. 0
  136503. };
  136504. static long _vq_quantlist__44c0_sm_p8_0[] = {
  136505. 4,
  136506. 3,
  136507. 5,
  136508. 2,
  136509. 6,
  136510. 1,
  136511. 7,
  136512. 0,
  136513. 8,
  136514. };
  136515. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  136516. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  136517. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  136518. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136519. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136520. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136521. 12,
  136522. };
  136523. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  136524. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  136525. };
  136526. static long _vq_quantmap__44c0_sm_p8_0[] = {
  136527. 7, 5, 3, 1, 0, 2, 4, 6,
  136528. 8,
  136529. };
  136530. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  136531. _vq_quantthresh__44c0_sm_p8_0,
  136532. _vq_quantmap__44c0_sm_p8_0,
  136533. 9,
  136534. 9
  136535. };
  136536. static static_codebook _44c0_sm_p8_0 = {
  136537. 2, 81,
  136538. _vq_lengthlist__44c0_sm_p8_0,
  136539. 1, -516186112, 1627103232, 4, 0,
  136540. _vq_quantlist__44c0_sm_p8_0,
  136541. NULL,
  136542. &_vq_auxt__44c0_sm_p8_0,
  136543. NULL,
  136544. 0
  136545. };
  136546. static long _vq_quantlist__44c0_sm_p8_1[] = {
  136547. 6,
  136548. 5,
  136549. 7,
  136550. 4,
  136551. 8,
  136552. 3,
  136553. 9,
  136554. 2,
  136555. 10,
  136556. 1,
  136557. 11,
  136558. 0,
  136559. 12,
  136560. };
  136561. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  136562. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  136563. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  136564. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  136565. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  136566. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  136567. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  136568. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  136569. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  136570. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  136571. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  136572. 20,13,13,12,12,16,13,15,13,
  136573. };
  136574. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  136575. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136576. 42.5, 59.5, 76.5, 93.5,
  136577. };
  136578. static long _vq_quantmap__44c0_sm_p8_1[] = {
  136579. 11, 9, 7, 5, 3, 1, 0, 2,
  136580. 4, 6, 8, 10, 12,
  136581. };
  136582. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  136583. _vq_quantthresh__44c0_sm_p8_1,
  136584. _vq_quantmap__44c0_sm_p8_1,
  136585. 13,
  136586. 13
  136587. };
  136588. static static_codebook _44c0_sm_p8_1 = {
  136589. 2, 169,
  136590. _vq_lengthlist__44c0_sm_p8_1,
  136591. 1, -522616832, 1620115456, 4, 0,
  136592. _vq_quantlist__44c0_sm_p8_1,
  136593. NULL,
  136594. &_vq_auxt__44c0_sm_p8_1,
  136595. NULL,
  136596. 0
  136597. };
  136598. static long _vq_quantlist__44c0_sm_p8_2[] = {
  136599. 8,
  136600. 7,
  136601. 9,
  136602. 6,
  136603. 10,
  136604. 5,
  136605. 11,
  136606. 4,
  136607. 12,
  136608. 3,
  136609. 13,
  136610. 2,
  136611. 14,
  136612. 1,
  136613. 15,
  136614. 0,
  136615. 16,
  136616. };
  136617. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  136618. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136619. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136620. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  136621. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136622. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136623. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  136624. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  136625. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  136626. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  136627. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  136628. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  136629. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136630. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  136631. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  136632. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  136633. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136634. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136635. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  136636. 9,
  136637. };
  136638. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  136639. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136640. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136641. };
  136642. static long _vq_quantmap__44c0_sm_p8_2[] = {
  136643. 15, 13, 11, 9, 7, 5, 3, 1,
  136644. 0, 2, 4, 6, 8, 10, 12, 14,
  136645. 16,
  136646. };
  136647. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  136648. _vq_quantthresh__44c0_sm_p8_2,
  136649. _vq_quantmap__44c0_sm_p8_2,
  136650. 17,
  136651. 17
  136652. };
  136653. static static_codebook _44c0_sm_p8_2 = {
  136654. 2, 289,
  136655. _vq_lengthlist__44c0_sm_p8_2,
  136656. 1, -529530880, 1611661312, 5, 0,
  136657. _vq_quantlist__44c0_sm_p8_2,
  136658. NULL,
  136659. &_vq_auxt__44c0_sm_p8_2,
  136660. NULL,
  136661. 0
  136662. };
  136663. static long _huff_lengthlist__44c0_sm_short[] = {
  136664. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  136665. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  136666. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  136667. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  136668. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  136669. 12,
  136670. };
  136671. static static_codebook _huff_book__44c0_sm_short = {
  136672. 2, 81,
  136673. _huff_lengthlist__44c0_sm_short,
  136674. 0, 0, 0, 0, 0,
  136675. NULL,
  136676. NULL,
  136677. NULL,
  136678. NULL,
  136679. 0
  136680. };
  136681. static long _huff_lengthlist__44c1_s_long[] = {
  136682. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  136683. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  136684. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  136685. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  136686. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  136687. 11,
  136688. };
  136689. static static_codebook _huff_book__44c1_s_long = {
  136690. 2, 81,
  136691. _huff_lengthlist__44c1_s_long,
  136692. 0, 0, 0, 0, 0,
  136693. NULL,
  136694. NULL,
  136695. NULL,
  136696. NULL,
  136697. 0
  136698. };
  136699. static long _vq_quantlist__44c1_s_p1_0[] = {
  136700. 1,
  136701. 0,
  136702. 2,
  136703. };
  136704. static long _vq_lengthlist__44c1_s_p1_0[] = {
  136705. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  136706. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136710. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  136711. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136715. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  136716. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  136751. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  136752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  136756. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  136757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  136761. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  136762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136796. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  136797. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136801. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  136802. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  136803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136806. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  136807. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0,
  137116. };
  137117. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137118. -0.5, 0.5,
  137119. };
  137120. static long _vq_quantmap__44c1_s_p1_0[] = {
  137121. 1, 0, 2,
  137122. };
  137123. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137124. _vq_quantthresh__44c1_s_p1_0,
  137125. _vq_quantmap__44c1_s_p1_0,
  137126. 3,
  137127. 3
  137128. };
  137129. static static_codebook _44c1_s_p1_0 = {
  137130. 8, 6561,
  137131. _vq_lengthlist__44c1_s_p1_0,
  137132. 1, -535822336, 1611661312, 2, 0,
  137133. _vq_quantlist__44c1_s_p1_0,
  137134. NULL,
  137135. &_vq_auxt__44c1_s_p1_0,
  137136. NULL,
  137137. 0
  137138. };
  137139. static long _vq_quantlist__44c1_s_p2_0[] = {
  137140. 2,
  137141. 1,
  137142. 3,
  137143. 0,
  137144. 4,
  137145. };
  137146. static long _vq_lengthlist__44c1_s_p2_0[] = {
  137147. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0,
  137187. };
  137188. static float _vq_quantthresh__44c1_s_p2_0[] = {
  137189. -1.5, -0.5, 0.5, 1.5,
  137190. };
  137191. static long _vq_quantmap__44c1_s_p2_0[] = {
  137192. 3, 1, 0, 2, 4,
  137193. };
  137194. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  137195. _vq_quantthresh__44c1_s_p2_0,
  137196. _vq_quantmap__44c1_s_p2_0,
  137197. 5,
  137198. 5
  137199. };
  137200. static static_codebook _44c1_s_p2_0 = {
  137201. 4, 625,
  137202. _vq_lengthlist__44c1_s_p2_0,
  137203. 1, -533725184, 1611661312, 3, 0,
  137204. _vq_quantlist__44c1_s_p2_0,
  137205. NULL,
  137206. &_vq_auxt__44c1_s_p2_0,
  137207. NULL,
  137208. 0
  137209. };
  137210. static long _vq_quantlist__44c1_s_p3_0[] = {
  137211. 4,
  137212. 3,
  137213. 5,
  137214. 2,
  137215. 6,
  137216. 1,
  137217. 7,
  137218. 0,
  137219. 8,
  137220. };
  137221. static long _vq_lengthlist__44c1_s_p3_0[] = {
  137222. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  137223. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137224. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137225. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137226. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0,
  137228. };
  137229. static float _vq_quantthresh__44c1_s_p3_0[] = {
  137230. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137231. };
  137232. static long _vq_quantmap__44c1_s_p3_0[] = {
  137233. 7, 5, 3, 1, 0, 2, 4, 6,
  137234. 8,
  137235. };
  137236. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  137237. _vq_quantthresh__44c1_s_p3_0,
  137238. _vq_quantmap__44c1_s_p3_0,
  137239. 9,
  137240. 9
  137241. };
  137242. static static_codebook _44c1_s_p3_0 = {
  137243. 2, 81,
  137244. _vq_lengthlist__44c1_s_p3_0,
  137245. 1, -531628032, 1611661312, 4, 0,
  137246. _vq_quantlist__44c1_s_p3_0,
  137247. NULL,
  137248. &_vq_auxt__44c1_s_p3_0,
  137249. NULL,
  137250. 0
  137251. };
  137252. static long _vq_quantlist__44c1_s_p4_0[] = {
  137253. 4,
  137254. 3,
  137255. 5,
  137256. 2,
  137257. 6,
  137258. 1,
  137259. 7,
  137260. 0,
  137261. 8,
  137262. };
  137263. static long _vq_lengthlist__44c1_s_p4_0[] = {
  137264. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  137265. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137266. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  137267. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  137268. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137269. 11,
  137270. };
  137271. static float _vq_quantthresh__44c1_s_p4_0[] = {
  137272. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137273. };
  137274. static long _vq_quantmap__44c1_s_p4_0[] = {
  137275. 7, 5, 3, 1, 0, 2, 4, 6,
  137276. 8,
  137277. };
  137278. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  137279. _vq_quantthresh__44c1_s_p4_0,
  137280. _vq_quantmap__44c1_s_p4_0,
  137281. 9,
  137282. 9
  137283. };
  137284. static static_codebook _44c1_s_p4_0 = {
  137285. 2, 81,
  137286. _vq_lengthlist__44c1_s_p4_0,
  137287. 1, -531628032, 1611661312, 4, 0,
  137288. _vq_quantlist__44c1_s_p4_0,
  137289. NULL,
  137290. &_vq_auxt__44c1_s_p4_0,
  137291. NULL,
  137292. 0
  137293. };
  137294. static long _vq_quantlist__44c1_s_p5_0[] = {
  137295. 8,
  137296. 7,
  137297. 9,
  137298. 6,
  137299. 10,
  137300. 5,
  137301. 11,
  137302. 4,
  137303. 12,
  137304. 3,
  137305. 13,
  137306. 2,
  137307. 14,
  137308. 1,
  137309. 15,
  137310. 0,
  137311. 16,
  137312. };
  137313. static long _vq_lengthlist__44c1_s_p5_0[] = {
  137314. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  137315. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137316. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137317. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137318. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137319. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  137320. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  137321. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137322. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137323. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137324. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137325. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137326. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  137327. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137328. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  137329. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  137330. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137332. 14,
  137333. };
  137334. static float _vq_quantthresh__44c1_s_p5_0[] = {
  137335. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137336. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137337. };
  137338. static long _vq_quantmap__44c1_s_p5_0[] = {
  137339. 15, 13, 11, 9, 7, 5, 3, 1,
  137340. 0, 2, 4, 6, 8, 10, 12, 14,
  137341. 16,
  137342. };
  137343. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  137344. _vq_quantthresh__44c1_s_p5_0,
  137345. _vq_quantmap__44c1_s_p5_0,
  137346. 17,
  137347. 17
  137348. };
  137349. static static_codebook _44c1_s_p5_0 = {
  137350. 2, 289,
  137351. _vq_lengthlist__44c1_s_p5_0,
  137352. 1, -529530880, 1611661312, 5, 0,
  137353. _vq_quantlist__44c1_s_p5_0,
  137354. NULL,
  137355. &_vq_auxt__44c1_s_p5_0,
  137356. NULL,
  137357. 0
  137358. };
  137359. static long _vq_quantlist__44c1_s_p6_0[] = {
  137360. 1,
  137361. 0,
  137362. 2,
  137363. };
  137364. static long _vq_lengthlist__44c1_s_p6_0[] = {
  137365. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137366. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  137367. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137368. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  137369. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  137370. 11,
  137371. };
  137372. static float _vq_quantthresh__44c1_s_p6_0[] = {
  137373. -5.5, 5.5,
  137374. };
  137375. static long _vq_quantmap__44c1_s_p6_0[] = {
  137376. 1, 0, 2,
  137377. };
  137378. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  137379. _vq_quantthresh__44c1_s_p6_0,
  137380. _vq_quantmap__44c1_s_p6_0,
  137381. 3,
  137382. 3
  137383. };
  137384. static static_codebook _44c1_s_p6_0 = {
  137385. 4, 81,
  137386. _vq_lengthlist__44c1_s_p6_0,
  137387. 1, -529137664, 1618345984, 2, 0,
  137388. _vq_quantlist__44c1_s_p6_0,
  137389. NULL,
  137390. &_vq_auxt__44c1_s_p6_0,
  137391. NULL,
  137392. 0
  137393. };
  137394. static long _vq_quantlist__44c1_s_p6_1[] = {
  137395. 5,
  137396. 4,
  137397. 6,
  137398. 3,
  137399. 7,
  137400. 2,
  137401. 8,
  137402. 1,
  137403. 9,
  137404. 0,
  137405. 10,
  137406. };
  137407. static long _vq_lengthlist__44c1_s_p6_1[] = {
  137408. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  137409. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  137410. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137411. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  137412. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  137413. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137414. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137415. 10,10,10, 8, 8, 8, 8, 8, 8,
  137416. };
  137417. static float _vq_quantthresh__44c1_s_p6_1[] = {
  137418. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137419. 3.5, 4.5,
  137420. };
  137421. static long _vq_quantmap__44c1_s_p6_1[] = {
  137422. 9, 7, 5, 3, 1, 0, 2, 4,
  137423. 6, 8, 10,
  137424. };
  137425. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  137426. _vq_quantthresh__44c1_s_p6_1,
  137427. _vq_quantmap__44c1_s_p6_1,
  137428. 11,
  137429. 11
  137430. };
  137431. static static_codebook _44c1_s_p6_1 = {
  137432. 2, 121,
  137433. _vq_lengthlist__44c1_s_p6_1,
  137434. 1, -531365888, 1611661312, 4, 0,
  137435. _vq_quantlist__44c1_s_p6_1,
  137436. NULL,
  137437. &_vq_auxt__44c1_s_p6_1,
  137438. NULL,
  137439. 0
  137440. };
  137441. static long _vq_quantlist__44c1_s_p7_0[] = {
  137442. 6,
  137443. 5,
  137444. 7,
  137445. 4,
  137446. 8,
  137447. 3,
  137448. 9,
  137449. 2,
  137450. 10,
  137451. 1,
  137452. 11,
  137453. 0,
  137454. 12,
  137455. };
  137456. static long _vq_lengthlist__44c1_s_p7_0[] = {
  137457. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  137458. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  137459. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137460. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137461. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  137462. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  137463. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  137464. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137465. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137466. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  137467. 0,12,11,11,11,13,10,14,13,
  137468. };
  137469. static float _vq_quantthresh__44c1_s_p7_0[] = {
  137470. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137471. 12.5, 17.5, 22.5, 27.5,
  137472. };
  137473. static long _vq_quantmap__44c1_s_p7_0[] = {
  137474. 11, 9, 7, 5, 3, 1, 0, 2,
  137475. 4, 6, 8, 10, 12,
  137476. };
  137477. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  137478. _vq_quantthresh__44c1_s_p7_0,
  137479. _vq_quantmap__44c1_s_p7_0,
  137480. 13,
  137481. 13
  137482. };
  137483. static static_codebook _44c1_s_p7_0 = {
  137484. 2, 169,
  137485. _vq_lengthlist__44c1_s_p7_0,
  137486. 1, -526516224, 1616117760, 4, 0,
  137487. _vq_quantlist__44c1_s_p7_0,
  137488. NULL,
  137489. &_vq_auxt__44c1_s_p7_0,
  137490. NULL,
  137491. 0
  137492. };
  137493. static long _vq_quantlist__44c1_s_p7_1[] = {
  137494. 2,
  137495. 1,
  137496. 3,
  137497. 0,
  137498. 4,
  137499. };
  137500. static long _vq_lengthlist__44c1_s_p7_1[] = {
  137501. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  137502. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137503. };
  137504. static float _vq_quantthresh__44c1_s_p7_1[] = {
  137505. -1.5, -0.5, 0.5, 1.5,
  137506. };
  137507. static long _vq_quantmap__44c1_s_p7_1[] = {
  137508. 3, 1, 0, 2, 4,
  137509. };
  137510. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  137511. _vq_quantthresh__44c1_s_p7_1,
  137512. _vq_quantmap__44c1_s_p7_1,
  137513. 5,
  137514. 5
  137515. };
  137516. static static_codebook _44c1_s_p7_1 = {
  137517. 2, 25,
  137518. _vq_lengthlist__44c1_s_p7_1,
  137519. 1, -533725184, 1611661312, 3, 0,
  137520. _vq_quantlist__44c1_s_p7_1,
  137521. NULL,
  137522. &_vq_auxt__44c1_s_p7_1,
  137523. NULL,
  137524. 0
  137525. };
  137526. static long _vq_quantlist__44c1_s_p8_0[] = {
  137527. 6,
  137528. 5,
  137529. 7,
  137530. 4,
  137531. 8,
  137532. 3,
  137533. 9,
  137534. 2,
  137535. 10,
  137536. 1,
  137537. 11,
  137538. 0,
  137539. 12,
  137540. };
  137541. static long _vq_lengthlist__44c1_s_p8_0[] = {
  137542. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  137543. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  137544. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137545. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137546. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137547. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137548. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137549. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137550. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137551. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137552. 10,10,10,10,10,10,10,10,10,
  137553. };
  137554. static float _vq_quantthresh__44c1_s_p8_0[] = {
  137555. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  137556. 552.5, 773.5, 994.5, 1215.5,
  137557. };
  137558. static long _vq_quantmap__44c1_s_p8_0[] = {
  137559. 11, 9, 7, 5, 3, 1, 0, 2,
  137560. 4, 6, 8, 10, 12,
  137561. };
  137562. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  137563. _vq_quantthresh__44c1_s_p8_0,
  137564. _vq_quantmap__44c1_s_p8_0,
  137565. 13,
  137566. 13
  137567. };
  137568. static static_codebook _44c1_s_p8_0 = {
  137569. 2, 169,
  137570. _vq_lengthlist__44c1_s_p8_0,
  137571. 1, -514541568, 1627103232, 4, 0,
  137572. _vq_quantlist__44c1_s_p8_0,
  137573. NULL,
  137574. &_vq_auxt__44c1_s_p8_0,
  137575. NULL,
  137576. 0
  137577. };
  137578. static long _vq_quantlist__44c1_s_p8_1[] = {
  137579. 6,
  137580. 5,
  137581. 7,
  137582. 4,
  137583. 8,
  137584. 3,
  137585. 9,
  137586. 2,
  137587. 10,
  137588. 1,
  137589. 11,
  137590. 0,
  137591. 12,
  137592. };
  137593. static long _vq_lengthlist__44c1_s_p8_1[] = {
  137594. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  137595. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137596. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  137597. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  137598. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  137599. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  137600. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  137601. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  137602. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  137603. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  137604. 16,13,12,12,11,14,12,15,13,
  137605. };
  137606. static float _vq_quantthresh__44c1_s_p8_1[] = {
  137607. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137608. 42.5, 59.5, 76.5, 93.5,
  137609. };
  137610. static long _vq_quantmap__44c1_s_p8_1[] = {
  137611. 11, 9, 7, 5, 3, 1, 0, 2,
  137612. 4, 6, 8, 10, 12,
  137613. };
  137614. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  137615. _vq_quantthresh__44c1_s_p8_1,
  137616. _vq_quantmap__44c1_s_p8_1,
  137617. 13,
  137618. 13
  137619. };
  137620. static static_codebook _44c1_s_p8_1 = {
  137621. 2, 169,
  137622. _vq_lengthlist__44c1_s_p8_1,
  137623. 1, -522616832, 1620115456, 4, 0,
  137624. _vq_quantlist__44c1_s_p8_1,
  137625. NULL,
  137626. &_vq_auxt__44c1_s_p8_1,
  137627. NULL,
  137628. 0
  137629. };
  137630. static long _vq_quantlist__44c1_s_p8_2[] = {
  137631. 8,
  137632. 7,
  137633. 9,
  137634. 6,
  137635. 10,
  137636. 5,
  137637. 11,
  137638. 4,
  137639. 12,
  137640. 3,
  137641. 13,
  137642. 2,
  137643. 14,
  137644. 1,
  137645. 15,
  137646. 0,
  137647. 16,
  137648. };
  137649. static long _vq_lengthlist__44c1_s_p8_2[] = {
  137650. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137651. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137652. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137653. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137654. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137655. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137656. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137657. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  137658. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  137659. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  137660. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  137661. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  137662. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  137663. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  137664. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137665. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  137666. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  137667. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  137668. 9,
  137669. };
  137670. static float _vq_quantthresh__44c1_s_p8_2[] = {
  137671. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137672. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137673. };
  137674. static long _vq_quantmap__44c1_s_p8_2[] = {
  137675. 15, 13, 11, 9, 7, 5, 3, 1,
  137676. 0, 2, 4, 6, 8, 10, 12, 14,
  137677. 16,
  137678. };
  137679. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  137680. _vq_quantthresh__44c1_s_p8_2,
  137681. _vq_quantmap__44c1_s_p8_2,
  137682. 17,
  137683. 17
  137684. };
  137685. static static_codebook _44c1_s_p8_2 = {
  137686. 2, 289,
  137687. _vq_lengthlist__44c1_s_p8_2,
  137688. 1, -529530880, 1611661312, 5, 0,
  137689. _vq_quantlist__44c1_s_p8_2,
  137690. NULL,
  137691. &_vq_auxt__44c1_s_p8_2,
  137692. NULL,
  137693. 0
  137694. };
  137695. static long _huff_lengthlist__44c1_s_short[] = {
  137696. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  137697. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  137698. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  137699. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  137700. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  137701. 11,
  137702. };
  137703. static static_codebook _huff_book__44c1_s_short = {
  137704. 2, 81,
  137705. _huff_lengthlist__44c1_s_short,
  137706. 0, 0, 0, 0, 0,
  137707. NULL,
  137708. NULL,
  137709. NULL,
  137710. NULL,
  137711. 0
  137712. };
  137713. static long _huff_lengthlist__44c1_sm_long[] = {
  137714. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  137715. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  137716. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  137717. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  137718. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  137719. 11,
  137720. };
  137721. static static_codebook _huff_book__44c1_sm_long = {
  137722. 2, 81,
  137723. _huff_lengthlist__44c1_sm_long,
  137724. 0, 0, 0, 0, 0,
  137725. NULL,
  137726. NULL,
  137727. NULL,
  137728. NULL,
  137729. 0
  137730. };
  137731. static long _vq_quantlist__44c1_sm_p1_0[] = {
  137732. 1,
  137733. 0,
  137734. 2,
  137735. };
  137736. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  137737. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137738. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137742. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137743. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137747. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137748. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  137783. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  137784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137788. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137793. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137828. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  137829. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137833. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137834. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  137835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137838. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137839. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  137840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0,
  138148. };
  138149. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  138150. -0.5, 0.5,
  138151. };
  138152. static long _vq_quantmap__44c1_sm_p1_0[] = {
  138153. 1, 0, 2,
  138154. };
  138155. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  138156. _vq_quantthresh__44c1_sm_p1_0,
  138157. _vq_quantmap__44c1_sm_p1_0,
  138158. 3,
  138159. 3
  138160. };
  138161. static static_codebook _44c1_sm_p1_0 = {
  138162. 8, 6561,
  138163. _vq_lengthlist__44c1_sm_p1_0,
  138164. 1, -535822336, 1611661312, 2, 0,
  138165. _vq_quantlist__44c1_sm_p1_0,
  138166. NULL,
  138167. &_vq_auxt__44c1_sm_p1_0,
  138168. NULL,
  138169. 0
  138170. };
  138171. static long _vq_quantlist__44c1_sm_p2_0[] = {
  138172. 2,
  138173. 1,
  138174. 3,
  138175. 0,
  138176. 4,
  138177. };
  138178. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  138179. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0,
  138219. };
  138220. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  138221. -1.5, -0.5, 0.5, 1.5,
  138222. };
  138223. static long _vq_quantmap__44c1_sm_p2_0[] = {
  138224. 3, 1, 0, 2, 4,
  138225. };
  138226. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  138227. _vq_quantthresh__44c1_sm_p2_0,
  138228. _vq_quantmap__44c1_sm_p2_0,
  138229. 5,
  138230. 5
  138231. };
  138232. static static_codebook _44c1_sm_p2_0 = {
  138233. 4, 625,
  138234. _vq_lengthlist__44c1_sm_p2_0,
  138235. 1, -533725184, 1611661312, 3, 0,
  138236. _vq_quantlist__44c1_sm_p2_0,
  138237. NULL,
  138238. &_vq_auxt__44c1_sm_p2_0,
  138239. NULL,
  138240. 0
  138241. };
  138242. static long _vq_quantlist__44c1_sm_p3_0[] = {
  138243. 4,
  138244. 3,
  138245. 5,
  138246. 2,
  138247. 6,
  138248. 1,
  138249. 7,
  138250. 0,
  138251. 8,
  138252. };
  138253. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  138254. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  138255. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  138256. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138257. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138258. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0,
  138260. };
  138261. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  138262. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138263. };
  138264. static long _vq_quantmap__44c1_sm_p3_0[] = {
  138265. 7, 5, 3, 1, 0, 2, 4, 6,
  138266. 8,
  138267. };
  138268. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  138269. _vq_quantthresh__44c1_sm_p3_0,
  138270. _vq_quantmap__44c1_sm_p3_0,
  138271. 9,
  138272. 9
  138273. };
  138274. static static_codebook _44c1_sm_p3_0 = {
  138275. 2, 81,
  138276. _vq_lengthlist__44c1_sm_p3_0,
  138277. 1, -531628032, 1611661312, 4, 0,
  138278. _vq_quantlist__44c1_sm_p3_0,
  138279. NULL,
  138280. &_vq_auxt__44c1_sm_p3_0,
  138281. NULL,
  138282. 0
  138283. };
  138284. static long _vq_quantlist__44c1_sm_p4_0[] = {
  138285. 4,
  138286. 3,
  138287. 5,
  138288. 2,
  138289. 6,
  138290. 1,
  138291. 7,
  138292. 0,
  138293. 8,
  138294. };
  138295. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  138296. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  138297. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138298. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138299. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  138300. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138301. 11,
  138302. };
  138303. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  138304. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138305. };
  138306. static long _vq_quantmap__44c1_sm_p4_0[] = {
  138307. 7, 5, 3, 1, 0, 2, 4, 6,
  138308. 8,
  138309. };
  138310. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  138311. _vq_quantthresh__44c1_sm_p4_0,
  138312. _vq_quantmap__44c1_sm_p4_0,
  138313. 9,
  138314. 9
  138315. };
  138316. static static_codebook _44c1_sm_p4_0 = {
  138317. 2, 81,
  138318. _vq_lengthlist__44c1_sm_p4_0,
  138319. 1, -531628032, 1611661312, 4, 0,
  138320. _vq_quantlist__44c1_sm_p4_0,
  138321. NULL,
  138322. &_vq_auxt__44c1_sm_p4_0,
  138323. NULL,
  138324. 0
  138325. };
  138326. static long _vq_quantlist__44c1_sm_p5_0[] = {
  138327. 8,
  138328. 7,
  138329. 9,
  138330. 6,
  138331. 10,
  138332. 5,
  138333. 11,
  138334. 4,
  138335. 12,
  138336. 3,
  138337. 13,
  138338. 2,
  138339. 14,
  138340. 1,
  138341. 15,
  138342. 0,
  138343. 16,
  138344. };
  138345. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  138346. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138347. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138348. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  138349. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138350. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138351. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  138352. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  138353. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138354. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138355. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138356. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138357. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138358. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138359. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138360. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  138361. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138362. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138364. 14,
  138365. };
  138366. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  138367. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138368. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138369. };
  138370. static long _vq_quantmap__44c1_sm_p5_0[] = {
  138371. 15, 13, 11, 9, 7, 5, 3, 1,
  138372. 0, 2, 4, 6, 8, 10, 12, 14,
  138373. 16,
  138374. };
  138375. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  138376. _vq_quantthresh__44c1_sm_p5_0,
  138377. _vq_quantmap__44c1_sm_p5_0,
  138378. 17,
  138379. 17
  138380. };
  138381. static static_codebook _44c1_sm_p5_0 = {
  138382. 2, 289,
  138383. _vq_lengthlist__44c1_sm_p5_0,
  138384. 1, -529530880, 1611661312, 5, 0,
  138385. _vq_quantlist__44c1_sm_p5_0,
  138386. NULL,
  138387. &_vq_auxt__44c1_sm_p5_0,
  138388. NULL,
  138389. 0
  138390. };
  138391. static long _vq_quantlist__44c1_sm_p6_0[] = {
  138392. 1,
  138393. 0,
  138394. 2,
  138395. };
  138396. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  138397. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138398. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  138399. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  138400. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  138401. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  138402. 11,
  138403. };
  138404. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  138405. -5.5, 5.5,
  138406. };
  138407. static long _vq_quantmap__44c1_sm_p6_0[] = {
  138408. 1, 0, 2,
  138409. };
  138410. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  138411. _vq_quantthresh__44c1_sm_p6_0,
  138412. _vq_quantmap__44c1_sm_p6_0,
  138413. 3,
  138414. 3
  138415. };
  138416. static static_codebook _44c1_sm_p6_0 = {
  138417. 4, 81,
  138418. _vq_lengthlist__44c1_sm_p6_0,
  138419. 1, -529137664, 1618345984, 2, 0,
  138420. _vq_quantlist__44c1_sm_p6_0,
  138421. NULL,
  138422. &_vq_auxt__44c1_sm_p6_0,
  138423. NULL,
  138424. 0
  138425. };
  138426. static long _vq_quantlist__44c1_sm_p6_1[] = {
  138427. 5,
  138428. 4,
  138429. 6,
  138430. 3,
  138431. 7,
  138432. 2,
  138433. 8,
  138434. 1,
  138435. 9,
  138436. 0,
  138437. 10,
  138438. };
  138439. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  138440. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  138441. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  138442. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  138443. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138444. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138445. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  138446. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138447. 10,10,10, 8, 8, 8, 8, 8, 8,
  138448. };
  138449. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  138450. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138451. 3.5, 4.5,
  138452. };
  138453. static long _vq_quantmap__44c1_sm_p6_1[] = {
  138454. 9, 7, 5, 3, 1, 0, 2, 4,
  138455. 6, 8, 10,
  138456. };
  138457. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  138458. _vq_quantthresh__44c1_sm_p6_1,
  138459. _vq_quantmap__44c1_sm_p6_1,
  138460. 11,
  138461. 11
  138462. };
  138463. static static_codebook _44c1_sm_p6_1 = {
  138464. 2, 121,
  138465. _vq_lengthlist__44c1_sm_p6_1,
  138466. 1, -531365888, 1611661312, 4, 0,
  138467. _vq_quantlist__44c1_sm_p6_1,
  138468. NULL,
  138469. &_vq_auxt__44c1_sm_p6_1,
  138470. NULL,
  138471. 0
  138472. };
  138473. static long _vq_quantlist__44c1_sm_p7_0[] = {
  138474. 6,
  138475. 5,
  138476. 7,
  138477. 4,
  138478. 8,
  138479. 3,
  138480. 9,
  138481. 2,
  138482. 10,
  138483. 1,
  138484. 11,
  138485. 0,
  138486. 12,
  138487. };
  138488. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  138489. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  138490. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  138491. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138492. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138493. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  138494. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  138495. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  138496. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138497. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138498. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  138499. 0,12,12,11,11,13,12,14,13,
  138500. };
  138501. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  138502. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138503. 12.5, 17.5, 22.5, 27.5,
  138504. };
  138505. static long _vq_quantmap__44c1_sm_p7_0[] = {
  138506. 11, 9, 7, 5, 3, 1, 0, 2,
  138507. 4, 6, 8, 10, 12,
  138508. };
  138509. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  138510. _vq_quantthresh__44c1_sm_p7_0,
  138511. _vq_quantmap__44c1_sm_p7_0,
  138512. 13,
  138513. 13
  138514. };
  138515. static static_codebook _44c1_sm_p7_0 = {
  138516. 2, 169,
  138517. _vq_lengthlist__44c1_sm_p7_0,
  138518. 1, -526516224, 1616117760, 4, 0,
  138519. _vq_quantlist__44c1_sm_p7_0,
  138520. NULL,
  138521. &_vq_auxt__44c1_sm_p7_0,
  138522. NULL,
  138523. 0
  138524. };
  138525. static long _vq_quantlist__44c1_sm_p7_1[] = {
  138526. 2,
  138527. 1,
  138528. 3,
  138529. 0,
  138530. 4,
  138531. };
  138532. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  138533. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  138534. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  138535. };
  138536. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  138537. -1.5, -0.5, 0.5, 1.5,
  138538. };
  138539. static long _vq_quantmap__44c1_sm_p7_1[] = {
  138540. 3, 1, 0, 2, 4,
  138541. };
  138542. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  138543. _vq_quantthresh__44c1_sm_p7_1,
  138544. _vq_quantmap__44c1_sm_p7_1,
  138545. 5,
  138546. 5
  138547. };
  138548. static static_codebook _44c1_sm_p7_1 = {
  138549. 2, 25,
  138550. _vq_lengthlist__44c1_sm_p7_1,
  138551. 1, -533725184, 1611661312, 3, 0,
  138552. _vq_quantlist__44c1_sm_p7_1,
  138553. NULL,
  138554. &_vq_auxt__44c1_sm_p7_1,
  138555. NULL,
  138556. 0
  138557. };
  138558. static long _vq_quantlist__44c1_sm_p8_0[] = {
  138559. 6,
  138560. 5,
  138561. 7,
  138562. 4,
  138563. 8,
  138564. 3,
  138565. 9,
  138566. 2,
  138567. 10,
  138568. 1,
  138569. 11,
  138570. 0,
  138571. 12,
  138572. };
  138573. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  138574. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  138575. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  138576. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138577. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138578. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138579. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138580. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138581. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138582. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138583. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138584. 13,13,13,13,13,13,13,13,13,
  138585. };
  138586. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  138587. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138588. 552.5, 773.5, 994.5, 1215.5,
  138589. };
  138590. static long _vq_quantmap__44c1_sm_p8_0[] = {
  138591. 11, 9, 7, 5, 3, 1, 0, 2,
  138592. 4, 6, 8, 10, 12,
  138593. };
  138594. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  138595. _vq_quantthresh__44c1_sm_p8_0,
  138596. _vq_quantmap__44c1_sm_p8_0,
  138597. 13,
  138598. 13
  138599. };
  138600. static static_codebook _44c1_sm_p8_0 = {
  138601. 2, 169,
  138602. _vq_lengthlist__44c1_sm_p8_0,
  138603. 1, -514541568, 1627103232, 4, 0,
  138604. _vq_quantlist__44c1_sm_p8_0,
  138605. NULL,
  138606. &_vq_auxt__44c1_sm_p8_0,
  138607. NULL,
  138608. 0
  138609. };
  138610. static long _vq_quantlist__44c1_sm_p8_1[] = {
  138611. 6,
  138612. 5,
  138613. 7,
  138614. 4,
  138615. 8,
  138616. 3,
  138617. 9,
  138618. 2,
  138619. 10,
  138620. 1,
  138621. 11,
  138622. 0,
  138623. 12,
  138624. };
  138625. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  138626. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  138627. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  138628. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  138629. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  138630. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  138631. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  138632. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  138633. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  138634. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  138635. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  138636. 20,13,12,12,12,14,12,14,13,
  138637. };
  138638. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  138639. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138640. 42.5, 59.5, 76.5, 93.5,
  138641. };
  138642. static long _vq_quantmap__44c1_sm_p8_1[] = {
  138643. 11, 9, 7, 5, 3, 1, 0, 2,
  138644. 4, 6, 8, 10, 12,
  138645. };
  138646. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  138647. _vq_quantthresh__44c1_sm_p8_1,
  138648. _vq_quantmap__44c1_sm_p8_1,
  138649. 13,
  138650. 13
  138651. };
  138652. static static_codebook _44c1_sm_p8_1 = {
  138653. 2, 169,
  138654. _vq_lengthlist__44c1_sm_p8_1,
  138655. 1, -522616832, 1620115456, 4, 0,
  138656. _vq_quantlist__44c1_sm_p8_1,
  138657. NULL,
  138658. &_vq_auxt__44c1_sm_p8_1,
  138659. NULL,
  138660. 0
  138661. };
  138662. static long _vq_quantlist__44c1_sm_p8_2[] = {
  138663. 8,
  138664. 7,
  138665. 9,
  138666. 6,
  138667. 10,
  138668. 5,
  138669. 11,
  138670. 4,
  138671. 12,
  138672. 3,
  138673. 13,
  138674. 2,
  138675. 14,
  138676. 1,
  138677. 15,
  138678. 0,
  138679. 16,
  138680. };
  138681. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  138682. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138683. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138684. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  138685. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138686. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  138687. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138688. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138689. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138690. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  138691. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138692. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  138693. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  138694. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  138695. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  138696. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138697. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  138698. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138699. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  138700. 9,
  138701. };
  138702. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  138703. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138704. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138705. };
  138706. static long _vq_quantmap__44c1_sm_p8_2[] = {
  138707. 15, 13, 11, 9, 7, 5, 3, 1,
  138708. 0, 2, 4, 6, 8, 10, 12, 14,
  138709. 16,
  138710. };
  138711. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  138712. _vq_quantthresh__44c1_sm_p8_2,
  138713. _vq_quantmap__44c1_sm_p8_2,
  138714. 17,
  138715. 17
  138716. };
  138717. static static_codebook _44c1_sm_p8_2 = {
  138718. 2, 289,
  138719. _vq_lengthlist__44c1_sm_p8_2,
  138720. 1, -529530880, 1611661312, 5, 0,
  138721. _vq_quantlist__44c1_sm_p8_2,
  138722. NULL,
  138723. &_vq_auxt__44c1_sm_p8_2,
  138724. NULL,
  138725. 0
  138726. };
  138727. static long _huff_lengthlist__44c1_sm_short[] = {
  138728. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  138729. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  138730. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  138731. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  138732. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  138733. 11,
  138734. };
  138735. static static_codebook _huff_book__44c1_sm_short = {
  138736. 2, 81,
  138737. _huff_lengthlist__44c1_sm_short,
  138738. 0, 0, 0, 0, 0,
  138739. NULL,
  138740. NULL,
  138741. NULL,
  138742. NULL,
  138743. 0
  138744. };
  138745. static long _huff_lengthlist__44cn1_s_long[] = {
  138746. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  138747. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  138748. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  138749. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  138750. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  138751. 20,
  138752. };
  138753. static static_codebook _huff_book__44cn1_s_long = {
  138754. 2, 81,
  138755. _huff_lengthlist__44cn1_s_long,
  138756. 0, 0, 0, 0, 0,
  138757. NULL,
  138758. NULL,
  138759. NULL,
  138760. NULL,
  138761. 0
  138762. };
  138763. static long _vq_quantlist__44cn1_s_p1_0[] = {
  138764. 1,
  138765. 0,
  138766. 2,
  138767. };
  138768. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  138769. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138770. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138774. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  138775. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138779. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  138780. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  138815. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  138816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  138820. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  138821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  138825. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  138826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138860. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  138861. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138865. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  138866. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  138867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138870. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  138871. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  138872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0,
  139180. };
  139181. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  139182. -0.5, 0.5,
  139183. };
  139184. static long _vq_quantmap__44cn1_s_p1_0[] = {
  139185. 1, 0, 2,
  139186. };
  139187. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  139188. _vq_quantthresh__44cn1_s_p1_0,
  139189. _vq_quantmap__44cn1_s_p1_0,
  139190. 3,
  139191. 3
  139192. };
  139193. static static_codebook _44cn1_s_p1_0 = {
  139194. 8, 6561,
  139195. _vq_lengthlist__44cn1_s_p1_0,
  139196. 1, -535822336, 1611661312, 2, 0,
  139197. _vq_quantlist__44cn1_s_p1_0,
  139198. NULL,
  139199. &_vq_auxt__44cn1_s_p1_0,
  139200. NULL,
  139201. 0
  139202. };
  139203. static long _vq_quantlist__44cn1_s_p2_0[] = {
  139204. 2,
  139205. 1,
  139206. 3,
  139207. 0,
  139208. 4,
  139209. };
  139210. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  139211. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0,
  139251. };
  139252. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  139253. -1.5, -0.5, 0.5, 1.5,
  139254. };
  139255. static long _vq_quantmap__44cn1_s_p2_0[] = {
  139256. 3, 1, 0, 2, 4,
  139257. };
  139258. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  139259. _vq_quantthresh__44cn1_s_p2_0,
  139260. _vq_quantmap__44cn1_s_p2_0,
  139261. 5,
  139262. 5
  139263. };
  139264. static static_codebook _44cn1_s_p2_0 = {
  139265. 4, 625,
  139266. _vq_lengthlist__44cn1_s_p2_0,
  139267. 1, -533725184, 1611661312, 3, 0,
  139268. _vq_quantlist__44cn1_s_p2_0,
  139269. NULL,
  139270. &_vq_auxt__44cn1_s_p2_0,
  139271. NULL,
  139272. 0
  139273. };
  139274. static long _vq_quantlist__44cn1_s_p3_0[] = {
  139275. 4,
  139276. 3,
  139277. 5,
  139278. 2,
  139279. 6,
  139280. 1,
  139281. 7,
  139282. 0,
  139283. 8,
  139284. };
  139285. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  139286. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  139287. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  139288. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139289. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139290. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0,
  139292. };
  139293. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  139294. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139295. };
  139296. static long _vq_quantmap__44cn1_s_p3_0[] = {
  139297. 7, 5, 3, 1, 0, 2, 4, 6,
  139298. 8,
  139299. };
  139300. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  139301. _vq_quantthresh__44cn1_s_p3_0,
  139302. _vq_quantmap__44cn1_s_p3_0,
  139303. 9,
  139304. 9
  139305. };
  139306. static static_codebook _44cn1_s_p3_0 = {
  139307. 2, 81,
  139308. _vq_lengthlist__44cn1_s_p3_0,
  139309. 1, -531628032, 1611661312, 4, 0,
  139310. _vq_quantlist__44cn1_s_p3_0,
  139311. NULL,
  139312. &_vq_auxt__44cn1_s_p3_0,
  139313. NULL,
  139314. 0
  139315. };
  139316. static long _vq_quantlist__44cn1_s_p4_0[] = {
  139317. 4,
  139318. 3,
  139319. 5,
  139320. 2,
  139321. 6,
  139322. 1,
  139323. 7,
  139324. 0,
  139325. 8,
  139326. };
  139327. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  139328. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  139329. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  139330. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  139331. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  139332. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  139333. 11,
  139334. };
  139335. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  139336. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139337. };
  139338. static long _vq_quantmap__44cn1_s_p4_0[] = {
  139339. 7, 5, 3, 1, 0, 2, 4, 6,
  139340. 8,
  139341. };
  139342. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  139343. _vq_quantthresh__44cn1_s_p4_0,
  139344. _vq_quantmap__44cn1_s_p4_0,
  139345. 9,
  139346. 9
  139347. };
  139348. static static_codebook _44cn1_s_p4_0 = {
  139349. 2, 81,
  139350. _vq_lengthlist__44cn1_s_p4_0,
  139351. 1, -531628032, 1611661312, 4, 0,
  139352. _vq_quantlist__44cn1_s_p4_0,
  139353. NULL,
  139354. &_vq_auxt__44cn1_s_p4_0,
  139355. NULL,
  139356. 0
  139357. };
  139358. static long _vq_quantlist__44cn1_s_p5_0[] = {
  139359. 8,
  139360. 7,
  139361. 9,
  139362. 6,
  139363. 10,
  139364. 5,
  139365. 11,
  139366. 4,
  139367. 12,
  139368. 3,
  139369. 13,
  139370. 2,
  139371. 14,
  139372. 1,
  139373. 15,
  139374. 0,
  139375. 16,
  139376. };
  139377. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  139378. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  139379. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139380. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  139381. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139382. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139383. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  139384. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  139385. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  139386. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139387. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  139388. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139389. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139390. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  139391. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139392. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  139393. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  139394. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  139396. 14,
  139397. };
  139398. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  139399. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139400. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139401. };
  139402. static long _vq_quantmap__44cn1_s_p5_0[] = {
  139403. 15, 13, 11, 9, 7, 5, 3, 1,
  139404. 0, 2, 4, 6, 8, 10, 12, 14,
  139405. 16,
  139406. };
  139407. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  139408. _vq_quantthresh__44cn1_s_p5_0,
  139409. _vq_quantmap__44cn1_s_p5_0,
  139410. 17,
  139411. 17
  139412. };
  139413. static static_codebook _44cn1_s_p5_0 = {
  139414. 2, 289,
  139415. _vq_lengthlist__44cn1_s_p5_0,
  139416. 1, -529530880, 1611661312, 5, 0,
  139417. _vq_quantlist__44cn1_s_p5_0,
  139418. NULL,
  139419. &_vq_auxt__44cn1_s_p5_0,
  139420. NULL,
  139421. 0
  139422. };
  139423. static long _vq_quantlist__44cn1_s_p6_0[] = {
  139424. 1,
  139425. 0,
  139426. 2,
  139427. };
  139428. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  139429. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  139430. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  139431. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  139432. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  139433. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  139434. 10,
  139435. };
  139436. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  139437. -5.5, 5.5,
  139438. };
  139439. static long _vq_quantmap__44cn1_s_p6_0[] = {
  139440. 1, 0, 2,
  139441. };
  139442. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  139443. _vq_quantthresh__44cn1_s_p6_0,
  139444. _vq_quantmap__44cn1_s_p6_0,
  139445. 3,
  139446. 3
  139447. };
  139448. static static_codebook _44cn1_s_p6_0 = {
  139449. 4, 81,
  139450. _vq_lengthlist__44cn1_s_p6_0,
  139451. 1, -529137664, 1618345984, 2, 0,
  139452. _vq_quantlist__44cn1_s_p6_0,
  139453. NULL,
  139454. &_vq_auxt__44cn1_s_p6_0,
  139455. NULL,
  139456. 0
  139457. };
  139458. static long _vq_quantlist__44cn1_s_p6_1[] = {
  139459. 5,
  139460. 4,
  139461. 6,
  139462. 3,
  139463. 7,
  139464. 2,
  139465. 8,
  139466. 1,
  139467. 9,
  139468. 0,
  139469. 10,
  139470. };
  139471. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  139472. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  139473. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  139474. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139475. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  139476. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  139477. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  139478. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  139479. 10,10,10, 9, 9, 9, 9, 9, 9,
  139480. };
  139481. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  139482. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139483. 3.5, 4.5,
  139484. };
  139485. static long _vq_quantmap__44cn1_s_p6_1[] = {
  139486. 9, 7, 5, 3, 1, 0, 2, 4,
  139487. 6, 8, 10,
  139488. };
  139489. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  139490. _vq_quantthresh__44cn1_s_p6_1,
  139491. _vq_quantmap__44cn1_s_p6_1,
  139492. 11,
  139493. 11
  139494. };
  139495. static static_codebook _44cn1_s_p6_1 = {
  139496. 2, 121,
  139497. _vq_lengthlist__44cn1_s_p6_1,
  139498. 1, -531365888, 1611661312, 4, 0,
  139499. _vq_quantlist__44cn1_s_p6_1,
  139500. NULL,
  139501. &_vq_auxt__44cn1_s_p6_1,
  139502. NULL,
  139503. 0
  139504. };
  139505. static long _vq_quantlist__44cn1_s_p7_0[] = {
  139506. 6,
  139507. 5,
  139508. 7,
  139509. 4,
  139510. 8,
  139511. 3,
  139512. 9,
  139513. 2,
  139514. 10,
  139515. 1,
  139516. 11,
  139517. 0,
  139518. 12,
  139519. };
  139520. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  139521. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  139522. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  139523. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139524. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139525. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  139526. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  139527. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  139528. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  139529. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  139530. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  139531. 0,13,13,12,12,13,13,13,14,
  139532. };
  139533. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  139534. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139535. 12.5, 17.5, 22.5, 27.5,
  139536. };
  139537. static long _vq_quantmap__44cn1_s_p7_0[] = {
  139538. 11, 9, 7, 5, 3, 1, 0, 2,
  139539. 4, 6, 8, 10, 12,
  139540. };
  139541. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  139542. _vq_quantthresh__44cn1_s_p7_0,
  139543. _vq_quantmap__44cn1_s_p7_0,
  139544. 13,
  139545. 13
  139546. };
  139547. static static_codebook _44cn1_s_p7_0 = {
  139548. 2, 169,
  139549. _vq_lengthlist__44cn1_s_p7_0,
  139550. 1, -526516224, 1616117760, 4, 0,
  139551. _vq_quantlist__44cn1_s_p7_0,
  139552. NULL,
  139553. &_vq_auxt__44cn1_s_p7_0,
  139554. NULL,
  139555. 0
  139556. };
  139557. static long _vq_quantlist__44cn1_s_p7_1[] = {
  139558. 2,
  139559. 1,
  139560. 3,
  139561. 0,
  139562. 4,
  139563. };
  139564. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  139565. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  139566. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  139567. };
  139568. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  139569. -1.5, -0.5, 0.5, 1.5,
  139570. };
  139571. static long _vq_quantmap__44cn1_s_p7_1[] = {
  139572. 3, 1, 0, 2, 4,
  139573. };
  139574. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  139575. _vq_quantthresh__44cn1_s_p7_1,
  139576. _vq_quantmap__44cn1_s_p7_1,
  139577. 5,
  139578. 5
  139579. };
  139580. static static_codebook _44cn1_s_p7_1 = {
  139581. 2, 25,
  139582. _vq_lengthlist__44cn1_s_p7_1,
  139583. 1, -533725184, 1611661312, 3, 0,
  139584. _vq_quantlist__44cn1_s_p7_1,
  139585. NULL,
  139586. &_vq_auxt__44cn1_s_p7_1,
  139587. NULL,
  139588. 0
  139589. };
  139590. static long _vq_quantlist__44cn1_s_p8_0[] = {
  139591. 2,
  139592. 1,
  139593. 3,
  139594. 0,
  139595. 4,
  139596. };
  139597. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  139598. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  139599. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  139600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139601. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  139602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139604. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139605. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  139606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139607. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  139608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  139609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139611. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139612. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139613. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  139614. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139615. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139616. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139617. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139618. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139620. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139621. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139622. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139624. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139625. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139626. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139627. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139628. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139631. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  139632. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139633. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139634. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139635. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139636. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139637. 12,
  139638. };
  139639. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  139640. -331.5, -110.5, 110.5, 331.5,
  139641. };
  139642. static long _vq_quantmap__44cn1_s_p8_0[] = {
  139643. 3, 1, 0, 2, 4,
  139644. };
  139645. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  139646. _vq_quantthresh__44cn1_s_p8_0,
  139647. _vq_quantmap__44cn1_s_p8_0,
  139648. 5,
  139649. 5
  139650. };
  139651. static static_codebook _44cn1_s_p8_0 = {
  139652. 4, 625,
  139653. _vq_lengthlist__44cn1_s_p8_0,
  139654. 1, -518283264, 1627103232, 3, 0,
  139655. _vq_quantlist__44cn1_s_p8_0,
  139656. NULL,
  139657. &_vq_auxt__44cn1_s_p8_0,
  139658. NULL,
  139659. 0
  139660. };
  139661. static long _vq_quantlist__44cn1_s_p8_1[] = {
  139662. 6,
  139663. 5,
  139664. 7,
  139665. 4,
  139666. 8,
  139667. 3,
  139668. 9,
  139669. 2,
  139670. 10,
  139671. 1,
  139672. 11,
  139673. 0,
  139674. 12,
  139675. };
  139676. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  139677. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  139678. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  139679. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  139680. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  139681. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  139682. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  139683. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  139684. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  139685. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  139686. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  139687. 15,12,12,11,11,14,12,13,14,
  139688. };
  139689. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  139690. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139691. 42.5, 59.5, 76.5, 93.5,
  139692. };
  139693. static long _vq_quantmap__44cn1_s_p8_1[] = {
  139694. 11, 9, 7, 5, 3, 1, 0, 2,
  139695. 4, 6, 8, 10, 12,
  139696. };
  139697. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  139698. _vq_quantthresh__44cn1_s_p8_1,
  139699. _vq_quantmap__44cn1_s_p8_1,
  139700. 13,
  139701. 13
  139702. };
  139703. static static_codebook _44cn1_s_p8_1 = {
  139704. 2, 169,
  139705. _vq_lengthlist__44cn1_s_p8_1,
  139706. 1, -522616832, 1620115456, 4, 0,
  139707. _vq_quantlist__44cn1_s_p8_1,
  139708. NULL,
  139709. &_vq_auxt__44cn1_s_p8_1,
  139710. NULL,
  139711. 0
  139712. };
  139713. static long _vq_quantlist__44cn1_s_p8_2[] = {
  139714. 8,
  139715. 7,
  139716. 9,
  139717. 6,
  139718. 10,
  139719. 5,
  139720. 11,
  139721. 4,
  139722. 12,
  139723. 3,
  139724. 13,
  139725. 2,
  139726. 14,
  139727. 1,
  139728. 15,
  139729. 0,
  139730. 16,
  139731. };
  139732. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  139733. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  139734. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139735. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139736. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  139737. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  139738. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  139739. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  139740. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  139741. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  139742. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  139743. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  139744. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139745. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  139746. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  139747. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  139748. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  139749. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  139750. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  139751. 9,
  139752. };
  139753. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  139754. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139755. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139756. };
  139757. static long _vq_quantmap__44cn1_s_p8_2[] = {
  139758. 15, 13, 11, 9, 7, 5, 3, 1,
  139759. 0, 2, 4, 6, 8, 10, 12, 14,
  139760. 16,
  139761. };
  139762. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  139763. _vq_quantthresh__44cn1_s_p8_2,
  139764. _vq_quantmap__44cn1_s_p8_2,
  139765. 17,
  139766. 17
  139767. };
  139768. static static_codebook _44cn1_s_p8_2 = {
  139769. 2, 289,
  139770. _vq_lengthlist__44cn1_s_p8_2,
  139771. 1, -529530880, 1611661312, 5, 0,
  139772. _vq_quantlist__44cn1_s_p8_2,
  139773. NULL,
  139774. &_vq_auxt__44cn1_s_p8_2,
  139775. NULL,
  139776. 0
  139777. };
  139778. static long _huff_lengthlist__44cn1_s_short[] = {
  139779. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  139780. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  139781. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  139782. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  139783. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  139784. 10,
  139785. };
  139786. static static_codebook _huff_book__44cn1_s_short = {
  139787. 2, 81,
  139788. _huff_lengthlist__44cn1_s_short,
  139789. 0, 0, 0, 0, 0,
  139790. NULL,
  139791. NULL,
  139792. NULL,
  139793. NULL,
  139794. 0
  139795. };
  139796. static long _huff_lengthlist__44cn1_sm_long[] = {
  139797. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  139798. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  139799. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  139800. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  139801. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  139802. 17,
  139803. };
  139804. static static_codebook _huff_book__44cn1_sm_long = {
  139805. 2, 81,
  139806. _huff_lengthlist__44cn1_sm_long,
  139807. 0, 0, 0, 0, 0,
  139808. NULL,
  139809. NULL,
  139810. NULL,
  139811. NULL,
  139812. 0
  139813. };
  139814. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  139815. 1,
  139816. 0,
  139817. 2,
  139818. };
  139819. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  139820. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139821. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139825. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139826. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139830. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139831. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139866. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  139871. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  139876. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139911. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139912. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139916. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139917. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  139918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139921. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  139922. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0,
  140231. };
  140232. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  140233. -0.5, 0.5,
  140234. };
  140235. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  140236. 1, 0, 2,
  140237. };
  140238. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  140239. _vq_quantthresh__44cn1_sm_p1_0,
  140240. _vq_quantmap__44cn1_sm_p1_0,
  140241. 3,
  140242. 3
  140243. };
  140244. static static_codebook _44cn1_sm_p1_0 = {
  140245. 8, 6561,
  140246. _vq_lengthlist__44cn1_sm_p1_0,
  140247. 1, -535822336, 1611661312, 2, 0,
  140248. _vq_quantlist__44cn1_sm_p1_0,
  140249. NULL,
  140250. &_vq_auxt__44cn1_sm_p1_0,
  140251. NULL,
  140252. 0
  140253. };
  140254. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  140255. 2,
  140256. 1,
  140257. 3,
  140258. 0,
  140259. 4,
  140260. };
  140261. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  140262. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0,
  140302. };
  140303. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  140304. -1.5, -0.5, 0.5, 1.5,
  140305. };
  140306. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  140307. 3, 1, 0, 2, 4,
  140308. };
  140309. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  140310. _vq_quantthresh__44cn1_sm_p2_0,
  140311. _vq_quantmap__44cn1_sm_p2_0,
  140312. 5,
  140313. 5
  140314. };
  140315. static static_codebook _44cn1_sm_p2_0 = {
  140316. 4, 625,
  140317. _vq_lengthlist__44cn1_sm_p2_0,
  140318. 1, -533725184, 1611661312, 3, 0,
  140319. _vq_quantlist__44cn1_sm_p2_0,
  140320. NULL,
  140321. &_vq_auxt__44cn1_sm_p2_0,
  140322. NULL,
  140323. 0
  140324. };
  140325. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  140326. 4,
  140327. 3,
  140328. 5,
  140329. 2,
  140330. 6,
  140331. 1,
  140332. 7,
  140333. 0,
  140334. 8,
  140335. };
  140336. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  140337. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  140338. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  140339. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  140340. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  140341. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0,
  140343. };
  140344. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  140345. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140346. };
  140347. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  140348. 7, 5, 3, 1, 0, 2, 4, 6,
  140349. 8,
  140350. };
  140351. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  140352. _vq_quantthresh__44cn1_sm_p3_0,
  140353. _vq_quantmap__44cn1_sm_p3_0,
  140354. 9,
  140355. 9
  140356. };
  140357. static static_codebook _44cn1_sm_p3_0 = {
  140358. 2, 81,
  140359. _vq_lengthlist__44cn1_sm_p3_0,
  140360. 1, -531628032, 1611661312, 4, 0,
  140361. _vq_quantlist__44cn1_sm_p3_0,
  140362. NULL,
  140363. &_vq_auxt__44cn1_sm_p3_0,
  140364. NULL,
  140365. 0
  140366. };
  140367. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  140368. 4,
  140369. 3,
  140370. 5,
  140371. 2,
  140372. 6,
  140373. 1,
  140374. 7,
  140375. 0,
  140376. 8,
  140377. };
  140378. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  140379. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  140380. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  140381. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  140382. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140383. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140384. 11,
  140385. };
  140386. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  140387. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140388. };
  140389. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  140390. 7, 5, 3, 1, 0, 2, 4, 6,
  140391. 8,
  140392. };
  140393. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  140394. _vq_quantthresh__44cn1_sm_p4_0,
  140395. _vq_quantmap__44cn1_sm_p4_0,
  140396. 9,
  140397. 9
  140398. };
  140399. static static_codebook _44cn1_sm_p4_0 = {
  140400. 2, 81,
  140401. _vq_lengthlist__44cn1_sm_p4_0,
  140402. 1, -531628032, 1611661312, 4, 0,
  140403. _vq_quantlist__44cn1_sm_p4_0,
  140404. NULL,
  140405. &_vq_auxt__44cn1_sm_p4_0,
  140406. NULL,
  140407. 0
  140408. };
  140409. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  140410. 8,
  140411. 7,
  140412. 9,
  140413. 6,
  140414. 10,
  140415. 5,
  140416. 11,
  140417. 4,
  140418. 12,
  140419. 3,
  140420. 13,
  140421. 2,
  140422. 14,
  140423. 1,
  140424. 15,
  140425. 0,
  140426. 16,
  140427. };
  140428. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  140429. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  140430. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  140431. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  140432. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140433. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  140434. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  140435. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  140436. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  140437. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  140438. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  140439. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  140440. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  140441. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  140442. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  140443. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  140444. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  140445. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  140447. 14,
  140448. };
  140449. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  140450. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140451. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140452. };
  140453. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  140454. 15, 13, 11, 9, 7, 5, 3, 1,
  140455. 0, 2, 4, 6, 8, 10, 12, 14,
  140456. 16,
  140457. };
  140458. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  140459. _vq_quantthresh__44cn1_sm_p5_0,
  140460. _vq_quantmap__44cn1_sm_p5_0,
  140461. 17,
  140462. 17
  140463. };
  140464. static static_codebook _44cn1_sm_p5_0 = {
  140465. 2, 289,
  140466. _vq_lengthlist__44cn1_sm_p5_0,
  140467. 1, -529530880, 1611661312, 5, 0,
  140468. _vq_quantlist__44cn1_sm_p5_0,
  140469. NULL,
  140470. &_vq_auxt__44cn1_sm_p5_0,
  140471. NULL,
  140472. 0
  140473. };
  140474. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  140475. 1,
  140476. 0,
  140477. 2,
  140478. };
  140479. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  140480. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  140481. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  140482. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  140483. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  140484. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  140485. 10,
  140486. };
  140487. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  140488. -5.5, 5.5,
  140489. };
  140490. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  140491. 1, 0, 2,
  140492. };
  140493. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  140494. _vq_quantthresh__44cn1_sm_p6_0,
  140495. _vq_quantmap__44cn1_sm_p6_0,
  140496. 3,
  140497. 3
  140498. };
  140499. static static_codebook _44cn1_sm_p6_0 = {
  140500. 4, 81,
  140501. _vq_lengthlist__44cn1_sm_p6_0,
  140502. 1, -529137664, 1618345984, 2, 0,
  140503. _vq_quantlist__44cn1_sm_p6_0,
  140504. NULL,
  140505. &_vq_auxt__44cn1_sm_p6_0,
  140506. NULL,
  140507. 0
  140508. };
  140509. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  140510. 5,
  140511. 4,
  140512. 6,
  140513. 3,
  140514. 7,
  140515. 2,
  140516. 8,
  140517. 1,
  140518. 9,
  140519. 0,
  140520. 10,
  140521. };
  140522. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  140523. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  140524. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  140525. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140526. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  140527. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  140528. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  140529. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  140530. 10,10,10, 8, 9, 8, 8, 9, 8,
  140531. };
  140532. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  140533. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140534. 3.5, 4.5,
  140535. };
  140536. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  140537. 9, 7, 5, 3, 1, 0, 2, 4,
  140538. 6, 8, 10,
  140539. };
  140540. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  140541. _vq_quantthresh__44cn1_sm_p6_1,
  140542. _vq_quantmap__44cn1_sm_p6_1,
  140543. 11,
  140544. 11
  140545. };
  140546. static static_codebook _44cn1_sm_p6_1 = {
  140547. 2, 121,
  140548. _vq_lengthlist__44cn1_sm_p6_1,
  140549. 1, -531365888, 1611661312, 4, 0,
  140550. _vq_quantlist__44cn1_sm_p6_1,
  140551. NULL,
  140552. &_vq_auxt__44cn1_sm_p6_1,
  140553. NULL,
  140554. 0
  140555. };
  140556. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  140557. 6,
  140558. 5,
  140559. 7,
  140560. 4,
  140561. 8,
  140562. 3,
  140563. 9,
  140564. 2,
  140565. 10,
  140566. 1,
  140567. 11,
  140568. 0,
  140569. 12,
  140570. };
  140571. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  140572. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  140573. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  140574. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140575. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140576. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  140577. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  140578. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140579. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  140580. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  140581. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  140582. 0,13,12,12,12,13,13,13,14,
  140583. };
  140584. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  140585. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140586. 12.5, 17.5, 22.5, 27.5,
  140587. };
  140588. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  140589. 11, 9, 7, 5, 3, 1, 0, 2,
  140590. 4, 6, 8, 10, 12,
  140591. };
  140592. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  140593. _vq_quantthresh__44cn1_sm_p7_0,
  140594. _vq_quantmap__44cn1_sm_p7_0,
  140595. 13,
  140596. 13
  140597. };
  140598. static static_codebook _44cn1_sm_p7_0 = {
  140599. 2, 169,
  140600. _vq_lengthlist__44cn1_sm_p7_0,
  140601. 1, -526516224, 1616117760, 4, 0,
  140602. _vq_quantlist__44cn1_sm_p7_0,
  140603. NULL,
  140604. &_vq_auxt__44cn1_sm_p7_0,
  140605. NULL,
  140606. 0
  140607. };
  140608. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  140609. 2,
  140610. 1,
  140611. 3,
  140612. 0,
  140613. 4,
  140614. };
  140615. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  140616. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  140617. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  140618. };
  140619. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  140620. -1.5, -0.5, 0.5, 1.5,
  140621. };
  140622. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  140623. 3, 1, 0, 2, 4,
  140624. };
  140625. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  140626. _vq_quantthresh__44cn1_sm_p7_1,
  140627. _vq_quantmap__44cn1_sm_p7_1,
  140628. 5,
  140629. 5
  140630. };
  140631. static static_codebook _44cn1_sm_p7_1 = {
  140632. 2, 25,
  140633. _vq_lengthlist__44cn1_sm_p7_1,
  140634. 1, -533725184, 1611661312, 3, 0,
  140635. _vq_quantlist__44cn1_sm_p7_1,
  140636. NULL,
  140637. &_vq_auxt__44cn1_sm_p7_1,
  140638. NULL,
  140639. 0
  140640. };
  140641. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  140642. 4,
  140643. 3,
  140644. 5,
  140645. 2,
  140646. 6,
  140647. 1,
  140648. 7,
  140649. 0,
  140650. 8,
  140651. };
  140652. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  140653. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  140654. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  140655. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  140656. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  140657. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  140658. 14,
  140659. };
  140660. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  140661. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  140662. };
  140663. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  140664. 7, 5, 3, 1, 0, 2, 4, 6,
  140665. 8,
  140666. };
  140667. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  140668. _vq_quantthresh__44cn1_sm_p8_0,
  140669. _vq_quantmap__44cn1_sm_p8_0,
  140670. 9,
  140671. 9
  140672. };
  140673. static static_codebook _44cn1_sm_p8_0 = {
  140674. 2, 81,
  140675. _vq_lengthlist__44cn1_sm_p8_0,
  140676. 1, -516186112, 1627103232, 4, 0,
  140677. _vq_quantlist__44cn1_sm_p8_0,
  140678. NULL,
  140679. &_vq_auxt__44cn1_sm_p8_0,
  140680. NULL,
  140681. 0
  140682. };
  140683. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  140684. 6,
  140685. 5,
  140686. 7,
  140687. 4,
  140688. 8,
  140689. 3,
  140690. 9,
  140691. 2,
  140692. 10,
  140693. 1,
  140694. 11,
  140695. 0,
  140696. 12,
  140697. };
  140698. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  140699. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  140700. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  140701. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  140702. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  140703. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  140704. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  140705. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  140706. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  140707. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  140708. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  140709. 17,12,12,11,10,13,11,13,13,
  140710. };
  140711. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  140712. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140713. 42.5, 59.5, 76.5, 93.5,
  140714. };
  140715. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  140716. 11, 9, 7, 5, 3, 1, 0, 2,
  140717. 4, 6, 8, 10, 12,
  140718. };
  140719. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  140720. _vq_quantthresh__44cn1_sm_p8_1,
  140721. _vq_quantmap__44cn1_sm_p8_1,
  140722. 13,
  140723. 13
  140724. };
  140725. static static_codebook _44cn1_sm_p8_1 = {
  140726. 2, 169,
  140727. _vq_lengthlist__44cn1_sm_p8_1,
  140728. 1, -522616832, 1620115456, 4, 0,
  140729. _vq_quantlist__44cn1_sm_p8_1,
  140730. NULL,
  140731. &_vq_auxt__44cn1_sm_p8_1,
  140732. NULL,
  140733. 0
  140734. };
  140735. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  140736. 8,
  140737. 7,
  140738. 9,
  140739. 6,
  140740. 10,
  140741. 5,
  140742. 11,
  140743. 4,
  140744. 12,
  140745. 3,
  140746. 13,
  140747. 2,
  140748. 14,
  140749. 1,
  140750. 15,
  140751. 0,
  140752. 16,
  140753. };
  140754. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  140755. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140756. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140757. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  140758. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  140759. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  140760. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  140761. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  140762. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  140763. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  140764. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  140765. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  140766. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  140767. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  140768. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  140769. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  140770. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140771. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140772. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  140773. 9,
  140774. };
  140775. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  140776. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140777. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140778. };
  140779. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  140780. 15, 13, 11, 9, 7, 5, 3, 1,
  140781. 0, 2, 4, 6, 8, 10, 12, 14,
  140782. 16,
  140783. };
  140784. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  140785. _vq_quantthresh__44cn1_sm_p8_2,
  140786. _vq_quantmap__44cn1_sm_p8_2,
  140787. 17,
  140788. 17
  140789. };
  140790. static static_codebook _44cn1_sm_p8_2 = {
  140791. 2, 289,
  140792. _vq_lengthlist__44cn1_sm_p8_2,
  140793. 1, -529530880, 1611661312, 5, 0,
  140794. _vq_quantlist__44cn1_sm_p8_2,
  140795. NULL,
  140796. &_vq_auxt__44cn1_sm_p8_2,
  140797. NULL,
  140798. 0
  140799. };
  140800. static long _huff_lengthlist__44cn1_sm_short[] = {
  140801. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  140802. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  140803. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  140804. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  140805. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  140806. 9,
  140807. };
  140808. static static_codebook _huff_book__44cn1_sm_short = {
  140809. 2, 81,
  140810. _huff_lengthlist__44cn1_sm_short,
  140811. 0, 0, 0, 0, 0,
  140812. NULL,
  140813. NULL,
  140814. NULL,
  140815. NULL,
  140816. 0
  140817. };
  140818. /*** End of inlined file: res_books_stereo.h ***/
  140819. /***** residue backends *********************************************/
  140820. static vorbis_info_residue0 _residue_44_low={
  140821. 0,-1, -1, 9,-1,
  140822. /* 0 1 2 3 4 5 6 7 */
  140823. {0},
  140824. {-1},
  140825. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  140826. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  140827. };
  140828. static vorbis_info_residue0 _residue_44_mid={
  140829. 0,-1, -1, 10,-1,
  140830. /* 0 1 2 3 4 5 6 7 8 */
  140831. {0},
  140832. {-1},
  140833. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  140834. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  140835. };
  140836. static vorbis_info_residue0 _residue_44_high={
  140837. 0,-1, -1, 10,-1,
  140838. /* 0 1 2 3 4 5 6 7 8 */
  140839. {0},
  140840. {-1},
  140841. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  140842. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  140843. };
  140844. static static_bookblock _resbook_44s_n1={
  140845. {
  140846. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  140847. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  140848. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  140849. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  140850. }
  140851. };
  140852. static static_bookblock _resbook_44sm_n1={
  140853. {
  140854. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  140855. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  140856. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  140857. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  140858. }
  140859. };
  140860. static static_bookblock _resbook_44s_0={
  140861. {
  140862. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  140863. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  140864. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  140865. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  140866. }
  140867. };
  140868. static static_bookblock _resbook_44sm_0={
  140869. {
  140870. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  140871. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  140872. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  140873. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  140874. }
  140875. };
  140876. static static_bookblock _resbook_44s_1={
  140877. {
  140878. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  140879. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  140880. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  140881. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  140882. }
  140883. };
  140884. static static_bookblock _resbook_44sm_1={
  140885. {
  140886. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  140887. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  140888. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  140889. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  140890. }
  140891. };
  140892. static static_bookblock _resbook_44s_2={
  140893. {
  140894. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  140895. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  140896. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  140897. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  140898. }
  140899. };
  140900. static static_bookblock _resbook_44s_3={
  140901. {
  140902. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  140903. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  140904. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  140905. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  140906. }
  140907. };
  140908. static static_bookblock _resbook_44s_4={
  140909. {
  140910. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  140911. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  140912. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  140913. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  140914. }
  140915. };
  140916. static static_bookblock _resbook_44s_5={
  140917. {
  140918. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  140919. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  140920. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  140921. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  140922. }
  140923. };
  140924. static static_bookblock _resbook_44s_6={
  140925. {
  140926. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  140927. {0,0,&_44c6_s_p4_0},
  140928. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  140929. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  140930. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  140931. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  140932. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  140933. }
  140934. };
  140935. static static_bookblock _resbook_44s_7={
  140936. {
  140937. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  140938. {0,0,&_44c7_s_p4_0},
  140939. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  140940. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  140941. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  140942. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  140943. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  140944. }
  140945. };
  140946. static static_bookblock _resbook_44s_8={
  140947. {
  140948. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  140949. {0,0,&_44c8_s_p4_0},
  140950. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  140951. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  140952. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  140953. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  140954. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  140955. }
  140956. };
  140957. static static_bookblock _resbook_44s_9={
  140958. {
  140959. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  140960. {0,0,&_44c9_s_p4_0},
  140961. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  140962. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  140963. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  140964. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  140965. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  140966. }
  140967. };
  140968. static vorbis_residue_template _res_44s_n1[]={
  140969. {2,0, &_residue_44_low,
  140970. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  140971. &_resbook_44s_n1,&_resbook_44sm_n1},
  140972. {2,0, &_residue_44_low,
  140973. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  140974. &_resbook_44s_n1,&_resbook_44sm_n1}
  140975. };
  140976. static vorbis_residue_template _res_44s_0[]={
  140977. {2,0, &_residue_44_low,
  140978. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  140979. &_resbook_44s_0,&_resbook_44sm_0},
  140980. {2,0, &_residue_44_low,
  140981. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  140982. &_resbook_44s_0,&_resbook_44sm_0}
  140983. };
  140984. static vorbis_residue_template _res_44s_1[]={
  140985. {2,0, &_residue_44_low,
  140986. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  140987. &_resbook_44s_1,&_resbook_44sm_1},
  140988. {2,0, &_residue_44_low,
  140989. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  140990. &_resbook_44s_1,&_resbook_44sm_1}
  140991. };
  140992. static vorbis_residue_template _res_44s_2[]={
  140993. {2,0, &_residue_44_mid,
  140994. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  140995. &_resbook_44s_2,&_resbook_44s_2},
  140996. {2,0, &_residue_44_mid,
  140997. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  140998. &_resbook_44s_2,&_resbook_44s_2}
  140999. };
  141000. static vorbis_residue_template _res_44s_3[]={
  141001. {2,0, &_residue_44_mid,
  141002. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141003. &_resbook_44s_3,&_resbook_44s_3},
  141004. {2,0, &_residue_44_mid,
  141005. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141006. &_resbook_44s_3,&_resbook_44s_3}
  141007. };
  141008. static vorbis_residue_template _res_44s_4[]={
  141009. {2,0, &_residue_44_mid,
  141010. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141011. &_resbook_44s_4,&_resbook_44s_4},
  141012. {2,0, &_residue_44_mid,
  141013. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141014. &_resbook_44s_4,&_resbook_44s_4}
  141015. };
  141016. static vorbis_residue_template _res_44s_5[]={
  141017. {2,0, &_residue_44_mid,
  141018. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141019. &_resbook_44s_5,&_resbook_44s_5},
  141020. {2,0, &_residue_44_mid,
  141021. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141022. &_resbook_44s_5,&_resbook_44s_5}
  141023. };
  141024. static vorbis_residue_template _res_44s_6[]={
  141025. {2,0, &_residue_44_high,
  141026. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141027. &_resbook_44s_6,&_resbook_44s_6},
  141028. {2,0, &_residue_44_high,
  141029. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141030. &_resbook_44s_6,&_resbook_44s_6}
  141031. };
  141032. static vorbis_residue_template _res_44s_7[]={
  141033. {2,0, &_residue_44_high,
  141034. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141035. &_resbook_44s_7,&_resbook_44s_7},
  141036. {2,0, &_residue_44_high,
  141037. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141038. &_resbook_44s_7,&_resbook_44s_7}
  141039. };
  141040. static vorbis_residue_template _res_44s_8[]={
  141041. {2,0, &_residue_44_high,
  141042. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141043. &_resbook_44s_8,&_resbook_44s_8},
  141044. {2,0, &_residue_44_high,
  141045. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141046. &_resbook_44s_8,&_resbook_44s_8}
  141047. };
  141048. static vorbis_residue_template _res_44s_9[]={
  141049. {2,0, &_residue_44_high,
  141050. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141051. &_resbook_44s_9,&_resbook_44s_9},
  141052. {2,0, &_residue_44_high,
  141053. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141054. &_resbook_44s_9,&_resbook_44s_9}
  141055. };
  141056. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141057. { _map_nominal, _res_44s_n1 }, /* -1 */
  141058. { _map_nominal, _res_44s_0 }, /* 0 */
  141059. { _map_nominal, _res_44s_1 }, /* 1 */
  141060. { _map_nominal, _res_44s_2 }, /* 2 */
  141061. { _map_nominal, _res_44s_3 }, /* 3 */
  141062. { _map_nominal, _res_44s_4 }, /* 4 */
  141063. { _map_nominal, _res_44s_5 }, /* 5 */
  141064. { _map_nominal, _res_44s_6 }, /* 6 */
  141065. { _map_nominal, _res_44s_7 }, /* 7 */
  141066. { _map_nominal, _res_44s_8 }, /* 8 */
  141067. { _map_nominal, _res_44s_9 }, /* 9 */
  141068. };
  141069. /*** End of inlined file: residue_44.h ***/
  141070. /*** Start of inlined file: psych_44.h ***/
  141071. /* preecho trigger settings *****************************************/
  141072. static vorbis_info_psy_global _psy_global_44[5]={
  141073. {8, /* lines per eighth octave */
  141074. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141075. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141076. -6.f,
  141077. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141078. },
  141079. {8, /* lines per eighth octave */
  141080. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141081. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141082. -6.f,
  141083. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141084. },
  141085. {8, /* lines per eighth octave */
  141086. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141087. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141088. -6.f,
  141089. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141090. },
  141091. {8, /* lines per eighth octave */
  141092. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141093. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141094. -6.f,
  141095. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141096. },
  141097. {8, /* lines per eighth octave */
  141098. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141099. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141100. -6.f,
  141101. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141102. },
  141103. };
  141104. /* noise compander lookups * low, mid, high quality ****************/
  141105. static compandblock _psy_compand_44[6]={
  141106. /* sub-mode Z short */
  141107. {{
  141108. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141109. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141110. 16,17,18,19,20,21,22, 23, /* 23dB */
  141111. 24,25,26,27,28,29,30, 31, /* 31dB */
  141112. 32,33,34,35,36,37,38, 39, /* 39dB */
  141113. }},
  141114. /* mode_Z nominal short */
  141115. {{
  141116. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141117. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141118. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141119. 15,16,17,17,17,18,18, 19, /* 31dB */
  141120. 19,19,20,21,22,23,24, 25, /* 39dB */
  141121. }},
  141122. /* mode A short */
  141123. {{
  141124. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  141125. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  141126. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141127. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141128. 11,12,13,14,15,16,17, 18, /* 39dB */
  141129. }},
  141130. /* sub-mode Z long */
  141131. {{
  141132. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141133. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141134. 16,17,18,19,20,21,22, 23, /* 23dB */
  141135. 24,25,26,27,28,29,30, 31, /* 31dB */
  141136. 32,33,34,35,36,37,38, 39, /* 39dB */
  141137. }},
  141138. /* mode_Z nominal long */
  141139. {{
  141140. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141141. 8, 9,10,11,12,12,13, 13, /* 15dB */
  141142. 13,14,14,14,15,15,15, 15, /* 23dB */
  141143. 16,16,17,17,17,18,18, 19, /* 31dB */
  141144. 19,19,20,21,22,23,24, 25, /* 39dB */
  141145. }},
  141146. /* mode A long */
  141147. {{
  141148. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141149. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  141150. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141151. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141152. 11,12,13,14,15,16,17, 18, /* 39dB */
  141153. }}
  141154. };
  141155. /* tonal masking curve level adjustments *************************/
  141156. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  141157. /* 63 125 250 500 1 2 4 8 16 */
  141158. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  141159. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141160. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  141161. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141162. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  141163. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141164. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  141165. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141166. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  141167. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  141168. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141169. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141170. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141171. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141172. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141173. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141174. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141175. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141176. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141177. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141178. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141179. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141180. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141181. };
  141182. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  141183. /* 63 125 250 500 1 2 4 8 16 */
  141184. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  141185. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141186. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  141187. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141188. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  141189. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141190. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  141191. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141192. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  141193. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  141194. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141195. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141196. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141197. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141198. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141199. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141200. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141201. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141202. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141203. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141204. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141205. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141206. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141207. };
  141208. /* noise bias (transition block) */
  141209. static noise3 _psy_noisebias_trans[12]={
  141210. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141211. /* -1 */
  141212. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141213. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141214. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141215. /* 0
  141216. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141217. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  141218. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141219. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141220. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  141221. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141222. /* 1
  141223. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141224. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141225. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141226. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141227. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141228. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141229. /* 2
  141230. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141231. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141232. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  141233. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141234. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141235. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  141236. /* 3
  141237. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141238. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141239. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141240. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141241. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141242. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141243. /* 4
  141244. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141245. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141246. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141247. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141248. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141249. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141250. /* 5
  141251. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141252. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141253. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  141254. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141255. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141256. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  141257. /* 6
  141258. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141259. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141260. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141261. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141262. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141263. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141264. /* 7
  141265. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141266. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  141267. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  141268. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141269. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141270. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141271. /* 8
  141272. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141273. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141274. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141275. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141276. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141277. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141278. /* 9
  141279. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141280. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141281. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141282. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141283. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  141284. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  141285. /* 10 */
  141286. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  141287. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  141288. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141289. };
  141290. /* noise bias (long block) */
  141291. static noise3 _psy_noisebias_long[12]={
  141292. /*63 125 250 500 1k 2k 4k 8k 16k*/
  141293. /* -1 */
  141294. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  141295. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  141296. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141297. /* 0 */
  141298. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141299. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  141300. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141301. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141302. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  141303. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141304. /* 1 */
  141305. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141306. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141307. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141308. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141309. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141310. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141311. /* 2 */
  141312. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141313. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141314. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141315. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141316. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141317. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141318. /* 3 */
  141319. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141320. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141321. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141322. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141323. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141324. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  141325. /* 4 */
  141326. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141327. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141328. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141329. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141330. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141331. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  141332. /* 5 */
  141333. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141334. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141335. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  141336. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141337. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141338. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  141339. /* 6 */
  141340. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141341. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141342. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141343. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141344. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141345. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  141346. /* 7 */
  141347. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141348. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  141349. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141350. /* 8 */
  141351. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  141352. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  141353. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141354. /* 9 */
  141355. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141356. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  141357. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141358. /* 10 */
  141359. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  141360. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  141361. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141362. };
  141363. /* noise bias (impulse block) */
  141364. static noise3 _psy_noisebias_impulse[12]={
  141365. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141366. /* -1 */
  141367. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141368. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141369. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141370. /* 0 */
  141371. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141372. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  141373. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  141374. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141375. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  141376. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141377. /* 1 */
  141378. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141379. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  141380. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  141381. /* 2 */
  141382. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141383. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141384. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141385. /* 3 */
  141386. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  141387. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141388. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141389. /* 4 */
  141390. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  141391. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141392. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141393. /* 5 */
  141394. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141395. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  141396. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  141397. /* 6
  141398. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141399. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  141400. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  141401. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141402. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  141403. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  141404. /* 7 */
  141405. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  141406. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  141407. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  141408. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  141409. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  141410. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  141411. /* 8 */
  141412. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  141413. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  141414. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141415. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  141416. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  141417. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  141418. /* 9 */
  141419. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141420. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  141421. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141422. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141423. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  141424. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141425. /* 10 */
  141426. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  141427. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  141428. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141429. };
  141430. /* noise bias (padding block) */
  141431. static noise3 _psy_noisebias_padding[12]={
  141432. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141433. /* -1 */
  141434. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141435. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141436. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141437. /* 0 */
  141438. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141439. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  141440. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  141441. /* 1 */
  141442. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141443. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  141444. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  141445. /* 2 */
  141446. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141447. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  141448. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  141449. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141450. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  141451. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141452. /* 3 */
  141453. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  141454. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  141455. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141456. /* 4 */
  141457. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  141458. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  141459. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141460. /* 5 */
  141461. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141462. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  141463. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  141464. /* 6 */
  141465. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141466. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  141467. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  141468. /* 7 */
  141469. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141470. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  141471. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  141472. /* 8 */
  141473. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  141474. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  141475. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  141476. /* 9 */
  141477. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  141478. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  141479. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  141480. /* 10 */
  141481. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  141482. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  141483. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141484. };
  141485. static noiseguard _psy_noiseguards_44[4]={
  141486. {3,3,15},
  141487. {3,3,15},
  141488. {10,10,100},
  141489. {10,10,100},
  141490. };
  141491. static int _psy_tone_suppress[12]={
  141492. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  141493. };
  141494. static int _psy_tone_0dB[12]={
  141495. 90,90,95,95,95,95,105,105,105,105,105,105,
  141496. };
  141497. static int _psy_noise_suppress[12]={
  141498. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  141499. };
  141500. static vorbis_info_psy _psy_info_template={
  141501. /* blockflag */
  141502. -1,
  141503. /* ath_adjatt, ath_maxatt */
  141504. -140.,-140.,
  141505. /* tonemask att boost/decay,suppr,curves */
  141506. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  141507. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  141508. 1, -0.f, .5f, .5f, 0,0,0,
  141509. /* noiseoffset*3, noisecompand, max_curve_dB */
  141510. {{-1},{-1},{-1}},{-1},105.f,
  141511. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  141512. 0,0,-1,-1,0.,
  141513. };
  141514. /* ath ****************/
  141515. static int _psy_ath_floater[12]={
  141516. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  141517. };
  141518. static int _psy_ath_abs[12]={
  141519. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  141520. };
  141521. /* stereo setup. These don't map directly to quality level, there's
  141522. an additional indirection as several of the below may be used in a
  141523. single bitmanaged stream
  141524. ****************/
  141525. /* various stereo possibilities */
  141526. /* stereo mode by base quality level */
  141527. static adj_stereo _psy_stereo_modes_44[12]={
  141528. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  141529. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  141530. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  141531. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  141532. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  141533. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  141534. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  141535. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  141536. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  141537. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141538. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  141539. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  141540. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141541. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  141542. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  141543. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  141544. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  141545. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141546. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141547. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  141548. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  141549. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  141550. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141551. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  141552. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  141553. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  141554. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141555. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141556. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  141557. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  141558. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  141559. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  141560. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141561. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  141562. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141563. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  141564. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  141565. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141566. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  141567. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141568. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  141569. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141570. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141571. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141572. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  141573. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  141574. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141575. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  141576. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141577. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141578. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141579. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  141580. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141581. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141582. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141583. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141584. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  141585. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141586. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141587. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141588. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141589. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141590. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141591. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141592. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141593. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  141594. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141595. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141596. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141597. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141598. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141599. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141600. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141601. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141602. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  141603. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141604. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141605. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  141606. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141607. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  141608. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141609. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141610. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  141611. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141612. };
  141613. /* tone master attenuation by base quality mode and bitrate tweak */
  141614. static att3 _psy_tone_masteratt_44[12]={
  141615. {{ 35, 21, 9}, 0, 0}, /* -1 */
  141616. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  141617. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  141618. {{ 25, 12, 2}, 0, 0}, /* 1 */
  141619. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  141620. {{ 20, 9, -3}, 0, 0}, /* 2 */
  141621. {{ 20, 9, -4}, 0, 0}, /* 3 */
  141622. {{ 20, 9, -4}, 0, 0}, /* 4 */
  141623. {{ 20, 6, -6}, 0, 0}, /* 5 */
  141624. {{ 20, 3, -10}, 0, 0}, /* 6 */
  141625. {{ 18, 1, -14}, 0, 0}, /* 7 */
  141626. {{ 18, 0, -16}, 0, 0}, /* 8 */
  141627. {{ 18, -2, -16}, 0, 0}, /* 9 */
  141628. {{ 12, -2, -20}, 0, 0}, /* 10 */
  141629. };
  141630. /* lowpass by mode **************/
  141631. static double _psy_lowpass_44[12]={
  141632. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  141633. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  141634. };
  141635. /* noise normalization **********/
  141636. static int _noise_start_short_44[11]={
  141637. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  141638. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  141639. };
  141640. static int _noise_start_long_44[11]={
  141641. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  141642. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  141643. };
  141644. static int _noise_part_short_44[11]={
  141645. 8,8,8,8,8,8,8,8,8,8,8
  141646. };
  141647. static int _noise_part_long_44[11]={
  141648. 32,32,32,32,32,32,32,32,32,32,32
  141649. };
  141650. static double _noise_thresh_44[11]={
  141651. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  141652. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  141653. };
  141654. static double _noise_thresh_5only[2]={
  141655. .5,.5,
  141656. };
  141657. /*** End of inlined file: psych_44.h ***/
  141658. static double rate_mapping_44_stereo[12]={
  141659. 22500.,32000.,40000.,48000.,56000.,64000.,
  141660. 80000.,96000.,112000.,128000.,160000.,250001.
  141661. };
  141662. static double quality_mapping_44[12]={
  141663. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  141664. };
  141665. static int blocksize_short_44[11]={
  141666. 512,256,256,256,256,256,256,256,256,256,256
  141667. };
  141668. static int blocksize_long_44[11]={
  141669. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  141670. };
  141671. static double _psy_compand_short_mapping[12]={
  141672. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  141673. };
  141674. static double _psy_compand_long_mapping[12]={
  141675. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  141676. };
  141677. static double _global_mapping_44[12]={
  141678. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  141679. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  141680. };
  141681. static int _floor_short_mapping_44[11]={
  141682. 1,0,0,2,2,4,5,5,5,5,5
  141683. };
  141684. static int _floor_long_mapping_44[11]={
  141685. 8,7,7,7,7,7,7,7,7,7,7
  141686. };
  141687. ve_setup_data_template ve_setup_44_stereo={
  141688. 11,
  141689. rate_mapping_44_stereo,
  141690. quality_mapping_44,
  141691. 2,
  141692. 40000,
  141693. 50000,
  141694. blocksize_short_44,
  141695. blocksize_long_44,
  141696. _psy_tone_masteratt_44,
  141697. _psy_tone_0dB,
  141698. _psy_tone_suppress,
  141699. _vp_tonemask_adj_otherblock,
  141700. _vp_tonemask_adj_longblock,
  141701. _vp_tonemask_adj_otherblock,
  141702. _psy_noiseguards_44,
  141703. _psy_noisebias_impulse,
  141704. _psy_noisebias_padding,
  141705. _psy_noisebias_trans,
  141706. _psy_noisebias_long,
  141707. _psy_noise_suppress,
  141708. _psy_compand_44,
  141709. _psy_compand_short_mapping,
  141710. _psy_compand_long_mapping,
  141711. {_noise_start_short_44,_noise_start_long_44},
  141712. {_noise_part_short_44,_noise_part_long_44},
  141713. _noise_thresh_44,
  141714. _psy_ath_floater,
  141715. _psy_ath_abs,
  141716. _psy_lowpass_44,
  141717. _psy_global_44,
  141718. _global_mapping_44,
  141719. _psy_stereo_modes_44,
  141720. _floor_books,
  141721. _floor,
  141722. _floor_short_mapping_44,
  141723. _floor_long_mapping_44,
  141724. _mapres_template_44_stereo
  141725. };
  141726. /*** End of inlined file: setup_44.h ***/
  141727. /*** Start of inlined file: setup_44u.h ***/
  141728. /*** Start of inlined file: residue_44u.h ***/
  141729. /*** Start of inlined file: res_books_uncoupled.h ***/
  141730. static long _vq_quantlist__16u0__p1_0[] = {
  141731. 1,
  141732. 0,
  141733. 2,
  141734. };
  141735. static long _vq_lengthlist__16u0__p1_0[] = {
  141736. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  141737. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  141738. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  141739. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  141740. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  141741. 12,
  141742. };
  141743. static float _vq_quantthresh__16u0__p1_0[] = {
  141744. -0.5, 0.5,
  141745. };
  141746. static long _vq_quantmap__16u0__p1_0[] = {
  141747. 1, 0, 2,
  141748. };
  141749. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  141750. _vq_quantthresh__16u0__p1_0,
  141751. _vq_quantmap__16u0__p1_0,
  141752. 3,
  141753. 3
  141754. };
  141755. static static_codebook _16u0__p1_0 = {
  141756. 4, 81,
  141757. _vq_lengthlist__16u0__p1_0,
  141758. 1, -535822336, 1611661312, 2, 0,
  141759. _vq_quantlist__16u0__p1_0,
  141760. NULL,
  141761. &_vq_auxt__16u0__p1_0,
  141762. NULL,
  141763. 0
  141764. };
  141765. static long _vq_quantlist__16u0__p2_0[] = {
  141766. 1,
  141767. 0,
  141768. 2,
  141769. };
  141770. static long _vq_lengthlist__16u0__p2_0[] = {
  141771. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  141772. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  141773. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  141774. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  141775. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  141776. 8,
  141777. };
  141778. static float _vq_quantthresh__16u0__p2_0[] = {
  141779. -0.5, 0.5,
  141780. };
  141781. static long _vq_quantmap__16u0__p2_0[] = {
  141782. 1, 0, 2,
  141783. };
  141784. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  141785. _vq_quantthresh__16u0__p2_0,
  141786. _vq_quantmap__16u0__p2_0,
  141787. 3,
  141788. 3
  141789. };
  141790. static static_codebook _16u0__p2_0 = {
  141791. 4, 81,
  141792. _vq_lengthlist__16u0__p2_0,
  141793. 1, -535822336, 1611661312, 2, 0,
  141794. _vq_quantlist__16u0__p2_0,
  141795. NULL,
  141796. &_vq_auxt__16u0__p2_0,
  141797. NULL,
  141798. 0
  141799. };
  141800. static long _vq_quantlist__16u0__p3_0[] = {
  141801. 2,
  141802. 1,
  141803. 3,
  141804. 0,
  141805. 4,
  141806. };
  141807. static long _vq_lengthlist__16u0__p3_0[] = {
  141808. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  141809. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  141810. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  141811. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  141812. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  141813. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  141814. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  141815. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  141816. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  141817. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  141818. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  141819. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  141820. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  141821. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  141822. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  141823. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  141824. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  141825. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  141826. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  141827. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  141828. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  141829. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  141830. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  141831. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  141832. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  141833. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  141834. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  141835. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  141836. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  141837. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  141838. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  141839. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  141840. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  141841. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  141842. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  141843. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  141844. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  141845. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  141846. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  141847. 18,
  141848. };
  141849. static float _vq_quantthresh__16u0__p3_0[] = {
  141850. -1.5, -0.5, 0.5, 1.5,
  141851. };
  141852. static long _vq_quantmap__16u0__p3_0[] = {
  141853. 3, 1, 0, 2, 4,
  141854. };
  141855. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  141856. _vq_quantthresh__16u0__p3_0,
  141857. _vq_quantmap__16u0__p3_0,
  141858. 5,
  141859. 5
  141860. };
  141861. static static_codebook _16u0__p3_0 = {
  141862. 4, 625,
  141863. _vq_lengthlist__16u0__p3_0,
  141864. 1, -533725184, 1611661312, 3, 0,
  141865. _vq_quantlist__16u0__p3_0,
  141866. NULL,
  141867. &_vq_auxt__16u0__p3_0,
  141868. NULL,
  141869. 0
  141870. };
  141871. static long _vq_quantlist__16u0__p4_0[] = {
  141872. 2,
  141873. 1,
  141874. 3,
  141875. 0,
  141876. 4,
  141877. };
  141878. static long _vq_lengthlist__16u0__p4_0[] = {
  141879. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  141880. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  141881. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  141882. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  141883. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  141884. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  141885. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  141886. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  141887. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  141888. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  141889. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  141890. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  141891. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  141892. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  141893. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  141894. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  141895. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  141896. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  141897. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  141898. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  141899. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  141900. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  141901. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  141902. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  141903. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  141904. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  141905. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  141906. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  141907. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  141908. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  141909. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  141910. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  141911. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  141912. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  141913. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  141914. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  141915. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  141916. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  141917. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  141918. 11,
  141919. };
  141920. static float _vq_quantthresh__16u0__p4_0[] = {
  141921. -1.5, -0.5, 0.5, 1.5,
  141922. };
  141923. static long _vq_quantmap__16u0__p4_0[] = {
  141924. 3, 1, 0, 2, 4,
  141925. };
  141926. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  141927. _vq_quantthresh__16u0__p4_0,
  141928. _vq_quantmap__16u0__p4_0,
  141929. 5,
  141930. 5
  141931. };
  141932. static static_codebook _16u0__p4_0 = {
  141933. 4, 625,
  141934. _vq_lengthlist__16u0__p4_0,
  141935. 1, -533725184, 1611661312, 3, 0,
  141936. _vq_quantlist__16u0__p4_0,
  141937. NULL,
  141938. &_vq_auxt__16u0__p4_0,
  141939. NULL,
  141940. 0
  141941. };
  141942. static long _vq_quantlist__16u0__p5_0[] = {
  141943. 4,
  141944. 3,
  141945. 5,
  141946. 2,
  141947. 6,
  141948. 1,
  141949. 7,
  141950. 0,
  141951. 8,
  141952. };
  141953. static long _vq_lengthlist__16u0__p5_0[] = {
  141954. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  141955. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  141956. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  141957. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141958. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  141959. 12,
  141960. };
  141961. static float _vq_quantthresh__16u0__p5_0[] = {
  141962. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141963. };
  141964. static long _vq_quantmap__16u0__p5_0[] = {
  141965. 7, 5, 3, 1, 0, 2, 4, 6,
  141966. 8,
  141967. };
  141968. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  141969. _vq_quantthresh__16u0__p5_0,
  141970. _vq_quantmap__16u0__p5_0,
  141971. 9,
  141972. 9
  141973. };
  141974. static static_codebook _16u0__p5_0 = {
  141975. 2, 81,
  141976. _vq_lengthlist__16u0__p5_0,
  141977. 1, -531628032, 1611661312, 4, 0,
  141978. _vq_quantlist__16u0__p5_0,
  141979. NULL,
  141980. &_vq_auxt__16u0__p5_0,
  141981. NULL,
  141982. 0
  141983. };
  141984. static long _vq_quantlist__16u0__p6_0[] = {
  141985. 6,
  141986. 5,
  141987. 7,
  141988. 4,
  141989. 8,
  141990. 3,
  141991. 9,
  141992. 2,
  141993. 10,
  141994. 1,
  141995. 11,
  141996. 0,
  141997. 12,
  141998. };
  141999. static long _vq_lengthlist__16u0__p6_0[] = {
  142000. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142001. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142002. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142003. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142004. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142005. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142006. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142007. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142008. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142009. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142010. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142011. };
  142012. static float _vq_quantthresh__16u0__p6_0[] = {
  142013. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142014. 12.5, 17.5, 22.5, 27.5,
  142015. };
  142016. static long _vq_quantmap__16u0__p6_0[] = {
  142017. 11, 9, 7, 5, 3, 1, 0, 2,
  142018. 4, 6, 8, 10, 12,
  142019. };
  142020. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142021. _vq_quantthresh__16u0__p6_0,
  142022. _vq_quantmap__16u0__p6_0,
  142023. 13,
  142024. 13
  142025. };
  142026. static static_codebook _16u0__p6_0 = {
  142027. 2, 169,
  142028. _vq_lengthlist__16u0__p6_0,
  142029. 1, -526516224, 1616117760, 4, 0,
  142030. _vq_quantlist__16u0__p6_0,
  142031. NULL,
  142032. &_vq_auxt__16u0__p6_0,
  142033. NULL,
  142034. 0
  142035. };
  142036. static long _vq_quantlist__16u0__p6_1[] = {
  142037. 2,
  142038. 1,
  142039. 3,
  142040. 0,
  142041. 4,
  142042. };
  142043. static long _vq_lengthlist__16u0__p6_1[] = {
  142044. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142045. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142046. };
  142047. static float _vq_quantthresh__16u0__p6_1[] = {
  142048. -1.5, -0.5, 0.5, 1.5,
  142049. };
  142050. static long _vq_quantmap__16u0__p6_1[] = {
  142051. 3, 1, 0, 2, 4,
  142052. };
  142053. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142054. _vq_quantthresh__16u0__p6_1,
  142055. _vq_quantmap__16u0__p6_1,
  142056. 5,
  142057. 5
  142058. };
  142059. static static_codebook _16u0__p6_1 = {
  142060. 2, 25,
  142061. _vq_lengthlist__16u0__p6_1,
  142062. 1, -533725184, 1611661312, 3, 0,
  142063. _vq_quantlist__16u0__p6_1,
  142064. NULL,
  142065. &_vq_auxt__16u0__p6_1,
  142066. NULL,
  142067. 0
  142068. };
  142069. static long _vq_quantlist__16u0__p7_0[] = {
  142070. 1,
  142071. 0,
  142072. 2,
  142073. };
  142074. static long _vq_lengthlist__16u0__p7_0[] = {
  142075. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142076. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142077. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142078. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142079. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142080. 7,
  142081. };
  142082. static float _vq_quantthresh__16u0__p7_0[] = {
  142083. -157.5, 157.5,
  142084. };
  142085. static long _vq_quantmap__16u0__p7_0[] = {
  142086. 1, 0, 2,
  142087. };
  142088. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142089. _vq_quantthresh__16u0__p7_0,
  142090. _vq_quantmap__16u0__p7_0,
  142091. 3,
  142092. 3
  142093. };
  142094. static static_codebook _16u0__p7_0 = {
  142095. 4, 81,
  142096. _vq_lengthlist__16u0__p7_0,
  142097. 1, -518803456, 1628680192, 2, 0,
  142098. _vq_quantlist__16u0__p7_0,
  142099. NULL,
  142100. &_vq_auxt__16u0__p7_0,
  142101. NULL,
  142102. 0
  142103. };
  142104. static long _vq_quantlist__16u0__p7_1[] = {
  142105. 7,
  142106. 6,
  142107. 8,
  142108. 5,
  142109. 9,
  142110. 4,
  142111. 10,
  142112. 3,
  142113. 11,
  142114. 2,
  142115. 12,
  142116. 1,
  142117. 13,
  142118. 0,
  142119. 14,
  142120. };
  142121. static long _vq_lengthlist__16u0__p7_1[] = {
  142122. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142123. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142124. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  142125. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  142126. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  142127. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  142128. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142129. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142130. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142131. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142132. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142133. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142134. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142135. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142136. 10,
  142137. };
  142138. static float _vq_quantthresh__16u0__p7_1[] = {
  142139. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142140. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142141. };
  142142. static long _vq_quantmap__16u0__p7_1[] = {
  142143. 13, 11, 9, 7, 5, 3, 1, 0,
  142144. 2, 4, 6, 8, 10, 12, 14,
  142145. };
  142146. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  142147. _vq_quantthresh__16u0__p7_1,
  142148. _vq_quantmap__16u0__p7_1,
  142149. 15,
  142150. 15
  142151. };
  142152. static static_codebook _16u0__p7_1 = {
  142153. 2, 225,
  142154. _vq_lengthlist__16u0__p7_1,
  142155. 1, -520986624, 1620377600, 4, 0,
  142156. _vq_quantlist__16u0__p7_1,
  142157. NULL,
  142158. &_vq_auxt__16u0__p7_1,
  142159. NULL,
  142160. 0
  142161. };
  142162. static long _vq_quantlist__16u0__p7_2[] = {
  142163. 10,
  142164. 9,
  142165. 11,
  142166. 8,
  142167. 12,
  142168. 7,
  142169. 13,
  142170. 6,
  142171. 14,
  142172. 5,
  142173. 15,
  142174. 4,
  142175. 16,
  142176. 3,
  142177. 17,
  142178. 2,
  142179. 18,
  142180. 1,
  142181. 19,
  142182. 0,
  142183. 20,
  142184. };
  142185. static long _vq_lengthlist__16u0__p7_2[] = {
  142186. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  142187. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  142188. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  142189. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  142190. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  142191. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  142192. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  142193. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  142194. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  142195. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  142196. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  142197. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  142198. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  142199. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  142200. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  142201. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  142202. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  142203. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  142204. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  142205. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  142206. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  142207. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  142208. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  142209. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  142210. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  142211. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  142212. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  142213. 10,10,12,11,10,11,11,11,10,
  142214. };
  142215. static float _vq_quantthresh__16u0__p7_2[] = {
  142216. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  142217. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  142218. 6.5, 7.5, 8.5, 9.5,
  142219. };
  142220. static long _vq_quantmap__16u0__p7_2[] = {
  142221. 19, 17, 15, 13, 11, 9, 7, 5,
  142222. 3, 1, 0, 2, 4, 6, 8, 10,
  142223. 12, 14, 16, 18, 20,
  142224. };
  142225. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  142226. _vq_quantthresh__16u0__p7_2,
  142227. _vq_quantmap__16u0__p7_2,
  142228. 21,
  142229. 21
  142230. };
  142231. static static_codebook _16u0__p7_2 = {
  142232. 2, 441,
  142233. _vq_lengthlist__16u0__p7_2,
  142234. 1, -529268736, 1611661312, 5, 0,
  142235. _vq_quantlist__16u0__p7_2,
  142236. NULL,
  142237. &_vq_auxt__16u0__p7_2,
  142238. NULL,
  142239. 0
  142240. };
  142241. static long _huff_lengthlist__16u0__single[] = {
  142242. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  142243. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  142244. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  142245. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  142246. };
  142247. static static_codebook _huff_book__16u0__single = {
  142248. 2, 64,
  142249. _huff_lengthlist__16u0__single,
  142250. 0, 0, 0, 0, 0,
  142251. NULL,
  142252. NULL,
  142253. NULL,
  142254. NULL,
  142255. 0
  142256. };
  142257. static long _huff_lengthlist__16u1__long[] = {
  142258. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  142259. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  142260. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  142261. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  142262. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  142263. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  142264. 16,13,16,18,
  142265. };
  142266. static static_codebook _huff_book__16u1__long = {
  142267. 2, 100,
  142268. _huff_lengthlist__16u1__long,
  142269. 0, 0, 0, 0, 0,
  142270. NULL,
  142271. NULL,
  142272. NULL,
  142273. NULL,
  142274. 0
  142275. };
  142276. static long _vq_quantlist__16u1__p1_0[] = {
  142277. 1,
  142278. 0,
  142279. 2,
  142280. };
  142281. static long _vq_lengthlist__16u1__p1_0[] = {
  142282. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  142283. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  142284. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  142285. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142286. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  142287. 11,
  142288. };
  142289. static float _vq_quantthresh__16u1__p1_0[] = {
  142290. -0.5, 0.5,
  142291. };
  142292. static long _vq_quantmap__16u1__p1_0[] = {
  142293. 1, 0, 2,
  142294. };
  142295. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  142296. _vq_quantthresh__16u1__p1_0,
  142297. _vq_quantmap__16u1__p1_0,
  142298. 3,
  142299. 3
  142300. };
  142301. static static_codebook _16u1__p1_0 = {
  142302. 4, 81,
  142303. _vq_lengthlist__16u1__p1_0,
  142304. 1, -535822336, 1611661312, 2, 0,
  142305. _vq_quantlist__16u1__p1_0,
  142306. NULL,
  142307. &_vq_auxt__16u1__p1_0,
  142308. NULL,
  142309. 0
  142310. };
  142311. static long _vq_quantlist__16u1__p2_0[] = {
  142312. 1,
  142313. 0,
  142314. 2,
  142315. };
  142316. static long _vq_lengthlist__16u1__p2_0[] = {
  142317. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  142318. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  142319. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  142320. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142321. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  142322. 8,
  142323. };
  142324. static float _vq_quantthresh__16u1__p2_0[] = {
  142325. -0.5, 0.5,
  142326. };
  142327. static long _vq_quantmap__16u1__p2_0[] = {
  142328. 1, 0, 2,
  142329. };
  142330. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  142331. _vq_quantthresh__16u1__p2_0,
  142332. _vq_quantmap__16u1__p2_0,
  142333. 3,
  142334. 3
  142335. };
  142336. static static_codebook _16u1__p2_0 = {
  142337. 4, 81,
  142338. _vq_lengthlist__16u1__p2_0,
  142339. 1, -535822336, 1611661312, 2, 0,
  142340. _vq_quantlist__16u1__p2_0,
  142341. NULL,
  142342. &_vq_auxt__16u1__p2_0,
  142343. NULL,
  142344. 0
  142345. };
  142346. static long _vq_quantlist__16u1__p3_0[] = {
  142347. 2,
  142348. 1,
  142349. 3,
  142350. 0,
  142351. 4,
  142352. };
  142353. static long _vq_lengthlist__16u1__p3_0[] = {
  142354. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  142355. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  142356. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  142357. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142358. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  142359. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  142360. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  142361. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  142362. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142363. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  142364. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  142365. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  142366. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  142367. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  142368. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  142369. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  142370. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142371. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  142372. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  142373. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  142374. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  142375. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  142376. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  142377. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  142378. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  142379. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  142380. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  142381. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  142382. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  142383. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  142384. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  142385. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  142386. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  142387. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  142388. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  142389. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  142390. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  142391. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  142392. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  142393. 16,
  142394. };
  142395. static float _vq_quantthresh__16u1__p3_0[] = {
  142396. -1.5, -0.5, 0.5, 1.5,
  142397. };
  142398. static long _vq_quantmap__16u1__p3_0[] = {
  142399. 3, 1, 0, 2, 4,
  142400. };
  142401. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  142402. _vq_quantthresh__16u1__p3_0,
  142403. _vq_quantmap__16u1__p3_0,
  142404. 5,
  142405. 5
  142406. };
  142407. static static_codebook _16u1__p3_0 = {
  142408. 4, 625,
  142409. _vq_lengthlist__16u1__p3_0,
  142410. 1, -533725184, 1611661312, 3, 0,
  142411. _vq_quantlist__16u1__p3_0,
  142412. NULL,
  142413. &_vq_auxt__16u1__p3_0,
  142414. NULL,
  142415. 0
  142416. };
  142417. static long _vq_quantlist__16u1__p4_0[] = {
  142418. 2,
  142419. 1,
  142420. 3,
  142421. 0,
  142422. 4,
  142423. };
  142424. static long _vq_lengthlist__16u1__p4_0[] = {
  142425. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  142426. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  142427. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  142428. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  142429. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  142430. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  142431. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  142432. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  142433. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  142434. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  142435. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  142436. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  142437. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  142438. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  142439. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  142440. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  142441. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  142442. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  142443. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  142444. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  142445. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  142446. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  142447. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  142448. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  142449. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  142450. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  142451. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  142452. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  142453. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  142454. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  142455. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  142456. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  142457. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  142458. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  142459. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  142460. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  142461. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  142462. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  142463. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  142464. 11,
  142465. };
  142466. static float _vq_quantthresh__16u1__p4_0[] = {
  142467. -1.5, -0.5, 0.5, 1.5,
  142468. };
  142469. static long _vq_quantmap__16u1__p4_0[] = {
  142470. 3, 1, 0, 2, 4,
  142471. };
  142472. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  142473. _vq_quantthresh__16u1__p4_0,
  142474. _vq_quantmap__16u1__p4_0,
  142475. 5,
  142476. 5
  142477. };
  142478. static static_codebook _16u1__p4_0 = {
  142479. 4, 625,
  142480. _vq_lengthlist__16u1__p4_0,
  142481. 1, -533725184, 1611661312, 3, 0,
  142482. _vq_quantlist__16u1__p4_0,
  142483. NULL,
  142484. &_vq_auxt__16u1__p4_0,
  142485. NULL,
  142486. 0
  142487. };
  142488. static long _vq_quantlist__16u1__p5_0[] = {
  142489. 4,
  142490. 3,
  142491. 5,
  142492. 2,
  142493. 6,
  142494. 1,
  142495. 7,
  142496. 0,
  142497. 8,
  142498. };
  142499. static long _vq_lengthlist__16u1__p5_0[] = {
  142500. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142501. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142502. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  142503. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  142504. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  142505. 13,
  142506. };
  142507. static float _vq_quantthresh__16u1__p5_0[] = {
  142508. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142509. };
  142510. static long _vq_quantmap__16u1__p5_0[] = {
  142511. 7, 5, 3, 1, 0, 2, 4, 6,
  142512. 8,
  142513. };
  142514. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  142515. _vq_quantthresh__16u1__p5_0,
  142516. _vq_quantmap__16u1__p5_0,
  142517. 9,
  142518. 9
  142519. };
  142520. static static_codebook _16u1__p5_0 = {
  142521. 2, 81,
  142522. _vq_lengthlist__16u1__p5_0,
  142523. 1, -531628032, 1611661312, 4, 0,
  142524. _vq_quantlist__16u1__p5_0,
  142525. NULL,
  142526. &_vq_auxt__16u1__p5_0,
  142527. NULL,
  142528. 0
  142529. };
  142530. static long _vq_quantlist__16u1__p6_0[] = {
  142531. 4,
  142532. 3,
  142533. 5,
  142534. 2,
  142535. 6,
  142536. 1,
  142537. 7,
  142538. 0,
  142539. 8,
  142540. };
  142541. static long _vq_lengthlist__16u1__p6_0[] = {
  142542. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  142543. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  142544. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  142545. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  142546. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  142547. 11,
  142548. };
  142549. static float _vq_quantthresh__16u1__p6_0[] = {
  142550. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142551. };
  142552. static long _vq_quantmap__16u1__p6_0[] = {
  142553. 7, 5, 3, 1, 0, 2, 4, 6,
  142554. 8,
  142555. };
  142556. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  142557. _vq_quantthresh__16u1__p6_0,
  142558. _vq_quantmap__16u1__p6_0,
  142559. 9,
  142560. 9
  142561. };
  142562. static static_codebook _16u1__p6_0 = {
  142563. 2, 81,
  142564. _vq_lengthlist__16u1__p6_0,
  142565. 1, -531628032, 1611661312, 4, 0,
  142566. _vq_quantlist__16u1__p6_0,
  142567. NULL,
  142568. &_vq_auxt__16u1__p6_0,
  142569. NULL,
  142570. 0
  142571. };
  142572. static long _vq_quantlist__16u1__p7_0[] = {
  142573. 1,
  142574. 0,
  142575. 2,
  142576. };
  142577. static long _vq_lengthlist__16u1__p7_0[] = {
  142578. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  142579. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  142580. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  142581. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  142582. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  142583. 13,
  142584. };
  142585. static float _vq_quantthresh__16u1__p7_0[] = {
  142586. -5.5, 5.5,
  142587. };
  142588. static long _vq_quantmap__16u1__p7_0[] = {
  142589. 1, 0, 2,
  142590. };
  142591. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  142592. _vq_quantthresh__16u1__p7_0,
  142593. _vq_quantmap__16u1__p7_0,
  142594. 3,
  142595. 3
  142596. };
  142597. static static_codebook _16u1__p7_0 = {
  142598. 4, 81,
  142599. _vq_lengthlist__16u1__p7_0,
  142600. 1, -529137664, 1618345984, 2, 0,
  142601. _vq_quantlist__16u1__p7_0,
  142602. NULL,
  142603. &_vq_auxt__16u1__p7_0,
  142604. NULL,
  142605. 0
  142606. };
  142607. static long _vq_quantlist__16u1__p7_1[] = {
  142608. 5,
  142609. 4,
  142610. 6,
  142611. 3,
  142612. 7,
  142613. 2,
  142614. 8,
  142615. 1,
  142616. 9,
  142617. 0,
  142618. 10,
  142619. };
  142620. static long _vq_lengthlist__16u1__p7_1[] = {
  142621. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  142622. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  142623. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  142624. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  142625. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  142626. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  142627. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  142628. 8, 9, 9,10,10,10,10,10,10,
  142629. };
  142630. static float _vq_quantthresh__16u1__p7_1[] = {
  142631. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142632. 3.5, 4.5,
  142633. };
  142634. static long _vq_quantmap__16u1__p7_1[] = {
  142635. 9, 7, 5, 3, 1, 0, 2, 4,
  142636. 6, 8, 10,
  142637. };
  142638. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  142639. _vq_quantthresh__16u1__p7_1,
  142640. _vq_quantmap__16u1__p7_1,
  142641. 11,
  142642. 11
  142643. };
  142644. static static_codebook _16u1__p7_1 = {
  142645. 2, 121,
  142646. _vq_lengthlist__16u1__p7_1,
  142647. 1, -531365888, 1611661312, 4, 0,
  142648. _vq_quantlist__16u1__p7_1,
  142649. NULL,
  142650. &_vq_auxt__16u1__p7_1,
  142651. NULL,
  142652. 0
  142653. };
  142654. static long _vq_quantlist__16u1__p8_0[] = {
  142655. 5,
  142656. 4,
  142657. 6,
  142658. 3,
  142659. 7,
  142660. 2,
  142661. 8,
  142662. 1,
  142663. 9,
  142664. 0,
  142665. 10,
  142666. };
  142667. static long _vq_lengthlist__16u1__p8_0[] = {
  142668. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  142669. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  142670. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  142671. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  142672. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  142673. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  142674. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  142675. 13,14,14,15,15,16,16,15,16,
  142676. };
  142677. static float _vq_quantthresh__16u1__p8_0[] = {
  142678. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  142679. 38.5, 49.5,
  142680. };
  142681. static long _vq_quantmap__16u1__p8_0[] = {
  142682. 9, 7, 5, 3, 1, 0, 2, 4,
  142683. 6, 8, 10,
  142684. };
  142685. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  142686. _vq_quantthresh__16u1__p8_0,
  142687. _vq_quantmap__16u1__p8_0,
  142688. 11,
  142689. 11
  142690. };
  142691. static static_codebook _16u1__p8_0 = {
  142692. 2, 121,
  142693. _vq_lengthlist__16u1__p8_0,
  142694. 1, -524582912, 1618345984, 4, 0,
  142695. _vq_quantlist__16u1__p8_0,
  142696. NULL,
  142697. &_vq_auxt__16u1__p8_0,
  142698. NULL,
  142699. 0
  142700. };
  142701. static long _vq_quantlist__16u1__p8_1[] = {
  142702. 5,
  142703. 4,
  142704. 6,
  142705. 3,
  142706. 7,
  142707. 2,
  142708. 8,
  142709. 1,
  142710. 9,
  142711. 0,
  142712. 10,
  142713. };
  142714. static long _vq_lengthlist__16u1__p8_1[] = {
  142715. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  142716. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  142717. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  142718. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  142719. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  142720. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  142721. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  142722. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  142723. };
  142724. static float _vq_quantthresh__16u1__p8_1[] = {
  142725. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142726. 3.5, 4.5,
  142727. };
  142728. static long _vq_quantmap__16u1__p8_1[] = {
  142729. 9, 7, 5, 3, 1, 0, 2, 4,
  142730. 6, 8, 10,
  142731. };
  142732. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  142733. _vq_quantthresh__16u1__p8_1,
  142734. _vq_quantmap__16u1__p8_1,
  142735. 11,
  142736. 11
  142737. };
  142738. static static_codebook _16u1__p8_1 = {
  142739. 2, 121,
  142740. _vq_lengthlist__16u1__p8_1,
  142741. 1, -531365888, 1611661312, 4, 0,
  142742. _vq_quantlist__16u1__p8_1,
  142743. NULL,
  142744. &_vq_auxt__16u1__p8_1,
  142745. NULL,
  142746. 0
  142747. };
  142748. static long _vq_quantlist__16u1__p9_0[] = {
  142749. 7,
  142750. 6,
  142751. 8,
  142752. 5,
  142753. 9,
  142754. 4,
  142755. 10,
  142756. 3,
  142757. 11,
  142758. 2,
  142759. 12,
  142760. 1,
  142761. 13,
  142762. 0,
  142763. 14,
  142764. };
  142765. static long _vq_lengthlist__16u1__p9_0[] = {
  142766. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142767. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142768. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142769. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142770. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142771. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142772. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142773. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142774. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142775. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142776. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142777. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142778. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142779. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142780. 8,
  142781. };
  142782. static float _vq_quantthresh__16u1__p9_0[] = {
  142783. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  142784. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  142785. };
  142786. static long _vq_quantmap__16u1__p9_0[] = {
  142787. 13, 11, 9, 7, 5, 3, 1, 0,
  142788. 2, 4, 6, 8, 10, 12, 14,
  142789. };
  142790. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  142791. _vq_quantthresh__16u1__p9_0,
  142792. _vq_quantmap__16u1__p9_0,
  142793. 15,
  142794. 15
  142795. };
  142796. static static_codebook _16u1__p9_0 = {
  142797. 2, 225,
  142798. _vq_lengthlist__16u1__p9_0,
  142799. 1, -514071552, 1627381760, 4, 0,
  142800. _vq_quantlist__16u1__p9_0,
  142801. NULL,
  142802. &_vq_auxt__16u1__p9_0,
  142803. NULL,
  142804. 0
  142805. };
  142806. static long _vq_quantlist__16u1__p9_1[] = {
  142807. 7,
  142808. 6,
  142809. 8,
  142810. 5,
  142811. 9,
  142812. 4,
  142813. 10,
  142814. 3,
  142815. 11,
  142816. 2,
  142817. 12,
  142818. 1,
  142819. 13,
  142820. 0,
  142821. 14,
  142822. };
  142823. static long _vq_lengthlist__16u1__p9_1[] = {
  142824. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  142825. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  142826. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  142827. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  142828. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  142829. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  142830. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  142831. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  142832. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  142833. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142834. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142835. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142836. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142837. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142838. 9,
  142839. };
  142840. static float _vq_quantthresh__16u1__p9_1[] = {
  142841. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142842. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142843. };
  142844. static long _vq_quantmap__16u1__p9_1[] = {
  142845. 13, 11, 9, 7, 5, 3, 1, 0,
  142846. 2, 4, 6, 8, 10, 12, 14,
  142847. };
  142848. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  142849. _vq_quantthresh__16u1__p9_1,
  142850. _vq_quantmap__16u1__p9_1,
  142851. 15,
  142852. 15
  142853. };
  142854. static static_codebook _16u1__p9_1 = {
  142855. 2, 225,
  142856. _vq_lengthlist__16u1__p9_1,
  142857. 1, -522338304, 1620115456, 4, 0,
  142858. _vq_quantlist__16u1__p9_1,
  142859. NULL,
  142860. &_vq_auxt__16u1__p9_1,
  142861. NULL,
  142862. 0
  142863. };
  142864. static long _vq_quantlist__16u1__p9_2[] = {
  142865. 8,
  142866. 7,
  142867. 9,
  142868. 6,
  142869. 10,
  142870. 5,
  142871. 11,
  142872. 4,
  142873. 12,
  142874. 3,
  142875. 13,
  142876. 2,
  142877. 14,
  142878. 1,
  142879. 15,
  142880. 0,
  142881. 16,
  142882. };
  142883. static long _vq_lengthlist__16u1__p9_2[] = {
  142884. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  142885. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  142886. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  142887. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  142888. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  142889. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  142890. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  142891. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  142892. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  142893. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  142894. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  142895. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  142896. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  142897. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  142898. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  142899. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  142900. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  142901. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  142902. 10,
  142903. };
  142904. static float _vq_quantthresh__16u1__p9_2[] = {
  142905. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142906. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142907. };
  142908. static long _vq_quantmap__16u1__p9_2[] = {
  142909. 15, 13, 11, 9, 7, 5, 3, 1,
  142910. 0, 2, 4, 6, 8, 10, 12, 14,
  142911. 16,
  142912. };
  142913. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  142914. _vq_quantthresh__16u1__p9_2,
  142915. _vq_quantmap__16u1__p9_2,
  142916. 17,
  142917. 17
  142918. };
  142919. static static_codebook _16u1__p9_2 = {
  142920. 2, 289,
  142921. _vq_lengthlist__16u1__p9_2,
  142922. 1, -529530880, 1611661312, 5, 0,
  142923. _vq_quantlist__16u1__p9_2,
  142924. NULL,
  142925. &_vq_auxt__16u1__p9_2,
  142926. NULL,
  142927. 0
  142928. };
  142929. static long _huff_lengthlist__16u1__short[] = {
  142930. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  142931. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  142932. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  142933. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  142934. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  142935. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  142936. 16,16,16,16,
  142937. };
  142938. static static_codebook _huff_book__16u1__short = {
  142939. 2, 100,
  142940. _huff_lengthlist__16u1__short,
  142941. 0, 0, 0, 0, 0,
  142942. NULL,
  142943. NULL,
  142944. NULL,
  142945. NULL,
  142946. 0
  142947. };
  142948. static long _huff_lengthlist__16u2__long[] = {
  142949. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  142950. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  142951. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  142952. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  142953. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  142954. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  142955. 13,14,18,18,
  142956. };
  142957. static static_codebook _huff_book__16u2__long = {
  142958. 2, 100,
  142959. _huff_lengthlist__16u2__long,
  142960. 0, 0, 0, 0, 0,
  142961. NULL,
  142962. NULL,
  142963. NULL,
  142964. NULL,
  142965. 0
  142966. };
  142967. static long _huff_lengthlist__16u2__short[] = {
  142968. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  142969. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  142970. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  142971. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  142972. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  142973. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  142974. 16,16,16,16,
  142975. };
  142976. static static_codebook _huff_book__16u2__short = {
  142977. 2, 100,
  142978. _huff_lengthlist__16u2__short,
  142979. 0, 0, 0, 0, 0,
  142980. NULL,
  142981. NULL,
  142982. NULL,
  142983. NULL,
  142984. 0
  142985. };
  142986. static long _vq_quantlist__16u2_p1_0[] = {
  142987. 1,
  142988. 0,
  142989. 2,
  142990. };
  142991. static long _vq_lengthlist__16u2_p1_0[] = {
  142992. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  142993. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  142994. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  142995. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  142996. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  142997. 10,
  142998. };
  142999. static float _vq_quantthresh__16u2_p1_0[] = {
  143000. -0.5, 0.5,
  143001. };
  143002. static long _vq_quantmap__16u2_p1_0[] = {
  143003. 1, 0, 2,
  143004. };
  143005. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143006. _vq_quantthresh__16u2_p1_0,
  143007. _vq_quantmap__16u2_p1_0,
  143008. 3,
  143009. 3
  143010. };
  143011. static static_codebook _16u2_p1_0 = {
  143012. 4, 81,
  143013. _vq_lengthlist__16u2_p1_0,
  143014. 1, -535822336, 1611661312, 2, 0,
  143015. _vq_quantlist__16u2_p1_0,
  143016. NULL,
  143017. &_vq_auxt__16u2_p1_0,
  143018. NULL,
  143019. 0
  143020. };
  143021. static long _vq_quantlist__16u2_p2_0[] = {
  143022. 2,
  143023. 1,
  143024. 3,
  143025. 0,
  143026. 4,
  143027. };
  143028. static long _vq_lengthlist__16u2_p2_0[] = {
  143029. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143030. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143031. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143032. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143033. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143034. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143035. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143036. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143037. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143038. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143039. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143040. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143041. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143042. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143043. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143044. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143045. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143046. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143047. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143048. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143049. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143050. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143051. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143052. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143053. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143054. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143055. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143056. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143057. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143058. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143059. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143060. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143061. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143062. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143063. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143064. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143065. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143066. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143067. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143068. 13,
  143069. };
  143070. static float _vq_quantthresh__16u2_p2_0[] = {
  143071. -1.5, -0.5, 0.5, 1.5,
  143072. };
  143073. static long _vq_quantmap__16u2_p2_0[] = {
  143074. 3, 1, 0, 2, 4,
  143075. };
  143076. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143077. _vq_quantthresh__16u2_p2_0,
  143078. _vq_quantmap__16u2_p2_0,
  143079. 5,
  143080. 5
  143081. };
  143082. static static_codebook _16u2_p2_0 = {
  143083. 4, 625,
  143084. _vq_lengthlist__16u2_p2_0,
  143085. 1, -533725184, 1611661312, 3, 0,
  143086. _vq_quantlist__16u2_p2_0,
  143087. NULL,
  143088. &_vq_auxt__16u2_p2_0,
  143089. NULL,
  143090. 0
  143091. };
  143092. static long _vq_quantlist__16u2_p3_0[] = {
  143093. 4,
  143094. 3,
  143095. 5,
  143096. 2,
  143097. 6,
  143098. 1,
  143099. 7,
  143100. 0,
  143101. 8,
  143102. };
  143103. static long _vq_lengthlist__16u2_p3_0[] = {
  143104. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143105. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143106. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143107. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143108. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143109. 11,
  143110. };
  143111. static float _vq_quantthresh__16u2_p3_0[] = {
  143112. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143113. };
  143114. static long _vq_quantmap__16u2_p3_0[] = {
  143115. 7, 5, 3, 1, 0, 2, 4, 6,
  143116. 8,
  143117. };
  143118. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143119. _vq_quantthresh__16u2_p3_0,
  143120. _vq_quantmap__16u2_p3_0,
  143121. 9,
  143122. 9
  143123. };
  143124. static static_codebook _16u2_p3_0 = {
  143125. 2, 81,
  143126. _vq_lengthlist__16u2_p3_0,
  143127. 1, -531628032, 1611661312, 4, 0,
  143128. _vq_quantlist__16u2_p3_0,
  143129. NULL,
  143130. &_vq_auxt__16u2_p3_0,
  143131. NULL,
  143132. 0
  143133. };
  143134. static long _vq_quantlist__16u2_p4_0[] = {
  143135. 8,
  143136. 7,
  143137. 9,
  143138. 6,
  143139. 10,
  143140. 5,
  143141. 11,
  143142. 4,
  143143. 12,
  143144. 3,
  143145. 13,
  143146. 2,
  143147. 14,
  143148. 1,
  143149. 15,
  143150. 0,
  143151. 16,
  143152. };
  143153. static long _vq_lengthlist__16u2_p4_0[] = {
  143154. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  143155. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  143156. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  143157. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  143158. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  143159. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  143160. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143161. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  143162. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  143163. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  143164. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  143165. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  143166. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  143167. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  143168. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  143169. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  143170. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  143171. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  143172. 14,
  143173. };
  143174. static float _vq_quantthresh__16u2_p4_0[] = {
  143175. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143176. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143177. };
  143178. static long _vq_quantmap__16u2_p4_0[] = {
  143179. 15, 13, 11, 9, 7, 5, 3, 1,
  143180. 0, 2, 4, 6, 8, 10, 12, 14,
  143181. 16,
  143182. };
  143183. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  143184. _vq_quantthresh__16u2_p4_0,
  143185. _vq_quantmap__16u2_p4_0,
  143186. 17,
  143187. 17
  143188. };
  143189. static static_codebook _16u2_p4_0 = {
  143190. 2, 289,
  143191. _vq_lengthlist__16u2_p4_0,
  143192. 1, -529530880, 1611661312, 5, 0,
  143193. _vq_quantlist__16u2_p4_0,
  143194. NULL,
  143195. &_vq_auxt__16u2_p4_0,
  143196. NULL,
  143197. 0
  143198. };
  143199. static long _vq_quantlist__16u2_p5_0[] = {
  143200. 1,
  143201. 0,
  143202. 2,
  143203. };
  143204. static long _vq_lengthlist__16u2_p5_0[] = {
  143205. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  143206. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  143207. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  143208. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  143209. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  143210. 10,
  143211. };
  143212. static float _vq_quantthresh__16u2_p5_0[] = {
  143213. -5.5, 5.5,
  143214. };
  143215. static long _vq_quantmap__16u2_p5_0[] = {
  143216. 1, 0, 2,
  143217. };
  143218. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  143219. _vq_quantthresh__16u2_p5_0,
  143220. _vq_quantmap__16u2_p5_0,
  143221. 3,
  143222. 3
  143223. };
  143224. static static_codebook _16u2_p5_0 = {
  143225. 4, 81,
  143226. _vq_lengthlist__16u2_p5_0,
  143227. 1, -529137664, 1618345984, 2, 0,
  143228. _vq_quantlist__16u2_p5_0,
  143229. NULL,
  143230. &_vq_auxt__16u2_p5_0,
  143231. NULL,
  143232. 0
  143233. };
  143234. static long _vq_quantlist__16u2_p5_1[] = {
  143235. 5,
  143236. 4,
  143237. 6,
  143238. 3,
  143239. 7,
  143240. 2,
  143241. 8,
  143242. 1,
  143243. 9,
  143244. 0,
  143245. 10,
  143246. };
  143247. static long _vq_lengthlist__16u2_p5_1[] = {
  143248. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  143249. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  143250. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143251. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143252. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143253. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143254. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143255. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143256. };
  143257. static float _vq_quantthresh__16u2_p5_1[] = {
  143258. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143259. 3.5, 4.5,
  143260. };
  143261. static long _vq_quantmap__16u2_p5_1[] = {
  143262. 9, 7, 5, 3, 1, 0, 2, 4,
  143263. 6, 8, 10,
  143264. };
  143265. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  143266. _vq_quantthresh__16u2_p5_1,
  143267. _vq_quantmap__16u2_p5_1,
  143268. 11,
  143269. 11
  143270. };
  143271. static static_codebook _16u2_p5_1 = {
  143272. 2, 121,
  143273. _vq_lengthlist__16u2_p5_1,
  143274. 1, -531365888, 1611661312, 4, 0,
  143275. _vq_quantlist__16u2_p5_1,
  143276. NULL,
  143277. &_vq_auxt__16u2_p5_1,
  143278. NULL,
  143279. 0
  143280. };
  143281. static long _vq_quantlist__16u2_p6_0[] = {
  143282. 6,
  143283. 5,
  143284. 7,
  143285. 4,
  143286. 8,
  143287. 3,
  143288. 9,
  143289. 2,
  143290. 10,
  143291. 1,
  143292. 11,
  143293. 0,
  143294. 12,
  143295. };
  143296. static long _vq_lengthlist__16u2_p6_0[] = {
  143297. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  143298. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  143299. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  143300. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  143301. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  143302. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  143303. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  143304. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  143305. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  143306. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  143307. 12,13,13,14,14,14,14,15,15,
  143308. };
  143309. static float _vq_quantthresh__16u2_p6_0[] = {
  143310. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143311. 12.5, 17.5, 22.5, 27.5,
  143312. };
  143313. static long _vq_quantmap__16u2_p6_0[] = {
  143314. 11, 9, 7, 5, 3, 1, 0, 2,
  143315. 4, 6, 8, 10, 12,
  143316. };
  143317. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  143318. _vq_quantthresh__16u2_p6_0,
  143319. _vq_quantmap__16u2_p6_0,
  143320. 13,
  143321. 13
  143322. };
  143323. static static_codebook _16u2_p6_0 = {
  143324. 2, 169,
  143325. _vq_lengthlist__16u2_p6_0,
  143326. 1, -526516224, 1616117760, 4, 0,
  143327. _vq_quantlist__16u2_p6_0,
  143328. NULL,
  143329. &_vq_auxt__16u2_p6_0,
  143330. NULL,
  143331. 0
  143332. };
  143333. static long _vq_quantlist__16u2_p6_1[] = {
  143334. 2,
  143335. 1,
  143336. 3,
  143337. 0,
  143338. 4,
  143339. };
  143340. static long _vq_lengthlist__16u2_p6_1[] = {
  143341. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  143342. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  143343. };
  143344. static float _vq_quantthresh__16u2_p6_1[] = {
  143345. -1.5, -0.5, 0.5, 1.5,
  143346. };
  143347. static long _vq_quantmap__16u2_p6_1[] = {
  143348. 3, 1, 0, 2, 4,
  143349. };
  143350. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  143351. _vq_quantthresh__16u2_p6_1,
  143352. _vq_quantmap__16u2_p6_1,
  143353. 5,
  143354. 5
  143355. };
  143356. static static_codebook _16u2_p6_1 = {
  143357. 2, 25,
  143358. _vq_lengthlist__16u2_p6_1,
  143359. 1, -533725184, 1611661312, 3, 0,
  143360. _vq_quantlist__16u2_p6_1,
  143361. NULL,
  143362. &_vq_auxt__16u2_p6_1,
  143363. NULL,
  143364. 0
  143365. };
  143366. static long _vq_quantlist__16u2_p7_0[] = {
  143367. 6,
  143368. 5,
  143369. 7,
  143370. 4,
  143371. 8,
  143372. 3,
  143373. 9,
  143374. 2,
  143375. 10,
  143376. 1,
  143377. 11,
  143378. 0,
  143379. 12,
  143380. };
  143381. static long _vq_lengthlist__16u2_p7_0[] = {
  143382. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  143383. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  143384. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  143385. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  143386. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  143387. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  143388. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  143389. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  143390. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  143391. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  143392. 12,13,13,13,14,14,14,15,14,
  143393. };
  143394. static float _vq_quantthresh__16u2_p7_0[] = {
  143395. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  143396. 27.5, 38.5, 49.5, 60.5,
  143397. };
  143398. static long _vq_quantmap__16u2_p7_0[] = {
  143399. 11, 9, 7, 5, 3, 1, 0, 2,
  143400. 4, 6, 8, 10, 12,
  143401. };
  143402. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  143403. _vq_quantthresh__16u2_p7_0,
  143404. _vq_quantmap__16u2_p7_0,
  143405. 13,
  143406. 13
  143407. };
  143408. static static_codebook _16u2_p7_0 = {
  143409. 2, 169,
  143410. _vq_lengthlist__16u2_p7_0,
  143411. 1, -523206656, 1618345984, 4, 0,
  143412. _vq_quantlist__16u2_p7_0,
  143413. NULL,
  143414. &_vq_auxt__16u2_p7_0,
  143415. NULL,
  143416. 0
  143417. };
  143418. static long _vq_quantlist__16u2_p7_1[] = {
  143419. 5,
  143420. 4,
  143421. 6,
  143422. 3,
  143423. 7,
  143424. 2,
  143425. 8,
  143426. 1,
  143427. 9,
  143428. 0,
  143429. 10,
  143430. };
  143431. static long _vq_lengthlist__16u2_p7_1[] = {
  143432. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  143433. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  143434. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  143435. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  143436. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  143437. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  143438. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  143439. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143440. };
  143441. static float _vq_quantthresh__16u2_p7_1[] = {
  143442. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143443. 3.5, 4.5,
  143444. };
  143445. static long _vq_quantmap__16u2_p7_1[] = {
  143446. 9, 7, 5, 3, 1, 0, 2, 4,
  143447. 6, 8, 10,
  143448. };
  143449. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  143450. _vq_quantthresh__16u2_p7_1,
  143451. _vq_quantmap__16u2_p7_1,
  143452. 11,
  143453. 11
  143454. };
  143455. static static_codebook _16u2_p7_1 = {
  143456. 2, 121,
  143457. _vq_lengthlist__16u2_p7_1,
  143458. 1, -531365888, 1611661312, 4, 0,
  143459. _vq_quantlist__16u2_p7_1,
  143460. NULL,
  143461. &_vq_auxt__16u2_p7_1,
  143462. NULL,
  143463. 0
  143464. };
  143465. static long _vq_quantlist__16u2_p8_0[] = {
  143466. 7,
  143467. 6,
  143468. 8,
  143469. 5,
  143470. 9,
  143471. 4,
  143472. 10,
  143473. 3,
  143474. 11,
  143475. 2,
  143476. 12,
  143477. 1,
  143478. 13,
  143479. 0,
  143480. 14,
  143481. };
  143482. static long _vq_lengthlist__16u2_p8_0[] = {
  143483. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  143484. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  143485. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  143486. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  143487. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  143488. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  143489. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  143490. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  143491. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  143492. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  143493. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  143494. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  143495. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  143496. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  143497. 14,
  143498. };
  143499. static float _vq_quantthresh__16u2_p8_0[] = {
  143500. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143501. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143502. };
  143503. static long _vq_quantmap__16u2_p8_0[] = {
  143504. 13, 11, 9, 7, 5, 3, 1, 0,
  143505. 2, 4, 6, 8, 10, 12, 14,
  143506. };
  143507. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  143508. _vq_quantthresh__16u2_p8_0,
  143509. _vq_quantmap__16u2_p8_0,
  143510. 15,
  143511. 15
  143512. };
  143513. static static_codebook _16u2_p8_0 = {
  143514. 2, 225,
  143515. _vq_lengthlist__16u2_p8_0,
  143516. 1, -520986624, 1620377600, 4, 0,
  143517. _vq_quantlist__16u2_p8_0,
  143518. NULL,
  143519. &_vq_auxt__16u2_p8_0,
  143520. NULL,
  143521. 0
  143522. };
  143523. static long _vq_quantlist__16u2_p8_1[] = {
  143524. 10,
  143525. 9,
  143526. 11,
  143527. 8,
  143528. 12,
  143529. 7,
  143530. 13,
  143531. 6,
  143532. 14,
  143533. 5,
  143534. 15,
  143535. 4,
  143536. 16,
  143537. 3,
  143538. 17,
  143539. 2,
  143540. 18,
  143541. 1,
  143542. 19,
  143543. 0,
  143544. 20,
  143545. };
  143546. static long _vq_lengthlist__16u2_p8_1[] = {
  143547. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  143548. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  143549. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  143550. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  143551. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  143552. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  143553. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  143554. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  143555. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  143556. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  143557. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  143558. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  143559. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  143560. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  143561. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  143562. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  143563. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  143564. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  143565. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  143566. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  143567. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  143568. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  143569. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  143570. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  143571. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  143572. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  143573. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  143574. 11,11,10,11,11,11,10,11,11,
  143575. };
  143576. static float _vq_quantthresh__16u2_p8_1[] = {
  143577. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143578. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143579. 6.5, 7.5, 8.5, 9.5,
  143580. };
  143581. static long _vq_quantmap__16u2_p8_1[] = {
  143582. 19, 17, 15, 13, 11, 9, 7, 5,
  143583. 3, 1, 0, 2, 4, 6, 8, 10,
  143584. 12, 14, 16, 18, 20,
  143585. };
  143586. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  143587. _vq_quantthresh__16u2_p8_1,
  143588. _vq_quantmap__16u2_p8_1,
  143589. 21,
  143590. 21
  143591. };
  143592. static static_codebook _16u2_p8_1 = {
  143593. 2, 441,
  143594. _vq_lengthlist__16u2_p8_1,
  143595. 1, -529268736, 1611661312, 5, 0,
  143596. _vq_quantlist__16u2_p8_1,
  143597. NULL,
  143598. &_vq_auxt__16u2_p8_1,
  143599. NULL,
  143600. 0
  143601. };
  143602. static long _vq_quantlist__16u2_p9_0[] = {
  143603. 5586,
  143604. 4655,
  143605. 6517,
  143606. 3724,
  143607. 7448,
  143608. 2793,
  143609. 8379,
  143610. 1862,
  143611. 9310,
  143612. 931,
  143613. 10241,
  143614. 0,
  143615. 11172,
  143616. 5521,
  143617. 5651,
  143618. };
  143619. static long _vq_lengthlist__16u2_p9_0[] = {
  143620. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  143621. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143622. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143623. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143624. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143625. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143626. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143627. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143628. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143629. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143630. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143631. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143632. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  143633. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  143634. 5,
  143635. };
  143636. static float _vq_quantthresh__16u2_p9_0[] = {
  143637. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  143638. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  143639. };
  143640. static long _vq_quantmap__16u2_p9_0[] = {
  143641. 11, 9, 7, 5, 3, 1, 13, 0,
  143642. 14, 2, 4, 6, 8, 10, 12,
  143643. };
  143644. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  143645. _vq_quantthresh__16u2_p9_0,
  143646. _vq_quantmap__16u2_p9_0,
  143647. 15,
  143648. 15
  143649. };
  143650. static static_codebook _16u2_p9_0 = {
  143651. 2, 225,
  143652. _vq_lengthlist__16u2_p9_0,
  143653. 1, -510275072, 1611661312, 14, 0,
  143654. _vq_quantlist__16u2_p9_0,
  143655. NULL,
  143656. &_vq_auxt__16u2_p9_0,
  143657. NULL,
  143658. 0
  143659. };
  143660. static long _vq_quantlist__16u2_p9_1[] = {
  143661. 392,
  143662. 343,
  143663. 441,
  143664. 294,
  143665. 490,
  143666. 245,
  143667. 539,
  143668. 196,
  143669. 588,
  143670. 147,
  143671. 637,
  143672. 98,
  143673. 686,
  143674. 49,
  143675. 735,
  143676. 0,
  143677. 784,
  143678. 388,
  143679. 396,
  143680. };
  143681. static long _vq_lengthlist__16u2_p9_1[] = {
  143682. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  143683. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  143684. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  143685. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  143686. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  143687. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  143688. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143689. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  143690. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  143691. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143692. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143693. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143694. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143695. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143696. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  143697. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143698. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143699. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143700. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143701. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143702. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  143703. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  143704. 11,11,11,11,11,11,11, 5, 4,
  143705. };
  143706. static float _vq_quantthresh__16u2_p9_1[] = {
  143707. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  143708. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  143709. 318.5, 367.5,
  143710. };
  143711. static long _vq_quantmap__16u2_p9_1[] = {
  143712. 15, 13, 11, 9, 7, 5, 3, 1,
  143713. 17, 0, 18, 2, 4, 6, 8, 10,
  143714. 12, 14, 16,
  143715. };
  143716. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  143717. _vq_quantthresh__16u2_p9_1,
  143718. _vq_quantmap__16u2_p9_1,
  143719. 19,
  143720. 19
  143721. };
  143722. static static_codebook _16u2_p9_1 = {
  143723. 2, 361,
  143724. _vq_lengthlist__16u2_p9_1,
  143725. 1, -518488064, 1611661312, 10, 0,
  143726. _vq_quantlist__16u2_p9_1,
  143727. NULL,
  143728. &_vq_auxt__16u2_p9_1,
  143729. NULL,
  143730. 0
  143731. };
  143732. static long _vq_quantlist__16u2_p9_2[] = {
  143733. 24,
  143734. 23,
  143735. 25,
  143736. 22,
  143737. 26,
  143738. 21,
  143739. 27,
  143740. 20,
  143741. 28,
  143742. 19,
  143743. 29,
  143744. 18,
  143745. 30,
  143746. 17,
  143747. 31,
  143748. 16,
  143749. 32,
  143750. 15,
  143751. 33,
  143752. 14,
  143753. 34,
  143754. 13,
  143755. 35,
  143756. 12,
  143757. 36,
  143758. 11,
  143759. 37,
  143760. 10,
  143761. 38,
  143762. 9,
  143763. 39,
  143764. 8,
  143765. 40,
  143766. 7,
  143767. 41,
  143768. 6,
  143769. 42,
  143770. 5,
  143771. 43,
  143772. 4,
  143773. 44,
  143774. 3,
  143775. 45,
  143776. 2,
  143777. 46,
  143778. 1,
  143779. 47,
  143780. 0,
  143781. 48,
  143782. };
  143783. static long _vq_lengthlist__16u2_p9_2[] = {
  143784. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  143785. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  143786. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  143787. 11,
  143788. };
  143789. static float _vq_quantthresh__16u2_p9_2[] = {
  143790. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  143791. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  143792. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143793. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143794. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  143795. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  143796. };
  143797. static long _vq_quantmap__16u2_p9_2[] = {
  143798. 47, 45, 43, 41, 39, 37, 35, 33,
  143799. 31, 29, 27, 25, 23, 21, 19, 17,
  143800. 15, 13, 11, 9, 7, 5, 3, 1,
  143801. 0, 2, 4, 6, 8, 10, 12, 14,
  143802. 16, 18, 20, 22, 24, 26, 28, 30,
  143803. 32, 34, 36, 38, 40, 42, 44, 46,
  143804. 48,
  143805. };
  143806. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  143807. _vq_quantthresh__16u2_p9_2,
  143808. _vq_quantmap__16u2_p9_2,
  143809. 49,
  143810. 49
  143811. };
  143812. static static_codebook _16u2_p9_2 = {
  143813. 1, 49,
  143814. _vq_lengthlist__16u2_p9_2,
  143815. 1, -526909440, 1611661312, 6, 0,
  143816. _vq_quantlist__16u2_p9_2,
  143817. NULL,
  143818. &_vq_auxt__16u2_p9_2,
  143819. NULL,
  143820. 0
  143821. };
  143822. static long _vq_quantlist__8u0__p1_0[] = {
  143823. 1,
  143824. 0,
  143825. 2,
  143826. };
  143827. static long _vq_lengthlist__8u0__p1_0[] = {
  143828. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  143829. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  143830. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  143831. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  143832. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  143833. 11,
  143834. };
  143835. static float _vq_quantthresh__8u0__p1_0[] = {
  143836. -0.5, 0.5,
  143837. };
  143838. static long _vq_quantmap__8u0__p1_0[] = {
  143839. 1, 0, 2,
  143840. };
  143841. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  143842. _vq_quantthresh__8u0__p1_0,
  143843. _vq_quantmap__8u0__p1_0,
  143844. 3,
  143845. 3
  143846. };
  143847. static static_codebook _8u0__p1_0 = {
  143848. 4, 81,
  143849. _vq_lengthlist__8u0__p1_0,
  143850. 1, -535822336, 1611661312, 2, 0,
  143851. _vq_quantlist__8u0__p1_0,
  143852. NULL,
  143853. &_vq_auxt__8u0__p1_0,
  143854. NULL,
  143855. 0
  143856. };
  143857. static long _vq_quantlist__8u0__p2_0[] = {
  143858. 1,
  143859. 0,
  143860. 2,
  143861. };
  143862. static long _vq_lengthlist__8u0__p2_0[] = {
  143863. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  143864. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  143865. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  143866. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  143867. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  143868. 8,
  143869. };
  143870. static float _vq_quantthresh__8u0__p2_0[] = {
  143871. -0.5, 0.5,
  143872. };
  143873. static long _vq_quantmap__8u0__p2_0[] = {
  143874. 1, 0, 2,
  143875. };
  143876. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  143877. _vq_quantthresh__8u0__p2_0,
  143878. _vq_quantmap__8u0__p2_0,
  143879. 3,
  143880. 3
  143881. };
  143882. static static_codebook _8u0__p2_0 = {
  143883. 4, 81,
  143884. _vq_lengthlist__8u0__p2_0,
  143885. 1, -535822336, 1611661312, 2, 0,
  143886. _vq_quantlist__8u0__p2_0,
  143887. NULL,
  143888. &_vq_auxt__8u0__p2_0,
  143889. NULL,
  143890. 0
  143891. };
  143892. static long _vq_quantlist__8u0__p3_0[] = {
  143893. 2,
  143894. 1,
  143895. 3,
  143896. 0,
  143897. 4,
  143898. };
  143899. static long _vq_lengthlist__8u0__p3_0[] = {
  143900. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  143901. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  143902. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  143903. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  143904. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  143905. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  143906. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  143907. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  143908. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  143909. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  143910. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  143911. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  143912. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  143913. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  143914. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  143915. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  143916. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  143917. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  143918. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  143919. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  143920. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  143921. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  143922. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  143923. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  143924. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  143925. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  143926. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  143927. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  143928. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  143929. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  143930. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  143931. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  143932. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  143933. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  143934. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  143935. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  143936. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  143937. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  143938. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  143939. 16,
  143940. };
  143941. static float _vq_quantthresh__8u0__p3_0[] = {
  143942. -1.5, -0.5, 0.5, 1.5,
  143943. };
  143944. static long _vq_quantmap__8u0__p3_0[] = {
  143945. 3, 1, 0, 2, 4,
  143946. };
  143947. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  143948. _vq_quantthresh__8u0__p3_0,
  143949. _vq_quantmap__8u0__p3_0,
  143950. 5,
  143951. 5
  143952. };
  143953. static static_codebook _8u0__p3_0 = {
  143954. 4, 625,
  143955. _vq_lengthlist__8u0__p3_0,
  143956. 1, -533725184, 1611661312, 3, 0,
  143957. _vq_quantlist__8u0__p3_0,
  143958. NULL,
  143959. &_vq_auxt__8u0__p3_0,
  143960. NULL,
  143961. 0
  143962. };
  143963. static long _vq_quantlist__8u0__p4_0[] = {
  143964. 2,
  143965. 1,
  143966. 3,
  143967. 0,
  143968. 4,
  143969. };
  143970. static long _vq_lengthlist__8u0__p4_0[] = {
  143971. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  143972. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  143973. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  143974. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  143975. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  143976. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  143977. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  143978. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  143979. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  143980. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  143981. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  143982. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  143983. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  143984. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  143985. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  143986. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  143987. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  143988. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  143989. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  143990. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  143991. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  143992. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  143993. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  143994. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  143995. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  143996. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  143997. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  143998. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  143999. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144000. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144001. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144002. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144003. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144004. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144005. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144006. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144007. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144008. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144009. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144010. 12,
  144011. };
  144012. static float _vq_quantthresh__8u0__p4_0[] = {
  144013. -1.5, -0.5, 0.5, 1.5,
  144014. };
  144015. static long _vq_quantmap__8u0__p4_0[] = {
  144016. 3, 1, 0, 2, 4,
  144017. };
  144018. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144019. _vq_quantthresh__8u0__p4_0,
  144020. _vq_quantmap__8u0__p4_0,
  144021. 5,
  144022. 5
  144023. };
  144024. static static_codebook _8u0__p4_0 = {
  144025. 4, 625,
  144026. _vq_lengthlist__8u0__p4_0,
  144027. 1, -533725184, 1611661312, 3, 0,
  144028. _vq_quantlist__8u0__p4_0,
  144029. NULL,
  144030. &_vq_auxt__8u0__p4_0,
  144031. NULL,
  144032. 0
  144033. };
  144034. static long _vq_quantlist__8u0__p5_0[] = {
  144035. 4,
  144036. 3,
  144037. 5,
  144038. 2,
  144039. 6,
  144040. 1,
  144041. 7,
  144042. 0,
  144043. 8,
  144044. };
  144045. static long _vq_lengthlist__8u0__p5_0[] = {
  144046. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144047. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144048. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144049. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144050. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144051. 12,
  144052. };
  144053. static float _vq_quantthresh__8u0__p5_0[] = {
  144054. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144055. };
  144056. static long _vq_quantmap__8u0__p5_0[] = {
  144057. 7, 5, 3, 1, 0, 2, 4, 6,
  144058. 8,
  144059. };
  144060. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144061. _vq_quantthresh__8u0__p5_0,
  144062. _vq_quantmap__8u0__p5_0,
  144063. 9,
  144064. 9
  144065. };
  144066. static static_codebook _8u0__p5_0 = {
  144067. 2, 81,
  144068. _vq_lengthlist__8u0__p5_0,
  144069. 1, -531628032, 1611661312, 4, 0,
  144070. _vq_quantlist__8u0__p5_0,
  144071. NULL,
  144072. &_vq_auxt__8u0__p5_0,
  144073. NULL,
  144074. 0
  144075. };
  144076. static long _vq_quantlist__8u0__p6_0[] = {
  144077. 6,
  144078. 5,
  144079. 7,
  144080. 4,
  144081. 8,
  144082. 3,
  144083. 9,
  144084. 2,
  144085. 10,
  144086. 1,
  144087. 11,
  144088. 0,
  144089. 12,
  144090. };
  144091. static long _vq_lengthlist__8u0__p6_0[] = {
  144092. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144093. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144094. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144095. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144096. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144097. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144098. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144099. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144100. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144101. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144102. 16, 0,15, 0,17, 0, 0, 0, 0,
  144103. };
  144104. static float _vq_quantthresh__8u0__p6_0[] = {
  144105. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144106. 12.5, 17.5, 22.5, 27.5,
  144107. };
  144108. static long _vq_quantmap__8u0__p6_0[] = {
  144109. 11, 9, 7, 5, 3, 1, 0, 2,
  144110. 4, 6, 8, 10, 12,
  144111. };
  144112. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144113. _vq_quantthresh__8u0__p6_0,
  144114. _vq_quantmap__8u0__p6_0,
  144115. 13,
  144116. 13
  144117. };
  144118. static static_codebook _8u0__p6_0 = {
  144119. 2, 169,
  144120. _vq_lengthlist__8u0__p6_0,
  144121. 1, -526516224, 1616117760, 4, 0,
  144122. _vq_quantlist__8u0__p6_0,
  144123. NULL,
  144124. &_vq_auxt__8u0__p6_0,
  144125. NULL,
  144126. 0
  144127. };
  144128. static long _vq_quantlist__8u0__p6_1[] = {
  144129. 2,
  144130. 1,
  144131. 3,
  144132. 0,
  144133. 4,
  144134. };
  144135. static long _vq_lengthlist__8u0__p6_1[] = {
  144136. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  144137. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  144138. };
  144139. static float _vq_quantthresh__8u0__p6_1[] = {
  144140. -1.5, -0.5, 0.5, 1.5,
  144141. };
  144142. static long _vq_quantmap__8u0__p6_1[] = {
  144143. 3, 1, 0, 2, 4,
  144144. };
  144145. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  144146. _vq_quantthresh__8u0__p6_1,
  144147. _vq_quantmap__8u0__p6_1,
  144148. 5,
  144149. 5
  144150. };
  144151. static static_codebook _8u0__p6_1 = {
  144152. 2, 25,
  144153. _vq_lengthlist__8u0__p6_1,
  144154. 1, -533725184, 1611661312, 3, 0,
  144155. _vq_quantlist__8u0__p6_1,
  144156. NULL,
  144157. &_vq_auxt__8u0__p6_1,
  144158. NULL,
  144159. 0
  144160. };
  144161. static long _vq_quantlist__8u0__p7_0[] = {
  144162. 1,
  144163. 0,
  144164. 2,
  144165. };
  144166. static long _vq_lengthlist__8u0__p7_0[] = {
  144167. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144168. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144169. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144170. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144171. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144172. 7,
  144173. };
  144174. static float _vq_quantthresh__8u0__p7_0[] = {
  144175. -157.5, 157.5,
  144176. };
  144177. static long _vq_quantmap__8u0__p7_0[] = {
  144178. 1, 0, 2,
  144179. };
  144180. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  144181. _vq_quantthresh__8u0__p7_0,
  144182. _vq_quantmap__8u0__p7_0,
  144183. 3,
  144184. 3
  144185. };
  144186. static static_codebook _8u0__p7_0 = {
  144187. 4, 81,
  144188. _vq_lengthlist__8u0__p7_0,
  144189. 1, -518803456, 1628680192, 2, 0,
  144190. _vq_quantlist__8u0__p7_0,
  144191. NULL,
  144192. &_vq_auxt__8u0__p7_0,
  144193. NULL,
  144194. 0
  144195. };
  144196. static long _vq_quantlist__8u0__p7_1[] = {
  144197. 7,
  144198. 6,
  144199. 8,
  144200. 5,
  144201. 9,
  144202. 4,
  144203. 10,
  144204. 3,
  144205. 11,
  144206. 2,
  144207. 12,
  144208. 1,
  144209. 13,
  144210. 0,
  144211. 14,
  144212. };
  144213. static long _vq_lengthlist__8u0__p7_1[] = {
  144214. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  144215. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  144216. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  144217. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  144218. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  144219. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  144220. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144221. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144222. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144223. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144224. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144225. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144226. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  144227. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144228. 10,
  144229. };
  144230. static float _vq_quantthresh__8u0__p7_1[] = {
  144231. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144232. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144233. };
  144234. static long _vq_quantmap__8u0__p7_1[] = {
  144235. 13, 11, 9, 7, 5, 3, 1, 0,
  144236. 2, 4, 6, 8, 10, 12, 14,
  144237. };
  144238. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  144239. _vq_quantthresh__8u0__p7_1,
  144240. _vq_quantmap__8u0__p7_1,
  144241. 15,
  144242. 15
  144243. };
  144244. static static_codebook _8u0__p7_1 = {
  144245. 2, 225,
  144246. _vq_lengthlist__8u0__p7_1,
  144247. 1, -520986624, 1620377600, 4, 0,
  144248. _vq_quantlist__8u0__p7_1,
  144249. NULL,
  144250. &_vq_auxt__8u0__p7_1,
  144251. NULL,
  144252. 0
  144253. };
  144254. static long _vq_quantlist__8u0__p7_2[] = {
  144255. 10,
  144256. 9,
  144257. 11,
  144258. 8,
  144259. 12,
  144260. 7,
  144261. 13,
  144262. 6,
  144263. 14,
  144264. 5,
  144265. 15,
  144266. 4,
  144267. 16,
  144268. 3,
  144269. 17,
  144270. 2,
  144271. 18,
  144272. 1,
  144273. 19,
  144274. 0,
  144275. 20,
  144276. };
  144277. static long _vq_lengthlist__8u0__p7_2[] = {
  144278. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  144279. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  144280. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  144281. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  144282. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  144283. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  144284. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  144285. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  144286. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  144287. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  144288. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  144289. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  144290. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  144291. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  144292. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  144293. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  144294. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  144295. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  144296. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  144297. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  144298. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  144299. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  144300. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  144301. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  144302. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  144303. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  144304. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  144305. 11,12,11,11,11,10,10,11,11,
  144306. };
  144307. static float _vq_quantthresh__8u0__p7_2[] = {
  144308. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144309. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144310. 6.5, 7.5, 8.5, 9.5,
  144311. };
  144312. static long _vq_quantmap__8u0__p7_2[] = {
  144313. 19, 17, 15, 13, 11, 9, 7, 5,
  144314. 3, 1, 0, 2, 4, 6, 8, 10,
  144315. 12, 14, 16, 18, 20,
  144316. };
  144317. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  144318. _vq_quantthresh__8u0__p7_2,
  144319. _vq_quantmap__8u0__p7_2,
  144320. 21,
  144321. 21
  144322. };
  144323. static static_codebook _8u0__p7_2 = {
  144324. 2, 441,
  144325. _vq_lengthlist__8u0__p7_2,
  144326. 1, -529268736, 1611661312, 5, 0,
  144327. _vq_quantlist__8u0__p7_2,
  144328. NULL,
  144329. &_vq_auxt__8u0__p7_2,
  144330. NULL,
  144331. 0
  144332. };
  144333. static long _huff_lengthlist__8u0__single[] = {
  144334. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  144335. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  144336. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  144337. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  144338. };
  144339. static static_codebook _huff_book__8u0__single = {
  144340. 2, 64,
  144341. _huff_lengthlist__8u0__single,
  144342. 0, 0, 0, 0, 0,
  144343. NULL,
  144344. NULL,
  144345. NULL,
  144346. NULL,
  144347. 0
  144348. };
  144349. static long _vq_quantlist__8u1__p1_0[] = {
  144350. 1,
  144351. 0,
  144352. 2,
  144353. };
  144354. static long _vq_lengthlist__8u1__p1_0[] = {
  144355. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  144356. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  144357. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  144358. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  144359. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  144360. 10,
  144361. };
  144362. static float _vq_quantthresh__8u1__p1_0[] = {
  144363. -0.5, 0.5,
  144364. };
  144365. static long _vq_quantmap__8u1__p1_0[] = {
  144366. 1, 0, 2,
  144367. };
  144368. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  144369. _vq_quantthresh__8u1__p1_0,
  144370. _vq_quantmap__8u1__p1_0,
  144371. 3,
  144372. 3
  144373. };
  144374. static static_codebook _8u1__p1_0 = {
  144375. 4, 81,
  144376. _vq_lengthlist__8u1__p1_0,
  144377. 1, -535822336, 1611661312, 2, 0,
  144378. _vq_quantlist__8u1__p1_0,
  144379. NULL,
  144380. &_vq_auxt__8u1__p1_0,
  144381. NULL,
  144382. 0
  144383. };
  144384. static long _vq_quantlist__8u1__p2_0[] = {
  144385. 1,
  144386. 0,
  144387. 2,
  144388. };
  144389. static long _vq_lengthlist__8u1__p2_0[] = {
  144390. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  144391. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  144392. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  144393. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  144394. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  144395. 7,
  144396. };
  144397. static float _vq_quantthresh__8u1__p2_0[] = {
  144398. -0.5, 0.5,
  144399. };
  144400. static long _vq_quantmap__8u1__p2_0[] = {
  144401. 1, 0, 2,
  144402. };
  144403. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  144404. _vq_quantthresh__8u1__p2_0,
  144405. _vq_quantmap__8u1__p2_0,
  144406. 3,
  144407. 3
  144408. };
  144409. static static_codebook _8u1__p2_0 = {
  144410. 4, 81,
  144411. _vq_lengthlist__8u1__p2_0,
  144412. 1, -535822336, 1611661312, 2, 0,
  144413. _vq_quantlist__8u1__p2_0,
  144414. NULL,
  144415. &_vq_auxt__8u1__p2_0,
  144416. NULL,
  144417. 0
  144418. };
  144419. static long _vq_quantlist__8u1__p3_0[] = {
  144420. 2,
  144421. 1,
  144422. 3,
  144423. 0,
  144424. 4,
  144425. };
  144426. static long _vq_lengthlist__8u1__p3_0[] = {
  144427. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144428. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144429. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  144430. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  144431. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  144432. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  144433. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  144434. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  144435. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  144436. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  144437. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  144438. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  144439. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  144440. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  144441. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  144442. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  144443. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  144444. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  144445. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  144446. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  144447. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  144448. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  144449. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  144450. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  144451. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  144452. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  144453. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  144454. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  144455. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  144456. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  144457. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  144458. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  144459. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  144460. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  144461. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  144462. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  144463. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  144464. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  144465. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  144466. 16,
  144467. };
  144468. static float _vq_quantthresh__8u1__p3_0[] = {
  144469. -1.5, -0.5, 0.5, 1.5,
  144470. };
  144471. static long _vq_quantmap__8u1__p3_0[] = {
  144472. 3, 1, 0, 2, 4,
  144473. };
  144474. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  144475. _vq_quantthresh__8u1__p3_0,
  144476. _vq_quantmap__8u1__p3_0,
  144477. 5,
  144478. 5
  144479. };
  144480. static static_codebook _8u1__p3_0 = {
  144481. 4, 625,
  144482. _vq_lengthlist__8u1__p3_0,
  144483. 1, -533725184, 1611661312, 3, 0,
  144484. _vq_quantlist__8u1__p3_0,
  144485. NULL,
  144486. &_vq_auxt__8u1__p3_0,
  144487. NULL,
  144488. 0
  144489. };
  144490. static long _vq_quantlist__8u1__p4_0[] = {
  144491. 2,
  144492. 1,
  144493. 3,
  144494. 0,
  144495. 4,
  144496. };
  144497. static long _vq_lengthlist__8u1__p4_0[] = {
  144498. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  144499. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  144500. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  144501. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  144502. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  144503. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  144504. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  144505. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  144506. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  144507. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  144508. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  144509. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  144510. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  144511. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  144512. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  144513. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  144514. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  144515. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144516. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  144517. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  144518. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  144519. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  144520. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  144521. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  144522. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  144523. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  144524. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  144525. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  144526. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  144527. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  144528. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  144529. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  144530. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  144531. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  144532. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  144533. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  144534. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  144535. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  144536. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  144537. 10,
  144538. };
  144539. static float _vq_quantthresh__8u1__p4_0[] = {
  144540. -1.5, -0.5, 0.5, 1.5,
  144541. };
  144542. static long _vq_quantmap__8u1__p4_0[] = {
  144543. 3, 1, 0, 2, 4,
  144544. };
  144545. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  144546. _vq_quantthresh__8u1__p4_0,
  144547. _vq_quantmap__8u1__p4_0,
  144548. 5,
  144549. 5
  144550. };
  144551. static static_codebook _8u1__p4_0 = {
  144552. 4, 625,
  144553. _vq_lengthlist__8u1__p4_0,
  144554. 1, -533725184, 1611661312, 3, 0,
  144555. _vq_quantlist__8u1__p4_0,
  144556. NULL,
  144557. &_vq_auxt__8u1__p4_0,
  144558. NULL,
  144559. 0
  144560. };
  144561. static long _vq_quantlist__8u1__p5_0[] = {
  144562. 4,
  144563. 3,
  144564. 5,
  144565. 2,
  144566. 6,
  144567. 1,
  144568. 7,
  144569. 0,
  144570. 8,
  144571. };
  144572. static long _vq_lengthlist__8u1__p5_0[] = {
  144573. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  144574. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  144575. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  144576. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  144577. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  144578. 13,
  144579. };
  144580. static float _vq_quantthresh__8u1__p5_0[] = {
  144581. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144582. };
  144583. static long _vq_quantmap__8u1__p5_0[] = {
  144584. 7, 5, 3, 1, 0, 2, 4, 6,
  144585. 8,
  144586. };
  144587. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  144588. _vq_quantthresh__8u1__p5_0,
  144589. _vq_quantmap__8u1__p5_0,
  144590. 9,
  144591. 9
  144592. };
  144593. static static_codebook _8u1__p5_0 = {
  144594. 2, 81,
  144595. _vq_lengthlist__8u1__p5_0,
  144596. 1, -531628032, 1611661312, 4, 0,
  144597. _vq_quantlist__8u1__p5_0,
  144598. NULL,
  144599. &_vq_auxt__8u1__p5_0,
  144600. NULL,
  144601. 0
  144602. };
  144603. static long _vq_quantlist__8u1__p6_0[] = {
  144604. 4,
  144605. 3,
  144606. 5,
  144607. 2,
  144608. 6,
  144609. 1,
  144610. 7,
  144611. 0,
  144612. 8,
  144613. };
  144614. static long _vq_lengthlist__8u1__p6_0[] = {
  144615. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  144616. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  144617. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  144618. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  144619. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  144620. 10,
  144621. };
  144622. static float _vq_quantthresh__8u1__p6_0[] = {
  144623. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144624. };
  144625. static long _vq_quantmap__8u1__p6_0[] = {
  144626. 7, 5, 3, 1, 0, 2, 4, 6,
  144627. 8,
  144628. };
  144629. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  144630. _vq_quantthresh__8u1__p6_0,
  144631. _vq_quantmap__8u1__p6_0,
  144632. 9,
  144633. 9
  144634. };
  144635. static static_codebook _8u1__p6_0 = {
  144636. 2, 81,
  144637. _vq_lengthlist__8u1__p6_0,
  144638. 1, -531628032, 1611661312, 4, 0,
  144639. _vq_quantlist__8u1__p6_0,
  144640. NULL,
  144641. &_vq_auxt__8u1__p6_0,
  144642. NULL,
  144643. 0
  144644. };
  144645. static long _vq_quantlist__8u1__p7_0[] = {
  144646. 1,
  144647. 0,
  144648. 2,
  144649. };
  144650. static long _vq_lengthlist__8u1__p7_0[] = {
  144651. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  144652. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  144653. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  144654. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  144655. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  144656. 11,
  144657. };
  144658. static float _vq_quantthresh__8u1__p7_0[] = {
  144659. -5.5, 5.5,
  144660. };
  144661. static long _vq_quantmap__8u1__p7_0[] = {
  144662. 1, 0, 2,
  144663. };
  144664. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  144665. _vq_quantthresh__8u1__p7_0,
  144666. _vq_quantmap__8u1__p7_0,
  144667. 3,
  144668. 3
  144669. };
  144670. static static_codebook _8u1__p7_0 = {
  144671. 4, 81,
  144672. _vq_lengthlist__8u1__p7_0,
  144673. 1, -529137664, 1618345984, 2, 0,
  144674. _vq_quantlist__8u1__p7_0,
  144675. NULL,
  144676. &_vq_auxt__8u1__p7_0,
  144677. NULL,
  144678. 0
  144679. };
  144680. static long _vq_quantlist__8u1__p7_1[] = {
  144681. 5,
  144682. 4,
  144683. 6,
  144684. 3,
  144685. 7,
  144686. 2,
  144687. 8,
  144688. 1,
  144689. 9,
  144690. 0,
  144691. 10,
  144692. };
  144693. static long _vq_lengthlist__8u1__p7_1[] = {
  144694. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  144695. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  144696. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144697. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  144698. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  144699. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  144700. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  144701. 9, 9, 9, 9, 9,10,10,10,10,
  144702. };
  144703. static float _vq_quantthresh__8u1__p7_1[] = {
  144704. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144705. 3.5, 4.5,
  144706. };
  144707. static long _vq_quantmap__8u1__p7_1[] = {
  144708. 9, 7, 5, 3, 1, 0, 2, 4,
  144709. 6, 8, 10,
  144710. };
  144711. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  144712. _vq_quantthresh__8u1__p7_1,
  144713. _vq_quantmap__8u1__p7_1,
  144714. 11,
  144715. 11
  144716. };
  144717. static static_codebook _8u1__p7_1 = {
  144718. 2, 121,
  144719. _vq_lengthlist__8u1__p7_1,
  144720. 1, -531365888, 1611661312, 4, 0,
  144721. _vq_quantlist__8u1__p7_1,
  144722. NULL,
  144723. &_vq_auxt__8u1__p7_1,
  144724. NULL,
  144725. 0
  144726. };
  144727. static long _vq_quantlist__8u1__p8_0[] = {
  144728. 5,
  144729. 4,
  144730. 6,
  144731. 3,
  144732. 7,
  144733. 2,
  144734. 8,
  144735. 1,
  144736. 9,
  144737. 0,
  144738. 10,
  144739. };
  144740. static long _vq_lengthlist__8u1__p8_0[] = {
  144741. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  144742. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  144743. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  144744. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  144745. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  144746. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  144747. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  144748. 12,13,13,14,14,15,15,15,15,
  144749. };
  144750. static float _vq_quantthresh__8u1__p8_0[] = {
  144751. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144752. 38.5, 49.5,
  144753. };
  144754. static long _vq_quantmap__8u1__p8_0[] = {
  144755. 9, 7, 5, 3, 1, 0, 2, 4,
  144756. 6, 8, 10,
  144757. };
  144758. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  144759. _vq_quantthresh__8u1__p8_0,
  144760. _vq_quantmap__8u1__p8_0,
  144761. 11,
  144762. 11
  144763. };
  144764. static static_codebook _8u1__p8_0 = {
  144765. 2, 121,
  144766. _vq_lengthlist__8u1__p8_0,
  144767. 1, -524582912, 1618345984, 4, 0,
  144768. _vq_quantlist__8u1__p8_0,
  144769. NULL,
  144770. &_vq_auxt__8u1__p8_0,
  144771. NULL,
  144772. 0
  144773. };
  144774. static long _vq_quantlist__8u1__p8_1[] = {
  144775. 5,
  144776. 4,
  144777. 6,
  144778. 3,
  144779. 7,
  144780. 2,
  144781. 8,
  144782. 1,
  144783. 9,
  144784. 0,
  144785. 10,
  144786. };
  144787. static long _vq_lengthlist__8u1__p8_1[] = {
  144788. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  144789. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144790. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144791. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  144792. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144793. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  144794. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  144795. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  144796. };
  144797. static float _vq_quantthresh__8u1__p8_1[] = {
  144798. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144799. 3.5, 4.5,
  144800. };
  144801. static long _vq_quantmap__8u1__p8_1[] = {
  144802. 9, 7, 5, 3, 1, 0, 2, 4,
  144803. 6, 8, 10,
  144804. };
  144805. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  144806. _vq_quantthresh__8u1__p8_1,
  144807. _vq_quantmap__8u1__p8_1,
  144808. 11,
  144809. 11
  144810. };
  144811. static static_codebook _8u1__p8_1 = {
  144812. 2, 121,
  144813. _vq_lengthlist__8u1__p8_1,
  144814. 1, -531365888, 1611661312, 4, 0,
  144815. _vq_quantlist__8u1__p8_1,
  144816. NULL,
  144817. &_vq_auxt__8u1__p8_1,
  144818. NULL,
  144819. 0
  144820. };
  144821. static long _vq_quantlist__8u1__p9_0[] = {
  144822. 7,
  144823. 6,
  144824. 8,
  144825. 5,
  144826. 9,
  144827. 4,
  144828. 10,
  144829. 3,
  144830. 11,
  144831. 2,
  144832. 12,
  144833. 1,
  144834. 13,
  144835. 0,
  144836. 14,
  144837. };
  144838. static long _vq_lengthlist__8u1__p9_0[] = {
  144839. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  144840. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  144841. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144851. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  144852. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144853. 10,
  144854. };
  144855. static float _vq_quantthresh__8u1__p9_0[] = {
  144856. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144857. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144858. };
  144859. static long _vq_quantmap__8u1__p9_0[] = {
  144860. 13, 11, 9, 7, 5, 3, 1, 0,
  144861. 2, 4, 6, 8, 10, 12, 14,
  144862. };
  144863. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  144864. _vq_quantthresh__8u1__p9_0,
  144865. _vq_quantmap__8u1__p9_0,
  144866. 15,
  144867. 15
  144868. };
  144869. static static_codebook _8u1__p9_0 = {
  144870. 2, 225,
  144871. _vq_lengthlist__8u1__p9_0,
  144872. 1, -514071552, 1627381760, 4, 0,
  144873. _vq_quantlist__8u1__p9_0,
  144874. NULL,
  144875. &_vq_auxt__8u1__p9_0,
  144876. NULL,
  144877. 0
  144878. };
  144879. static long _vq_quantlist__8u1__p9_1[] = {
  144880. 7,
  144881. 6,
  144882. 8,
  144883. 5,
  144884. 9,
  144885. 4,
  144886. 10,
  144887. 3,
  144888. 11,
  144889. 2,
  144890. 12,
  144891. 1,
  144892. 13,
  144893. 0,
  144894. 14,
  144895. };
  144896. static long _vq_lengthlist__8u1__p9_1[] = {
  144897. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  144898. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  144899. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  144900. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  144901. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  144902. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  144903. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  144904. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  144905. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  144906. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  144907. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  144908. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  144909. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  144910. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  144911. 13,
  144912. };
  144913. static float _vq_quantthresh__8u1__p9_1[] = {
  144914. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144915. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144916. };
  144917. static long _vq_quantmap__8u1__p9_1[] = {
  144918. 13, 11, 9, 7, 5, 3, 1, 0,
  144919. 2, 4, 6, 8, 10, 12, 14,
  144920. };
  144921. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  144922. _vq_quantthresh__8u1__p9_1,
  144923. _vq_quantmap__8u1__p9_1,
  144924. 15,
  144925. 15
  144926. };
  144927. static static_codebook _8u1__p9_1 = {
  144928. 2, 225,
  144929. _vq_lengthlist__8u1__p9_1,
  144930. 1, -522338304, 1620115456, 4, 0,
  144931. _vq_quantlist__8u1__p9_1,
  144932. NULL,
  144933. &_vq_auxt__8u1__p9_1,
  144934. NULL,
  144935. 0
  144936. };
  144937. static long _vq_quantlist__8u1__p9_2[] = {
  144938. 8,
  144939. 7,
  144940. 9,
  144941. 6,
  144942. 10,
  144943. 5,
  144944. 11,
  144945. 4,
  144946. 12,
  144947. 3,
  144948. 13,
  144949. 2,
  144950. 14,
  144951. 1,
  144952. 15,
  144953. 0,
  144954. 16,
  144955. };
  144956. static long _vq_lengthlist__8u1__p9_2[] = {
  144957. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144958. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  144959. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144960. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144961. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  144962. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  144963. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  144964. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  144965. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  144966. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  144967. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  144968. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  144969. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  144970. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144971. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  144972. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  144973. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144974. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144975. 10,
  144976. };
  144977. static float _vq_quantthresh__8u1__p9_2[] = {
  144978. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144979. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144980. };
  144981. static long _vq_quantmap__8u1__p9_2[] = {
  144982. 15, 13, 11, 9, 7, 5, 3, 1,
  144983. 0, 2, 4, 6, 8, 10, 12, 14,
  144984. 16,
  144985. };
  144986. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  144987. _vq_quantthresh__8u1__p9_2,
  144988. _vq_quantmap__8u1__p9_2,
  144989. 17,
  144990. 17
  144991. };
  144992. static static_codebook _8u1__p9_2 = {
  144993. 2, 289,
  144994. _vq_lengthlist__8u1__p9_2,
  144995. 1, -529530880, 1611661312, 5, 0,
  144996. _vq_quantlist__8u1__p9_2,
  144997. NULL,
  144998. &_vq_auxt__8u1__p9_2,
  144999. NULL,
  145000. 0
  145001. };
  145002. static long _huff_lengthlist__8u1__single[] = {
  145003. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145004. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145005. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145006. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145007. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145008. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145009. 13, 8, 8,15,
  145010. };
  145011. static static_codebook _huff_book__8u1__single = {
  145012. 2, 100,
  145013. _huff_lengthlist__8u1__single,
  145014. 0, 0, 0, 0, 0,
  145015. NULL,
  145016. NULL,
  145017. NULL,
  145018. NULL,
  145019. 0
  145020. };
  145021. static long _huff_lengthlist__44u0__long[] = {
  145022. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145023. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145024. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145025. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145026. };
  145027. static static_codebook _huff_book__44u0__long = {
  145028. 2, 64,
  145029. _huff_lengthlist__44u0__long,
  145030. 0, 0, 0, 0, 0,
  145031. NULL,
  145032. NULL,
  145033. NULL,
  145034. NULL,
  145035. 0
  145036. };
  145037. static long _vq_quantlist__44u0__p1_0[] = {
  145038. 1,
  145039. 0,
  145040. 2,
  145041. };
  145042. static long _vq_lengthlist__44u0__p1_0[] = {
  145043. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145044. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145045. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145046. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145047. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145048. 13,
  145049. };
  145050. static float _vq_quantthresh__44u0__p1_0[] = {
  145051. -0.5, 0.5,
  145052. };
  145053. static long _vq_quantmap__44u0__p1_0[] = {
  145054. 1, 0, 2,
  145055. };
  145056. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145057. _vq_quantthresh__44u0__p1_0,
  145058. _vq_quantmap__44u0__p1_0,
  145059. 3,
  145060. 3
  145061. };
  145062. static static_codebook _44u0__p1_0 = {
  145063. 4, 81,
  145064. _vq_lengthlist__44u0__p1_0,
  145065. 1, -535822336, 1611661312, 2, 0,
  145066. _vq_quantlist__44u0__p1_0,
  145067. NULL,
  145068. &_vq_auxt__44u0__p1_0,
  145069. NULL,
  145070. 0
  145071. };
  145072. static long _vq_quantlist__44u0__p2_0[] = {
  145073. 1,
  145074. 0,
  145075. 2,
  145076. };
  145077. static long _vq_lengthlist__44u0__p2_0[] = {
  145078. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145079. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145080. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145081. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145082. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145083. 9,
  145084. };
  145085. static float _vq_quantthresh__44u0__p2_0[] = {
  145086. -0.5, 0.5,
  145087. };
  145088. static long _vq_quantmap__44u0__p2_0[] = {
  145089. 1, 0, 2,
  145090. };
  145091. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145092. _vq_quantthresh__44u0__p2_0,
  145093. _vq_quantmap__44u0__p2_0,
  145094. 3,
  145095. 3
  145096. };
  145097. static static_codebook _44u0__p2_0 = {
  145098. 4, 81,
  145099. _vq_lengthlist__44u0__p2_0,
  145100. 1, -535822336, 1611661312, 2, 0,
  145101. _vq_quantlist__44u0__p2_0,
  145102. NULL,
  145103. &_vq_auxt__44u0__p2_0,
  145104. NULL,
  145105. 0
  145106. };
  145107. static long _vq_quantlist__44u0__p3_0[] = {
  145108. 2,
  145109. 1,
  145110. 3,
  145111. 0,
  145112. 4,
  145113. };
  145114. static long _vq_lengthlist__44u0__p3_0[] = {
  145115. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145116. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145117. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145118. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145119. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145120. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145121. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145122. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145123. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145124. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145125. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145126. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145127. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145128. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145129. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145130. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145131. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145132. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145133. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145134. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145135. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145136. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145137. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145138. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145139. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145140. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145141. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145142. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145143. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145144. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145145. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145146. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145147. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145148. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145149. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145150. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145151. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145152. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145153. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145154. 19,
  145155. };
  145156. static float _vq_quantthresh__44u0__p3_0[] = {
  145157. -1.5, -0.5, 0.5, 1.5,
  145158. };
  145159. static long _vq_quantmap__44u0__p3_0[] = {
  145160. 3, 1, 0, 2, 4,
  145161. };
  145162. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  145163. _vq_quantthresh__44u0__p3_0,
  145164. _vq_quantmap__44u0__p3_0,
  145165. 5,
  145166. 5
  145167. };
  145168. static static_codebook _44u0__p3_0 = {
  145169. 4, 625,
  145170. _vq_lengthlist__44u0__p3_0,
  145171. 1, -533725184, 1611661312, 3, 0,
  145172. _vq_quantlist__44u0__p3_0,
  145173. NULL,
  145174. &_vq_auxt__44u0__p3_0,
  145175. NULL,
  145176. 0
  145177. };
  145178. static long _vq_quantlist__44u0__p4_0[] = {
  145179. 2,
  145180. 1,
  145181. 3,
  145182. 0,
  145183. 4,
  145184. };
  145185. static long _vq_lengthlist__44u0__p4_0[] = {
  145186. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145187. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145188. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145189. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145190. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145191. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145192. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145193. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145194. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145195. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  145196. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  145197. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145198. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  145199. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  145200. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  145201. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  145202. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  145203. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  145204. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  145205. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  145206. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  145207. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  145208. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  145209. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  145210. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  145211. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  145212. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  145213. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  145214. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  145215. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  145216. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  145217. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  145218. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  145219. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  145220. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  145221. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  145222. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  145223. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  145224. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  145225. 12,
  145226. };
  145227. static float _vq_quantthresh__44u0__p4_0[] = {
  145228. -1.5, -0.5, 0.5, 1.5,
  145229. };
  145230. static long _vq_quantmap__44u0__p4_0[] = {
  145231. 3, 1, 0, 2, 4,
  145232. };
  145233. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  145234. _vq_quantthresh__44u0__p4_0,
  145235. _vq_quantmap__44u0__p4_0,
  145236. 5,
  145237. 5
  145238. };
  145239. static static_codebook _44u0__p4_0 = {
  145240. 4, 625,
  145241. _vq_lengthlist__44u0__p4_0,
  145242. 1, -533725184, 1611661312, 3, 0,
  145243. _vq_quantlist__44u0__p4_0,
  145244. NULL,
  145245. &_vq_auxt__44u0__p4_0,
  145246. NULL,
  145247. 0
  145248. };
  145249. static long _vq_quantlist__44u0__p5_0[] = {
  145250. 4,
  145251. 3,
  145252. 5,
  145253. 2,
  145254. 6,
  145255. 1,
  145256. 7,
  145257. 0,
  145258. 8,
  145259. };
  145260. static long _vq_lengthlist__44u0__p5_0[] = {
  145261. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  145262. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  145263. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  145264. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145265. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  145266. 12,
  145267. };
  145268. static float _vq_quantthresh__44u0__p5_0[] = {
  145269. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145270. };
  145271. static long _vq_quantmap__44u0__p5_0[] = {
  145272. 7, 5, 3, 1, 0, 2, 4, 6,
  145273. 8,
  145274. };
  145275. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  145276. _vq_quantthresh__44u0__p5_0,
  145277. _vq_quantmap__44u0__p5_0,
  145278. 9,
  145279. 9
  145280. };
  145281. static static_codebook _44u0__p5_0 = {
  145282. 2, 81,
  145283. _vq_lengthlist__44u0__p5_0,
  145284. 1, -531628032, 1611661312, 4, 0,
  145285. _vq_quantlist__44u0__p5_0,
  145286. NULL,
  145287. &_vq_auxt__44u0__p5_0,
  145288. NULL,
  145289. 0
  145290. };
  145291. static long _vq_quantlist__44u0__p6_0[] = {
  145292. 6,
  145293. 5,
  145294. 7,
  145295. 4,
  145296. 8,
  145297. 3,
  145298. 9,
  145299. 2,
  145300. 10,
  145301. 1,
  145302. 11,
  145303. 0,
  145304. 12,
  145305. };
  145306. static long _vq_lengthlist__44u0__p6_0[] = {
  145307. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  145308. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  145309. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145310. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  145311. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  145312. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  145313. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  145314. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  145315. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  145316. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  145317. 15,17,16,17,18,17,17,18, 0,
  145318. };
  145319. static float _vq_quantthresh__44u0__p6_0[] = {
  145320. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145321. 12.5, 17.5, 22.5, 27.5,
  145322. };
  145323. static long _vq_quantmap__44u0__p6_0[] = {
  145324. 11, 9, 7, 5, 3, 1, 0, 2,
  145325. 4, 6, 8, 10, 12,
  145326. };
  145327. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  145328. _vq_quantthresh__44u0__p6_0,
  145329. _vq_quantmap__44u0__p6_0,
  145330. 13,
  145331. 13
  145332. };
  145333. static static_codebook _44u0__p6_0 = {
  145334. 2, 169,
  145335. _vq_lengthlist__44u0__p6_0,
  145336. 1, -526516224, 1616117760, 4, 0,
  145337. _vq_quantlist__44u0__p6_0,
  145338. NULL,
  145339. &_vq_auxt__44u0__p6_0,
  145340. NULL,
  145341. 0
  145342. };
  145343. static long _vq_quantlist__44u0__p6_1[] = {
  145344. 2,
  145345. 1,
  145346. 3,
  145347. 0,
  145348. 4,
  145349. };
  145350. static long _vq_lengthlist__44u0__p6_1[] = {
  145351. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145352. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  145353. };
  145354. static float _vq_quantthresh__44u0__p6_1[] = {
  145355. -1.5, -0.5, 0.5, 1.5,
  145356. };
  145357. static long _vq_quantmap__44u0__p6_1[] = {
  145358. 3, 1, 0, 2, 4,
  145359. };
  145360. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  145361. _vq_quantthresh__44u0__p6_1,
  145362. _vq_quantmap__44u0__p6_1,
  145363. 5,
  145364. 5
  145365. };
  145366. static static_codebook _44u0__p6_1 = {
  145367. 2, 25,
  145368. _vq_lengthlist__44u0__p6_1,
  145369. 1, -533725184, 1611661312, 3, 0,
  145370. _vq_quantlist__44u0__p6_1,
  145371. NULL,
  145372. &_vq_auxt__44u0__p6_1,
  145373. NULL,
  145374. 0
  145375. };
  145376. static long _vq_quantlist__44u0__p7_0[] = {
  145377. 2,
  145378. 1,
  145379. 3,
  145380. 0,
  145381. 4,
  145382. };
  145383. static long _vq_lengthlist__44u0__p7_0[] = {
  145384. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  145385. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145387. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145388. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145390. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145391. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  145392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145393. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145394. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145395. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145396. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145397. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145398. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145399. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145400. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145401. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145402. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145403. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145404. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145405. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145406. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145407. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145408. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145409. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145410. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145411. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145412. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145413. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145414. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  145415. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145416. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145417. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145418. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145419. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145420. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145421. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145422. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145423. 10,
  145424. };
  145425. static float _vq_quantthresh__44u0__p7_0[] = {
  145426. -253.5, -84.5, 84.5, 253.5,
  145427. };
  145428. static long _vq_quantmap__44u0__p7_0[] = {
  145429. 3, 1, 0, 2, 4,
  145430. };
  145431. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  145432. _vq_quantthresh__44u0__p7_0,
  145433. _vq_quantmap__44u0__p7_0,
  145434. 5,
  145435. 5
  145436. };
  145437. static static_codebook _44u0__p7_0 = {
  145438. 4, 625,
  145439. _vq_lengthlist__44u0__p7_0,
  145440. 1, -518709248, 1626677248, 3, 0,
  145441. _vq_quantlist__44u0__p7_0,
  145442. NULL,
  145443. &_vq_auxt__44u0__p7_0,
  145444. NULL,
  145445. 0
  145446. };
  145447. static long _vq_quantlist__44u0__p7_1[] = {
  145448. 6,
  145449. 5,
  145450. 7,
  145451. 4,
  145452. 8,
  145453. 3,
  145454. 9,
  145455. 2,
  145456. 10,
  145457. 1,
  145458. 11,
  145459. 0,
  145460. 12,
  145461. };
  145462. static long _vq_lengthlist__44u0__p7_1[] = {
  145463. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  145464. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  145465. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  145466. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  145467. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  145468. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  145469. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  145470. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  145471. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  145472. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  145473. 15,15,15,15,15,15,15,15,15,
  145474. };
  145475. static float _vq_quantthresh__44u0__p7_1[] = {
  145476. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  145477. 32.5, 45.5, 58.5, 71.5,
  145478. };
  145479. static long _vq_quantmap__44u0__p7_1[] = {
  145480. 11, 9, 7, 5, 3, 1, 0, 2,
  145481. 4, 6, 8, 10, 12,
  145482. };
  145483. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  145484. _vq_quantthresh__44u0__p7_1,
  145485. _vq_quantmap__44u0__p7_1,
  145486. 13,
  145487. 13
  145488. };
  145489. static static_codebook _44u0__p7_1 = {
  145490. 2, 169,
  145491. _vq_lengthlist__44u0__p7_1,
  145492. 1, -523010048, 1618608128, 4, 0,
  145493. _vq_quantlist__44u0__p7_1,
  145494. NULL,
  145495. &_vq_auxt__44u0__p7_1,
  145496. NULL,
  145497. 0
  145498. };
  145499. static long _vq_quantlist__44u0__p7_2[] = {
  145500. 6,
  145501. 5,
  145502. 7,
  145503. 4,
  145504. 8,
  145505. 3,
  145506. 9,
  145507. 2,
  145508. 10,
  145509. 1,
  145510. 11,
  145511. 0,
  145512. 12,
  145513. };
  145514. static long _vq_lengthlist__44u0__p7_2[] = {
  145515. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  145516. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  145517. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  145518. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  145519. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  145520. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  145521. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  145522. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145523. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145524. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  145525. 9, 9, 9,10, 9, 9,10,10, 9,
  145526. };
  145527. static float _vq_quantthresh__44u0__p7_2[] = {
  145528. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  145529. 2.5, 3.5, 4.5, 5.5,
  145530. };
  145531. static long _vq_quantmap__44u0__p7_2[] = {
  145532. 11, 9, 7, 5, 3, 1, 0, 2,
  145533. 4, 6, 8, 10, 12,
  145534. };
  145535. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  145536. _vq_quantthresh__44u0__p7_2,
  145537. _vq_quantmap__44u0__p7_2,
  145538. 13,
  145539. 13
  145540. };
  145541. static static_codebook _44u0__p7_2 = {
  145542. 2, 169,
  145543. _vq_lengthlist__44u0__p7_2,
  145544. 1, -531103744, 1611661312, 4, 0,
  145545. _vq_quantlist__44u0__p7_2,
  145546. NULL,
  145547. &_vq_auxt__44u0__p7_2,
  145548. NULL,
  145549. 0
  145550. };
  145551. static long _huff_lengthlist__44u0__short[] = {
  145552. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  145553. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  145554. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  145555. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  145556. };
  145557. static static_codebook _huff_book__44u0__short = {
  145558. 2, 64,
  145559. _huff_lengthlist__44u0__short,
  145560. 0, 0, 0, 0, 0,
  145561. NULL,
  145562. NULL,
  145563. NULL,
  145564. NULL,
  145565. 0
  145566. };
  145567. static long _huff_lengthlist__44u1__long[] = {
  145568. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145569. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145570. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145571. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145572. };
  145573. static static_codebook _huff_book__44u1__long = {
  145574. 2, 64,
  145575. _huff_lengthlist__44u1__long,
  145576. 0, 0, 0, 0, 0,
  145577. NULL,
  145578. NULL,
  145579. NULL,
  145580. NULL,
  145581. 0
  145582. };
  145583. static long _vq_quantlist__44u1__p1_0[] = {
  145584. 1,
  145585. 0,
  145586. 2,
  145587. };
  145588. static long _vq_lengthlist__44u1__p1_0[] = {
  145589. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145590. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145591. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145592. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145593. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145594. 13,
  145595. };
  145596. static float _vq_quantthresh__44u1__p1_0[] = {
  145597. -0.5, 0.5,
  145598. };
  145599. static long _vq_quantmap__44u1__p1_0[] = {
  145600. 1, 0, 2,
  145601. };
  145602. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  145603. _vq_quantthresh__44u1__p1_0,
  145604. _vq_quantmap__44u1__p1_0,
  145605. 3,
  145606. 3
  145607. };
  145608. static static_codebook _44u1__p1_0 = {
  145609. 4, 81,
  145610. _vq_lengthlist__44u1__p1_0,
  145611. 1, -535822336, 1611661312, 2, 0,
  145612. _vq_quantlist__44u1__p1_0,
  145613. NULL,
  145614. &_vq_auxt__44u1__p1_0,
  145615. NULL,
  145616. 0
  145617. };
  145618. static long _vq_quantlist__44u1__p2_0[] = {
  145619. 1,
  145620. 0,
  145621. 2,
  145622. };
  145623. static long _vq_lengthlist__44u1__p2_0[] = {
  145624. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145625. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145626. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145627. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145628. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145629. 9,
  145630. };
  145631. static float _vq_quantthresh__44u1__p2_0[] = {
  145632. -0.5, 0.5,
  145633. };
  145634. static long _vq_quantmap__44u1__p2_0[] = {
  145635. 1, 0, 2,
  145636. };
  145637. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  145638. _vq_quantthresh__44u1__p2_0,
  145639. _vq_quantmap__44u1__p2_0,
  145640. 3,
  145641. 3
  145642. };
  145643. static static_codebook _44u1__p2_0 = {
  145644. 4, 81,
  145645. _vq_lengthlist__44u1__p2_0,
  145646. 1, -535822336, 1611661312, 2, 0,
  145647. _vq_quantlist__44u1__p2_0,
  145648. NULL,
  145649. &_vq_auxt__44u1__p2_0,
  145650. NULL,
  145651. 0
  145652. };
  145653. static long _vq_quantlist__44u1__p3_0[] = {
  145654. 2,
  145655. 1,
  145656. 3,
  145657. 0,
  145658. 4,
  145659. };
  145660. static long _vq_lengthlist__44u1__p3_0[] = {
  145661. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145662. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145663. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145664. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145665. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145666. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145667. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145668. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145669. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145670. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145671. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145672. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145673. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145674. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145675. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145676. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145677. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145678. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145679. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145680. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145681. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145682. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145683. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145684. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145685. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145686. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145687. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145688. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145689. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145690. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145691. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145692. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145693. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145694. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145695. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145696. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145697. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145698. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145699. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145700. 19,
  145701. };
  145702. static float _vq_quantthresh__44u1__p3_0[] = {
  145703. -1.5, -0.5, 0.5, 1.5,
  145704. };
  145705. static long _vq_quantmap__44u1__p3_0[] = {
  145706. 3, 1, 0, 2, 4,
  145707. };
  145708. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  145709. _vq_quantthresh__44u1__p3_0,
  145710. _vq_quantmap__44u1__p3_0,
  145711. 5,
  145712. 5
  145713. };
  145714. static static_codebook _44u1__p3_0 = {
  145715. 4, 625,
  145716. _vq_lengthlist__44u1__p3_0,
  145717. 1, -533725184, 1611661312, 3, 0,
  145718. _vq_quantlist__44u1__p3_0,
  145719. NULL,
  145720. &_vq_auxt__44u1__p3_0,
  145721. NULL,
  145722. 0
  145723. };
  145724. static long _vq_quantlist__44u1__p4_0[] = {
  145725. 2,
  145726. 1,
  145727. 3,
  145728. 0,
  145729. 4,
  145730. };
  145731. static long _vq_lengthlist__44u1__p4_0[] = {
  145732. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145733. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145734. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145735. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145736. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145737. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145738. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145739. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145740. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145741. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  145742. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  145743. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145744. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  145745. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  145746. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  145747. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  145748. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  145749. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  145750. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  145751. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  145752. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  145753. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  145754. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  145755. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  145756. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  145757. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  145758. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  145759. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  145760. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  145761. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  145762. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  145763. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  145764. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  145765. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  145766. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  145767. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  145768. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  145769. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  145770. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  145771. 12,
  145772. };
  145773. static float _vq_quantthresh__44u1__p4_0[] = {
  145774. -1.5, -0.5, 0.5, 1.5,
  145775. };
  145776. static long _vq_quantmap__44u1__p4_0[] = {
  145777. 3, 1, 0, 2, 4,
  145778. };
  145779. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  145780. _vq_quantthresh__44u1__p4_0,
  145781. _vq_quantmap__44u1__p4_0,
  145782. 5,
  145783. 5
  145784. };
  145785. static static_codebook _44u1__p4_0 = {
  145786. 4, 625,
  145787. _vq_lengthlist__44u1__p4_0,
  145788. 1, -533725184, 1611661312, 3, 0,
  145789. _vq_quantlist__44u1__p4_0,
  145790. NULL,
  145791. &_vq_auxt__44u1__p4_0,
  145792. NULL,
  145793. 0
  145794. };
  145795. static long _vq_quantlist__44u1__p5_0[] = {
  145796. 4,
  145797. 3,
  145798. 5,
  145799. 2,
  145800. 6,
  145801. 1,
  145802. 7,
  145803. 0,
  145804. 8,
  145805. };
  145806. static long _vq_lengthlist__44u1__p5_0[] = {
  145807. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  145808. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  145809. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  145810. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145811. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  145812. 12,
  145813. };
  145814. static float _vq_quantthresh__44u1__p5_0[] = {
  145815. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145816. };
  145817. static long _vq_quantmap__44u1__p5_0[] = {
  145818. 7, 5, 3, 1, 0, 2, 4, 6,
  145819. 8,
  145820. };
  145821. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  145822. _vq_quantthresh__44u1__p5_0,
  145823. _vq_quantmap__44u1__p5_0,
  145824. 9,
  145825. 9
  145826. };
  145827. static static_codebook _44u1__p5_0 = {
  145828. 2, 81,
  145829. _vq_lengthlist__44u1__p5_0,
  145830. 1, -531628032, 1611661312, 4, 0,
  145831. _vq_quantlist__44u1__p5_0,
  145832. NULL,
  145833. &_vq_auxt__44u1__p5_0,
  145834. NULL,
  145835. 0
  145836. };
  145837. static long _vq_quantlist__44u1__p6_0[] = {
  145838. 6,
  145839. 5,
  145840. 7,
  145841. 4,
  145842. 8,
  145843. 3,
  145844. 9,
  145845. 2,
  145846. 10,
  145847. 1,
  145848. 11,
  145849. 0,
  145850. 12,
  145851. };
  145852. static long _vq_lengthlist__44u1__p6_0[] = {
  145853. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  145854. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  145855. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145856. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  145857. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  145858. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  145859. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  145860. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  145861. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  145862. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  145863. 15,17,16,17,18,17,17,18, 0,
  145864. };
  145865. static float _vq_quantthresh__44u1__p6_0[] = {
  145866. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145867. 12.5, 17.5, 22.5, 27.5,
  145868. };
  145869. static long _vq_quantmap__44u1__p6_0[] = {
  145870. 11, 9, 7, 5, 3, 1, 0, 2,
  145871. 4, 6, 8, 10, 12,
  145872. };
  145873. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  145874. _vq_quantthresh__44u1__p6_0,
  145875. _vq_quantmap__44u1__p6_0,
  145876. 13,
  145877. 13
  145878. };
  145879. static static_codebook _44u1__p6_0 = {
  145880. 2, 169,
  145881. _vq_lengthlist__44u1__p6_0,
  145882. 1, -526516224, 1616117760, 4, 0,
  145883. _vq_quantlist__44u1__p6_0,
  145884. NULL,
  145885. &_vq_auxt__44u1__p6_0,
  145886. NULL,
  145887. 0
  145888. };
  145889. static long _vq_quantlist__44u1__p6_1[] = {
  145890. 2,
  145891. 1,
  145892. 3,
  145893. 0,
  145894. 4,
  145895. };
  145896. static long _vq_lengthlist__44u1__p6_1[] = {
  145897. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145898. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  145899. };
  145900. static float _vq_quantthresh__44u1__p6_1[] = {
  145901. -1.5, -0.5, 0.5, 1.5,
  145902. };
  145903. static long _vq_quantmap__44u1__p6_1[] = {
  145904. 3, 1, 0, 2, 4,
  145905. };
  145906. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  145907. _vq_quantthresh__44u1__p6_1,
  145908. _vq_quantmap__44u1__p6_1,
  145909. 5,
  145910. 5
  145911. };
  145912. static static_codebook _44u1__p6_1 = {
  145913. 2, 25,
  145914. _vq_lengthlist__44u1__p6_1,
  145915. 1, -533725184, 1611661312, 3, 0,
  145916. _vq_quantlist__44u1__p6_1,
  145917. NULL,
  145918. &_vq_auxt__44u1__p6_1,
  145919. NULL,
  145920. 0
  145921. };
  145922. static long _vq_quantlist__44u1__p7_0[] = {
  145923. 3,
  145924. 2,
  145925. 4,
  145926. 1,
  145927. 5,
  145928. 0,
  145929. 6,
  145930. };
  145931. static long _vq_lengthlist__44u1__p7_0[] = {
  145932. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145933. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145934. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145935. 8,
  145936. };
  145937. static float _vq_quantthresh__44u1__p7_0[] = {
  145938. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  145939. };
  145940. static long _vq_quantmap__44u1__p7_0[] = {
  145941. 5, 3, 1, 0, 2, 4, 6,
  145942. };
  145943. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  145944. _vq_quantthresh__44u1__p7_0,
  145945. _vq_quantmap__44u1__p7_0,
  145946. 7,
  145947. 7
  145948. };
  145949. static static_codebook _44u1__p7_0 = {
  145950. 2, 49,
  145951. _vq_lengthlist__44u1__p7_0,
  145952. 1, -518017024, 1626677248, 3, 0,
  145953. _vq_quantlist__44u1__p7_0,
  145954. NULL,
  145955. &_vq_auxt__44u1__p7_0,
  145956. NULL,
  145957. 0
  145958. };
  145959. static long _vq_quantlist__44u1__p7_1[] = {
  145960. 6,
  145961. 5,
  145962. 7,
  145963. 4,
  145964. 8,
  145965. 3,
  145966. 9,
  145967. 2,
  145968. 10,
  145969. 1,
  145970. 11,
  145971. 0,
  145972. 12,
  145973. };
  145974. static long _vq_lengthlist__44u1__p7_1[] = {
  145975. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  145976. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  145977. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  145978. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  145979. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  145980. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  145981. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  145982. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  145983. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  145984. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  145985. 15,15,15,15,15,15,15,15,15,
  145986. };
  145987. static float _vq_quantthresh__44u1__p7_1[] = {
  145988. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  145989. 32.5, 45.5, 58.5, 71.5,
  145990. };
  145991. static long _vq_quantmap__44u1__p7_1[] = {
  145992. 11, 9, 7, 5, 3, 1, 0, 2,
  145993. 4, 6, 8, 10, 12,
  145994. };
  145995. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  145996. _vq_quantthresh__44u1__p7_1,
  145997. _vq_quantmap__44u1__p7_1,
  145998. 13,
  145999. 13
  146000. };
  146001. static static_codebook _44u1__p7_1 = {
  146002. 2, 169,
  146003. _vq_lengthlist__44u1__p7_1,
  146004. 1, -523010048, 1618608128, 4, 0,
  146005. _vq_quantlist__44u1__p7_1,
  146006. NULL,
  146007. &_vq_auxt__44u1__p7_1,
  146008. NULL,
  146009. 0
  146010. };
  146011. static long _vq_quantlist__44u1__p7_2[] = {
  146012. 6,
  146013. 5,
  146014. 7,
  146015. 4,
  146016. 8,
  146017. 3,
  146018. 9,
  146019. 2,
  146020. 10,
  146021. 1,
  146022. 11,
  146023. 0,
  146024. 12,
  146025. };
  146026. static long _vq_lengthlist__44u1__p7_2[] = {
  146027. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146028. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146029. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146030. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146031. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146032. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146033. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146034. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146035. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146036. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146037. 9, 9, 9,10, 9, 9,10,10, 9,
  146038. };
  146039. static float _vq_quantthresh__44u1__p7_2[] = {
  146040. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146041. 2.5, 3.5, 4.5, 5.5,
  146042. };
  146043. static long _vq_quantmap__44u1__p7_2[] = {
  146044. 11, 9, 7, 5, 3, 1, 0, 2,
  146045. 4, 6, 8, 10, 12,
  146046. };
  146047. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146048. _vq_quantthresh__44u1__p7_2,
  146049. _vq_quantmap__44u1__p7_2,
  146050. 13,
  146051. 13
  146052. };
  146053. static static_codebook _44u1__p7_2 = {
  146054. 2, 169,
  146055. _vq_lengthlist__44u1__p7_2,
  146056. 1, -531103744, 1611661312, 4, 0,
  146057. _vq_quantlist__44u1__p7_2,
  146058. NULL,
  146059. &_vq_auxt__44u1__p7_2,
  146060. NULL,
  146061. 0
  146062. };
  146063. static long _huff_lengthlist__44u1__short[] = {
  146064. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146065. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146066. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146067. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146068. };
  146069. static static_codebook _huff_book__44u1__short = {
  146070. 2, 64,
  146071. _huff_lengthlist__44u1__short,
  146072. 0, 0, 0, 0, 0,
  146073. NULL,
  146074. NULL,
  146075. NULL,
  146076. NULL,
  146077. 0
  146078. };
  146079. static long _huff_lengthlist__44u2__long[] = {
  146080. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146081. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146082. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146083. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146084. };
  146085. static static_codebook _huff_book__44u2__long = {
  146086. 2, 64,
  146087. _huff_lengthlist__44u2__long,
  146088. 0, 0, 0, 0, 0,
  146089. NULL,
  146090. NULL,
  146091. NULL,
  146092. NULL,
  146093. 0
  146094. };
  146095. static long _vq_quantlist__44u2__p1_0[] = {
  146096. 1,
  146097. 0,
  146098. 2,
  146099. };
  146100. static long _vq_lengthlist__44u2__p1_0[] = {
  146101. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146102. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146103. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146104. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146105. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146106. 13,
  146107. };
  146108. static float _vq_quantthresh__44u2__p1_0[] = {
  146109. -0.5, 0.5,
  146110. };
  146111. static long _vq_quantmap__44u2__p1_0[] = {
  146112. 1, 0, 2,
  146113. };
  146114. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146115. _vq_quantthresh__44u2__p1_0,
  146116. _vq_quantmap__44u2__p1_0,
  146117. 3,
  146118. 3
  146119. };
  146120. static static_codebook _44u2__p1_0 = {
  146121. 4, 81,
  146122. _vq_lengthlist__44u2__p1_0,
  146123. 1, -535822336, 1611661312, 2, 0,
  146124. _vq_quantlist__44u2__p1_0,
  146125. NULL,
  146126. &_vq_auxt__44u2__p1_0,
  146127. NULL,
  146128. 0
  146129. };
  146130. static long _vq_quantlist__44u2__p2_0[] = {
  146131. 1,
  146132. 0,
  146133. 2,
  146134. };
  146135. static long _vq_lengthlist__44u2__p2_0[] = {
  146136. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146137. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  146138. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146139. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146140. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146141. 9,
  146142. };
  146143. static float _vq_quantthresh__44u2__p2_0[] = {
  146144. -0.5, 0.5,
  146145. };
  146146. static long _vq_quantmap__44u2__p2_0[] = {
  146147. 1, 0, 2,
  146148. };
  146149. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  146150. _vq_quantthresh__44u2__p2_0,
  146151. _vq_quantmap__44u2__p2_0,
  146152. 3,
  146153. 3
  146154. };
  146155. static static_codebook _44u2__p2_0 = {
  146156. 4, 81,
  146157. _vq_lengthlist__44u2__p2_0,
  146158. 1, -535822336, 1611661312, 2, 0,
  146159. _vq_quantlist__44u2__p2_0,
  146160. NULL,
  146161. &_vq_auxt__44u2__p2_0,
  146162. NULL,
  146163. 0
  146164. };
  146165. static long _vq_quantlist__44u2__p3_0[] = {
  146166. 2,
  146167. 1,
  146168. 3,
  146169. 0,
  146170. 4,
  146171. };
  146172. static long _vq_lengthlist__44u2__p3_0[] = {
  146173. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146174. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146175. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146176. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146177. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  146178. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  146179. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146180. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  146181. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146182. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146183. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  146184. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146185. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  146186. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  146187. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  146188. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  146189. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146190. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  146191. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  146192. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  146193. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  146194. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  146195. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  146196. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  146197. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  146198. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  146199. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  146200. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  146201. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  146202. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  146203. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  146204. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  146205. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  146206. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  146207. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  146208. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  146209. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  146210. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  146211. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  146212. 0,
  146213. };
  146214. static float _vq_quantthresh__44u2__p3_0[] = {
  146215. -1.5, -0.5, 0.5, 1.5,
  146216. };
  146217. static long _vq_quantmap__44u2__p3_0[] = {
  146218. 3, 1, 0, 2, 4,
  146219. };
  146220. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  146221. _vq_quantthresh__44u2__p3_0,
  146222. _vq_quantmap__44u2__p3_0,
  146223. 5,
  146224. 5
  146225. };
  146226. static static_codebook _44u2__p3_0 = {
  146227. 4, 625,
  146228. _vq_lengthlist__44u2__p3_0,
  146229. 1, -533725184, 1611661312, 3, 0,
  146230. _vq_quantlist__44u2__p3_0,
  146231. NULL,
  146232. &_vq_auxt__44u2__p3_0,
  146233. NULL,
  146234. 0
  146235. };
  146236. static long _vq_quantlist__44u2__p4_0[] = {
  146237. 2,
  146238. 1,
  146239. 3,
  146240. 0,
  146241. 4,
  146242. };
  146243. static long _vq_lengthlist__44u2__p4_0[] = {
  146244. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  146245. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146246. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  146247. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  146248. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  146249. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  146250. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  146251. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  146252. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  146253. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  146254. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  146255. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146256. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  146257. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  146258. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  146259. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  146260. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  146261. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146262. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  146263. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  146264. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  146265. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  146266. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  146267. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  146268. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  146269. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  146270. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  146271. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  146272. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  146273. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  146274. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  146275. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  146276. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  146277. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  146278. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  146279. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  146280. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  146281. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  146282. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  146283. 13,
  146284. };
  146285. static float _vq_quantthresh__44u2__p4_0[] = {
  146286. -1.5, -0.5, 0.5, 1.5,
  146287. };
  146288. static long _vq_quantmap__44u2__p4_0[] = {
  146289. 3, 1, 0, 2, 4,
  146290. };
  146291. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  146292. _vq_quantthresh__44u2__p4_0,
  146293. _vq_quantmap__44u2__p4_0,
  146294. 5,
  146295. 5
  146296. };
  146297. static static_codebook _44u2__p4_0 = {
  146298. 4, 625,
  146299. _vq_lengthlist__44u2__p4_0,
  146300. 1, -533725184, 1611661312, 3, 0,
  146301. _vq_quantlist__44u2__p4_0,
  146302. NULL,
  146303. &_vq_auxt__44u2__p4_0,
  146304. NULL,
  146305. 0
  146306. };
  146307. static long _vq_quantlist__44u2__p5_0[] = {
  146308. 4,
  146309. 3,
  146310. 5,
  146311. 2,
  146312. 6,
  146313. 1,
  146314. 7,
  146315. 0,
  146316. 8,
  146317. };
  146318. static long _vq_lengthlist__44u2__p5_0[] = {
  146319. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  146320. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146321. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146322. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  146323. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  146324. 13,
  146325. };
  146326. static float _vq_quantthresh__44u2__p5_0[] = {
  146327. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146328. };
  146329. static long _vq_quantmap__44u2__p5_0[] = {
  146330. 7, 5, 3, 1, 0, 2, 4, 6,
  146331. 8,
  146332. };
  146333. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  146334. _vq_quantthresh__44u2__p5_0,
  146335. _vq_quantmap__44u2__p5_0,
  146336. 9,
  146337. 9
  146338. };
  146339. static static_codebook _44u2__p5_0 = {
  146340. 2, 81,
  146341. _vq_lengthlist__44u2__p5_0,
  146342. 1, -531628032, 1611661312, 4, 0,
  146343. _vq_quantlist__44u2__p5_0,
  146344. NULL,
  146345. &_vq_auxt__44u2__p5_0,
  146346. NULL,
  146347. 0
  146348. };
  146349. static long _vq_quantlist__44u2__p6_0[] = {
  146350. 6,
  146351. 5,
  146352. 7,
  146353. 4,
  146354. 8,
  146355. 3,
  146356. 9,
  146357. 2,
  146358. 10,
  146359. 1,
  146360. 11,
  146361. 0,
  146362. 12,
  146363. };
  146364. static long _vq_lengthlist__44u2__p6_0[] = {
  146365. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  146366. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  146367. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  146368. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  146369. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  146370. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  146371. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  146372. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  146373. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  146374. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  146375. 15,17,17,16,18,17,18, 0, 0,
  146376. };
  146377. static float _vq_quantthresh__44u2__p6_0[] = {
  146378. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146379. 12.5, 17.5, 22.5, 27.5,
  146380. };
  146381. static long _vq_quantmap__44u2__p6_0[] = {
  146382. 11, 9, 7, 5, 3, 1, 0, 2,
  146383. 4, 6, 8, 10, 12,
  146384. };
  146385. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  146386. _vq_quantthresh__44u2__p6_0,
  146387. _vq_quantmap__44u2__p6_0,
  146388. 13,
  146389. 13
  146390. };
  146391. static static_codebook _44u2__p6_0 = {
  146392. 2, 169,
  146393. _vq_lengthlist__44u2__p6_0,
  146394. 1, -526516224, 1616117760, 4, 0,
  146395. _vq_quantlist__44u2__p6_0,
  146396. NULL,
  146397. &_vq_auxt__44u2__p6_0,
  146398. NULL,
  146399. 0
  146400. };
  146401. static long _vq_quantlist__44u2__p6_1[] = {
  146402. 2,
  146403. 1,
  146404. 3,
  146405. 0,
  146406. 4,
  146407. };
  146408. static long _vq_lengthlist__44u2__p6_1[] = {
  146409. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  146410. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  146411. };
  146412. static float _vq_quantthresh__44u2__p6_1[] = {
  146413. -1.5, -0.5, 0.5, 1.5,
  146414. };
  146415. static long _vq_quantmap__44u2__p6_1[] = {
  146416. 3, 1, 0, 2, 4,
  146417. };
  146418. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  146419. _vq_quantthresh__44u2__p6_1,
  146420. _vq_quantmap__44u2__p6_1,
  146421. 5,
  146422. 5
  146423. };
  146424. static static_codebook _44u2__p6_1 = {
  146425. 2, 25,
  146426. _vq_lengthlist__44u2__p6_1,
  146427. 1, -533725184, 1611661312, 3, 0,
  146428. _vq_quantlist__44u2__p6_1,
  146429. NULL,
  146430. &_vq_auxt__44u2__p6_1,
  146431. NULL,
  146432. 0
  146433. };
  146434. static long _vq_quantlist__44u2__p7_0[] = {
  146435. 4,
  146436. 3,
  146437. 5,
  146438. 2,
  146439. 6,
  146440. 1,
  146441. 7,
  146442. 0,
  146443. 8,
  146444. };
  146445. static long _vq_lengthlist__44u2__p7_0[] = {
  146446. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  146447. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  146448. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146449. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146450. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146451. 11,
  146452. };
  146453. static float _vq_quantthresh__44u2__p7_0[] = {
  146454. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  146455. };
  146456. static long _vq_quantmap__44u2__p7_0[] = {
  146457. 7, 5, 3, 1, 0, 2, 4, 6,
  146458. 8,
  146459. };
  146460. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  146461. _vq_quantthresh__44u2__p7_0,
  146462. _vq_quantmap__44u2__p7_0,
  146463. 9,
  146464. 9
  146465. };
  146466. static static_codebook _44u2__p7_0 = {
  146467. 2, 81,
  146468. _vq_lengthlist__44u2__p7_0,
  146469. 1, -516612096, 1626677248, 4, 0,
  146470. _vq_quantlist__44u2__p7_0,
  146471. NULL,
  146472. &_vq_auxt__44u2__p7_0,
  146473. NULL,
  146474. 0
  146475. };
  146476. static long _vq_quantlist__44u2__p7_1[] = {
  146477. 6,
  146478. 5,
  146479. 7,
  146480. 4,
  146481. 8,
  146482. 3,
  146483. 9,
  146484. 2,
  146485. 10,
  146486. 1,
  146487. 11,
  146488. 0,
  146489. 12,
  146490. };
  146491. static long _vq_lengthlist__44u2__p7_1[] = {
  146492. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  146493. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  146494. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  146495. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  146496. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  146497. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  146498. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  146499. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  146500. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  146501. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  146502. 14,14,14,17,15,17,17,17,17,
  146503. };
  146504. static float _vq_quantthresh__44u2__p7_1[] = {
  146505. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146506. 32.5, 45.5, 58.5, 71.5,
  146507. };
  146508. static long _vq_quantmap__44u2__p7_1[] = {
  146509. 11, 9, 7, 5, 3, 1, 0, 2,
  146510. 4, 6, 8, 10, 12,
  146511. };
  146512. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  146513. _vq_quantthresh__44u2__p7_1,
  146514. _vq_quantmap__44u2__p7_1,
  146515. 13,
  146516. 13
  146517. };
  146518. static static_codebook _44u2__p7_1 = {
  146519. 2, 169,
  146520. _vq_lengthlist__44u2__p7_1,
  146521. 1, -523010048, 1618608128, 4, 0,
  146522. _vq_quantlist__44u2__p7_1,
  146523. NULL,
  146524. &_vq_auxt__44u2__p7_1,
  146525. NULL,
  146526. 0
  146527. };
  146528. static long _vq_quantlist__44u2__p7_2[] = {
  146529. 6,
  146530. 5,
  146531. 7,
  146532. 4,
  146533. 8,
  146534. 3,
  146535. 9,
  146536. 2,
  146537. 10,
  146538. 1,
  146539. 11,
  146540. 0,
  146541. 12,
  146542. };
  146543. static long _vq_lengthlist__44u2__p7_2[] = {
  146544. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  146545. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  146546. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  146547. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146548. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  146549. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  146550. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146551. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146552. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  146553. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  146554. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146555. };
  146556. static float _vq_quantthresh__44u2__p7_2[] = {
  146557. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146558. 2.5, 3.5, 4.5, 5.5,
  146559. };
  146560. static long _vq_quantmap__44u2__p7_2[] = {
  146561. 11, 9, 7, 5, 3, 1, 0, 2,
  146562. 4, 6, 8, 10, 12,
  146563. };
  146564. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  146565. _vq_quantthresh__44u2__p7_2,
  146566. _vq_quantmap__44u2__p7_2,
  146567. 13,
  146568. 13
  146569. };
  146570. static static_codebook _44u2__p7_2 = {
  146571. 2, 169,
  146572. _vq_lengthlist__44u2__p7_2,
  146573. 1, -531103744, 1611661312, 4, 0,
  146574. _vq_quantlist__44u2__p7_2,
  146575. NULL,
  146576. &_vq_auxt__44u2__p7_2,
  146577. NULL,
  146578. 0
  146579. };
  146580. static long _huff_lengthlist__44u2__short[] = {
  146581. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  146582. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  146583. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  146584. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  146585. };
  146586. static static_codebook _huff_book__44u2__short = {
  146587. 2, 64,
  146588. _huff_lengthlist__44u2__short,
  146589. 0, 0, 0, 0, 0,
  146590. NULL,
  146591. NULL,
  146592. NULL,
  146593. NULL,
  146594. 0
  146595. };
  146596. static long _huff_lengthlist__44u3__long[] = {
  146597. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  146598. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  146599. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  146600. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  146601. };
  146602. static static_codebook _huff_book__44u3__long = {
  146603. 2, 64,
  146604. _huff_lengthlist__44u3__long,
  146605. 0, 0, 0, 0, 0,
  146606. NULL,
  146607. NULL,
  146608. NULL,
  146609. NULL,
  146610. 0
  146611. };
  146612. static long _vq_quantlist__44u3__p1_0[] = {
  146613. 1,
  146614. 0,
  146615. 2,
  146616. };
  146617. static long _vq_lengthlist__44u3__p1_0[] = {
  146618. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  146619. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146620. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  146621. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  146622. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  146623. 13,
  146624. };
  146625. static float _vq_quantthresh__44u3__p1_0[] = {
  146626. -0.5, 0.5,
  146627. };
  146628. static long _vq_quantmap__44u3__p1_0[] = {
  146629. 1, 0, 2,
  146630. };
  146631. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  146632. _vq_quantthresh__44u3__p1_0,
  146633. _vq_quantmap__44u3__p1_0,
  146634. 3,
  146635. 3
  146636. };
  146637. static static_codebook _44u3__p1_0 = {
  146638. 4, 81,
  146639. _vq_lengthlist__44u3__p1_0,
  146640. 1, -535822336, 1611661312, 2, 0,
  146641. _vq_quantlist__44u3__p1_0,
  146642. NULL,
  146643. &_vq_auxt__44u3__p1_0,
  146644. NULL,
  146645. 0
  146646. };
  146647. static long _vq_quantlist__44u3__p2_0[] = {
  146648. 1,
  146649. 0,
  146650. 2,
  146651. };
  146652. static long _vq_lengthlist__44u3__p2_0[] = {
  146653. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146654. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  146655. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146656. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146657. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  146658. 9,
  146659. };
  146660. static float _vq_quantthresh__44u3__p2_0[] = {
  146661. -0.5, 0.5,
  146662. };
  146663. static long _vq_quantmap__44u3__p2_0[] = {
  146664. 1, 0, 2,
  146665. };
  146666. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  146667. _vq_quantthresh__44u3__p2_0,
  146668. _vq_quantmap__44u3__p2_0,
  146669. 3,
  146670. 3
  146671. };
  146672. static static_codebook _44u3__p2_0 = {
  146673. 4, 81,
  146674. _vq_lengthlist__44u3__p2_0,
  146675. 1, -535822336, 1611661312, 2, 0,
  146676. _vq_quantlist__44u3__p2_0,
  146677. NULL,
  146678. &_vq_auxt__44u3__p2_0,
  146679. NULL,
  146680. 0
  146681. };
  146682. static long _vq_quantlist__44u3__p3_0[] = {
  146683. 2,
  146684. 1,
  146685. 3,
  146686. 0,
  146687. 4,
  146688. };
  146689. static long _vq_lengthlist__44u3__p3_0[] = {
  146690. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146691. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146692. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146693. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146694. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  146695. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  146696. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  146697. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  146698. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146699. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146700. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  146701. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146702. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  146703. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  146704. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  146705. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  146706. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  146707. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  146708. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  146709. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  146710. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  146711. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  146712. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  146713. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  146714. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  146715. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  146716. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  146717. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  146718. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  146719. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  146720. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  146721. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  146722. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  146723. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  146724. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  146725. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  146726. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  146727. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  146728. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  146729. 0,
  146730. };
  146731. static float _vq_quantthresh__44u3__p3_0[] = {
  146732. -1.5, -0.5, 0.5, 1.5,
  146733. };
  146734. static long _vq_quantmap__44u3__p3_0[] = {
  146735. 3, 1, 0, 2, 4,
  146736. };
  146737. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  146738. _vq_quantthresh__44u3__p3_0,
  146739. _vq_quantmap__44u3__p3_0,
  146740. 5,
  146741. 5
  146742. };
  146743. static static_codebook _44u3__p3_0 = {
  146744. 4, 625,
  146745. _vq_lengthlist__44u3__p3_0,
  146746. 1, -533725184, 1611661312, 3, 0,
  146747. _vq_quantlist__44u3__p3_0,
  146748. NULL,
  146749. &_vq_auxt__44u3__p3_0,
  146750. NULL,
  146751. 0
  146752. };
  146753. static long _vq_quantlist__44u3__p4_0[] = {
  146754. 2,
  146755. 1,
  146756. 3,
  146757. 0,
  146758. 4,
  146759. };
  146760. static long _vq_lengthlist__44u3__p4_0[] = {
  146761. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  146762. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146763. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  146764. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  146765. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  146766. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  146767. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  146768. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  146769. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  146770. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  146771. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  146772. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146773. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  146774. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  146775. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  146776. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  146777. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  146778. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146779. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  146780. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  146781. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  146782. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  146783. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  146784. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  146785. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  146786. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  146787. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  146788. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  146789. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  146790. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  146791. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  146792. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  146793. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  146794. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  146795. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  146796. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  146797. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  146798. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  146799. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  146800. 13,
  146801. };
  146802. static float _vq_quantthresh__44u3__p4_0[] = {
  146803. -1.5, -0.5, 0.5, 1.5,
  146804. };
  146805. static long _vq_quantmap__44u3__p4_0[] = {
  146806. 3, 1, 0, 2, 4,
  146807. };
  146808. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  146809. _vq_quantthresh__44u3__p4_0,
  146810. _vq_quantmap__44u3__p4_0,
  146811. 5,
  146812. 5
  146813. };
  146814. static static_codebook _44u3__p4_0 = {
  146815. 4, 625,
  146816. _vq_lengthlist__44u3__p4_0,
  146817. 1, -533725184, 1611661312, 3, 0,
  146818. _vq_quantlist__44u3__p4_0,
  146819. NULL,
  146820. &_vq_auxt__44u3__p4_0,
  146821. NULL,
  146822. 0
  146823. };
  146824. static long _vq_quantlist__44u3__p5_0[] = {
  146825. 4,
  146826. 3,
  146827. 5,
  146828. 2,
  146829. 6,
  146830. 1,
  146831. 7,
  146832. 0,
  146833. 8,
  146834. };
  146835. static long _vq_lengthlist__44u3__p5_0[] = {
  146836. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  146837. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  146838. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  146839. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146840. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  146841. 12,
  146842. };
  146843. static float _vq_quantthresh__44u3__p5_0[] = {
  146844. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146845. };
  146846. static long _vq_quantmap__44u3__p5_0[] = {
  146847. 7, 5, 3, 1, 0, 2, 4, 6,
  146848. 8,
  146849. };
  146850. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  146851. _vq_quantthresh__44u3__p5_0,
  146852. _vq_quantmap__44u3__p5_0,
  146853. 9,
  146854. 9
  146855. };
  146856. static static_codebook _44u3__p5_0 = {
  146857. 2, 81,
  146858. _vq_lengthlist__44u3__p5_0,
  146859. 1, -531628032, 1611661312, 4, 0,
  146860. _vq_quantlist__44u3__p5_0,
  146861. NULL,
  146862. &_vq_auxt__44u3__p5_0,
  146863. NULL,
  146864. 0
  146865. };
  146866. static long _vq_quantlist__44u3__p6_0[] = {
  146867. 6,
  146868. 5,
  146869. 7,
  146870. 4,
  146871. 8,
  146872. 3,
  146873. 9,
  146874. 2,
  146875. 10,
  146876. 1,
  146877. 11,
  146878. 0,
  146879. 12,
  146880. };
  146881. static long _vq_lengthlist__44u3__p6_0[] = {
  146882. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  146883. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  146884. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146885. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  146886. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  146887. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  146888. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  146889. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  146890. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  146891. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  146892. 15,16,16,16,17,18,16,20,18,
  146893. };
  146894. static float _vq_quantthresh__44u3__p6_0[] = {
  146895. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146896. 12.5, 17.5, 22.5, 27.5,
  146897. };
  146898. static long _vq_quantmap__44u3__p6_0[] = {
  146899. 11, 9, 7, 5, 3, 1, 0, 2,
  146900. 4, 6, 8, 10, 12,
  146901. };
  146902. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  146903. _vq_quantthresh__44u3__p6_0,
  146904. _vq_quantmap__44u3__p6_0,
  146905. 13,
  146906. 13
  146907. };
  146908. static static_codebook _44u3__p6_0 = {
  146909. 2, 169,
  146910. _vq_lengthlist__44u3__p6_0,
  146911. 1, -526516224, 1616117760, 4, 0,
  146912. _vq_quantlist__44u3__p6_0,
  146913. NULL,
  146914. &_vq_auxt__44u3__p6_0,
  146915. NULL,
  146916. 0
  146917. };
  146918. static long _vq_quantlist__44u3__p6_1[] = {
  146919. 2,
  146920. 1,
  146921. 3,
  146922. 0,
  146923. 4,
  146924. };
  146925. static long _vq_lengthlist__44u3__p6_1[] = {
  146926. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  146927. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  146928. };
  146929. static float _vq_quantthresh__44u3__p6_1[] = {
  146930. -1.5, -0.5, 0.5, 1.5,
  146931. };
  146932. static long _vq_quantmap__44u3__p6_1[] = {
  146933. 3, 1, 0, 2, 4,
  146934. };
  146935. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  146936. _vq_quantthresh__44u3__p6_1,
  146937. _vq_quantmap__44u3__p6_1,
  146938. 5,
  146939. 5
  146940. };
  146941. static static_codebook _44u3__p6_1 = {
  146942. 2, 25,
  146943. _vq_lengthlist__44u3__p6_1,
  146944. 1, -533725184, 1611661312, 3, 0,
  146945. _vq_quantlist__44u3__p6_1,
  146946. NULL,
  146947. &_vq_auxt__44u3__p6_1,
  146948. NULL,
  146949. 0
  146950. };
  146951. static long _vq_quantlist__44u3__p7_0[] = {
  146952. 4,
  146953. 3,
  146954. 5,
  146955. 2,
  146956. 6,
  146957. 1,
  146958. 7,
  146959. 0,
  146960. 8,
  146961. };
  146962. static long _vq_lengthlist__44u3__p7_0[] = {
  146963. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  146964. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146965. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146966. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146967. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146968. 9,
  146969. };
  146970. static float _vq_quantthresh__44u3__p7_0[] = {
  146971. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  146972. };
  146973. static long _vq_quantmap__44u3__p7_0[] = {
  146974. 7, 5, 3, 1, 0, 2, 4, 6,
  146975. 8,
  146976. };
  146977. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  146978. _vq_quantthresh__44u3__p7_0,
  146979. _vq_quantmap__44u3__p7_0,
  146980. 9,
  146981. 9
  146982. };
  146983. static static_codebook _44u3__p7_0 = {
  146984. 2, 81,
  146985. _vq_lengthlist__44u3__p7_0,
  146986. 1, -515907584, 1627381760, 4, 0,
  146987. _vq_quantlist__44u3__p7_0,
  146988. NULL,
  146989. &_vq_auxt__44u3__p7_0,
  146990. NULL,
  146991. 0
  146992. };
  146993. static long _vq_quantlist__44u3__p7_1[] = {
  146994. 7,
  146995. 6,
  146996. 8,
  146997. 5,
  146998. 9,
  146999. 4,
  147000. 10,
  147001. 3,
  147002. 11,
  147003. 2,
  147004. 12,
  147005. 1,
  147006. 13,
  147007. 0,
  147008. 14,
  147009. };
  147010. static long _vq_lengthlist__44u3__p7_1[] = {
  147011. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147012. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147013. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147014. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147015. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147016. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147017. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147018. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147019. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147020. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147021. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147022. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147023. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147024. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147025. 17,
  147026. };
  147027. static float _vq_quantthresh__44u3__p7_1[] = {
  147028. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147029. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147030. };
  147031. static long _vq_quantmap__44u3__p7_1[] = {
  147032. 13, 11, 9, 7, 5, 3, 1, 0,
  147033. 2, 4, 6, 8, 10, 12, 14,
  147034. };
  147035. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147036. _vq_quantthresh__44u3__p7_1,
  147037. _vq_quantmap__44u3__p7_1,
  147038. 15,
  147039. 15
  147040. };
  147041. static static_codebook _44u3__p7_1 = {
  147042. 2, 225,
  147043. _vq_lengthlist__44u3__p7_1,
  147044. 1, -522338304, 1620115456, 4, 0,
  147045. _vq_quantlist__44u3__p7_1,
  147046. NULL,
  147047. &_vq_auxt__44u3__p7_1,
  147048. NULL,
  147049. 0
  147050. };
  147051. static long _vq_quantlist__44u3__p7_2[] = {
  147052. 8,
  147053. 7,
  147054. 9,
  147055. 6,
  147056. 10,
  147057. 5,
  147058. 11,
  147059. 4,
  147060. 12,
  147061. 3,
  147062. 13,
  147063. 2,
  147064. 14,
  147065. 1,
  147066. 15,
  147067. 0,
  147068. 16,
  147069. };
  147070. static long _vq_lengthlist__44u3__p7_2[] = {
  147071. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147072. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147073. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147074. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147075. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147076. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147077. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147078. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147079. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147080. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147081. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147082. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147083. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147084. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147085. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147086. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147087. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147088. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147089. 11,
  147090. };
  147091. static float _vq_quantthresh__44u3__p7_2[] = {
  147092. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147093. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147094. };
  147095. static long _vq_quantmap__44u3__p7_2[] = {
  147096. 15, 13, 11, 9, 7, 5, 3, 1,
  147097. 0, 2, 4, 6, 8, 10, 12, 14,
  147098. 16,
  147099. };
  147100. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147101. _vq_quantthresh__44u3__p7_2,
  147102. _vq_quantmap__44u3__p7_2,
  147103. 17,
  147104. 17
  147105. };
  147106. static static_codebook _44u3__p7_2 = {
  147107. 2, 289,
  147108. _vq_lengthlist__44u3__p7_2,
  147109. 1, -529530880, 1611661312, 5, 0,
  147110. _vq_quantlist__44u3__p7_2,
  147111. NULL,
  147112. &_vq_auxt__44u3__p7_2,
  147113. NULL,
  147114. 0
  147115. };
  147116. static long _huff_lengthlist__44u3__short[] = {
  147117. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147118. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147119. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147120. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147121. };
  147122. static static_codebook _huff_book__44u3__short = {
  147123. 2, 64,
  147124. _huff_lengthlist__44u3__short,
  147125. 0, 0, 0, 0, 0,
  147126. NULL,
  147127. NULL,
  147128. NULL,
  147129. NULL,
  147130. 0
  147131. };
  147132. static long _huff_lengthlist__44u4__long[] = {
  147133. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  147134. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  147135. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  147136. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  147137. };
  147138. static static_codebook _huff_book__44u4__long = {
  147139. 2, 64,
  147140. _huff_lengthlist__44u4__long,
  147141. 0, 0, 0, 0, 0,
  147142. NULL,
  147143. NULL,
  147144. NULL,
  147145. NULL,
  147146. 0
  147147. };
  147148. static long _vq_quantlist__44u4__p1_0[] = {
  147149. 1,
  147150. 0,
  147151. 2,
  147152. };
  147153. static long _vq_lengthlist__44u4__p1_0[] = {
  147154. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147155. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147156. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  147157. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147158. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  147159. 13,
  147160. };
  147161. static float _vq_quantthresh__44u4__p1_0[] = {
  147162. -0.5, 0.5,
  147163. };
  147164. static long _vq_quantmap__44u4__p1_0[] = {
  147165. 1, 0, 2,
  147166. };
  147167. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  147168. _vq_quantthresh__44u4__p1_0,
  147169. _vq_quantmap__44u4__p1_0,
  147170. 3,
  147171. 3
  147172. };
  147173. static static_codebook _44u4__p1_0 = {
  147174. 4, 81,
  147175. _vq_lengthlist__44u4__p1_0,
  147176. 1, -535822336, 1611661312, 2, 0,
  147177. _vq_quantlist__44u4__p1_0,
  147178. NULL,
  147179. &_vq_auxt__44u4__p1_0,
  147180. NULL,
  147181. 0
  147182. };
  147183. static long _vq_quantlist__44u4__p2_0[] = {
  147184. 1,
  147185. 0,
  147186. 2,
  147187. };
  147188. static long _vq_lengthlist__44u4__p2_0[] = {
  147189. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147190. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  147191. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147192. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  147193. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147194. 9,
  147195. };
  147196. static float _vq_quantthresh__44u4__p2_0[] = {
  147197. -0.5, 0.5,
  147198. };
  147199. static long _vq_quantmap__44u4__p2_0[] = {
  147200. 1, 0, 2,
  147201. };
  147202. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  147203. _vq_quantthresh__44u4__p2_0,
  147204. _vq_quantmap__44u4__p2_0,
  147205. 3,
  147206. 3
  147207. };
  147208. static static_codebook _44u4__p2_0 = {
  147209. 4, 81,
  147210. _vq_lengthlist__44u4__p2_0,
  147211. 1, -535822336, 1611661312, 2, 0,
  147212. _vq_quantlist__44u4__p2_0,
  147213. NULL,
  147214. &_vq_auxt__44u4__p2_0,
  147215. NULL,
  147216. 0
  147217. };
  147218. static long _vq_quantlist__44u4__p3_0[] = {
  147219. 2,
  147220. 1,
  147221. 3,
  147222. 0,
  147223. 4,
  147224. };
  147225. static long _vq_lengthlist__44u4__p3_0[] = {
  147226. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147227. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  147228. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  147229. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  147230. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  147231. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  147232. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  147233. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  147234. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  147235. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  147236. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  147237. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  147238. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  147239. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  147240. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  147241. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  147242. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  147243. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  147244. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  147245. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  147246. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  147247. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  147248. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  147249. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  147250. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  147251. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  147252. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  147253. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  147254. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  147255. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  147256. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  147257. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  147258. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  147259. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  147260. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  147261. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  147262. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  147263. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  147264. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  147265. 0,
  147266. };
  147267. static float _vq_quantthresh__44u4__p3_0[] = {
  147268. -1.5, -0.5, 0.5, 1.5,
  147269. };
  147270. static long _vq_quantmap__44u4__p3_0[] = {
  147271. 3, 1, 0, 2, 4,
  147272. };
  147273. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  147274. _vq_quantthresh__44u4__p3_0,
  147275. _vq_quantmap__44u4__p3_0,
  147276. 5,
  147277. 5
  147278. };
  147279. static static_codebook _44u4__p3_0 = {
  147280. 4, 625,
  147281. _vq_lengthlist__44u4__p3_0,
  147282. 1, -533725184, 1611661312, 3, 0,
  147283. _vq_quantlist__44u4__p3_0,
  147284. NULL,
  147285. &_vq_auxt__44u4__p3_0,
  147286. NULL,
  147287. 0
  147288. };
  147289. static long _vq_quantlist__44u4__p4_0[] = {
  147290. 2,
  147291. 1,
  147292. 3,
  147293. 0,
  147294. 4,
  147295. };
  147296. static long _vq_lengthlist__44u4__p4_0[] = {
  147297. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147298. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147299. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147300. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147301. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147302. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  147303. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  147304. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  147305. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147306. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147307. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147308. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147309. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147310. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  147311. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147312. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147313. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147314. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147315. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147316. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147317. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147318. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147319. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147320. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147321. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147322. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  147323. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  147324. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  147325. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  147326. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  147327. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  147328. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147329. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147330. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  147331. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147332. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  147333. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147334. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  147335. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  147336. 13,
  147337. };
  147338. static float _vq_quantthresh__44u4__p4_0[] = {
  147339. -1.5, -0.5, 0.5, 1.5,
  147340. };
  147341. static long _vq_quantmap__44u4__p4_0[] = {
  147342. 3, 1, 0, 2, 4,
  147343. };
  147344. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  147345. _vq_quantthresh__44u4__p4_0,
  147346. _vq_quantmap__44u4__p4_0,
  147347. 5,
  147348. 5
  147349. };
  147350. static static_codebook _44u4__p4_0 = {
  147351. 4, 625,
  147352. _vq_lengthlist__44u4__p4_0,
  147353. 1, -533725184, 1611661312, 3, 0,
  147354. _vq_quantlist__44u4__p4_0,
  147355. NULL,
  147356. &_vq_auxt__44u4__p4_0,
  147357. NULL,
  147358. 0
  147359. };
  147360. static long _vq_quantlist__44u4__p5_0[] = {
  147361. 4,
  147362. 3,
  147363. 5,
  147364. 2,
  147365. 6,
  147366. 1,
  147367. 7,
  147368. 0,
  147369. 8,
  147370. };
  147371. static long _vq_lengthlist__44u4__p5_0[] = {
  147372. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147373. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147374. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  147375. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147376. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  147377. 12,
  147378. };
  147379. static float _vq_quantthresh__44u4__p5_0[] = {
  147380. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147381. };
  147382. static long _vq_quantmap__44u4__p5_0[] = {
  147383. 7, 5, 3, 1, 0, 2, 4, 6,
  147384. 8,
  147385. };
  147386. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  147387. _vq_quantthresh__44u4__p5_0,
  147388. _vq_quantmap__44u4__p5_0,
  147389. 9,
  147390. 9
  147391. };
  147392. static static_codebook _44u4__p5_0 = {
  147393. 2, 81,
  147394. _vq_lengthlist__44u4__p5_0,
  147395. 1, -531628032, 1611661312, 4, 0,
  147396. _vq_quantlist__44u4__p5_0,
  147397. NULL,
  147398. &_vq_auxt__44u4__p5_0,
  147399. NULL,
  147400. 0
  147401. };
  147402. static long _vq_quantlist__44u4__p6_0[] = {
  147403. 6,
  147404. 5,
  147405. 7,
  147406. 4,
  147407. 8,
  147408. 3,
  147409. 9,
  147410. 2,
  147411. 10,
  147412. 1,
  147413. 11,
  147414. 0,
  147415. 12,
  147416. };
  147417. static long _vq_lengthlist__44u4__p6_0[] = {
  147418. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  147419. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147420. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147421. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147422. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  147423. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  147424. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  147425. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  147426. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  147427. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  147428. 16,16,16,17,17,18,17,20,21,
  147429. };
  147430. static float _vq_quantthresh__44u4__p6_0[] = {
  147431. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147432. 12.5, 17.5, 22.5, 27.5,
  147433. };
  147434. static long _vq_quantmap__44u4__p6_0[] = {
  147435. 11, 9, 7, 5, 3, 1, 0, 2,
  147436. 4, 6, 8, 10, 12,
  147437. };
  147438. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  147439. _vq_quantthresh__44u4__p6_0,
  147440. _vq_quantmap__44u4__p6_0,
  147441. 13,
  147442. 13
  147443. };
  147444. static static_codebook _44u4__p6_0 = {
  147445. 2, 169,
  147446. _vq_lengthlist__44u4__p6_0,
  147447. 1, -526516224, 1616117760, 4, 0,
  147448. _vq_quantlist__44u4__p6_0,
  147449. NULL,
  147450. &_vq_auxt__44u4__p6_0,
  147451. NULL,
  147452. 0
  147453. };
  147454. static long _vq_quantlist__44u4__p6_1[] = {
  147455. 2,
  147456. 1,
  147457. 3,
  147458. 0,
  147459. 4,
  147460. };
  147461. static long _vq_lengthlist__44u4__p6_1[] = {
  147462. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147463. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147464. };
  147465. static float _vq_quantthresh__44u4__p6_1[] = {
  147466. -1.5, -0.5, 0.5, 1.5,
  147467. };
  147468. static long _vq_quantmap__44u4__p6_1[] = {
  147469. 3, 1, 0, 2, 4,
  147470. };
  147471. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  147472. _vq_quantthresh__44u4__p6_1,
  147473. _vq_quantmap__44u4__p6_1,
  147474. 5,
  147475. 5
  147476. };
  147477. static static_codebook _44u4__p6_1 = {
  147478. 2, 25,
  147479. _vq_lengthlist__44u4__p6_1,
  147480. 1, -533725184, 1611661312, 3, 0,
  147481. _vq_quantlist__44u4__p6_1,
  147482. NULL,
  147483. &_vq_auxt__44u4__p6_1,
  147484. NULL,
  147485. 0
  147486. };
  147487. static long _vq_quantlist__44u4__p7_0[] = {
  147488. 6,
  147489. 5,
  147490. 7,
  147491. 4,
  147492. 8,
  147493. 3,
  147494. 9,
  147495. 2,
  147496. 10,
  147497. 1,
  147498. 11,
  147499. 0,
  147500. 12,
  147501. };
  147502. static long _vq_lengthlist__44u4__p7_0[] = {
  147503. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  147504. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  147505. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147506. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147507. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147508. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147510. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147513. 11,11,11,11,11,11,11,11,11,
  147514. };
  147515. static float _vq_quantthresh__44u4__p7_0[] = {
  147516. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  147517. 637.5, 892.5, 1147.5, 1402.5,
  147518. };
  147519. static long _vq_quantmap__44u4__p7_0[] = {
  147520. 11, 9, 7, 5, 3, 1, 0, 2,
  147521. 4, 6, 8, 10, 12,
  147522. };
  147523. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  147524. _vq_quantthresh__44u4__p7_0,
  147525. _vq_quantmap__44u4__p7_0,
  147526. 13,
  147527. 13
  147528. };
  147529. static static_codebook _44u4__p7_0 = {
  147530. 2, 169,
  147531. _vq_lengthlist__44u4__p7_0,
  147532. 1, -514332672, 1627381760, 4, 0,
  147533. _vq_quantlist__44u4__p7_0,
  147534. NULL,
  147535. &_vq_auxt__44u4__p7_0,
  147536. NULL,
  147537. 0
  147538. };
  147539. static long _vq_quantlist__44u4__p7_1[] = {
  147540. 7,
  147541. 6,
  147542. 8,
  147543. 5,
  147544. 9,
  147545. 4,
  147546. 10,
  147547. 3,
  147548. 11,
  147549. 2,
  147550. 12,
  147551. 1,
  147552. 13,
  147553. 0,
  147554. 14,
  147555. };
  147556. static long _vq_lengthlist__44u4__p7_1[] = {
  147557. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  147558. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  147559. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  147560. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  147561. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  147562. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  147563. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  147564. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  147565. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  147566. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  147567. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  147568. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  147569. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  147570. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  147571. 16,
  147572. };
  147573. static float _vq_quantthresh__44u4__p7_1[] = {
  147574. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147575. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147576. };
  147577. static long _vq_quantmap__44u4__p7_1[] = {
  147578. 13, 11, 9, 7, 5, 3, 1, 0,
  147579. 2, 4, 6, 8, 10, 12, 14,
  147580. };
  147581. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  147582. _vq_quantthresh__44u4__p7_1,
  147583. _vq_quantmap__44u4__p7_1,
  147584. 15,
  147585. 15
  147586. };
  147587. static static_codebook _44u4__p7_1 = {
  147588. 2, 225,
  147589. _vq_lengthlist__44u4__p7_1,
  147590. 1, -522338304, 1620115456, 4, 0,
  147591. _vq_quantlist__44u4__p7_1,
  147592. NULL,
  147593. &_vq_auxt__44u4__p7_1,
  147594. NULL,
  147595. 0
  147596. };
  147597. static long _vq_quantlist__44u4__p7_2[] = {
  147598. 8,
  147599. 7,
  147600. 9,
  147601. 6,
  147602. 10,
  147603. 5,
  147604. 11,
  147605. 4,
  147606. 12,
  147607. 3,
  147608. 13,
  147609. 2,
  147610. 14,
  147611. 1,
  147612. 15,
  147613. 0,
  147614. 16,
  147615. };
  147616. static long _vq_lengthlist__44u4__p7_2[] = {
  147617. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147618. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147619. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147620. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147621. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147622. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147623. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147624. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  147625. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  147626. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  147627. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147628. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  147629. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147630. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  147631. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  147632. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147633. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147634. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  147635. 10,
  147636. };
  147637. static float _vq_quantthresh__44u4__p7_2[] = {
  147638. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147639. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147640. };
  147641. static long _vq_quantmap__44u4__p7_2[] = {
  147642. 15, 13, 11, 9, 7, 5, 3, 1,
  147643. 0, 2, 4, 6, 8, 10, 12, 14,
  147644. 16,
  147645. };
  147646. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  147647. _vq_quantthresh__44u4__p7_2,
  147648. _vq_quantmap__44u4__p7_2,
  147649. 17,
  147650. 17
  147651. };
  147652. static static_codebook _44u4__p7_2 = {
  147653. 2, 289,
  147654. _vq_lengthlist__44u4__p7_2,
  147655. 1, -529530880, 1611661312, 5, 0,
  147656. _vq_quantlist__44u4__p7_2,
  147657. NULL,
  147658. &_vq_auxt__44u4__p7_2,
  147659. NULL,
  147660. 0
  147661. };
  147662. static long _huff_lengthlist__44u4__short[] = {
  147663. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  147664. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  147665. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  147666. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  147667. };
  147668. static static_codebook _huff_book__44u4__short = {
  147669. 2, 64,
  147670. _huff_lengthlist__44u4__short,
  147671. 0, 0, 0, 0, 0,
  147672. NULL,
  147673. NULL,
  147674. NULL,
  147675. NULL,
  147676. 0
  147677. };
  147678. static long _huff_lengthlist__44u5__long[] = {
  147679. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  147680. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  147681. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  147682. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  147683. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  147684. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  147685. 14, 8, 7, 8,
  147686. };
  147687. static static_codebook _huff_book__44u5__long = {
  147688. 2, 100,
  147689. _huff_lengthlist__44u5__long,
  147690. 0, 0, 0, 0, 0,
  147691. NULL,
  147692. NULL,
  147693. NULL,
  147694. NULL,
  147695. 0
  147696. };
  147697. static long _vq_quantlist__44u5__p1_0[] = {
  147698. 1,
  147699. 0,
  147700. 2,
  147701. };
  147702. static long _vq_lengthlist__44u5__p1_0[] = {
  147703. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  147704. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  147705. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  147706. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  147707. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  147708. 12,
  147709. };
  147710. static float _vq_quantthresh__44u5__p1_0[] = {
  147711. -0.5, 0.5,
  147712. };
  147713. static long _vq_quantmap__44u5__p1_0[] = {
  147714. 1, 0, 2,
  147715. };
  147716. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  147717. _vq_quantthresh__44u5__p1_0,
  147718. _vq_quantmap__44u5__p1_0,
  147719. 3,
  147720. 3
  147721. };
  147722. static static_codebook _44u5__p1_0 = {
  147723. 4, 81,
  147724. _vq_lengthlist__44u5__p1_0,
  147725. 1, -535822336, 1611661312, 2, 0,
  147726. _vq_quantlist__44u5__p1_0,
  147727. NULL,
  147728. &_vq_auxt__44u5__p1_0,
  147729. NULL,
  147730. 0
  147731. };
  147732. static long _vq_quantlist__44u5__p2_0[] = {
  147733. 1,
  147734. 0,
  147735. 2,
  147736. };
  147737. static long _vq_lengthlist__44u5__p2_0[] = {
  147738. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  147739. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  147740. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  147741. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  147742. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  147743. 9,
  147744. };
  147745. static float _vq_quantthresh__44u5__p2_0[] = {
  147746. -0.5, 0.5,
  147747. };
  147748. static long _vq_quantmap__44u5__p2_0[] = {
  147749. 1, 0, 2,
  147750. };
  147751. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  147752. _vq_quantthresh__44u5__p2_0,
  147753. _vq_quantmap__44u5__p2_0,
  147754. 3,
  147755. 3
  147756. };
  147757. static static_codebook _44u5__p2_0 = {
  147758. 4, 81,
  147759. _vq_lengthlist__44u5__p2_0,
  147760. 1, -535822336, 1611661312, 2, 0,
  147761. _vq_quantlist__44u5__p2_0,
  147762. NULL,
  147763. &_vq_auxt__44u5__p2_0,
  147764. NULL,
  147765. 0
  147766. };
  147767. static long _vq_quantlist__44u5__p3_0[] = {
  147768. 2,
  147769. 1,
  147770. 3,
  147771. 0,
  147772. 4,
  147773. };
  147774. static long _vq_lengthlist__44u5__p3_0[] = {
  147775. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  147776. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  147777. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  147778. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  147779. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  147780. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  147781. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  147782. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  147783. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  147784. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  147785. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  147786. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  147787. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  147788. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  147789. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  147790. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  147791. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147792. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  147793. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  147794. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  147795. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  147796. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  147797. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  147798. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  147799. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  147800. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  147801. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  147802. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  147803. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  147804. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  147805. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  147806. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  147807. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  147808. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  147809. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  147810. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  147811. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  147812. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  147813. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  147814. 0,
  147815. };
  147816. static float _vq_quantthresh__44u5__p3_0[] = {
  147817. -1.5, -0.5, 0.5, 1.5,
  147818. };
  147819. static long _vq_quantmap__44u5__p3_0[] = {
  147820. 3, 1, 0, 2, 4,
  147821. };
  147822. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  147823. _vq_quantthresh__44u5__p3_0,
  147824. _vq_quantmap__44u5__p3_0,
  147825. 5,
  147826. 5
  147827. };
  147828. static static_codebook _44u5__p3_0 = {
  147829. 4, 625,
  147830. _vq_lengthlist__44u5__p3_0,
  147831. 1, -533725184, 1611661312, 3, 0,
  147832. _vq_quantlist__44u5__p3_0,
  147833. NULL,
  147834. &_vq_auxt__44u5__p3_0,
  147835. NULL,
  147836. 0
  147837. };
  147838. static long _vq_quantlist__44u5__p4_0[] = {
  147839. 2,
  147840. 1,
  147841. 3,
  147842. 0,
  147843. 4,
  147844. };
  147845. static long _vq_lengthlist__44u5__p4_0[] = {
  147846. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  147847. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  147848. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  147849. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  147850. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  147851. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  147852. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  147853. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  147854. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  147855. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  147856. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  147857. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147858. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  147859. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  147860. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  147861. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  147862. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  147863. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147864. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  147865. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  147866. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  147867. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  147868. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  147869. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  147870. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  147871. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  147872. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  147873. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  147874. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  147875. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  147876. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  147877. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  147878. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  147879. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  147880. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  147881. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  147882. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  147883. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  147884. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  147885. 12,
  147886. };
  147887. static float _vq_quantthresh__44u5__p4_0[] = {
  147888. -1.5, -0.5, 0.5, 1.5,
  147889. };
  147890. static long _vq_quantmap__44u5__p4_0[] = {
  147891. 3, 1, 0, 2, 4,
  147892. };
  147893. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  147894. _vq_quantthresh__44u5__p4_0,
  147895. _vq_quantmap__44u5__p4_0,
  147896. 5,
  147897. 5
  147898. };
  147899. static static_codebook _44u5__p4_0 = {
  147900. 4, 625,
  147901. _vq_lengthlist__44u5__p4_0,
  147902. 1, -533725184, 1611661312, 3, 0,
  147903. _vq_quantlist__44u5__p4_0,
  147904. NULL,
  147905. &_vq_auxt__44u5__p4_0,
  147906. NULL,
  147907. 0
  147908. };
  147909. static long _vq_quantlist__44u5__p5_0[] = {
  147910. 4,
  147911. 3,
  147912. 5,
  147913. 2,
  147914. 6,
  147915. 1,
  147916. 7,
  147917. 0,
  147918. 8,
  147919. };
  147920. static long _vq_lengthlist__44u5__p5_0[] = {
  147921. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  147922. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  147923. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  147924. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  147925. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  147926. 14,
  147927. };
  147928. static float _vq_quantthresh__44u5__p5_0[] = {
  147929. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147930. };
  147931. static long _vq_quantmap__44u5__p5_0[] = {
  147932. 7, 5, 3, 1, 0, 2, 4, 6,
  147933. 8,
  147934. };
  147935. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  147936. _vq_quantthresh__44u5__p5_0,
  147937. _vq_quantmap__44u5__p5_0,
  147938. 9,
  147939. 9
  147940. };
  147941. static static_codebook _44u5__p5_0 = {
  147942. 2, 81,
  147943. _vq_lengthlist__44u5__p5_0,
  147944. 1, -531628032, 1611661312, 4, 0,
  147945. _vq_quantlist__44u5__p5_0,
  147946. NULL,
  147947. &_vq_auxt__44u5__p5_0,
  147948. NULL,
  147949. 0
  147950. };
  147951. static long _vq_quantlist__44u5__p6_0[] = {
  147952. 4,
  147953. 3,
  147954. 5,
  147955. 2,
  147956. 6,
  147957. 1,
  147958. 7,
  147959. 0,
  147960. 8,
  147961. };
  147962. static long _vq_lengthlist__44u5__p6_0[] = {
  147963. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  147964. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147965. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  147966. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  147967. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  147968. 11,
  147969. };
  147970. static float _vq_quantthresh__44u5__p6_0[] = {
  147971. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147972. };
  147973. static long _vq_quantmap__44u5__p6_0[] = {
  147974. 7, 5, 3, 1, 0, 2, 4, 6,
  147975. 8,
  147976. };
  147977. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  147978. _vq_quantthresh__44u5__p6_0,
  147979. _vq_quantmap__44u5__p6_0,
  147980. 9,
  147981. 9
  147982. };
  147983. static static_codebook _44u5__p6_0 = {
  147984. 2, 81,
  147985. _vq_lengthlist__44u5__p6_0,
  147986. 1, -531628032, 1611661312, 4, 0,
  147987. _vq_quantlist__44u5__p6_0,
  147988. NULL,
  147989. &_vq_auxt__44u5__p6_0,
  147990. NULL,
  147991. 0
  147992. };
  147993. static long _vq_quantlist__44u5__p7_0[] = {
  147994. 1,
  147995. 0,
  147996. 2,
  147997. };
  147998. static long _vq_lengthlist__44u5__p7_0[] = {
  147999. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148000. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148001. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148002. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148003. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148004. 12,
  148005. };
  148006. static float _vq_quantthresh__44u5__p7_0[] = {
  148007. -5.5, 5.5,
  148008. };
  148009. static long _vq_quantmap__44u5__p7_0[] = {
  148010. 1, 0, 2,
  148011. };
  148012. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148013. _vq_quantthresh__44u5__p7_0,
  148014. _vq_quantmap__44u5__p7_0,
  148015. 3,
  148016. 3
  148017. };
  148018. static static_codebook _44u5__p7_0 = {
  148019. 4, 81,
  148020. _vq_lengthlist__44u5__p7_0,
  148021. 1, -529137664, 1618345984, 2, 0,
  148022. _vq_quantlist__44u5__p7_0,
  148023. NULL,
  148024. &_vq_auxt__44u5__p7_0,
  148025. NULL,
  148026. 0
  148027. };
  148028. static long _vq_quantlist__44u5__p7_1[] = {
  148029. 5,
  148030. 4,
  148031. 6,
  148032. 3,
  148033. 7,
  148034. 2,
  148035. 8,
  148036. 1,
  148037. 9,
  148038. 0,
  148039. 10,
  148040. };
  148041. static long _vq_lengthlist__44u5__p7_1[] = {
  148042. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148043. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148044. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148045. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148046. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148047. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148048. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148049. 9, 9, 9, 9, 9,10,10,10,10,
  148050. };
  148051. static float _vq_quantthresh__44u5__p7_1[] = {
  148052. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148053. 3.5, 4.5,
  148054. };
  148055. static long _vq_quantmap__44u5__p7_1[] = {
  148056. 9, 7, 5, 3, 1, 0, 2, 4,
  148057. 6, 8, 10,
  148058. };
  148059. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148060. _vq_quantthresh__44u5__p7_1,
  148061. _vq_quantmap__44u5__p7_1,
  148062. 11,
  148063. 11
  148064. };
  148065. static static_codebook _44u5__p7_1 = {
  148066. 2, 121,
  148067. _vq_lengthlist__44u5__p7_1,
  148068. 1, -531365888, 1611661312, 4, 0,
  148069. _vq_quantlist__44u5__p7_1,
  148070. NULL,
  148071. &_vq_auxt__44u5__p7_1,
  148072. NULL,
  148073. 0
  148074. };
  148075. static long _vq_quantlist__44u5__p8_0[] = {
  148076. 5,
  148077. 4,
  148078. 6,
  148079. 3,
  148080. 7,
  148081. 2,
  148082. 8,
  148083. 1,
  148084. 9,
  148085. 0,
  148086. 10,
  148087. };
  148088. static long _vq_lengthlist__44u5__p8_0[] = {
  148089. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148090. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148091. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148092. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148093. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148094. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148095. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148096. 12,13,13,14,14,14,14,15,15,
  148097. };
  148098. static float _vq_quantthresh__44u5__p8_0[] = {
  148099. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148100. 38.5, 49.5,
  148101. };
  148102. static long _vq_quantmap__44u5__p8_0[] = {
  148103. 9, 7, 5, 3, 1, 0, 2, 4,
  148104. 6, 8, 10,
  148105. };
  148106. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148107. _vq_quantthresh__44u5__p8_0,
  148108. _vq_quantmap__44u5__p8_0,
  148109. 11,
  148110. 11
  148111. };
  148112. static static_codebook _44u5__p8_0 = {
  148113. 2, 121,
  148114. _vq_lengthlist__44u5__p8_0,
  148115. 1, -524582912, 1618345984, 4, 0,
  148116. _vq_quantlist__44u5__p8_0,
  148117. NULL,
  148118. &_vq_auxt__44u5__p8_0,
  148119. NULL,
  148120. 0
  148121. };
  148122. static long _vq_quantlist__44u5__p8_1[] = {
  148123. 5,
  148124. 4,
  148125. 6,
  148126. 3,
  148127. 7,
  148128. 2,
  148129. 8,
  148130. 1,
  148131. 9,
  148132. 0,
  148133. 10,
  148134. };
  148135. static long _vq_lengthlist__44u5__p8_1[] = {
  148136. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  148137. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  148138. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  148139. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148140. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  148141. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148142. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148143. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148144. };
  148145. static float _vq_quantthresh__44u5__p8_1[] = {
  148146. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148147. 3.5, 4.5,
  148148. };
  148149. static long _vq_quantmap__44u5__p8_1[] = {
  148150. 9, 7, 5, 3, 1, 0, 2, 4,
  148151. 6, 8, 10,
  148152. };
  148153. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  148154. _vq_quantthresh__44u5__p8_1,
  148155. _vq_quantmap__44u5__p8_1,
  148156. 11,
  148157. 11
  148158. };
  148159. static static_codebook _44u5__p8_1 = {
  148160. 2, 121,
  148161. _vq_lengthlist__44u5__p8_1,
  148162. 1, -531365888, 1611661312, 4, 0,
  148163. _vq_quantlist__44u5__p8_1,
  148164. NULL,
  148165. &_vq_auxt__44u5__p8_1,
  148166. NULL,
  148167. 0
  148168. };
  148169. static long _vq_quantlist__44u5__p9_0[] = {
  148170. 6,
  148171. 5,
  148172. 7,
  148173. 4,
  148174. 8,
  148175. 3,
  148176. 9,
  148177. 2,
  148178. 10,
  148179. 1,
  148180. 11,
  148181. 0,
  148182. 12,
  148183. };
  148184. static long _vq_lengthlist__44u5__p9_0[] = {
  148185. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  148186. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  148187. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  148188. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  148189. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148190. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148191. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148192. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148193. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  148194. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148195. 12,12,12,12,12,12,12,12,12,
  148196. };
  148197. static float _vq_quantthresh__44u5__p9_0[] = {
  148198. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148199. 637.5, 892.5, 1147.5, 1402.5,
  148200. };
  148201. static long _vq_quantmap__44u5__p9_0[] = {
  148202. 11, 9, 7, 5, 3, 1, 0, 2,
  148203. 4, 6, 8, 10, 12,
  148204. };
  148205. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  148206. _vq_quantthresh__44u5__p9_0,
  148207. _vq_quantmap__44u5__p9_0,
  148208. 13,
  148209. 13
  148210. };
  148211. static static_codebook _44u5__p9_0 = {
  148212. 2, 169,
  148213. _vq_lengthlist__44u5__p9_0,
  148214. 1, -514332672, 1627381760, 4, 0,
  148215. _vq_quantlist__44u5__p9_0,
  148216. NULL,
  148217. &_vq_auxt__44u5__p9_0,
  148218. NULL,
  148219. 0
  148220. };
  148221. static long _vq_quantlist__44u5__p9_1[] = {
  148222. 7,
  148223. 6,
  148224. 8,
  148225. 5,
  148226. 9,
  148227. 4,
  148228. 10,
  148229. 3,
  148230. 11,
  148231. 2,
  148232. 12,
  148233. 1,
  148234. 13,
  148235. 0,
  148236. 14,
  148237. };
  148238. static long _vq_lengthlist__44u5__p9_1[] = {
  148239. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  148240. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  148241. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  148242. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  148243. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  148244. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  148245. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  148246. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  148247. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  148248. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  148249. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  148250. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  148251. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  148252. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  148253. 14,
  148254. };
  148255. static float _vq_quantthresh__44u5__p9_1[] = {
  148256. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148257. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148258. };
  148259. static long _vq_quantmap__44u5__p9_1[] = {
  148260. 13, 11, 9, 7, 5, 3, 1, 0,
  148261. 2, 4, 6, 8, 10, 12, 14,
  148262. };
  148263. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  148264. _vq_quantthresh__44u5__p9_1,
  148265. _vq_quantmap__44u5__p9_1,
  148266. 15,
  148267. 15
  148268. };
  148269. static static_codebook _44u5__p9_1 = {
  148270. 2, 225,
  148271. _vq_lengthlist__44u5__p9_1,
  148272. 1, -522338304, 1620115456, 4, 0,
  148273. _vq_quantlist__44u5__p9_1,
  148274. NULL,
  148275. &_vq_auxt__44u5__p9_1,
  148276. NULL,
  148277. 0
  148278. };
  148279. static long _vq_quantlist__44u5__p9_2[] = {
  148280. 8,
  148281. 7,
  148282. 9,
  148283. 6,
  148284. 10,
  148285. 5,
  148286. 11,
  148287. 4,
  148288. 12,
  148289. 3,
  148290. 13,
  148291. 2,
  148292. 14,
  148293. 1,
  148294. 15,
  148295. 0,
  148296. 16,
  148297. };
  148298. static long _vq_lengthlist__44u5__p9_2[] = {
  148299. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148300. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148301. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148302. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148303. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148304. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148305. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148306. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148307. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148308. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  148309. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  148310. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148311. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148312. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148313. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148314. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148315. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148316. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  148317. 10,
  148318. };
  148319. static float _vq_quantthresh__44u5__p9_2[] = {
  148320. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148321. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148322. };
  148323. static long _vq_quantmap__44u5__p9_2[] = {
  148324. 15, 13, 11, 9, 7, 5, 3, 1,
  148325. 0, 2, 4, 6, 8, 10, 12, 14,
  148326. 16,
  148327. };
  148328. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  148329. _vq_quantthresh__44u5__p9_2,
  148330. _vq_quantmap__44u5__p9_2,
  148331. 17,
  148332. 17
  148333. };
  148334. static static_codebook _44u5__p9_2 = {
  148335. 2, 289,
  148336. _vq_lengthlist__44u5__p9_2,
  148337. 1, -529530880, 1611661312, 5, 0,
  148338. _vq_quantlist__44u5__p9_2,
  148339. NULL,
  148340. &_vq_auxt__44u5__p9_2,
  148341. NULL,
  148342. 0
  148343. };
  148344. static long _huff_lengthlist__44u5__short[] = {
  148345. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  148346. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  148347. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  148348. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  148349. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  148350. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  148351. 6, 8,15,17,
  148352. };
  148353. static static_codebook _huff_book__44u5__short = {
  148354. 2, 100,
  148355. _huff_lengthlist__44u5__short,
  148356. 0, 0, 0, 0, 0,
  148357. NULL,
  148358. NULL,
  148359. NULL,
  148360. NULL,
  148361. 0
  148362. };
  148363. static long _huff_lengthlist__44u6__long[] = {
  148364. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  148365. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  148366. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  148367. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  148368. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  148369. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  148370. 13, 8, 7, 7,
  148371. };
  148372. static static_codebook _huff_book__44u6__long = {
  148373. 2, 100,
  148374. _huff_lengthlist__44u6__long,
  148375. 0, 0, 0, 0, 0,
  148376. NULL,
  148377. NULL,
  148378. NULL,
  148379. NULL,
  148380. 0
  148381. };
  148382. static long _vq_quantlist__44u6__p1_0[] = {
  148383. 1,
  148384. 0,
  148385. 2,
  148386. };
  148387. static long _vq_lengthlist__44u6__p1_0[] = {
  148388. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148389. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148390. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148391. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  148392. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148393. 12,
  148394. };
  148395. static float _vq_quantthresh__44u6__p1_0[] = {
  148396. -0.5, 0.5,
  148397. };
  148398. static long _vq_quantmap__44u6__p1_0[] = {
  148399. 1, 0, 2,
  148400. };
  148401. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  148402. _vq_quantthresh__44u6__p1_0,
  148403. _vq_quantmap__44u6__p1_0,
  148404. 3,
  148405. 3
  148406. };
  148407. static static_codebook _44u6__p1_0 = {
  148408. 4, 81,
  148409. _vq_lengthlist__44u6__p1_0,
  148410. 1, -535822336, 1611661312, 2, 0,
  148411. _vq_quantlist__44u6__p1_0,
  148412. NULL,
  148413. &_vq_auxt__44u6__p1_0,
  148414. NULL,
  148415. 0
  148416. };
  148417. static long _vq_quantlist__44u6__p2_0[] = {
  148418. 1,
  148419. 0,
  148420. 2,
  148421. };
  148422. static long _vq_lengthlist__44u6__p2_0[] = {
  148423. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148424. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148425. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  148426. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148427. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148428. 9,
  148429. };
  148430. static float _vq_quantthresh__44u6__p2_0[] = {
  148431. -0.5, 0.5,
  148432. };
  148433. static long _vq_quantmap__44u6__p2_0[] = {
  148434. 1, 0, 2,
  148435. };
  148436. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  148437. _vq_quantthresh__44u6__p2_0,
  148438. _vq_quantmap__44u6__p2_0,
  148439. 3,
  148440. 3
  148441. };
  148442. static static_codebook _44u6__p2_0 = {
  148443. 4, 81,
  148444. _vq_lengthlist__44u6__p2_0,
  148445. 1, -535822336, 1611661312, 2, 0,
  148446. _vq_quantlist__44u6__p2_0,
  148447. NULL,
  148448. &_vq_auxt__44u6__p2_0,
  148449. NULL,
  148450. 0
  148451. };
  148452. static long _vq_quantlist__44u6__p3_0[] = {
  148453. 2,
  148454. 1,
  148455. 3,
  148456. 0,
  148457. 4,
  148458. };
  148459. static long _vq_lengthlist__44u6__p3_0[] = {
  148460. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148461. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  148462. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148463. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  148464. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  148465. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  148466. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  148467. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  148468. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  148469. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148470. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  148471. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148472. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  148473. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  148474. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  148475. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  148476. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148477. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  148478. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  148479. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  148480. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  148481. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  148482. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  148483. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  148484. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  148485. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  148486. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  148487. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  148488. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  148489. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  148490. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  148491. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  148492. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  148493. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  148494. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  148495. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  148496. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  148497. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  148498. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  148499. 19,
  148500. };
  148501. static float _vq_quantthresh__44u6__p3_0[] = {
  148502. -1.5, -0.5, 0.5, 1.5,
  148503. };
  148504. static long _vq_quantmap__44u6__p3_0[] = {
  148505. 3, 1, 0, 2, 4,
  148506. };
  148507. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  148508. _vq_quantthresh__44u6__p3_0,
  148509. _vq_quantmap__44u6__p3_0,
  148510. 5,
  148511. 5
  148512. };
  148513. static static_codebook _44u6__p3_0 = {
  148514. 4, 625,
  148515. _vq_lengthlist__44u6__p3_0,
  148516. 1, -533725184, 1611661312, 3, 0,
  148517. _vq_quantlist__44u6__p3_0,
  148518. NULL,
  148519. &_vq_auxt__44u6__p3_0,
  148520. NULL,
  148521. 0
  148522. };
  148523. static long _vq_quantlist__44u6__p4_0[] = {
  148524. 2,
  148525. 1,
  148526. 3,
  148527. 0,
  148528. 4,
  148529. };
  148530. static long _vq_lengthlist__44u6__p4_0[] = {
  148531. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148532. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148533. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  148534. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  148535. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  148536. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  148537. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148538. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  148539. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  148540. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  148541. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  148542. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  148543. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148544. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  148545. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  148546. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  148547. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  148548. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  148549. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148550. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  148551. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  148552. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  148553. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  148554. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  148555. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  148556. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  148557. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  148558. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  148559. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  148560. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  148561. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  148562. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148563. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  148564. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  148565. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  148566. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  148567. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  148568. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  148569. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  148570. 13,
  148571. };
  148572. static float _vq_quantthresh__44u6__p4_0[] = {
  148573. -1.5, -0.5, 0.5, 1.5,
  148574. };
  148575. static long _vq_quantmap__44u6__p4_0[] = {
  148576. 3, 1, 0, 2, 4,
  148577. };
  148578. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  148579. _vq_quantthresh__44u6__p4_0,
  148580. _vq_quantmap__44u6__p4_0,
  148581. 5,
  148582. 5
  148583. };
  148584. static static_codebook _44u6__p4_0 = {
  148585. 4, 625,
  148586. _vq_lengthlist__44u6__p4_0,
  148587. 1, -533725184, 1611661312, 3, 0,
  148588. _vq_quantlist__44u6__p4_0,
  148589. NULL,
  148590. &_vq_auxt__44u6__p4_0,
  148591. NULL,
  148592. 0
  148593. };
  148594. static long _vq_quantlist__44u6__p5_0[] = {
  148595. 4,
  148596. 3,
  148597. 5,
  148598. 2,
  148599. 6,
  148600. 1,
  148601. 7,
  148602. 0,
  148603. 8,
  148604. };
  148605. static long _vq_lengthlist__44u6__p5_0[] = {
  148606. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148607. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  148608. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148609. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  148610. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  148611. 14,
  148612. };
  148613. static float _vq_quantthresh__44u6__p5_0[] = {
  148614. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148615. };
  148616. static long _vq_quantmap__44u6__p5_0[] = {
  148617. 7, 5, 3, 1, 0, 2, 4, 6,
  148618. 8,
  148619. };
  148620. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  148621. _vq_quantthresh__44u6__p5_0,
  148622. _vq_quantmap__44u6__p5_0,
  148623. 9,
  148624. 9
  148625. };
  148626. static static_codebook _44u6__p5_0 = {
  148627. 2, 81,
  148628. _vq_lengthlist__44u6__p5_0,
  148629. 1, -531628032, 1611661312, 4, 0,
  148630. _vq_quantlist__44u6__p5_0,
  148631. NULL,
  148632. &_vq_auxt__44u6__p5_0,
  148633. NULL,
  148634. 0
  148635. };
  148636. static long _vq_quantlist__44u6__p6_0[] = {
  148637. 4,
  148638. 3,
  148639. 5,
  148640. 2,
  148641. 6,
  148642. 1,
  148643. 7,
  148644. 0,
  148645. 8,
  148646. };
  148647. static long _vq_lengthlist__44u6__p6_0[] = {
  148648. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148649. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  148650. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  148651. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  148652. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  148653. 12,
  148654. };
  148655. static float _vq_quantthresh__44u6__p6_0[] = {
  148656. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148657. };
  148658. static long _vq_quantmap__44u6__p6_0[] = {
  148659. 7, 5, 3, 1, 0, 2, 4, 6,
  148660. 8,
  148661. };
  148662. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  148663. _vq_quantthresh__44u6__p6_0,
  148664. _vq_quantmap__44u6__p6_0,
  148665. 9,
  148666. 9
  148667. };
  148668. static static_codebook _44u6__p6_0 = {
  148669. 2, 81,
  148670. _vq_lengthlist__44u6__p6_0,
  148671. 1, -531628032, 1611661312, 4, 0,
  148672. _vq_quantlist__44u6__p6_0,
  148673. NULL,
  148674. &_vq_auxt__44u6__p6_0,
  148675. NULL,
  148676. 0
  148677. };
  148678. static long _vq_quantlist__44u6__p7_0[] = {
  148679. 1,
  148680. 0,
  148681. 2,
  148682. };
  148683. static long _vq_lengthlist__44u6__p7_0[] = {
  148684. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  148685. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  148686. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  148687. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  148688. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  148689. 10,
  148690. };
  148691. static float _vq_quantthresh__44u6__p7_0[] = {
  148692. -5.5, 5.5,
  148693. };
  148694. static long _vq_quantmap__44u6__p7_0[] = {
  148695. 1, 0, 2,
  148696. };
  148697. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  148698. _vq_quantthresh__44u6__p7_0,
  148699. _vq_quantmap__44u6__p7_0,
  148700. 3,
  148701. 3
  148702. };
  148703. static static_codebook _44u6__p7_0 = {
  148704. 4, 81,
  148705. _vq_lengthlist__44u6__p7_0,
  148706. 1, -529137664, 1618345984, 2, 0,
  148707. _vq_quantlist__44u6__p7_0,
  148708. NULL,
  148709. &_vq_auxt__44u6__p7_0,
  148710. NULL,
  148711. 0
  148712. };
  148713. static long _vq_quantlist__44u6__p7_1[] = {
  148714. 5,
  148715. 4,
  148716. 6,
  148717. 3,
  148718. 7,
  148719. 2,
  148720. 8,
  148721. 1,
  148722. 9,
  148723. 0,
  148724. 10,
  148725. };
  148726. static long _vq_lengthlist__44u6__p7_1[] = {
  148727. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  148728. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  148729. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  148730. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  148731. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  148732. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  148733. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  148734. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148735. };
  148736. static float _vq_quantthresh__44u6__p7_1[] = {
  148737. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148738. 3.5, 4.5,
  148739. };
  148740. static long _vq_quantmap__44u6__p7_1[] = {
  148741. 9, 7, 5, 3, 1, 0, 2, 4,
  148742. 6, 8, 10,
  148743. };
  148744. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  148745. _vq_quantthresh__44u6__p7_1,
  148746. _vq_quantmap__44u6__p7_1,
  148747. 11,
  148748. 11
  148749. };
  148750. static static_codebook _44u6__p7_1 = {
  148751. 2, 121,
  148752. _vq_lengthlist__44u6__p7_1,
  148753. 1, -531365888, 1611661312, 4, 0,
  148754. _vq_quantlist__44u6__p7_1,
  148755. NULL,
  148756. &_vq_auxt__44u6__p7_1,
  148757. NULL,
  148758. 0
  148759. };
  148760. static long _vq_quantlist__44u6__p8_0[] = {
  148761. 5,
  148762. 4,
  148763. 6,
  148764. 3,
  148765. 7,
  148766. 2,
  148767. 8,
  148768. 1,
  148769. 9,
  148770. 0,
  148771. 10,
  148772. };
  148773. static long _vq_lengthlist__44u6__p8_0[] = {
  148774. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148775. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148776. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  148777. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  148778. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  148779. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  148780. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  148781. 12,13,13,14,14,14,15,15,15,
  148782. };
  148783. static float _vq_quantthresh__44u6__p8_0[] = {
  148784. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148785. 38.5, 49.5,
  148786. };
  148787. static long _vq_quantmap__44u6__p8_0[] = {
  148788. 9, 7, 5, 3, 1, 0, 2, 4,
  148789. 6, 8, 10,
  148790. };
  148791. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  148792. _vq_quantthresh__44u6__p8_0,
  148793. _vq_quantmap__44u6__p8_0,
  148794. 11,
  148795. 11
  148796. };
  148797. static static_codebook _44u6__p8_0 = {
  148798. 2, 121,
  148799. _vq_lengthlist__44u6__p8_0,
  148800. 1, -524582912, 1618345984, 4, 0,
  148801. _vq_quantlist__44u6__p8_0,
  148802. NULL,
  148803. &_vq_auxt__44u6__p8_0,
  148804. NULL,
  148805. 0
  148806. };
  148807. static long _vq_quantlist__44u6__p8_1[] = {
  148808. 5,
  148809. 4,
  148810. 6,
  148811. 3,
  148812. 7,
  148813. 2,
  148814. 8,
  148815. 1,
  148816. 9,
  148817. 0,
  148818. 10,
  148819. };
  148820. static long _vq_lengthlist__44u6__p8_1[] = {
  148821. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  148822. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  148823. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  148824. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148825. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  148826. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148827. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  148828. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148829. };
  148830. static float _vq_quantthresh__44u6__p8_1[] = {
  148831. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148832. 3.5, 4.5,
  148833. };
  148834. static long _vq_quantmap__44u6__p8_1[] = {
  148835. 9, 7, 5, 3, 1, 0, 2, 4,
  148836. 6, 8, 10,
  148837. };
  148838. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  148839. _vq_quantthresh__44u6__p8_1,
  148840. _vq_quantmap__44u6__p8_1,
  148841. 11,
  148842. 11
  148843. };
  148844. static static_codebook _44u6__p8_1 = {
  148845. 2, 121,
  148846. _vq_lengthlist__44u6__p8_1,
  148847. 1, -531365888, 1611661312, 4, 0,
  148848. _vq_quantlist__44u6__p8_1,
  148849. NULL,
  148850. &_vq_auxt__44u6__p8_1,
  148851. NULL,
  148852. 0
  148853. };
  148854. static long _vq_quantlist__44u6__p9_0[] = {
  148855. 7,
  148856. 6,
  148857. 8,
  148858. 5,
  148859. 9,
  148860. 4,
  148861. 10,
  148862. 3,
  148863. 11,
  148864. 2,
  148865. 12,
  148866. 1,
  148867. 13,
  148868. 0,
  148869. 14,
  148870. };
  148871. static long _vq_lengthlist__44u6__p9_0[] = {
  148872. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  148873. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  148874. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  148875. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  148876. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  148877. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  148878. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  148879. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  148880. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  148881. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  148882. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  148883. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  148884. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  148885. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  148886. 14,
  148887. };
  148888. static float _vq_quantthresh__44u6__p9_0[] = {
  148889. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  148890. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  148891. };
  148892. static long _vq_quantmap__44u6__p9_0[] = {
  148893. 13, 11, 9, 7, 5, 3, 1, 0,
  148894. 2, 4, 6, 8, 10, 12, 14,
  148895. };
  148896. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  148897. _vq_quantthresh__44u6__p9_0,
  148898. _vq_quantmap__44u6__p9_0,
  148899. 15,
  148900. 15
  148901. };
  148902. static static_codebook _44u6__p9_0 = {
  148903. 2, 225,
  148904. _vq_lengthlist__44u6__p9_0,
  148905. 1, -514071552, 1627381760, 4, 0,
  148906. _vq_quantlist__44u6__p9_0,
  148907. NULL,
  148908. &_vq_auxt__44u6__p9_0,
  148909. NULL,
  148910. 0
  148911. };
  148912. static long _vq_quantlist__44u6__p9_1[] = {
  148913. 7,
  148914. 6,
  148915. 8,
  148916. 5,
  148917. 9,
  148918. 4,
  148919. 10,
  148920. 3,
  148921. 11,
  148922. 2,
  148923. 12,
  148924. 1,
  148925. 13,
  148926. 0,
  148927. 14,
  148928. };
  148929. static long _vq_lengthlist__44u6__p9_1[] = {
  148930. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  148931. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  148932. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  148933. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  148934. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  148935. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  148936. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  148937. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  148938. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  148939. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  148940. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  148941. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  148942. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  148943. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  148944. 13,
  148945. };
  148946. static float _vq_quantthresh__44u6__p9_1[] = {
  148947. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148948. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148949. };
  148950. static long _vq_quantmap__44u6__p9_1[] = {
  148951. 13, 11, 9, 7, 5, 3, 1, 0,
  148952. 2, 4, 6, 8, 10, 12, 14,
  148953. };
  148954. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  148955. _vq_quantthresh__44u6__p9_1,
  148956. _vq_quantmap__44u6__p9_1,
  148957. 15,
  148958. 15
  148959. };
  148960. static static_codebook _44u6__p9_1 = {
  148961. 2, 225,
  148962. _vq_lengthlist__44u6__p9_1,
  148963. 1, -522338304, 1620115456, 4, 0,
  148964. _vq_quantlist__44u6__p9_1,
  148965. NULL,
  148966. &_vq_auxt__44u6__p9_1,
  148967. NULL,
  148968. 0
  148969. };
  148970. static long _vq_quantlist__44u6__p9_2[] = {
  148971. 8,
  148972. 7,
  148973. 9,
  148974. 6,
  148975. 10,
  148976. 5,
  148977. 11,
  148978. 4,
  148979. 12,
  148980. 3,
  148981. 13,
  148982. 2,
  148983. 14,
  148984. 1,
  148985. 15,
  148986. 0,
  148987. 16,
  148988. };
  148989. static long _vq_lengthlist__44u6__p9_2[] = {
  148990. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  148991. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  148992. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  148993. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148994. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148995. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148996. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148997. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148998. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  148999. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149000. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149001. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149002. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149003. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149004. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149005. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149006. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149007. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149008. 10,
  149009. };
  149010. static float _vq_quantthresh__44u6__p9_2[] = {
  149011. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149012. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149013. };
  149014. static long _vq_quantmap__44u6__p9_2[] = {
  149015. 15, 13, 11, 9, 7, 5, 3, 1,
  149016. 0, 2, 4, 6, 8, 10, 12, 14,
  149017. 16,
  149018. };
  149019. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149020. _vq_quantthresh__44u6__p9_2,
  149021. _vq_quantmap__44u6__p9_2,
  149022. 17,
  149023. 17
  149024. };
  149025. static static_codebook _44u6__p9_2 = {
  149026. 2, 289,
  149027. _vq_lengthlist__44u6__p9_2,
  149028. 1, -529530880, 1611661312, 5, 0,
  149029. _vq_quantlist__44u6__p9_2,
  149030. NULL,
  149031. &_vq_auxt__44u6__p9_2,
  149032. NULL,
  149033. 0
  149034. };
  149035. static long _huff_lengthlist__44u6__short[] = {
  149036. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149037. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149038. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149039. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149040. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149041. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149042. 7, 6, 9,16,
  149043. };
  149044. static static_codebook _huff_book__44u6__short = {
  149045. 2, 100,
  149046. _huff_lengthlist__44u6__short,
  149047. 0, 0, 0, 0, 0,
  149048. NULL,
  149049. NULL,
  149050. NULL,
  149051. NULL,
  149052. 0
  149053. };
  149054. static long _huff_lengthlist__44u7__long[] = {
  149055. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149056. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149057. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149058. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149059. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149060. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149061. 12, 8, 6, 7,
  149062. };
  149063. static static_codebook _huff_book__44u7__long = {
  149064. 2, 100,
  149065. _huff_lengthlist__44u7__long,
  149066. 0, 0, 0, 0, 0,
  149067. NULL,
  149068. NULL,
  149069. NULL,
  149070. NULL,
  149071. 0
  149072. };
  149073. static long _vq_quantlist__44u7__p1_0[] = {
  149074. 1,
  149075. 0,
  149076. 2,
  149077. };
  149078. static long _vq_lengthlist__44u7__p1_0[] = {
  149079. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149080. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149081. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149082. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149083. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149084. 12,
  149085. };
  149086. static float _vq_quantthresh__44u7__p1_0[] = {
  149087. -0.5, 0.5,
  149088. };
  149089. static long _vq_quantmap__44u7__p1_0[] = {
  149090. 1, 0, 2,
  149091. };
  149092. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149093. _vq_quantthresh__44u7__p1_0,
  149094. _vq_quantmap__44u7__p1_0,
  149095. 3,
  149096. 3
  149097. };
  149098. static static_codebook _44u7__p1_0 = {
  149099. 4, 81,
  149100. _vq_lengthlist__44u7__p1_0,
  149101. 1, -535822336, 1611661312, 2, 0,
  149102. _vq_quantlist__44u7__p1_0,
  149103. NULL,
  149104. &_vq_auxt__44u7__p1_0,
  149105. NULL,
  149106. 0
  149107. };
  149108. static long _vq_quantlist__44u7__p2_0[] = {
  149109. 1,
  149110. 0,
  149111. 2,
  149112. };
  149113. static long _vq_lengthlist__44u7__p2_0[] = {
  149114. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149115. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149116. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149117. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149118. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149119. 9,
  149120. };
  149121. static float _vq_quantthresh__44u7__p2_0[] = {
  149122. -0.5, 0.5,
  149123. };
  149124. static long _vq_quantmap__44u7__p2_0[] = {
  149125. 1, 0, 2,
  149126. };
  149127. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  149128. _vq_quantthresh__44u7__p2_0,
  149129. _vq_quantmap__44u7__p2_0,
  149130. 3,
  149131. 3
  149132. };
  149133. static static_codebook _44u7__p2_0 = {
  149134. 4, 81,
  149135. _vq_lengthlist__44u7__p2_0,
  149136. 1, -535822336, 1611661312, 2, 0,
  149137. _vq_quantlist__44u7__p2_0,
  149138. NULL,
  149139. &_vq_auxt__44u7__p2_0,
  149140. NULL,
  149141. 0
  149142. };
  149143. static long _vq_quantlist__44u7__p3_0[] = {
  149144. 2,
  149145. 1,
  149146. 3,
  149147. 0,
  149148. 4,
  149149. };
  149150. static long _vq_lengthlist__44u7__p3_0[] = {
  149151. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149152. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149153. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149154. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  149155. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  149156. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  149157. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149158. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  149159. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  149160. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  149161. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  149162. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  149163. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  149164. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  149165. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  149166. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  149167. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  149168. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149169. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  149170. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  149171. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  149172. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  149173. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  149174. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  149175. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  149176. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  149177. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  149178. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  149179. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  149180. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  149181. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  149182. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  149183. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  149184. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  149185. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  149186. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  149187. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  149188. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  149189. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  149190. 0,
  149191. };
  149192. static float _vq_quantthresh__44u7__p3_0[] = {
  149193. -1.5, -0.5, 0.5, 1.5,
  149194. };
  149195. static long _vq_quantmap__44u7__p3_0[] = {
  149196. 3, 1, 0, 2, 4,
  149197. };
  149198. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  149199. _vq_quantthresh__44u7__p3_0,
  149200. _vq_quantmap__44u7__p3_0,
  149201. 5,
  149202. 5
  149203. };
  149204. static static_codebook _44u7__p3_0 = {
  149205. 4, 625,
  149206. _vq_lengthlist__44u7__p3_0,
  149207. 1, -533725184, 1611661312, 3, 0,
  149208. _vq_quantlist__44u7__p3_0,
  149209. NULL,
  149210. &_vq_auxt__44u7__p3_0,
  149211. NULL,
  149212. 0
  149213. };
  149214. static long _vq_quantlist__44u7__p4_0[] = {
  149215. 2,
  149216. 1,
  149217. 3,
  149218. 0,
  149219. 4,
  149220. };
  149221. static long _vq_lengthlist__44u7__p4_0[] = {
  149222. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149223. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  149224. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  149225. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149226. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149227. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149228. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  149229. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  149230. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149231. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149232. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  149233. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149234. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149235. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  149236. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  149237. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149238. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  149239. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149240. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  149241. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  149242. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149243. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149244. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  149245. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149246. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  149247. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149248. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149249. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  149250. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  149251. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  149252. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  149253. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149254. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  149255. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149256. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  149257. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149258. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  149259. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  149260. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  149261. 14,
  149262. };
  149263. static float _vq_quantthresh__44u7__p4_0[] = {
  149264. -1.5, -0.5, 0.5, 1.5,
  149265. };
  149266. static long _vq_quantmap__44u7__p4_0[] = {
  149267. 3, 1, 0, 2, 4,
  149268. };
  149269. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  149270. _vq_quantthresh__44u7__p4_0,
  149271. _vq_quantmap__44u7__p4_0,
  149272. 5,
  149273. 5
  149274. };
  149275. static static_codebook _44u7__p4_0 = {
  149276. 4, 625,
  149277. _vq_lengthlist__44u7__p4_0,
  149278. 1, -533725184, 1611661312, 3, 0,
  149279. _vq_quantlist__44u7__p4_0,
  149280. NULL,
  149281. &_vq_auxt__44u7__p4_0,
  149282. NULL,
  149283. 0
  149284. };
  149285. static long _vq_quantlist__44u7__p5_0[] = {
  149286. 4,
  149287. 3,
  149288. 5,
  149289. 2,
  149290. 6,
  149291. 1,
  149292. 7,
  149293. 0,
  149294. 8,
  149295. };
  149296. static long _vq_lengthlist__44u7__p5_0[] = {
  149297. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149298. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  149299. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  149300. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  149301. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  149302. 14,
  149303. };
  149304. static float _vq_quantthresh__44u7__p5_0[] = {
  149305. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149306. };
  149307. static long _vq_quantmap__44u7__p5_0[] = {
  149308. 7, 5, 3, 1, 0, 2, 4, 6,
  149309. 8,
  149310. };
  149311. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  149312. _vq_quantthresh__44u7__p5_0,
  149313. _vq_quantmap__44u7__p5_0,
  149314. 9,
  149315. 9
  149316. };
  149317. static static_codebook _44u7__p5_0 = {
  149318. 2, 81,
  149319. _vq_lengthlist__44u7__p5_0,
  149320. 1, -531628032, 1611661312, 4, 0,
  149321. _vq_quantlist__44u7__p5_0,
  149322. NULL,
  149323. &_vq_auxt__44u7__p5_0,
  149324. NULL,
  149325. 0
  149326. };
  149327. static long _vq_quantlist__44u7__p6_0[] = {
  149328. 4,
  149329. 3,
  149330. 5,
  149331. 2,
  149332. 6,
  149333. 1,
  149334. 7,
  149335. 0,
  149336. 8,
  149337. };
  149338. static long _vq_lengthlist__44u7__p6_0[] = {
  149339. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  149340. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149341. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149342. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  149343. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  149344. 12,
  149345. };
  149346. static float _vq_quantthresh__44u7__p6_0[] = {
  149347. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149348. };
  149349. static long _vq_quantmap__44u7__p6_0[] = {
  149350. 7, 5, 3, 1, 0, 2, 4, 6,
  149351. 8,
  149352. };
  149353. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  149354. _vq_quantthresh__44u7__p6_0,
  149355. _vq_quantmap__44u7__p6_0,
  149356. 9,
  149357. 9
  149358. };
  149359. static static_codebook _44u7__p6_0 = {
  149360. 2, 81,
  149361. _vq_lengthlist__44u7__p6_0,
  149362. 1, -531628032, 1611661312, 4, 0,
  149363. _vq_quantlist__44u7__p6_0,
  149364. NULL,
  149365. &_vq_auxt__44u7__p6_0,
  149366. NULL,
  149367. 0
  149368. };
  149369. static long _vq_quantlist__44u7__p7_0[] = {
  149370. 1,
  149371. 0,
  149372. 2,
  149373. };
  149374. static long _vq_lengthlist__44u7__p7_0[] = {
  149375. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  149376. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  149377. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  149378. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  149379. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  149380. 10,
  149381. };
  149382. static float _vq_quantthresh__44u7__p7_0[] = {
  149383. -5.5, 5.5,
  149384. };
  149385. static long _vq_quantmap__44u7__p7_0[] = {
  149386. 1, 0, 2,
  149387. };
  149388. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  149389. _vq_quantthresh__44u7__p7_0,
  149390. _vq_quantmap__44u7__p7_0,
  149391. 3,
  149392. 3
  149393. };
  149394. static static_codebook _44u7__p7_0 = {
  149395. 4, 81,
  149396. _vq_lengthlist__44u7__p7_0,
  149397. 1, -529137664, 1618345984, 2, 0,
  149398. _vq_quantlist__44u7__p7_0,
  149399. NULL,
  149400. &_vq_auxt__44u7__p7_0,
  149401. NULL,
  149402. 0
  149403. };
  149404. static long _vq_quantlist__44u7__p7_1[] = {
  149405. 5,
  149406. 4,
  149407. 6,
  149408. 3,
  149409. 7,
  149410. 2,
  149411. 8,
  149412. 1,
  149413. 9,
  149414. 0,
  149415. 10,
  149416. };
  149417. static long _vq_lengthlist__44u7__p7_1[] = {
  149418. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  149419. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  149420. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  149421. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  149422. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  149423. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149424. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  149425. 8, 9, 9, 9, 9, 9,10,10,10,
  149426. };
  149427. static float _vq_quantthresh__44u7__p7_1[] = {
  149428. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149429. 3.5, 4.5,
  149430. };
  149431. static long _vq_quantmap__44u7__p7_1[] = {
  149432. 9, 7, 5, 3, 1, 0, 2, 4,
  149433. 6, 8, 10,
  149434. };
  149435. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  149436. _vq_quantthresh__44u7__p7_1,
  149437. _vq_quantmap__44u7__p7_1,
  149438. 11,
  149439. 11
  149440. };
  149441. static static_codebook _44u7__p7_1 = {
  149442. 2, 121,
  149443. _vq_lengthlist__44u7__p7_1,
  149444. 1, -531365888, 1611661312, 4, 0,
  149445. _vq_quantlist__44u7__p7_1,
  149446. NULL,
  149447. &_vq_auxt__44u7__p7_1,
  149448. NULL,
  149449. 0
  149450. };
  149451. static long _vq_quantlist__44u7__p8_0[] = {
  149452. 5,
  149453. 4,
  149454. 6,
  149455. 3,
  149456. 7,
  149457. 2,
  149458. 8,
  149459. 1,
  149460. 9,
  149461. 0,
  149462. 10,
  149463. };
  149464. static long _vq_lengthlist__44u7__p8_0[] = {
  149465. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  149466. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  149467. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  149468. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  149469. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  149470. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  149471. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  149472. 12,13,13,14,14,15,15,15,16,
  149473. };
  149474. static float _vq_quantthresh__44u7__p8_0[] = {
  149475. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149476. 38.5, 49.5,
  149477. };
  149478. static long _vq_quantmap__44u7__p8_0[] = {
  149479. 9, 7, 5, 3, 1, 0, 2, 4,
  149480. 6, 8, 10,
  149481. };
  149482. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  149483. _vq_quantthresh__44u7__p8_0,
  149484. _vq_quantmap__44u7__p8_0,
  149485. 11,
  149486. 11
  149487. };
  149488. static static_codebook _44u7__p8_0 = {
  149489. 2, 121,
  149490. _vq_lengthlist__44u7__p8_0,
  149491. 1, -524582912, 1618345984, 4, 0,
  149492. _vq_quantlist__44u7__p8_0,
  149493. NULL,
  149494. &_vq_auxt__44u7__p8_0,
  149495. NULL,
  149496. 0
  149497. };
  149498. static long _vq_quantlist__44u7__p8_1[] = {
  149499. 5,
  149500. 4,
  149501. 6,
  149502. 3,
  149503. 7,
  149504. 2,
  149505. 8,
  149506. 1,
  149507. 9,
  149508. 0,
  149509. 10,
  149510. };
  149511. static long _vq_lengthlist__44u7__p8_1[] = {
  149512. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  149513. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  149514. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  149515. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  149516. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  149517. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  149518. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  149519. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  149520. };
  149521. static float _vq_quantthresh__44u7__p8_1[] = {
  149522. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149523. 3.5, 4.5,
  149524. };
  149525. static long _vq_quantmap__44u7__p8_1[] = {
  149526. 9, 7, 5, 3, 1, 0, 2, 4,
  149527. 6, 8, 10,
  149528. };
  149529. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  149530. _vq_quantthresh__44u7__p8_1,
  149531. _vq_quantmap__44u7__p8_1,
  149532. 11,
  149533. 11
  149534. };
  149535. static static_codebook _44u7__p8_1 = {
  149536. 2, 121,
  149537. _vq_lengthlist__44u7__p8_1,
  149538. 1, -531365888, 1611661312, 4, 0,
  149539. _vq_quantlist__44u7__p8_1,
  149540. NULL,
  149541. &_vq_auxt__44u7__p8_1,
  149542. NULL,
  149543. 0
  149544. };
  149545. static long _vq_quantlist__44u7__p9_0[] = {
  149546. 5,
  149547. 4,
  149548. 6,
  149549. 3,
  149550. 7,
  149551. 2,
  149552. 8,
  149553. 1,
  149554. 9,
  149555. 0,
  149556. 10,
  149557. };
  149558. static long _vq_lengthlist__44u7__p9_0[] = {
  149559. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  149560. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  149561. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149562. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149563. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149564. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149565. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149566. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149567. };
  149568. static float _vq_quantthresh__44u7__p9_0[] = {
  149569. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  149570. 2229.5, 2866.5,
  149571. };
  149572. static long _vq_quantmap__44u7__p9_0[] = {
  149573. 9, 7, 5, 3, 1, 0, 2, 4,
  149574. 6, 8, 10,
  149575. };
  149576. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  149577. _vq_quantthresh__44u7__p9_0,
  149578. _vq_quantmap__44u7__p9_0,
  149579. 11,
  149580. 11
  149581. };
  149582. static static_codebook _44u7__p9_0 = {
  149583. 2, 121,
  149584. _vq_lengthlist__44u7__p9_0,
  149585. 1, -512171520, 1630791680, 4, 0,
  149586. _vq_quantlist__44u7__p9_0,
  149587. NULL,
  149588. &_vq_auxt__44u7__p9_0,
  149589. NULL,
  149590. 0
  149591. };
  149592. static long _vq_quantlist__44u7__p9_1[] = {
  149593. 6,
  149594. 5,
  149595. 7,
  149596. 4,
  149597. 8,
  149598. 3,
  149599. 9,
  149600. 2,
  149601. 10,
  149602. 1,
  149603. 11,
  149604. 0,
  149605. 12,
  149606. };
  149607. static long _vq_lengthlist__44u7__p9_1[] = {
  149608. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  149609. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  149610. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  149611. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  149612. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  149613. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  149614. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  149615. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  149616. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  149617. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  149618. 15,15,15,15,17,17,16,17,16,
  149619. };
  149620. static float _vq_quantthresh__44u7__p9_1[] = {
  149621. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  149622. 122.5, 171.5, 220.5, 269.5,
  149623. };
  149624. static long _vq_quantmap__44u7__p9_1[] = {
  149625. 11, 9, 7, 5, 3, 1, 0, 2,
  149626. 4, 6, 8, 10, 12,
  149627. };
  149628. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  149629. _vq_quantthresh__44u7__p9_1,
  149630. _vq_quantmap__44u7__p9_1,
  149631. 13,
  149632. 13
  149633. };
  149634. static static_codebook _44u7__p9_1 = {
  149635. 2, 169,
  149636. _vq_lengthlist__44u7__p9_1,
  149637. 1, -518889472, 1622704128, 4, 0,
  149638. _vq_quantlist__44u7__p9_1,
  149639. NULL,
  149640. &_vq_auxt__44u7__p9_1,
  149641. NULL,
  149642. 0
  149643. };
  149644. static long _vq_quantlist__44u7__p9_2[] = {
  149645. 24,
  149646. 23,
  149647. 25,
  149648. 22,
  149649. 26,
  149650. 21,
  149651. 27,
  149652. 20,
  149653. 28,
  149654. 19,
  149655. 29,
  149656. 18,
  149657. 30,
  149658. 17,
  149659. 31,
  149660. 16,
  149661. 32,
  149662. 15,
  149663. 33,
  149664. 14,
  149665. 34,
  149666. 13,
  149667. 35,
  149668. 12,
  149669. 36,
  149670. 11,
  149671. 37,
  149672. 10,
  149673. 38,
  149674. 9,
  149675. 39,
  149676. 8,
  149677. 40,
  149678. 7,
  149679. 41,
  149680. 6,
  149681. 42,
  149682. 5,
  149683. 43,
  149684. 4,
  149685. 44,
  149686. 3,
  149687. 45,
  149688. 2,
  149689. 46,
  149690. 1,
  149691. 47,
  149692. 0,
  149693. 48,
  149694. };
  149695. static long _vq_lengthlist__44u7__p9_2[] = {
  149696. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  149697. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149698. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  149699. 8,
  149700. };
  149701. static float _vq_quantthresh__44u7__p9_2[] = {
  149702. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  149703. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  149704. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149705. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149706. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  149707. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  149708. };
  149709. static long _vq_quantmap__44u7__p9_2[] = {
  149710. 47, 45, 43, 41, 39, 37, 35, 33,
  149711. 31, 29, 27, 25, 23, 21, 19, 17,
  149712. 15, 13, 11, 9, 7, 5, 3, 1,
  149713. 0, 2, 4, 6, 8, 10, 12, 14,
  149714. 16, 18, 20, 22, 24, 26, 28, 30,
  149715. 32, 34, 36, 38, 40, 42, 44, 46,
  149716. 48,
  149717. };
  149718. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  149719. _vq_quantthresh__44u7__p9_2,
  149720. _vq_quantmap__44u7__p9_2,
  149721. 49,
  149722. 49
  149723. };
  149724. static static_codebook _44u7__p9_2 = {
  149725. 1, 49,
  149726. _vq_lengthlist__44u7__p9_2,
  149727. 1, -526909440, 1611661312, 6, 0,
  149728. _vq_quantlist__44u7__p9_2,
  149729. NULL,
  149730. &_vq_auxt__44u7__p9_2,
  149731. NULL,
  149732. 0
  149733. };
  149734. static long _huff_lengthlist__44u7__short[] = {
  149735. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  149736. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  149737. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  149738. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  149739. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  149740. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  149741. 6, 8, 5, 9,
  149742. };
  149743. static static_codebook _huff_book__44u7__short = {
  149744. 2, 100,
  149745. _huff_lengthlist__44u7__short,
  149746. 0, 0, 0, 0, 0,
  149747. NULL,
  149748. NULL,
  149749. NULL,
  149750. NULL,
  149751. 0
  149752. };
  149753. static long _huff_lengthlist__44u8__long[] = {
  149754. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  149755. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  149756. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  149757. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  149758. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  149759. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  149760. 10, 8, 8, 9,
  149761. };
  149762. static static_codebook _huff_book__44u8__long = {
  149763. 2, 100,
  149764. _huff_lengthlist__44u8__long,
  149765. 0, 0, 0, 0, 0,
  149766. NULL,
  149767. NULL,
  149768. NULL,
  149769. NULL,
  149770. 0
  149771. };
  149772. static long _huff_lengthlist__44u8__short[] = {
  149773. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  149774. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  149775. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  149776. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  149777. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  149778. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  149779. 10,10,15,17,
  149780. };
  149781. static static_codebook _huff_book__44u8__short = {
  149782. 2, 100,
  149783. _huff_lengthlist__44u8__short,
  149784. 0, 0, 0, 0, 0,
  149785. NULL,
  149786. NULL,
  149787. NULL,
  149788. NULL,
  149789. 0
  149790. };
  149791. static long _vq_quantlist__44u8_p1_0[] = {
  149792. 1,
  149793. 0,
  149794. 2,
  149795. };
  149796. static long _vq_lengthlist__44u8_p1_0[] = {
  149797. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  149798. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  149799. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  149800. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  149801. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  149802. 10,
  149803. };
  149804. static float _vq_quantthresh__44u8_p1_0[] = {
  149805. -0.5, 0.5,
  149806. };
  149807. static long _vq_quantmap__44u8_p1_0[] = {
  149808. 1, 0, 2,
  149809. };
  149810. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  149811. _vq_quantthresh__44u8_p1_0,
  149812. _vq_quantmap__44u8_p1_0,
  149813. 3,
  149814. 3
  149815. };
  149816. static static_codebook _44u8_p1_0 = {
  149817. 4, 81,
  149818. _vq_lengthlist__44u8_p1_0,
  149819. 1, -535822336, 1611661312, 2, 0,
  149820. _vq_quantlist__44u8_p1_0,
  149821. NULL,
  149822. &_vq_auxt__44u8_p1_0,
  149823. NULL,
  149824. 0
  149825. };
  149826. static long _vq_quantlist__44u8_p2_0[] = {
  149827. 2,
  149828. 1,
  149829. 3,
  149830. 0,
  149831. 4,
  149832. };
  149833. static long _vq_lengthlist__44u8_p2_0[] = {
  149834. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149835. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  149836. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  149837. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  149838. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  149839. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  149840. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149841. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  149842. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149843. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  149844. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  149845. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149846. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  149847. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  149848. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  149849. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  149850. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149851. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  149852. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  149853. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  149854. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  149855. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  149856. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  149857. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149858. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  149859. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149860. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  149861. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  149862. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  149863. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  149864. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  149865. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149866. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  149867. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  149868. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149869. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  149870. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  149871. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  149872. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  149873. 14,
  149874. };
  149875. static float _vq_quantthresh__44u8_p2_0[] = {
  149876. -1.5, -0.5, 0.5, 1.5,
  149877. };
  149878. static long _vq_quantmap__44u8_p2_0[] = {
  149879. 3, 1, 0, 2, 4,
  149880. };
  149881. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  149882. _vq_quantthresh__44u8_p2_0,
  149883. _vq_quantmap__44u8_p2_0,
  149884. 5,
  149885. 5
  149886. };
  149887. static static_codebook _44u8_p2_0 = {
  149888. 4, 625,
  149889. _vq_lengthlist__44u8_p2_0,
  149890. 1, -533725184, 1611661312, 3, 0,
  149891. _vq_quantlist__44u8_p2_0,
  149892. NULL,
  149893. &_vq_auxt__44u8_p2_0,
  149894. NULL,
  149895. 0
  149896. };
  149897. static long _vq_quantlist__44u8_p3_0[] = {
  149898. 4,
  149899. 3,
  149900. 5,
  149901. 2,
  149902. 6,
  149903. 1,
  149904. 7,
  149905. 0,
  149906. 8,
  149907. };
  149908. static long _vq_lengthlist__44u8_p3_0[] = {
  149909. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149910. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149911. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149912. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149913. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  149914. 12,
  149915. };
  149916. static float _vq_quantthresh__44u8_p3_0[] = {
  149917. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149918. };
  149919. static long _vq_quantmap__44u8_p3_0[] = {
  149920. 7, 5, 3, 1, 0, 2, 4, 6,
  149921. 8,
  149922. };
  149923. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  149924. _vq_quantthresh__44u8_p3_0,
  149925. _vq_quantmap__44u8_p3_0,
  149926. 9,
  149927. 9
  149928. };
  149929. static static_codebook _44u8_p3_0 = {
  149930. 2, 81,
  149931. _vq_lengthlist__44u8_p3_0,
  149932. 1, -531628032, 1611661312, 4, 0,
  149933. _vq_quantlist__44u8_p3_0,
  149934. NULL,
  149935. &_vq_auxt__44u8_p3_0,
  149936. NULL,
  149937. 0
  149938. };
  149939. static long _vq_quantlist__44u8_p4_0[] = {
  149940. 8,
  149941. 7,
  149942. 9,
  149943. 6,
  149944. 10,
  149945. 5,
  149946. 11,
  149947. 4,
  149948. 12,
  149949. 3,
  149950. 13,
  149951. 2,
  149952. 14,
  149953. 1,
  149954. 15,
  149955. 0,
  149956. 16,
  149957. };
  149958. static long _vq_lengthlist__44u8_p4_0[] = {
  149959. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  149960. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  149961. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  149962. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  149963. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  149964. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  149965. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  149966. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  149967. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  149968. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  149969. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  149970. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  149971. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  149972. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  149973. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  149974. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  149975. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  149976. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  149977. 14,
  149978. };
  149979. static float _vq_quantthresh__44u8_p4_0[] = {
  149980. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149981. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149982. };
  149983. static long _vq_quantmap__44u8_p4_0[] = {
  149984. 15, 13, 11, 9, 7, 5, 3, 1,
  149985. 0, 2, 4, 6, 8, 10, 12, 14,
  149986. 16,
  149987. };
  149988. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  149989. _vq_quantthresh__44u8_p4_0,
  149990. _vq_quantmap__44u8_p4_0,
  149991. 17,
  149992. 17
  149993. };
  149994. static static_codebook _44u8_p4_0 = {
  149995. 2, 289,
  149996. _vq_lengthlist__44u8_p4_0,
  149997. 1, -529530880, 1611661312, 5, 0,
  149998. _vq_quantlist__44u8_p4_0,
  149999. NULL,
  150000. &_vq_auxt__44u8_p4_0,
  150001. NULL,
  150002. 0
  150003. };
  150004. static long _vq_quantlist__44u8_p5_0[] = {
  150005. 1,
  150006. 0,
  150007. 2,
  150008. };
  150009. static long _vq_lengthlist__44u8_p5_0[] = {
  150010. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150011. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150012. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150013. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150014. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150015. 10,
  150016. };
  150017. static float _vq_quantthresh__44u8_p5_0[] = {
  150018. -5.5, 5.5,
  150019. };
  150020. static long _vq_quantmap__44u8_p5_0[] = {
  150021. 1, 0, 2,
  150022. };
  150023. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150024. _vq_quantthresh__44u8_p5_0,
  150025. _vq_quantmap__44u8_p5_0,
  150026. 3,
  150027. 3
  150028. };
  150029. static static_codebook _44u8_p5_0 = {
  150030. 4, 81,
  150031. _vq_lengthlist__44u8_p5_0,
  150032. 1, -529137664, 1618345984, 2, 0,
  150033. _vq_quantlist__44u8_p5_0,
  150034. NULL,
  150035. &_vq_auxt__44u8_p5_0,
  150036. NULL,
  150037. 0
  150038. };
  150039. static long _vq_quantlist__44u8_p5_1[] = {
  150040. 5,
  150041. 4,
  150042. 6,
  150043. 3,
  150044. 7,
  150045. 2,
  150046. 8,
  150047. 1,
  150048. 9,
  150049. 0,
  150050. 10,
  150051. };
  150052. static long _vq_lengthlist__44u8_p5_1[] = {
  150053. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150054. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150055. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150056. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150057. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150058. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150059. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150060. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150061. };
  150062. static float _vq_quantthresh__44u8_p5_1[] = {
  150063. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150064. 3.5, 4.5,
  150065. };
  150066. static long _vq_quantmap__44u8_p5_1[] = {
  150067. 9, 7, 5, 3, 1, 0, 2, 4,
  150068. 6, 8, 10,
  150069. };
  150070. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150071. _vq_quantthresh__44u8_p5_1,
  150072. _vq_quantmap__44u8_p5_1,
  150073. 11,
  150074. 11
  150075. };
  150076. static static_codebook _44u8_p5_1 = {
  150077. 2, 121,
  150078. _vq_lengthlist__44u8_p5_1,
  150079. 1, -531365888, 1611661312, 4, 0,
  150080. _vq_quantlist__44u8_p5_1,
  150081. NULL,
  150082. &_vq_auxt__44u8_p5_1,
  150083. NULL,
  150084. 0
  150085. };
  150086. static long _vq_quantlist__44u8_p6_0[] = {
  150087. 6,
  150088. 5,
  150089. 7,
  150090. 4,
  150091. 8,
  150092. 3,
  150093. 9,
  150094. 2,
  150095. 10,
  150096. 1,
  150097. 11,
  150098. 0,
  150099. 12,
  150100. };
  150101. static long _vq_lengthlist__44u8_p6_0[] = {
  150102. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150103. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150104. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150105. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150106. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150107. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150108. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150109. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150110. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150111. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150112. 11,11,11,11,11,12,11,12,12,
  150113. };
  150114. static float _vq_quantthresh__44u8_p6_0[] = {
  150115. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150116. 12.5, 17.5, 22.5, 27.5,
  150117. };
  150118. static long _vq_quantmap__44u8_p6_0[] = {
  150119. 11, 9, 7, 5, 3, 1, 0, 2,
  150120. 4, 6, 8, 10, 12,
  150121. };
  150122. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150123. _vq_quantthresh__44u8_p6_0,
  150124. _vq_quantmap__44u8_p6_0,
  150125. 13,
  150126. 13
  150127. };
  150128. static static_codebook _44u8_p6_0 = {
  150129. 2, 169,
  150130. _vq_lengthlist__44u8_p6_0,
  150131. 1, -526516224, 1616117760, 4, 0,
  150132. _vq_quantlist__44u8_p6_0,
  150133. NULL,
  150134. &_vq_auxt__44u8_p6_0,
  150135. NULL,
  150136. 0
  150137. };
  150138. static long _vq_quantlist__44u8_p6_1[] = {
  150139. 2,
  150140. 1,
  150141. 3,
  150142. 0,
  150143. 4,
  150144. };
  150145. static long _vq_lengthlist__44u8_p6_1[] = {
  150146. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  150147. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  150148. };
  150149. static float _vq_quantthresh__44u8_p6_1[] = {
  150150. -1.5, -0.5, 0.5, 1.5,
  150151. };
  150152. static long _vq_quantmap__44u8_p6_1[] = {
  150153. 3, 1, 0, 2, 4,
  150154. };
  150155. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  150156. _vq_quantthresh__44u8_p6_1,
  150157. _vq_quantmap__44u8_p6_1,
  150158. 5,
  150159. 5
  150160. };
  150161. static static_codebook _44u8_p6_1 = {
  150162. 2, 25,
  150163. _vq_lengthlist__44u8_p6_1,
  150164. 1, -533725184, 1611661312, 3, 0,
  150165. _vq_quantlist__44u8_p6_1,
  150166. NULL,
  150167. &_vq_auxt__44u8_p6_1,
  150168. NULL,
  150169. 0
  150170. };
  150171. static long _vq_quantlist__44u8_p7_0[] = {
  150172. 6,
  150173. 5,
  150174. 7,
  150175. 4,
  150176. 8,
  150177. 3,
  150178. 9,
  150179. 2,
  150180. 10,
  150181. 1,
  150182. 11,
  150183. 0,
  150184. 12,
  150185. };
  150186. static long _vq_lengthlist__44u8_p7_0[] = {
  150187. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  150188. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  150189. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  150190. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  150191. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  150192. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  150193. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  150194. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  150195. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  150196. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  150197. 13,13,14,14,14,15,15,15,16,
  150198. };
  150199. static float _vq_quantthresh__44u8_p7_0[] = {
  150200. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  150201. 27.5, 38.5, 49.5, 60.5,
  150202. };
  150203. static long _vq_quantmap__44u8_p7_0[] = {
  150204. 11, 9, 7, 5, 3, 1, 0, 2,
  150205. 4, 6, 8, 10, 12,
  150206. };
  150207. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  150208. _vq_quantthresh__44u8_p7_0,
  150209. _vq_quantmap__44u8_p7_0,
  150210. 13,
  150211. 13
  150212. };
  150213. static static_codebook _44u8_p7_0 = {
  150214. 2, 169,
  150215. _vq_lengthlist__44u8_p7_0,
  150216. 1, -523206656, 1618345984, 4, 0,
  150217. _vq_quantlist__44u8_p7_0,
  150218. NULL,
  150219. &_vq_auxt__44u8_p7_0,
  150220. NULL,
  150221. 0
  150222. };
  150223. static long _vq_quantlist__44u8_p7_1[] = {
  150224. 5,
  150225. 4,
  150226. 6,
  150227. 3,
  150228. 7,
  150229. 2,
  150230. 8,
  150231. 1,
  150232. 9,
  150233. 0,
  150234. 10,
  150235. };
  150236. static long _vq_lengthlist__44u8_p7_1[] = {
  150237. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150238. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  150239. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150240. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  150241. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  150242. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150243. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150244. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150245. };
  150246. static float _vq_quantthresh__44u8_p7_1[] = {
  150247. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150248. 3.5, 4.5,
  150249. };
  150250. static long _vq_quantmap__44u8_p7_1[] = {
  150251. 9, 7, 5, 3, 1, 0, 2, 4,
  150252. 6, 8, 10,
  150253. };
  150254. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  150255. _vq_quantthresh__44u8_p7_1,
  150256. _vq_quantmap__44u8_p7_1,
  150257. 11,
  150258. 11
  150259. };
  150260. static static_codebook _44u8_p7_1 = {
  150261. 2, 121,
  150262. _vq_lengthlist__44u8_p7_1,
  150263. 1, -531365888, 1611661312, 4, 0,
  150264. _vq_quantlist__44u8_p7_1,
  150265. NULL,
  150266. &_vq_auxt__44u8_p7_1,
  150267. NULL,
  150268. 0
  150269. };
  150270. static long _vq_quantlist__44u8_p8_0[] = {
  150271. 7,
  150272. 6,
  150273. 8,
  150274. 5,
  150275. 9,
  150276. 4,
  150277. 10,
  150278. 3,
  150279. 11,
  150280. 2,
  150281. 12,
  150282. 1,
  150283. 13,
  150284. 0,
  150285. 14,
  150286. };
  150287. static long _vq_lengthlist__44u8_p8_0[] = {
  150288. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  150289. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  150290. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  150291. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  150292. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  150293. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  150294. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  150295. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  150296. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  150297. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  150298. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  150299. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  150300. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  150301. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  150302. 17,
  150303. };
  150304. static float _vq_quantthresh__44u8_p8_0[] = {
  150305. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  150306. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  150307. };
  150308. static long _vq_quantmap__44u8_p8_0[] = {
  150309. 13, 11, 9, 7, 5, 3, 1, 0,
  150310. 2, 4, 6, 8, 10, 12, 14,
  150311. };
  150312. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  150313. _vq_quantthresh__44u8_p8_0,
  150314. _vq_quantmap__44u8_p8_0,
  150315. 15,
  150316. 15
  150317. };
  150318. static static_codebook _44u8_p8_0 = {
  150319. 2, 225,
  150320. _vq_lengthlist__44u8_p8_0,
  150321. 1, -520986624, 1620377600, 4, 0,
  150322. _vq_quantlist__44u8_p8_0,
  150323. NULL,
  150324. &_vq_auxt__44u8_p8_0,
  150325. NULL,
  150326. 0
  150327. };
  150328. static long _vq_quantlist__44u8_p8_1[] = {
  150329. 10,
  150330. 9,
  150331. 11,
  150332. 8,
  150333. 12,
  150334. 7,
  150335. 13,
  150336. 6,
  150337. 14,
  150338. 5,
  150339. 15,
  150340. 4,
  150341. 16,
  150342. 3,
  150343. 17,
  150344. 2,
  150345. 18,
  150346. 1,
  150347. 19,
  150348. 0,
  150349. 20,
  150350. };
  150351. static long _vq_lengthlist__44u8_p8_1[] = {
  150352. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  150353. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  150354. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  150355. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  150356. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150357. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150358. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  150359. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  150360. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150361. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150362. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  150363. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  150364. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150365. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150366. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150367. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  150368. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  150369. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  150370. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  150371. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  150372. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150373. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150374. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150375. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  150376. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  150377. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150378. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  150379. 10,10,10,10,10,10,10,10,10,
  150380. };
  150381. static float _vq_quantthresh__44u8_p8_1[] = {
  150382. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  150383. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  150384. 6.5, 7.5, 8.5, 9.5,
  150385. };
  150386. static long _vq_quantmap__44u8_p8_1[] = {
  150387. 19, 17, 15, 13, 11, 9, 7, 5,
  150388. 3, 1, 0, 2, 4, 6, 8, 10,
  150389. 12, 14, 16, 18, 20,
  150390. };
  150391. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  150392. _vq_quantthresh__44u8_p8_1,
  150393. _vq_quantmap__44u8_p8_1,
  150394. 21,
  150395. 21
  150396. };
  150397. static static_codebook _44u8_p8_1 = {
  150398. 2, 441,
  150399. _vq_lengthlist__44u8_p8_1,
  150400. 1, -529268736, 1611661312, 5, 0,
  150401. _vq_quantlist__44u8_p8_1,
  150402. NULL,
  150403. &_vq_auxt__44u8_p8_1,
  150404. NULL,
  150405. 0
  150406. };
  150407. static long _vq_quantlist__44u8_p9_0[] = {
  150408. 4,
  150409. 3,
  150410. 5,
  150411. 2,
  150412. 6,
  150413. 1,
  150414. 7,
  150415. 0,
  150416. 8,
  150417. };
  150418. static long _vq_lengthlist__44u8_p9_0[] = {
  150419. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  150420. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150421. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150422. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150423. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150424. 8,
  150425. };
  150426. static float _vq_quantthresh__44u8_p9_0[] = {
  150427. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  150428. };
  150429. static long _vq_quantmap__44u8_p9_0[] = {
  150430. 7, 5, 3, 1, 0, 2, 4, 6,
  150431. 8,
  150432. };
  150433. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  150434. _vq_quantthresh__44u8_p9_0,
  150435. _vq_quantmap__44u8_p9_0,
  150436. 9,
  150437. 9
  150438. };
  150439. static static_codebook _44u8_p9_0 = {
  150440. 2, 81,
  150441. _vq_lengthlist__44u8_p9_0,
  150442. 1, -511895552, 1631393792, 4, 0,
  150443. _vq_quantlist__44u8_p9_0,
  150444. NULL,
  150445. &_vq_auxt__44u8_p9_0,
  150446. NULL,
  150447. 0
  150448. };
  150449. static long _vq_quantlist__44u8_p9_1[] = {
  150450. 9,
  150451. 8,
  150452. 10,
  150453. 7,
  150454. 11,
  150455. 6,
  150456. 12,
  150457. 5,
  150458. 13,
  150459. 4,
  150460. 14,
  150461. 3,
  150462. 15,
  150463. 2,
  150464. 16,
  150465. 1,
  150466. 17,
  150467. 0,
  150468. 18,
  150469. };
  150470. static long _vq_lengthlist__44u8_p9_1[] = {
  150471. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  150472. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  150473. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  150474. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  150475. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  150476. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  150477. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  150478. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  150479. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  150480. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  150481. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  150482. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  150483. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  150484. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  150485. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  150486. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  150487. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  150488. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  150489. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  150490. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  150491. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  150492. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  150493. 16,15,16,16,16,16,16,16,16,
  150494. };
  150495. static float _vq_quantthresh__44u8_p9_1[] = {
  150496. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  150497. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  150498. 367.5, 416.5,
  150499. };
  150500. static long _vq_quantmap__44u8_p9_1[] = {
  150501. 17, 15, 13, 11, 9, 7, 5, 3,
  150502. 1, 0, 2, 4, 6, 8, 10, 12,
  150503. 14, 16, 18,
  150504. };
  150505. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  150506. _vq_quantthresh__44u8_p9_1,
  150507. _vq_quantmap__44u8_p9_1,
  150508. 19,
  150509. 19
  150510. };
  150511. static static_codebook _44u8_p9_1 = {
  150512. 2, 361,
  150513. _vq_lengthlist__44u8_p9_1,
  150514. 1, -518287360, 1622704128, 5, 0,
  150515. _vq_quantlist__44u8_p9_1,
  150516. NULL,
  150517. &_vq_auxt__44u8_p9_1,
  150518. NULL,
  150519. 0
  150520. };
  150521. static long _vq_quantlist__44u8_p9_2[] = {
  150522. 24,
  150523. 23,
  150524. 25,
  150525. 22,
  150526. 26,
  150527. 21,
  150528. 27,
  150529. 20,
  150530. 28,
  150531. 19,
  150532. 29,
  150533. 18,
  150534. 30,
  150535. 17,
  150536. 31,
  150537. 16,
  150538. 32,
  150539. 15,
  150540. 33,
  150541. 14,
  150542. 34,
  150543. 13,
  150544. 35,
  150545. 12,
  150546. 36,
  150547. 11,
  150548. 37,
  150549. 10,
  150550. 38,
  150551. 9,
  150552. 39,
  150553. 8,
  150554. 40,
  150555. 7,
  150556. 41,
  150557. 6,
  150558. 42,
  150559. 5,
  150560. 43,
  150561. 4,
  150562. 44,
  150563. 3,
  150564. 45,
  150565. 2,
  150566. 46,
  150567. 1,
  150568. 47,
  150569. 0,
  150570. 48,
  150571. };
  150572. static long _vq_lengthlist__44u8_p9_2[] = {
  150573. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  150574. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150575. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150576. 7,
  150577. };
  150578. static float _vq_quantthresh__44u8_p9_2[] = {
  150579. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150580. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150581. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150582. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150583. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150584. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150585. };
  150586. static long _vq_quantmap__44u8_p9_2[] = {
  150587. 47, 45, 43, 41, 39, 37, 35, 33,
  150588. 31, 29, 27, 25, 23, 21, 19, 17,
  150589. 15, 13, 11, 9, 7, 5, 3, 1,
  150590. 0, 2, 4, 6, 8, 10, 12, 14,
  150591. 16, 18, 20, 22, 24, 26, 28, 30,
  150592. 32, 34, 36, 38, 40, 42, 44, 46,
  150593. 48,
  150594. };
  150595. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  150596. _vq_quantthresh__44u8_p9_2,
  150597. _vq_quantmap__44u8_p9_2,
  150598. 49,
  150599. 49
  150600. };
  150601. static static_codebook _44u8_p9_2 = {
  150602. 1, 49,
  150603. _vq_lengthlist__44u8_p9_2,
  150604. 1, -526909440, 1611661312, 6, 0,
  150605. _vq_quantlist__44u8_p9_2,
  150606. NULL,
  150607. &_vq_auxt__44u8_p9_2,
  150608. NULL,
  150609. 0
  150610. };
  150611. static long _huff_lengthlist__44u9__long[] = {
  150612. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  150613. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  150614. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  150615. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  150616. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  150617. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  150618. 10, 8, 8, 9,
  150619. };
  150620. static static_codebook _huff_book__44u9__long = {
  150621. 2, 100,
  150622. _huff_lengthlist__44u9__long,
  150623. 0, 0, 0, 0, 0,
  150624. NULL,
  150625. NULL,
  150626. NULL,
  150627. NULL,
  150628. 0
  150629. };
  150630. static long _huff_lengthlist__44u9__short[] = {
  150631. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  150632. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  150633. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  150634. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  150635. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  150636. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  150637. 9, 9,12,15,
  150638. };
  150639. static static_codebook _huff_book__44u9__short = {
  150640. 2, 100,
  150641. _huff_lengthlist__44u9__short,
  150642. 0, 0, 0, 0, 0,
  150643. NULL,
  150644. NULL,
  150645. NULL,
  150646. NULL,
  150647. 0
  150648. };
  150649. static long _vq_quantlist__44u9_p1_0[] = {
  150650. 1,
  150651. 0,
  150652. 2,
  150653. };
  150654. static long _vq_lengthlist__44u9_p1_0[] = {
  150655. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  150656. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  150657. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  150658. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  150659. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  150660. 10,
  150661. };
  150662. static float _vq_quantthresh__44u9_p1_0[] = {
  150663. -0.5, 0.5,
  150664. };
  150665. static long _vq_quantmap__44u9_p1_0[] = {
  150666. 1, 0, 2,
  150667. };
  150668. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  150669. _vq_quantthresh__44u9_p1_0,
  150670. _vq_quantmap__44u9_p1_0,
  150671. 3,
  150672. 3
  150673. };
  150674. static static_codebook _44u9_p1_0 = {
  150675. 4, 81,
  150676. _vq_lengthlist__44u9_p1_0,
  150677. 1, -535822336, 1611661312, 2, 0,
  150678. _vq_quantlist__44u9_p1_0,
  150679. NULL,
  150680. &_vq_auxt__44u9_p1_0,
  150681. NULL,
  150682. 0
  150683. };
  150684. static long _vq_quantlist__44u9_p2_0[] = {
  150685. 2,
  150686. 1,
  150687. 3,
  150688. 0,
  150689. 4,
  150690. };
  150691. static long _vq_lengthlist__44u9_p2_0[] = {
  150692. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  150693. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  150694. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  150695. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  150696. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  150697. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  150698. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  150699. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  150700. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150701. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150702. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  150703. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  150704. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  150705. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  150706. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  150707. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  150708. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  150709. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  150710. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  150711. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  150712. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  150713. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  150714. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  150715. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  150716. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  150717. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  150718. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  150719. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  150720. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  150721. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  150722. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  150723. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  150724. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  150725. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  150726. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  150727. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  150728. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  150729. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  150730. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  150731. 14,
  150732. };
  150733. static float _vq_quantthresh__44u9_p2_0[] = {
  150734. -1.5, -0.5, 0.5, 1.5,
  150735. };
  150736. static long _vq_quantmap__44u9_p2_0[] = {
  150737. 3, 1, 0, 2, 4,
  150738. };
  150739. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  150740. _vq_quantthresh__44u9_p2_0,
  150741. _vq_quantmap__44u9_p2_0,
  150742. 5,
  150743. 5
  150744. };
  150745. static static_codebook _44u9_p2_0 = {
  150746. 4, 625,
  150747. _vq_lengthlist__44u9_p2_0,
  150748. 1, -533725184, 1611661312, 3, 0,
  150749. _vq_quantlist__44u9_p2_0,
  150750. NULL,
  150751. &_vq_auxt__44u9_p2_0,
  150752. NULL,
  150753. 0
  150754. };
  150755. static long _vq_quantlist__44u9_p3_0[] = {
  150756. 4,
  150757. 3,
  150758. 5,
  150759. 2,
  150760. 6,
  150761. 1,
  150762. 7,
  150763. 0,
  150764. 8,
  150765. };
  150766. static long _vq_lengthlist__44u9_p3_0[] = {
  150767. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  150768. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150769. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  150770. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  150771. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  150772. 11,
  150773. };
  150774. static float _vq_quantthresh__44u9_p3_0[] = {
  150775. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150776. };
  150777. static long _vq_quantmap__44u9_p3_0[] = {
  150778. 7, 5, 3, 1, 0, 2, 4, 6,
  150779. 8,
  150780. };
  150781. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  150782. _vq_quantthresh__44u9_p3_0,
  150783. _vq_quantmap__44u9_p3_0,
  150784. 9,
  150785. 9
  150786. };
  150787. static static_codebook _44u9_p3_0 = {
  150788. 2, 81,
  150789. _vq_lengthlist__44u9_p3_0,
  150790. 1, -531628032, 1611661312, 4, 0,
  150791. _vq_quantlist__44u9_p3_0,
  150792. NULL,
  150793. &_vq_auxt__44u9_p3_0,
  150794. NULL,
  150795. 0
  150796. };
  150797. static long _vq_quantlist__44u9_p4_0[] = {
  150798. 8,
  150799. 7,
  150800. 9,
  150801. 6,
  150802. 10,
  150803. 5,
  150804. 11,
  150805. 4,
  150806. 12,
  150807. 3,
  150808. 13,
  150809. 2,
  150810. 14,
  150811. 1,
  150812. 15,
  150813. 0,
  150814. 16,
  150815. };
  150816. static long _vq_lengthlist__44u9_p4_0[] = {
  150817. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  150818. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  150819. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  150820. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  150821. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  150822. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  150823. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  150824. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  150825. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  150826. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  150827. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  150828. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  150829. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  150830. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  150831. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  150832. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  150833. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  150834. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  150835. 14,
  150836. };
  150837. static float _vq_quantthresh__44u9_p4_0[] = {
  150838. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150839. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150840. };
  150841. static long _vq_quantmap__44u9_p4_0[] = {
  150842. 15, 13, 11, 9, 7, 5, 3, 1,
  150843. 0, 2, 4, 6, 8, 10, 12, 14,
  150844. 16,
  150845. };
  150846. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  150847. _vq_quantthresh__44u9_p4_0,
  150848. _vq_quantmap__44u9_p4_0,
  150849. 17,
  150850. 17
  150851. };
  150852. static static_codebook _44u9_p4_0 = {
  150853. 2, 289,
  150854. _vq_lengthlist__44u9_p4_0,
  150855. 1, -529530880, 1611661312, 5, 0,
  150856. _vq_quantlist__44u9_p4_0,
  150857. NULL,
  150858. &_vq_auxt__44u9_p4_0,
  150859. NULL,
  150860. 0
  150861. };
  150862. static long _vq_quantlist__44u9_p5_0[] = {
  150863. 1,
  150864. 0,
  150865. 2,
  150866. };
  150867. static long _vq_lengthlist__44u9_p5_0[] = {
  150868. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150869. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150870. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  150871. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150872. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150873. 10,
  150874. };
  150875. static float _vq_quantthresh__44u9_p5_0[] = {
  150876. -5.5, 5.5,
  150877. };
  150878. static long _vq_quantmap__44u9_p5_0[] = {
  150879. 1, 0, 2,
  150880. };
  150881. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  150882. _vq_quantthresh__44u9_p5_0,
  150883. _vq_quantmap__44u9_p5_0,
  150884. 3,
  150885. 3
  150886. };
  150887. static static_codebook _44u9_p5_0 = {
  150888. 4, 81,
  150889. _vq_lengthlist__44u9_p5_0,
  150890. 1, -529137664, 1618345984, 2, 0,
  150891. _vq_quantlist__44u9_p5_0,
  150892. NULL,
  150893. &_vq_auxt__44u9_p5_0,
  150894. NULL,
  150895. 0
  150896. };
  150897. static long _vq_quantlist__44u9_p5_1[] = {
  150898. 5,
  150899. 4,
  150900. 6,
  150901. 3,
  150902. 7,
  150903. 2,
  150904. 8,
  150905. 1,
  150906. 9,
  150907. 0,
  150908. 10,
  150909. };
  150910. static long _vq_lengthlist__44u9_p5_1[] = {
  150911. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  150912. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  150913. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  150914. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150915. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150916. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  150917. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150918. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150919. };
  150920. static float _vq_quantthresh__44u9_p5_1[] = {
  150921. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150922. 3.5, 4.5,
  150923. };
  150924. static long _vq_quantmap__44u9_p5_1[] = {
  150925. 9, 7, 5, 3, 1, 0, 2, 4,
  150926. 6, 8, 10,
  150927. };
  150928. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  150929. _vq_quantthresh__44u9_p5_1,
  150930. _vq_quantmap__44u9_p5_1,
  150931. 11,
  150932. 11
  150933. };
  150934. static static_codebook _44u9_p5_1 = {
  150935. 2, 121,
  150936. _vq_lengthlist__44u9_p5_1,
  150937. 1, -531365888, 1611661312, 4, 0,
  150938. _vq_quantlist__44u9_p5_1,
  150939. NULL,
  150940. &_vq_auxt__44u9_p5_1,
  150941. NULL,
  150942. 0
  150943. };
  150944. static long _vq_quantlist__44u9_p6_0[] = {
  150945. 6,
  150946. 5,
  150947. 7,
  150948. 4,
  150949. 8,
  150950. 3,
  150951. 9,
  150952. 2,
  150953. 10,
  150954. 1,
  150955. 11,
  150956. 0,
  150957. 12,
  150958. };
  150959. static long _vq_lengthlist__44u9_p6_0[] = {
  150960. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150961. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  150962. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  150963. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  150964. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  150965. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150966. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150967. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  150968. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  150969. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150970. 10,11,11,11,11,12,11,12,12,
  150971. };
  150972. static float _vq_quantthresh__44u9_p6_0[] = {
  150973. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150974. 12.5, 17.5, 22.5, 27.5,
  150975. };
  150976. static long _vq_quantmap__44u9_p6_0[] = {
  150977. 11, 9, 7, 5, 3, 1, 0, 2,
  150978. 4, 6, 8, 10, 12,
  150979. };
  150980. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  150981. _vq_quantthresh__44u9_p6_0,
  150982. _vq_quantmap__44u9_p6_0,
  150983. 13,
  150984. 13
  150985. };
  150986. static static_codebook _44u9_p6_0 = {
  150987. 2, 169,
  150988. _vq_lengthlist__44u9_p6_0,
  150989. 1, -526516224, 1616117760, 4, 0,
  150990. _vq_quantlist__44u9_p6_0,
  150991. NULL,
  150992. &_vq_auxt__44u9_p6_0,
  150993. NULL,
  150994. 0
  150995. };
  150996. static long _vq_quantlist__44u9_p6_1[] = {
  150997. 2,
  150998. 1,
  150999. 3,
  151000. 0,
  151001. 4,
  151002. };
  151003. static long _vq_lengthlist__44u9_p6_1[] = {
  151004. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151005. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151006. };
  151007. static float _vq_quantthresh__44u9_p6_1[] = {
  151008. -1.5, -0.5, 0.5, 1.5,
  151009. };
  151010. static long _vq_quantmap__44u9_p6_1[] = {
  151011. 3, 1, 0, 2, 4,
  151012. };
  151013. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151014. _vq_quantthresh__44u9_p6_1,
  151015. _vq_quantmap__44u9_p6_1,
  151016. 5,
  151017. 5
  151018. };
  151019. static static_codebook _44u9_p6_1 = {
  151020. 2, 25,
  151021. _vq_lengthlist__44u9_p6_1,
  151022. 1, -533725184, 1611661312, 3, 0,
  151023. _vq_quantlist__44u9_p6_1,
  151024. NULL,
  151025. &_vq_auxt__44u9_p6_1,
  151026. NULL,
  151027. 0
  151028. };
  151029. static long _vq_quantlist__44u9_p7_0[] = {
  151030. 6,
  151031. 5,
  151032. 7,
  151033. 4,
  151034. 8,
  151035. 3,
  151036. 9,
  151037. 2,
  151038. 10,
  151039. 1,
  151040. 11,
  151041. 0,
  151042. 12,
  151043. };
  151044. static long _vq_lengthlist__44u9_p7_0[] = {
  151045. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151046. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151047. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151048. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151049. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151050. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151051. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151052. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151053. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151054. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151055. 12,13,13,14,14,14,15,15,15,
  151056. };
  151057. static float _vq_quantthresh__44u9_p7_0[] = {
  151058. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151059. 27.5, 38.5, 49.5, 60.5,
  151060. };
  151061. static long _vq_quantmap__44u9_p7_0[] = {
  151062. 11, 9, 7, 5, 3, 1, 0, 2,
  151063. 4, 6, 8, 10, 12,
  151064. };
  151065. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151066. _vq_quantthresh__44u9_p7_0,
  151067. _vq_quantmap__44u9_p7_0,
  151068. 13,
  151069. 13
  151070. };
  151071. static static_codebook _44u9_p7_0 = {
  151072. 2, 169,
  151073. _vq_lengthlist__44u9_p7_0,
  151074. 1, -523206656, 1618345984, 4, 0,
  151075. _vq_quantlist__44u9_p7_0,
  151076. NULL,
  151077. &_vq_auxt__44u9_p7_0,
  151078. NULL,
  151079. 0
  151080. };
  151081. static long _vq_quantlist__44u9_p7_1[] = {
  151082. 5,
  151083. 4,
  151084. 6,
  151085. 3,
  151086. 7,
  151087. 2,
  151088. 8,
  151089. 1,
  151090. 9,
  151091. 0,
  151092. 10,
  151093. };
  151094. static long _vq_lengthlist__44u9_p7_1[] = {
  151095. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151096. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151097. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151098. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151099. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151100. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151101. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151102. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151103. };
  151104. static float _vq_quantthresh__44u9_p7_1[] = {
  151105. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151106. 3.5, 4.5,
  151107. };
  151108. static long _vq_quantmap__44u9_p7_1[] = {
  151109. 9, 7, 5, 3, 1, 0, 2, 4,
  151110. 6, 8, 10,
  151111. };
  151112. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151113. _vq_quantthresh__44u9_p7_1,
  151114. _vq_quantmap__44u9_p7_1,
  151115. 11,
  151116. 11
  151117. };
  151118. static static_codebook _44u9_p7_1 = {
  151119. 2, 121,
  151120. _vq_lengthlist__44u9_p7_1,
  151121. 1, -531365888, 1611661312, 4, 0,
  151122. _vq_quantlist__44u9_p7_1,
  151123. NULL,
  151124. &_vq_auxt__44u9_p7_1,
  151125. NULL,
  151126. 0
  151127. };
  151128. static long _vq_quantlist__44u9_p8_0[] = {
  151129. 7,
  151130. 6,
  151131. 8,
  151132. 5,
  151133. 9,
  151134. 4,
  151135. 10,
  151136. 3,
  151137. 11,
  151138. 2,
  151139. 12,
  151140. 1,
  151141. 13,
  151142. 0,
  151143. 14,
  151144. };
  151145. static long _vq_lengthlist__44u9_p8_0[] = {
  151146. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  151147. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151148. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  151149. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  151150. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  151151. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  151152. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  151153. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  151154. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  151155. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  151156. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  151157. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  151158. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  151159. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  151160. 15,
  151161. };
  151162. static float _vq_quantthresh__44u9_p8_0[] = {
  151163. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151164. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151165. };
  151166. static long _vq_quantmap__44u9_p8_0[] = {
  151167. 13, 11, 9, 7, 5, 3, 1, 0,
  151168. 2, 4, 6, 8, 10, 12, 14,
  151169. };
  151170. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  151171. _vq_quantthresh__44u9_p8_0,
  151172. _vq_quantmap__44u9_p8_0,
  151173. 15,
  151174. 15
  151175. };
  151176. static static_codebook _44u9_p8_0 = {
  151177. 2, 225,
  151178. _vq_lengthlist__44u9_p8_0,
  151179. 1, -520986624, 1620377600, 4, 0,
  151180. _vq_quantlist__44u9_p8_0,
  151181. NULL,
  151182. &_vq_auxt__44u9_p8_0,
  151183. NULL,
  151184. 0
  151185. };
  151186. static long _vq_quantlist__44u9_p8_1[] = {
  151187. 10,
  151188. 9,
  151189. 11,
  151190. 8,
  151191. 12,
  151192. 7,
  151193. 13,
  151194. 6,
  151195. 14,
  151196. 5,
  151197. 15,
  151198. 4,
  151199. 16,
  151200. 3,
  151201. 17,
  151202. 2,
  151203. 18,
  151204. 1,
  151205. 19,
  151206. 0,
  151207. 20,
  151208. };
  151209. static long _vq_lengthlist__44u9_p8_1[] = {
  151210. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151211. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151212. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  151213. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151214. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  151215. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151216. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151217. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  151218. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151219. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151220. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  151221. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  151222. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151223. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151224. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151225. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151226. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151227. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151228. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  151229. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151230. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151231. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  151232. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  151233. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  151234. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151235. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  151236. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151237. 10,10,10,10,10,10,10,10,10,
  151238. };
  151239. static float _vq_quantthresh__44u9_p8_1[] = {
  151240. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151241. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151242. 6.5, 7.5, 8.5, 9.5,
  151243. };
  151244. static long _vq_quantmap__44u9_p8_1[] = {
  151245. 19, 17, 15, 13, 11, 9, 7, 5,
  151246. 3, 1, 0, 2, 4, 6, 8, 10,
  151247. 12, 14, 16, 18, 20,
  151248. };
  151249. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  151250. _vq_quantthresh__44u9_p8_1,
  151251. _vq_quantmap__44u9_p8_1,
  151252. 21,
  151253. 21
  151254. };
  151255. static static_codebook _44u9_p8_1 = {
  151256. 2, 441,
  151257. _vq_lengthlist__44u9_p8_1,
  151258. 1, -529268736, 1611661312, 5, 0,
  151259. _vq_quantlist__44u9_p8_1,
  151260. NULL,
  151261. &_vq_auxt__44u9_p8_1,
  151262. NULL,
  151263. 0
  151264. };
  151265. static long _vq_quantlist__44u9_p9_0[] = {
  151266. 7,
  151267. 6,
  151268. 8,
  151269. 5,
  151270. 9,
  151271. 4,
  151272. 10,
  151273. 3,
  151274. 11,
  151275. 2,
  151276. 12,
  151277. 1,
  151278. 13,
  151279. 0,
  151280. 14,
  151281. };
  151282. static long _vq_lengthlist__44u9_p9_0[] = {
  151283. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  151284. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  151285. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151286. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151287. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151289. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151290. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151291. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151292. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151293. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151295. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151296. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151297. 10,
  151298. };
  151299. static float _vq_quantthresh__44u9_p9_0[] = {
  151300. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  151301. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  151302. };
  151303. static long _vq_quantmap__44u9_p9_0[] = {
  151304. 13, 11, 9, 7, 5, 3, 1, 0,
  151305. 2, 4, 6, 8, 10, 12, 14,
  151306. };
  151307. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  151308. _vq_quantthresh__44u9_p9_0,
  151309. _vq_quantmap__44u9_p9_0,
  151310. 15,
  151311. 15
  151312. };
  151313. static static_codebook _44u9_p9_0 = {
  151314. 2, 225,
  151315. _vq_lengthlist__44u9_p9_0,
  151316. 1, -510036736, 1631393792, 4, 0,
  151317. _vq_quantlist__44u9_p9_0,
  151318. NULL,
  151319. &_vq_auxt__44u9_p9_0,
  151320. NULL,
  151321. 0
  151322. };
  151323. static long _vq_quantlist__44u9_p9_1[] = {
  151324. 9,
  151325. 8,
  151326. 10,
  151327. 7,
  151328. 11,
  151329. 6,
  151330. 12,
  151331. 5,
  151332. 13,
  151333. 4,
  151334. 14,
  151335. 3,
  151336. 15,
  151337. 2,
  151338. 16,
  151339. 1,
  151340. 17,
  151341. 0,
  151342. 18,
  151343. };
  151344. static long _vq_lengthlist__44u9_p9_1[] = {
  151345. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  151346. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  151347. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  151348. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  151349. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  151350. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  151351. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  151352. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  151353. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  151354. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  151355. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  151356. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  151357. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  151358. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  151359. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  151360. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  151361. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  151362. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  151363. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  151364. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  151365. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  151366. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  151367. 17,17,15,17,15,17,16,16,17,
  151368. };
  151369. static float _vq_quantthresh__44u9_p9_1[] = {
  151370. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151371. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151372. 367.5, 416.5,
  151373. };
  151374. static long _vq_quantmap__44u9_p9_1[] = {
  151375. 17, 15, 13, 11, 9, 7, 5, 3,
  151376. 1, 0, 2, 4, 6, 8, 10, 12,
  151377. 14, 16, 18,
  151378. };
  151379. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  151380. _vq_quantthresh__44u9_p9_1,
  151381. _vq_quantmap__44u9_p9_1,
  151382. 19,
  151383. 19
  151384. };
  151385. static static_codebook _44u9_p9_1 = {
  151386. 2, 361,
  151387. _vq_lengthlist__44u9_p9_1,
  151388. 1, -518287360, 1622704128, 5, 0,
  151389. _vq_quantlist__44u9_p9_1,
  151390. NULL,
  151391. &_vq_auxt__44u9_p9_1,
  151392. NULL,
  151393. 0
  151394. };
  151395. static long _vq_quantlist__44u9_p9_2[] = {
  151396. 24,
  151397. 23,
  151398. 25,
  151399. 22,
  151400. 26,
  151401. 21,
  151402. 27,
  151403. 20,
  151404. 28,
  151405. 19,
  151406. 29,
  151407. 18,
  151408. 30,
  151409. 17,
  151410. 31,
  151411. 16,
  151412. 32,
  151413. 15,
  151414. 33,
  151415. 14,
  151416. 34,
  151417. 13,
  151418. 35,
  151419. 12,
  151420. 36,
  151421. 11,
  151422. 37,
  151423. 10,
  151424. 38,
  151425. 9,
  151426. 39,
  151427. 8,
  151428. 40,
  151429. 7,
  151430. 41,
  151431. 6,
  151432. 42,
  151433. 5,
  151434. 43,
  151435. 4,
  151436. 44,
  151437. 3,
  151438. 45,
  151439. 2,
  151440. 46,
  151441. 1,
  151442. 47,
  151443. 0,
  151444. 48,
  151445. };
  151446. static long _vq_lengthlist__44u9_p9_2[] = {
  151447. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151448. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151449. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151450. 7,
  151451. };
  151452. static float _vq_quantthresh__44u9_p9_2[] = {
  151453. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151454. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151455. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151456. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151457. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151458. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151459. };
  151460. static long _vq_quantmap__44u9_p9_2[] = {
  151461. 47, 45, 43, 41, 39, 37, 35, 33,
  151462. 31, 29, 27, 25, 23, 21, 19, 17,
  151463. 15, 13, 11, 9, 7, 5, 3, 1,
  151464. 0, 2, 4, 6, 8, 10, 12, 14,
  151465. 16, 18, 20, 22, 24, 26, 28, 30,
  151466. 32, 34, 36, 38, 40, 42, 44, 46,
  151467. 48,
  151468. };
  151469. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  151470. _vq_quantthresh__44u9_p9_2,
  151471. _vq_quantmap__44u9_p9_2,
  151472. 49,
  151473. 49
  151474. };
  151475. static static_codebook _44u9_p9_2 = {
  151476. 1, 49,
  151477. _vq_lengthlist__44u9_p9_2,
  151478. 1, -526909440, 1611661312, 6, 0,
  151479. _vq_quantlist__44u9_p9_2,
  151480. NULL,
  151481. &_vq_auxt__44u9_p9_2,
  151482. NULL,
  151483. 0
  151484. };
  151485. static long _huff_lengthlist__44un1__long[] = {
  151486. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  151487. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  151488. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  151489. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  151490. };
  151491. static static_codebook _huff_book__44un1__long = {
  151492. 2, 64,
  151493. _huff_lengthlist__44un1__long,
  151494. 0, 0, 0, 0, 0,
  151495. NULL,
  151496. NULL,
  151497. NULL,
  151498. NULL,
  151499. 0
  151500. };
  151501. static long _vq_quantlist__44un1__p1_0[] = {
  151502. 1,
  151503. 0,
  151504. 2,
  151505. };
  151506. static long _vq_lengthlist__44un1__p1_0[] = {
  151507. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  151508. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  151509. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  151510. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  151511. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  151512. 12,
  151513. };
  151514. static float _vq_quantthresh__44un1__p1_0[] = {
  151515. -0.5, 0.5,
  151516. };
  151517. static long _vq_quantmap__44un1__p1_0[] = {
  151518. 1, 0, 2,
  151519. };
  151520. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  151521. _vq_quantthresh__44un1__p1_0,
  151522. _vq_quantmap__44un1__p1_0,
  151523. 3,
  151524. 3
  151525. };
  151526. static static_codebook _44un1__p1_0 = {
  151527. 4, 81,
  151528. _vq_lengthlist__44un1__p1_0,
  151529. 1, -535822336, 1611661312, 2, 0,
  151530. _vq_quantlist__44un1__p1_0,
  151531. NULL,
  151532. &_vq_auxt__44un1__p1_0,
  151533. NULL,
  151534. 0
  151535. };
  151536. static long _vq_quantlist__44un1__p2_0[] = {
  151537. 1,
  151538. 0,
  151539. 2,
  151540. };
  151541. static long _vq_lengthlist__44un1__p2_0[] = {
  151542. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  151543. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  151544. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  151545. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  151546. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  151547. 8,
  151548. };
  151549. static float _vq_quantthresh__44un1__p2_0[] = {
  151550. -0.5, 0.5,
  151551. };
  151552. static long _vq_quantmap__44un1__p2_0[] = {
  151553. 1, 0, 2,
  151554. };
  151555. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  151556. _vq_quantthresh__44un1__p2_0,
  151557. _vq_quantmap__44un1__p2_0,
  151558. 3,
  151559. 3
  151560. };
  151561. static static_codebook _44un1__p2_0 = {
  151562. 4, 81,
  151563. _vq_lengthlist__44un1__p2_0,
  151564. 1, -535822336, 1611661312, 2, 0,
  151565. _vq_quantlist__44un1__p2_0,
  151566. NULL,
  151567. &_vq_auxt__44un1__p2_0,
  151568. NULL,
  151569. 0
  151570. };
  151571. static long _vq_quantlist__44un1__p3_0[] = {
  151572. 2,
  151573. 1,
  151574. 3,
  151575. 0,
  151576. 4,
  151577. };
  151578. static long _vq_lengthlist__44un1__p3_0[] = {
  151579. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  151580. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  151581. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  151582. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  151583. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  151584. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  151585. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  151586. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  151587. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  151588. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  151589. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  151590. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  151591. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  151592. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  151593. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  151594. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  151595. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  151596. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  151597. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  151598. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  151599. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  151600. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  151601. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  151602. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  151603. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  151604. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  151605. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  151606. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  151607. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  151608. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  151609. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  151610. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  151611. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  151612. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  151613. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  151614. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  151615. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  151616. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  151617. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  151618. 17,
  151619. };
  151620. static float _vq_quantthresh__44un1__p3_0[] = {
  151621. -1.5, -0.5, 0.5, 1.5,
  151622. };
  151623. static long _vq_quantmap__44un1__p3_0[] = {
  151624. 3, 1, 0, 2, 4,
  151625. };
  151626. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  151627. _vq_quantthresh__44un1__p3_0,
  151628. _vq_quantmap__44un1__p3_0,
  151629. 5,
  151630. 5
  151631. };
  151632. static static_codebook _44un1__p3_0 = {
  151633. 4, 625,
  151634. _vq_lengthlist__44un1__p3_0,
  151635. 1, -533725184, 1611661312, 3, 0,
  151636. _vq_quantlist__44un1__p3_0,
  151637. NULL,
  151638. &_vq_auxt__44un1__p3_0,
  151639. NULL,
  151640. 0
  151641. };
  151642. static long _vq_quantlist__44un1__p4_0[] = {
  151643. 2,
  151644. 1,
  151645. 3,
  151646. 0,
  151647. 4,
  151648. };
  151649. static long _vq_lengthlist__44un1__p4_0[] = {
  151650. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  151651. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  151652. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  151653. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  151654. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  151655. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  151656. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  151657. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  151658. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  151659. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  151660. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  151661. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  151662. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  151663. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  151664. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  151665. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  151666. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  151667. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  151668. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  151669. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  151670. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  151671. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  151672. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  151673. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  151674. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  151675. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  151676. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  151677. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  151678. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  151679. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  151680. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  151681. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  151682. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  151683. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  151684. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  151685. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  151686. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  151687. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  151688. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  151689. 12,
  151690. };
  151691. static float _vq_quantthresh__44un1__p4_0[] = {
  151692. -1.5, -0.5, 0.5, 1.5,
  151693. };
  151694. static long _vq_quantmap__44un1__p4_0[] = {
  151695. 3, 1, 0, 2, 4,
  151696. };
  151697. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  151698. _vq_quantthresh__44un1__p4_0,
  151699. _vq_quantmap__44un1__p4_0,
  151700. 5,
  151701. 5
  151702. };
  151703. static static_codebook _44un1__p4_0 = {
  151704. 4, 625,
  151705. _vq_lengthlist__44un1__p4_0,
  151706. 1, -533725184, 1611661312, 3, 0,
  151707. _vq_quantlist__44un1__p4_0,
  151708. NULL,
  151709. &_vq_auxt__44un1__p4_0,
  151710. NULL,
  151711. 0
  151712. };
  151713. static long _vq_quantlist__44un1__p5_0[] = {
  151714. 4,
  151715. 3,
  151716. 5,
  151717. 2,
  151718. 6,
  151719. 1,
  151720. 7,
  151721. 0,
  151722. 8,
  151723. };
  151724. static long _vq_lengthlist__44un1__p5_0[] = {
  151725. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  151726. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  151727. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  151728. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  151729. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  151730. 12,
  151731. };
  151732. static float _vq_quantthresh__44un1__p5_0[] = {
  151733. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151734. };
  151735. static long _vq_quantmap__44un1__p5_0[] = {
  151736. 7, 5, 3, 1, 0, 2, 4, 6,
  151737. 8,
  151738. };
  151739. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  151740. _vq_quantthresh__44un1__p5_0,
  151741. _vq_quantmap__44un1__p5_0,
  151742. 9,
  151743. 9
  151744. };
  151745. static static_codebook _44un1__p5_0 = {
  151746. 2, 81,
  151747. _vq_lengthlist__44un1__p5_0,
  151748. 1, -531628032, 1611661312, 4, 0,
  151749. _vq_quantlist__44un1__p5_0,
  151750. NULL,
  151751. &_vq_auxt__44un1__p5_0,
  151752. NULL,
  151753. 0
  151754. };
  151755. static long _vq_quantlist__44un1__p6_0[] = {
  151756. 6,
  151757. 5,
  151758. 7,
  151759. 4,
  151760. 8,
  151761. 3,
  151762. 9,
  151763. 2,
  151764. 10,
  151765. 1,
  151766. 11,
  151767. 0,
  151768. 12,
  151769. };
  151770. static long _vq_lengthlist__44un1__p6_0[] = {
  151771. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  151772. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  151773. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  151774. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  151775. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  151776. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  151777. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  151778. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  151779. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  151780. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  151781. 16, 0,15,18,18, 0,16, 0, 0,
  151782. };
  151783. static float _vq_quantthresh__44un1__p6_0[] = {
  151784. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151785. 12.5, 17.5, 22.5, 27.5,
  151786. };
  151787. static long _vq_quantmap__44un1__p6_0[] = {
  151788. 11, 9, 7, 5, 3, 1, 0, 2,
  151789. 4, 6, 8, 10, 12,
  151790. };
  151791. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  151792. _vq_quantthresh__44un1__p6_0,
  151793. _vq_quantmap__44un1__p6_0,
  151794. 13,
  151795. 13
  151796. };
  151797. static static_codebook _44un1__p6_0 = {
  151798. 2, 169,
  151799. _vq_lengthlist__44un1__p6_0,
  151800. 1, -526516224, 1616117760, 4, 0,
  151801. _vq_quantlist__44un1__p6_0,
  151802. NULL,
  151803. &_vq_auxt__44un1__p6_0,
  151804. NULL,
  151805. 0
  151806. };
  151807. static long _vq_quantlist__44un1__p6_1[] = {
  151808. 2,
  151809. 1,
  151810. 3,
  151811. 0,
  151812. 4,
  151813. };
  151814. static long _vq_lengthlist__44un1__p6_1[] = {
  151815. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  151816. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  151817. };
  151818. static float _vq_quantthresh__44un1__p6_1[] = {
  151819. -1.5, -0.5, 0.5, 1.5,
  151820. };
  151821. static long _vq_quantmap__44un1__p6_1[] = {
  151822. 3, 1, 0, 2, 4,
  151823. };
  151824. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  151825. _vq_quantthresh__44un1__p6_1,
  151826. _vq_quantmap__44un1__p6_1,
  151827. 5,
  151828. 5
  151829. };
  151830. static static_codebook _44un1__p6_1 = {
  151831. 2, 25,
  151832. _vq_lengthlist__44un1__p6_1,
  151833. 1, -533725184, 1611661312, 3, 0,
  151834. _vq_quantlist__44un1__p6_1,
  151835. NULL,
  151836. &_vq_auxt__44un1__p6_1,
  151837. NULL,
  151838. 0
  151839. };
  151840. static long _vq_quantlist__44un1__p7_0[] = {
  151841. 2,
  151842. 1,
  151843. 3,
  151844. 0,
  151845. 4,
  151846. };
  151847. static long _vq_lengthlist__44un1__p7_0[] = {
  151848. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  151849. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  151850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151851. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151852. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151853. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151855. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  151856. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151857. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151858. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  151859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151860. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151861. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151863. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  151864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151865. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  151866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151867. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151874. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151875. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151876. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151877. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151878. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151880. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151881. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151882. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151883. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151884. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151885. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151886. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151887. 10,
  151888. };
  151889. static float _vq_quantthresh__44un1__p7_0[] = {
  151890. -253.5, -84.5, 84.5, 253.5,
  151891. };
  151892. static long _vq_quantmap__44un1__p7_0[] = {
  151893. 3, 1, 0, 2, 4,
  151894. };
  151895. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  151896. _vq_quantthresh__44un1__p7_0,
  151897. _vq_quantmap__44un1__p7_0,
  151898. 5,
  151899. 5
  151900. };
  151901. static static_codebook _44un1__p7_0 = {
  151902. 4, 625,
  151903. _vq_lengthlist__44un1__p7_0,
  151904. 1, -518709248, 1626677248, 3, 0,
  151905. _vq_quantlist__44un1__p7_0,
  151906. NULL,
  151907. &_vq_auxt__44un1__p7_0,
  151908. NULL,
  151909. 0
  151910. };
  151911. static long _vq_quantlist__44un1__p7_1[] = {
  151912. 6,
  151913. 5,
  151914. 7,
  151915. 4,
  151916. 8,
  151917. 3,
  151918. 9,
  151919. 2,
  151920. 10,
  151921. 1,
  151922. 11,
  151923. 0,
  151924. 12,
  151925. };
  151926. static long _vq_lengthlist__44un1__p7_1[] = {
  151927. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  151928. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  151929. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  151930. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  151931. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  151932. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  151933. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  151934. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  151935. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  151936. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  151937. 12,13,13,12,13,13,14,14,14,
  151938. };
  151939. static float _vq_quantthresh__44un1__p7_1[] = {
  151940. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  151941. 32.5, 45.5, 58.5, 71.5,
  151942. };
  151943. static long _vq_quantmap__44un1__p7_1[] = {
  151944. 11, 9, 7, 5, 3, 1, 0, 2,
  151945. 4, 6, 8, 10, 12,
  151946. };
  151947. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  151948. _vq_quantthresh__44un1__p7_1,
  151949. _vq_quantmap__44un1__p7_1,
  151950. 13,
  151951. 13
  151952. };
  151953. static static_codebook _44un1__p7_1 = {
  151954. 2, 169,
  151955. _vq_lengthlist__44un1__p7_1,
  151956. 1, -523010048, 1618608128, 4, 0,
  151957. _vq_quantlist__44un1__p7_1,
  151958. NULL,
  151959. &_vq_auxt__44un1__p7_1,
  151960. NULL,
  151961. 0
  151962. };
  151963. static long _vq_quantlist__44un1__p7_2[] = {
  151964. 6,
  151965. 5,
  151966. 7,
  151967. 4,
  151968. 8,
  151969. 3,
  151970. 9,
  151971. 2,
  151972. 10,
  151973. 1,
  151974. 11,
  151975. 0,
  151976. 12,
  151977. };
  151978. static long _vq_lengthlist__44un1__p7_2[] = {
  151979. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  151980. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  151981. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  151982. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  151983. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  151984. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  151985. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  151986. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  151987. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  151988. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  151989. 9, 9, 9,10,10,10,10,10,10,
  151990. };
  151991. static float _vq_quantthresh__44un1__p7_2[] = {
  151992. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  151993. 2.5, 3.5, 4.5, 5.5,
  151994. };
  151995. static long _vq_quantmap__44un1__p7_2[] = {
  151996. 11, 9, 7, 5, 3, 1, 0, 2,
  151997. 4, 6, 8, 10, 12,
  151998. };
  151999. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152000. _vq_quantthresh__44un1__p7_2,
  152001. _vq_quantmap__44un1__p7_2,
  152002. 13,
  152003. 13
  152004. };
  152005. static static_codebook _44un1__p7_2 = {
  152006. 2, 169,
  152007. _vq_lengthlist__44un1__p7_2,
  152008. 1, -531103744, 1611661312, 4, 0,
  152009. _vq_quantlist__44un1__p7_2,
  152010. NULL,
  152011. &_vq_auxt__44un1__p7_2,
  152012. NULL,
  152013. 0
  152014. };
  152015. static long _huff_lengthlist__44un1__short[] = {
  152016. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152017. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152018. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152019. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152020. };
  152021. static static_codebook _huff_book__44un1__short = {
  152022. 2, 64,
  152023. _huff_lengthlist__44un1__short,
  152024. 0, 0, 0, 0, 0,
  152025. NULL,
  152026. NULL,
  152027. NULL,
  152028. NULL,
  152029. 0
  152030. };
  152031. /*** End of inlined file: res_books_uncoupled.h ***/
  152032. /***** residue backends *********************************************/
  152033. static vorbis_info_residue0 _residue_44_low_un={
  152034. 0,-1, -1, 8,-1,
  152035. {0},
  152036. {-1},
  152037. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152038. { -1, 25, -1, 45, -1, -1, -1}
  152039. };
  152040. static vorbis_info_residue0 _residue_44_mid_un={
  152041. 0,-1, -1, 10,-1,
  152042. /* 0 1 2 3 4 5 6 7 8 9 */
  152043. {0},
  152044. {-1},
  152045. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152046. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152047. };
  152048. static vorbis_info_residue0 _residue_44_hi_un={
  152049. 0,-1, -1, 10,-1,
  152050. /* 0 1 2 3 4 5 6 7 8 9 */
  152051. {0},
  152052. {-1},
  152053. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152054. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152055. };
  152056. /* mapping conventions:
  152057. only one submap (this would change for efficient 5.1 support for example)*/
  152058. /* Four psychoacoustic profiles are used, one for each blocktype */
  152059. static vorbis_info_mapping0 _map_nominal_u[2]={
  152060. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152061. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152062. };
  152063. static static_bookblock _resbook_44u_n1={
  152064. {
  152065. {0},
  152066. {0,0,&_44un1__p1_0},
  152067. {0,0,&_44un1__p2_0},
  152068. {0,0,&_44un1__p3_0},
  152069. {0,0,&_44un1__p4_0},
  152070. {0,0,&_44un1__p5_0},
  152071. {&_44un1__p6_0,&_44un1__p6_1},
  152072. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152073. }
  152074. };
  152075. static static_bookblock _resbook_44u_0={
  152076. {
  152077. {0},
  152078. {0,0,&_44u0__p1_0},
  152079. {0,0,&_44u0__p2_0},
  152080. {0,0,&_44u0__p3_0},
  152081. {0,0,&_44u0__p4_0},
  152082. {0,0,&_44u0__p5_0},
  152083. {&_44u0__p6_0,&_44u0__p6_1},
  152084. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152085. }
  152086. };
  152087. static static_bookblock _resbook_44u_1={
  152088. {
  152089. {0},
  152090. {0,0,&_44u1__p1_0},
  152091. {0,0,&_44u1__p2_0},
  152092. {0,0,&_44u1__p3_0},
  152093. {0,0,&_44u1__p4_0},
  152094. {0,0,&_44u1__p5_0},
  152095. {&_44u1__p6_0,&_44u1__p6_1},
  152096. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152097. }
  152098. };
  152099. static static_bookblock _resbook_44u_2={
  152100. {
  152101. {0},
  152102. {0,0,&_44u2__p1_0},
  152103. {0,0,&_44u2__p2_0},
  152104. {0,0,&_44u2__p3_0},
  152105. {0,0,&_44u2__p4_0},
  152106. {0,0,&_44u2__p5_0},
  152107. {&_44u2__p6_0,&_44u2__p6_1},
  152108. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152109. }
  152110. };
  152111. static static_bookblock _resbook_44u_3={
  152112. {
  152113. {0},
  152114. {0,0,&_44u3__p1_0},
  152115. {0,0,&_44u3__p2_0},
  152116. {0,0,&_44u3__p3_0},
  152117. {0,0,&_44u3__p4_0},
  152118. {0,0,&_44u3__p5_0},
  152119. {&_44u3__p6_0,&_44u3__p6_1},
  152120. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152121. }
  152122. };
  152123. static static_bookblock _resbook_44u_4={
  152124. {
  152125. {0},
  152126. {0,0,&_44u4__p1_0},
  152127. {0,0,&_44u4__p2_0},
  152128. {0,0,&_44u4__p3_0},
  152129. {0,0,&_44u4__p4_0},
  152130. {0,0,&_44u4__p5_0},
  152131. {&_44u4__p6_0,&_44u4__p6_1},
  152132. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  152133. }
  152134. };
  152135. static static_bookblock _resbook_44u_5={
  152136. {
  152137. {0},
  152138. {0,0,&_44u5__p1_0},
  152139. {0,0,&_44u5__p2_0},
  152140. {0,0,&_44u5__p3_0},
  152141. {0,0,&_44u5__p4_0},
  152142. {0,0,&_44u5__p5_0},
  152143. {0,0,&_44u5__p6_0},
  152144. {&_44u5__p7_0,&_44u5__p7_1},
  152145. {&_44u5__p8_0,&_44u5__p8_1},
  152146. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  152147. }
  152148. };
  152149. static static_bookblock _resbook_44u_6={
  152150. {
  152151. {0},
  152152. {0,0,&_44u6__p1_0},
  152153. {0,0,&_44u6__p2_0},
  152154. {0,0,&_44u6__p3_0},
  152155. {0,0,&_44u6__p4_0},
  152156. {0,0,&_44u6__p5_0},
  152157. {0,0,&_44u6__p6_0},
  152158. {&_44u6__p7_0,&_44u6__p7_1},
  152159. {&_44u6__p8_0,&_44u6__p8_1},
  152160. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  152161. }
  152162. };
  152163. static static_bookblock _resbook_44u_7={
  152164. {
  152165. {0},
  152166. {0,0,&_44u7__p1_0},
  152167. {0,0,&_44u7__p2_0},
  152168. {0,0,&_44u7__p3_0},
  152169. {0,0,&_44u7__p4_0},
  152170. {0,0,&_44u7__p5_0},
  152171. {0,0,&_44u7__p6_0},
  152172. {&_44u7__p7_0,&_44u7__p7_1},
  152173. {&_44u7__p8_0,&_44u7__p8_1},
  152174. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  152175. }
  152176. };
  152177. static static_bookblock _resbook_44u_8={
  152178. {
  152179. {0},
  152180. {0,0,&_44u8_p1_0},
  152181. {0,0,&_44u8_p2_0},
  152182. {0,0,&_44u8_p3_0},
  152183. {0,0,&_44u8_p4_0},
  152184. {&_44u8_p5_0,&_44u8_p5_1},
  152185. {&_44u8_p6_0,&_44u8_p6_1},
  152186. {&_44u8_p7_0,&_44u8_p7_1},
  152187. {&_44u8_p8_0,&_44u8_p8_1},
  152188. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  152189. }
  152190. };
  152191. static static_bookblock _resbook_44u_9={
  152192. {
  152193. {0},
  152194. {0,0,&_44u9_p1_0},
  152195. {0,0,&_44u9_p2_0},
  152196. {0,0,&_44u9_p3_0},
  152197. {0,0,&_44u9_p4_0},
  152198. {&_44u9_p5_0,&_44u9_p5_1},
  152199. {&_44u9_p6_0,&_44u9_p6_1},
  152200. {&_44u9_p7_0,&_44u9_p7_1},
  152201. {&_44u9_p8_0,&_44u9_p8_1},
  152202. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  152203. }
  152204. };
  152205. static vorbis_residue_template _res_44u_n1[]={
  152206. {1,0, &_residue_44_low_un,
  152207. &_huff_book__44un1__short,&_huff_book__44un1__short,
  152208. &_resbook_44u_n1,&_resbook_44u_n1},
  152209. {1,0, &_residue_44_low_un,
  152210. &_huff_book__44un1__long,&_huff_book__44un1__long,
  152211. &_resbook_44u_n1,&_resbook_44u_n1}
  152212. };
  152213. static vorbis_residue_template _res_44u_0[]={
  152214. {1,0, &_residue_44_low_un,
  152215. &_huff_book__44u0__short,&_huff_book__44u0__short,
  152216. &_resbook_44u_0,&_resbook_44u_0},
  152217. {1,0, &_residue_44_low_un,
  152218. &_huff_book__44u0__long,&_huff_book__44u0__long,
  152219. &_resbook_44u_0,&_resbook_44u_0}
  152220. };
  152221. static vorbis_residue_template _res_44u_1[]={
  152222. {1,0, &_residue_44_low_un,
  152223. &_huff_book__44u1__short,&_huff_book__44u1__short,
  152224. &_resbook_44u_1,&_resbook_44u_1},
  152225. {1,0, &_residue_44_low_un,
  152226. &_huff_book__44u1__long,&_huff_book__44u1__long,
  152227. &_resbook_44u_1,&_resbook_44u_1}
  152228. };
  152229. static vorbis_residue_template _res_44u_2[]={
  152230. {1,0, &_residue_44_low_un,
  152231. &_huff_book__44u2__short,&_huff_book__44u2__short,
  152232. &_resbook_44u_2,&_resbook_44u_2},
  152233. {1,0, &_residue_44_low_un,
  152234. &_huff_book__44u2__long,&_huff_book__44u2__long,
  152235. &_resbook_44u_2,&_resbook_44u_2}
  152236. };
  152237. static vorbis_residue_template _res_44u_3[]={
  152238. {1,0, &_residue_44_low_un,
  152239. &_huff_book__44u3__short,&_huff_book__44u3__short,
  152240. &_resbook_44u_3,&_resbook_44u_3},
  152241. {1,0, &_residue_44_low_un,
  152242. &_huff_book__44u3__long,&_huff_book__44u3__long,
  152243. &_resbook_44u_3,&_resbook_44u_3}
  152244. };
  152245. static vorbis_residue_template _res_44u_4[]={
  152246. {1,0, &_residue_44_low_un,
  152247. &_huff_book__44u4__short,&_huff_book__44u4__short,
  152248. &_resbook_44u_4,&_resbook_44u_4},
  152249. {1,0, &_residue_44_low_un,
  152250. &_huff_book__44u4__long,&_huff_book__44u4__long,
  152251. &_resbook_44u_4,&_resbook_44u_4}
  152252. };
  152253. static vorbis_residue_template _res_44u_5[]={
  152254. {1,0, &_residue_44_mid_un,
  152255. &_huff_book__44u5__short,&_huff_book__44u5__short,
  152256. &_resbook_44u_5,&_resbook_44u_5},
  152257. {1,0, &_residue_44_mid_un,
  152258. &_huff_book__44u5__long,&_huff_book__44u5__long,
  152259. &_resbook_44u_5,&_resbook_44u_5}
  152260. };
  152261. static vorbis_residue_template _res_44u_6[]={
  152262. {1,0, &_residue_44_mid_un,
  152263. &_huff_book__44u6__short,&_huff_book__44u6__short,
  152264. &_resbook_44u_6,&_resbook_44u_6},
  152265. {1,0, &_residue_44_mid_un,
  152266. &_huff_book__44u6__long,&_huff_book__44u6__long,
  152267. &_resbook_44u_6,&_resbook_44u_6}
  152268. };
  152269. static vorbis_residue_template _res_44u_7[]={
  152270. {1,0, &_residue_44_mid_un,
  152271. &_huff_book__44u7__short,&_huff_book__44u7__short,
  152272. &_resbook_44u_7,&_resbook_44u_7},
  152273. {1,0, &_residue_44_mid_un,
  152274. &_huff_book__44u7__long,&_huff_book__44u7__long,
  152275. &_resbook_44u_7,&_resbook_44u_7}
  152276. };
  152277. static vorbis_residue_template _res_44u_8[]={
  152278. {1,0, &_residue_44_hi_un,
  152279. &_huff_book__44u8__short,&_huff_book__44u8__short,
  152280. &_resbook_44u_8,&_resbook_44u_8},
  152281. {1,0, &_residue_44_hi_un,
  152282. &_huff_book__44u8__long,&_huff_book__44u8__long,
  152283. &_resbook_44u_8,&_resbook_44u_8}
  152284. };
  152285. static vorbis_residue_template _res_44u_9[]={
  152286. {1,0, &_residue_44_hi_un,
  152287. &_huff_book__44u9__short,&_huff_book__44u9__short,
  152288. &_resbook_44u_9,&_resbook_44u_9},
  152289. {1,0, &_residue_44_hi_un,
  152290. &_huff_book__44u9__long,&_huff_book__44u9__long,
  152291. &_resbook_44u_9,&_resbook_44u_9}
  152292. };
  152293. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  152294. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  152295. { _map_nominal_u, _res_44u_0 }, /* 0 */
  152296. { _map_nominal_u, _res_44u_1 }, /* 1 */
  152297. { _map_nominal_u, _res_44u_2 }, /* 2 */
  152298. { _map_nominal_u, _res_44u_3 }, /* 3 */
  152299. { _map_nominal_u, _res_44u_4 }, /* 4 */
  152300. { _map_nominal_u, _res_44u_5 }, /* 5 */
  152301. { _map_nominal_u, _res_44u_6 }, /* 6 */
  152302. { _map_nominal_u, _res_44u_7 }, /* 7 */
  152303. { _map_nominal_u, _res_44u_8 }, /* 8 */
  152304. { _map_nominal_u, _res_44u_9 }, /* 9 */
  152305. };
  152306. /*** End of inlined file: residue_44u.h ***/
  152307. static double rate_mapping_44_un[12]={
  152308. 32000.,48000.,60000.,70000.,80000.,86000.,
  152309. 96000.,110000.,120000.,140000.,160000.,240001.
  152310. };
  152311. ve_setup_data_template ve_setup_44_uncoupled={
  152312. 11,
  152313. rate_mapping_44_un,
  152314. quality_mapping_44,
  152315. -1,
  152316. 40000,
  152317. 50000,
  152318. blocksize_short_44,
  152319. blocksize_long_44,
  152320. _psy_tone_masteratt_44,
  152321. _psy_tone_0dB,
  152322. _psy_tone_suppress,
  152323. _vp_tonemask_adj_otherblock,
  152324. _vp_tonemask_adj_longblock,
  152325. _vp_tonemask_adj_otherblock,
  152326. _psy_noiseguards_44,
  152327. _psy_noisebias_impulse,
  152328. _psy_noisebias_padding,
  152329. _psy_noisebias_trans,
  152330. _psy_noisebias_long,
  152331. _psy_noise_suppress,
  152332. _psy_compand_44,
  152333. _psy_compand_short_mapping,
  152334. _psy_compand_long_mapping,
  152335. {_noise_start_short_44,_noise_start_long_44},
  152336. {_noise_part_short_44,_noise_part_long_44},
  152337. _noise_thresh_44,
  152338. _psy_ath_floater,
  152339. _psy_ath_abs,
  152340. _psy_lowpass_44,
  152341. _psy_global_44,
  152342. _global_mapping_44,
  152343. NULL,
  152344. _floor_books,
  152345. _floor,
  152346. _floor_short_mapping_44,
  152347. _floor_long_mapping_44,
  152348. _mapres_template_44_uncoupled
  152349. };
  152350. /*** End of inlined file: setup_44u.h ***/
  152351. /*** Start of inlined file: setup_32.h ***/
  152352. static double rate_mapping_32[12]={
  152353. 18000.,28000.,35000.,45000.,56000.,60000.,
  152354. 75000.,90000.,100000.,115000.,150000.,190000.,
  152355. };
  152356. static double rate_mapping_32_un[12]={
  152357. 30000.,42000.,52000.,64000.,72000.,78000.,
  152358. 86000.,92000.,110000.,120000.,140000.,190000.,
  152359. };
  152360. static double _psy_lowpass_32[12]={
  152361. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  152362. };
  152363. ve_setup_data_template ve_setup_32_stereo={
  152364. 11,
  152365. rate_mapping_32,
  152366. quality_mapping_44,
  152367. 2,
  152368. 26000,
  152369. 40000,
  152370. blocksize_short_44,
  152371. blocksize_long_44,
  152372. _psy_tone_masteratt_44,
  152373. _psy_tone_0dB,
  152374. _psy_tone_suppress,
  152375. _vp_tonemask_adj_otherblock,
  152376. _vp_tonemask_adj_longblock,
  152377. _vp_tonemask_adj_otherblock,
  152378. _psy_noiseguards_44,
  152379. _psy_noisebias_impulse,
  152380. _psy_noisebias_padding,
  152381. _psy_noisebias_trans,
  152382. _psy_noisebias_long,
  152383. _psy_noise_suppress,
  152384. _psy_compand_44,
  152385. _psy_compand_short_mapping,
  152386. _psy_compand_long_mapping,
  152387. {_noise_start_short_44,_noise_start_long_44},
  152388. {_noise_part_short_44,_noise_part_long_44},
  152389. _noise_thresh_44,
  152390. _psy_ath_floater,
  152391. _psy_ath_abs,
  152392. _psy_lowpass_32,
  152393. _psy_global_44,
  152394. _global_mapping_44,
  152395. _psy_stereo_modes_44,
  152396. _floor_books,
  152397. _floor,
  152398. _floor_short_mapping_44,
  152399. _floor_long_mapping_44,
  152400. _mapres_template_44_stereo
  152401. };
  152402. ve_setup_data_template ve_setup_32_uncoupled={
  152403. 11,
  152404. rate_mapping_32_un,
  152405. quality_mapping_44,
  152406. -1,
  152407. 26000,
  152408. 40000,
  152409. blocksize_short_44,
  152410. blocksize_long_44,
  152411. _psy_tone_masteratt_44,
  152412. _psy_tone_0dB,
  152413. _psy_tone_suppress,
  152414. _vp_tonemask_adj_otherblock,
  152415. _vp_tonemask_adj_longblock,
  152416. _vp_tonemask_adj_otherblock,
  152417. _psy_noiseguards_44,
  152418. _psy_noisebias_impulse,
  152419. _psy_noisebias_padding,
  152420. _psy_noisebias_trans,
  152421. _psy_noisebias_long,
  152422. _psy_noise_suppress,
  152423. _psy_compand_44,
  152424. _psy_compand_short_mapping,
  152425. _psy_compand_long_mapping,
  152426. {_noise_start_short_44,_noise_start_long_44},
  152427. {_noise_part_short_44,_noise_part_long_44},
  152428. _noise_thresh_44,
  152429. _psy_ath_floater,
  152430. _psy_ath_abs,
  152431. _psy_lowpass_32,
  152432. _psy_global_44,
  152433. _global_mapping_44,
  152434. NULL,
  152435. _floor_books,
  152436. _floor,
  152437. _floor_short_mapping_44,
  152438. _floor_long_mapping_44,
  152439. _mapres_template_44_uncoupled
  152440. };
  152441. /*** End of inlined file: setup_32.h ***/
  152442. /*** Start of inlined file: setup_8.h ***/
  152443. /*** Start of inlined file: psych_8.h ***/
  152444. static att3 _psy_tone_masteratt_8[3]={
  152445. {{ 32, 25, 12}, 0, 0}, /* 0 */
  152446. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152447. {{ 20, 0, -14}, 0, 0}, /* 0 */
  152448. };
  152449. static vp_adjblock _vp_tonemask_adj_8[3]={
  152450. /* adjust for mode zero */
  152451. /* 63 125 250 500 1 2 4 8 16 */
  152452. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  152453. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  152454. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  152455. };
  152456. static noise3 _psy_noisebias_8[3]={
  152457. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152458. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  152459. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  152460. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152461. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  152462. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  152463. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152464. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  152465. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  152466. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  152467. };
  152468. /* stereo mode by base quality level */
  152469. static adj_stereo _psy_stereo_modes_8[3]={
  152470. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  152471. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152472. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152473. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152474. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152475. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152476. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152477. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152478. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152479. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152480. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152481. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152482. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152483. };
  152484. static noiseguard _psy_noiseguards_8[2]={
  152485. {10,10,-1},
  152486. {10,10,-1},
  152487. };
  152488. static compandblock _psy_compand_8[2]={
  152489. {{
  152490. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  152491. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  152492. 12,12,13,13,14,14,15, 15, /* 23dB */
  152493. 16,16,17,17,17,18,18, 19, /* 31dB */
  152494. 19,19,20,21,22,23,24, 25, /* 39dB */
  152495. }},
  152496. {{
  152497. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  152498. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  152499. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  152500. 9,10,11,12,13,14,15, 16, /* 31dB */
  152501. 17,18,19,20,21,22,23, 24, /* 39dB */
  152502. }},
  152503. };
  152504. static double _psy_lowpass_8[3]={3.,4.,4.};
  152505. static int _noise_start_8[2]={
  152506. 64,64,
  152507. };
  152508. static int _noise_part_8[2]={
  152509. 8,8,
  152510. };
  152511. static int _psy_ath_floater_8[3]={
  152512. -100,-100,-105,
  152513. };
  152514. static int _psy_ath_abs_8[3]={
  152515. -130,-130,-140,
  152516. };
  152517. /*** End of inlined file: psych_8.h ***/
  152518. /*** Start of inlined file: residue_8.h ***/
  152519. /***** residue backends *********************************************/
  152520. static static_bookblock _resbook_8s_0={
  152521. {
  152522. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  152523. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  152524. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  152525. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  152526. }
  152527. };
  152528. static static_bookblock _resbook_8s_1={
  152529. {
  152530. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  152531. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  152532. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  152533. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  152534. }
  152535. };
  152536. static vorbis_residue_template _res_8s_0[]={
  152537. {2,0, &_residue_44_mid,
  152538. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  152539. &_resbook_8s_0,&_resbook_8s_0},
  152540. };
  152541. static vorbis_residue_template _res_8s_1[]={
  152542. {2,0, &_residue_44_mid,
  152543. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  152544. &_resbook_8s_1,&_resbook_8s_1},
  152545. };
  152546. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  152547. { _map_nominal, _res_8s_0 }, /* 0 */
  152548. { _map_nominal, _res_8s_1 }, /* 1 */
  152549. };
  152550. static static_bookblock _resbook_8u_0={
  152551. {
  152552. {0},
  152553. {0,0,&_8u0__p1_0},
  152554. {0,0,&_8u0__p2_0},
  152555. {0,0,&_8u0__p3_0},
  152556. {0,0,&_8u0__p4_0},
  152557. {0,0,&_8u0__p5_0},
  152558. {&_8u0__p6_0,&_8u0__p6_1},
  152559. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  152560. }
  152561. };
  152562. static static_bookblock _resbook_8u_1={
  152563. {
  152564. {0},
  152565. {0,0,&_8u1__p1_0},
  152566. {0,0,&_8u1__p2_0},
  152567. {0,0,&_8u1__p3_0},
  152568. {0,0,&_8u1__p4_0},
  152569. {0,0,&_8u1__p5_0},
  152570. {0,0,&_8u1__p6_0},
  152571. {&_8u1__p7_0,&_8u1__p7_1},
  152572. {&_8u1__p8_0,&_8u1__p8_1},
  152573. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  152574. }
  152575. };
  152576. static vorbis_residue_template _res_8u_0[]={
  152577. {1,0, &_residue_44_low_un,
  152578. &_huff_book__8u0__single,&_huff_book__8u0__single,
  152579. &_resbook_8u_0,&_resbook_8u_0},
  152580. };
  152581. static vorbis_residue_template _res_8u_1[]={
  152582. {1,0, &_residue_44_mid_un,
  152583. &_huff_book__8u1__single,&_huff_book__8u1__single,
  152584. &_resbook_8u_1,&_resbook_8u_1},
  152585. };
  152586. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  152587. { _map_nominal_u, _res_8u_0 }, /* 0 */
  152588. { _map_nominal_u, _res_8u_1 }, /* 1 */
  152589. };
  152590. /*** End of inlined file: residue_8.h ***/
  152591. static int blocksize_8[2]={
  152592. 512,512
  152593. };
  152594. static int _floor_mapping_8[2]={
  152595. 6,6,
  152596. };
  152597. static double rate_mapping_8[3]={
  152598. 6000.,9000.,32000.,
  152599. };
  152600. static double rate_mapping_8_uncoupled[3]={
  152601. 8000.,14000.,42000.,
  152602. };
  152603. static double quality_mapping_8[3]={
  152604. -.1,.0,1.
  152605. };
  152606. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  152607. static double _global_mapping_8[3]={ 1., 2., 3. };
  152608. ve_setup_data_template ve_setup_8_stereo={
  152609. 2,
  152610. rate_mapping_8,
  152611. quality_mapping_8,
  152612. 2,
  152613. 8000,
  152614. 9000,
  152615. blocksize_8,
  152616. blocksize_8,
  152617. _psy_tone_masteratt_8,
  152618. _psy_tone_0dB,
  152619. _psy_tone_suppress,
  152620. _vp_tonemask_adj_8,
  152621. NULL,
  152622. _vp_tonemask_adj_8,
  152623. _psy_noiseguards_8,
  152624. _psy_noisebias_8,
  152625. _psy_noisebias_8,
  152626. NULL,
  152627. NULL,
  152628. _psy_noise_suppress,
  152629. _psy_compand_8,
  152630. _psy_compand_8_mapping,
  152631. NULL,
  152632. {_noise_start_8,_noise_start_8},
  152633. {_noise_part_8,_noise_part_8},
  152634. _noise_thresh_5only,
  152635. _psy_ath_floater_8,
  152636. _psy_ath_abs_8,
  152637. _psy_lowpass_8,
  152638. _psy_global_44,
  152639. _global_mapping_8,
  152640. _psy_stereo_modes_8,
  152641. _floor_books,
  152642. _floor,
  152643. _floor_mapping_8,
  152644. NULL,
  152645. _mapres_template_8_stereo
  152646. };
  152647. ve_setup_data_template ve_setup_8_uncoupled={
  152648. 2,
  152649. rate_mapping_8_uncoupled,
  152650. quality_mapping_8,
  152651. -1,
  152652. 8000,
  152653. 9000,
  152654. blocksize_8,
  152655. blocksize_8,
  152656. _psy_tone_masteratt_8,
  152657. _psy_tone_0dB,
  152658. _psy_tone_suppress,
  152659. _vp_tonemask_adj_8,
  152660. NULL,
  152661. _vp_tonemask_adj_8,
  152662. _psy_noiseguards_8,
  152663. _psy_noisebias_8,
  152664. _psy_noisebias_8,
  152665. NULL,
  152666. NULL,
  152667. _psy_noise_suppress,
  152668. _psy_compand_8,
  152669. _psy_compand_8_mapping,
  152670. NULL,
  152671. {_noise_start_8,_noise_start_8},
  152672. {_noise_part_8,_noise_part_8},
  152673. _noise_thresh_5only,
  152674. _psy_ath_floater_8,
  152675. _psy_ath_abs_8,
  152676. _psy_lowpass_8,
  152677. _psy_global_44,
  152678. _global_mapping_8,
  152679. _psy_stereo_modes_8,
  152680. _floor_books,
  152681. _floor,
  152682. _floor_mapping_8,
  152683. NULL,
  152684. _mapres_template_8_uncoupled
  152685. };
  152686. /*** End of inlined file: setup_8.h ***/
  152687. /*** Start of inlined file: setup_11.h ***/
  152688. /*** Start of inlined file: psych_11.h ***/
  152689. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  152690. static att3 _psy_tone_masteratt_11[3]={
  152691. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152692. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152693. {{ 20, 0, -14}, 0, 0}, /* 0 */
  152694. };
  152695. static vp_adjblock _vp_tonemask_adj_11[3]={
  152696. /* adjust for mode zero */
  152697. /* 63 125 250 500 1 2 4 8 16 */
  152698. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  152699. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  152700. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  152701. };
  152702. static noise3 _psy_noisebias_11[3]={
  152703. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152704. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  152705. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  152706. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152707. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  152708. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  152709. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152710. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  152711. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  152712. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  152713. };
  152714. static double _noise_thresh_11[3]={ .3,.5,.5 };
  152715. /*** End of inlined file: psych_11.h ***/
  152716. static int blocksize_11[2]={
  152717. 512,512
  152718. };
  152719. static int _floor_mapping_11[2]={
  152720. 6,6,
  152721. };
  152722. static double rate_mapping_11[3]={
  152723. 8000.,13000.,44000.,
  152724. };
  152725. static double rate_mapping_11_uncoupled[3]={
  152726. 12000.,20000.,50000.,
  152727. };
  152728. static double quality_mapping_11[3]={
  152729. -.1,.0,1.
  152730. };
  152731. ve_setup_data_template ve_setup_11_stereo={
  152732. 2,
  152733. rate_mapping_11,
  152734. quality_mapping_11,
  152735. 2,
  152736. 9000,
  152737. 15000,
  152738. blocksize_11,
  152739. blocksize_11,
  152740. _psy_tone_masteratt_11,
  152741. _psy_tone_0dB,
  152742. _psy_tone_suppress,
  152743. _vp_tonemask_adj_11,
  152744. NULL,
  152745. _vp_tonemask_adj_11,
  152746. _psy_noiseguards_8,
  152747. _psy_noisebias_11,
  152748. _psy_noisebias_11,
  152749. NULL,
  152750. NULL,
  152751. _psy_noise_suppress,
  152752. _psy_compand_8,
  152753. _psy_compand_8_mapping,
  152754. NULL,
  152755. {_noise_start_8,_noise_start_8},
  152756. {_noise_part_8,_noise_part_8},
  152757. _noise_thresh_11,
  152758. _psy_ath_floater_8,
  152759. _psy_ath_abs_8,
  152760. _psy_lowpass_11,
  152761. _psy_global_44,
  152762. _global_mapping_8,
  152763. _psy_stereo_modes_8,
  152764. _floor_books,
  152765. _floor,
  152766. _floor_mapping_11,
  152767. NULL,
  152768. _mapres_template_8_stereo
  152769. };
  152770. ve_setup_data_template ve_setup_11_uncoupled={
  152771. 2,
  152772. rate_mapping_11_uncoupled,
  152773. quality_mapping_11,
  152774. -1,
  152775. 9000,
  152776. 15000,
  152777. blocksize_11,
  152778. blocksize_11,
  152779. _psy_tone_masteratt_11,
  152780. _psy_tone_0dB,
  152781. _psy_tone_suppress,
  152782. _vp_tonemask_adj_11,
  152783. NULL,
  152784. _vp_tonemask_adj_11,
  152785. _psy_noiseguards_8,
  152786. _psy_noisebias_11,
  152787. _psy_noisebias_11,
  152788. NULL,
  152789. NULL,
  152790. _psy_noise_suppress,
  152791. _psy_compand_8,
  152792. _psy_compand_8_mapping,
  152793. NULL,
  152794. {_noise_start_8,_noise_start_8},
  152795. {_noise_part_8,_noise_part_8},
  152796. _noise_thresh_11,
  152797. _psy_ath_floater_8,
  152798. _psy_ath_abs_8,
  152799. _psy_lowpass_11,
  152800. _psy_global_44,
  152801. _global_mapping_8,
  152802. _psy_stereo_modes_8,
  152803. _floor_books,
  152804. _floor,
  152805. _floor_mapping_11,
  152806. NULL,
  152807. _mapres_template_8_uncoupled
  152808. };
  152809. /*** End of inlined file: setup_11.h ***/
  152810. /*** Start of inlined file: setup_16.h ***/
  152811. /*** Start of inlined file: psych_16.h ***/
  152812. /* stereo mode by base quality level */
  152813. static adj_stereo _psy_stereo_modes_16[4]={
  152814. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  152815. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152816. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152817. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  152818. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152819. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152820. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152821. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  152822. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152823. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152824. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152825. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152826. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152827. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  152828. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  152829. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  152830. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152831. };
  152832. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  152833. static att3 _psy_tone_masteratt_16[4]={
  152834. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152835. {{ 25, 22, 12}, 0, 0}, /* 0 */
  152836. {{ 20, 12, 0}, 0, 0}, /* 0 */
  152837. {{ 15, 0, -14}, 0, 0}, /* 0 */
  152838. };
  152839. static vp_adjblock _vp_tonemask_adj_16[4]={
  152840. /* adjust for mode zero */
  152841. /* 63 125 250 500 1 2 4 8 16 */
  152842. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  152843. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  152844. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  152845. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  152846. };
  152847. static noise3 _psy_noisebias_16_short[4]={
  152848. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152849. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  152850. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  152851. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  152852. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  152853. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  152854. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  152855. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  152856. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  152857. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  152858. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  152859. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  152860. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  152861. };
  152862. static noise3 _psy_noisebias_16_impulse[4]={
  152863. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152864. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  152865. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  152866. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  152867. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  152868. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  152869. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  152870. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  152871. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  152872. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  152873. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  152874. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  152875. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  152876. };
  152877. static noise3 _psy_noisebias_16[4]={
  152878. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152879. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  152880. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  152881. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  152882. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  152883. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  152884. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  152885. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  152886. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  152887. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  152888. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  152889. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  152890. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  152891. };
  152892. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  152893. static int _noise_start_16[3]={ 256,256,9999 };
  152894. static int _noise_part_16[4]={ 8,8,8,8 };
  152895. static int _psy_ath_floater_16[4]={
  152896. -100,-100,-100,-105,
  152897. };
  152898. static int _psy_ath_abs_16[4]={
  152899. -130,-130,-130,-140,
  152900. };
  152901. /*** End of inlined file: psych_16.h ***/
  152902. /*** Start of inlined file: residue_16.h ***/
  152903. /***** residue backends *********************************************/
  152904. static static_bookblock _resbook_16s_0={
  152905. {
  152906. {0},
  152907. {0,0,&_16c0_s_p1_0},
  152908. {0,0,&_16c0_s_p2_0},
  152909. {0,0,&_16c0_s_p3_0},
  152910. {0,0,&_16c0_s_p4_0},
  152911. {0,0,&_16c0_s_p5_0},
  152912. {0,0,&_16c0_s_p6_0},
  152913. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  152914. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  152915. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  152916. }
  152917. };
  152918. static static_bookblock _resbook_16s_1={
  152919. {
  152920. {0},
  152921. {0,0,&_16c1_s_p1_0},
  152922. {0,0,&_16c1_s_p2_0},
  152923. {0,0,&_16c1_s_p3_0},
  152924. {0,0,&_16c1_s_p4_0},
  152925. {0,0,&_16c1_s_p5_0},
  152926. {0,0,&_16c1_s_p6_0},
  152927. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  152928. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  152929. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  152930. }
  152931. };
  152932. static static_bookblock _resbook_16s_2={
  152933. {
  152934. {0},
  152935. {0,0,&_16c2_s_p1_0},
  152936. {0,0,&_16c2_s_p2_0},
  152937. {0,0,&_16c2_s_p3_0},
  152938. {0,0,&_16c2_s_p4_0},
  152939. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  152940. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  152941. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  152942. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  152943. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  152944. }
  152945. };
  152946. static vorbis_residue_template _res_16s_0[]={
  152947. {2,0, &_residue_44_mid,
  152948. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  152949. &_resbook_16s_0,&_resbook_16s_0},
  152950. };
  152951. static vorbis_residue_template _res_16s_1[]={
  152952. {2,0, &_residue_44_mid,
  152953. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  152954. &_resbook_16s_1,&_resbook_16s_1},
  152955. {2,0, &_residue_44_mid,
  152956. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  152957. &_resbook_16s_1,&_resbook_16s_1}
  152958. };
  152959. static vorbis_residue_template _res_16s_2[]={
  152960. {2,0, &_residue_44_high,
  152961. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  152962. &_resbook_16s_2,&_resbook_16s_2},
  152963. {2,0, &_residue_44_high,
  152964. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  152965. &_resbook_16s_2,&_resbook_16s_2}
  152966. };
  152967. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  152968. { _map_nominal, _res_16s_0 }, /* 0 */
  152969. { _map_nominal, _res_16s_1 }, /* 1 */
  152970. { _map_nominal, _res_16s_2 }, /* 2 */
  152971. };
  152972. static static_bookblock _resbook_16u_0={
  152973. {
  152974. {0},
  152975. {0,0,&_16u0__p1_0},
  152976. {0,0,&_16u0__p2_0},
  152977. {0,0,&_16u0__p3_0},
  152978. {0,0,&_16u0__p4_0},
  152979. {0,0,&_16u0__p5_0},
  152980. {&_16u0__p6_0,&_16u0__p6_1},
  152981. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  152982. }
  152983. };
  152984. static static_bookblock _resbook_16u_1={
  152985. {
  152986. {0},
  152987. {0,0,&_16u1__p1_0},
  152988. {0,0,&_16u1__p2_0},
  152989. {0,0,&_16u1__p3_0},
  152990. {0,0,&_16u1__p4_0},
  152991. {0,0,&_16u1__p5_0},
  152992. {0,0,&_16u1__p6_0},
  152993. {&_16u1__p7_0,&_16u1__p7_1},
  152994. {&_16u1__p8_0,&_16u1__p8_1},
  152995. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  152996. }
  152997. };
  152998. static static_bookblock _resbook_16u_2={
  152999. {
  153000. {0},
  153001. {0,0,&_16u2_p1_0},
  153002. {0,0,&_16u2_p2_0},
  153003. {0,0,&_16u2_p3_0},
  153004. {0,0,&_16u2_p4_0},
  153005. {&_16u2_p5_0,&_16u2_p5_1},
  153006. {&_16u2_p6_0,&_16u2_p6_1},
  153007. {&_16u2_p7_0,&_16u2_p7_1},
  153008. {&_16u2_p8_0,&_16u2_p8_1},
  153009. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153010. }
  153011. };
  153012. static vorbis_residue_template _res_16u_0[]={
  153013. {1,0, &_residue_44_low_un,
  153014. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153015. &_resbook_16u_0,&_resbook_16u_0},
  153016. };
  153017. static vorbis_residue_template _res_16u_1[]={
  153018. {1,0, &_residue_44_mid_un,
  153019. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153020. &_resbook_16u_1,&_resbook_16u_1},
  153021. {1,0, &_residue_44_mid_un,
  153022. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153023. &_resbook_16u_1,&_resbook_16u_1}
  153024. };
  153025. static vorbis_residue_template _res_16u_2[]={
  153026. {1,0, &_residue_44_hi_un,
  153027. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153028. &_resbook_16u_2,&_resbook_16u_2},
  153029. {1,0, &_residue_44_hi_un,
  153030. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153031. &_resbook_16u_2,&_resbook_16u_2}
  153032. };
  153033. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153034. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153035. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153036. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153037. };
  153038. /*** End of inlined file: residue_16.h ***/
  153039. static int blocksize_16_short[3]={
  153040. 1024,512,512
  153041. };
  153042. static int blocksize_16_long[3]={
  153043. 1024,1024,1024
  153044. };
  153045. static int _floor_mapping_16_short[3]={
  153046. 9,3,3
  153047. };
  153048. static int _floor_mapping_16[3]={
  153049. 9,9,9
  153050. };
  153051. static double rate_mapping_16[4]={
  153052. 12000.,20000.,44000.,86000.
  153053. };
  153054. static double rate_mapping_16_uncoupled[4]={
  153055. 16000.,28000.,64000.,100000.
  153056. };
  153057. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153058. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153059. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153060. ve_setup_data_template ve_setup_16_stereo={
  153061. 3,
  153062. rate_mapping_16,
  153063. quality_mapping_16,
  153064. 2,
  153065. 15000,
  153066. 19000,
  153067. blocksize_16_short,
  153068. blocksize_16_long,
  153069. _psy_tone_masteratt_16,
  153070. _psy_tone_0dB,
  153071. _psy_tone_suppress,
  153072. _vp_tonemask_adj_16,
  153073. _vp_tonemask_adj_16,
  153074. _vp_tonemask_adj_16,
  153075. _psy_noiseguards_8,
  153076. _psy_noisebias_16_impulse,
  153077. _psy_noisebias_16_short,
  153078. _psy_noisebias_16_short,
  153079. _psy_noisebias_16,
  153080. _psy_noise_suppress,
  153081. _psy_compand_8,
  153082. _psy_compand_16_mapping,
  153083. _psy_compand_16_mapping,
  153084. {_noise_start_16,_noise_start_16},
  153085. { _noise_part_16, _noise_part_16},
  153086. _noise_thresh_16,
  153087. _psy_ath_floater_16,
  153088. _psy_ath_abs_16,
  153089. _psy_lowpass_16,
  153090. _psy_global_44,
  153091. _global_mapping_16,
  153092. _psy_stereo_modes_16,
  153093. _floor_books,
  153094. _floor,
  153095. _floor_mapping_16_short,
  153096. _floor_mapping_16,
  153097. _mapres_template_16_stereo
  153098. };
  153099. ve_setup_data_template ve_setup_16_uncoupled={
  153100. 3,
  153101. rate_mapping_16_uncoupled,
  153102. quality_mapping_16,
  153103. -1,
  153104. 15000,
  153105. 19000,
  153106. blocksize_16_short,
  153107. blocksize_16_long,
  153108. _psy_tone_masteratt_16,
  153109. _psy_tone_0dB,
  153110. _psy_tone_suppress,
  153111. _vp_tonemask_adj_16,
  153112. _vp_tonemask_adj_16,
  153113. _vp_tonemask_adj_16,
  153114. _psy_noiseguards_8,
  153115. _psy_noisebias_16_impulse,
  153116. _psy_noisebias_16_short,
  153117. _psy_noisebias_16_short,
  153118. _psy_noisebias_16,
  153119. _psy_noise_suppress,
  153120. _psy_compand_8,
  153121. _psy_compand_16_mapping,
  153122. _psy_compand_16_mapping,
  153123. {_noise_start_16,_noise_start_16},
  153124. { _noise_part_16, _noise_part_16},
  153125. _noise_thresh_16,
  153126. _psy_ath_floater_16,
  153127. _psy_ath_abs_16,
  153128. _psy_lowpass_16,
  153129. _psy_global_44,
  153130. _global_mapping_16,
  153131. _psy_stereo_modes_16,
  153132. _floor_books,
  153133. _floor,
  153134. _floor_mapping_16_short,
  153135. _floor_mapping_16,
  153136. _mapres_template_16_uncoupled
  153137. };
  153138. /*** End of inlined file: setup_16.h ***/
  153139. /*** Start of inlined file: setup_22.h ***/
  153140. static double rate_mapping_22[4]={
  153141. 15000.,20000.,44000.,86000.
  153142. };
  153143. static double rate_mapping_22_uncoupled[4]={
  153144. 16000.,28000.,50000.,90000.
  153145. };
  153146. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  153147. ve_setup_data_template ve_setup_22_stereo={
  153148. 3,
  153149. rate_mapping_22,
  153150. quality_mapping_16,
  153151. 2,
  153152. 19000,
  153153. 26000,
  153154. blocksize_16_short,
  153155. blocksize_16_long,
  153156. _psy_tone_masteratt_16,
  153157. _psy_tone_0dB,
  153158. _psy_tone_suppress,
  153159. _vp_tonemask_adj_16,
  153160. _vp_tonemask_adj_16,
  153161. _vp_tonemask_adj_16,
  153162. _psy_noiseguards_8,
  153163. _psy_noisebias_16_impulse,
  153164. _psy_noisebias_16_short,
  153165. _psy_noisebias_16_short,
  153166. _psy_noisebias_16,
  153167. _psy_noise_suppress,
  153168. _psy_compand_8,
  153169. _psy_compand_8_mapping,
  153170. _psy_compand_8_mapping,
  153171. {_noise_start_16,_noise_start_16},
  153172. { _noise_part_16, _noise_part_16},
  153173. _noise_thresh_16,
  153174. _psy_ath_floater_16,
  153175. _psy_ath_abs_16,
  153176. _psy_lowpass_22,
  153177. _psy_global_44,
  153178. _global_mapping_16,
  153179. _psy_stereo_modes_16,
  153180. _floor_books,
  153181. _floor,
  153182. _floor_mapping_16_short,
  153183. _floor_mapping_16,
  153184. _mapres_template_16_stereo
  153185. };
  153186. ve_setup_data_template ve_setup_22_uncoupled={
  153187. 3,
  153188. rate_mapping_22_uncoupled,
  153189. quality_mapping_16,
  153190. -1,
  153191. 19000,
  153192. 26000,
  153193. blocksize_16_short,
  153194. blocksize_16_long,
  153195. _psy_tone_masteratt_16,
  153196. _psy_tone_0dB,
  153197. _psy_tone_suppress,
  153198. _vp_tonemask_adj_16,
  153199. _vp_tonemask_adj_16,
  153200. _vp_tonemask_adj_16,
  153201. _psy_noiseguards_8,
  153202. _psy_noisebias_16_impulse,
  153203. _psy_noisebias_16_short,
  153204. _psy_noisebias_16_short,
  153205. _psy_noisebias_16,
  153206. _psy_noise_suppress,
  153207. _psy_compand_8,
  153208. _psy_compand_8_mapping,
  153209. _psy_compand_8_mapping,
  153210. {_noise_start_16,_noise_start_16},
  153211. { _noise_part_16, _noise_part_16},
  153212. _noise_thresh_16,
  153213. _psy_ath_floater_16,
  153214. _psy_ath_abs_16,
  153215. _psy_lowpass_22,
  153216. _psy_global_44,
  153217. _global_mapping_16,
  153218. _psy_stereo_modes_16,
  153219. _floor_books,
  153220. _floor,
  153221. _floor_mapping_16_short,
  153222. _floor_mapping_16,
  153223. _mapres_template_16_uncoupled
  153224. };
  153225. /*** End of inlined file: setup_22.h ***/
  153226. /*** Start of inlined file: setup_X.h ***/
  153227. static double rate_mapping_X[12]={
  153228. -1.,-1.,-1.,-1.,-1.,-1.,
  153229. -1.,-1.,-1.,-1.,-1.,-1.
  153230. };
  153231. ve_setup_data_template ve_setup_X_stereo={
  153232. 11,
  153233. rate_mapping_X,
  153234. quality_mapping_44,
  153235. 2,
  153236. 50000,
  153237. 200000,
  153238. blocksize_short_44,
  153239. blocksize_long_44,
  153240. _psy_tone_masteratt_44,
  153241. _psy_tone_0dB,
  153242. _psy_tone_suppress,
  153243. _vp_tonemask_adj_otherblock,
  153244. _vp_tonemask_adj_longblock,
  153245. _vp_tonemask_adj_otherblock,
  153246. _psy_noiseguards_44,
  153247. _psy_noisebias_impulse,
  153248. _psy_noisebias_padding,
  153249. _psy_noisebias_trans,
  153250. _psy_noisebias_long,
  153251. _psy_noise_suppress,
  153252. _psy_compand_44,
  153253. _psy_compand_short_mapping,
  153254. _psy_compand_long_mapping,
  153255. {_noise_start_short_44,_noise_start_long_44},
  153256. {_noise_part_short_44,_noise_part_long_44},
  153257. _noise_thresh_44,
  153258. _psy_ath_floater,
  153259. _psy_ath_abs,
  153260. _psy_lowpass_44,
  153261. _psy_global_44,
  153262. _global_mapping_44,
  153263. _psy_stereo_modes_44,
  153264. _floor_books,
  153265. _floor,
  153266. _floor_short_mapping_44,
  153267. _floor_long_mapping_44,
  153268. _mapres_template_44_stereo
  153269. };
  153270. ve_setup_data_template ve_setup_X_uncoupled={
  153271. 11,
  153272. rate_mapping_X,
  153273. quality_mapping_44,
  153274. -1,
  153275. 50000,
  153276. 200000,
  153277. blocksize_short_44,
  153278. blocksize_long_44,
  153279. _psy_tone_masteratt_44,
  153280. _psy_tone_0dB,
  153281. _psy_tone_suppress,
  153282. _vp_tonemask_adj_otherblock,
  153283. _vp_tonemask_adj_longblock,
  153284. _vp_tonemask_adj_otherblock,
  153285. _psy_noiseguards_44,
  153286. _psy_noisebias_impulse,
  153287. _psy_noisebias_padding,
  153288. _psy_noisebias_trans,
  153289. _psy_noisebias_long,
  153290. _psy_noise_suppress,
  153291. _psy_compand_44,
  153292. _psy_compand_short_mapping,
  153293. _psy_compand_long_mapping,
  153294. {_noise_start_short_44,_noise_start_long_44},
  153295. {_noise_part_short_44,_noise_part_long_44},
  153296. _noise_thresh_44,
  153297. _psy_ath_floater,
  153298. _psy_ath_abs,
  153299. _psy_lowpass_44,
  153300. _psy_global_44,
  153301. _global_mapping_44,
  153302. NULL,
  153303. _floor_books,
  153304. _floor,
  153305. _floor_short_mapping_44,
  153306. _floor_long_mapping_44,
  153307. _mapres_template_44_uncoupled
  153308. };
  153309. ve_setup_data_template ve_setup_XX_stereo={
  153310. 2,
  153311. rate_mapping_X,
  153312. quality_mapping_8,
  153313. 2,
  153314. 0,
  153315. 8000,
  153316. blocksize_8,
  153317. blocksize_8,
  153318. _psy_tone_masteratt_8,
  153319. _psy_tone_0dB,
  153320. _psy_tone_suppress,
  153321. _vp_tonemask_adj_8,
  153322. NULL,
  153323. _vp_tonemask_adj_8,
  153324. _psy_noiseguards_8,
  153325. _psy_noisebias_8,
  153326. _psy_noisebias_8,
  153327. NULL,
  153328. NULL,
  153329. _psy_noise_suppress,
  153330. _psy_compand_8,
  153331. _psy_compand_8_mapping,
  153332. NULL,
  153333. {_noise_start_8,_noise_start_8},
  153334. {_noise_part_8,_noise_part_8},
  153335. _noise_thresh_5only,
  153336. _psy_ath_floater_8,
  153337. _psy_ath_abs_8,
  153338. _psy_lowpass_8,
  153339. _psy_global_44,
  153340. _global_mapping_8,
  153341. _psy_stereo_modes_8,
  153342. _floor_books,
  153343. _floor,
  153344. _floor_mapping_8,
  153345. NULL,
  153346. _mapres_template_8_stereo
  153347. };
  153348. ve_setup_data_template ve_setup_XX_uncoupled={
  153349. 2,
  153350. rate_mapping_X,
  153351. quality_mapping_8,
  153352. -1,
  153353. 0,
  153354. 8000,
  153355. blocksize_8,
  153356. blocksize_8,
  153357. _psy_tone_masteratt_8,
  153358. _psy_tone_0dB,
  153359. _psy_tone_suppress,
  153360. _vp_tonemask_adj_8,
  153361. NULL,
  153362. _vp_tonemask_adj_8,
  153363. _psy_noiseguards_8,
  153364. _psy_noisebias_8,
  153365. _psy_noisebias_8,
  153366. NULL,
  153367. NULL,
  153368. _psy_noise_suppress,
  153369. _psy_compand_8,
  153370. _psy_compand_8_mapping,
  153371. NULL,
  153372. {_noise_start_8,_noise_start_8},
  153373. {_noise_part_8,_noise_part_8},
  153374. _noise_thresh_5only,
  153375. _psy_ath_floater_8,
  153376. _psy_ath_abs_8,
  153377. _psy_lowpass_8,
  153378. _psy_global_44,
  153379. _global_mapping_8,
  153380. _psy_stereo_modes_8,
  153381. _floor_books,
  153382. _floor,
  153383. _floor_mapping_8,
  153384. NULL,
  153385. _mapres_template_8_uncoupled
  153386. };
  153387. /*** End of inlined file: setup_X.h ***/
  153388. static ve_setup_data_template *setup_list[]={
  153389. &ve_setup_44_stereo,
  153390. &ve_setup_44_uncoupled,
  153391. &ve_setup_32_stereo,
  153392. &ve_setup_32_uncoupled,
  153393. &ve_setup_22_stereo,
  153394. &ve_setup_22_uncoupled,
  153395. &ve_setup_16_stereo,
  153396. &ve_setup_16_uncoupled,
  153397. &ve_setup_11_stereo,
  153398. &ve_setup_11_uncoupled,
  153399. &ve_setup_8_stereo,
  153400. &ve_setup_8_uncoupled,
  153401. &ve_setup_X_stereo,
  153402. &ve_setup_X_uncoupled,
  153403. &ve_setup_XX_stereo,
  153404. &ve_setup_XX_uncoupled,
  153405. 0
  153406. };
  153407. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  153408. if(vi && vi->codec_setup){
  153409. vi->version=0;
  153410. vi->channels=ch;
  153411. vi->rate=rate;
  153412. return(0);
  153413. }
  153414. return(OV_EINVAL);
  153415. }
  153416. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  153417. static_codebook ***books,
  153418. vorbis_info_floor1 *in,
  153419. int *x){
  153420. int i,k,is=s;
  153421. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  153422. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153423. memcpy(f,in+x[is],sizeof(*f));
  153424. /* fill in the lowpass field, even if it's temporary */
  153425. f->n=ci->blocksizes[block]>>1;
  153426. /* books */
  153427. {
  153428. int partitions=f->partitions;
  153429. int maxclass=-1;
  153430. int maxbook=-1;
  153431. for(i=0;i<partitions;i++)
  153432. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  153433. for(i=0;i<=maxclass;i++){
  153434. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  153435. f->class_book[i]+=ci->books;
  153436. for(k=0;k<(1<<f->class_subs[i]);k++){
  153437. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  153438. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  153439. }
  153440. }
  153441. for(i=0;i<=maxbook;i++)
  153442. ci->book_param[ci->books++]=books[x[is]][i];
  153443. }
  153444. /* for now, we're only using floor 1 */
  153445. ci->floor_type[ci->floors]=1;
  153446. ci->floor_param[ci->floors]=f;
  153447. ci->floors++;
  153448. return;
  153449. }
  153450. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  153451. vorbis_info_psy_global *in,
  153452. double *x){
  153453. int i,is=s;
  153454. double ds=s-is;
  153455. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153456. vorbis_info_psy_global *g=&ci->psy_g_param;
  153457. memcpy(g,in+(int)x[is],sizeof(*g));
  153458. ds=x[is]*(1.-ds)+x[is+1]*ds;
  153459. is=(int)ds;
  153460. ds-=is;
  153461. if(ds==0 && is>0){
  153462. is--;
  153463. ds=1.;
  153464. }
  153465. /* interpolate the trigger threshholds */
  153466. for(i=0;i<4;i++){
  153467. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  153468. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  153469. }
  153470. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  153471. return;
  153472. }
  153473. static void vorbis_encode_global_stereo(vorbis_info *vi,
  153474. highlevel_encode_setup *hi,
  153475. adj_stereo *p){
  153476. float s=hi->stereo_point_setting;
  153477. int i,is=s;
  153478. double ds=s-is;
  153479. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153480. vorbis_info_psy_global *g=&ci->psy_g_param;
  153481. if(p){
  153482. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  153483. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  153484. if(hi->managed){
  153485. /* interpolate the kHz threshholds */
  153486. for(i=0;i<PACKETBLOBS;i++){
  153487. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  153488. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153489. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153490. g->coupling_pkHz[i]=kHz;
  153491. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  153492. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153493. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153494. }
  153495. }else{
  153496. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  153497. for(i=0;i<PACKETBLOBS;i++){
  153498. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153499. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153500. g->coupling_pkHz[i]=kHz;
  153501. }
  153502. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  153503. for(i=0;i<PACKETBLOBS;i++){
  153504. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153505. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153506. }
  153507. }
  153508. }else{
  153509. for(i=0;i<PACKETBLOBS;i++){
  153510. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  153511. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  153512. }
  153513. }
  153514. return;
  153515. }
  153516. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  153517. int *nn_start,
  153518. int *nn_partition,
  153519. double *nn_thresh,
  153520. int block){
  153521. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153522. vorbis_info_psy *p=ci->psy_param[block];
  153523. highlevel_encode_setup *hi=&ci->hi;
  153524. int is=s;
  153525. if(block>=ci->psys)
  153526. ci->psys=block+1;
  153527. if(!p){
  153528. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  153529. ci->psy_param[block]=p;
  153530. }
  153531. memcpy(p,&_psy_info_template,sizeof(*p));
  153532. p->blockflag=block>>1;
  153533. if(hi->noise_normalize_p){
  153534. p->normal_channel_p=1;
  153535. p->normal_point_p=1;
  153536. p->normal_start=nn_start[is];
  153537. p->normal_partition=nn_partition[is];
  153538. p->normal_thresh=nn_thresh[is];
  153539. }
  153540. return;
  153541. }
  153542. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  153543. att3 *att,
  153544. int *max,
  153545. vp_adjblock *in){
  153546. int i,is=s;
  153547. double ds=s-is;
  153548. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153549. vorbis_info_psy *p=ci->psy_param[block];
  153550. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  153551. filling the values in here */
  153552. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  153553. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  153554. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  153555. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  153556. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  153557. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  153558. for(i=0;i<P_BANDS;i++)
  153559. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  153560. return;
  153561. }
  153562. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  153563. compandblock *in, double *x){
  153564. int i,is=s;
  153565. double ds=s-is;
  153566. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153567. vorbis_info_psy *p=ci->psy_param[block];
  153568. ds=x[is]*(1.-ds)+x[is+1]*ds;
  153569. is=(int)ds;
  153570. ds-=is;
  153571. if(ds==0 && is>0){
  153572. is--;
  153573. ds=1.;
  153574. }
  153575. /* interpolate the compander settings */
  153576. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  153577. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  153578. return;
  153579. }
  153580. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  153581. int *suppress){
  153582. int is=s;
  153583. double ds=s-is;
  153584. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153585. vorbis_info_psy *p=ci->psy_param[block];
  153586. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  153587. return;
  153588. }
  153589. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  153590. int *suppress,
  153591. noise3 *in,
  153592. noiseguard *guard,
  153593. double userbias){
  153594. int i,is=s,j;
  153595. double ds=s-is;
  153596. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153597. vorbis_info_psy *p=ci->psy_param[block];
  153598. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  153599. p->noisewindowlomin=guard[block].lo;
  153600. p->noisewindowhimin=guard[block].hi;
  153601. p->noisewindowfixed=guard[block].fixed;
  153602. for(j=0;j<P_NOISECURVES;j++)
  153603. for(i=0;i<P_BANDS;i++)
  153604. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  153605. /* impulse blocks may take a user specified bias to boost the
  153606. nominal/high noise encoding depth */
  153607. for(j=0;j<P_NOISECURVES;j++){
  153608. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  153609. for(i=0;i<P_BANDS;i++){
  153610. p->noiseoff[j][i]+=userbias;
  153611. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  153612. }
  153613. }
  153614. return;
  153615. }
  153616. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  153617. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153618. vorbis_info_psy *p=ci->psy_param[block];
  153619. p->ath_adjatt=ci->hi.ath_floating_dB;
  153620. p->ath_maxatt=ci->hi.ath_absolute_dB;
  153621. return;
  153622. }
  153623. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  153624. int i;
  153625. for(i=0;i<ci->books;i++)
  153626. if(ci->book_param[i]==book)return(i);
  153627. return(ci->books++);
  153628. }
  153629. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  153630. int *shortb,int *longb){
  153631. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153632. int is=s;
  153633. int blockshort=shortb[is];
  153634. int blocklong=longb[is];
  153635. ci->blocksizes[0]=blockshort;
  153636. ci->blocksizes[1]=blocklong;
  153637. }
  153638. static void vorbis_encode_residue_setup(vorbis_info *vi,
  153639. int number, int block,
  153640. vorbis_residue_template *res){
  153641. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153642. int i,n;
  153643. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  153644. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  153645. memcpy(r,res->res,sizeof(*r));
  153646. if(ci->residues<=number)ci->residues=number+1;
  153647. switch(ci->blocksizes[block]){
  153648. case 64:case 128:case 256:
  153649. r->grouping=16;
  153650. break;
  153651. default:
  153652. r->grouping=32;
  153653. break;
  153654. }
  153655. ci->residue_type[number]=res->res_type;
  153656. /* to be adjusted by lowpass/pointlimit later */
  153657. n=r->end=ci->blocksizes[block]>>1;
  153658. if(res->res_type==2)
  153659. n=r->end*=vi->channels;
  153660. /* fill in all the books */
  153661. {
  153662. int booklist=0,k;
  153663. if(ci->hi.managed){
  153664. for(i=0;i<r->partitions;i++)
  153665. for(k=0;k<3;k++)
  153666. if(res->books_base_managed->books[i][k])
  153667. r->secondstages[i]|=(1<<k);
  153668. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  153669. ci->book_param[r->groupbook]=res->book_aux_managed;
  153670. for(i=0;i<r->partitions;i++){
  153671. for(k=0;k<3;k++){
  153672. if(res->books_base_managed->books[i][k]){
  153673. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  153674. r->booklist[booklist++]=bookid;
  153675. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  153676. }
  153677. }
  153678. }
  153679. }else{
  153680. for(i=0;i<r->partitions;i++)
  153681. for(k=0;k<3;k++)
  153682. if(res->books_base->books[i][k])
  153683. r->secondstages[i]|=(1<<k);
  153684. r->groupbook=book_dup_or_new(ci,res->book_aux);
  153685. ci->book_param[r->groupbook]=res->book_aux;
  153686. for(i=0;i<r->partitions;i++){
  153687. for(k=0;k<3;k++){
  153688. if(res->books_base->books[i][k]){
  153689. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  153690. r->booklist[booklist++]=bookid;
  153691. ci->book_param[bookid]=res->books_base->books[i][k];
  153692. }
  153693. }
  153694. }
  153695. }
  153696. }
  153697. /* lowpass setup/pointlimit */
  153698. {
  153699. double freq=ci->hi.lowpass_kHz*1000.;
  153700. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  153701. double nyq=vi->rate/2.;
  153702. long blocksize=ci->blocksizes[block]>>1;
  153703. /* lowpass needs to be set in the floor and the residue. */
  153704. if(freq>nyq)freq=nyq;
  153705. /* in the floor, the granularity can be very fine; it doesn't alter
  153706. the encoding structure, only the samples used to fit the floor
  153707. approximation */
  153708. f->n=freq/nyq*blocksize;
  153709. /* this res may by limited by the maximum pointlimit of the mode,
  153710. not the lowpass. the floor is always lowpass limited. */
  153711. if(res->limit_type){
  153712. if(ci->hi.managed)
  153713. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  153714. else
  153715. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  153716. if(freq>nyq)freq=nyq;
  153717. }
  153718. /* in the residue, we're constrained, physically, by partition
  153719. boundaries. We still lowpass 'wherever', but we have to round up
  153720. here to next boundary, or the vorbis spec will round it *down* to
  153721. previous boundary in encode/decode */
  153722. if(ci->residue_type[block]==2)
  153723. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  153724. r->grouping;
  153725. else
  153726. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  153727. r->grouping;
  153728. }
  153729. }
  153730. /* we assume two maps in this encoder */
  153731. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  153732. vorbis_mapping_template *maps){
  153733. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153734. int i,j,is=s,modes=2;
  153735. vorbis_info_mapping0 *map=maps[is].map;
  153736. vorbis_info_mode *mode=_mode_template;
  153737. vorbis_residue_template *res=maps[is].res;
  153738. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  153739. for(i=0;i<modes;i++){
  153740. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  153741. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  153742. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  153743. if(i>=ci->modes)ci->modes=i+1;
  153744. ci->map_type[i]=0;
  153745. memcpy(ci->map_param[i],map+i,sizeof(*map));
  153746. if(i>=ci->maps)ci->maps=i+1;
  153747. for(j=0;j<map[i].submaps;j++)
  153748. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  153749. ,res+map[i].residuesubmap[j]);
  153750. }
  153751. }
  153752. static double setting_to_approx_bitrate(vorbis_info *vi){
  153753. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153754. highlevel_encode_setup *hi=&ci->hi;
  153755. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  153756. int is=hi->base_setting;
  153757. double ds=hi->base_setting-is;
  153758. int ch=vi->channels;
  153759. double *r=setup->rate_mapping;
  153760. if(r==NULL)
  153761. return(-1);
  153762. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  153763. }
  153764. static void get_setup_template(vorbis_info *vi,
  153765. long ch,long srate,
  153766. double req,int q_or_bitrate){
  153767. int i=0,j;
  153768. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153769. highlevel_encode_setup *hi=&ci->hi;
  153770. if(q_or_bitrate)req/=ch;
  153771. while(setup_list[i]){
  153772. if(setup_list[i]->coupling_restriction==-1 ||
  153773. setup_list[i]->coupling_restriction==ch){
  153774. if(srate>=setup_list[i]->samplerate_min_restriction &&
  153775. srate<=setup_list[i]->samplerate_max_restriction){
  153776. int mappings=setup_list[i]->mappings;
  153777. double *map=(q_or_bitrate?
  153778. setup_list[i]->rate_mapping:
  153779. setup_list[i]->quality_mapping);
  153780. /* the template matches. Does the requested quality mode
  153781. fall within this template's modes? */
  153782. if(req<map[0]){++i;continue;}
  153783. if(req>map[setup_list[i]->mappings]){++i;continue;}
  153784. for(j=0;j<mappings;j++)
  153785. if(req>=map[j] && req<map[j+1])break;
  153786. /* an all-points match */
  153787. hi->setup=setup_list[i];
  153788. if(j==mappings)
  153789. hi->base_setting=j-.001;
  153790. else{
  153791. float low=map[j];
  153792. float high=map[j+1];
  153793. float del=(req-low)/(high-low);
  153794. hi->base_setting=j+del;
  153795. }
  153796. return;
  153797. }
  153798. }
  153799. i++;
  153800. }
  153801. hi->setup=NULL;
  153802. }
  153803. /* encoders will need to use vorbis_info_init beforehand and call
  153804. vorbis_info clear when all done */
  153805. /* two interfaces; this, more detailed one, and later a convenience
  153806. layer on top */
  153807. /* the final setup call */
  153808. int vorbis_encode_setup_init(vorbis_info *vi){
  153809. int i0=0,singleblock=0;
  153810. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153811. ve_setup_data_template *setup=NULL;
  153812. highlevel_encode_setup *hi=&ci->hi;
  153813. if(ci==NULL)return(OV_EINVAL);
  153814. if(!hi->impulse_block_p)i0=1;
  153815. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  153816. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  153817. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  153818. /* again, bound this to avoid the app shooting itself int he foot
  153819. too badly */
  153820. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  153821. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  153822. /* get the appropriate setup template; matches the fetch in previous
  153823. stages */
  153824. setup=(ve_setup_data_template *)hi->setup;
  153825. if(setup==NULL)return(OV_EINVAL);
  153826. hi->set_in_stone=1;
  153827. /* choose block sizes from configured sizes as well as paying
  153828. attention to long_block_p and short_block_p. If the configured
  153829. short and long blocks are the same length, we set long_block_p
  153830. and unset short_block_p */
  153831. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  153832. setup->blocksize_short,
  153833. setup->blocksize_long);
  153834. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  153835. /* floor setup; choose proper floor params. Allocated on the floor
  153836. stack in order; if we alloc only long floor, it's 0 */
  153837. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  153838. setup->floor_books,
  153839. setup->floor_params,
  153840. setup->floor_short_mapping);
  153841. if(!singleblock)
  153842. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  153843. setup->floor_books,
  153844. setup->floor_params,
  153845. setup->floor_long_mapping);
  153846. /* setup of [mostly] short block detection and stereo*/
  153847. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  153848. setup->global_params,
  153849. setup->global_mapping);
  153850. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  153851. /* basic psych setup and noise normalization */
  153852. vorbis_encode_psyset_setup(vi,hi->short_setting,
  153853. setup->psy_noise_normal_start[0],
  153854. setup->psy_noise_normal_partition[0],
  153855. setup->psy_noise_normal_thresh,
  153856. 0);
  153857. vorbis_encode_psyset_setup(vi,hi->short_setting,
  153858. setup->psy_noise_normal_start[0],
  153859. setup->psy_noise_normal_partition[0],
  153860. setup->psy_noise_normal_thresh,
  153861. 1);
  153862. if(!singleblock){
  153863. vorbis_encode_psyset_setup(vi,hi->long_setting,
  153864. setup->psy_noise_normal_start[1],
  153865. setup->psy_noise_normal_partition[1],
  153866. setup->psy_noise_normal_thresh,
  153867. 2);
  153868. vorbis_encode_psyset_setup(vi,hi->long_setting,
  153869. setup->psy_noise_normal_start[1],
  153870. setup->psy_noise_normal_partition[1],
  153871. setup->psy_noise_normal_thresh,
  153872. 3);
  153873. }
  153874. /* tone masking setup */
  153875. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  153876. setup->psy_tone_masteratt,
  153877. setup->psy_tone_0dB,
  153878. setup->psy_tone_adj_impulse);
  153879. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  153880. setup->psy_tone_masteratt,
  153881. setup->psy_tone_0dB,
  153882. setup->psy_tone_adj_other);
  153883. if(!singleblock){
  153884. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  153885. setup->psy_tone_masteratt,
  153886. setup->psy_tone_0dB,
  153887. setup->psy_tone_adj_other);
  153888. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  153889. setup->psy_tone_masteratt,
  153890. setup->psy_tone_0dB,
  153891. setup->psy_tone_adj_long);
  153892. }
  153893. /* noise companding setup */
  153894. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  153895. setup->psy_noise_compand,
  153896. setup->psy_noise_compand_short_mapping);
  153897. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  153898. setup->psy_noise_compand,
  153899. setup->psy_noise_compand_short_mapping);
  153900. if(!singleblock){
  153901. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  153902. setup->psy_noise_compand,
  153903. setup->psy_noise_compand_long_mapping);
  153904. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  153905. setup->psy_noise_compand,
  153906. setup->psy_noise_compand_long_mapping);
  153907. }
  153908. /* peak guarding setup */
  153909. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  153910. setup->psy_tone_dBsuppress);
  153911. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  153912. setup->psy_tone_dBsuppress);
  153913. if(!singleblock){
  153914. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  153915. setup->psy_tone_dBsuppress);
  153916. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  153917. setup->psy_tone_dBsuppress);
  153918. }
  153919. /* noise bias setup */
  153920. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  153921. setup->psy_noise_dBsuppress,
  153922. setup->psy_noise_bias_impulse,
  153923. setup->psy_noiseguards,
  153924. (i0==0?hi->impulse_noisetune:0.));
  153925. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  153926. setup->psy_noise_dBsuppress,
  153927. setup->psy_noise_bias_padding,
  153928. setup->psy_noiseguards,0.);
  153929. if(!singleblock){
  153930. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  153931. setup->psy_noise_dBsuppress,
  153932. setup->psy_noise_bias_trans,
  153933. setup->psy_noiseguards,0.);
  153934. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  153935. setup->psy_noise_dBsuppress,
  153936. setup->psy_noise_bias_long,
  153937. setup->psy_noiseguards,0.);
  153938. }
  153939. vorbis_encode_ath_setup(vi,0);
  153940. vorbis_encode_ath_setup(vi,1);
  153941. if(!singleblock){
  153942. vorbis_encode_ath_setup(vi,2);
  153943. vorbis_encode_ath_setup(vi,3);
  153944. }
  153945. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  153946. /* set bitrate readonlies and management */
  153947. if(hi->bitrate_av>0)
  153948. vi->bitrate_nominal=hi->bitrate_av;
  153949. else{
  153950. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  153951. }
  153952. vi->bitrate_lower=hi->bitrate_min;
  153953. vi->bitrate_upper=hi->bitrate_max;
  153954. if(hi->bitrate_av)
  153955. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  153956. else
  153957. vi->bitrate_window=0.;
  153958. if(hi->managed){
  153959. ci->bi.avg_rate=hi->bitrate_av;
  153960. ci->bi.min_rate=hi->bitrate_min;
  153961. ci->bi.max_rate=hi->bitrate_max;
  153962. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  153963. ci->bi.reservoir_bias=
  153964. hi->bitrate_reservoir_bias;
  153965. ci->bi.slew_damp=hi->bitrate_av_damp;
  153966. }
  153967. return(0);
  153968. }
  153969. static int vorbis_encode_setup_setting(vorbis_info *vi,
  153970. long channels,
  153971. long rate){
  153972. int ret=0,i,is;
  153973. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153974. highlevel_encode_setup *hi=&ci->hi;
  153975. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  153976. double ds;
  153977. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  153978. if(ret)return(ret);
  153979. is=hi->base_setting;
  153980. ds=hi->base_setting-is;
  153981. hi->short_setting=hi->base_setting;
  153982. hi->long_setting=hi->base_setting;
  153983. hi->managed=0;
  153984. hi->impulse_block_p=1;
  153985. hi->noise_normalize_p=1;
  153986. hi->stereo_point_setting=hi->base_setting;
  153987. hi->lowpass_kHz=
  153988. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  153989. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  153990. setup->psy_ath_float[is+1]*ds;
  153991. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  153992. setup->psy_ath_abs[is+1]*ds;
  153993. hi->amplitude_track_dBpersec=-6.;
  153994. hi->trigger_setting=hi->base_setting;
  153995. for(i=0;i<4;i++){
  153996. hi->block[i].tone_mask_setting=hi->base_setting;
  153997. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  153998. hi->block[i].noise_bias_setting=hi->base_setting;
  153999. hi->block[i].noise_compand_setting=hi->base_setting;
  154000. }
  154001. return(ret);
  154002. }
  154003. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154004. long channels,
  154005. long rate,
  154006. float quality){
  154007. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154008. highlevel_encode_setup *hi=&ci->hi;
  154009. quality+=.0000001;
  154010. if(quality>=1.)quality=.9999;
  154011. get_setup_template(vi,channels,rate,quality,0);
  154012. if(!hi->setup)return OV_EIMPL;
  154013. return vorbis_encode_setup_setting(vi,channels,rate);
  154014. }
  154015. int vorbis_encode_init_vbr(vorbis_info *vi,
  154016. long channels,
  154017. long rate,
  154018. float base_quality /* 0. to 1. */
  154019. ){
  154020. int ret=0;
  154021. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154022. if(ret){
  154023. vorbis_info_clear(vi);
  154024. return ret;
  154025. }
  154026. ret=vorbis_encode_setup_init(vi);
  154027. if(ret)
  154028. vorbis_info_clear(vi);
  154029. return(ret);
  154030. }
  154031. int vorbis_encode_setup_managed(vorbis_info *vi,
  154032. long channels,
  154033. long rate,
  154034. long max_bitrate,
  154035. long nominal_bitrate,
  154036. long min_bitrate){
  154037. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154038. highlevel_encode_setup *hi=&ci->hi;
  154039. double tnominal=nominal_bitrate;
  154040. int ret=0;
  154041. if(nominal_bitrate<=0.){
  154042. if(max_bitrate>0.){
  154043. if(min_bitrate>0.)
  154044. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154045. else
  154046. nominal_bitrate=max_bitrate*.875;
  154047. }else{
  154048. if(min_bitrate>0.){
  154049. nominal_bitrate=min_bitrate;
  154050. }else{
  154051. return(OV_EINVAL);
  154052. }
  154053. }
  154054. }
  154055. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154056. if(!hi->setup)return OV_EIMPL;
  154057. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154058. if(ret){
  154059. vorbis_info_clear(vi);
  154060. return ret;
  154061. }
  154062. /* initialize management with sane defaults */
  154063. hi->managed=1;
  154064. hi->bitrate_min=min_bitrate;
  154065. hi->bitrate_max=max_bitrate;
  154066. hi->bitrate_av=tnominal;
  154067. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154068. hi->bitrate_reservoir=nominal_bitrate*2;
  154069. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154070. return(ret);
  154071. }
  154072. int vorbis_encode_init(vorbis_info *vi,
  154073. long channels,
  154074. long rate,
  154075. long max_bitrate,
  154076. long nominal_bitrate,
  154077. long min_bitrate){
  154078. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154079. max_bitrate,
  154080. nominal_bitrate,
  154081. min_bitrate);
  154082. if(ret){
  154083. vorbis_info_clear(vi);
  154084. return(ret);
  154085. }
  154086. ret=vorbis_encode_setup_init(vi);
  154087. if(ret)
  154088. vorbis_info_clear(vi);
  154089. return(ret);
  154090. }
  154091. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154092. if(vi){
  154093. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154094. highlevel_encode_setup *hi=&ci->hi;
  154095. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154096. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154097. switch(number){
  154098. /* now deprecated *****************/
  154099. case OV_ECTL_RATEMANAGE_GET:
  154100. {
  154101. struct ovectl_ratemanage_arg *ai=
  154102. (struct ovectl_ratemanage_arg *)arg;
  154103. ai->management_active=hi->managed;
  154104. ai->bitrate_hard_window=ai->bitrate_av_window=
  154105. (double)hi->bitrate_reservoir/vi->rate;
  154106. ai->bitrate_av_window_center=1.;
  154107. ai->bitrate_hard_min=hi->bitrate_min;
  154108. ai->bitrate_hard_max=hi->bitrate_max;
  154109. ai->bitrate_av_lo=hi->bitrate_av;
  154110. ai->bitrate_av_hi=hi->bitrate_av;
  154111. }
  154112. return(0);
  154113. /* now deprecated *****************/
  154114. case OV_ECTL_RATEMANAGE_SET:
  154115. {
  154116. struct ovectl_ratemanage_arg *ai=
  154117. (struct ovectl_ratemanage_arg *)arg;
  154118. if(ai==NULL){
  154119. hi->managed=0;
  154120. }else{
  154121. hi->managed=ai->management_active;
  154122. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154123. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154124. }
  154125. }
  154126. return 0;
  154127. /* now deprecated *****************/
  154128. case OV_ECTL_RATEMANAGE_AVG:
  154129. {
  154130. struct ovectl_ratemanage_arg *ai=
  154131. (struct ovectl_ratemanage_arg *)arg;
  154132. if(ai==NULL){
  154133. hi->bitrate_av=0;
  154134. }else{
  154135. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  154136. }
  154137. }
  154138. return(0);
  154139. /* now deprecated *****************/
  154140. case OV_ECTL_RATEMANAGE_HARD:
  154141. {
  154142. struct ovectl_ratemanage_arg *ai=
  154143. (struct ovectl_ratemanage_arg *)arg;
  154144. if(ai==NULL){
  154145. hi->bitrate_min=0;
  154146. hi->bitrate_max=0;
  154147. }else{
  154148. hi->bitrate_min=ai->bitrate_hard_min;
  154149. hi->bitrate_max=ai->bitrate_hard_max;
  154150. hi->bitrate_reservoir=ai->bitrate_hard_window*
  154151. (hi->bitrate_max+hi->bitrate_min)*.5;
  154152. }
  154153. if(hi->bitrate_reservoir<128.)
  154154. hi->bitrate_reservoir=128.;
  154155. }
  154156. return(0);
  154157. /* replacement ratemanage interface */
  154158. case OV_ECTL_RATEMANAGE2_GET:
  154159. {
  154160. struct ovectl_ratemanage2_arg *ai=
  154161. (struct ovectl_ratemanage2_arg *)arg;
  154162. if(ai==NULL)return OV_EINVAL;
  154163. ai->management_active=hi->managed;
  154164. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  154165. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  154166. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  154167. ai->bitrate_average_damping=hi->bitrate_av_damp;
  154168. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  154169. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  154170. }
  154171. return (0);
  154172. case OV_ECTL_RATEMANAGE2_SET:
  154173. {
  154174. struct ovectl_ratemanage2_arg *ai=
  154175. (struct ovectl_ratemanage2_arg *)arg;
  154176. if(ai==NULL){
  154177. hi->managed=0;
  154178. }else{
  154179. /* sanity check; only catch invariant violations */
  154180. if(ai->bitrate_limit_min_kbps>0 &&
  154181. ai->bitrate_average_kbps>0 &&
  154182. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  154183. return OV_EINVAL;
  154184. if(ai->bitrate_limit_max_kbps>0 &&
  154185. ai->bitrate_average_kbps>0 &&
  154186. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  154187. return OV_EINVAL;
  154188. if(ai->bitrate_limit_min_kbps>0 &&
  154189. ai->bitrate_limit_max_kbps>0 &&
  154190. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  154191. return OV_EINVAL;
  154192. if(ai->bitrate_average_damping <= 0.)
  154193. return OV_EINVAL;
  154194. if(ai->bitrate_limit_reservoir_bits < 0)
  154195. return OV_EINVAL;
  154196. if(ai->bitrate_limit_reservoir_bias < 0.)
  154197. return OV_EINVAL;
  154198. if(ai->bitrate_limit_reservoir_bias > 1.)
  154199. return OV_EINVAL;
  154200. hi->managed=ai->management_active;
  154201. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  154202. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  154203. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  154204. hi->bitrate_av_damp=ai->bitrate_average_damping;
  154205. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  154206. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  154207. }
  154208. }
  154209. return 0;
  154210. case OV_ECTL_LOWPASS_GET:
  154211. {
  154212. double *farg=(double *)arg;
  154213. *farg=hi->lowpass_kHz;
  154214. }
  154215. return(0);
  154216. case OV_ECTL_LOWPASS_SET:
  154217. {
  154218. double *farg=(double *)arg;
  154219. hi->lowpass_kHz=*farg;
  154220. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  154221. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  154222. }
  154223. return(0);
  154224. case OV_ECTL_IBLOCK_GET:
  154225. {
  154226. double *farg=(double *)arg;
  154227. *farg=hi->impulse_noisetune;
  154228. }
  154229. return(0);
  154230. case OV_ECTL_IBLOCK_SET:
  154231. {
  154232. double *farg=(double *)arg;
  154233. hi->impulse_noisetune=*farg;
  154234. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  154235. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  154236. }
  154237. return(0);
  154238. }
  154239. return(OV_EIMPL);
  154240. }
  154241. return(OV_EINVAL);
  154242. }
  154243. #endif
  154244. /*** End of inlined file: vorbisenc.c ***/
  154245. /*** Start of inlined file: vorbisfile.c ***/
  154246. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  154247. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  154248. // tasks..
  154249. #if JUCE_MSVC
  154250. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  154251. #endif
  154252. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  154253. #if JUCE_USE_OGGVORBIS
  154254. #include <stdlib.h>
  154255. #include <stdio.h>
  154256. #include <errno.h>
  154257. #include <string.h>
  154258. #include <math.h>
  154259. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  154260. one logical bitstream arranged end to end (the only form of Ogg
  154261. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  154262. multiplexing] is not allowed in Vorbis) */
  154263. /* A Vorbis file can be played beginning to end (streamed) without
  154264. worrying ahead of time about chaining (see decoder_example.c). If
  154265. we have the whole file, however, and want random access
  154266. (seeking/scrubbing) or desire to know the total length/time of a
  154267. file, we need to account for the possibility of chaining. */
  154268. /* We can handle things a number of ways; we can determine the entire
  154269. bitstream structure right off the bat, or find pieces on demand.
  154270. This example determines and caches structure for the entire
  154271. bitstream, but builds a virtual decoder on the fly when moving
  154272. between links in the chain. */
  154273. /* There are also different ways to implement seeking. Enough
  154274. information exists in an Ogg bitstream to seek to
  154275. sample-granularity positions in the output. Or, one can seek by
  154276. picking some portion of the stream roughly in the desired area if
  154277. we only want coarse navigation through the stream. */
  154278. /*************************************************************************
  154279. * Many, many internal helpers. The intention is not to be confusing;
  154280. * rampant duplication and monolithic function implementation would be
  154281. * harder to understand anyway. The high level functions are last. Begin
  154282. * grokking near the end of the file */
  154283. /* read a little more data from the file/pipe into the ogg_sync framer
  154284. */
  154285. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  154286. over 8k gets what they deserve */
  154287. static long _get_data(OggVorbis_File *vf){
  154288. errno=0;
  154289. if(vf->datasource){
  154290. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  154291. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  154292. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  154293. if(bytes==0 && errno)return(-1);
  154294. return(bytes);
  154295. }else
  154296. return(0);
  154297. }
  154298. /* save a tiny smidge of verbosity to make the code more readable */
  154299. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  154300. if(vf->datasource){
  154301. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  154302. vf->offset=offset;
  154303. ogg_sync_reset(&vf->oy);
  154304. }else{
  154305. /* shouldn't happen unless someone writes a broken callback */
  154306. return;
  154307. }
  154308. }
  154309. /* The read/seek functions track absolute position within the stream */
  154310. /* from the head of the stream, get the next page. boundary specifies
  154311. if the function is allowed to fetch more data from the stream (and
  154312. how much) or only use internally buffered data.
  154313. boundary: -1) unbounded search
  154314. 0) read no additional data; use cached only
  154315. n) search for a new page beginning for n bytes
  154316. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  154317. n) found a page at absolute offset n */
  154318. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  154319. ogg_int64_t boundary){
  154320. if(boundary>0)boundary+=vf->offset;
  154321. while(1){
  154322. long more;
  154323. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  154324. more=ogg_sync_pageseek(&vf->oy,og);
  154325. if(more<0){
  154326. /* skipped n bytes */
  154327. vf->offset-=more;
  154328. }else{
  154329. if(more==0){
  154330. /* send more paramedics */
  154331. if(!boundary)return(OV_FALSE);
  154332. {
  154333. long ret=_get_data(vf);
  154334. if(ret==0)return(OV_EOF);
  154335. if(ret<0)return(OV_EREAD);
  154336. }
  154337. }else{
  154338. /* got a page. Return the offset at the page beginning,
  154339. advance the internal offset past the page end */
  154340. ogg_int64_t ret=vf->offset;
  154341. vf->offset+=more;
  154342. return(ret);
  154343. }
  154344. }
  154345. }
  154346. }
  154347. /* find the latest page beginning before the current stream cursor
  154348. position. Much dirtier than the above as Ogg doesn't have any
  154349. backward search linkage. no 'readp' as it will certainly have to
  154350. read. */
  154351. /* returns offset or OV_EREAD, OV_FAULT */
  154352. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  154353. ogg_int64_t begin=vf->offset;
  154354. ogg_int64_t end=begin;
  154355. ogg_int64_t ret;
  154356. ogg_int64_t offset=-1;
  154357. while(offset==-1){
  154358. begin-=CHUNKSIZE;
  154359. if(begin<0)
  154360. begin=0;
  154361. _seek_helper(vf,begin);
  154362. while(vf->offset<end){
  154363. ret=_get_next_page(vf,og,end-vf->offset);
  154364. if(ret==OV_EREAD)return(OV_EREAD);
  154365. if(ret<0){
  154366. break;
  154367. }else{
  154368. offset=ret;
  154369. }
  154370. }
  154371. }
  154372. /* we have the offset. Actually snork and hold the page now */
  154373. _seek_helper(vf,offset);
  154374. ret=_get_next_page(vf,og,CHUNKSIZE);
  154375. if(ret<0)
  154376. /* this shouldn't be possible */
  154377. return(OV_EFAULT);
  154378. return(offset);
  154379. }
  154380. /* finds each bitstream link one at a time using a bisection search
  154381. (has to begin by knowing the offset of the lb's initial page).
  154382. Recurses for each link so it can alloc the link storage after
  154383. finding them all, then unroll and fill the cache at the same time */
  154384. static int _bisect_forward_serialno(OggVorbis_File *vf,
  154385. ogg_int64_t begin,
  154386. ogg_int64_t searched,
  154387. ogg_int64_t end,
  154388. long currentno,
  154389. long m){
  154390. ogg_int64_t endsearched=end;
  154391. ogg_int64_t next=end;
  154392. ogg_page og;
  154393. ogg_int64_t ret;
  154394. /* the below guards against garbage seperating the last and
  154395. first pages of two links. */
  154396. while(searched<endsearched){
  154397. ogg_int64_t bisect;
  154398. if(endsearched-searched<CHUNKSIZE){
  154399. bisect=searched;
  154400. }else{
  154401. bisect=(searched+endsearched)/2;
  154402. }
  154403. _seek_helper(vf,bisect);
  154404. ret=_get_next_page(vf,&og,-1);
  154405. if(ret==OV_EREAD)return(OV_EREAD);
  154406. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  154407. endsearched=bisect;
  154408. if(ret>=0)next=ret;
  154409. }else{
  154410. searched=ret+og.header_len+og.body_len;
  154411. }
  154412. }
  154413. _seek_helper(vf,next);
  154414. ret=_get_next_page(vf,&og,-1);
  154415. if(ret==OV_EREAD)return(OV_EREAD);
  154416. if(searched>=end || ret<0){
  154417. vf->links=m+1;
  154418. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  154419. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  154420. vf->offsets[m+1]=searched;
  154421. }else{
  154422. ret=_bisect_forward_serialno(vf,next,vf->offset,
  154423. end,ogg_page_serialno(&og),m+1);
  154424. if(ret==OV_EREAD)return(OV_EREAD);
  154425. }
  154426. vf->offsets[m]=begin;
  154427. vf->serialnos[m]=currentno;
  154428. return(0);
  154429. }
  154430. /* uses the local ogg_stream storage in vf; this is important for
  154431. non-streaming input sources */
  154432. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  154433. long *serialno,ogg_page *og_ptr){
  154434. ogg_page og;
  154435. ogg_packet op;
  154436. int i,ret;
  154437. if(!og_ptr){
  154438. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  154439. if(llret==OV_EREAD)return(OV_EREAD);
  154440. if(llret<0)return OV_ENOTVORBIS;
  154441. og_ptr=&og;
  154442. }
  154443. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  154444. if(serialno)*serialno=vf->os.serialno;
  154445. vf->ready_state=STREAMSET;
  154446. /* extract the initial header from the first page and verify that the
  154447. Ogg bitstream is in fact Vorbis data */
  154448. vorbis_info_init(vi);
  154449. vorbis_comment_init(vc);
  154450. i=0;
  154451. while(i<3){
  154452. ogg_stream_pagein(&vf->os,og_ptr);
  154453. while(i<3){
  154454. int result=ogg_stream_packetout(&vf->os,&op);
  154455. if(result==0)break;
  154456. if(result==-1){
  154457. ret=OV_EBADHEADER;
  154458. goto bail_header;
  154459. }
  154460. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  154461. goto bail_header;
  154462. }
  154463. i++;
  154464. }
  154465. if(i<3)
  154466. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  154467. ret=OV_EBADHEADER;
  154468. goto bail_header;
  154469. }
  154470. }
  154471. return 0;
  154472. bail_header:
  154473. vorbis_info_clear(vi);
  154474. vorbis_comment_clear(vc);
  154475. vf->ready_state=OPENED;
  154476. return ret;
  154477. }
  154478. /* last step of the OggVorbis_File initialization; get all the
  154479. vorbis_info structs and PCM positions. Only called by the seekable
  154480. initialization (local stream storage is hacked slightly; pay
  154481. attention to how that's done) */
  154482. /* this is void and does not propogate errors up because we want to be
  154483. able to open and use damaged bitstreams as well as we can. Just
  154484. watch out for missing information for links in the OggVorbis_File
  154485. struct */
  154486. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  154487. ogg_page og;
  154488. int i;
  154489. ogg_int64_t ret;
  154490. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  154491. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  154492. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  154493. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  154494. for(i=0;i<vf->links;i++){
  154495. if(i==0){
  154496. /* we already grabbed the initial header earlier. Just set the offset */
  154497. vf->dataoffsets[i]=dataoffset;
  154498. _seek_helper(vf,dataoffset);
  154499. }else{
  154500. /* seek to the location of the initial header */
  154501. _seek_helper(vf,vf->offsets[i]);
  154502. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  154503. vf->dataoffsets[i]=-1;
  154504. }else{
  154505. vf->dataoffsets[i]=vf->offset;
  154506. }
  154507. }
  154508. /* fetch beginning PCM offset */
  154509. if(vf->dataoffsets[i]!=-1){
  154510. ogg_int64_t accumulated=0;
  154511. long lastblock=-1;
  154512. int result;
  154513. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  154514. while(1){
  154515. ogg_packet op;
  154516. ret=_get_next_page(vf,&og,-1);
  154517. if(ret<0)
  154518. /* this should not be possible unless the file is
  154519. truncated/mangled */
  154520. break;
  154521. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  154522. break;
  154523. /* count blocksizes of all frames in the page */
  154524. ogg_stream_pagein(&vf->os,&og);
  154525. while((result=ogg_stream_packetout(&vf->os,&op))){
  154526. if(result>0){ /* ignore holes */
  154527. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  154528. if(lastblock!=-1)
  154529. accumulated+=(lastblock+thisblock)>>2;
  154530. lastblock=thisblock;
  154531. }
  154532. }
  154533. if(ogg_page_granulepos(&og)!=-1){
  154534. /* pcm offset of last packet on the first audio page */
  154535. accumulated= ogg_page_granulepos(&og)-accumulated;
  154536. break;
  154537. }
  154538. }
  154539. /* less than zero? This is a stream with samples trimmed off
  154540. the beginning, a normal occurrence; set the offset to zero */
  154541. if(accumulated<0)accumulated=0;
  154542. vf->pcmlengths[i*2]=accumulated;
  154543. }
  154544. /* get the PCM length of this link. To do this,
  154545. get the last page of the stream */
  154546. {
  154547. ogg_int64_t end=vf->offsets[i+1];
  154548. _seek_helper(vf,end);
  154549. while(1){
  154550. ret=_get_prev_page(vf,&og);
  154551. if(ret<0){
  154552. /* this should not be possible */
  154553. vorbis_info_clear(vf->vi+i);
  154554. vorbis_comment_clear(vf->vc+i);
  154555. break;
  154556. }
  154557. if(ogg_page_granulepos(&og)!=-1){
  154558. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  154559. break;
  154560. }
  154561. vf->offset=ret;
  154562. }
  154563. }
  154564. }
  154565. }
  154566. static int _make_decode_ready(OggVorbis_File *vf){
  154567. if(vf->ready_state>STREAMSET)return 0;
  154568. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  154569. if(vf->seekable){
  154570. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  154571. return OV_EBADLINK;
  154572. }else{
  154573. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  154574. return OV_EBADLINK;
  154575. }
  154576. vorbis_block_init(&vf->vd,&vf->vb);
  154577. vf->ready_state=INITSET;
  154578. vf->bittrack=0.f;
  154579. vf->samptrack=0.f;
  154580. return 0;
  154581. }
  154582. static int _open_seekable2(OggVorbis_File *vf){
  154583. long serialno=vf->current_serialno;
  154584. ogg_int64_t dataoffset=vf->offset, end;
  154585. ogg_page og;
  154586. /* we're partially open and have a first link header state in
  154587. storage in vf */
  154588. /* we can seek, so set out learning all about this file */
  154589. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  154590. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  154591. /* We get the offset for the last page of the physical bitstream.
  154592. Most OggVorbis files will contain a single logical bitstream */
  154593. end=_get_prev_page(vf,&og);
  154594. if(end<0)return(end);
  154595. /* more than one logical bitstream? */
  154596. if(ogg_page_serialno(&og)!=serialno){
  154597. /* Chained bitstream. Bisect-search each logical bitstream
  154598. section. Do so based on serial number only */
  154599. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  154600. }else{
  154601. /* Only one logical bitstream */
  154602. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  154603. }
  154604. /* the initial header memory is referenced by vf after; don't free it */
  154605. _prefetch_all_headers(vf,dataoffset);
  154606. return(ov_raw_seek(vf,0));
  154607. }
  154608. /* clear out the current logical bitstream decoder */
  154609. static void _decode_clear(OggVorbis_File *vf){
  154610. vorbis_dsp_clear(&vf->vd);
  154611. vorbis_block_clear(&vf->vb);
  154612. vf->ready_state=OPENED;
  154613. }
  154614. /* fetch and process a packet. Handles the case where we're at a
  154615. bitstream boundary and dumps the decoding machine. If the decoding
  154616. machine is unloaded, it loads it. It also keeps pcm_offset up to
  154617. date (seek and read both use this. seek uses a special hack with
  154618. readp).
  154619. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  154620. 0) need more data (only if readp==0)
  154621. 1) got a packet
  154622. */
  154623. static int _fetch_and_process_packet(OggVorbis_File *vf,
  154624. ogg_packet *op_in,
  154625. int readp,
  154626. int spanp){
  154627. ogg_page og;
  154628. /* handle one packet. Try to fetch it from current stream state */
  154629. /* extract packets from page */
  154630. while(1){
  154631. /* process a packet if we can. If the machine isn't loaded,
  154632. neither is a page */
  154633. if(vf->ready_state==INITSET){
  154634. while(1) {
  154635. ogg_packet op;
  154636. ogg_packet *op_ptr=(op_in?op_in:&op);
  154637. int result=ogg_stream_packetout(&vf->os,op_ptr);
  154638. ogg_int64_t granulepos;
  154639. op_in=NULL;
  154640. if(result==-1)return(OV_HOLE); /* hole in the data. */
  154641. if(result>0){
  154642. /* got a packet. process it */
  154643. granulepos=op_ptr->granulepos;
  154644. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  154645. header handling. The
  154646. header packets aren't
  154647. audio, so if/when we
  154648. submit them,
  154649. vorbis_synthesis will
  154650. reject them */
  154651. /* suck in the synthesis data and track bitrate */
  154652. {
  154653. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  154654. /* for proper use of libvorbis within libvorbisfile,
  154655. oldsamples will always be zero. */
  154656. if(oldsamples)return(OV_EFAULT);
  154657. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  154658. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  154659. vf->bittrack+=op_ptr->bytes*8;
  154660. }
  154661. /* update the pcm offset. */
  154662. if(granulepos!=-1 && !op_ptr->e_o_s){
  154663. int link=(vf->seekable?vf->current_link:0);
  154664. int i,samples;
  154665. /* this packet has a pcm_offset on it (the last packet
  154666. completed on a page carries the offset) After processing
  154667. (above), we know the pcm position of the *last* sample
  154668. ready to be returned. Find the offset of the *first*
  154669. As an aside, this trick is inaccurate if we begin
  154670. reading anew right at the last page; the end-of-stream
  154671. granulepos declares the last frame in the stream, and the
  154672. last packet of the last page may be a partial frame.
  154673. So, we need a previous granulepos from an in-sequence page
  154674. to have a reference point. Thus the !op_ptr->e_o_s clause
  154675. above */
  154676. if(vf->seekable && link>0)
  154677. granulepos-=vf->pcmlengths[link*2];
  154678. if(granulepos<0)granulepos=0; /* actually, this
  154679. shouldn't be possible
  154680. here unless the stream
  154681. is very broken */
  154682. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  154683. granulepos-=samples;
  154684. for(i=0;i<link;i++)
  154685. granulepos+=vf->pcmlengths[i*2+1];
  154686. vf->pcm_offset=granulepos;
  154687. }
  154688. return(1);
  154689. }
  154690. }
  154691. else
  154692. break;
  154693. }
  154694. }
  154695. if(vf->ready_state>=OPENED){
  154696. ogg_int64_t ret;
  154697. if(!readp)return(0);
  154698. if((ret=_get_next_page(vf,&og,-1))<0){
  154699. return(OV_EOF); /* eof.
  154700. leave unitialized */
  154701. }
  154702. /* bitrate tracking; add the header's bytes here, the body bytes
  154703. are done by packet above */
  154704. vf->bittrack+=og.header_len*8;
  154705. /* has our decoding just traversed a bitstream boundary? */
  154706. if(vf->ready_state==INITSET){
  154707. if(vf->current_serialno!=ogg_page_serialno(&og)){
  154708. if(!spanp)
  154709. return(OV_EOF);
  154710. _decode_clear(vf);
  154711. if(!vf->seekable){
  154712. vorbis_info_clear(vf->vi);
  154713. vorbis_comment_clear(vf->vc);
  154714. }
  154715. }
  154716. }
  154717. }
  154718. /* Do we need to load a new machine before submitting the page? */
  154719. /* This is different in the seekable and non-seekable cases.
  154720. In the seekable case, we already have all the header
  154721. information loaded and cached; we just initialize the machine
  154722. with it and continue on our merry way.
  154723. In the non-seekable (streaming) case, we'll only be at a
  154724. boundary if we just left the previous logical bitstream and
  154725. we're now nominally at the header of the next bitstream
  154726. */
  154727. if(vf->ready_state!=INITSET){
  154728. int link;
  154729. if(vf->ready_state<STREAMSET){
  154730. if(vf->seekable){
  154731. vf->current_serialno=ogg_page_serialno(&og);
  154732. /* match the serialno to bitstream section. We use this rather than
  154733. offset positions to avoid problems near logical bitstream
  154734. boundaries */
  154735. for(link=0;link<vf->links;link++)
  154736. if(vf->serialnos[link]==vf->current_serialno)break;
  154737. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  154738. stream. error out,
  154739. leave machine
  154740. uninitialized */
  154741. vf->current_link=link;
  154742. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  154743. vf->ready_state=STREAMSET;
  154744. }else{
  154745. /* we're streaming */
  154746. /* fetch the three header packets, build the info struct */
  154747. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  154748. if(ret)return(ret);
  154749. vf->current_link++;
  154750. link=0;
  154751. }
  154752. }
  154753. {
  154754. int ret=_make_decode_ready(vf);
  154755. if(ret<0)return ret;
  154756. }
  154757. }
  154758. ogg_stream_pagein(&vf->os,&og);
  154759. }
  154760. }
  154761. /* if, eg, 64 bit stdio is configured by default, this will build with
  154762. fseek64 */
  154763. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  154764. if(f==NULL)return(-1);
  154765. return fseek(f,off,whence);
  154766. }
  154767. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  154768. long ibytes, ov_callbacks callbacks){
  154769. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  154770. int ret;
  154771. memset(vf,0,sizeof(*vf));
  154772. vf->datasource=f;
  154773. vf->callbacks = callbacks;
  154774. /* init the framing state */
  154775. ogg_sync_init(&vf->oy);
  154776. /* perhaps some data was previously read into a buffer for testing
  154777. against other stream types. Allow initialization from this
  154778. previously read data (as we may be reading from a non-seekable
  154779. stream) */
  154780. if(initial){
  154781. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  154782. memcpy(buffer,initial,ibytes);
  154783. ogg_sync_wrote(&vf->oy,ibytes);
  154784. }
  154785. /* can we seek? Stevens suggests the seek test was portable */
  154786. if(offsettest!=-1)vf->seekable=1;
  154787. /* No seeking yet; Set up a 'single' (current) logical bitstream
  154788. entry for partial open */
  154789. vf->links=1;
  154790. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  154791. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  154792. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  154793. /* Try to fetch the headers, maintaining all the storage */
  154794. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  154795. vf->datasource=NULL;
  154796. ov_clear(vf);
  154797. }else
  154798. vf->ready_state=PARTOPEN;
  154799. return(ret);
  154800. }
  154801. static int _ov_open2(OggVorbis_File *vf){
  154802. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  154803. vf->ready_state=OPENED;
  154804. if(vf->seekable){
  154805. int ret=_open_seekable2(vf);
  154806. if(ret){
  154807. vf->datasource=NULL;
  154808. ov_clear(vf);
  154809. }
  154810. return(ret);
  154811. }else
  154812. vf->ready_state=STREAMSET;
  154813. return 0;
  154814. }
  154815. /* clear out the OggVorbis_File struct */
  154816. int ov_clear(OggVorbis_File *vf){
  154817. if(vf){
  154818. vorbis_block_clear(&vf->vb);
  154819. vorbis_dsp_clear(&vf->vd);
  154820. ogg_stream_clear(&vf->os);
  154821. if(vf->vi && vf->links){
  154822. int i;
  154823. for(i=0;i<vf->links;i++){
  154824. vorbis_info_clear(vf->vi+i);
  154825. vorbis_comment_clear(vf->vc+i);
  154826. }
  154827. _ogg_free(vf->vi);
  154828. _ogg_free(vf->vc);
  154829. }
  154830. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  154831. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  154832. if(vf->serialnos)_ogg_free(vf->serialnos);
  154833. if(vf->offsets)_ogg_free(vf->offsets);
  154834. ogg_sync_clear(&vf->oy);
  154835. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  154836. memset(vf,0,sizeof(*vf));
  154837. }
  154838. #ifdef DEBUG_LEAKS
  154839. _VDBG_dump();
  154840. #endif
  154841. return(0);
  154842. }
  154843. /* inspects the OggVorbis file and finds/documents all the logical
  154844. bitstreams contained in it. Tries to be tolerant of logical
  154845. bitstream sections that are truncated/woogie.
  154846. return: -1) error
  154847. 0) OK
  154848. */
  154849. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  154850. ov_callbacks callbacks){
  154851. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  154852. if(ret)return ret;
  154853. return _ov_open2(vf);
  154854. }
  154855. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  154856. ov_callbacks callbacks = {
  154857. (size_t (*)(void *, size_t, size_t, void *)) fread,
  154858. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  154859. (int (*)(void *)) fclose,
  154860. (long (*)(void *)) ftell
  154861. };
  154862. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  154863. }
  154864. /* cheap hack for game usage where downsampling is desirable; there's
  154865. no need for SRC as we can just do it cheaply in libvorbis. */
  154866. int ov_halfrate(OggVorbis_File *vf,int flag){
  154867. int i;
  154868. if(vf->vi==NULL)return OV_EINVAL;
  154869. if(!vf->seekable)return OV_EINVAL;
  154870. if(vf->ready_state>=STREAMSET)
  154871. _decode_clear(vf); /* clear out stream state; later on libvorbis
  154872. will be able to swap this on the fly, but
  154873. for now dumping the decode machine is needed
  154874. to reinit the MDCT lookups. 1.1 libvorbis
  154875. is planned to be able to switch on the fly */
  154876. for(i=0;i<vf->links;i++){
  154877. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  154878. ov_halfrate(vf,0);
  154879. return OV_EINVAL;
  154880. }
  154881. }
  154882. return 0;
  154883. }
  154884. int ov_halfrate_p(OggVorbis_File *vf){
  154885. if(vf->vi==NULL)return OV_EINVAL;
  154886. return vorbis_synthesis_halfrate_p(vf->vi);
  154887. }
  154888. /* Only partially open the vorbis file; test for Vorbisness, and load
  154889. the headers for the first chain. Do not seek (although test for
  154890. seekability). Use ov_test_open to finish opening the file, else
  154891. ov_clear to close/free it. Same return codes as open. */
  154892. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  154893. ov_callbacks callbacks)
  154894. {
  154895. return _ov_open1(f,vf,initial,ibytes,callbacks);
  154896. }
  154897. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  154898. ov_callbacks callbacks = {
  154899. (size_t (*)(void *, size_t, size_t, void *)) fread,
  154900. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  154901. (int (*)(void *)) fclose,
  154902. (long (*)(void *)) ftell
  154903. };
  154904. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  154905. }
  154906. int ov_test_open(OggVorbis_File *vf){
  154907. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  154908. return _ov_open2(vf);
  154909. }
  154910. /* How many logical bitstreams in this physical bitstream? */
  154911. long ov_streams(OggVorbis_File *vf){
  154912. return vf->links;
  154913. }
  154914. /* Is the FILE * associated with vf seekable? */
  154915. long ov_seekable(OggVorbis_File *vf){
  154916. return vf->seekable;
  154917. }
  154918. /* returns the bitrate for a given logical bitstream or the entire
  154919. physical bitstream. If the file is open for random access, it will
  154920. find the *actual* average bitrate. If the file is streaming, it
  154921. returns the nominal bitrate (if set) else the average of the
  154922. upper/lower bounds (if set) else -1 (unset).
  154923. If you want the actual bitrate field settings, get them from the
  154924. vorbis_info structs */
  154925. long ov_bitrate(OggVorbis_File *vf,int i){
  154926. if(vf->ready_state<OPENED)return(OV_EINVAL);
  154927. if(i>=vf->links)return(OV_EINVAL);
  154928. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  154929. if(i<0){
  154930. ogg_int64_t bits=0;
  154931. int i;
  154932. float br;
  154933. for(i=0;i<vf->links;i++)
  154934. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  154935. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  154936. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  154937. * so this is slightly transformed to make it work.
  154938. */
  154939. br = bits/ov_time_total(vf,-1);
  154940. return(rint(br));
  154941. }else{
  154942. if(vf->seekable){
  154943. /* return the actual bitrate */
  154944. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  154945. }else{
  154946. /* return nominal if set */
  154947. if(vf->vi[i].bitrate_nominal>0){
  154948. return vf->vi[i].bitrate_nominal;
  154949. }else{
  154950. if(vf->vi[i].bitrate_upper>0){
  154951. if(vf->vi[i].bitrate_lower>0){
  154952. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  154953. }else{
  154954. return vf->vi[i].bitrate_upper;
  154955. }
  154956. }
  154957. return(OV_FALSE);
  154958. }
  154959. }
  154960. }
  154961. }
  154962. /* returns the actual bitrate since last call. returns -1 if no
  154963. additional data to offer since last call (or at beginning of stream),
  154964. EINVAL if stream is only partially open
  154965. */
  154966. long ov_bitrate_instant(OggVorbis_File *vf){
  154967. int link=(vf->seekable?vf->current_link:0);
  154968. long ret;
  154969. if(vf->ready_state<OPENED)return(OV_EINVAL);
  154970. if(vf->samptrack==0)return(OV_FALSE);
  154971. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  154972. vf->bittrack=0.f;
  154973. vf->samptrack=0.f;
  154974. return(ret);
  154975. }
  154976. /* Guess */
  154977. long ov_serialnumber(OggVorbis_File *vf,int i){
  154978. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  154979. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  154980. if(i<0){
  154981. return(vf->current_serialno);
  154982. }else{
  154983. return(vf->serialnos[i]);
  154984. }
  154985. }
  154986. /* returns: total raw (compressed) length of content if i==-1
  154987. raw (compressed) length of that logical bitstream for i==0 to n
  154988. OV_EINVAL if the stream is not seekable (we can't know the length)
  154989. or if stream is only partially open
  154990. */
  154991. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  154992. if(vf->ready_state<OPENED)return(OV_EINVAL);
  154993. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  154994. if(i<0){
  154995. ogg_int64_t acc=0;
  154996. int i;
  154997. for(i=0;i<vf->links;i++)
  154998. acc+=ov_raw_total(vf,i);
  154999. return(acc);
  155000. }else{
  155001. return(vf->offsets[i+1]-vf->offsets[i]);
  155002. }
  155003. }
  155004. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155005. (samples) of that logical bitstream for i==0 to n
  155006. OV_EINVAL if the stream is not seekable (we can't know the
  155007. length) or only partially open
  155008. */
  155009. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155010. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155011. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155012. if(i<0){
  155013. ogg_int64_t acc=0;
  155014. int i;
  155015. for(i=0;i<vf->links;i++)
  155016. acc+=ov_pcm_total(vf,i);
  155017. return(acc);
  155018. }else{
  155019. return(vf->pcmlengths[i*2+1]);
  155020. }
  155021. }
  155022. /* returns: total seconds of content if i==-1
  155023. seconds in that logical bitstream for i==0 to n
  155024. OV_EINVAL if the stream is not seekable (we can't know the
  155025. length) or only partially open
  155026. */
  155027. double ov_time_total(OggVorbis_File *vf,int i){
  155028. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155029. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155030. if(i<0){
  155031. double acc=0;
  155032. int i;
  155033. for(i=0;i<vf->links;i++)
  155034. acc+=ov_time_total(vf,i);
  155035. return(acc);
  155036. }else{
  155037. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155038. }
  155039. }
  155040. /* seek to an offset relative to the *compressed* data. This also
  155041. scans packets to update the PCM cursor. It will cross a logical
  155042. bitstream boundary, but only if it can't get any packets out of the
  155043. tail of the bitstream we seek to (so no surprises).
  155044. returns zero on success, nonzero on failure */
  155045. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155046. ogg_stream_state work_os;
  155047. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155048. if(!vf->seekable)
  155049. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155050. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155051. /* don't yet clear out decoding machine (if it's initialized), in
  155052. the case we're in the same link. Restart the decode lapping, and
  155053. let _fetch_and_process_packet deal with a potential bitstream
  155054. boundary */
  155055. vf->pcm_offset=-1;
  155056. ogg_stream_reset_serialno(&vf->os,
  155057. vf->current_serialno); /* must set serialno */
  155058. vorbis_synthesis_restart(&vf->vd);
  155059. _seek_helper(vf,pos);
  155060. /* we need to make sure the pcm_offset is set, but we don't want to
  155061. advance the raw cursor past good packets just to get to the first
  155062. with a granulepos. That's not equivalent behavior to beginning
  155063. decoding as immediately after the seek position as possible.
  155064. So, a hack. We use two stream states; a local scratch state and
  155065. the shared vf->os stream state. We use the local state to
  155066. scan, and the shared state as a buffer for later decode.
  155067. Unfortuantely, on the last page we still advance to last packet
  155068. because the granulepos on the last page is not necessarily on a
  155069. packet boundary, and we need to make sure the granpos is
  155070. correct.
  155071. */
  155072. {
  155073. ogg_page og;
  155074. ogg_packet op;
  155075. int lastblock=0;
  155076. int accblock=0;
  155077. int thisblock;
  155078. int eosflag;
  155079. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155080. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155081. return from not necessarily
  155082. starting from the beginning */
  155083. while(1){
  155084. if(vf->ready_state>=STREAMSET){
  155085. /* snarf/scan a packet if we can */
  155086. int result=ogg_stream_packetout(&work_os,&op);
  155087. if(result>0){
  155088. if(vf->vi[vf->current_link].codec_setup){
  155089. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155090. if(thisblock<0){
  155091. ogg_stream_packetout(&vf->os,NULL);
  155092. thisblock=0;
  155093. }else{
  155094. if(eosflag)
  155095. ogg_stream_packetout(&vf->os,NULL);
  155096. else
  155097. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155098. }
  155099. if(op.granulepos!=-1){
  155100. int i,link=vf->current_link;
  155101. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155102. if(granulepos<0)granulepos=0;
  155103. for(i=0;i<link;i++)
  155104. granulepos+=vf->pcmlengths[i*2+1];
  155105. vf->pcm_offset=granulepos-accblock;
  155106. break;
  155107. }
  155108. lastblock=thisblock;
  155109. continue;
  155110. }else
  155111. ogg_stream_packetout(&vf->os,NULL);
  155112. }
  155113. }
  155114. if(!lastblock){
  155115. if(_get_next_page(vf,&og,-1)<0){
  155116. vf->pcm_offset=ov_pcm_total(vf,-1);
  155117. break;
  155118. }
  155119. }else{
  155120. /* huh? Bogus stream with packets but no granulepos */
  155121. vf->pcm_offset=-1;
  155122. break;
  155123. }
  155124. /* has our decoding just traversed a bitstream boundary? */
  155125. if(vf->ready_state>=STREAMSET)
  155126. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155127. _decode_clear(vf); /* clear out stream state */
  155128. ogg_stream_clear(&work_os);
  155129. }
  155130. if(vf->ready_state<STREAMSET){
  155131. int link;
  155132. vf->current_serialno=ogg_page_serialno(&og);
  155133. for(link=0;link<vf->links;link++)
  155134. if(vf->serialnos[link]==vf->current_serialno)break;
  155135. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  155136. error out, leave
  155137. machine uninitialized */
  155138. vf->current_link=link;
  155139. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155140. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  155141. vf->ready_state=STREAMSET;
  155142. }
  155143. ogg_stream_pagein(&vf->os,&og);
  155144. ogg_stream_pagein(&work_os,&og);
  155145. eosflag=ogg_page_eos(&og);
  155146. }
  155147. }
  155148. ogg_stream_clear(&work_os);
  155149. vf->bittrack=0.f;
  155150. vf->samptrack=0.f;
  155151. return(0);
  155152. seek_error:
  155153. /* dump the machine so we're in a known state */
  155154. vf->pcm_offset=-1;
  155155. ogg_stream_clear(&work_os);
  155156. _decode_clear(vf);
  155157. return OV_EBADLINK;
  155158. }
  155159. /* Page granularity seek (faster than sample granularity because we
  155160. don't do the last bit of decode to find a specific sample).
  155161. Seek to the last [granule marked] page preceeding the specified pos
  155162. location, such that decoding past the returned point will quickly
  155163. arrive at the requested position. */
  155164. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  155165. int link=-1;
  155166. ogg_int64_t result=0;
  155167. ogg_int64_t total=ov_pcm_total(vf,-1);
  155168. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155169. if(!vf->seekable)return(OV_ENOSEEK);
  155170. if(pos<0 || pos>total)return(OV_EINVAL);
  155171. /* which bitstream section does this pcm offset occur in? */
  155172. for(link=vf->links-1;link>=0;link--){
  155173. total-=vf->pcmlengths[link*2+1];
  155174. if(pos>=total)break;
  155175. }
  155176. /* search within the logical bitstream for the page with the highest
  155177. pcm_pos preceeding (or equal to) pos. There is a danger here;
  155178. missing pages or incorrect frame number information in the
  155179. bitstream could make our task impossible. Account for that (it
  155180. would be an error condition) */
  155181. /* new search algorithm by HB (Nicholas Vinen) */
  155182. {
  155183. ogg_int64_t end=vf->offsets[link+1];
  155184. ogg_int64_t begin=vf->offsets[link];
  155185. ogg_int64_t begintime = vf->pcmlengths[link*2];
  155186. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  155187. ogg_int64_t target=pos-total+begintime;
  155188. ogg_int64_t best=begin;
  155189. ogg_page og;
  155190. while(begin<end){
  155191. ogg_int64_t bisect;
  155192. if(end-begin<CHUNKSIZE){
  155193. bisect=begin;
  155194. }else{
  155195. /* take a (pretty decent) guess. */
  155196. bisect=begin +
  155197. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  155198. if(bisect<=begin)
  155199. bisect=begin+1;
  155200. }
  155201. _seek_helper(vf,bisect);
  155202. while(begin<end){
  155203. result=_get_next_page(vf,&og,end-vf->offset);
  155204. if(result==OV_EREAD) goto seek_error;
  155205. if(result<0){
  155206. if(bisect<=begin+1)
  155207. end=begin; /* found it */
  155208. else{
  155209. if(bisect==0) goto seek_error;
  155210. bisect-=CHUNKSIZE;
  155211. if(bisect<=begin)bisect=begin+1;
  155212. _seek_helper(vf,bisect);
  155213. }
  155214. }else{
  155215. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  155216. if(granulepos==-1)continue;
  155217. if(granulepos<target){
  155218. best=result; /* raw offset of packet with granulepos */
  155219. begin=vf->offset; /* raw offset of next page */
  155220. begintime=granulepos;
  155221. if(target-begintime>44100)break;
  155222. bisect=begin; /* *not* begin + 1 */
  155223. }else{
  155224. if(bisect<=begin+1)
  155225. end=begin; /* found it */
  155226. else{
  155227. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  155228. end=result;
  155229. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  155230. if(bisect<=begin)bisect=begin+1;
  155231. _seek_helper(vf,bisect);
  155232. }else{
  155233. end=result;
  155234. endtime=granulepos;
  155235. break;
  155236. }
  155237. }
  155238. }
  155239. }
  155240. }
  155241. }
  155242. /* found our page. seek to it, update pcm offset. Easier case than
  155243. raw_seek, don't keep packets preceeding granulepos. */
  155244. {
  155245. ogg_page og;
  155246. ogg_packet op;
  155247. /* seek */
  155248. _seek_helper(vf,best);
  155249. vf->pcm_offset=-1;
  155250. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  155251. if(link!=vf->current_link){
  155252. /* Different link; dump entire decode machine */
  155253. _decode_clear(vf);
  155254. vf->current_link=link;
  155255. vf->current_serialno=ogg_page_serialno(&og);
  155256. vf->ready_state=STREAMSET;
  155257. }else{
  155258. vorbis_synthesis_restart(&vf->vd);
  155259. }
  155260. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155261. ogg_stream_pagein(&vf->os,&og);
  155262. /* pull out all but last packet; the one with granulepos */
  155263. while(1){
  155264. result=ogg_stream_packetpeek(&vf->os,&op);
  155265. if(result==0){
  155266. /* !!! the packet finishing this page originated on a
  155267. preceeding page. Keep fetching previous pages until we
  155268. get one with a granulepos or without the 'continued' flag
  155269. set. Then just use raw_seek for simplicity. */
  155270. _seek_helper(vf,best);
  155271. while(1){
  155272. result=_get_prev_page(vf,&og);
  155273. if(result<0) goto seek_error;
  155274. if(ogg_page_granulepos(&og)>-1 ||
  155275. !ogg_page_continued(&og)){
  155276. return ov_raw_seek(vf,result);
  155277. }
  155278. vf->offset=result;
  155279. }
  155280. }
  155281. if(result<0){
  155282. result = OV_EBADPACKET;
  155283. goto seek_error;
  155284. }
  155285. if(op.granulepos!=-1){
  155286. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155287. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155288. vf->pcm_offset+=total;
  155289. break;
  155290. }else
  155291. result=ogg_stream_packetout(&vf->os,NULL);
  155292. }
  155293. }
  155294. }
  155295. /* verify result */
  155296. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  155297. result=OV_EFAULT;
  155298. goto seek_error;
  155299. }
  155300. vf->bittrack=0.f;
  155301. vf->samptrack=0.f;
  155302. return(0);
  155303. seek_error:
  155304. /* dump machine so we're in a known state */
  155305. vf->pcm_offset=-1;
  155306. _decode_clear(vf);
  155307. return (int)result;
  155308. }
  155309. /* seek to a sample offset relative to the decompressed pcm stream
  155310. returns zero on success, nonzero on failure */
  155311. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155312. int thisblock,lastblock=0;
  155313. int ret=ov_pcm_seek_page(vf,pos);
  155314. if(ret<0)return(ret);
  155315. if((ret=_make_decode_ready(vf)))return ret;
  155316. /* discard leading packets we don't need for the lapping of the
  155317. position we want; don't decode them */
  155318. while(1){
  155319. ogg_packet op;
  155320. ogg_page og;
  155321. int ret=ogg_stream_packetpeek(&vf->os,&op);
  155322. if(ret>0){
  155323. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155324. if(thisblock<0){
  155325. ogg_stream_packetout(&vf->os,NULL);
  155326. continue; /* non audio packet */
  155327. }
  155328. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  155329. if(vf->pcm_offset+((thisblock+
  155330. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  155331. /* remove the packet from packet queue and track its granulepos */
  155332. ogg_stream_packetout(&vf->os,NULL);
  155333. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  155334. only tracking, no
  155335. pcm_decode */
  155336. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155337. /* end of logical stream case is hard, especially with exact
  155338. length positioning. */
  155339. if(op.granulepos>-1){
  155340. int i;
  155341. /* always believe the stream markers */
  155342. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155343. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155344. for(i=0;i<vf->current_link;i++)
  155345. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  155346. }
  155347. lastblock=thisblock;
  155348. }else{
  155349. if(ret<0 && ret!=OV_HOLE)break;
  155350. /* suck in a new page */
  155351. if(_get_next_page(vf,&og,-1)<0)break;
  155352. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  155353. if(vf->ready_state<STREAMSET){
  155354. int link;
  155355. vf->current_serialno=ogg_page_serialno(&og);
  155356. for(link=0;link<vf->links;link++)
  155357. if(vf->serialnos[link]==vf->current_serialno)break;
  155358. if(link==vf->links)return(OV_EBADLINK);
  155359. vf->current_link=link;
  155360. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155361. vf->ready_state=STREAMSET;
  155362. ret=_make_decode_ready(vf);
  155363. if(ret)return ret;
  155364. lastblock=0;
  155365. }
  155366. ogg_stream_pagein(&vf->os,&og);
  155367. }
  155368. }
  155369. vf->bittrack=0.f;
  155370. vf->samptrack=0.f;
  155371. /* discard samples until we reach the desired position. Crossing a
  155372. logical bitstream boundary with abandon is OK. */
  155373. while(vf->pcm_offset<pos){
  155374. ogg_int64_t target=pos-vf->pcm_offset;
  155375. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155376. if(samples>target)samples=target;
  155377. vorbis_synthesis_read(&vf->vd,samples);
  155378. vf->pcm_offset+=samples;
  155379. if(samples<target)
  155380. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  155381. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  155382. }
  155383. return 0;
  155384. }
  155385. /* seek to a playback time relative to the decompressed pcm stream
  155386. returns zero on success, nonzero on failure */
  155387. int ov_time_seek(OggVorbis_File *vf,double seconds){
  155388. /* translate time to PCM position and call ov_pcm_seek */
  155389. int link=-1;
  155390. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  155391. double time_total=ov_time_total(vf,-1);
  155392. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155393. if(!vf->seekable)return(OV_ENOSEEK);
  155394. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  155395. /* which bitstream section does this time offset occur in? */
  155396. for(link=vf->links-1;link>=0;link--){
  155397. pcm_total-=vf->pcmlengths[link*2+1];
  155398. time_total-=ov_time_total(vf,link);
  155399. if(seconds>=time_total)break;
  155400. }
  155401. /* enough information to convert time offset to pcm offset */
  155402. {
  155403. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  155404. return(ov_pcm_seek(vf,target));
  155405. }
  155406. }
  155407. /* page-granularity version of ov_time_seek
  155408. returns zero on success, nonzero on failure */
  155409. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  155410. /* translate time to PCM position and call ov_pcm_seek */
  155411. int link=-1;
  155412. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  155413. double time_total=ov_time_total(vf,-1);
  155414. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155415. if(!vf->seekable)return(OV_ENOSEEK);
  155416. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  155417. /* which bitstream section does this time offset occur in? */
  155418. for(link=vf->links-1;link>=0;link--){
  155419. pcm_total-=vf->pcmlengths[link*2+1];
  155420. time_total-=ov_time_total(vf,link);
  155421. if(seconds>=time_total)break;
  155422. }
  155423. /* enough information to convert time offset to pcm offset */
  155424. {
  155425. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  155426. return(ov_pcm_seek_page(vf,target));
  155427. }
  155428. }
  155429. /* tell the current stream offset cursor. Note that seek followed by
  155430. tell will likely not give the set offset due to caching */
  155431. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  155432. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155433. return(vf->offset);
  155434. }
  155435. /* return PCM offset (sample) of next PCM sample to be read */
  155436. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  155437. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155438. return(vf->pcm_offset);
  155439. }
  155440. /* return time offset (seconds) of next PCM sample to be read */
  155441. double ov_time_tell(OggVorbis_File *vf){
  155442. int link=0;
  155443. ogg_int64_t pcm_total=0;
  155444. double time_total=0.f;
  155445. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155446. if(vf->seekable){
  155447. pcm_total=ov_pcm_total(vf,-1);
  155448. time_total=ov_time_total(vf,-1);
  155449. /* which bitstream section does this time offset occur in? */
  155450. for(link=vf->links-1;link>=0;link--){
  155451. pcm_total-=vf->pcmlengths[link*2+1];
  155452. time_total-=ov_time_total(vf,link);
  155453. if(vf->pcm_offset>=pcm_total)break;
  155454. }
  155455. }
  155456. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  155457. }
  155458. /* link: -1) return the vorbis_info struct for the bitstream section
  155459. currently being decoded
  155460. 0-n) to request information for a specific bitstream section
  155461. In the case of a non-seekable bitstream, any call returns the
  155462. current bitstream. NULL in the case that the machine is not
  155463. initialized */
  155464. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  155465. if(vf->seekable){
  155466. if(link<0)
  155467. if(vf->ready_state>=STREAMSET)
  155468. return vf->vi+vf->current_link;
  155469. else
  155470. return vf->vi;
  155471. else
  155472. if(link>=vf->links)
  155473. return NULL;
  155474. else
  155475. return vf->vi+link;
  155476. }else{
  155477. return vf->vi;
  155478. }
  155479. }
  155480. /* grr, strong typing, grr, no templates/inheritence, grr */
  155481. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  155482. if(vf->seekable){
  155483. if(link<0)
  155484. if(vf->ready_state>=STREAMSET)
  155485. return vf->vc+vf->current_link;
  155486. else
  155487. return vf->vc;
  155488. else
  155489. if(link>=vf->links)
  155490. return NULL;
  155491. else
  155492. return vf->vc+link;
  155493. }else{
  155494. return vf->vc;
  155495. }
  155496. }
  155497. static int host_is_big_endian() {
  155498. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  155499. unsigned char *bytewise = (unsigned char *)&pattern;
  155500. if (bytewise[0] == 0xfe) return 1;
  155501. return 0;
  155502. }
  155503. /* up to this point, everything could more or less hide the multiple
  155504. logical bitstream nature of chaining from the toplevel application
  155505. if the toplevel application didn't particularly care. However, at
  155506. the point that we actually read audio back, the multiple-section
  155507. nature must surface: Multiple bitstream sections do not necessarily
  155508. have to have the same number of channels or sampling rate.
  155509. ov_read returns the sequential logical bitstream number currently
  155510. being decoded along with the PCM data in order that the toplevel
  155511. application can take action on channel/sample rate changes. This
  155512. number will be incremented even for streamed (non-seekable) streams
  155513. (for seekable streams, it represents the actual logical bitstream
  155514. index within the physical bitstream. Note that the accessor
  155515. functions above are aware of this dichotomy).
  155516. input values: buffer) a buffer to hold packed PCM data for return
  155517. length) the byte length requested to be placed into buffer
  155518. bigendianp) should the data be packed LSB first (0) or
  155519. MSB first (1)
  155520. word) word size for output. currently 1 (byte) or
  155521. 2 (16 bit short)
  155522. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  155523. 0) EOF
  155524. n) number of bytes of PCM actually returned. The
  155525. below works on a packet-by-packet basis, so the
  155526. return length is not related to the 'length' passed
  155527. in, just guaranteed to fit.
  155528. *section) set to the logical bitstream number */
  155529. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  155530. int bigendianp,int word,int sgned,int *bitstream){
  155531. int i,j;
  155532. int host_endian = host_is_big_endian();
  155533. float **pcm;
  155534. long samples;
  155535. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155536. while(1){
  155537. if(vf->ready_state==INITSET){
  155538. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  155539. if(samples)break;
  155540. }
  155541. /* suck in another packet */
  155542. {
  155543. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  155544. if(ret==OV_EOF)
  155545. return(0);
  155546. if(ret<=0)
  155547. return(ret);
  155548. }
  155549. }
  155550. if(samples>0){
  155551. /* yay! proceed to pack data into the byte buffer */
  155552. long channels=ov_info(vf,-1)->channels;
  155553. long bytespersample=word * channels;
  155554. vorbis_fpu_control fpu;
  155555. (void) fpu; // (to avoid a warning about it being unused)
  155556. if(samples>length/bytespersample)samples=length/bytespersample;
  155557. if(samples <= 0)
  155558. return OV_EINVAL;
  155559. /* a tight loop to pack each size */
  155560. {
  155561. int val;
  155562. if(word==1){
  155563. int off=(sgned?0:128);
  155564. vorbis_fpu_setround(&fpu);
  155565. for(j=0;j<samples;j++)
  155566. for(i=0;i<channels;i++){
  155567. val=vorbis_ftoi(pcm[i][j]*128.f);
  155568. if(val>127)val=127;
  155569. else if(val<-128)val=-128;
  155570. *buffer++=val+off;
  155571. }
  155572. vorbis_fpu_restore(fpu);
  155573. }else{
  155574. int off=(sgned?0:32768);
  155575. if(host_endian==bigendianp){
  155576. if(sgned){
  155577. vorbis_fpu_setround(&fpu);
  155578. for(i=0;i<channels;i++) { /* It's faster in this order */
  155579. float *src=pcm[i];
  155580. short *dest=((short *)buffer)+i;
  155581. for(j=0;j<samples;j++) {
  155582. val=vorbis_ftoi(src[j]*32768.f);
  155583. if(val>32767)val=32767;
  155584. else if(val<-32768)val=-32768;
  155585. *dest=val;
  155586. dest+=channels;
  155587. }
  155588. }
  155589. vorbis_fpu_restore(fpu);
  155590. }else{
  155591. vorbis_fpu_setround(&fpu);
  155592. for(i=0;i<channels;i++) {
  155593. float *src=pcm[i];
  155594. short *dest=((short *)buffer)+i;
  155595. for(j=0;j<samples;j++) {
  155596. val=vorbis_ftoi(src[j]*32768.f);
  155597. if(val>32767)val=32767;
  155598. else if(val<-32768)val=-32768;
  155599. *dest=val+off;
  155600. dest+=channels;
  155601. }
  155602. }
  155603. vorbis_fpu_restore(fpu);
  155604. }
  155605. }else if(bigendianp){
  155606. vorbis_fpu_setround(&fpu);
  155607. for(j=0;j<samples;j++)
  155608. for(i=0;i<channels;i++){
  155609. val=vorbis_ftoi(pcm[i][j]*32768.f);
  155610. if(val>32767)val=32767;
  155611. else if(val<-32768)val=-32768;
  155612. val+=off;
  155613. *buffer++=(val>>8);
  155614. *buffer++=(val&0xff);
  155615. }
  155616. vorbis_fpu_restore(fpu);
  155617. }else{
  155618. int val;
  155619. vorbis_fpu_setround(&fpu);
  155620. for(j=0;j<samples;j++)
  155621. for(i=0;i<channels;i++){
  155622. val=vorbis_ftoi(pcm[i][j]*32768.f);
  155623. if(val>32767)val=32767;
  155624. else if(val<-32768)val=-32768;
  155625. val+=off;
  155626. *buffer++=(val&0xff);
  155627. *buffer++=(val>>8);
  155628. }
  155629. vorbis_fpu_restore(fpu);
  155630. }
  155631. }
  155632. }
  155633. vorbis_synthesis_read(&vf->vd,samples);
  155634. vf->pcm_offset+=samples;
  155635. if(bitstream)*bitstream=vf->current_link;
  155636. return(samples*bytespersample);
  155637. }else{
  155638. return(samples);
  155639. }
  155640. }
  155641. /* input values: pcm_channels) a float vector per channel of output
  155642. length) the sample length being read by the app
  155643. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  155644. 0) EOF
  155645. n) number of samples of PCM actually returned. The
  155646. below works on a packet-by-packet basis, so the
  155647. return length is not related to the 'length' passed
  155648. in, just guaranteed to fit.
  155649. *section) set to the logical bitstream number */
  155650. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  155651. int *bitstream){
  155652. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155653. while(1){
  155654. if(vf->ready_state==INITSET){
  155655. float **pcm;
  155656. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  155657. if(samples){
  155658. if(pcm_channels)*pcm_channels=pcm;
  155659. if(samples>length)samples=length;
  155660. vorbis_synthesis_read(&vf->vd,samples);
  155661. vf->pcm_offset+=samples;
  155662. if(bitstream)*bitstream=vf->current_link;
  155663. return samples;
  155664. }
  155665. }
  155666. /* suck in another packet */
  155667. {
  155668. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  155669. if(ret==OV_EOF)return(0);
  155670. if(ret<=0)return(ret);
  155671. }
  155672. }
  155673. }
  155674. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  155675. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  155676. ogg_int64_t off);
  155677. static void _ov_splice(float **pcm,float **lappcm,
  155678. int n1, int n2,
  155679. int ch1, int ch2,
  155680. float *w1, float *w2){
  155681. int i,j;
  155682. float *w=w1;
  155683. int n=n1;
  155684. if(n1>n2){
  155685. n=n2;
  155686. w=w2;
  155687. }
  155688. /* splice */
  155689. for(j=0;j<ch1 && j<ch2;j++){
  155690. float *s=lappcm[j];
  155691. float *d=pcm[j];
  155692. for(i=0;i<n;i++){
  155693. float wd=w[i]*w[i];
  155694. float ws=1.-wd;
  155695. d[i]=d[i]*wd + s[i]*ws;
  155696. }
  155697. }
  155698. /* window from zero */
  155699. for(;j<ch2;j++){
  155700. float *d=pcm[j];
  155701. for(i=0;i<n;i++){
  155702. float wd=w[i]*w[i];
  155703. d[i]=d[i]*wd;
  155704. }
  155705. }
  155706. }
  155707. /* make sure vf is INITSET */
  155708. static int _ov_initset(OggVorbis_File *vf){
  155709. while(1){
  155710. if(vf->ready_state==INITSET)break;
  155711. /* suck in another packet */
  155712. {
  155713. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  155714. if(ret<0 && ret!=OV_HOLE)return(ret);
  155715. }
  155716. }
  155717. return 0;
  155718. }
  155719. /* make sure vf is INITSET and that we have a primed buffer; if
  155720. we're crosslapping at a stream section boundary, this also makes
  155721. sure we're sanity checking against the right stream information */
  155722. static int _ov_initprime(OggVorbis_File *vf){
  155723. vorbis_dsp_state *vd=&vf->vd;
  155724. while(1){
  155725. if(vf->ready_state==INITSET)
  155726. if(vorbis_synthesis_pcmout(vd,NULL))break;
  155727. /* suck in another packet */
  155728. {
  155729. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  155730. if(ret<0 && ret!=OV_HOLE)return(ret);
  155731. }
  155732. }
  155733. return 0;
  155734. }
  155735. /* grab enough data for lapping from vf; this may be in the form of
  155736. unreturned, already-decoded pcm, remaining PCM we will need to
  155737. decode, or synthetic postextrapolation from last packets. */
  155738. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  155739. float **lappcm,int lapsize){
  155740. int lapcount=0,i;
  155741. float **pcm;
  155742. /* try first to decode the lapping data */
  155743. while(lapcount<lapsize){
  155744. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  155745. if(samples){
  155746. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  155747. for(i=0;i<vi->channels;i++)
  155748. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  155749. lapcount+=samples;
  155750. vorbis_synthesis_read(vd,samples);
  155751. }else{
  155752. /* suck in another packet */
  155753. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  155754. if(ret==OV_EOF)break;
  155755. }
  155756. }
  155757. if(lapcount<lapsize){
  155758. /* failed to get lapping data from normal decode; pry it from the
  155759. postextrapolation buffering, or the second half of the MDCT
  155760. from the last packet */
  155761. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  155762. if(samples==0){
  155763. for(i=0;i<vi->channels;i++)
  155764. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  155765. lapcount=lapsize;
  155766. }else{
  155767. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  155768. for(i=0;i<vi->channels;i++)
  155769. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  155770. lapcount+=samples;
  155771. }
  155772. }
  155773. }
  155774. /* this sets up crosslapping of a sample by using trailing data from
  155775. sample 1 and lapping it into the windowing buffer of sample 2 */
  155776. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  155777. vorbis_info *vi1,*vi2;
  155778. float **lappcm;
  155779. float **pcm;
  155780. float *w1,*w2;
  155781. int n1,n2,i,ret,hs1,hs2;
  155782. if(vf1==vf2)return(0); /* degenerate case */
  155783. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  155784. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  155785. /* the relevant overlap buffers must be pre-checked and pre-primed
  155786. before looking at settings in the event that priming would cross
  155787. a bitstream boundary. So, do it now */
  155788. ret=_ov_initset(vf1);
  155789. if(ret)return(ret);
  155790. ret=_ov_initprime(vf2);
  155791. if(ret)return(ret);
  155792. vi1=ov_info(vf1,-1);
  155793. vi2=ov_info(vf2,-1);
  155794. hs1=ov_halfrate_p(vf1);
  155795. hs2=ov_halfrate_p(vf2);
  155796. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  155797. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  155798. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  155799. w1=vorbis_window(&vf1->vd,0);
  155800. w2=vorbis_window(&vf2->vd,0);
  155801. for(i=0;i<vi1->channels;i++)
  155802. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  155803. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  155804. /* have a lapping buffer from vf1; now to splice it into the lapping
  155805. buffer of vf2 */
  155806. /* consolidate and expose the buffer. */
  155807. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  155808. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  155809. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  155810. /* splice */
  155811. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  155812. /* done */
  155813. return(0);
  155814. }
  155815. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  155816. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  155817. vorbis_info *vi;
  155818. float **lappcm;
  155819. float **pcm;
  155820. float *w1,*w2;
  155821. int n1,n2,ch1,ch2,hs;
  155822. int i,ret;
  155823. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155824. ret=_ov_initset(vf);
  155825. if(ret)return(ret);
  155826. vi=ov_info(vf,-1);
  155827. hs=ov_halfrate_p(vf);
  155828. ch1=vi->channels;
  155829. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  155830. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  155831. persistent; even if the decode state
  155832. from this link gets dumped, this
  155833. window array continues to exist */
  155834. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  155835. for(i=0;i<ch1;i++)
  155836. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  155837. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  155838. /* have lapping data; seek and prime the buffer */
  155839. ret=localseek(vf,pos);
  155840. if(ret)return ret;
  155841. ret=_ov_initprime(vf);
  155842. if(ret)return(ret);
  155843. /* Guard against cross-link changes; they're perfectly legal */
  155844. vi=ov_info(vf,-1);
  155845. ch2=vi->channels;
  155846. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  155847. w2=vorbis_window(&vf->vd,0);
  155848. /* consolidate and expose the buffer. */
  155849. vorbis_synthesis_lapout(&vf->vd,&pcm);
  155850. /* splice */
  155851. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  155852. /* done */
  155853. return(0);
  155854. }
  155855. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  155856. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  155857. }
  155858. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  155859. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  155860. }
  155861. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  155862. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  155863. }
  155864. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  155865. int (*localseek)(OggVorbis_File *,double)){
  155866. vorbis_info *vi;
  155867. float **lappcm;
  155868. float **pcm;
  155869. float *w1,*w2;
  155870. int n1,n2,ch1,ch2,hs;
  155871. int i,ret;
  155872. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155873. ret=_ov_initset(vf);
  155874. if(ret)return(ret);
  155875. vi=ov_info(vf,-1);
  155876. hs=ov_halfrate_p(vf);
  155877. ch1=vi->channels;
  155878. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  155879. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  155880. persistent; even if the decode state
  155881. from this link gets dumped, this
  155882. window array continues to exist */
  155883. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  155884. for(i=0;i<ch1;i++)
  155885. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  155886. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  155887. /* have lapping data; seek and prime the buffer */
  155888. ret=localseek(vf,pos);
  155889. if(ret)return ret;
  155890. ret=_ov_initprime(vf);
  155891. if(ret)return(ret);
  155892. /* Guard against cross-link changes; they're perfectly legal */
  155893. vi=ov_info(vf,-1);
  155894. ch2=vi->channels;
  155895. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  155896. w2=vorbis_window(&vf->vd,0);
  155897. /* consolidate and expose the buffer. */
  155898. vorbis_synthesis_lapout(&vf->vd,&pcm);
  155899. /* splice */
  155900. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  155901. /* done */
  155902. return(0);
  155903. }
  155904. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  155905. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  155906. }
  155907. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  155908. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  155909. }
  155910. #endif
  155911. /*** End of inlined file: vorbisfile.c ***/
  155912. /*** Start of inlined file: window.c ***/
  155913. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155914. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155915. // tasks..
  155916. #if JUCE_MSVC
  155917. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155918. #endif
  155919. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155920. #if JUCE_USE_OGGVORBIS
  155921. #include <stdlib.h>
  155922. #include <math.h>
  155923. static float vwin64[32] = {
  155924. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  155925. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  155926. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  155927. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  155928. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  155929. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  155930. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  155931. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  155932. };
  155933. static float vwin128[64] = {
  155934. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  155935. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  155936. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  155937. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  155938. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  155939. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  155940. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  155941. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  155942. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  155943. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  155944. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  155945. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  155946. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  155947. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  155948. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  155949. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  155950. };
  155951. static float vwin256[128] = {
  155952. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  155953. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  155954. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  155955. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  155956. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  155957. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  155958. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  155959. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  155960. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  155961. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  155962. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  155963. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  155964. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  155965. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  155966. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  155967. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  155968. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  155969. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  155970. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  155971. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  155972. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  155973. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  155974. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  155975. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  155976. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  155977. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  155978. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  155979. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  155980. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  155981. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  155982. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  155983. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  155984. };
  155985. static float vwin512[256] = {
  155986. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  155987. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  155988. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  155989. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  155990. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  155991. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  155992. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  155993. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  155994. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  155995. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  155996. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  155997. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  155998. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  155999. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156000. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156001. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156002. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156003. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156004. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156005. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156006. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156007. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156008. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156009. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156010. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156011. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156012. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156013. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156014. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156015. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156016. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156017. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156018. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156019. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156020. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156021. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156022. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156023. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156024. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156025. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156026. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156027. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156028. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156029. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156030. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156031. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156032. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156033. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156034. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156035. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156036. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156037. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156038. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156039. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156040. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156041. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156042. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156043. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156044. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156045. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156046. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156047. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156048. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156049. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156050. };
  156051. static float vwin1024[512] = {
  156052. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156053. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156054. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156055. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156056. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156057. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156058. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156059. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156060. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156061. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156062. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156063. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156064. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156065. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156066. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156067. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156068. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156069. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156070. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156071. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156072. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156073. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156074. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156075. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156076. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156077. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156078. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156079. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156080. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156081. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156082. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156083. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156084. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156085. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156086. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156087. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156088. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156089. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156090. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156091. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156092. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156093. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156094. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156095. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156096. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156097. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156098. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156099. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156100. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156101. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156102. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156103. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156104. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156105. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156106. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156107. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156108. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156109. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156110. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156111. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156112. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156113. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156114. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156115. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156116. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156117. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156118. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156119. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156120. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156121. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156122. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156123. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156124. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  156125. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  156126. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  156127. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  156128. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  156129. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  156130. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  156131. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  156132. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  156133. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  156134. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  156135. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  156136. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  156137. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  156138. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  156139. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  156140. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  156141. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  156142. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  156143. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  156144. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  156145. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  156146. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  156147. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  156148. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  156149. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  156150. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  156151. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  156152. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  156153. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  156154. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  156155. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  156156. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  156157. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  156158. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  156159. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  156160. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  156161. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  156162. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  156163. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  156164. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  156165. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  156166. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  156167. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  156168. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  156169. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  156170. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  156171. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  156172. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  156173. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  156174. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  156175. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  156176. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  156177. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  156178. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  156179. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  156180. };
  156181. static float vwin2048[1024] = {
  156182. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  156183. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  156184. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  156185. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  156186. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  156187. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  156188. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  156189. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  156190. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  156191. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  156192. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  156193. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  156194. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  156195. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  156196. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  156197. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  156198. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  156199. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  156200. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  156201. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  156202. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  156203. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  156204. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  156205. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  156206. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  156207. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  156208. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  156209. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  156210. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  156211. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  156212. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  156213. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  156214. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  156215. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  156216. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  156217. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  156218. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  156219. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  156220. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  156221. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  156222. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  156223. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  156224. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  156225. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  156226. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  156227. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  156228. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  156229. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  156230. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  156231. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  156232. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  156233. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  156234. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  156235. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  156236. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  156237. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  156238. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  156239. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  156240. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  156241. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  156242. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  156243. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  156244. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  156245. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  156246. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  156247. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  156248. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  156249. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  156250. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  156251. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  156252. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  156253. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  156254. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  156255. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  156256. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  156257. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  156258. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  156259. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  156260. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  156261. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  156262. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  156263. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  156264. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  156265. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  156266. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  156267. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  156268. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  156269. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  156270. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  156271. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  156272. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  156273. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  156274. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  156275. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  156276. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  156277. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  156278. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  156279. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  156280. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  156281. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  156282. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  156283. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  156284. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  156285. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  156286. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  156287. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  156288. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  156289. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  156290. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  156291. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  156292. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  156293. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  156294. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  156295. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  156296. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  156297. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  156298. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  156299. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  156300. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  156301. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  156302. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  156303. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  156304. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  156305. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  156306. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  156307. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  156308. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  156309. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  156310. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  156311. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  156312. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  156313. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  156314. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  156315. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  156316. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  156317. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  156318. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  156319. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  156320. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  156321. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  156322. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  156323. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  156324. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  156325. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  156326. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  156327. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  156328. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  156329. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  156330. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  156331. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  156332. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  156333. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  156334. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  156335. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  156336. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  156337. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  156338. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  156339. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  156340. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  156341. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  156342. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  156343. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  156344. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  156345. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  156346. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  156347. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  156348. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  156349. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  156350. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  156351. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  156352. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  156353. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  156354. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  156355. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  156356. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  156357. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  156358. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  156359. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  156360. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  156361. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  156362. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  156363. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  156364. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  156365. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  156366. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  156367. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  156368. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  156369. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  156370. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  156371. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  156372. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  156373. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  156374. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  156375. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  156376. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  156377. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  156378. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  156379. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  156380. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  156381. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  156382. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  156383. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  156384. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  156385. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  156386. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  156387. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  156388. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  156389. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  156390. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  156391. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  156392. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  156393. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  156394. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  156395. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  156396. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  156397. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  156398. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  156399. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  156400. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  156401. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  156402. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  156403. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  156404. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  156405. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  156406. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  156407. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  156408. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  156409. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  156410. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  156411. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  156412. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  156413. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  156414. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  156415. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  156416. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  156417. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  156418. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  156419. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  156420. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  156421. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  156422. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  156423. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  156424. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  156425. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  156426. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  156427. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  156428. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  156429. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  156430. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  156431. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  156432. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  156433. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  156434. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  156435. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  156436. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  156437. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  156438. };
  156439. static float vwin4096[2048] = {
  156440. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  156441. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  156442. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  156443. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  156444. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  156445. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  156446. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  156447. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  156448. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  156449. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  156450. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  156451. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  156452. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  156453. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  156454. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  156455. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  156456. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  156457. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  156458. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  156459. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  156460. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  156461. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  156462. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  156463. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  156464. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  156465. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  156466. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  156467. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  156468. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  156469. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  156470. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  156471. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  156472. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  156473. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  156474. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  156475. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  156476. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  156477. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  156478. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  156479. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  156480. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  156481. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  156482. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  156483. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  156484. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  156485. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  156486. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  156487. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  156488. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  156489. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  156490. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  156491. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  156492. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  156493. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  156494. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  156495. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  156496. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  156497. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  156498. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  156499. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  156500. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  156501. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  156502. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  156503. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  156504. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  156505. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  156506. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  156507. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  156508. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  156509. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  156510. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  156511. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  156512. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  156513. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  156514. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  156515. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  156516. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  156517. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  156518. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  156519. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  156520. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  156521. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  156522. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  156523. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  156524. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  156525. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  156526. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  156527. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  156528. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  156529. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  156530. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  156531. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  156532. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  156533. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  156534. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  156535. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  156536. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  156537. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  156538. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  156539. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  156540. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  156541. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  156542. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  156543. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  156544. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  156545. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  156546. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  156547. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  156548. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  156549. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  156550. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  156551. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  156552. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  156553. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  156554. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  156555. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  156556. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  156557. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  156558. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  156559. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  156560. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  156561. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  156562. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  156563. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  156564. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  156565. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  156566. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  156567. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  156568. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  156569. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  156570. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  156571. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  156572. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  156573. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  156574. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  156575. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  156576. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  156577. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  156578. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  156579. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  156580. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  156581. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  156582. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  156583. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  156584. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  156585. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  156586. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  156587. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  156588. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  156589. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  156590. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  156591. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  156592. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  156593. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  156594. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  156595. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  156596. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  156597. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  156598. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  156599. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  156600. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  156601. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  156602. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  156603. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  156604. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  156605. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  156606. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  156607. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  156608. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  156609. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  156610. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  156611. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  156612. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  156613. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  156614. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  156615. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  156616. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  156617. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  156618. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  156619. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  156620. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  156621. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  156622. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  156623. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  156624. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  156625. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  156626. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  156627. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  156628. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  156629. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  156630. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  156631. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  156632. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  156633. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  156634. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  156635. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  156636. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  156637. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  156638. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  156639. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  156640. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  156641. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  156642. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  156643. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  156644. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  156645. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  156646. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  156647. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  156648. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  156649. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  156650. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  156651. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  156652. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  156653. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  156654. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  156655. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  156656. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  156657. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  156658. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  156659. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  156660. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  156661. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  156662. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  156663. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  156664. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  156665. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  156666. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  156667. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  156668. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  156669. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  156670. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  156671. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  156672. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  156673. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  156674. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  156675. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  156676. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  156677. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  156678. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  156679. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  156680. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  156681. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  156682. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  156683. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  156684. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  156685. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  156686. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  156687. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  156688. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  156689. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  156690. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  156691. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  156692. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  156693. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  156694. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  156695. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  156696. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  156697. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  156698. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  156699. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  156700. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  156701. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  156702. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  156703. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  156704. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  156705. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  156706. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  156707. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  156708. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  156709. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  156710. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  156711. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  156712. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  156713. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  156714. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  156715. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  156716. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  156717. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  156718. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  156719. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  156720. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  156721. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  156722. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  156723. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  156724. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  156725. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  156726. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  156727. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  156728. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  156729. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  156730. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  156731. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  156732. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  156733. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  156734. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  156735. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  156736. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  156737. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  156738. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  156739. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  156740. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  156741. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  156742. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  156743. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  156744. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  156745. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  156746. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  156747. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  156748. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  156749. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  156750. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  156751. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  156752. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  156753. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  156754. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  156755. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  156756. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  156757. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  156758. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  156759. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  156760. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  156761. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  156762. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  156763. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  156764. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  156765. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  156766. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  156767. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  156768. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  156769. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  156770. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  156771. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  156772. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  156773. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  156774. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  156775. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  156776. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  156777. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  156778. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  156779. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  156780. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  156781. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  156782. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  156783. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  156784. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  156785. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  156786. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  156787. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  156788. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  156789. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  156790. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  156791. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  156792. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  156793. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  156794. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  156795. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  156796. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  156797. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  156798. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  156799. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  156800. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  156801. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  156802. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  156803. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  156804. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  156805. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  156806. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  156807. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  156808. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  156809. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  156810. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  156811. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  156812. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  156813. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  156814. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  156815. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  156816. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  156817. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  156818. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  156819. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  156820. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  156821. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  156822. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  156823. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  156824. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  156825. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  156826. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  156827. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  156828. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  156829. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  156830. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  156831. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  156832. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  156833. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  156834. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  156835. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  156836. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  156837. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  156838. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  156839. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  156840. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  156841. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  156842. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  156843. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  156844. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  156845. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  156846. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  156847. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  156848. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  156849. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  156850. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  156851. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  156852. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  156853. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  156854. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  156855. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  156856. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  156857. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  156858. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  156859. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  156860. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  156861. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  156862. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  156863. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  156864. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  156865. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  156866. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  156867. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  156868. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  156869. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  156870. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  156871. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  156872. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  156873. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  156874. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  156875. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  156876. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  156877. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  156878. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  156879. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  156880. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  156881. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  156882. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  156883. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  156884. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  156885. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  156886. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  156887. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  156888. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  156889. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  156890. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  156891. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  156892. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  156893. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  156894. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  156895. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  156896. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  156897. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  156898. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  156899. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  156900. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  156901. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  156902. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  156903. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  156904. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  156905. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  156906. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  156907. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  156908. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  156909. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  156910. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  156911. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  156912. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  156913. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  156914. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  156915. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  156916. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  156917. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  156918. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  156919. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  156920. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  156921. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  156922. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  156923. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  156924. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  156925. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  156926. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  156927. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  156928. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  156929. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  156930. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  156931. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  156932. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  156933. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  156934. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  156935. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  156936. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  156937. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  156938. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  156939. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  156940. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  156941. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  156942. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  156943. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  156944. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  156945. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  156946. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  156947. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  156948. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  156949. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  156950. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  156951. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  156952. };
  156953. static float vwin8192[4096] = {
  156954. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  156955. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  156956. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  156957. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  156958. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  156959. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  156960. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  156961. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  156962. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  156963. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  156964. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  156965. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  156966. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  156967. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  156968. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  156969. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  156970. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  156971. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  156972. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  156973. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  156974. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  156975. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  156976. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  156977. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  156978. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  156979. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  156980. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  156981. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  156982. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  156983. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  156984. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  156985. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  156986. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  156987. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  156988. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  156989. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  156990. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  156991. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  156992. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  156993. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  156994. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  156995. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  156996. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  156997. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  156998. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  156999. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157000. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157001. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157002. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157003. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157004. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157005. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157006. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157007. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157008. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157009. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157010. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157011. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157012. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157013. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157014. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157015. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157016. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157017. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157018. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157019. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157020. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157021. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157022. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157023. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157024. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157025. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157026. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157027. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157028. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157029. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157030. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157031. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157032. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157033. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157034. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157035. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157036. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157037. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157038. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157039. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157040. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157041. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157042. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157043. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157044. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157045. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157046. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157047. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157048. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157049. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157050. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157051. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157052. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157053. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157054. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157055. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157056. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157057. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157058. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157059. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157060. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157061. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157062. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157063. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157064. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157065. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157066. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157067. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157068. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157069. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157070. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157071. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157072. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157073. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157074. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157075. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157076. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157077. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157078. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157079. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157080. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157081. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157082. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157083. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157084. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157085. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157086. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157087. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157088. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157089. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157090. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157091. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157092. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157093. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157094. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157095. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157096. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157097. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157098. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157099. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157100. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157101. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157102. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157103. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157104. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157105. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157106. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157107. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157108. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157109. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157110. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157111. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157112. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157113. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157114. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157115. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157116. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157117. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157118. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157119. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157120. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157121. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157122. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157123. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157124. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  157125. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  157126. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  157127. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  157128. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  157129. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  157130. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  157131. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  157132. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  157133. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  157134. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  157135. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  157136. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  157137. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  157138. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  157139. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  157140. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  157141. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  157142. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  157143. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  157144. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  157145. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  157146. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  157147. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  157148. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  157149. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  157150. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  157151. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  157152. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  157153. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  157154. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  157155. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  157156. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  157157. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  157158. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  157159. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  157160. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  157161. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  157162. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  157163. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  157164. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  157165. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  157166. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  157167. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  157168. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  157169. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  157170. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  157171. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  157172. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  157173. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  157174. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  157175. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  157176. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  157177. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  157178. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  157179. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  157180. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  157181. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  157182. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  157183. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  157184. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  157185. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  157186. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  157187. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  157188. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  157189. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  157190. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  157191. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  157192. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  157193. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  157194. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  157195. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  157196. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  157197. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  157198. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  157199. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  157200. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  157201. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  157202. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  157203. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  157204. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  157205. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  157206. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  157207. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  157208. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  157209. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  157210. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  157211. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  157212. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  157213. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  157214. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  157215. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  157216. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  157217. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  157218. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  157219. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  157220. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  157221. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  157222. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  157223. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  157224. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  157225. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  157226. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  157227. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  157228. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  157229. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  157230. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  157231. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  157232. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  157233. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  157234. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  157235. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  157236. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  157237. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  157238. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  157239. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  157240. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  157241. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  157242. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  157243. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  157244. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  157245. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  157246. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  157247. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  157248. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  157249. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  157250. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  157251. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  157252. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  157253. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  157254. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  157255. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  157256. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  157257. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  157258. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  157259. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  157260. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  157261. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  157262. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  157263. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  157264. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  157265. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  157266. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  157267. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  157268. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  157269. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  157270. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  157271. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  157272. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  157273. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  157274. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  157275. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  157276. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  157277. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  157278. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  157279. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  157280. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  157281. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  157282. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  157283. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  157284. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  157285. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  157286. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  157287. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  157288. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  157289. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  157290. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  157291. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  157292. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  157293. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  157294. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  157295. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  157296. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  157297. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  157298. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  157299. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  157300. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  157301. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  157302. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  157303. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  157304. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  157305. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  157306. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  157307. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  157308. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  157309. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  157310. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  157311. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  157312. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  157313. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  157314. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  157315. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  157316. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  157317. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  157318. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  157319. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  157320. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  157321. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  157322. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  157323. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  157324. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  157325. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  157326. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  157327. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  157328. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  157329. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  157330. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  157331. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  157332. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  157333. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  157334. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  157335. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  157336. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  157337. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  157338. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  157339. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  157340. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  157341. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  157342. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  157343. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  157344. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  157345. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  157346. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  157347. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  157348. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  157349. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  157350. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  157351. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  157352. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  157353. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  157354. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  157355. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  157356. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  157357. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  157358. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  157359. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  157360. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  157361. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  157362. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  157363. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  157364. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  157365. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  157366. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  157367. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  157368. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  157369. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  157370. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  157371. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  157372. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  157373. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  157374. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  157375. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  157376. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  157377. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  157378. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  157379. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  157380. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  157381. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  157382. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  157383. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  157384. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  157385. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  157386. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  157387. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  157388. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  157389. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  157390. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  157391. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  157392. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  157393. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  157394. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  157395. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  157396. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  157397. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  157398. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  157399. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  157400. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  157401. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  157402. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  157403. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  157404. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  157405. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  157406. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  157407. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  157408. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  157409. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  157410. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  157411. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  157412. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  157413. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  157414. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  157415. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  157416. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  157417. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  157418. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  157419. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  157420. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  157421. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  157422. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  157423. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  157424. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  157425. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  157426. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  157427. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  157428. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  157429. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  157430. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  157431. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  157432. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  157433. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  157434. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  157435. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  157436. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  157437. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  157438. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  157439. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  157440. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  157441. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  157442. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  157443. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  157444. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  157445. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  157446. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  157447. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  157448. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  157449. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  157450. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  157451. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  157452. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  157453. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  157454. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  157455. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  157456. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  157457. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  157458. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  157459. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  157460. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  157461. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  157462. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  157463. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  157464. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  157465. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  157466. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  157467. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  157468. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  157469. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  157470. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  157471. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  157472. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  157473. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  157474. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  157475. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  157476. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  157477. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  157478. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  157479. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  157480. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  157481. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  157482. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  157483. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  157484. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  157485. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  157486. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  157487. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  157488. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  157489. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  157490. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  157491. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  157492. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  157493. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  157494. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  157495. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  157496. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  157497. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  157498. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  157499. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  157500. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  157501. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  157502. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  157503. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  157504. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  157505. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  157506. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  157507. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  157508. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  157509. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  157510. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  157511. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  157512. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  157513. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  157514. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  157515. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  157516. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  157517. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  157518. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  157519. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  157520. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  157521. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  157522. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  157523. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  157524. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  157525. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  157526. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  157527. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  157528. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  157529. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  157530. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  157531. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  157532. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  157533. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  157534. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  157535. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  157536. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  157537. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  157538. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  157539. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  157540. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  157541. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  157542. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  157543. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  157544. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  157545. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  157546. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  157547. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  157548. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  157549. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  157550. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  157551. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  157552. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  157553. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  157554. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  157555. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  157556. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  157557. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  157558. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  157559. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  157560. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  157561. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  157562. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  157563. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  157564. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  157565. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  157566. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  157567. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  157568. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  157569. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  157570. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  157571. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  157572. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  157573. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  157574. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  157575. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  157576. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  157577. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  157578. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  157579. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  157580. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  157581. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  157582. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  157583. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  157584. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  157585. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  157586. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  157587. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  157588. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  157589. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  157590. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  157591. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  157592. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  157593. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  157594. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  157595. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  157596. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  157597. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  157598. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  157599. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  157600. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  157601. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  157602. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  157603. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  157604. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  157605. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  157606. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  157607. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  157608. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  157609. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  157610. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  157611. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  157612. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  157613. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  157614. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  157615. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  157616. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  157617. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  157618. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  157619. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  157620. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  157621. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  157622. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  157623. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  157624. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  157625. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  157626. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  157627. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  157628. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  157629. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  157630. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  157631. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  157632. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  157633. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  157634. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  157635. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  157636. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  157637. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  157638. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  157639. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  157640. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  157641. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  157642. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  157643. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  157644. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  157645. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  157646. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  157647. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  157648. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  157649. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  157650. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  157651. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  157652. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  157653. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  157654. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  157655. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  157656. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  157657. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  157658. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  157659. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  157660. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  157661. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  157662. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  157663. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  157664. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  157665. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  157666. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  157667. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  157668. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  157669. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  157670. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  157671. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  157672. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  157673. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  157674. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  157675. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  157676. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  157677. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  157678. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  157679. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  157680. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  157681. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  157682. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  157683. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  157684. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  157685. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  157686. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  157687. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  157688. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  157689. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  157690. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  157691. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  157692. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  157693. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  157694. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  157695. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  157696. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  157697. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  157698. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  157699. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  157700. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  157701. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  157702. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  157703. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  157704. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  157705. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  157706. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  157707. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  157708. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  157709. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  157710. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  157711. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  157712. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  157713. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  157714. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  157715. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  157716. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  157717. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  157718. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  157719. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  157720. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  157721. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  157722. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  157723. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  157724. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  157725. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  157726. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  157727. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  157728. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  157729. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  157730. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  157731. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  157732. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  157733. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  157734. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  157735. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  157736. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  157737. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  157738. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  157739. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  157740. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  157741. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  157742. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  157743. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  157744. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  157745. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  157746. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  157747. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  157748. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  157749. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  157750. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  157751. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  157752. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  157753. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  157754. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  157755. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  157756. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  157757. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  157758. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  157759. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  157760. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  157761. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  157762. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  157763. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  157764. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  157765. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  157766. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  157767. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  157768. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  157769. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  157770. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  157771. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  157772. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  157773. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  157774. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  157775. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  157776. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  157777. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  157778. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  157779. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  157780. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  157781. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  157782. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  157783. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  157784. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  157785. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  157786. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  157787. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  157788. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  157789. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  157790. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  157791. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  157792. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  157793. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  157794. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  157795. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  157796. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  157797. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  157798. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  157799. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  157800. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  157801. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  157802. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  157803. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  157804. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  157805. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  157806. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  157807. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  157808. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  157809. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  157810. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  157811. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  157812. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  157813. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  157814. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  157815. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  157816. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  157817. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  157818. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  157819. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  157820. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  157821. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  157822. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  157823. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  157824. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  157825. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  157826. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  157827. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  157828. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  157829. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  157830. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  157831. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  157832. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  157833. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  157834. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  157835. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  157836. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  157837. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  157838. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  157839. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  157840. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  157841. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  157842. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  157843. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  157844. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  157845. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  157846. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  157847. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  157848. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  157849. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  157850. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  157851. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  157852. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  157853. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  157854. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  157855. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  157856. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  157857. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  157858. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  157859. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  157860. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  157861. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  157862. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  157863. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  157864. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  157865. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  157866. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  157867. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  157868. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  157869. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  157870. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  157871. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  157872. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  157873. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  157874. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  157875. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  157876. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  157877. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  157878. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  157879. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  157880. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  157881. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  157882. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  157883. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  157884. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  157885. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  157886. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  157887. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  157888. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  157889. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  157890. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  157891. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  157892. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  157893. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  157894. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  157895. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  157896. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  157897. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  157898. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  157899. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  157900. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  157901. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  157902. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  157903. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  157904. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  157905. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  157906. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  157907. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  157908. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  157909. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  157910. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  157911. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  157912. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  157913. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  157914. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  157915. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  157916. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  157917. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  157918. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  157919. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  157920. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  157921. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  157922. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  157923. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  157924. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  157925. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  157926. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  157927. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  157928. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  157929. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  157930. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  157931. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  157932. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  157933. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  157934. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  157935. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  157936. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  157937. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  157938. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  157939. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  157940. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  157941. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  157942. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  157943. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  157944. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  157945. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  157946. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  157947. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  157948. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  157949. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  157950. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  157951. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  157952. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  157953. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  157954. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  157955. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  157956. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  157957. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  157958. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  157959. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  157960. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  157961. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  157962. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  157963. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  157964. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  157965. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  157966. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  157967. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  157968. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  157969. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  157970. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  157971. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  157972. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  157973. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  157974. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  157975. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  157976. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157977. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157978. };
  157979. static float *vwin[8] = {
  157980. vwin64,
  157981. vwin128,
  157982. vwin256,
  157983. vwin512,
  157984. vwin1024,
  157985. vwin2048,
  157986. vwin4096,
  157987. vwin8192,
  157988. };
  157989. float *_vorbis_window_get(int n){
  157990. return vwin[n];
  157991. }
  157992. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  157993. int lW,int W,int nW){
  157994. lW=(W?lW:0);
  157995. nW=(W?nW:0);
  157996. {
  157997. float *windowLW=vwin[winno[lW]];
  157998. float *windowNW=vwin[winno[nW]];
  157999. long n=blocksizes[W];
  158000. long ln=blocksizes[lW];
  158001. long rn=blocksizes[nW];
  158002. long leftbegin=n/4-ln/4;
  158003. long leftend=leftbegin+ln/2;
  158004. long rightbegin=n/2+n/4-rn/4;
  158005. long rightend=rightbegin+rn/2;
  158006. int i,p;
  158007. for(i=0;i<leftbegin;i++)
  158008. d[i]=0.f;
  158009. for(p=0;i<leftend;i++,p++)
  158010. d[i]*=windowLW[p];
  158011. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158012. d[i]*=windowNW[p];
  158013. for(;i<n;i++)
  158014. d[i]=0.f;
  158015. }
  158016. }
  158017. #endif
  158018. /*** End of inlined file: window.c ***/
  158019. #else
  158020. #include <vorbis/vorbisenc.h>
  158021. #include <vorbis/codec.h>
  158022. #include <vorbis/vorbisfile.h>
  158023. #endif
  158024. }
  158025. #undef max
  158026. #undef min
  158027. BEGIN_JUCE_NAMESPACE
  158028. static const char* const oggFormatName = "Ogg-Vorbis file";
  158029. static const char* const oggExtensions[] = { ".ogg", 0 };
  158030. class OggReader : public AudioFormatReader
  158031. {
  158032. OggVorbisNamespace::OggVorbis_File ovFile;
  158033. OggVorbisNamespace::ov_callbacks callbacks;
  158034. AudioSampleBuffer reservoir;
  158035. int reservoirStart, samplesInReservoir;
  158036. public:
  158037. OggReader (InputStream* const inp)
  158038. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158039. reservoir (2, 4096),
  158040. reservoirStart (0),
  158041. samplesInReservoir (0)
  158042. {
  158043. using namespace OggVorbisNamespace;
  158044. sampleRate = 0;
  158045. usesFloatingPointData = true;
  158046. callbacks.read_func = &oggReadCallback;
  158047. callbacks.seek_func = &oggSeekCallback;
  158048. callbacks.close_func = &oggCloseCallback;
  158049. callbacks.tell_func = &oggTellCallback;
  158050. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158051. if (err == 0)
  158052. {
  158053. vorbis_info* info = ov_info (&ovFile, -1);
  158054. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158055. numChannels = info->channels;
  158056. bitsPerSample = 16;
  158057. sampleRate = info->rate;
  158058. reservoir.setSize (numChannels,
  158059. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158060. }
  158061. }
  158062. ~OggReader()
  158063. {
  158064. OggVorbisNamespace::ov_clear (&ovFile);
  158065. }
  158066. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158067. int64 startSampleInFile, int numSamples)
  158068. {
  158069. while (numSamples > 0)
  158070. {
  158071. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158072. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158073. {
  158074. // got a few samples overlapping, so use them before seeking..
  158075. const int numToUse = jmin (numSamples, numAvailable);
  158076. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158077. if (destSamples[i] != 0)
  158078. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158079. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158080. sizeof (float) * numToUse);
  158081. startSampleInFile += numToUse;
  158082. numSamples -= numToUse;
  158083. startOffsetInDestBuffer += numToUse;
  158084. if (numSamples == 0)
  158085. break;
  158086. }
  158087. if (startSampleInFile < reservoirStart
  158088. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158089. {
  158090. // buffer miss, so refill the reservoir
  158091. int bitStream = 0;
  158092. reservoirStart = jmax (0, (int) startSampleInFile);
  158093. samplesInReservoir = reservoir.getNumSamples();
  158094. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158095. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158096. int offset = 0;
  158097. int numToRead = samplesInReservoir;
  158098. while (numToRead > 0)
  158099. {
  158100. float** dataIn = 0;
  158101. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158102. if (samps <= 0)
  158103. break;
  158104. jassert (samps <= numToRead);
  158105. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158106. {
  158107. memcpy (reservoir.getSampleData (i, offset),
  158108. dataIn[i],
  158109. sizeof (float) * samps);
  158110. }
  158111. numToRead -= samps;
  158112. offset += samps;
  158113. }
  158114. if (numToRead > 0)
  158115. reservoir.clear (offset, numToRead);
  158116. }
  158117. }
  158118. if (numSamples > 0)
  158119. {
  158120. for (int i = numDestChannels; --i >= 0;)
  158121. if (destSamples[i] != 0)
  158122. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158123. sizeof (int) * numSamples);
  158124. }
  158125. return true;
  158126. }
  158127. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  158128. {
  158129. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  158130. }
  158131. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  158132. {
  158133. InputStream* const in = static_cast <InputStream*> (datasource);
  158134. if (whence == SEEK_CUR)
  158135. offset += in->getPosition();
  158136. else if (whence == SEEK_END)
  158137. offset += in->getTotalLength();
  158138. in->setPosition (offset);
  158139. return 0;
  158140. }
  158141. static int oggCloseCallback (void*)
  158142. {
  158143. return 0;
  158144. }
  158145. static long oggTellCallback (void* datasource)
  158146. {
  158147. return (long) static_cast <InputStream*> (datasource)->getPosition();
  158148. }
  158149. juce_UseDebuggingNewOperator
  158150. };
  158151. class OggWriter : public AudioFormatWriter
  158152. {
  158153. OggVorbisNamespace::ogg_stream_state os;
  158154. OggVorbisNamespace::ogg_page og;
  158155. OggVorbisNamespace::ogg_packet op;
  158156. OggVorbisNamespace::vorbis_info vi;
  158157. OggVorbisNamespace::vorbis_comment vc;
  158158. OggVorbisNamespace::vorbis_dsp_state vd;
  158159. OggVorbisNamespace::vorbis_block vb;
  158160. public:
  158161. bool ok;
  158162. OggWriter (OutputStream* const out,
  158163. const double sampleRate,
  158164. const int numChannels,
  158165. const int bitsPerSample,
  158166. const int qualityIndex)
  158167. : AudioFormatWriter (out, TRANS (oggFormatName),
  158168. sampleRate,
  158169. numChannels,
  158170. bitsPerSample)
  158171. {
  158172. using namespace OggVorbisNamespace;
  158173. ok = false;
  158174. vorbis_info_init (&vi);
  158175. if (vorbis_encode_init_vbr (&vi,
  158176. numChannels,
  158177. (int) sampleRate,
  158178. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  158179. {
  158180. vorbis_comment_init (&vc);
  158181. if (JUCEApplication::getInstance() != 0)
  158182. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  158183. vorbis_analysis_init (&vd, &vi);
  158184. vorbis_block_init (&vd, &vb);
  158185. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  158186. ogg_packet header;
  158187. ogg_packet header_comm;
  158188. ogg_packet header_code;
  158189. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  158190. ogg_stream_packetin (&os, &header);
  158191. ogg_stream_packetin (&os, &header_comm);
  158192. ogg_stream_packetin (&os, &header_code);
  158193. for (;;)
  158194. {
  158195. if (ogg_stream_flush (&os, &og) == 0)
  158196. break;
  158197. output->write (og.header, og.header_len);
  158198. output->write (og.body, og.body_len);
  158199. }
  158200. ok = true;
  158201. }
  158202. }
  158203. ~OggWriter()
  158204. {
  158205. using namespace OggVorbisNamespace;
  158206. if (ok)
  158207. {
  158208. // write a zero-length packet to show ogg that we're finished..
  158209. write (0, 0);
  158210. ogg_stream_clear (&os);
  158211. vorbis_block_clear (&vb);
  158212. vorbis_dsp_clear (&vd);
  158213. vorbis_comment_clear (&vc);
  158214. vorbis_info_clear (&vi);
  158215. output->flush();
  158216. }
  158217. else
  158218. {
  158219. vorbis_info_clear (&vi);
  158220. output = 0; // to stop the base class deleting this, as it needs to be returned
  158221. // to the caller of createWriter()
  158222. }
  158223. }
  158224. bool write (const int** samplesToWrite, int numSamples)
  158225. {
  158226. using namespace OggVorbisNamespace;
  158227. if (! ok)
  158228. return false;
  158229. if (numSamples > 0)
  158230. {
  158231. const double gain = 1.0 / 0x80000000u;
  158232. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  158233. for (int i = numChannels; --i >= 0;)
  158234. {
  158235. float* const dst = vorbisBuffer[i];
  158236. const int* const src = samplesToWrite [i];
  158237. if (src != 0 && dst != 0)
  158238. {
  158239. for (int j = 0; j < numSamples; ++j)
  158240. dst[j] = (float) (src[j] * gain);
  158241. }
  158242. }
  158243. }
  158244. vorbis_analysis_wrote (&vd, numSamples);
  158245. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  158246. {
  158247. vorbis_analysis (&vb, 0);
  158248. vorbis_bitrate_addblock (&vb);
  158249. while (vorbis_bitrate_flushpacket (&vd, &op))
  158250. {
  158251. ogg_stream_packetin (&os, &op);
  158252. for (;;)
  158253. {
  158254. if (ogg_stream_pageout (&os, &og) == 0)
  158255. break;
  158256. output->write (og.header, og.header_len);
  158257. output->write (og.body, og.body_len);
  158258. if (ogg_page_eos (&og))
  158259. break;
  158260. }
  158261. }
  158262. }
  158263. return true;
  158264. }
  158265. juce_UseDebuggingNewOperator
  158266. };
  158267. OggVorbisAudioFormat::OggVorbisAudioFormat()
  158268. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  158269. {
  158270. }
  158271. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  158272. {
  158273. }
  158274. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  158275. {
  158276. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  158277. return Array <int> (rates);
  158278. }
  158279. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  158280. {
  158281. Array <int> depths;
  158282. depths.add (32);
  158283. return depths;
  158284. }
  158285. bool OggVorbisAudioFormat::canDoStereo()
  158286. {
  158287. return true;
  158288. }
  158289. bool OggVorbisAudioFormat::canDoMono()
  158290. {
  158291. return true;
  158292. }
  158293. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  158294. const bool deleteStreamIfOpeningFails)
  158295. {
  158296. ScopedPointer <OggReader> r (new OggReader (in));
  158297. if (r->sampleRate != 0)
  158298. return r.release();
  158299. if (! deleteStreamIfOpeningFails)
  158300. r->input = 0;
  158301. return 0;
  158302. }
  158303. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  158304. double sampleRate,
  158305. unsigned int numChannels,
  158306. int bitsPerSample,
  158307. const StringPairArray& /*metadataValues*/,
  158308. int qualityOptionIndex)
  158309. {
  158310. ScopedPointer <OggWriter> w (new OggWriter (out,
  158311. sampleRate,
  158312. numChannels,
  158313. bitsPerSample,
  158314. qualityOptionIndex));
  158315. return w->ok ? w.release() : 0;
  158316. }
  158317. bool OggVorbisAudioFormat::isCompressed()
  158318. {
  158319. return true;
  158320. }
  158321. const StringArray OggVorbisAudioFormat::getQualityOptions()
  158322. {
  158323. StringArray s;
  158324. s.add ("Low Quality");
  158325. s.add ("Medium Quality");
  158326. s.add ("High Quality");
  158327. return s;
  158328. }
  158329. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  158330. {
  158331. FileInputStream* const in = source.createInputStream();
  158332. if (in != 0)
  158333. {
  158334. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  158335. if (r != 0)
  158336. {
  158337. const int64 numSamps = r->lengthInSamples;
  158338. r = 0;
  158339. const int64 fileNumSamps = source.getSize() / 4;
  158340. const double ratio = numSamps / (double) fileNumSamps;
  158341. if (ratio > 12.0)
  158342. return 0;
  158343. else if (ratio > 6.0)
  158344. return 1;
  158345. else
  158346. return 2;
  158347. }
  158348. }
  158349. return 1;
  158350. }
  158351. END_JUCE_NAMESPACE
  158352. #endif
  158353. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  158354. #endif
  158355. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  158356. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  158357. #if JUCE_MSVC
  158358. #pragma warning (push)
  158359. #endif
  158360. namespace jpeglibNamespace
  158361. {
  158362. #if JUCE_INCLUDE_JPEGLIB_CODE
  158363. #if JUCE_MINGW
  158364. typedef unsigned char boolean;
  158365. #endif
  158366. extern "C"
  158367. {
  158368. #define JPEG_INTERNALS
  158369. #undef FAR
  158370. /*** Start of inlined file: jpeglib.h ***/
  158371. #ifndef JPEGLIB_H
  158372. #define JPEGLIB_H
  158373. /*
  158374. * First we include the configuration files that record how this
  158375. * installation of the JPEG library is set up. jconfig.h can be
  158376. * generated automatically for many systems. jmorecfg.h contains
  158377. * manual configuration options that most people need not worry about.
  158378. */
  158379. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  158380. /*** Start of inlined file: jconfig.h ***/
  158381. /* see jconfig.doc for explanations */
  158382. // disable all the warnings under MSVC
  158383. #ifdef _MSC_VER
  158384. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  158385. #endif
  158386. #ifdef __BORLANDC__
  158387. #pragma warn -8057
  158388. #pragma warn -8019
  158389. #pragma warn -8004
  158390. #pragma warn -8008
  158391. #endif
  158392. #define HAVE_PROTOTYPES
  158393. #define HAVE_UNSIGNED_CHAR
  158394. #define HAVE_UNSIGNED_SHORT
  158395. /* #define void char */
  158396. /* #define const */
  158397. #undef CHAR_IS_UNSIGNED
  158398. #define HAVE_STDDEF_H
  158399. #define HAVE_STDLIB_H
  158400. #undef NEED_BSD_STRINGS
  158401. #undef NEED_SYS_TYPES_H
  158402. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  158403. #undef NEED_SHORT_EXTERNAL_NAMES
  158404. #undef INCOMPLETE_TYPES_BROKEN
  158405. /* Define "boolean" as unsigned char, not int, per Windows custom */
  158406. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  158407. typedef unsigned char boolean;
  158408. #endif
  158409. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  158410. #ifdef JPEG_INTERNALS
  158411. #undef RIGHT_SHIFT_IS_UNSIGNED
  158412. #endif /* JPEG_INTERNALS */
  158413. #ifdef JPEG_CJPEG_DJPEG
  158414. #define BMP_SUPPORTED /* BMP image file format */
  158415. #define GIF_SUPPORTED /* GIF image file format */
  158416. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  158417. #undef RLE_SUPPORTED /* Utah RLE image file format */
  158418. #define TARGA_SUPPORTED /* Targa image file format */
  158419. #define TWO_FILE_COMMANDLINE /* optional */
  158420. #define USE_SETMODE /* Microsoft has setmode() */
  158421. #undef NEED_SIGNAL_CATCHER
  158422. #undef DONT_USE_B_MODE
  158423. #undef PROGRESS_REPORT /* optional */
  158424. #endif /* JPEG_CJPEG_DJPEG */
  158425. /*** End of inlined file: jconfig.h ***/
  158426. /* widely used configuration options */
  158427. #endif
  158428. /*** Start of inlined file: jmorecfg.h ***/
  158429. /*
  158430. * Define BITS_IN_JSAMPLE as either
  158431. * 8 for 8-bit sample values (the usual setting)
  158432. * 12 for 12-bit sample values
  158433. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  158434. * JPEG standard, and the IJG code does not support anything else!
  158435. * We do not support run-time selection of data precision, sorry.
  158436. */
  158437. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  158438. /*
  158439. * Maximum number of components (color channels) allowed in JPEG image.
  158440. * To meet the letter of the JPEG spec, set this to 255. However, darn
  158441. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  158442. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  158443. * really short on memory. (Each allowed component costs a hundred or so
  158444. * bytes of storage, whether actually used in an image or not.)
  158445. */
  158446. #define MAX_COMPONENTS 10 /* maximum number of image components */
  158447. /*
  158448. * Basic data types.
  158449. * You may need to change these if you have a machine with unusual data
  158450. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  158451. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  158452. * but it had better be at least 16.
  158453. */
  158454. /* Representation of a single sample (pixel element value).
  158455. * We frequently allocate large arrays of these, so it's important to keep
  158456. * them small. But if you have memory to burn and access to char or short
  158457. * arrays is very slow on your hardware, you might want to change these.
  158458. */
  158459. #if BITS_IN_JSAMPLE == 8
  158460. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  158461. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  158462. */
  158463. #ifdef HAVE_UNSIGNED_CHAR
  158464. typedef unsigned char JSAMPLE;
  158465. #define GETJSAMPLE(value) ((int) (value))
  158466. #else /* not HAVE_UNSIGNED_CHAR */
  158467. typedef char JSAMPLE;
  158468. #ifdef CHAR_IS_UNSIGNED
  158469. #define GETJSAMPLE(value) ((int) (value))
  158470. #else
  158471. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  158472. #endif /* CHAR_IS_UNSIGNED */
  158473. #endif /* HAVE_UNSIGNED_CHAR */
  158474. #define MAXJSAMPLE 255
  158475. #define CENTERJSAMPLE 128
  158476. #endif /* BITS_IN_JSAMPLE == 8 */
  158477. #if BITS_IN_JSAMPLE == 12
  158478. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  158479. * On nearly all machines "short" will do nicely.
  158480. */
  158481. typedef short JSAMPLE;
  158482. #define GETJSAMPLE(value) ((int) (value))
  158483. #define MAXJSAMPLE 4095
  158484. #define CENTERJSAMPLE 2048
  158485. #endif /* BITS_IN_JSAMPLE == 12 */
  158486. /* Representation of a DCT frequency coefficient.
  158487. * This should be a signed value of at least 16 bits; "short" is usually OK.
  158488. * Again, we allocate large arrays of these, but you can change to int
  158489. * if you have memory to burn and "short" is really slow.
  158490. */
  158491. typedef short JCOEF;
  158492. /* Compressed datastreams are represented as arrays of JOCTET.
  158493. * These must be EXACTLY 8 bits wide, at least once they are written to
  158494. * external storage. Note that when using the stdio data source/destination
  158495. * managers, this is also the data type passed to fread/fwrite.
  158496. */
  158497. #ifdef HAVE_UNSIGNED_CHAR
  158498. typedef unsigned char JOCTET;
  158499. #define GETJOCTET(value) (value)
  158500. #else /* not HAVE_UNSIGNED_CHAR */
  158501. typedef char JOCTET;
  158502. #ifdef CHAR_IS_UNSIGNED
  158503. #define GETJOCTET(value) (value)
  158504. #else
  158505. #define GETJOCTET(value) ((value) & 0xFF)
  158506. #endif /* CHAR_IS_UNSIGNED */
  158507. #endif /* HAVE_UNSIGNED_CHAR */
  158508. /* These typedefs are used for various table entries and so forth.
  158509. * They must be at least as wide as specified; but making them too big
  158510. * won't cost a huge amount of memory, so we don't provide special
  158511. * extraction code like we did for JSAMPLE. (In other words, these
  158512. * typedefs live at a different point on the speed/space tradeoff curve.)
  158513. */
  158514. /* UINT8 must hold at least the values 0..255. */
  158515. #ifdef HAVE_UNSIGNED_CHAR
  158516. typedef unsigned char UINT8;
  158517. #else /* not HAVE_UNSIGNED_CHAR */
  158518. #ifdef CHAR_IS_UNSIGNED
  158519. typedef char UINT8;
  158520. #else /* not CHAR_IS_UNSIGNED */
  158521. typedef short UINT8;
  158522. #endif /* CHAR_IS_UNSIGNED */
  158523. #endif /* HAVE_UNSIGNED_CHAR */
  158524. /* UINT16 must hold at least the values 0..65535. */
  158525. #ifdef HAVE_UNSIGNED_SHORT
  158526. typedef unsigned short UINT16;
  158527. #else /* not HAVE_UNSIGNED_SHORT */
  158528. typedef unsigned int UINT16;
  158529. #endif /* HAVE_UNSIGNED_SHORT */
  158530. /* INT16 must hold at least the values -32768..32767. */
  158531. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  158532. typedef short INT16;
  158533. #endif
  158534. /* INT32 must hold at least signed 32-bit values. */
  158535. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  158536. typedef long INT32;
  158537. #endif
  158538. /* Datatype used for image dimensions. The JPEG standard only supports
  158539. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  158540. * "unsigned int" is sufficient on all machines. However, if you need to
  158541. * handle larger images and you don't mind deviating from the spec, you
  158542. * can change this datatype.
  158543. */
  158544. typedef unsigned int JDIMENSION;
  158545. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  158546. /* These macros are used in all function definitions and extern declarations.
  158547. * You could modify them if you need to change function linkage conventions;
  158548. * in particular, you'll need to do that to make the library a Windows DLL.
  158549. * Another application is to make all functions global for use with debuggers
  158550. * or code profilers that require it.
  158551. */
  158552. /* a function called through method pointers: */
  158553. #define METHODDEF(type) static type
  158554. /* a function used only in its module: */
  158555. #define LOCAL(type) static type
  158556. /* a function referenced thru EXTERNs: */
  158557. #define GLOBAL(type) type
  158558. /* a reference to a GLOBAL function: */
  158559. #define EXTERN(type) extern type
  158560. /* This macro is used to declare a "method", that is, a function pointer.
  158561. * We want to supply prototype parameters if the compiler can cope.
  158562. * Note that the arglist parameter must be parenthesized!
  158563. * Again, you can customize this if you need special linkage keywords.
  158564. */
  158565. #ifdef HAVE_PROTOTYPES
  158566. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  158567. #else
  158568. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  158569. #endif
  158570. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  158571. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  158572. * by just saying "FAR *" where such a pointer is needed. In a few places
  158573. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  158574. */
  158575. #ifdef NEED_FAR_POINTERS
  158576. #define FAR far
  158577. #else
  158578. #define FAR
  158579. #endif
  158580. /*
  158581. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  158582. * in standard header files. Or you may have conflicts with application-
  158583. * specific header files that you want to include together with these files.
  158584. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  158585. */
  158586. #ifndef HAVE_BOOLEAN
  158587. typedef int boolean;
  158588. #endif
  158589. #ifndef FALSE /* in case these macros already exist */
  158590. #define FALSE 0 /* values of boolean */
  158591. #endif
  158592. #ifndef TRUE
  158593. #define TRUE 1
  158594. #endif
  158595. /*
  158596. * The remaining options affect code selection within the JPEG library,
  158597. * but they don't need to be visible to most applications using the library.
  158598. * To minimize application namespace pollution, the symbols won't be
  158599. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  158600. */
  158601. #ifdef JPEG_INTERNALS
  158602. #define JPEG_INTERNAL_OPTIONS
  158603. #endif
  158604. #ifdef JPEG_INTERNAL_OPTIONS
  158605. /*
  158606. * These defines indicate whether to include various optional functions.
  158607. * Undefining some of these symbols will produce a smaller but less capable
  158608. * library. Note that you can leave certain source files out of the
  158609. * compilation/linking process if you've #undef'd the corresponding symbols.
  158610. * (You may HAVE to do that if your compiler doesn't like null source files.)
  158611. */
  158612. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  158613. /* Capability options common to encoder and decoder: */
  158614. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  158615. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  158616. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  158617. /* Encoder capability options: */
  158618. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  158619. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  158620. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  158621. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  158622. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  158623. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  158624. * precision, so jchuff.c normally uses entropy optimization to compute
  158625. * usable tables for higher precision. If you don't want to do optimization,
  158626. * you'll have to supply different default Huffman tables.
  158627. * The exact same statements apply for progressive JPEG: the default tables
  158628. * don't work for progressive mode. (This may get fixed, however.)
  158629. */
  158630. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  158631. /* Decoder capability options: */
  158632. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  158633. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  158634. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  158635. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  158636. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  158637. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  158638. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  158639. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  158640. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  158641. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  158642. /* more capability options later, no doubt */
  158643. /*
  158644. * Ordering of RGB data in scanlines passed to or from the application.
  158645. * If your application wants to deal with data in the order B,G,R, just
  158646. * change these macros. You can also deal with formats such as R,G,B,X
  158647. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  158648. * the offsets will also change the order in which colormap data is organized.
  158649. * RESTRICTIONS:
  158650. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  158651. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  158652. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  158653. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  158654. * is not 3 (they don't understand about dummy color components!). So you
  158655. * can't use color quantization if you change that value.
  158656. */
  158657. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  158658. #define RGB_GREEN 1 /* Offset of Green */
  158659. #define RGB_BLUE 2 /* Offset of Blue */
  158660. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  158661. /* Definitions for speed-related optimizations. */
  158662. /* If your compiler supports inline functions, define INLINE
  158663. * as the inline keyword; otherwise define it as empty.
  158664. */
  158665. #ifndef INLINE
  158666. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  158667. #define INLINE __inline__
  158668. #endif
  158669. #ifndef INLINE
  158670. #define INLINE /* default is to define it as empty */
  158671. #endif
  158672. #endif
  158673. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  158674. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  158675. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  158676. */
  158677. #ifndef MULTIPLIER
  158678. #define MULTIPLIER int /* type for fastest integer multiply */
  158679. #endif
  158680. /* FAST_FLOAT should be either float or double, whichever is done faster
  158681. * by your compiler. (Note that this type is only used in the floating point
  158682. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  158683. * Typically, float is faster in ANSI C compilers, while double is faster in
  158684. * pre-ANSI compilers (because they insist on converting to double anyway).
  158685. * The code below therefore chooses float if we have ANSI-style prototypes.
  158686. */
  158687. #ifndef FAST_FLOAT
  158688. #ifdef HAVE_PROTOTYPES
  158689. #define FAST_FLOAT float
  158690. #else
  158691. #define FAST_FLOAT double
  158692. #endif
  158693. #endif
  158694. #endif /* JPEG_INTERNAL_OPTIONS */
  158695. /*** End of inlined file: jmorecfg.h ***/
  158696. /* seldom changed options */
  158697. /* Version ID for the JPEG library.
  158698. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  158699. */
  158700. #define JPEG_LIB_VERSION 62 /* Version 6b */
  158701. /* Various constants determining the sizes of things.
  158702. * All of these are specified by the JPEG standard, so don't change them
  158703. * if you want to be compatible.
  158704. */
  158705. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  158706. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  158707. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  158708. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  158709. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  158710. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  158711. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  158712. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  158713. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  158714. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  158715. * to handle it. We even let you do this from the jconfig.h file. However,
  158716. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  158717. * sometimes emits noncompliant files doesn't mean you should too.
  158718. */
  158719. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  158720. #ifndef D_MAX_BLOCKS_IN_MCU
  158721. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  158722. #endif
  158723. /* Data structures for images (arrays of samples and of DCT coefficients).
  158724. * On 80x86 machines, the image arrays are too big for near pointers,
  158725. * but the pointer arrays can fit in near memory.
  158726. */
  158727. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  158728. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  158729. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  158730. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  158731. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  158732. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  158733. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  158734. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  158735. /* Types for JPEG compression parameters and working tables. */
  158736. /* DCT coefficient quantization tables. */
  158737. typedef struct {
  158738. /* This array gives the coefficient quantizers in natural array order
  158739. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  158740. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  158741. */
  158742. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  158743. /* This field is used only during compression. It's initialized FALSE when
  158744. * the table is created, and set TRUE when it's been output to the file.
  158745. * You could suppress output of a table by setting this to TRUE.
  158746. * (See jpeg_suppress_tables for an example.)
  158747. */
  158748. boolean sent_table; /* TRUE when table has been output */
  158749. } JQUANT_TBL;
  158750. /* Huffman coding tables. */
  158751. typedef struct {
  158752. /* These two fields directly represent the contents of a JPEG DHT marker */
  158753. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  158754. /* length k bits; bits[0] is unused */
  158755. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  158756. /* This field is used only during compression. It's initialized FALSE when
  158757. * the table is created, and set TRUE when it's been output to the file.
  158758. * You could suppress output of a table by setting this to TRUE.
  158759. * (See jpeg_suppress_tables for an example.)
  158760. */
  158761. boolean sent_table; /* TRUE when table has been output */
  158762. } JHUFF_TBL;
  158763. /* Basic info about one component (color channel). */
  158764. typedef struct {
  158765. /* These values are fixed over the whole image. */
  158766. /* For compression, they must be supplied by parameter setup; */
  158767. /* for decompression, they are read from the SOF marker. */
  158768. int component_id; /* identifier for this component (0..255) */
  158769. int component_index; /* its index in SOF or cinfo->comp_info[] */
  158770. int h_samp_factor; /* horizontal sampling factor (1..4) */
  158771. int v_samp_factor; /* vertical sampling factor (1..4) */
  158772. int quant_tbl_no; /* quantization table selector (0..3) */
  158773. /* These values may vary between scans. */
  158774. /* For compression, they must be supplied by parameter setup; */
  158775. /* for decompression, they are read from the SOS marker. */
  158776. /* The decompressor output side may not use these variables. */
  158777. int dc_tbl_no; /* DC entropy table selector (0..3) */
  158778. int ac_tbl_no; /* AC entropy table selector (0..3) */
  158779. /* Remaining fields should be treated as private by applications. */
  158780. /* These values are computed during compression or decompression startup: */
  158781. /* Component's size in DCT blocks.
  158782. * Any dummy blocks added to complete an MCU are not counted; therefore
  158783. * these values do not depend on whether a scan is interleaved or not.
  158784. */
  158785. JDIMENSION width_in_blocks;
  158786. JDIMENSION height_in_blocks;
  158787. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  158788. * For decompression this is the size of the output from one DCT block,
  158789. * reflecting any scaling we choose to apply during the IDCT step.
  158790. * Values of 1,2,4,8 are likely to be supported. Note that different
  158791. * components may receive different IDCT scalings.
  158792. */
  158793. int DCT_scaled_size;
  158794. /* The downsampled dimensions are the component's actual, unpadded number
  158795. * of samples at the main buffer (preprocessing/compression interface), thus
  158796. * downsampled_width = ceil(image_width * Hi/Hmax)
  158797. * and similarly for height. For decompression, IDCT scaling is included, so
  158798. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  158799. */
  158800. JDIMENSION downsampled_width; /* actual width in samples */
  158801. JDIMENSION downsampled_height; /* actual height in samples */
  158802. /* This flag is used only for decompression. In cases where some of the
  158803. * components will be ignored (eg grayscale output from YCbCr image),
  158804. * we can skip most computations for the unused components.
  158805. */
  158806. boolean component_needed; /* do we need the value of this component? */
  158807. /* These values are computed before starting a scan of the component. */
  158808. /* The decompressor output side may not use these variables. */
  158809. int MCU_width; /* number of blocks per MCU, horizontally */
  158810. int MCU_height; /* number of blocks per MCU, vertically */
  158811. int MCU_blocks; /* MCU_width * MCU_height */
  158812. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  158813. int last_col_width; /* # of non-dummy blocks across in last MCU */
  158814. int last_row_height; /* # of non-dummy blocks down in last MCU */
  158815. /* Saved quantization table for component; NULL if none yet saved.
  158816. * See jdinput.c comments about the need for this information.
  158817. * This field is currently used only for decompression.
  158818. */
  158819. JQUANT_TBL * quant_table;
  158820. /* Private per-component storage for DCT or IDCT subsystem. */
  158821. void * dct_table;
  158822. } jpeg_component_info;
  158823. /* The script for encoding a multiple-scan file is an array of these: */
  158824. typedef struct {
  158825. int comps_in_scan; /* number of components encoded in this scan */
  158826. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  158827. int Ss, Se; /* progressive JPEG spectral selection parms */
  158828. int Ah, Al; /* progressive JPEG successive approx. parms */
  158829. } jpeg_scan_info;
  158830. /* The decompressor can save APPn and COM markers in a list of these: */
  158831. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  158832. struct jpeg_marker_struct {
  158833. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  158834. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  158835. unsigned int original_length; /* # bytes of data in the file */
  158836. unsigned int data_length; /* # bytes of data saved at data[] */
  158837. JOCTET FAR * data; /* the data contained in the marker */
  158838. /* the marker length word is not counted in data_length or original_length */
  158839. };
  158840. /* Known color spaces. */
  158841. typedef enum {
  158842. JCS_UNKNOWN, /* error/unspecified */
  158843. JCS_GRAYSCALE, /* monochrome */
  158844. JCS_RGB, /* red/green/blue */
  158845. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  158846. JCS_CMYK, /* C/M/Y/K */
  158847. JCS_YCCK /* Y/Cb/Cr/K */
  158848. } J_COLOR_SPACE;
  158849. /* DCT/IDCT algorithm options. */
  158850. typedef enum {
  158851. JDCT_ISLOW, /* slow but accurate integer algorithm */
  158852. JDCT_IFAST, /* faster, less accurate integer method */
  158853. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  158854. } J_DCT_METHOD;
  158855. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  158856. #define JDCT_DEFAULT JDCT_ISLOW
  158857. #endif
  158858. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  158859. #define JDCT_FASTEST JDCT_IFAST
  158860. #endif
  158861. /* Dithering options for decompression. */
  158862. typedef enum {
  158863. JDITHER_NONE, /* no dithering */
  158864. JDITHER_ORDERED, /* simple ordered dither */
  158865. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  158866. } J_DITHER_MODE;
  158867. /* Common fields between JPEG compression and decompression master structs. */
  158868. #define jpeg_common_fields \
  158869. struct jpeg_error_mgr * err; /* Error handler module */\
  158870. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  158871. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  158872. void * client_data; /* Available for use by application */\
  158873. boolean is_decompressor; /* So common code can tell which is which */\
  158874. int global_state /* For checking call sequence validity */
  158875. /* Routines that are to be used by both halves of the library are declared
  158876. * to receive a pointer to this structure. There are no actual instances of
  158877. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  158878. */
  158879. struct jpeg_common_struct {
  158880. jpeg_common_fields; /* Fields common to both master struct types */
  158881. /* Additional fields follow in an actual jpeg_compress_struct or
  158882. * jpeg_decompress_struct. All three structs must agree on these
  158883. * initial fields! (This would be a lot cleaner in C++.)
  158884. */
  158885. };
  158886. typedef struct jpeg_common_struct * j_common_ptr;
  158887. typedef struct jpeg_compress_struct * j_compress_ptr;
  158888. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  158889. /* Master record for a compression instance */
  158890. struct jpeg_compress_struct {
  158891. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  158892. /* Destination for compressed data */
  158893. struct jpeg_destination_mgr * dest;
  158894. /* Description of source image --- these fields must be filled in by
  158895. * outer application before starting compression. in_color_space must
  158896. * be correct before you can even call jpeg_set_defaults().
  158897. */
  158898. JDIMENSION image_width; /* input image width */
  158899. JDIMENSION image_height; /* input image height */
  158900. int input_components; /* # of color components in input image */
  158901. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  158902. double input_gamma; /* image gamma of input image */
  158903. /* Compression parameters --- these fields must be set before calling
  158904. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  158905. * initialize everything to reasonable defaults, then changing anything
  158906. * the application specifically wants to change. That way you won't get
  158907. * burnt when new parameters are added. Also note that there are several
  158908. * helper routines to simplify changing parameters.
  158909. */
  158910. int data_precision; /* bits of precision in image data */
  158911. int num_components; /* # of color components in JPEG image */
  158912. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  158913. jpeg_component_info * comp_info;
  158914. /* comp_info[i] describes component that appears i'th in SOF */
  158915. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  158916. /* ptrs to coefficient quantization tables, or NULL if not defined */
  158917. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  158918. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  158919. /* ptrs to Huffman coding tables, or NULL if not defined */
  158920. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  158921. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  158922. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  158923. int num_scans; /* # of entries in scan_info array */
  158924. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  158925. /* The default value of scan_info is NULL, which causes a single-scan
  158926. * sequential JPEG file to be emitted. To create a multi-scan file,
  158927. * set num_scans and scan_info to point to an array of scan definitions.
  158928. */
  158929. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  158930. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  158931. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  158932. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  158933. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  158934. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  158935. /* The restart interval can be specified in absolute MCUs by setting
  158936. * restart_interval, or in MCU rows by setting restart_in_rows
  158937. * (in which case the correct restart_interval will be figured
  158938. * for each scan).
  158939. */
  158940. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  158941. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  158942. /* Parameters controlling emission of special markers. */
  158943. boolean write_JFIF_header; /* should a JFIF marker be written? */
  158944. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  158945. UINT8 JFIF_minor_version;
  158946. /* These three values are not used by the JPEG code, merely copied */
  158947. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  158948. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  158949. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  158950. UINT8 density_unit; /* JFIF code for pixel size units */
  158951. UINT16 X_density; /* Horizontal pixel density */
  158952. UINT16 Y_density; /* Vertical pixel density */
  158953. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  158954. /* State variable: index of next scanline to be written to
  158955. * jpeg_write_scanlines(). Application may use this to control its
  158956. * processing loop, e.g., "while (next_scanline < image_height)".
  158957. */
  158958. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  158959. /* Remaining fields are known throughout compressor, but generally
  158960. * should not be touched by a surrounding application.
  158961. */
  158962. /*
  158963. * These fields are computed during compression startup
  158964. */
  158965. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  158966. int max_h_samp_factor; /* largest h_samp_factor */
  158967. int max_v_samp_factor; /* largest v_samp_factor */
  158968. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  158969. /* The coefficient controller receives data in units of MCU rows as defined
  158970. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  158971. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  158972. * "iMCU" (interleaved MCU) row.
  158973. */
  158974. /*
  158975. * These fields are valid during any one scan.
  158976. * They describe the components and MCUs actually appearing in the scan.
  158977. */
  158978. int comps_in_scan; /* # of JPEG components in this scan */
  158979. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  158980. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  158981. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  158982. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  158983. int blocks_in_MCU; /* # of DCT blocks per MCU */
  158984. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  158985. /* MCU_membership[i] is index in cur_comp_info of component owning */
  158986. /* i'th block in an MCU */
  158987. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  158988. /*
  158989. * Links to compression subobjects (methods and private variables of modules)
  158990. */
  158991. struct jpeg_comp_master * master;
  158992. struct jpeg_c_main_controller * main;
  158993. struct jpeg_c_prep_controller * prep;
  158994. struct jpeg_c_coef_controller * coef;
  158995. struct jpeg_marker_writer * marker;
  158996. struct jpeg_color_converter * cconvert;
  158997. struct jpeg_downsampler * downsample;
  158998. struct jpeg_forward_dct * fdct;
  158999. struct jpeg_entropy_encoder * entropy;
  159000. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159001. int script_space_size;
  159002. };
  159003. /* Master record for a decompression instance */
  159004. struct jpeg_decompress_struct {
  159005. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159006. /* Source of compressed data */
  159007. struct jpeg_source_mgr * src;
  159008. /* Basic description of image --- filled in by jpeg_read_header(). */
  159009. /* Application may inspect these values to decide how to process image. */
  159010. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159011. JDIMENSION image_height; /* nominal image height */
  159012. int num_components; /* # of color components in JPEG image */
  159013. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159014. /* Decompression processing parameters --- these fields must be set before
  159015. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159016. * them to default values.
  159017. */
  159018. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159019. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159020. double output_gamma; /* image gamma wanted in output */
  159021. boolean buffered_image; /* TRUE=multiple output passes */
  159022. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159023. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159024. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159025. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159026. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159027. /* the following are ignored if not quantize_colors: */
  159028. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159029. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159030. int desired_number_of_colors; /* max # colors to use in created colormap */
  159031. /* these are significant only in buffered-image mode: */
  159032. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159033. boolean enable_external_quant;/* enable future use of external colormap */
  159034. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159035. /* Description of actual output image that will be returned to application.
  159036. * These fields are computed by jpeg_start_decompress().
  159037. * You can also use jpeg_calc_output_dimensions() to determine these values
  159038. * in advance of calling jpeg_start_decompress().
  159039. */
  159040. JDIMENSION output_width; /* scaled image width */
  159041. JDIMENSION output_height; /* scaled image height */
  159042. int out_color_components; /* # of color components in out_color_space */
  159043. int output_components; /* # of color components returned */
  159044. /* output_components is 1 (a colormap index) when quantizing colors;
  159045. * otherwise it equals out_color_components.
  159046. */
  159047. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159048. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159049. * high, space and time will be wasted due to unnecessary data copying.
  159050. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159051. */
  159052. /* When quantizing colors, the output colormap is described by these fields.
  159053. * The application can supply a colormap by setting colormap non-NULL before
  159054. * calling jpeg_start_decompress; otherwise a colormap is created during
  159055. * jpeg_start_decompress or jpeg_start_output.
  159056. * The map has out_color_components rows and actual_number_of_colors columns.
  159057. */
  159058. int actual_number_of_colors; /* number of entries in use */
  159059. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159060. /* State variables: these variables indicate the progress of decompression.
  159061. * The application may examine these but must not modify them.
  159062. */
  159063. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159064. * Application may use this to control its processing loop, e.g.,
  159065. * "while (output_scanline < output_height)".
  159066. */
  159067. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159068. /* Current input scan number and number of iMCU rows completed in scan.
  159069. * These indicate the progress of the decompressor input side.
  159070. */
  159071. int input_scan_number; /* Number of SOS markers seen so far */
  159072. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159073. /* The "output scan number" is the notional scan being displayed by the
  159074. * output side. The decompressor will not allow output scan/row number
  159075. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159076. */
  159077. int output_scan_number; /* Nominal scan number being displayed */
  159078. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159079. /* Current progression status. coef_bits[c][i] indicates the precision
  159080. * with which component c's DCT coefficient i (in zigzag order) is known.
  159081. * It is -1 when no data has yet been received, otherwise it is the point
  159082. * transform (shift) value for the most recent scan of the coefficient
  159083. * (thus, 0 at completion of the progression).
  159084. * This pointer is NULL when reading a non-progressive file.
  159085. */
  159086. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159087. /* Internal JPEG parameters --- the application usually need not look at
  159088. * these fields. Note that the decompressor output side may not use
  159089. * any parameters that can change between scans.
  159090. */
  159091. /* Quantization and Huffman tables are carried forward across input
  159092. * datastreams when processing abbreviated JPEG datastreams.
  159093. */
  159094. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159095. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159096. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159097. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159098. /* ptrs to Huffman coding tables, or NULL if not defined */
  159099. /* These parameters are never carried across datastreams, since they
  159100. * are given in SOF/SOS markers or defined to be reset by SOI.
  159101. */
  159102. int data_precision; /* bits of precision in image data */
  159103. jpeg_component_info * comp_info;
  159104. /* comp_info[i] describes component that appears i'th in SOF */
  159105. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159106. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159107. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159108. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159109. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159110. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159111. /* These fields record data obtained from optional markers recognized by
  159112. * the JPEG library.
  159113. */
  159114. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159115. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159116. UINT8 JFIF_major_version; /* JFIF version number */
  159117. UINT8 JFIF_minor_version;
  159118. UINT8 density_unit; /* JFIF code for pixel size units */
  159119. UINT16 X_density; /* Horizontal pixel density */
  159120. UINT16 Y_density; /* Vertical pixel density */
  159121. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159122. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159123. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159124. /* Aside from the specific data retained from APPn markers known to the
  159125. * library, the uninterpreted contents of any or all APPn and COM markers
  159126. * can be saved in a list for examination by the application.
  159127. */
  159128. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159129. /* Remaining fields are known throughout decompressor, but generally
  159130. * should not be touched by a surrounding application.
  159131. */
  159132. /*
  159133. * These fields are computed during decompression startup
  159134. */
  159135. int max_h_samp_factor; /* largest h_samp_factor */
  159136. int max_v_samp_factor; /* largest v_samp_factor */
  159137. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  159138. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  159139. /* The coefficient controller's input and output progress is measured in
  159140. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  159141. * in fully interleaved JPEG scans, but are used whether the scan is
  159142. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  159143. * rows of each component. Therefore, the IDCT output contains
  159144. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  159145. */
  159146. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  159147. /*
  159148. * These fields are valid during any one scan.
  159149. * They describe the components and MCUs actually appearing in the scan.
  159150. * Note that the decompressor output side must not use these fields.
  159151. */
  159152. int comps_in_scan; /* # of JPEG components in this scan */
  159153. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159154. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159155. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159156. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159157. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159158. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  159159. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159160. /* i'th block in an MCU */
  159161. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159162. /* This field is shared between entropy decoder and marker parser.
  159163. * It is either zero or the code of a JPEG marker that has been
  159164. * read from the data source, but has not yet been processed.
  159165. */
  159166. int unread_marker;
  159167. /*
  159168. * Links to decompression subobjects (methods, private variables of modules)
  159169. */
  159170. struct jpeg_decomp_master * master;
  159171. struct jpeg_d_main_controller * main;
  159172. struct jpeg_d_coef_controller * coef;
  159173. struct jpeg_d_post_controller * post;
  159174. struct jpeg_input_controller * inputctl;
  159175. struct jpeg_marker_reader * marker;
  159176. struct jpeg_entropy_decoder * entropy;
  159177. struct jpeg_inverse_dct * idct;
  159178. struct jpeg_upsampler * upsample;
  159179. struct jpeg_color_deconverter * cconvert;
  159180. struct jpeg_color_quantizer * cquantize;
  159181. };
  159182. /* "Object" declarations for JPEG modules that may be supplied or called
  159183. * directly by the surrounding application.
  159184. * As with all objects in the JPEG library, these structs only define the
  159185. * publicly visible methods and state variables of a module. Additional
  159186. * private fields may exist after the public ones.
  159187. */
  159188. /* Error handler object */
  159189. struct jpeg_error_mgr {
  159190. /* Error exit handler: does not return to caller */
  159191. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  159192. /* Conditionally emit a trace or warning message */
  159193. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  159194. /* Routine that actually outputs a trace or error message */
  159195. JMETHOD(void, output_message, (j_common_ptr cinfo));
  159196. /* Format a message string for the most recent JPEG error or message */
  159197. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  159198. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  159199. /* Reset error state variables at start of a new image */
  159200. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  159201. /* The message ID code and any parameters are saved here.
  159202. * A message can have one string parameter or up to 8 int parameters.
  159203. */
  159204. int msg_code;
  159205. #define JMSG_STR_PARM_MAX 80
  159206. union {
  159207. int i[8];
  159208. char s[JMSG_STR_PARM_MAX];
  159209. } msg_parm;
  159210. /* Standard state variables for error facility */
  159211. int trace_level; /* max msg_level that will be displayed */
  159212. /* For recoverable corrupt-data errors, we emit a warning message,
  159213. * but keep going unless emit_message chooses to abort. emit_message
  159214. * should count warnings in num_warnings. The surrounding application
  159215. * can check for bad data by seeing if num_warnings is nonzero at the
  159216. * end of processing.
  159217. */
  159218. long num_warnings; /* number of corrupt-data warnings */
  159219. /* These fields point to the table(s) of error message strings.
  159220. * An application can change the table pointer to switch to a different
  159221. * message list (typically, to change the language in which errors are
  159222. * reported). Some applications may wish to add additional error codes
  159223. * that will be handled by the JPEG library error mechanism; the second
  159224. * table pointer is used for this purpose.
  159225. *
  159226. * First table includes all errors generated by JPEG library itself.
  159227. * Error code 0 is reserved for a "no such error string" message.
  159228. */
  159229. const char * const * jpeg_message_table; /* Library errors */
  159230. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  159231. /* Second table can be added by application (see cjpeg/djpeg for example).
  159232. * It contains strings numbered first_addon_message..last_addon_message.
  159233. */
  159234. const char * const * addon_message_table; /* Non-library errors */
  159235. int first_addon_message; /* code for first string in addon table */
  159236. int last_addon_message; /* code for last string in addon table */
  159237. };
  159238. /* Progress monitor object */
  159239. struct jpeg_progress_mgr {
  159240. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  159241. long pass_counter; /* work units completed in this pass */
  159242. long pass_limit; /* total number of work units in this pass */
  159243. int completed_passes; /* passes completed so far */
  159244. int total_passes; /* total number of passes expected */
  159245. };
  159246. /* Data destination object for compression */
  159247. struct jpeg_destination_mgr {
  159248. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159249. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159250. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  159251. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  159252. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  159253. };
  159254. /* Data source object for decompression */
  159255. struct jpeg_source_mgr {
  159256. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  159257. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  159258. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  159259. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  159260. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  159261. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  159262. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  159263. };
  159264. /* Memory manager object.
  159265. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  159266. * and "really big" objects (virtual arrays with backing store if needed).
  159267. * The memory manager does not allow individual objects to be freed; rather,
  159268. * each created object is assigned to a pool, and whole pools can be freed
  159269. * at once. This is faster and more convenient than remembering exactly what
  159270. * to free, especially where malloc()/free() are not too speedy.
  159271. * NB: alloc routines never return NULL. They exit to error_exit if not
  159272. * successful.
  159273. */
  159274. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  159275. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  159276. #define JPOOL_NUMPOOLS 2
  159277. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  159278. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  159279. struct jpeg_memory_mgr {
  159280. /* Method pointers */
  159281. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  159282. size_t sizeofobject));
  159283. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  159284. size_t sizeofobject));
  159285. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  159286. JDIMENSION samplesperrow,
  159287. JDIMENSION numrows));
  159288. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  159289. JDIMENSION blocksperrow,
  159290. JDIMENSION numrows));
  159291. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  159292. int pool_id,
  159293. boolean pre_zero,
  159294. JDIMENSION samplesperrow,
  159295. JDIMENSION numrows,
  159296. JDIMENSION maxaccess));
  159297. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  159298. int pool_id,
  159299. boolean pre_zero,
  159300. JDIMENSION blocksperrow,
  159301. JDIMENSION numrows,
  159302. JDIMENSION maxaccess));
  159303. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  159304. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  159305. jvirt_sarray_ptr ptr,
  159306. JDIMENSION start_row,
  159307. JDIMENSION num_rows,
  159308. boolean writable));
  159309. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  159310. jvirt_barray_ptr ptr,
  159311. JDIMENSION start_row,
  159312. JDIMENSION num_rows,
  159313. boolean writable));
  159314. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  159315. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  159316. /* Limit on memory allocation for this JPEG object. (Note that this is
  159317. * merely advisory, not a guaranteed maximum; it only affects the space
  159318. * used for virtual-array buffers.) May be changed by outer application
  159319. * after creating the JPEG object.
  159320. */
  159321. long max_memory_to_use;
  159322. /* Maximum allocation request accepted by alloc_large. */
  159323. long max_alloc_chunk;
  159324. };
  159325. /* Routine signature for application-supplied marker processing methods.
  159326. * Need not pass marker code since it is stored in cinfo->unread_marker.
  159327. */
  159328. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  159329. /* Declarations for routines called by application.
  159330. * The JPP macro hides prototype parameters from compilers that can't cope.
  159331. * Note JPP requires double parentheses.
  159332. */
  159333. #ifdef HAVE_PROTOTYPES
  159334. #define JPP(arglist) arglist
  159335. #else
  159336. #define JPP(arglist) ()
  159337. #endif
  159338. /* Short forms of external names for systems with brain-damaged linkers.
  159339. * We shorten external names to be unique in the first six letters, which
  159340. * is good enough for all known systems.
  159341. * (If your compiler itself needs names to be unique in less than 15
  159342. * characters, you are out of luck. Get a better compiler.)
  159343. */
  159344. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159345. #define jpeg_std_error jStdError
  159346. #define jpeg_CreateCompress jCreaCompress
  159347. #define jpeg_CreateDecompress jCreaDecompress
  159348. #define jpeg_destroy_compress jDestCompress
  159349. #define jpeg_destroy_decompress jDestDecompress
  159350. #define jpeg_stdio_dest jStdDest
  159351. #define jpeg_stdio_src jStdSrc
  159352. #define jpeg_set_defaults jSetDefaults
  159353. #define jpeg_set_colorspace jSetColorspace
  159354. #define jpeg_default_colorspace jDefColorspace
  159355. #define jpeg_set_quality jSetQuality
  159356. #define jpeg_set_linear_quality jSetLQuality
  159357. #define jpeg_add_quant_table jAddQuantTable
  159358. #define jpeg_quality_scaling jQualityScaling
  159359. #define jpeg_simple_progression jSimProgress
  159360. #define jpeg_suppress_tables jSuppressTables
  159361. #define jpeg_alloc_quant_table jAlcQTable
  159362. #define jpeg_alloc_huff_table jAlcHTable
  159363. #define jpeg_start_compress jStrtCompress
  159364. #define jpeg_write_scanlines jWrtScanlines
  159365. #define jpeg_finish_compress jFinCompress
  159366. #define jpeg_write_raw_data jWrtRawData
  159367. #define jpeg_write_marker jWrtMarker
  159368. #define jpeg_write_m_header jWrtMHeader
  159369. #define jpeg_write_m_byte jWrtMByte
  159370. #define jpeg_write_tables jWrtTables
  159371. #define jpeg_read_header jReadHeader
  159372. #define jpeg_start_decompress jStrtDecompress
  159373. #define jpeg_read_scanlines jReadScanlines
  159374. #define jpeg_finish_decompress jFinDecompress
  159375. #define jpeg_read_raw_data jReadRawData
  159376. #define jpeg_has_multiple_scans jHasMultScn
  159377. #define jpeg_start_output jStrtOutput
  159378. #define jpeg_finish_output jFinOutput
  159379. #define jpeg_input_complete jInComplete
  159380. #define jpeg_new_colormap jNewCMap
  159381. #define jpeg_consume_input jConsumeInput
  159382. #define jpeg_calc_output_dimensions jCalcDimensions
  159383. #define jpeg_save_markers jSaveMarkers
  159384. #define jpeg_set_marker_processor jSetMarker
  159385. #define jpeg_read_coefficients jReadCoefs
  159386. #define jpeg_write_coefficients jWrtCoefs
  159387. #define jpeg_copy_critical_parameters jCopyCrit
  159388. #define jpeg_abort_compress jAbrtCompress
  159389. #define jpeg_abort_decompress jAbrtDecompress
  159390. #define jpeg_abort jAbort
  159391. #define jpeg_destroy jDestroy
  159392. #define jpeg_resync_to_restart jResyncRestart
  159393. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159394. /* Default error-management setup */
  159395. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  159396. JPP((struct jpeg_error_mgr * err));
  159397. /* Initialization of JPEG compression objects.
  159398. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  159399. * names that applications should call. These expand to calls on
  159400. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  159401. * passed for version mismatch checking.
  159402. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  159403. */
  159404. #define jpeg_create_compress(cinfo) \
  159405. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  159406. (size_t) sizeof(struct jpeg_compress_struct))
  159407. #define jpeg_create_decompress(cinfo) \
  159408. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  159409. (size_t) sizeof(struct jpeg_decompress_struct))
  159410. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  159411. int version, size_t structsize));
  159412. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  159413. int version, size_t structsize));
  159414. /* Destruction of JPEG compression objects */
  159415. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  159416. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  159417. /* Standard data source and destination managers: stdio streams. */
  159418. /* Caller is responsible for opening the file before and closing after. */
  159419. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  159420. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  159421. /* Default parameter setup for compression */
  159422. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  159423. /* Compression parameter setup aids */
  159424. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  159425. J_COLOR_SPACE colorspace));
  159426. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  159427. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  159428. boolean force_baseline));
  159429. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  159430. int scale_factor,
  159431. boolean force_baseline));
  159432. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  159433. const unsigned int *basic_table,
  159434. int scale_factor,
  159435. boolean force_baseline));
  159436. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  159437. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  159438. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  159439. boolean suppress));
  159440. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  159441. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  159442. /* Main entry points for compression */
  159443. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  159444. boolean write_all_tables));
  159445. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  159446. JSAMPARRAY scanlines,
  159447. JDIMENSION num_lines));
  159448. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  159449. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  159450. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  159451. JSAMPIMAGE data,
  159452. JDIMENSION num_lines));
  159453. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  159454. EXTERN(void) jpeg_write_marker
  159455. JPP((j_compress_ptr cinfo, int marker,
  159456. const JOCTET * dataptr, unsigned int datalen));
  159457. /* Same, but piecemeal. */
  159458. EXTERN(void) jpeg_write_m_header
  159459. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  159460. EXTERN(void) jpeg_write_m_byte
  159461. JPP((j_compress_ptr cinfo, int val));
  159462. /* Alternate compression function: just write an abbreviated table file */
  159463. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  159464. /* Decompression startup: read start of JPEG datastream to see what's there */
  159465. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  159466. boolean require_image));
  159467. /* Return value is one of: */
  159468. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  159469. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  159470. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  159471. /* If you pass require_image = TRUE (normal case), you need not check for
  159472. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  159473. * JPEG_SUSPENDED is only possible if you use a data source module that can
  159474. * give a suspension return (the stdio source module doesn't).
  159475. */
  159476. /* Main entry points for decompression */
  159477. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  159478. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  159479. JSAMPARRAY scanlines,
  159480. JDIMENSION max_lines));
  159481. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  159482. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  159483. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  159484. JSAMPIMAGE data,
  159485. JDIMENSION max_lines));
  159486. /* Additional entry points for buffered-image mode. */
  159487. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  159488. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  159489. int scan_number));
  159490. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  159491. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  159492. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  159493. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  159494. /* Return value is one of: */
  159495. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  159496. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  159497. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  159498. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  159499. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  159500. /* Precalculate output dimensions for current decompression parameters. */
  159501. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  159502. /* Control saving of COM and APPn markers into marker_list. */
  159503. EXTERN(void) jpeg_save_markers
  159504. JPP((j_decompress_ptr cinfo, int marker_code,
  159505. unsigned int length_limit));
  159506. /* Install a special processing method for COM or APPn markers. */
  159507. EXTERN(void) jpeg_set_marker_processor
  159508. JPP((j_decompress_ptr cinfo, int marker_code,
  159509. jpeg_marker_parser_method routine));
  159510. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  159511. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  159512. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  159513. jvirt_barray_ptr * coef_arrays));
  159514. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  159515. j_compress_ptr dstinfo));
  159516. /* If you choose to abort compression or decompression before completing
  159517. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  159518. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  159519. * if you're done with the JPEG object, but if you want to clean it up and
  159520. * reuse it, call this:
  159521. */
  159522. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  159523. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  159524. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  159525. * flavor of JPEG object. These may be more convenient in some places.
  159526. */
  159527. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  159528. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  159529. /* Default restart-marker-resync procedure for use by data source modules */
  159530. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  159531. int desired));
  159532. /* These marker codes are exported since applications and data source modules
  159533. * are likely to want to use them.
  159534. */
  159535. #define JPEG_RST0 0xD0 /* RST0 marker code */
  159536. #define JPEG_EOI 0xD9 /* EOI marker code */
  159537. #define JPEG_APP0 0xE0 /* APP0 marker code */
  159538. #define JPEG_COM 0xFE /* COM marker code */
  159539. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  159540. * for structure definitions that are never filled in, keep it quiet by
  159541. * supplying dummy definitions for the various substructures.
  159542. */
  159543. #ifdef INCOMPLETE_TYPES_BROKEN
  159544. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  159545. struct jvirt_sarray_control { long dummy; };
  159546. struct jvirt_barray_control { long dummy; };
  159547. struct jpeg_comp_master { long dummy; };
  159548. struct jpeg_c_main_controller { long dummy; };
  159549. struct jpeg_c_prep_controller { long dummy; };
  159550. struct jpeg_c_coef_controller { long dummy; };
  159551. struct jpeg_marker_writer { long dummy; };
  159552. struct jpeg_color_converter { long dummy; };
  159553. struct jpeg_downsampler { long dummy; };
  159554. struct jpeg_forward_dct { long dummy; };
  159555. struct jpeg_entropy_encoder { long dummy; };
  159556. struct jpeg_decomp_master { long dummy; };
  159557. struct jpeg_d_main_controller { long dummy; };
  159558. struct jpeg_d_coef_controller { long dummy; };
  159559. struct jpeg_d_post_controller { long dummy; };
  159560. struct jpeg_input_controller { long dummy; };
  159561. struct jpeg_marker_reader { long dummy; };
  159562. struct jpeg_entropy_decoder { long dummy; };
  159563. struct jpeg_inverse_dct { long dummy; };
  159564. struct jpeg_upsampler { long dummy; };
  159565. struct jpeg_color_deconverter { long dummy; };
  159566. struct jpeg_color_quantizer { long dummy; };
  159567. #endif /* JPEG_INTERNALS */
  159568. #endif /* INCOMPLETE_TYPES_BROKEN */
  159569. /*
  159570. * The JPEG library modules define JPEG_INTERNALS before including this file.
  159571. * The internal structure declarations are read only when that is true.
  159572. * Applications using the library should not include jpegint.h, but may wish
  159573. * to include jerror.h.
  159574. */
  159575. #ifdef JPEG_INTERNALS
  159576. /*** Start of inlined file: jpegint.h ***/
  159577. /* Declarations for both compression & decompression */
  159578. typedef enum { /* Operating modes for buffer controllers */
  159579. JBUF_PASS_THRU, /* Plain stripwise operation */
  159580. /* Remaining modes require a full-image buffer to have been created */
  159581. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  159582. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  159583. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  159584. } J_BUF_MODE;
  159585. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  159586. #define CSTATE_START 100 /* after create_compress */
  159587. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  159588. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  159589. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  159590. #define DSTATE_START 200 /* after create_decompress */
  159591. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  159592. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  159593. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  159594. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  159595. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  159596. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  159597. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  159598. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  159599. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  159600. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  159601. /* Declarations for compression modules */
  159602. /* Master control module */
  159603. struct jpeg_comp_master {
  159604. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  159605. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  159606. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  159607. /* State variables made visible to other modules */
  159608. boolean call_pass_startup; /* True if pass_startup must be called */
  159609. boolean is_last_pass; /* True during last pass */
  159610. };
  159611. /* Main buffer control (downsampled-data buffer) */
  159612. struct jpeg_c_main_controller {
  159613. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159614. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  159615. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159616. JDIMENSION in_rows_avail));
  159617. };
  159618. /* Compression preprocessing (downsampling input buffer control) */
  159619. struct jpeg_c_prep_controller {
  159620. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159621. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  159622. JSAMPARRAY input_buf,
  159623. JDIMENSION *in_row_ctr,
  159624. JDIMENSION in_rows_avail,
  159625. JSAMPIMAGE output_buf,
  159626. JDIMENSION *out_row_group_ctr,
  159627. JDIMENSION out_row_groups_avail));
  159628. };
  159629. /* Coefficient buffer control */
  159630. struct jpeg_c_coef_controller {
  159631. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159632. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  159633. JSAMPIMAGE input_buf));
  159634. };
  159635. /* Colorspace conversion */
  159636. struct jpeg_color_converter {
  159637. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159638. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  159639. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159640. JDIMENSION output_row, int num_rows));
  159641. };
  159642. /* Downsampling */
  159643. struct jpeg_downsampler {
  159644. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159645. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  159646. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  159647. JSAMPIMAGE output_buf,
  159648. JDIMENSION out_row_group_index));
  159649. boolean need_context_rows; /* TRUE if need rows above & below */
  159650. };
  159651. /* Forward DCT (also controls coefficient quantization) */
  159652. struct jpeg_forward_dct {
  159653. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159654. /* perhaps this should be an array??? */
  159655. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  159656. jpeg_component_info * compptr,
  159657. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  159658. JDIMENSION start_row, JDIMENSION start_col,
  159659. JDIMENSION num_blocks));
  159660. };
  159661. /* Entropy encoding */
  159662. struct jpeg_entropy_encoder {
  159663. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  159664. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  159665. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  159666. };
  159667. /* Marker writing */
  159668. struct jpeg_marker_writer {
  159669. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  159670. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  159671. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  159672. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  159673. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  159674. /* These routines are exported to allow insertion of extra markers */
  159675. /* Probably only COM and APPn markers should be written this way */
  159676. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  159677. unsigned int datalen));
  159678. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  159679. };
  159680. /* Declarations for decompression modules */
  159681. /* Master control module */
  159682. struct jpeg_decomp_master {
  159683. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  159684. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  159685. /* State variables made visible to other modules */
  159686. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  159687. };
  159688. /* Input control module */
  159689. struct jpeg_input_controller {
  159690. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  159691. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  159692. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  159693. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  159694. /* State variables made visible to other modules */
  159695. boolean has_multiple_scans; /* True if file has multiple scans */
  159696. boolean eoi_reached; /* True when EOI has been consumed */
  159697. };
  159698. /* Main buffer control (downsampled-data buffer) */
  159699. struct jpeg_d_main_controller {
  159700. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  159701. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  159702. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  159703. JDIMENSION out_rows_avail));
  159704. };
  159705. /* Coefficient buffer control */
  159706. struct jpeg_d_coef_controller {
  159707. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  159708. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  159709. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  159710. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  159711. JSAMPIMAGE output_buf));
  159712. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  159713. jvirt_barray_ptr *coef_arrays;
  159714. };
  159715. /* Decompression postprocessing (color quantization buffer control) */
  159716. struct jpeg_d_post_controller {
  159717. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  159718. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  159719. JSAMPIMAGE input_buf,
  159720. JDIMENSION *in_row_group_ctr,
  159721. JDIMENSION in_row_groups_avail,
  159722. JSAMPARRAY output_buf,
  159723. JDIMENSION *out_row_ctr,
  159724. JDIMENSION out_rows_avail));
  159725. };
  159726. /* Marker reading & parsing */
  159727. struct jpeg_marker_reader {
  159728. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  159729. /* Read markers until SOS or EOI.
  159730. * Returns same codes as are defined for jpeg_consume_input:
  159731. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  159732. */
  159733. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  159734. /* Read a restart marker --- exported for use by entropy decoder only */
  159735. jpeg_marker_parser_method read_restart_marker;
  159736. /* State of marker reader --- nominally internal, but applications
  159737. * supplying COM or APPn handlers might like to know the state.
  159738. */
  159739. boolean saw_SOI; /* found SOI? */
  159740. boolean saw_SOF; /* found SOF? */
  159741. int next_restart_num; /* next restart number expected (0-7) */
  159742. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  159743. };
  159744. /* Entropy decoding */
  159745. struct jpeg_entropy_decoder {
  159746. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  159747. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  159748. JBLOCKROW *MCU_data));
  159749. /* This is here to share code between baseline and progressive decoders; */
  159750. /* other modules probably should not use it */
  159751. boolean insufficient_data; /* set TRUE after emitting warning */
  159752. };
  159753. /* Inverse DCT (also performs dequantization) */
  159754. typedef JMETHOD(void, inverse_DCT_method_ptr,
  159755. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159756. JCOEFPTR coef_block,
  159757. JSAMPARRAY output_buf, JDIMENSION output_col));
  159758. struct jpeg_inverse_dct {
  159759. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  159760. /* It is useful to allow each component to have a separate IDCT method. */
  159761. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  159762. };
  159763. /* Upsampling (note that upsampler must also call color converter) */
  159764. struct jpeg_upsampler {
  159765. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  159766. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  159767. JSAMPIMAGE input_buf,
  159768. JDIMENSION *in_row_group_ctr,
  159769. JDIMENSION in_row_groups_avail,
  159770. JSAMPARRAY output_buf,
  159771. JDIMENSION *out_row_ctr,
  159772. JDIMENSION out_rows_avail));
  159773. boolean need_context_rows; /* TRUE if need rows above & below */
  159774. };
  159775. /* Colorspace conversion */
  159776. struct jpeg_color_deconverter {
  159777. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  159778. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  159779. JSAMPIMAGE input_buf, JDIMENSION input_row,
  159780. JSAMPARRAY output_buf, int num_rows));
  159781. };
  159782. /* Color quantization or color precision reduction */
  159783. struct jpeg_color_quantizer {
  159784. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  159785. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  159786. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  159787. int num_rows));
  159788. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  159789. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  159790. };
  159791. /* Miscellaneous useful macros */
  159792. #undef MAX
  159793. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  159794. #undef MIN
  159795. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  159796. /* We assume that right shift corresponds to signed division by 2 with
  159797. * rounding towards minus infinity. This is correct for typical "arithmetic
  159798. * shift" instructions that shift in copies of the sign bit. But some
  159799. * C compilers implement >> with an unsigned shift. For these machines you
  159800. * must define RIGHT_SHIFT_IS_UNSIGNED.
  159801. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  159802. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  159803. * included in the variables of any routine using RIGHT_SHIFT.
  159804. */
  159805. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  159806. #define SHIFT_TEMPS INT32 shift_temp;
  159807. #define RIGHT_SHIFT(x,shft) \
  159808. ((shift_temp = (x)) < 0 ? \
  159809. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  159810. (shift_temp >> (shft)))
  159811. #else
  159812. #define SHIFT_TEMPS
  159813. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  159814. #endif
  159815. /* Short forms of external names for systems with brain-damaged linkers. */
  159816. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159817. #define jinit_compress_master jICompress
  159818. #define jinit_c_master_control jICMaster
  159819. #define jinit_c_main_controller jICMainC
  159820. #define jinit_c_prep_controller jICPrepC
  159821. #define jinit_c_coef_controller jICCoefC
  159822. #define jinit_color_converter jICColor
  159823. #define jinit_downsampler jIDownsampler
  159824. #define jinit_forward_dct jIFDCT
  159825. #define jinit_huff_encoder jIHEncoder
  159826. #define jinit_phuff_encoder jIPHEncoder
  159827. #define jinit_marker_writer jIMWriter
  159828. #define jinit_master_decompress jIDMaster
  159829. #define jinit_d_main_controller jIDMainC
  159830. #define jinit_d_coef_controller jIDCoefC
  159831. #define jinit_d_post_controller jIDPostC
  159832. #define jinit_input_controller jIInCtlr
  159833. #define jinit_marker_reader jIMReader
  159834. #define jinit_huff_decoder jIHDecoder
  159835. #define jinit_phuff_decoder jIPHDecoder
  159836. #define jinit_inverse_dct jIIDCT
  159837. #define jinit_upsampler jIUpsampler
  159838. #define jinit_color_deconverter jIDColor
  159839. #define jinit_1pass_quantizer jI1Quant
  159840. #define jinit_2pass_quantizer jI2Quant
  159841. #define jinit_merged_upsampler jIMUpsampler
  159842. #define jinit_memory_mgr jIMemMgr
  159843. #define jdiv_round_up jDivRound
  159844. #define jround_up jRound
  159845. #define jcopy_sample_rows jCopySamples
  159846. #define jcopy_block_row jCopyBlocks
  159847. #define jzero_far jZeroFar
  159848. #define jpeg_zigzag_order jZIGTable
  159849. #define jpeg_natural_order jZAGTable
  159850. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159851. /* Compression module initialization routines */
  159852. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  159853. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  159854. boolean transcode_only));
  159855. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  159856. boolean need_full_buffer));
  159857. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  159858. boolean need_full_buffer));
  159859. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  159860. boolean need_full_buffer));
  159861. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  159862. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  159863. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  159864. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  159865. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  159866. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  159867. /* Decompression module initialization routines */
  159868. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  159869. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  159870. boolean need_full_buffer));
  159871. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  159872. boolean need_full_buffer));
  159873. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  159874. boolean need_full_buffer));
  159875. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  159876. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  159877. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  159878. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  159879. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  159880. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  159881. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  159882. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  159883. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  159884. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  159885. /* Memory manager initialization */
  159886. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  159887. /* Utility routines in jutils.c */
  159888. EXTERN(long) jdiv_round_up JPP((long a, long b));
  159889. EXTERN(long) jround_up JPP((long a, long b));
  159890. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  159891. JSAMPARRAY output_array, int dest_row,
  159892. int num_rows, JDIMENSION num_cols));
  159893. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  159894. JDIMENSION num_blocks));
  159895. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  159896. /* Constant tables in jutils.c */
  159897. #if 0 /* This table is not actually needed in v6a */
  159898. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  159899. #endif
  159900. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  159901. /* Suppress undefined-structure complaints if necessary. */
  159902. #ifdef INCOMPLETE_TYPES_BROKEN
  159903. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  159904. struct jvirt_sarray_control { long dummy; };
  159905. struct jvirt_barray_control { long dummy; };
  159906. #endif
  159907. #endif /* INCOMPLETE_TYPES_BROKEN */
  159908. /*** End of inlined file: jpegint.h ***/
  159909. /* fetch private declarations */
  159910. /*** Start of inlined file: jerror.h ***/
  159911. /*
  159912. * To define the enum list of message codes, include this file without
  159913. * defining macro JMESSAGE. To create a message string table, include it
  159914. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  159915. */
  159916. #ifndef JMESSAGE
  159917. #ifndef JERROR_H
  159918. /* First time through, define the enum list */
  159919. #define JMAKE_ENUM_LIST
  159920. #else
  159921. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  159922. #define JMESSAGE(code,string)
  159923. #endif /* JERROR_H */
  159924. #endif /* JMESSAGE */
  159925. #ifdef JMAKE_ENUM_LIST
  159926. typedef enum {
  159927. #define JMESSAGE(code,string) code ,
  159928. #endif /* JMAKE_ENUM_LIST */
  159929. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  159930. /* For maintenance convenience, list is alphabetical by message code name */
  159931. JMESSAGE(JERR_ARITH_NOTIMPL,
  159932. "Sorry, there are legal restrictions on arithmetic coding")
  159933. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  159934. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  159935. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  159936. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  159937. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  159938. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  159939. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  159940. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  159941. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  159942. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  159943. JMESSAGE(JERR_BAD_LIB_VERSION,
  159944. "Wrong JPEG library version: library is %d, caller expects %d")
  159945. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  159946. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  159947. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  159948. JMESSAGE(JERR_BAD_PROGRESSION,
  159949. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  159950. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  159951. "Invalid progressive parameters at scan script entry %d")
  159952. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  159953. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  159954. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  159955. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  159956. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  159957. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  159958. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  159959. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  159960. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  159961. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  159962. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  159963. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  159964. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  159965. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  159966. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  159967. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  159968. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  159969. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  159970. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  159971. JMESSAGE(JERR_FILE_READ, "Input file read error")
  159972. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  159973. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  159974. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  159975. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  159976. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  159977. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  159978. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  159979. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  159980. "Cannot transcode due to multiple use of quantization table %d")
  159981. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  159982. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  159983. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  159984. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  159985. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  159986. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  159987. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  159988. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  159989. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  159990. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  159991. JMESSAGE(JERR_QUANT_COMPONENTS,
  159992. "Cannot quantize more than %d color components")
  159993. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  159994. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  159995. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  159996. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  159997. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  159998. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  159999. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160000. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160001. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160002. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160003. JMESSAGE(JERR_TFILE_WRITE,
  160004. "Write failed on temporary file --- out of disk space?")
  160005. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160006. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160007. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160008. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160009. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160010. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160011. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160012. JMESSAGE(JMSG_VERSION, JVERSION)
  160013. JMESSAGE(JTRC_16BIT_TABLES,
  160014. "Caution: quantization tables are too coarse for baseline JPEG")
  160015. JMESSAGE(JTRC_ADOBE,
  160016. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160017. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160018. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160019. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160020. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160021. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160022. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160023. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160024. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160025. JMESSAGE(JTRC_EOI, "End Of Image")
  160026. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160027. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160028. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160029. "Warning: thumbnail image size does not match data length %u")
  160030. JMESSAGE(JTRC_JFIF_EXTENSION,
  160031. "JFIF extension marker: type 0x%02x, length %u")
  160032. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160033. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160034. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160035. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160036. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160037. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160038. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160039. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160040. JMESSAGE(JTRC_RST, "RST%d")
  160041. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160042. "Smoothing not supported with nonstandard sampling ratios")
  160043. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160044. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160045. JMESSAGE(JTRC_SOI, "Start of Image")
  160046. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160047. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160048. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160049. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160050. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160051. JMESSAGE(JTRC_THUMB_JPEG,
  160052. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160053. JMESSAGE(JTRC_THUMB_PALETTE,
  160054. "JFIF extension marker: palette thumbnail image, length %u")
  160055. JMESSAGE(JTRC_THUMB_RGB,
  160056. "JFIF extension marker: RGB thumbnail image, length %u")
  160057. JMESSAGE(JTRC_UNKNOWN_IDS,
  160058. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160059. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160060. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160061. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160062. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160063. "Inconsistent progression sequence for component %d coefficient %d")
  160064. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160065. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160066. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160067. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160068. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160069. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160070. JMESSAGE(JWRN_MUST_RESYNC,
  160071. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160072. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160073. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160074. #ifdef JMAKE_ENUM_LIST
  160075. JMSG_LASTMSGCODE
  160076. } J_MESSAGE_CODE;
  160077. #undef JMAKE_ENUM_LIST
  160078. #endif /* JMAKE_ENUM_LIST */
  160079. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160080. #undef JMESSAGE
  160081. #ifndef JERROR_H
  160082. #define JERROR_H
  160083. /* Macros to simplify using the error and trace message stuff */
  160084. /* The first parameter is either type of cinfo pointer */
  160085. /* Fatal errors (print message and exit) */
  160086. #define ERREXIT(cinfo,code) \
  160087. ((cinfo)->err->msg_code = (code), \
  160088. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160089. #define ERREXIT1(cinfo,code,p1) \
  160090. ((cinfo)->err->msg_code = (code), \
  160091. (cinfo)->err->msg_parm.i[0] = (p1), \
  160092. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160093. #define ERREXIT2(cinfo,code,p1,p2) \
  160094. ((cinfo)->err->msg_code = (code), \
  160095. (cinfo)->err->msg_parm.i[0] = (p1), \
  160096. (cinfo)->err->msg_parm.i[1] = (p2), \
  160097. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160098. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160099. ((cinfo)->err->msg_code = (code), \
  160100. (cinfo)->err->msg_parm.i[0] = (p1), \
  160101. (cinfo)->err->msg_parm.i[1] = (p2), \
  160102. (cinfo)->err->msg_parm.i[2] = (p3), \
  160103. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160104. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160105. ((cinfo)->err->msg_code = (code), \
  160106. (cinfo)->err->msg_parm.i[0] = (p1), \
  160107. (cinfo)->err->msg_parm.i[1] = (p2), \
  160108. (cinfo)->err->msg_parm.i[2] = (p3), \
  160109. (cinfo)->err->msg_parm.i[3] = (p4), \
  160110. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160111. #define ERREXITS(cinfo,code,str) \
  160112. ((cinfo)->err->msg_code = (code), \
  160113. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160114. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160115. #define MAKESTMT(stuff) do { stuff } while (0)
  160116. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160117. #define WARNMS(cinfo,code) \
  160118. ((cinfo)->err->msg_code = (code), \
  160119. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160120. #define WARNMS1(cinfo,code,p1) \
  160121. ((cinfo)->err->msg_code = (code), \
  160122. (cinfo)->err->msg_parm.i[0] = (p1), \
  160123. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160124. #define WARNMS2(cinfo,code,p1,p2) \
  160125. ((cinfo)->err->msg_code = (code), \
  160126. (cinfo)->err->msg_parm.i[0] = (p1), \
  160127. (cinfo)->err->msg_parm.i[1] = (p2), \
  160128. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160129. /* Informational/debugging messages */
  160130. #define TRACEMS(cinfo,lvl,code) \
  160131. ((cinfo)->err->msg_code = (code), \
  160132. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160133. #define TRACEMS1(cinfo,lvl,code,p1) \
  160134. ((cinfo)->err->msg_code = (code), \
  160135. (cinfo)->err->msg_parm.i[0] = (p1), \
  160136. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160137. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  160138. ((cinfo)->err->msg_code = (code), \
  160139. (cinfo)->err->msg_parm.i[0] = (p1), \
  160140. (cinfo)->err->msg_parm.i[1] = (p2), \
  160141. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160142. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  160143. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160144. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  160145. (cinfo)->err->msg_code = (code); \
  160146. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160147. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  160148. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160149. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160150. (cinfo)->err->msg_code = (code); \
  160151. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160152. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  160153. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160154. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160155. _mp[4] = (p5); \
  160156. (cinfo)->err->msg_code = (code); \
  160157. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160158. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  160159. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160160. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160161. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  160162. (cinfo)->err->msg_code = (code); \
  160163. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160164. #define TRACEMSS(cinfo,lvl,code,str) \
  160165. ((cinfo)->err->msg_code = (code), \
  160166. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160167. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160168. #endif /* JERROR_H */
  160169. /*** End of inlined file: jerror.h ***/
  160170. /* fetch error codes too */
  160171. #endif
  160172. #endif /* JPEGLIB_H */
  160173. /*** End of inlined file: jpeglib.h ***/
  160174. /*** Start of inlined file: jcapimin.c ***/
  160175. #define JPEG_INTERNALS
  160176. /*** Start of inlined file: jinclude.h ***/
  160177. /* Include auto-config file to find out which system include files we need. */
  160178. #ifndef __jinclude_h__
  160179. #define __jinclude_h__
  160180. /*** Start of inlined file: jconfig.h ***/
  160181. /* see jconfig.doc for explanations */
  160182. // disable all the warnings under MSVC
  160183. #ifdef _MSC_VER
  160184. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  160185. #endif
  160186. #ifdef __BORLANDC__
  160187. #pragma warn -8057
  160188. #pragma warn -8019
  160189. #pragma warn -8004
  160190. #pragma warn -8008
  160191. #endif
  160192. #define HAVE_PROTOTYPES
  160193. #define HAVE_UNSIGNED_CHAR
  160194. #define HAVE_UNSIGNED_SHORT
  160195. /* #define void char */
  160196. /* #define const */
  160197. #undef CHAR_IS_UNSIGNED
  160198. #define HAVE_STDDEF_H
  160199. #define HAVE_STDLIB_H
  160200. #undef NEED_BSD_STRINGS
  160201. #undef NEED_SYS_TYPES_H
  160202. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  160203. #undef NEED_SHORT_EXTERNAL_NAMES
  160204. #undef INCOMPLETE_TYPES_BROKEN
  160205. /* Define "boolean" as unsigned char, not int, per Windows custom */
  160206. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  160207. typedef unsigned char boolean;
  160208. #endif
  160209. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  160210. #ifdef JPEG_INTERNALS
  160211. #undef RIGHT_SHIFT_IS_UNSIGNED
  160212. #endif /* JPEG_INTERNALS */
  160213. #ifdef JPEG_CJPEG_DJPEG
  160214. #define BMP_SUPPORTED /* BMP image file format */
  160215. #define GIF_SUPPORTED /* GIF image file format */
  160216. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  160217. #undef RLE_SUPPORTED /* Utah RLE image file format */
  160218. #define TARGA_SUPPORTED /* Targa image file format */
  160219. #define TWO_FILE_COMMANDLINE /* optional */
  160220. #define USE_SETMODE /* Microsoft has setmode() */
  160221. #undef NEED_SIGNAL_CATCHER
  160222. #undef DONT_USE_B_MODE
  160223. #undef PROGRESS_REPORT /* optional */
  160224. #endif /* JPEG_CJPEG_DJPEG */
  160225. /*** End of inlined file: jconfig.h ***/
  160226. /* auto configuration options */
  160227. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  160228. /*
  160229. * We need the NULL macro and size_t typedef.
  160230. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  160231. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  160232. * pull in <sys/types.h> as well.
  160233. * Note that the core JPEG library does not require <stdio.h>;
  160234. * only the default error handler and data source/destination modules do.
  160235. * But we must pull it in because of the references to FILE in jpeglib.h.
  160236. * You can remove those references if you want to compile without <stdio.h>.
  160237. */
  160238. #ifdef HAVE_STDDEF_H
  160239. #include <stddef.h>
  160240. #endif
  160241. #ifdef HAVE_STDLIB_H
  160242. #include <stdlib.h>
  160243. #endif
  160244. #ifdef NEED_SYS_TYPES_H
  160245. #include <sys/types.h>
  160246. #endif
  160247. #include <stdio.h>
  160248. /*
  160249. * We need memory copying and zeroing functions, plus strncpy().
  160250. * ANSI and System V implementations declare these in <string.h>.
  160251. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  160252. * Some systems may declare memset and memcpy in <memory.h>.
  160253. *
  160254. * NOTE: we assume the size parameters to these functions are of type size_t.
  160255. * Change the casts in these macros if not!
  160256. */
  160257. #ifdef NEED_BSD_STRINGS
  160258. #include <strings.h>
  160259. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  160260. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  160261. #else /* not BSD, assume ANSI/SysV string lib */
  160262. #include <string.h>
  160263. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  160264. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  160265. #endif
  160266. /*
  160267. * In ANSI C, and indeed any rational implementation, size_t is also the
  160268. * type returned by sizeof(). However, it seems there are some irrational
  160269. * implementations out there, in which sizeof() returns an int even though
  160270. * size_t is defined as long or unsigned long. To ensure consistent results
  160271. * we always use this SIZEOF() macro in place of using sizeof() directly.
  160272. */
  160273. #define SIZEOF(object) ((size_t) sizeof(object))
  160274. /*
  160275. * The modules that use fread() and fwrite() always invoke them through
  160276. * these macros. On some systems you may need to twiddle the argument casts.
  160277. * CAUTION: argument order is different from underlying functions!
  160278. */
  160279. #define JFREAD(file,buf,sizeofbuf) \
  160280. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160281. #define JFWRITE(file,buf,sizeofbuf) \
  160282. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160283. typedef enum { /* JPEG marker codes */
  160284. M_SOF0 = 0xc0,
  160285. M_SOF1 = 0xc1,
  160286. M_SOF2 = 0xc2,
  160287. M_SOF3 = 0xc3,
  160288. M_SOF5 = 0xc5,
  160289. M_SOF6 = 0xc6,
  160290. M_SOF7 = 0xc7,
  160291. M_JPG = 0xc8,
  160292. M_SOF9 = 0xc9,
  160293. M_SOF10 = 0xca,
  160294. M_SOF11 = 0xcb,
  160295. M_SOF13 = 0xcd,
  160296. M_SOF14 = 0xce,
  160297. M_SOF15 = 0xcf,
  160298. M_DHT = 0xc4,
  160299. M_DAC = 0xcc,
  160300. M_RST0 = 0xd0,
  160301. M_RST1 = 0xd1,
  160302. M_RST2 = 0xd2,
  160303. M_RST3 = 0xd3,
  160304. M_RST4 = 0xd4,
  160305. M_RST5 = 0xd5,
  160306. M_RST6 = 0xd6,
  160307. M_RST7 = 0xd7,
  160308. M_SOI = 0xd8,
  160309. M_EOI = 0xd9,
  160310. M_SOS = 0xda,
  160311. M_DQT = 0xdb,
  160312. M_DNL = 0xdc,
  160313. M_DRI = 0xdd,
  160314. M_DHP = 0xde,
  160315. M_EXP = 0xdf,
  160316. M_APP0 = 0xe0,
  160317. M_APP1 = 0xe1,
  160318. M_APP2 = 0xe2,
  160319. M_APP3 = 0xe3,
  160320. M_APP4 = 0xe4,
  160321. M_APP5 = 0xe5,
  160322. M_APP6 = 0xe6,
  160323. M_APP7 = 0xe7,
  160324. M_APP8 = 0xe8,
  160325. M_APP9 = 0xe9,
  160326. M_APP10 = 0xea,
  160327. M_APP11 = 0xeb,
  160328. M_APP12 = 0xec,
  160329. M_APP13 = 0xed,
  160330. M_APP14 = 0xee,
  160331. M_APP15 = 0xef,
  160332. M_JPG0 = 0xf0,
  160333. M_JPG13 = 0xfd,
  160334. M_COM = 0xfe,
  160335. M_TEM = 0x01,
  160336. M_ERROR = 0x100
  160337. } JPEG_MARKER;
  160338. /*
  160339. * Figure F.12: extend sign bit.
  160340. * On some machines, a shift and add will be faster than a table lookup.
  160341. */
  160342. #ifdef AVOID_TABLES
  160343. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  160344. #else
  160345. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  160346. static const int extend_test[16] = /* entry n is 2**(n-1) */
  160347. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  160348. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  160349. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  160350. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  160351. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  160352. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  160353. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  160354. #endif /* AVOID_TABLES */
  160355. #endif
  160356. /*** End of inlined file: jinclude.h ***/
  160357. /*
  160358. * Initialization of a JPEG compression object.
  160359. * The error manager must already be set up (in case memory manager fails).
  160360. */
  160361. GLOBAL(void)
  160362. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  160363. {
  160364. int i;
  160365. /* Guard against version mismatches between library and caller. */
  160366. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  160367. if (version != JPEG_LIB_VERSION)
  160368. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  160369. if (structsize != SIZEOF(struct jpeg_compress_struct))
  160370. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  160371. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  160372. /* For debugging purposes, we zero the whole master structure.
  160373. * But the application has already set the err pointer, and may have set
  160374. * client_data, so we have to save and restore those fields.
  160375. * Note: if application hasn't set client_data, tools like Purify may
  160376. * complain here.
  160377. */
  160378. {
  160379. struct jpeg_error_mgr * err = cinfo->err;
  160380. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  160381. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  160382. cinfo->err = err;
  160383. cinfo->client_data = client_data;
  160384. }
  160385. cinfo->is_decompressor = FALSE;
  160386. /* Initialize a memory manager instance for this object */
  160387. jinit_memory_mgr((j_common_ptr) cinfo);
  160388. /* Zero out pointers to permanent structures. */
  160389. cinfo->progress = NULL;
  160390. cinfo->dest = NULL;
  160391. cinfo->comp_info = NULL;
  160392. for (i = 0; i < NUM_QUANT_TBLS; i++)
  160393. cinfo->quant_tbl_ptrs[i] = NULL;
  160394. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160395. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  160396. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  160397. }
  160398. cinfo->script_space = NULL;
  160399. cinfo->input_gamma = 1.0; /* in case application forgets */
  160400. /* OK, I'm ready */
  160401. cinfo->global_state = CSTATE_START;
  160402. }
  160403. /*
  160404. * Destruction of a JPEG compression object
  160405. */
  160406. GLOBAL(void)
  160407. jpeg_destroy_compress (j_compress_ptr cinfo)
  160408. {
  160409. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  160410. }
  160411. /*
  160412. * Abort processing of a JPEG compression operation,
  160413. * but don't destroy the object itself.
  160414. */
  160415. GLOBAL(void)
  160416. jpeg_abort_compress (j_compress_ptr cinfo)
  160417. {
  160418. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  160419. }
  160420. /*
  160421. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  160422. * Marks all currently defined tables as already written (if suppress)
  160423. * or not written (if !suppress). This will control whether they get emitted
  160424. * by a subsequent jpeg_start_compress call.
  160425. *
  160426. * This routine is exported for use by applications that want to produce
  160427. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  160428. * since it is called by jpeg_start_compress, we put it here --- otherwise
  160429. * jcparam.o would be linked whether the application used it or not.
  160430. */
  160431. GLOBAL(void)
  160432. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  160433. {
  160434. int i;
  160435. JQUANT_TBL * qtbl;
  160436. JHUFF_TBL * htbl;
  160437. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160438. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  160439. qtbl->sent_table = suppress;
  160440. }
  160441. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160442. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  160443. htbl->sent_table = suppress;
  160444. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  160445. htbl->sent_table = suppress;
  160446. }
  160447. }
  160448. /*
  160449. * Finish JPEG compression.
  160450. *
  160451. * If a multipass operating mode was selected, this may do a great deal of
  160452. * work including most of the actual output.
  160453. */
  160454. GLOBAL(void)
  160455. jpeg_finish_compress (j_compress_ptr cinfo)
  160456. {
  160457. JDIMENSION iMCU_row;
  160458. if (cinfo->global_state == CSTATE_SCANNING ||
  160459. cinfo->global_state == CSTATE_RAW_OK) {
  160460. /* Terminate first pass */
  160461. if (cinfo->next_scanline < cinfo->image_height)
  160462. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  160463. (*cinfo->master->finish_pass) (cinfo);
  160464. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  160465. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160466. /* Perform any remaining passes */
  160467. while (! cinfo->master->is_last_pass) {
  160468. (*cinfo->master->prepare_for_pass) (cinfo);
  160469. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  160470. if (cinfo->progress != NULL) {
  160471. cinfo->progress->pass_counter = (long) iMCU_row;
  160472. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  160473. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160474. }
  160475. /* We bypass the main controller and invoke coef controller directly;
  160476. * all work is being done from the coefficient buffer.
  160477. */
  160478. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  160479. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160480. }
  160481. (*cinfo->master->finish_pass) (cinfo);
  160482. }
  160483. /* Write EOI, do final cleanup */
  160484. (*cinfo->marker->write_file_trailer) (cinfo);
  160485. (*cinfo->dest->term_destination) (cinfo);
  160486. /* We can use jpeg_abort to release memory and reset global_state */
  160487. jpeg_abort((j_common_ptr) cinfo);
  160488. }
  160489. /*
  160490. * Write a special marker.
  160491. * This is only recommended for writing COM or APPn markers.
  160492. * Must be called after jpeg_start_compress() and before
  160493. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  160494. */
  160495. GLOBAL(void)
  160496. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  160497. const JOCTET *dataptr, unsigned int datalen)
  160498. {
  160499. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  160500. if (cinfo->next_scanline != 0 ||
  160501. (cinfo->global_state != CSTATE_SCANNING &&
  160502. cinfo->global_state != CSTATE_RAW_OK &&
  160503. cinfo->global_state != CSTATE_WRCOEFS))
  160504. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160505. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  160506. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  160507. while (datalen--) {
  160508. (*write_marker_byte) (cinfo, *dataptr);
  160509. dataptr++;
  160510. }
  160511. }
  160512. /* Same, but piecemeal. */
  160513. GLOBAL(void)
  160514. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160515. {
  160516. if (cinfo->next_scanline != 0 ||
  160517. (cinfo->global_state != CSTATE_SCANNING &&
  160518. cinfo->global_state != CSTATE_RAW_OK &&
  160519. cinfo->global_state != CSTATE_WRCOEFS))
  160520. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160521. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  160522. }
  160523. GLOBAL(void)
  160524. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  160525. {
  160526. (*cinfo->marker->write_marker_byte) (cinfo, val);
  160527. }
  160528. /*
  160529. * Alternate compression function: just write an abbreviated table file.
  160530. * Before calling this, all parameters and a data destination must be set up.
  160531. *
  160532. * To produce a pair of files containing abbreviated tables and abbreviated
  160533. * image data, one would proceed as follows:
  160534. *
  160535. * initialize JPEG object
  160536. * set JPEG parameters
  160537. * set destination to table file
  160538. * jpeg_write_tables(cinfo);
  160539. * set destination to image file
  160540. * jpeg_start_compress(cinfo, FALSE);
  160541. * write data...
  160542. * jpeg_finish_compress(cinfo);
  160543. *
  160544. * jpeg_write_tables has the side effect of marking all tables written
  160545. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  160546. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  160547. */
  160548. GLOBAL(void)
  160549. jpeg_write_tables (j_compress_ptr cinfo)
  160550. {
  160551. if (cinfo->global_state != CSTATE_START)
  160552. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160553. /* (Re)initialize error mgr and destination modules */
  160554. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160555. (*cinfo->dest->init_destination) (cinfo);
  160556. /* Initialize the marker writer ... bit of a crock to do it here. */
  160557. jinit_marker_writer(cinfo);
  160558. /* Write them tables! */
  160559. (*cinfo->marker->write_tables_only) (cinfo);
  160560. /* And clean up. */
  160561. (*cinfo->dest->term_destination) (cinfo);
  160562. /*
  160563. * In library releases up through v6a, we called jpeg_abort() here to free
  160564. * any working memory allocated by the destination manager and marker
  160565. * writer. Some applications had a problem with that: they allocated space
  160566. * of their own from the library memory manager, and didn't want it to go
  160567. * away during write_tables. So now we do nothing. This will cause a
  160568. * memory leak if an app calls write_tables repeatedly without doing a full
  160569. * compression cycle or otherwise resetting the JPEG object. However, that
  160570. * seems less bad than unexpectedly freeing memory in the normal case.
  160571. * An app that prefers the old behavior can call jpeg_abort for itself after
  160572. * each call to jpeg_write_tables().
  160573. */
  160574. }
  160575. /*** End of inlined file: jcapimin.c ***/
  160576. /*** Start of inlined file: jcapistd.c ***/
  160577. #define JPEG_INTERNALS
  160578. /*
  160579. * Compression initialization.
  160580. * Before calling this, all parameters and a data destination must be set up.
  160581. *
  160582. * We require a write_all_tables parameter as a failsafe check when writing
  160583. * multiple datastreams from the same compression object. Since prior runs
  160584. * will have left all the tables marked sent_table=TRUE, a subsequent run
  160585. * would emit an abbreviated stream (no tables) by default. This may be what
  160586. * is wanted, but for safety's sake it should not be the default behavior:
  160587. * programmers should have to make a deliberate choice to emit abbreviated
  160588. * images. Therefore the documentation and examples should encourage people
  160589. * to pass write_all_tables=TRUE; then it will take active thought to do the
  160590. * wrong thing.
  160591. */
  160592. GLOBAL(void)
  160593. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  160594. {
  160595. if (cinfo->global_state != CSTATE_START)
  160596. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160597. if (write_all_tables)
  160598. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  160599. /* (Re)initialize error mgr and destination modules */
  160600. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160601. (*cinfo->dest->init_destination) (cinfo);
  160602. /* Perform master selection of active modules */
  160603. jinit_compress_master(cinfo);
  160604. /* Set up for the first pass */
  160605. (*cinfo->master->prepare_for_pass) (cinfo);
  160606. /* Ready for application to drive first pass through jpeg_write_scanlines
  160607. * or jpeg_write_raw_data.
  160608. */
  160609. cinfo->next_scanline = 0;
  160610. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  160611. }
  160612. /*
  160613. * Write some scanlines of data to the JPEG compressor.
  160614. *
  160615. * The return value will be the number of lines actually written.
  160616. * This should be less than the supplied num_lines only in case that
  160617. * the data destination module has requested suspension of the compressor,
  160618. * or if more than image_height scanlines are passed in.
  160619. *
  160620. * Note: we warn about excess calls to jpeg_write_scanlines() since
  160621. * this likely signals an application programmer error. However,
  160622. * excess scanlines passed in the last valid call are *silently* ignored,
  160623. * so that the application need not adjust num_lines for end-of-image
  160624. * when using a multiple-scanline buffer.
  160625. */
  160626. GLOBAL(JDIMENSION)
  160627. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  160628. JDIMENSION num_lines)
  160629. {
  160630. JDIMENSION row_ctr, rows_left;
  160631. if (cinfo->global_state != CSTATE_SCANNING)
  160632. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160633. if (cinfo->next_scanline >= cinfo->image_height)
  160634. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160635. /* Call progress monitor hook if present */
  160636. if (cinfo->progress != NULL) {
  160637. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  160638. cinfo->progress->pass_limit = (long) cinfo->image_height;
  160639. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160640. }
  160641. /* Give master control module another chance if this is first call to
  160642. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  160643. * delayed so that application can write COM, etc, markers between
  160644. * jpeg_start_compress and jpeg_write_scanlines.
  160645. */
  160646. if (cinfo->master->call_pass_startup)
  160647. (*cinfo->master->pass_startup) (cinfo);
  160648. /* Ignore any extra scanlines at bottom of image. */
  160649. rows_left = cinfo->image_height - cinfo->next_scanline;
  160650. if (num_lines > rows_left)
  160651. num_lines = rows_left;
  160652. row_ctr = 0;
  160653. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  160654. cinfo->next_scanline += row_ctr;
  160655. return row_ctr;
  160656. }
  160657. /*
  160658. * Alternate entry point to write raw data.
  160659. * Processes exactly one iMCU row per call, unless suspended.
  160660. */
  160661. GLOBAL(JDIMENSION)
  160662. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  160663. JDIMENSION num_lines)
  160664. {
  160665. JDIMENSION lines_per_iMCU_row;
  160666. if (cinfo->global_state != CSTATE_RAW_OK)
  160667. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160668. if (cinfo->next_scanline >= cinfo->image_height) {
  160669. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160670. return 0;
  160671. }
  160672. /* Call progress monitor hook if present */
  160673. if (cinfo->progress != NULL) {
  160674. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  160675. cinfo->progress->pass_limit = (long) cinfo->image_height;
  160676. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160677. }
  160678. /* Give master control module another chance if this is first call to
  160679. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  160680. * delayed so that application can write COM, etc, markers between
  160681. * jpeg_start_compress and jpeg_write_raw_data.
  160682. */
  160683. if (cinfo->master->call_pass_startup)
  160684. (*cinfo->master->pass_startup) (cinfo);
  160685. /* Verify that at least one iMCU row has been passed. */
  160686. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  160687. if (num_lines < lines_per_iMCU_row)
  160688. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  160689. /* Directly compress the row. */
  160690. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  160691. /* If compressor did not consume the whole row, suspend processing. */
  160692. return 0;
  160693. }
  160694. /* OK, we processed one iMCU row. */
  160695. cinfo->next_scanline += lines_per_iMCU_row;
  160696. return lines_per_iMCU_row;
  160697. }
  160698. /*** End of inlined file: jcapistd.c ***/
  160699. /*** Start of inlined file: jccoefct.c ***/
  160700. #define JPEG_INTERNALS
  160701. /* We use a full-image coefficient buffer when doing Huffman optimization,
  160702. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  160703. * step is run during the first pass, and subsequent passes need only read
  160704. * the buffered coefficients.
  160705. */
  160706. #ifdef ENTROPY_OPT_SUPPORTED
  160707. #define FULL_COEF_BUFFER_SUPPORTED
  160708. #else
  160709. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160710. #define FULL_COEF_BUFFER_SUPPORTED
  160711. #endif
  160712. #endif
  160713. /* Private buffer controller object */
  160714. typedef struct {
  160715. struct jpeg_c_coef_controller pub; /* public fields */
  160716. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  160717. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  160718. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  160719. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  160720. /* For single-pass compression, it's sufficient to buffer just one MCU
  160721. * (although this may prove a bit slow in practice). We allocate a
  160722. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  160723. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  160724. * it's not really very big; this is to keep the module interfaces unchanged
  160725. * when a large coefficient buffer is necessary.)
  160726. * In multi-pass modes, this array points to the current MCU's blocks
  160727. * within the virtual arrays.
  160728. */
  160729. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  160730. /* In multi-pass modes, we need a virtual block array for each component. */
  160731. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  160732. } my_coef_controller;
  160733. typedef my_coef_controller * my_coef_ptr;
  160734. /* Forward declarations */
  160735. METHODDEF(boolean) compress_data
  160736. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  160737. #ifdef FULL_COEF_BUFFER_SUPPORTED
  160738. METHODDEF(boolean) compress_first_pass
  160739. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  160740. METHODDEF(boolean) compress_output
  160741. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  160742. #endif
  160743. LOCAL(void)
  160744. start_iMCU_row (j_compress_ptr cinfo)
  160745. /* Reset within-iMCU-row counters for a new row */
  160746. {
  160747. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  160748. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  160749. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  160750. * But at the bottom of the image, process only what's left.
  160751. */
  160752. if (cinfo->comps_in_scan > 1) {
  160753. coef->MCU_rows_per_iMCU_row = 1;
  160754. } else {
  160755. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  160756. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  160757. else
  160758. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  160759. }
  160760. coef->mcu_ctr = 0;
  160761. coef->MCU_vert_offset = 0;
  160762. }
  160763. /*
  160764. * Initialize for a processing pass.
  160765. */
  160766. METHODDEF(void)
  160767. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  160768. {
  160769. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  160770. coef->iMCU_row_num = 0;
  160771. start_iMCU_row(cinfo);
  160772. switch (pass_mode) {
  160773. case JBUF_PASS_THRU:
  160774. if (coef->whole_image[0] != NULL)
  160775. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160776. coef->pub.compress_data = compress_data;
  160777. break;
  160778. #ifdef FULL_COEF_BUFFER_SUPPORTED
  160779. case JBUF_SAVE_AND_PASS:
  160780. if (coef->whole_image[0] == NULL)
  160781. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160782. coef->pub.compress_data = compress_first_pass;
  160783. break;
  160784. case JBUF_CRANK_DEST:
  160785. if (coef->whole_image[0] == NULL)
  160786. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160787. coef->pub.compress_data = compress_output;
  160788. break;
  160789. #endif
  160790. default:
  160791. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160792. break;
  160793. }
  160794. }
  160795. /*
  160796. * Process some data in the single-pass case.
  160797. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  160798. * per call, ie, v_samp_factor block rows for each component in the image.
  160799. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  160800. *
  160801. * NB: input_buf contains a plane for each component in image,
  160802. * which we index according to the component's SOF position.
  160803. */
  160804. METHODDEF(boolean)
  160805. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  160806. {
  160807. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  160808. JDIMENSION MCU_col_num; /* index of current MCU within row */
  160809. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  160810. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  160811. int blkn, bi, ci, yindex, yoffset, blockcnt;
  160812. JDIMENSION ypos, xpos;
  160813. jpeg_component_info *compptr;
  160814. /* Loop to write as much as one whole iMCU row */
  160815. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  160816. yoffset++) {
  160817. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  160818. MCU_col_num++) {
  160819. /* Determine where data comes from in input_buf and do the DCT thing.
  160820. * Each call on forward_DCT processes a horizontal row of DCT blocks
  160821. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  160822. * sequentially. Dummy blocks at the right or bottom edge are filled in
  160823. * specially. The data in them does not matter for image reconstruction,
  160824. * so we fill them with values that will encode to the smallest amount of
  160825. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  160826. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  160827. */
  160828. blkn = 0;
  160829. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160830. compptr = cinfo->cur_comp_info[ci];
  160831. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  160832. : compptr->last_col_width;
  160833. xpos = MCU_col_num * compptr->MCU_sample_width;
  160834. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  160835. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  160836. if (coef->iMCU_row_num < last_iMCU_row ||
  160837. yoffset+yindex < compptr->last_row_height) {
  160838. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  160839. input_buf[compptr->component_index],
  160840. coef->MCU_buffer[blkn],
  160841. ypos, xpos, (JDIMENSION) blockcnt);
  160842. if (blockcnt < compptr->MCU_width) {
  160843. /* Create some dummy blocks at the right edge of the image. */
  160844. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  160845. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  160846. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  160847. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  160848. }
  160849. }
  160850. } else {
  160851. /* Create a row of dummy blocks at the bottom of the image. */
  160852. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  160853. compptr->MCU_width * SIZEOF(JBLOCK));
  160854. for (bi = 0; bi < compptr->MCU_width; bi++) {
  160855. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  160856. }
  160857. }
  160858. blkn += compptr->MCU_width;
  160859. ypos += DCTSIZE;
  160860. }
  160861. }
  160862. /* Try to write the MCU. In event of a suspension failure, we will
  160863. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  160864. */
  160865. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  160866. /* Suspension forced; update state counters and exit */
  160867. coef->MCU_vert_offset = yoffset;
  160868. coef->mcu_ctr = MCU_col_num;
  160869. return FALSE;
  160870. }
  160871. }
  160872. /* Completed an MCU row, but perhaps not an iMCU row */
  160873. coef->mcu_ctr = 0;
  160874. }
  160875. /* Completed the iMCU row, advance counters for next one */
  160876. coef->iMCU_row_num++;
  160877. start_iMCU_row(cinfo);
  160878. return TRUE;
  160879. }
  160880. #ifdef FULL_COEF_BUFFER_SUPPORTED
  160881. /*
  160882. * Process some data in the first pass of a multi-pass case.
  160883. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  160884. * per call, ie, v_samp_factor block rows for each component in the image.
  160885. * This amount of data is read from the source buffer, DCT'd and quantized,
  160886. * and saved into the virtual arrays. We also generate suitable dummy blocks
  160887. * as needed at the right and lower edges. (The dummy blocks are constructed
  160888. * in the virtual arrays, which have been padded appropriately.) This makes
  160889. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  160890. *
  160891. * We must also emit the data to the entropy encoder. This is conveniently
  160892. * done by calling compress_output() after we've loaded the current strip
  160893. * of the virtual arrays.
  160894. *
  160895. * NB: input_buf contains a plane for each component in image. All
  160896. * components are DCT'd and loaded into the virtual arrays in this pass.
  160897. * However, it may be that only a subset of the components are emitted to
  160898. * the entropy encoder during this first pass; be careful about looking
  160899. * at the scan-dependent variables (MCU dimensions, etc).
  160900. */
  160901. METHODDEF(boolean)
  160902. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  160903. {
  160904. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  160905. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  160906. JDIMENSION blocks_across, MCUs_across, MCUindex;
  160907. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  160908. JCOEF lastDC;
  160909. jpeg_component_info *compptr;
  160910. JBLOCKARRAY buffer;
  160911. JBLOCKROW thisblockrow, lastblockrow;
  160912. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160913. ci++, compptr++) {
  160914. /* Align the virtual buffer for this component. */
  160915. buffer = (*cinfo->mem->access_virt_barray)
  160916. ((j_common_ptr) cinfo, coef->whole_image[ci],
  160917. coef->iMCU_row_num * compptr->v_samp_factor,
  160918. (JDIMENSION) compptr->v_samp_factor, TRUE);
  160919. /* Count non-dummy DCT block rows in this iMCU row. */
  160920. if (coef->iMCU_row_num < last_iMCU_row)
  160921. block_rows = compptr->v_samp_factor;
  160922. else {
  160923. /* NB: can't use last_row_height here, since may not be set! */
  160924. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  160925. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  160926. }
  160927. blocks_across = compptr->width_in_blocks;
  160928. h_samp_factor = compptr->h_samp_factor;
  160929. /* Count number of dummy blocks to be added at the right margin. */
  160930. ndummy = (int) (blocks_across % h_samp_factor);
  160931. if (ndummy > 0)
  160932. ndummy = h_samp_factor - ndummy;
  160933. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  160934. * on forward_DCT processes a complete horizontal row of DCT blocks.
  160935. */
  160936. for (block_row = 0; block_row < block_rows; block_row++) {
  160937. thisblockrow = buffer[block_row];
  160938. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  160939. input_buf[ci], thisblockrow,
  160940. (JDIMENSION) (block_row * DCTSIZE),
  160941. (JDIMENSION) 0, blocks_across);
  160942. if (ndummy > 0) {
  160943. /* Create dummy blocks at the right edge of the image. */
  160944. thisblockrow += blocks_across; /* => first dummy block */
  160945. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  160946. lastDC = thisblockrow[-1][0];
  160947. for (bi = 0; bi < ndummy; bi++) {
  160948. thisblockrow[bi][0] = lastDC;
  160949. }
  160950. }
  160951. }
  160952. /* If at end of image, create dummy block rows as needed.
  160953. * The tricky part here is that within each MCU, we want the DC values
  160954. * of the dummy blocks to match the last real block's DC value.
  160955. * This squeezes a few more bytes out of the resulting file...
  160956. */
  160957. if (coef->iMCU_row_num == last_iMCU_row) {
  160958. blocks_across += ndummy; /* include lower right corner */
  160959. MCUs_across = blocks_across / h_samp_factor;
  160960. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  160961. block_row++) {
  160962. thisblockrow = buffer[block_row];
  160963. lastblockrow = buffer[block_row-1];
  160964. jzero_far((void FAR *) thisblockrow,
  160965. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  160966. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  160967. lastDC = lastblockrow[h_samp_factor-1][0];
  160968. for (bi = 0; bi < h_samp_factor; bi++) {
  160969. thisblockrow[bi][0] = lastDC;
  160970. }
  160971. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  160972. lastblockrow += h_samp_factor;
  160973. }
  160974. }
  160975. }
  160976. }
  160977. /* NB: compress_output will increment iMCU_row_num if successful.
  160978. * A suspension return will result in redoing all the work above next time.
  160979. */
  160980. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  160981. return compress_output(cinfo, input_buf);
  160982. }
  160983. /*
  160984. * Process some data in subsequent passes of a multi-pass case.
  160985. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  160986. * per call, ie, v_samp_factor block rows for each component in the scan.
  160987. * The data is obtained from the virtual arrays and fed to the entropy coder.
  160988. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  160989. *
  160990. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  160991. */
  160992. METHODDEF(boolean)
  160993. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  160994. {
  160995. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  160996. JDIMENSION MCU_col_num; /* index of current MCU within row */
  160997. int blkn, ci, xindex, yindex, yoffset;
  160998. JDIMENSION start_col;
  160999. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161000. JBLOCKROW buffer_ptr;
  161001. jpeg_component_info *compptr;
  161002. /* Align the virtual buffers for the components used in this scan.
  161003. * NB: during first pass, this is safe only because the buffers will
  161004. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161005. */
  161006. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161007. compptr = cinfo->cur_comp_info[ci];
  161008. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161009. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161010. coef->iMCU_row_num * compptr->v_samp_factor,
  161011. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161012. }
  161013. /* Loop to process one whole iMCU row */
  161014. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161015. yoffset++) {
  161016. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161017. MCU_col_num++) {
  161018. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161019. blkn = 0; /* index of current DCT block within MCU */
  161020. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161021. compptr = cinfo->cur_comp_info[ci];
  161022. start_col = MCU_col_num * compptr->MCU_width;
  161023. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161024. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161025. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161026. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161027. }
  161028. }
  161029. }
  161030. /* Try to write the MCU. */
  161031. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161032. /* Suspension forced; update state counters and exit */
  161033. coef->MCU_vert_offset = yoffset;
  161034. coef->mcu_ctr = MCU_col_num;
  161035. return FALSE;
  161036. }
  161037. }
  161038. /* Completed an MCU row, but perhaps not an iMCU row */
  161039. coef->mcu_ctr = 0;
  161040. }
  161041. /* Completed the iMCU row, advance counters for next one */
  161042. coef->iMCU_row_num++;
  161043. start_iMCU_row(cinfo);
  161044. return TRUE;
  161045. }
  161046. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161047. /*
  161048. * Initialize coefficient buffer controller.
  161049. */
  161050. GLOBAL(void)
  161051. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161052. {
  161053. my_coef_ptr coef;
  161054. coef = (my_coef_ptr)
  161055. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161056. SIZEOF(my_coef_controller));
  161057. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161058. coef->pub.start_pass = start_pass_coef;
  161059. /* Create the coefficient buffer. */
  161060. if (need_full_buffer) {
  161061. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161062. /* Allocate a full-image virtual array for each component, */
  161063. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161064. int ci;
  161065. jpeg_component_info *compptr;
  161066. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161067. ci++, compptr++) {
  161068. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161069. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161070. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161071. (long) compptr->h_samp_factor),
  161072. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161073. (long) compptr->v_samp_factor),
  161074. (JDIMENSION) compptr->v_samp_factor);
  161075. }
  161076. #else
  161077. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161078. #endif
  161079. } else {
  161080. /* We only need a single-MCU buffer. */
  161081. JBLOCKROW buffer;
  161082. int i;
  161083. buffer = (JBLOCKROW)
  161084. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161085. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161086. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161087. coef->MCU_buffer[i] = buffer + i;
  161088. }
  161089. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161090. }
  161091. }
  161092. /*** End of inlined file: jccoefct.c ***/
  161093. /*** Start of inlined file: jccolor.c ***/
  161094. #define JPEG_INTERNALS
  161095. /* Private subobject */
  161096. typedef struct {
  161097. struct jpeg_color_converter pub; /* public fields */
  161098. /* Private state for RGB->YCC conversion */
  161099. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161100. } my_color_converter;
  161101. typedef my_color_converter * my_cconvert_ptr;
  161102. /**************** RGB -> YCbCr conversion: most common case **************/
  161103. /*
  161104. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161105. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161106. * The conversion equations to be implemented are therefore
  161107. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161108. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161109. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161110. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161111. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161112. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161113. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161114. * were not represented exactly. Now we sacrifice exact representation of
  161115. * maximum red and maximum blue in order to get exact grayscales.
  161116. *
  161117. * To avoid floating-point arithmetic, we represent the fractional constants
  161118. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161119. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161120. *
  161121. * For even more speed, we avoid doing any multiplications in the inner loop
  161122. * by precalculating the constants times R,G,B for all possible values.
  161123. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161124. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161125. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161126. * colorspace anyway.
  161127. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161128. * in the tables to save adding them separately in the inner loop.
  161129. */
  161130. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161131. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161132. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161133. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161134. /* We allocate one big table and divide it up into eight parts, instead of
  161135. * doing eight alloc_small requests. This lets us use a single table base
  161136. * address, which can be held in a register in the inner loops on many
  161137. * machines (more than can hold all eight addresses, anyway).
  161138. */
  161139. #define R_Y_OFF 0 /* offset to R => Y section */
  161140. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  161141. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  161142. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  161143. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  161144. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  161145. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  161146. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  161147. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  161148. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  161149. /*
  161150. * Initialize for RGB->YCC colorspace conversion.
  161151. */
  161152. METHODDEF(void)
  161153. rgb_ycc_start (j_compress_ptr cinfo)
  161154. {
  161155. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161156. INT32 * rgb_ycc_tab;
  161157. INT32 i;
  161158. /* Allocate and fill in the conversion tables. */
  161159. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  161160. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161161. (TABLE_SIZE * SIZEOF(INT32)));
  161162. for (i = 0; i <= MAXJSAMPLE; i++) {
  161163. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  161164. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  161165. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  161166. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  161167. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  161168. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  161169. * This ensures that the maximum output will round to MAXJSAMPLE
  161170. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  161171. */
  161172. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161173. /* B=>Cb and R=>Cr tables are the same
  161174. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161175. */
  161176. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  161177. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  161178. }
  161179. }
  161180. /*
  161181. * Convert some rows of samples to the JPEG colorspace.
  161182. *
  161183. * Note that we change from the application's interleaved-pixel format
  161184. * to our internal noninterleaved, one-plane-per-component format.
  161185. * The input buffer is therefore three times as wide as the output buffer.
  161186. *
  161187. * A starting row offset is provided only for the output buffer. The caller
  161188. * can easily adjust the passed input_buf value to accommodate any row
  161189. * offset required on that side.
  161190. */
  161191. METHODDEF(void)
  161192. rgb_ycc_convert (j_compress_ptr cinfo,
  161193. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161194. JDIMENSION output_row, int num_rows)
  161195. {
  161196. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161197. register int r, g, b;
  161198. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161199. register JSAMPROW inptr;
  161200. register JSAMPROW outptr0, outptr1, outptr2;
  161201. register JDIMENSION col;
  161202. JDIMENSION num_cols = cinfo->image_width;
  161203. while (--num_rows >= 0) {
  161204. inptr = *input_buf++;
  161205. outptr0 = output_buf[0][output_row];
  161206. outptr1 = output_buf[1][output_row];
  161207. outptr2 = output_buf[2][output_row];
  161208. output_row++;
  161209. for (col = 0; col < num_cols; col++) {
  161210. r = GETJSAMPLE(inptr[RGB_RED]);
  161211. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161212. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161213. inptr += RGB_PIXELSIZE;
  161214. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161215. * must be too; we do not need an explicit range-limiting operation.
  161216. * Hence the value being shifted is never negative, and we don't
  161217. * need the general RIGHT_SHIFT macro.
  161218. */
  161219. /* Y */
  161220. outptr0[col] = (JSAMPLE)
  161221. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161222. >> SCALEBITS);
  161223. /* Cb */
  161224. outptr1[col] = (JSAMPLE)
  161225. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161226. >> SCALEBITS);
  161227. /* Cr */
  161228. outptr2[col] = (JSAMPLE)
  161229. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161230. >> SCALEBITS);
  161231. }
  161232. }
  161233. }
  161234. /**************** Cases other than RGB -> YCbCr **************/
  161235. /*
  161236. * Convert some rows of samples to the JPEG colorspace.
  161237. * This version handles RGB->grayscale conversion, which is the same
  161238. * as the RGB->Y portion of RGB->YCbCr.
  161239. * We assume rgb_ycc_start has been called (we only use the Y tables).
  161240. */
  161241. METHODDEF(void)
  161242. rgb_gray_convert (j_compress_ptr cinfo,
  161243. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161244. JDIMENSION output_row, int num_rows)
  161245. {
  161246. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161247. register int r, g, b;
  161248. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161249. register JSAMPROW inptr;
  161250. register JSAMPROW outptr;
  161251. register JDIMENSION col;
  161252. JDIMENSION num_cols = cinfo->image_width;
  161253. while (--num_rows >= 0) {
  161254. inptr = *input_buf++;
  161255. outptr = output_buf[0][output_row];
  161256. output_row++;
  161257. for (col = 0; col < num_cols; col++) {
  161258. r = GETJSAMPLE(inptr[RGB_RED]);
  161259. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161260. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161261. inptr += RGB_PIXELSIZE;
  161262. /* Y */
  161263. outptr[col] = (JSAMPLE)
  161264. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161265. >> SCALEBITS);
  161266. }
  161267. }
  161268. }
  161269. /*
  161270. * Convert some rows of samples to the JPEG colorspace.
  161271. * This version handles Adobe-style CMYK->YCCK conversion,
  161272. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  161273. * conversion as above, while passing K (black) unchanged.
  161274. * We assume rgb_ycc_start has been called.
  161275. */
  161276. METHODDEF(void)
  161277. cmyk_ycck_convert (j_compress_ptr cinfo,
  161278. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161279. JDIMENSION output_row, int num_rows)
  161280. {
  161281. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161282. register int r, g, b;
  161283. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161284. register JSAMPROW inptr;
  161285. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  161286. register JDIMENSION col;
  161287. JDIMENSION num_cols = cinfo->image_width;
  161288. while (--num_rows >= 0) {
  161289. inptr = *input_buf++;
  161290. outptr0 = output_buf[0][output_row];
  161291. outptr1 = output_buf[1][output_row];
  161292. outptr2 = output_buf[2][output_row];
  161293. outptr3 = output_buf[3][output_row];
  161294. output_row++;
  161295. for (col = 0; col < num_cols; col++) {
  161296. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  161297. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  161298. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  161299. /* K passes through as-is */
  161300. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  161301. inptr += 4;
  161302. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161303. * must be too; we do not need an explicit range-limiting operation.
  161304. * Hence the value being shifted is never negative, and we don't
  161305. * need the general RIGHT_SHIFT macro.
  161306. */
  161307. /* Y */
  161308. outptr0[col] = (JSAMPLE)
  161309. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161310. >> SCALEBITS);
  161311. /* Cb */
  161312. outptr1[col] = (JSAMPLE)
  161313. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161314. >> SCALEBITS);
  161315. /* Cr */
  161316. outptr2[col] = (JSAMPLE)
  161317. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161318. >> SCALEBITS);
  161319. }
  161320. }
  161321. }
  161322. /*
  161323. * Convert some rows of samples to the JPEG colorspace.
  161324. * This version handles grayscale output with no conversion.
  161325. * The source can be either plain grayscale or YCbCr (since Y == gray).
  161326. */
  161327. METHODDEF(void)
  161328. grayscale_convert (j_compress_ptr cinfo,
  161329. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161330. JDIMENSION output_row, int num_rows)
  161331. {
  161332. register JSAMPROW inptr;
  161333. register JSAMPROW outptr;
  161334. register JDIMENSION col;
  161335. JDIMENSION num_cols = cinfo->image_width;
  161336. int instride = cinfo->input_components;
  161337. while (--num_rows >= 0) {
  161338. inptr = *input_buf++;
  161339. outptr = output_buf[0][output_row];
  161340. output_row++;
  161341. for (col = 0; col < num_cols; col++) {
  161342. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  161343. inptr += instride;
  161344. }
  161345. }
  161346. }
  161347. /*
  161348. * Convert some rows of samples to the JPEG colorspace.
  161349. * This version handles multi-component colorspaces without conversion.
  161350. * We assume input_components == num_components.
  161351. */
  161352. METHODDEF(void)
  161353. null_convert (j_compress_ptr cinfo,
  161354. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161355. JDIMENSION output_row, int num_rows)
  161356. {
  161357. register JSAMPROW inptr;
  161358. register JSAMPROW outptr;
  161359. register JDIMENSION col;
  161360. register int ci;
  161361. int nc = cinfo->num_components;
  161362. JDIMENSION num_cols = cinfo->image_width;
  161363. while (--num_rows >= 0) {
  161364. /* It seems fastest to make a separate pass for each component. */
  161365. for (ci = 0; ci < nc; ci++) {
  161366. inptr = *input_buf;
  161367. outptr = output_buf[ci][output_row];
  161368. for (col = 0; col < num_cols; col++) {
  161369. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  161370. inptr += nc;
  161371. }
  161372. }
  161373. input_buf++;
  161374. output_row++;
  161375. }
  161376. }
  161377. /*
  161378. * Empty method for start_pass.
  161379. */
  161380. METHODDEF(void)
  161381. null_method (j_compress_ptr)
  161382. {
  161383. /* no work needed */
  161384. }
  161385. /*
  161386. * Module initialization routine for input colorspace conversion.
  161387. */
  161388. GLOBAL(void)
  161389. jinit_color_converter (j_compress_ptr cinfo)
  161390. {
  161391. my_cconvert_ptr cconvert;
  161392. cconvert = (my_cconvert_ptr)
  161393. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161394. SIZEOF(my_color_converter));
  161395. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  161396. /* set start_pass to null method until we find out differently */
  161397. cconvert->pub.start_pass = null_method;
  161398. /* Make sure input_components agrees with in_color_space */
  161399. switch (cinfo->in_color_space) {
  161400. case JCS_GRAYSCALE:
  161401. if (cinfo->input_components != 1)
  161402. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161403. break;
  161404. case JCS_RGB:
  161405. #if RGB_PIXELSIZE != 3
  161406. if (cinfo->input_components != RGB_PIXELSIZE)
  161407. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161408. break;
  161409. #endif /* else share code with YCbCr */
  161410. case JCS_YCbCr:
  161411. if (cinfo->input_components != 3)
  161412. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161413. break;
  161414. case JCS_CMYK:
  161415. case JCS_YCCK:
  161416. if (cinfo->input_components != 4)
  161417. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161418. break;
  161419. default: /* JCS_UNKNOWN can be anything */
  161420. if (cinfo->input_components < 1)
  161421. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161422. break;
  161423. }
  161424. /* Check num_components, set conversion method based on requested space */
  161425. switch (cinfo->jpeg_color_space) {
  161426. case JCS_GRAYSCALE:
  161427. if (cinfo->num_components != 1)
  161428. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161429. if (cinfo->in_color_space == JCS_GRAYSCALE)
  161430. cconvert->pub.color_convert = grayscale_convert;
  161431. else if (cinfo->in_color_space == JCS_RGB) {
  161432. cconvert->pub.start_pass = rgb_ycc_start;
  161433. cconvert->pub.color_convert = rgb_gray_convert;
  161434. } else if (cinfo->in_color_space == JCS_YCbCr)
  161435. cconvert->pub.color_convert = grayscale_convert;
  161436. else
  161437. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161438. break;
  161439. case JCS_RGB:
  161440. if (cinfo->num_components != 3)
  161441. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161442. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  161443. cconvert->pub.color_convert = null_convert;
  161444. else
  161445. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161446. break;
  161447. case JCS_YCbCr:
  161448. if (cinfo->num_components != 3)
  161449. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161450. if (cinfo->in_color_space == JCS_RGB) {
  161451. cconvert->pub.start_pass = rgb_ycc_start;
  161452. cconvert->pub.color_convert = rgb_ycc_convert;
  161453. } else if (cinfo->in_color_space == JCS_YCbCr)
  161454. cconvert->pub.color_convert = null_convert;
  161455. else
  161456. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161457. break;
  161458. case JCS_CMYK:
  161459. if (cinfo->num_components != 4)
  161460. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161461. if (cinfo->in_color_space == JCS_CMYK)
  161462. cconvert->pub.color_convert = null_convert;
  161463. else
  161464. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161465. break;
  161466. case JCS_YCCK:
  161467. if (cinfo->num_components != 4)
  161468. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161469. if (cinfo->in_color_space == JCS_CMYK) {
  161470. cconvert->pub.start_pass = rgb_ycc_start;
  161471. cconvert->pub.color_convert = cmyk_ycck_convert;
  161472. } else if (cinfo->in_color_space == JCS_YCCK)
  161473. cconvert->pub.color_convert = null_convert;
  161474. else
  161475. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161476. break;
  161477. default: /* allow null conversion of JCS_UNKNOWN */
  161478. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  161479. cinfo->num_components != cinfo->input_components)
  161480. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161481. cconvert->pub.color_convert = null_convert;
  161482. break;
  161483. }
  161484. }
  161485. /*** End of inlined file: jccolor.c ***/
  161486. #undef FIX
  161487. /*** Start of inlined file: jcdctmgr.c ***/
  161488. #define JPEG_INTERNALS
  161489. /*** Start of inlined file: jdct.h ***/
  161490. /*
  161491. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  161492. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  161493. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  161494. * implementations use an array of type FAST_FLOAT, instead.)
  161495. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  161496. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  161497. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  161498. * convention improves accuracy in integer implementations and saves some
  161499. * work in floating-point ones.
  161500. * Quantization of the output coefficients is done by jcdctmgr.c.
  161501. */
  161502. #ifndef __jdct_h__
  161503. #define __jdct_h__
  161504. #if BITS_IN_JSAMPLE == 8
  161505. typedef int DCTELEM; /* 16 or 32 bits is fine */
  161506. #else
  161507. typedef INT32 DCTELEM; /* must have 32 bits */
  161508. #endif
  161509. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  161510. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  161511. /*
  161512. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  161513. * to an output sample array. The routine must dequantize the input data as
  161514. * well as perform the IDCT; for dequantization, it uses the multiplier table
  161515. * pointed to by compptr->dct_table. The output data is to be placed into the
  161516. * sample array starting at a specified column. (Any row offset needed will
  161517. * be applied to the array pointer before it is passed to the IDCT code.)
  161518. * Note that the number of samples emitted by the IDCT routine is
  161519. * DCT_scaled_size * DCT_scaled_size.
  161520. */
  161521. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  161522. /*
  161523. * Each IDCT routine has its own ideas about the best dct_table element type.
  161524. */
  161525. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  161526. #if BITS_IN_JSAMPLE == 8
  161527. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  161528. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  161529. #else
  161530. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  161531. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  161532. #endif
  161533. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  161534. /*
  161535. * Each IDCT routine is responsible for range-limiting its results and
  161536. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  161537. * be quite far out of range if the input data is corrupt, so a bulletproof
  161538. * range-limiting step is required. We use a mask-and-table-lookup method
  161539. * to do the combined operations quickly. See the comments with
  161540. * prepare_range_limit_table (in jdmaster.c) for more info.
  161541. */
  161542. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  161543. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  161544. /* Short forms of external names for systems with brain-damaged linkers. */
  161545. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161546. #define jpeg_fdct_islow jFDislow
  161547. #define jpeg_fdct_ifast jFDifast
  161548. #define jpeg_fdct_float jFDfloat
  161549. #define jpeg_idct_islow jRDislow
  161550. #define jpeg_idct_ifast jRDifast
  161551. #define jpeg_idct_float jRDfloat
  161552. #define jpeg_idct_4x4 jRD4x4
  161553. #define jpeg_idct_2x2 jRD2x2
  161554. #define jpeg_idct_1x1 jRD1x1
  161555. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161556. /* Extern declarations for the forward and inverse DCT routines. */
  161557. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  161558. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  161559. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  161560. EXTERN(void) jpeg_idct_islow
  161561. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161562. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161563. EXTERN(void) jpeg_idct_ifast
  161564. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161565. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161566. EXTERN(void) jpeg_idct_float
  161567. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161568. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161569. EXTERN(void) jpeg_idct_4x4
  161570. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161571. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161572. EXTERN(void) jpeg_idct_2x2
  161573. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161574. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161575. EXTERN(void) jpeg_idct_1x1
  161576. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161577. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161578. /*
  161579. * Macros for handling fixed-point arithmetic; these are used by many
  161580. * but not all of the DCT/IDCT modules.
  161581. *
  161582. * All values are expected to be of type INT32.
  161583. * Fractional constants are scaled left by CONST_BITS bits.
  161584. * CONST_BITS is defined within each module using these macros,
  161585. * and may differ from one module to the next.
  161586. */
  161587. #define ONE ((INT32) 1)
  161588. #define CONST_SCALE (ONE << CONST_BITS)
  161589. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  161590. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  161591. * thus causing a lot of useless floating-point operations at run time.
  161592. */
  161593. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  161594. /* Descale and correctly round an INT32 value that's scaled by N bits.
  161595. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  161596. * the fudge factor is correct for either sign of X.
  161597. */
  161598. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  161599. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  161600. * This macro is used only when the two inputs will actually be no more than
  161601. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  161602. * full 32x32 multiply. This provides a useful speedup on many machines.
  161603. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  161604. * in C, but some C compilers will do the right thing if you provide the
  161605. * correct combination of casts.
  161606. */
  161607. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  161608. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  161609. #endif
  161610. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  161611. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  161612. #endif
  161613. #ifndef MULTIPLY16C16 /* default definition */
  161614. #define MULTIPLY16C16(var,const) ((var) * (const))
  161615. #endif
  161616. /* Same except both inputs are variables. */
  161617. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  161618. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  161619. #endif
  161620. #ifndef MULTIPLY16V16 /* default definition */
  161621. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  161622. #endif
  161623. #endif
  161624. /*** End of inlined file: jdct.h ***/
  161625. /* Private declarations for DCT subsystem */
  161626. /* Private subobject for this module */
  161627. typedef struct {
  161628. struct jpeg_forward_dct pub; /* public fields */
  161629. /* Pointer to the DCT routine actually in use */
  161630. forward_DCT_method_ptr do_dct;
  161631. /* The actual post-DCT divisors --- not identical to the quant table
  161632. * entries, because of scaling (especially for an unnormalized DCT).
  161633. * Each table is given in normal array order.
  161634. */
  161635. DCTELEM * divisors[NUM_QUANT_TBLS];
  161636. #ifdef DCT_FLOAT_SUPPORTED
  161637. /* Same as above for the floating-point case. */
  161638. float_DCT_method_ptr do_float_dct;
  161639. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  161640. #endif
  161641. } my_fdct_controller;
  161642. typedef my_fdct_controller * my_fdct_ptr;
  161643. /*
  161644. * Initialize for a processing pass.
  161645. * Verify that all referenced Q-tables are present, and set up
  161646. * the divisor table for each one.
  161647. * In the current implementation, DCT of all components is done during
  161648. * the first pass, even if only some components will be output in the
  161649. * first scan. Hence all components should be examined here.
  161650. */
  161651. METHODDEF(void)
  161652. start_pass_fdctmgr (j_compress_ptr cinfo)
  161653. {
  161654. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  161655. int ci, qtblno, i;
  161656. jpeg_component_info *compptr;
  161657. JQUANT_TBL * qtbl;
  161658. DCTELEM * dtbl;
  161659. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161660. ci++, compptr++) {
  161661. qtblno = compptr->quant_tbl_no;
  161662. /* Make sure specified quantization table is present */
  161663. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  161664. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  161665. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  161666. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  161667. /* Compute divisors for this quant table */
  161668. /* We may do this more than once for same table, but it's not a big deal */
  161669. switch (cinfo->dct_method) {
  161670. #ifdef DCT_ISLOW_SUPPORTED
  161671. case JDCT_ISLOW:
  161672. /* For LL&M IDCT method, divisors are equal to raw quantization
  161673. * coefficients multiplied by 8 (to counteract scaling).
  161674. */
  161675. if (fdct->divisors[qtblno] == NULL) {
  161676. fdct->divisors[qtblno] = (DCTELEM *)
  161677. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161678. DCTSIZE2 * SIZEOF(DCTELEM));
  161679. }
  161680. dtbl = fdct->divisors[qtblno];
  161681. for (i = 0; i < DCTSIZE2; i++) {
  161682. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  161683. }
  161684. break;
  161685. #endif
  161686. #ifdef DCT_IFAST_SUPPORTED
  161687. case JDCT_IFAST:
  161688. {
  161689. /* For AA&N IDCT method, divisors are equal to quantization
  161690. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  161691. * scalefactor[0] = 1
  161692. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  161693. * We apply a further scale factor of 8.
  161694. */
  161695. #define CONST_BITS 14
  161696. static const INT16 aanscales[DCTSIZE2] = {
  161697. /* precomputed values scaled up by 14 bits */
  161698. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  161699. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  161700. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  161701. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  161702. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  161703. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  161704. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  161705. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  161706. };
  161707. SHIFT_TEMPS
  161708. if (fdct->divisors[qtblno] == NULL) {
  161709. fdct->divisors[qtblno] = (DCTELEM *)
  161710. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161711. DCTSIZE2 * SIZEOF(DCTELEM));
  161712. }
  161713. dtbl = fdct->divisors[qtblno];
  161714. for (i = 0; i < DCTSIZE2; i++) {
  161715. dtbl[i] = (DCTELEM)
  161716. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  161717. (INT32) aanscales[i]),
  161718. CONST_BITS-3);
  161719. }
  161720. }
  161721. break;
  161722. #endif
  161723. #ifdef DCT_FLOAT_SUPPORTED
  161724. case JDCT_FLOAT:
  161725. {
  161726. /* For float AA&N IDCT method, divisors are equal to quantization
  161727. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  161728. * scalefactor[0] = 1
  161729. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  161730. * We apply a further scale factor of 8.
  161731. * What's actually stored is 1/divisor so that the inner loop can
  161732. * use a multiplication rather than a division.
  161733. */
  161734. FAST_FLOAT * fdtbl;
  161735. int row, col;
  161736. static const double aanscalefactor[DCTSIZE] = {
  161737. 1.0, 1.387039845, 1.306562965, 1.175875602,
  161738. 1.0, 0.785694958, 0.541196100, 0.275899379
  161739. };
  161740. if (fdct->float_divisors[qtblno] == NULL) {
  161741. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  161742. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161743. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  161744. }
  161745. fdtbl = fdct->float_divisors[qtblno];
  161746. i = 0;
  161747. for (row = 0; row < DCTSIZE; row++) {
  161748. for (col = 0; col < DCTSIZE; col++) {
  161749. fdtbl[i] = (FAST_FLOAT)
  161750. (1.0 / (((double) qtbl->quantval[i] *
  161751. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  161752. i++;
  161753. }
  161754. }
  161755. }
  161756. break;
  161757. #endif
  161758. default:
  161759. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161760. break;
  161761. }
  161762. }
  161763. }
  161764. /*
  161765. * Perform forward DCT on one or more blocks of a component.
  161766. *
  161767. * The input samples are taken from the sample_data[] array starting at
  161768. * position start_row/start_col, and moving to the right for any additional
  161769. * blocks. The quantized coefficients are returned in coef_blocks[].
  161770. */
  161771. METHODDEF(void)
  161772. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161773. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161774. JDIMENSION start_row, JDIMENSION start_col,
  161775. JDIMENSION num_blocks)
  161776. /* This version is used for integer DCT implementations. */
  161777. {
  161778. /* This routine is heavily used, so it's worth coding it tightly. */
  161779. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  161780. forward_DCT_method_ptr do_dct = fdct->do_dct;
  161781. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  161782. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  161783. JDIMENSION bi;
  161784. sample_data += start_row; /* fold in the vertical offset once */
  161785. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  161786. /* Load data into workspace, applying unsigned->signed conversion */
  161787. { register DCTELEM *workspaceptr;
  161788. register JSAMPROW elemptr;
  161789. register int elemr;
  161790. workspaceptr = workspace;
  161791. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  161792. elemptr = sample_data[elemr] + start_col;
  161793. #if DCTSIZE == 8 /* unroll the inner loop */
  161794. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161795. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161796. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161797. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161798. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161799. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161800. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161801. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161802. #else
  161803. { register int elemc;
  161804. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  161805. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161806. }
  161807. }
  161808. #endif
  161809. }
  161810. }
  161811. /* Perform the DCT */
  161812. (*do_dct) (workspace);
  161813. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  161814. { register DCTELEM temp, qval;
  161815. register int i;
  161816. register JCOEFPTR output_ptr = coef_blocks[bi];
  161817. for (i = 0; i < DCTSIZE2; i++) {
  161818. qval = divisors[i];
  161819. temp = workspace[i];
  161820. /* Divide the coefficient value by qval, ensuring proper rounding.
  161821. * Since C does not specify the direction of rounding for negative
  161822. * quotients, we have to force the dividend positive for portability.
  161823. *
  161824. * In most files, at least half of the output values will be zero
  161825. * (at default quantization settings, more like three-quarters...)
  161826. * so we should ensure that this case is fast. On many machines,
  161827. * a comparison is enough cheaper than a divide to make a special test
  161828. * a win. Since both inputs will be nonnegative, we need only test
  161829. * for a < b to discover whether a/b is 0.
  161830. * If your machine's division is fast enough, define FAST_DIVIDE.
  161831. */
  161832. #ifdef FAST_DIVIDE
  161833. #define DIVIDE_BY(a,b) a /= b
  161834. #else
  161835. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  161836. #endif
  161837. if (temp < 0) {
  161838. temp = -temp;
  161839. temp += qval>>1; /* for rounding */
  161840. DIVIDE_BY(temp, qval);
  161841. temp = -temp;
  161842. } else {
  161843. temp += qval>>1; /* for rounding */
  161844. DIVIDE_BY(temp, qval);
  161845. }
  161846. output_ptr[i] = (JCOEF) temp;
  161847. }
  161848. }
  161849. }
  161850. }
  161851. #ifdef DCT_FLOAT_SUPPORTED
  161852. METHODDEF(void)
  161853. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161854. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161855. JDIMENSION start_row, JDIMENSION start_col,
  161856. JDIMENSION num_blocks)
  161857. /* This version is used for floating-point DCT implementations. */
  161858. {
  161859. /* This routine is heavily used, so it's worth coding it tightly. */
  161860. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  161861. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  161862. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  161863. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  161864. JDIMENSION bi;
  161865. sample_data += start_row; /* fold in the vertical offset once */
  161866. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  161867. /* Load data into workspace, applying unsigned->signed conversion */
  161868. { register FAST_FLOAT *workspaceptr;
  161869. register JSAMPROW elemptr;
  161870. register int elemr;
  161871. workspaceptr = workspace;
  161872. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  161873. elemptr = sample_data[elemr] + start_col;
  161874. #if DCTSIZE == 8 /* unroll the inner loop */
  161875. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  161876. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  161877. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  161878. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  161879. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  161880. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  161881. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  161882. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  161883. #else
  161884. { register int elemc;
  161885. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  161886. *workspaceptr++ = (FAST_FLOAT)
  161887. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  161888. }
  161889. }
  161890. #endif
  161891. }
  161892. }
  161893. /* Perform the DCT */
  161894. (*do_dct) (workspace);
  161895. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  161896. { register FAST_FLOAT temp;
  161897. register int i;
  161898. register JCOEFPTR output_ptr = coef_blocks[bi];
  161899. for (i = 0; i < DCTSIZE2; i++) {
  161900. /* Apply the quantization and scaling factor */
  161901. temp = workspace[i] * divisors[i];
  161902. /* Round to nearest integer.
  161903. * Since C does not specify the direction of rounding for negative
  161904. * quotients, we have to force the dividend positive for portability.
  161905. * The maximum coefficient size is +-16K (for 12-bit data), so this
  161906. * code should work for either 16-bit or 32-bit ints.
  161907. */
  161908. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  161909. }
  161910. }
  161911. }
  161912. }
  161913. #endif /* DCT_FLOAT_SUPPORTED */
  161914. /*
  161915. * Initialize FDCT manager.
  161916. */
  161917. GLOBAL(void)
  161918. jinit_forward_dct (j_compress_ptr cinfo)
  161919. {
  161920. my_fdct_ptr fdct;
  161921. int i;
  161922. fdct = (my_fdct_ptr)
  161923. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161924. SIZEOF(my_fdct_controller));
  161925. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  161926. fdct->pub.start_pass = start_pass_fdctmgr;
  161927. switch (cinfo->dct_method) {
  161928. #ifdef DCT_ISLOW_SUPPORTED
  161929. case JDCT_ISLOW:
  161930. fdct->pub.forward_DCT = forward_DCT;
  161931. fdct->do_dct = jpeg_fdct_islow;
  161932. break;
  161933. #endif
  161934. #ifdef DCT_IFAST_SUPPORTED
  161935. case JDCT_IFAST:
  161936. fdct->pub.forward_DCT = forward_DCT;
  161937. fdct->do_dct = jpeg_fdct_ifast;
  161938. break;
  161939. #endif
  161940. #ifdef DCT_FLOAT_SUPPORTED
  161941. case JDCT_FLOAT:
  161942. fdct->pub.forward_DCT = forward_DCT_float;
  161943. fdct->do_float_dct = jpeg_fdct_float;
  161944. break;
  161945. #endif
  161946. default:
  161947. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161948. break;
  161949. }
  161950. /* Mark divisor tables unallocated */
  161951. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161952. fdct->divisors[i] = NULL;
  161953. #ifdef DCT_FLOAT_SUPPORTED
  161954. fdct->float_divisors[i] = NULL;
  161955. #endif
  161956. }
  161957. }
  161958. /*** End of inlined file: jcdctmgr.c ***/
  161959. #undef CONST_BITS
  161960. /*** Start of inlined file: jchuff.c ***/
  161961. #define JPEG_INTERNALS
  161962. /*** Start of inlined file: jchuff.h ***/
  161963. /* The legal range of a DCT coefficient is
  161964. * -1024 .. +1023 for 8-bit data;
  161965. * -16384 .. +16383 for 12-bit data.
  161966. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  161967. */
  161968. #ifndef _jchuff_h_
  161969. #define _jchuff_h_
  161970. #if BITS_IN_JSAMPLE == 8
  161971. #define MAX_COEF_BITS 10
  161972. #else
  161973. #define MAX_COEF_BITS 14
  161974. #endif
  161975. /* Derived data constructed for each Huffman table */
  161976. typedef struct {
  161977. unsigned int ehufco[256]; /* code for each symbol */
  161978. char ehufsi[256]; /* length of code for each symbol */
  161979. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  161980. } c_derived_tbl;
  161981. /* Short forms of external names for systems with brain-damaged linkers. */
  161982. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161983. #define jpeg_make_c_derived_tbl jMkCDerived
  161984. #define jpeg_gen_optimal_table jGenOptTbl
  161985. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161986. /* Expand a Huffman table definition into the derived format */
  161987. EXTERN(void) jpeg_make_c_derived_tbl
  161988. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  161989. c_derived_tbl ** pdtbl));
  161990. /* Generate an optimal table definition given the specified counts */
  161991. EXTERN(void) jpeg_gen_optimal_table
  161992. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  161993. #endif
  161994. /*** End of inlined file: jchuff.h ***/
  161995. /* Declarations shared with jcphuff.c */
  161996. /* Expanded entropy encoder object for Huffman encoding.
  161997. *
  161998. * The savable_state subrecord contains fields that change within an MCU,
  161999. * but must not be updated permanently until we complete the MCU.
  162000. */
  162001. typedef struct {
  162002. INT32 put_buffer; /* current bit-accumulation buffer */
  162003. int put_bits; /* # of bits now in it */
  162004. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162005. } savable_state;
  162006. /* This macro is to work around compilers with missing or broken
  162007. * structure assignment. You'll need to fix this code if you have
  162008. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162009. */
  162010. #ifndef NO_STRUCT_ASSIGN
  162011. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162012. #else
  162013. #if MAX_COMPS_IN_SCAN == 4
  162014. #define ASSIGN_STATE(dest,src) \
  162015. ((dest).put_buffer = (src).put_buffer, \
  162016. (dest).put_bits = (src).put_bits, \
  162017. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162018. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162019. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162020. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162021. #endif
  162022. #endif
  162023. typedef struct {
  162024. struct jpeg_entropy_encoder pub; /* public fields */
  162025. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162026. /* These fields are NOT loaded into local working state. */
  162027. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162028. int next_restart_num; /* next restart number to write (0-7) */
  162029. /* Pointers to derived tables (these workspaces have image lifespan) */
  162030. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162031. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162032. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162033. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162034. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162035. #endif
  162036. } huff_entropy_encoder;
  162037. typedef huff_entropy_encoder * huff_entropy_ptr;
  162038. /* Working state while writing an MCU.
  162039. * This struct contains all the fields that are needed by subroutines.
  162040. */
  162041. typedef struct {
  162042. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162043. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162044. savable_state cur; /* Current bit buffer & DC state */
  162045. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162046. } working_state;
  162047. /* Forward declarations */
  162048. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162049. JBLOCKROW *MCU_data));
  162050. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162051. #ifdef ENTROPY_OPT_SUPPORTED
  162052. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162053. JBLOCKROW *MCU_data));
  162054. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162055. #endif
  162056. /*
  162057. * Initialize for a Huffman-compressed scan.
  162058. * If gather_statistics is TRUE, we do not output anything during the scan,
  162059. * just count the Huffman symbols used and generate Huffman code tables.
  162060. */
  162061. METHODDEF(void)
  162062. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162063. {
  162064. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162065. int ci, dctbl, actbl;
  162066. jpeg_component_info * compptr;
  162067. if (gather_statistics) {
  162068. #ifdef ENTROPY_OPT_SUPPORTED
  162069. entropy->pub.encode_mcu = encode_mcu_gather;
  162070. entropy->pub.finish_pass = finish_pass_gather;
  162071. #else
  162072. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162073. #endif
  162074. } else {
  162075. entropy->pub.encode_mcu = encode_mcu_huff;
  162076. entropy->pub.finish_pass = finish_pass_huff;
  162077. }
  162078. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162079. compptr = cinfo->cur_comp_info[ci];
  162080. dctbl = compptr->dc_tbl_no;
  162081. actbl = compptr->ac_tbl_no;
  162082. if (gather_statistics) {
  162083. #ifdef ENTROPY_OPT_SUPPORTED
  162084. /* Check for invalid table indexes */
  162085. /* (make_c_derived_tbl does this in the other path) */
  162086. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162087. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162088. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162089. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162090. /* Allocate and zero the statistics tables */
  162091. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162092. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162093. entropy->dc_count_ptrs[dctbl] = (long *)
  162094. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162095. 257 * SIZEOF(long));
  162096. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162097. if (entropy->ac_count_ptrs[actbl] == NULL)
  162098. entropy->ac_count_ptrs[actbl] = (long *)
  162099. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162100. 257 * SIZEOF(long));
  162101. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162102. #endif
  162103. } else {
  162104. /* Compute derived values for Huffman tables */
  162105. /* We may do this more than once for a table, but it's not expensive */
  162106. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162107. & entropy->dc_derived_tbls[dctbl]);
  162108. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162109. & entropy->ac_derived_tbls[actbl]);
  162110. }
  162111. /* Initialize DC predictions to 0 */
  162112. entropy->saved.last_dc_val[ci] = 0;
  162113. }
  162114. /* Initialize bit buffer to empty */
  162115. entropy->saved.put_buffer = 0;
  162116. entropy->saved.put_bits = 0;
  162117. /* Initialize restart stuff */
  162118. entropy->restarts_to_go = cinfo->restart_interval;
  162119. entropy->next_restart_num = 0;
  162120. }
  162121. /*
  162122. * Compute the derived values for a Huffman table.
  162123. * This routine also performs some validation checks on the table.
  162124. *
  162125. * Note this is also used by jcphuff.c.
  162126. */
  162127. GLOBAL(void)
  162128. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162129. c_derived_tbl ** pdtbl)
  162130. {
  162131. JHUFF_TBL *htbl;
  162132. c_derived_tbl *dtbl;
  162133. int p, i, l, lastp, si, maxsymbol;
  162134. char huffsize[257];
  162135. unsigned int huffcode[257];
  162136. unsigned int code;
  162137. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  162138. * paralleling the order of the symbols themselves in htbl->huffval[].
  162139. */
  162140. /* Find the input Huffman table */
  162141. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  162142. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162143. htbl =
  162144. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  162145. if (htbl == NULL)
  162146. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162147. /* Allocate a workspace if we haven't already done so. */
  162148. if (*pdtbl == NULL)
  162149. *pdtbl = (c_derived_tbl *)
  162150. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162151. SIZEOF(c_derived_tbl));
  162152. dtbl = *pdtbl;
  162153. /* Figure C.1: make table of Huffman code length for each symbol */
  162154. p = 0;
  162155. for (l = 1; l <= 16; l++) {
  162156. i = (int) htbl->bits[l];
  162157. if (i < 0 || p + i > 256) /* protect against table overrun */
  162158. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162159. while (i--)
  162160. huffsize[p++] = (char) l;
  162161. }
  162162. huffsize[p] = 0;
  162163. lastp = p;
  162164. /* Figure C.2: generate the codes themselves */
  162165. /* We also validate that the counts represent a legal Huffman code tree. */
  162166. code = 0;
  162167. si = huffsize[0];
  162168. p = 0;
  162169. while (huffsize[p]) {
  162170. while (((int) huffsize[p]) == si) {
  162171. huffcode[p++] = code;
  162172. code++;
  162173. }
  162174. /* code is now 1 more than the last code used for codelength si; but
  162175. * it must still fit in si bits, since no code is allowed to be all ones.
  162176. */
  162177. if (((INT32) code) >= (((INT32) 1) << si))
  162178. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162179. code <<= 1;
  162180. si++;
  162181. }
  162182. /* Figure C.3: generate encoding tables */
  162183. /* These are code and size indexed by symbol value */
  162184. /* Set all codeless symbols to have code length 0;
  162185. * this lets us detect duplicate VAL entries here, and later
  162186. * allows emit_bits to detect any attempt to emit such symbols.
  162187. */
  162188. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  162189. /* This is also a convenient place to check for out-of-range
  162190. * and duplicated VAL entries. We allow 0..255 for AC symbols
  162191. * but only 0..15 for DC. (We could constrain them further
  162192. * based on data depth and mode, but this seems enough.)
  162193. */
  162194. maxsymbol = isDC ? 15 : 255;
  162195. for (p = 0; p < lastp; p++) {
  162196. i = htbl->huffval[p];
  162197. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  162198. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162199. dtbl->ehufco[i] = huffcode[p];
  162200. dtbl->ehufsi[i] = huffsize[p];
  162201. }
  162202. }
  162203. /* Outputting bytes to the file */
  162204. /* Emit a byte, taking 'action' if must suspend. */
  162205. #define emit_byte(state,val,action) \
  162206. { *(state)->next_output_byte++ = (JOCTET) (val); \
  162207. if (--(state)->free_in_buffer == 0) \
  162208. if (! dump_buffer(state)) \
  162209. { action; } }
  162210. LOCAL(boolean)
  162211. dump_buffer (working_state * state)
  162212. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  162213. {
  162214. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  162215. if (! (*dest->empty_output_buffer) (state->cinfo))
  162216. return FALSE;
  162217. /* After a successful buffer dump, must reset buffer pointers */
  162218. state->next_output_byte = dest->next_output_byte;
  162219. state->free_in_buffer = dest->free_in_buffer;
  162220. return TRUE;
  162221. }
  162222. /* Outputting bits to the file */
  162223. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162224. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162225. * in one call, and we never retain more than 7 bits in put_buffer
  162226. * between calls, so 24 bits are sufficient.
  162227. */
  162228. INLINE
  162229. LOCAL(boolean)
  162230. emit_bits (working_state * state, unsigned int code, int size)
  162231. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  162232. {
  162233. /* This routine is heavily used, so it's worth coding tightly. */
  162234. register INT32 put_buffer = (INT32) code;
  162235. register int put_bits = state->cur.put_bits;
  162236. /* if size is 0, caller used an invalid Huffman table entry */
  162237. if (size == 0)
  162238. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  162239. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162240. put_bits += size; /* new number of bits in buffer */
  162241. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162242. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  162243. while (put_bits >= 8) {
  162244. int c = (int) ((put_buffer >> 16) & 0xFF);
  162245. emit_byte(state, c, return FALSE);
  162246. if (c == 0xFF) { /* need to stuff a zero byte? */
  162247. emit_byte(state, 0, return FALSE);
  162248. }
  162249. put_buffer <<= 8;
  162250. put_bits -= 8;
  162251. }
  162252. state->cur.put_buffer = put_buffer; /* update state variables */
  162253. state->cur.put_bits = put_bits;
  162254. return TRUE;
  162255. }
  162256. LOCAL(boolean)
  162257. flush_bits (working_state * state)
  162258. {
  162259. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  162260. return FALSE;
  162261. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  162262. state->cur.put_bits = 0;
  162263. return TRUE;
  162264. }
  162265. /* Encode a single block's worth of coefficients */
  162266. LOCAL(boolean)
  162267. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  162268. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  162269. {
  162270. register int temp, temp2;
  162271. register int nbits;
  162272. register int k, r, i;
  162273. /* Encode the DC coefficient difference per section F.1.2.1 */
  162274. temp = temp2 = block[0] - last_dc_val;
  162275. if (temp < 0) {
  162276. temp = -temp; /* temp is abs value of input */
  162277. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  162278. /* This code assumes we are on a two's complement machine */
  162279. temp2--;
  162280. }
  162281. /* Find the number of bits needed for the magnitude of the coefficient */
  162282. nbits = 0;
  162283. while (temp) {
  162284. nbits++;
  162285. temp >>= 1;
  162286. }
  162287. /* Check for out-of-range coefficient values.
  162288. * Since we're encoding a difference, the range limit is twice as much.
  162289. */
  162290. if (nbits > MAX_COEF_BITS+1)
  162291. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162292. /* Emit the Huffman-coded symbol for the number of bits */
  162293. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  162294. return FALSE;
  162295. /* Emit that number of bits of the value, if positive, */
  162296. /* or the complement of its magnitude, if negative. */
  162297. if (nbits) /* emit_bits rejects calls with size 0 */
  162298. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162299. return FALSE;
  162300. /* Encode the AC coefficients per section F.1.2.2 */
  162301. r = 0; /* r = run length of zeros */
  162302. for (k = 1; k < DCTSIZE2; k++) {
  162303. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162304. r++;
  162305. } else {
  162306. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162307. while (r > 15) {
  162308. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  162309. return FALSE;
  162310. r -= 16;
  162311. }
  162312. temp2 = temp;
  162313. if (temp < 0) {
  162314. temp = -temp; /* temp is abs value of input */
  162315. /* This code assumes we are on a two's complement machine */
  162316. temp2--;
  162317. }
  162318. /* Find the number of bits needed for the magnitude of the coefficient */
  162319. nbits = 1; /* there must be at least one 1 bit */
  162320. while ((temp >>= 1))
  162321. nbits++;
  162322. /* Check for out-of-range coefficient values */
  162323. if (nbits > MAX_COEF_BITS)
  162324. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162325. /* Emit Huffman symbol for run length / number of bits */
  162326. i = (r << 4) + nbits;
  162327. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  162328. return FALSE;
  162329. /* Emit that number of bits of the value, if positive, */
  162330. /* or the complement of its magnitude, if negative. */
  162331. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162332. return FALSE;
  162333. r = 0;
  162334. }
  162335. }
  162336. /* If the last coef(s) were zero, emit an end-of-block code */
  162337. if (r > 0)
  162338. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  162339. return FALSE;
  162340. return TRUE;
  162341. }
  162342. /*
  162343. * Emit a restart marker & resynchronize predictions.
  162344. */
  162345. LOCAL(boolean)
  162346. emit_restart (working_state * state, int restart_num)
  162347. {
  162348. int ci;
  162349. if (! flush_bits(state))
  162350. return FALSE;
  162351. emit_byte(state, 0xFF, return FALSE);
  162352. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  162353. /* Re-initialize DC predictions to 0 */
  162354. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  162355. state->cur.last_dc_val[ci] = 0;
  162356. /* The restart counter is not updated until we successfully write the MCU. */
  162357. return TRUE;
  162358. }
  162359. /*
  162360. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  162361. */
  162362. METHODDEF(boolean)
  162363. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162364. {
  162365. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162366. working_state state;
  162367. int blkn, ci;
  162368. jpeg_component_info * compptr;
  162369. /* Load up working state */
  162370. state.next_output_byte = cinfo->dest->next_output_byte;
  162371. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162372. ASSIGN_STATE(state.cur, entropy->saved);
  162373. state.cinfo = cinfo;
  162374. /* Emit restart marker if needed */
  162375. if (cinfo->restart_interval) {
  162376. if (entropy->restarts_to_go == 0)
  162377. if (! emit_restart(&state, entropy->next_restart_num))
  162378. return FALSE;
  162379. }
  162380. /* Encode the MCU data blocks */
  162381. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162382. ci = cinfo->MCU_membership[blkn];
  162383. compptr = cinfo->cur_comp_info[ci];
  162384. if (! encode_one_block(&state,
  162385. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  162386. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  162387. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  162388. return FALSE;
  162389. /* Update last_dc_val */
  162390. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  162391. }
  162392. /* Completed MCU, so update state */
  162393. cinfo->dest->next_output_byte = state.next_output_byte;
  162394. cinfo->dest->free_in_buffer = state.free_in_buffer;
  162395. ASSIGN_STATE(entropy->saved, state.cur);
  162396. /* Update restart-interval state too */
  162397. if (cinfo->restart_interval) {
  162398. if (entropy->restarts_to_go == 0) {
  162399. entropy->restarts_to_go = cinfo->restart_interval;
  162400. entropy->next_restart_num++;
  162401. entropy->next_restart_num &= 7;
  162402. }
  162403. entropy->restarts_to_go--;
  162404. }
  162405. return TRUE;
  162406. }
  162407. /*
  162408. * Finish up at the end of a Huffman-compressed scan.
  162409. */
  162410. METHODDEF(void)
  162411. finish_pass_huff (j_compress_ptr cinfo)
  162412. {
  162413. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162414. working_state state;
  162415. /* Load up working state ... flush_bits needs it */
  162416. state.next_output_byte = cinfo->dest->next_output_byte;
  162417. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162418. ASSIGN_STATE(state.cur, entropy->saved);
  162419. state.cinfo = cinfo;
  162420. /* Flush out the last data */
  162421. if (! flush_bits(&state))
  162422. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  162423. /* Update state */
  162424. cinfo->dest->next_output_byte = state.next_output_byte;
  162425. cinfo->dest->free_in_buffer = state.free_in_buffer;
  162426. ASSIGN_STATE(entropy->saved, state.cur);
  162427. }
  162428. /*
  162429. * Huffman coding optimization.
  162430. *
  162431. * We first scan the supplied data and count the number of uses of each symbol
  162432. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  162433. * Then we build a Huffman coding tree for the observed counts.
  162434. * Symbols which are not needed at all for the particular image are not
  162435. * assigned any code, which saves space in the DHT marker as well as in
  162436. * the compressed data.
  162437. */
  162438. #ifdef ENTROPY_OPT_SUPPORTED
  162439. /* Process a single block's worth of coefficients */
  162440. LOCAL(void)
  162441. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  162442. long dc_counts[], long ac_counts[])
  162443. {
  162444. register int temp;
  162445. register int nbits;
  162446. register int k, r;
  162447. /* Encode the DC coefficient difference per section F.1.2.1 */
  162448. temp = block[0] - last_dc_val;
  162449. if (temp < 0)
  162450. temp = -temp;
  162451. /* Find the number of bits needed for the magnitude of the coefficient */
  162452. nbits = 0;
  162453. while (temp) {
  162454. nbits++;
  162455. temp >>= 1;
  162456. }
  162457. /* Check for out-of-range coefficient values.
  162458. * Since we're encoding a difference, the range limit is twice as much.
  162459. */
  162460. if (nbits > MAX_COEF_BITS+1)
  162461. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162462. /* Count the Huffman symbol for the number of bits */
  162463. dc_counts[nbits]++;
  162464. /* Encode the AC coefficients per section F.1.2.2 */
  162465. r = 0; /* r = run length of zeros */
  162466. for (k = 1; k < DCTSIZE2; k++) {
  162467. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162468. r++;
  162469. } else {
  162470. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162471. while (r > 15) {
  162472. ac_counts[0xF0]++;
  162473. r -= 16;
  162474. }
  162475. /* Find the number of bits needed for the magnitude of the coefficient */
  162476. if (temp < 0)
  162477. temp = -temp;
  162478. /* Find the number of bits needed for the magnitude of the coefficient */
  162479. nbits = 1; /* there must be at least one 1 bit */
  162480. while ((temp >>= 1))
  162481. nbits++;
  162482. /* Check for out-of-range coefficient values */
  162483. if (nbits > MAX_COEF_BITS)
  162484. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162485. /* Count Huffman symbol for run length / number of bits */
  162486. ac_counts[(r << 4) + nbits]++;
  162487. r = 0;
  162488. }
  162489. }
  162490. /* If the last coef(s) were zero, emit an end-of-block code */
  162491. if (r > 0)
  162492. ac_counts[0]++;
  162493. }
  162494. /*
  162495. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  162496. * No data is actually output, so no suspension return is possible.
  162497. */
  162498. METHODDEF(boolean)
  162499. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162500. {
  162501. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162502. int blkn, ci;
  162503. jpeg_component_info * compptr;
  162504. /* Take care of restart intervals if needed */
  162505. if (cinfo->restart_interval) {
  162506. if (entropy->restarts_to_go == 0) {
  162507. /* Re-initialize DC predictions to 0 */
  162508. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  162509. entropy->saved.last_dc_val[ci] = 0;
  162510. /* Update restart state */
  162511. entropy->restarts_to_go = cinfo->restart_interval;
  162512. }
  162513. entropy->restarts_to_go--;
  162514. }
  162515. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162516. ci = cinfo->MCU_membership[blkn];
  162517. compptr = cinfo->cur_comp_info[ci];
  162518. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  162519. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  162520. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  162521. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  162522. }
  162523. return TRUE;
  162524. }
  162525. /*
  162526. * Generate the best Huffman code table for the given counts, fill htbl.
  162527. * Note this is also used by jcphuff.c.
  162528. *
  162529. * The JPEG standard requires that no symbol be assigned a codeword of all
  162530. * one bits (so that padding bits added at the end of a compressed segment
  162531. * can't look like a valid code). Because of the canonical ordering of
  162532. * codewords, this just means that there must be an unused slot in the
  162533. * longest codeword length category. Section K.2 of the JPEG spec suggests
  162534. * reserving such a slot by pretending that symbol 256 is a valid symbol
  162535. * with count 1. In theory that's not optimal; giving it count zero but
  162536. * including it in the symbol set anyway should give a better Huffman code.
  162537. * But the theoretically better code actually seems to come out worse in
  162538. * practice, because it produces more all-ones bytes (which incur stuffed
  162539. * zero bytes in the final file). In any case the difference is tiny.
  162540. *
  162541. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  162542. * If some symbols have a very small but nonzero probability, the Huffman tree
  162543. * must be adjusted to meet the code length restriction. We currently use
  162544. * the adjustment method suggested in JPEG section K.2. This method is *not*
  162545. * optimal; it may not choose the best possible limited-length code. But
  162546. * typically only very-low-frequency symbols will be given less-than-optimal
  162547. * lengths, so the code is almost optimal. Experimental comparisons against
  162548. * an optimal limited-length-code algorithm indicate that the difference is
  162549. * microscopic --- usually less than a hundredth of a percent of total size.
  162550. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  162551. */
  162552. GLOBAL(void)
  162553. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  162554. {
  162555. #define MAX_CLEN 32 /* assumed maximum initial code length */
  162556. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  162557. int codesize[257]; /* codesize[k] = code length of symbol k */
  162558. int others[257]; /* next symbol in current branch of tree */
  162559. int c1, c2;
  162560. int p, i, j;
  162561. long v;
  162562. /* This algorithm is explained in section K.2 of the JPEG standard */
  162563. MEMZERO(bits, SIZEOF(bits));
  162564. MEMZERO(codesize, SIZEOF(codesize));
  162565. for (i = 0; i < 257; i++)
  162566. others[i] = -1; /* init links to empty */
  162567. freq[256] = 1; /* make sure 256 has a nonzero count */
  162568. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  162569. * that no real symbol is given code-value of all ones, because 256
  162570. * will be placed last in the largest codeword category.
  162571. */
  162572. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  162573. for (;;) {
  162574. /* Find the smallest nonzero frequency, set c1 = its symbol */
  162575. /* In case of ties, take the larger symbol number */
  162576. c1 = -1;
  162577. v = 1000000000L;
  162578. for (i = 0; i <= 256; i++) {
  162579. if (freq[i] && freq[i] <= v) {
  162580. v = freq[i];
  162581. c1 = i;
  162582. }
  162583. }
  162584. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  162585. /* In case of ties, take the larger symbol number */
  162586. c2 = -1;
  162587. v = 1000000000L;
  162588. for (i = 0; i <= 256; i++) {
  162589. if (freq[i] && freq[i] <= v && i != c1) {
  162590. v = freq[i];
  162591. c2 = i;
  162592. }
  162593. }
  162594. /* Done if we've merged everything into one frequency */
  162595. if (c2 < 0)
  162596. break;
  162597. /* Else merge the two counts/trees */
  162598. freq[c1] += freq[c2];
  162599. freq[c2] = 0;
  162600. /* Increment the codesize of everything in c1's tree branch */
  162601. codesize[c1]++;
  162602. while (others[c1] >= 0) {
  162603. c1 = others[c1];
  162604. codesize[c1]++;
  162605. }
  162606. others[c1] = c2; /* chain c2 onto c1's tree branch */
  162607. /* Increment the codesize of everything in c2's tree branch */
  162608. codesize[c2]++;
  162609. while (others[c2] >= 0) {
  162610. c2 = others[c2];
  162611. codesize[c2]++;
  162612. }
  162613. }
  162614. /* Now count the number of symbols of each code length */
  162615. for (i = 0; i <= 256; i++) {
  162616. if (codesize[i]) {
  162617. /* The JPEG standard seems to think that this can't happen, */
  162618. /* but I'm paranoid... */
  162619. if (codesize[i] > MAX_CLEN)
  162620. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  162621. bits[codesize[i]]++;
  162622. }
  162623. }
  162624. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  162625. * Huffman procedure assigned any such lengths, we must adjust the coding.
  162626. * Here is what the JPEG spec says about how this next bit works:
  162627. * Since symbols are paired for the longest Huffman code, the symbols are
  162628. * removed from this length category two at a time. The prefix for the pair
  162629. * (which is one bit shorter) is allocated to one of the pair; then,
  162630. * skipping the BITS entry for that prefix length, a code word from the next
  162631. * shortest nonzero BITS entry is converted into a prefix for two code words
  162632. * one bit longer.
  162633. */
  162634. for (i = MAX_CLEN; i > 16; i--) {
  162635. while (bits[i] > 0) {
  162636. j = i - 2; /* find length of new prefix to be used */
  162637. while (bits[j] == 0)
  162638. j--;
  162639. bits[i] -= 2; /* remove two symbols */
  162640. bits[i-1]++; /* one goes in this length */
  162641. bits[j+1] += 2; /* two new symbols in this length */
  162642. bits[j]--; /* symbol of this length is now a prefix */
  162643. }
  162644. }
  162645. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  162646. while (bits[i] == 0) /* find largest codelength still in use */
  162647. i--;
  162648. bits[i]--;
  162649. /* Return final symbol counts (only for lengths 0..16) */
  162650. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  162651. /* Return a list of the symbols sorted by code length */
  162652. /* It's not real clear to me why we don't need to consider the codelength
  162653. * changes made above, but the JPEG spec seems to think this works.
  162654. */
  162655. p = 0;
  162656. for (i = 1; i <= MAX_CLEN; i++) {
  162657. for (j = 0; j <= 255; j++) {
  162658. if (codesize[j] == i) {
  162659. htbl->huffval[p] = (UINT8) j;
  162660. p++;
  162661. }
  162662. }
  162663. }
  162664. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  162665. htbl->sent_table = FALSE;
  162666. }
  162667. /*
  162668. * Finish up a statistics-gathering pass and create the new Huffman tables.
  162669. */
  162670. METHODDEF(void)
  162671. finish_pass_gather (j_compress_ptr cinfo)
  162672. {
  162673. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162674. int ci, dctbl, actbl;
  162675. jpeg_component_info * compptr;
  162676. JHUFF_TBL **htblptr;
  162677. boolean did_dc[NUM_HUFF_TBLS];
  162678. boolean did_ac[NUM_HUFF_TBLS];
  162679. /* It's important not to apply jpeg_gen_optimal_table more than once
  162680. * per table, because it clobbers the input frequency counts!
  162681. */
  162682. MEMZERO(did_dc, SIZEOF(did_dc));
  162683. MEMZERO(did_ac, SIZEOF(did_ac));
  162684. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162685. compptr = cinfo->cur_comp_info[ci];
  162686. dctbl = compptr->dc_tbl_no;
  162687. actbl = compptr->ac_tbl_no;
  162688. if (! did_dc[dctbl]) {
  162689. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  162690. if (*htblptr == NULL)
  162691. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162692. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  162693. did_dc[dctbl] = TRUE;
  162694. }
  162695. if (! did_ac[actbl]) {
  162696. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  162697. if (*htblptr == NULL)
  162698. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162699. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  162700. did_ac[actbl] = TRUE;
  162701. }
  162702. }
  162703. }
  162704. #endif /* ENTROPY_OPT_SUPPORTED */
  162705. /*
  162706. * Module initialization routine for Huffman entropy encoding.
  162707. */
  162708. GLOBAL(void)
  162709. jinit_huff_encoder (j_compress_ptr cinfo)
  162710. {
  162711. huff_entropy_ptr entropy;
  162712. int i;
  162713. entropy = (huff_entropy_ptr)
  162714. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162715. SIZEOF(huff_entropy_encoder));
  162716. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  162717. entropy->pub.start_pass = start_pass_huff;
  162718. /* Mark tables unallocated */
  162719. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162720. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  162721. #ifdef ENTROPY_OPT_SUPPORTED
  162722. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  162723. #endif
  162724. }
  162725. }
  162726. /*** End of inlined file: jchuff.c ***/
  162727. #undef emit_byte
  162728. /*** Start of inlined file: jcinit.c ***/
  162729. #define JPEG_INTERNALS
  162730. /*
  162731. * Master selection of compression modules.
  162732. * This is done once at the start of processing an image. We determine
  162733. * which modules will be used and give them appropriate initialization calls.
  162734. */
  162735. GLOBAL(void)
  162736. jinit_compress_master (j_compress_ptr cinfo)
  162737. {
  162738. /* Initialize master control (includes parameter checking/processing) */
  162739. jinit_c_master_control(cinfo, FALSE /* full compression */);
  162740. /* Preprocessing */
  162741. if (! cinfo->raw_data_in) {
  162742. jinit_color_converter(cinfo);
  162743. jinit_downsampler(cinfo);
  162744. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  162745. }
  162746. /* Forward DCT */
  162747. jinit_forward_dct(cinfo);
  162748. /* Entropy encoding: either Huffman or arithmetic coding. */
  162749. if (cinfo->arith_code) {
  162750. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  162751. } else {
  162752. if (cinfo->progressive_mode) {
  162753. #ifdef C_PROGRESSIVE_SUPPORTED
  162754. jinit_phuff_encoder(cinfo);
  162755. #else
  162756. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162757. #endif
  162758. } else
  162759. jinit_huff_encoder(cinfo);
  162760. }
  162761. /* Need a full-image coefficient buffer in any multi-pass mode. */
  162762. jinit_c_coef_controller(cinfo,
  162763. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  162764. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  162765. jinit_marker_writer(cinfo);
  162766. /* We can now tell the memory manager to allocate virtual arrays. */
  162767. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  162768. /* Write the datastream header (SOI) immediately.
  162769. * Frame and scan headers are postponed till later.
  162770. * This lets application insert special markers after the SOI.
  162771. */
  162772. (*cinfo->marker->write_file_header) (cinfo);
  162773. }
  162774. /*** End of inlined file: jcinit.c ***/
  162775. /*** Start of inlined file: jcmainct.c ***/
  162776. #define JPEG_INTERNALS
  162777. /* Note: currently, there is no operating mode in which a full-image buffer
  162778. * is needed at this step. If there were, that mode could not be used with
  162779. * "raw data" input, since this module is bypassed in that case. However,
  162780. * we've left the code here for possible use in special applications.
  162781. */
  162782. #undef FULL_MAIN_BUFFER_SUPPORTED
  162783. /* Private buffer controller object */
  162784. typedef struct {
  162785. struct jpeg_c_main_controller pub; /* public fields */
  162786. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  162787. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  162788. boolean suspended; /* remember if we suspended output */
  162789. J_BUF_MODE pass_mode; /* current operating mode */
  162790. /* If using just a strip buffer, this points to the entire set of buffers
  162791. * (we allocate one for each component). In the full-image case, this
  162792. * points to the currently accessible strips of the virtual arrays.
  162793. */
  162794. JSAMPARRAY buffer[MAX_COMPONENTS];
  162795. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  162796. /* If using full-image storage, this array holds pointers to virtual-array
  162797. * control blocks for each component. Unused if not full-image storage.
  162798. */
  162799. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  162800. #endif
  162801. } my_main_controller;
  162802. typedef my_main_controller * my_main_ptr;
  162803. /* Forward declarations */
  162804. METHODDEF(void) process_data_simple_main
  162805. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  162806. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  162807. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  162808. METHODDEF(void) process_data_buffer_main
  162809. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  162810. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  162811. #endif
  162812. /*
  162813. * Initialize for a processing pass.
  162814. */
  162815. METHODDEF(void)
  162816. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162817. {
  162818. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  162819. /* Do nothing in raw-data mode. */
  162820. if (cinfo->raw_data_in)
  162821. return;
  162822. main_->cur_iMCU_row = 0; /* initialize counters */
  162823. main_->rowgroup_ctr = 0;
  162824. main_->suspended = FALSE;
  162825. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  162826. switch (pass_mode) {
  162827. case JBUF_PASS_THRU:
  162828. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  162829. if (main_->whole_image[0] != NULL)
  162830. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162831. #endif
  162832. main_->pub.process_data = process_data_simple_main;
  162833. break;
  162834. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  162835. case JBUF_SAVE_SOURCE:
  162836. case JBUF_CRANK_DEST:
  162837. case JBUF_SAVE_AND_PASS:
  162838. if (main_->whole_image[0] == NULL)
  162839. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162840. main_->pub.process_data = process_data_buffer_main;
  162841. break;
  162842. #endif
  162843. default:
  162844. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162845. break;
  162846. }
  162847. }
  162848. /*
  162849. * Process some data.
  162850. * This routine handles the simple pass-through mode,
  162851. * where we have only a strip buffer.
  162852. */
  162853. METHODDEF(void)
  162854. process_data_simple_main (j_compress_ptr cinfo,
  162855. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  162856. JDIMENSION in_rows_avail)
  162857. {
  162858. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  162859. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  162860. /* Read input data if we haven't filled the main buffer yet */
  162861. if (main_->rowgroup_ctr < DCTSIZE)
  162862. (*cinfo->prep->pre_process_data) (cinfo,
  162863. input_buf, in_row_ctr, in_rows_avail,
  162864. main_->buffer, &main_->rowgroup_ctr,
  162865. (JDIMENSION) DCTSIZE);
  162866. /* If we don't have a full iMCU row buffered, return to application for
  162867. * more data. Note that preprocessor will always pad to fill the iMCU row
  162868. * at the bottom of the image.
  162869. */
  162870. if (main_->rowgroup_ctr != DCTSIZE)
  162871. return;
  162872. /* Send the completed row to the compressor */
  162873. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  162874. /* If compressor did not consume the whole row, then we must need to
  162875. * suspend processing and return to the application. In this situation
  162876. * we pretend we didn't yet consume the last input row; otherwise, if
  162877. * it happened to be the last row of the image, the application would
  162878. * think we were done.
  162879. */
  162880. if (! main_->suspended) {
  162881. (*in_row_ctr)--;
  162882. main_->suspended = TRUE;
  162883. }
  162884. return;
  162885. }
  162886. /* We did finish the row. Undo our little suspension hack if a previous
  162887. * call suspended; then mark the main buffer empty.
  162888. */
  162889. if (main_->suspended) {
  162890. (*in_row_ctr)++;
  162891. main_->suspended = FALSE;
  162892. }
  162893. main_->rowgroup_ctr = 0;
  162894. main_->cur_iMCU_row++;
  162895. }
  162896. }
  162897. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  162898. /*
  162899. * Process some data.
  162900. * This routine handles all of the modes that use a full-size buffer.
  162901. */
  162902. METHODDEF(void)
  162903. process_data_buffer_main (j_compress_ptr cinfo,
  162904. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  162905. JDIMENSION in_rows_avail)
  162906. {
  162907. my_main_ptr main = (my_main_ptr) cinfo->main;
  162908. int ci;
  162909. jpeg_component_info *compptr;
  162910. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  162911. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  162912. /* Realign the virtual buffers if at the start of an iMCU row. */
  162913. if (main->rowgroup_ctr == 0) {
  162914. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162915. ci++, compptr++) {
  162916. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  162917. ((j_common_ptr) cinfo, main->whole_image[ci],
  162918. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  162919. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  162920. }
  162921. /* In a read pass, pretend we just read some source data. */
  162922. if (! writing) {
  162923. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  162924. main->rowgroup_ctr = DCTSIZE;
  162925. }
  162926. }
  162927. /* If a write pass, read input data until the current iMCU row is full. */
  162928. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  162929. if (writing) {
  162930. (*cinfo->prep->pre_process_data) (cinfo,
  162931. input_buf, in_row_ctr, in_rows_avail,
  162932. main->buffer, &main->rowgroup_ctr,
  162933. (JDIMENSION) DCTSIZE);
  162934. /* Return to application if we need more data to fill the iMCU row. */
  162935. if (main->rowgroup_ctr < DCTSIZE)
  162936. return;
  162937. }
  162938. /* Emit data, unless this is a sink-only pass. */
  162939. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  162940. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  162941. /* If compressor did not consume the whole row, then we must need to
  162942. * suspend processing and return to the application. In this situation
  162943. * we pretend we didn't yet consume the last input row; otherwise, if
  162944. * it happened to be the last row of the image, the application would
  162945. * think we were done.
  162946. */
  162947. if (! main->suspended) {
  162948. (*in_row_ctr)--;
  162949. main->suspended = TRUE;
  162950. }
  162951. return;
  162952. }
  162953. /* We did finish the row. Undo our little suspension hack if a previous
  162954. * call suspended; then mark the main buffer empty.
  162955. */
  162956. if (main->suspended) {
  162957. (*in_row_ctr)++;
  162958. main->suspended = FALSE;
  162959. }
  162960. }
  162961. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  162962. main->rowgroup_ctr = 0;
  162963. main->cur_iMCU_row++;
  162964. }
  162965. }
  162966. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  162967. /*
  162968. * Initialize main buffer controller.
  162969. */
  162970. GLOBAL(void)
  162971. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162972. {
  162973. my_main_ptr main_;
  162974. int ci;
  162975. jpeg_component_info *compptr;
  162976. main_ = (my_main_ptr)
  162977. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162978. SIZEOF(my_main_controller));
  162979. cinfo->main = (struct jpeg_c_main_controller *) main_;
  162980. main_->pub.start_pass = start_pass_main;
  162981. /* We don't need to create a buffer in raw-data mode. */
  162982. if (cinfo->raw_data_in)
  162983. return;
  162984. /* Create the buffer. It holds downsampled data, so each component
  162985. * may be of a different size.
  162986. */
  162987. if (need_full_buffer) {
  162988. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  162989. /* Allocate a full-image virtual array for each component */
  162990. /* Note we pad the bottom to a multiple of the iMCU height */
  162991. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162992. ci++, compptr++) {
  162993. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  162994. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162995. compptr->width_in_blocks * DCTSIZE,
  162996. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162997. (long) compptr->v_samp_factor) * DCTSIZE,
  162998. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  162999. }
  163000. #else
  163001. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163002. #endif
  163003. } else {
  163004. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163005. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163006. #endif
  163007. /* Allocate a strip buffer for each component */
  163008. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163009. ci++, compptr++) {
  163010. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163011. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163012. compptr->width_in_blocks * DCTSIZE,
  163013. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163014. }
  163015. }
  163016. }
  163017. /*** End of inlined file: jcmainct.c ***/
  163018. /*** Start of inlined file: jcmarker.c ***/
  163019. #define JPEG_INTERNALS
  163020. /* Private state */
  163021. typedef struct {
  163022. struct jpeg_marker_writer pub; /* public fields */
  163023. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163024. } my_marker_writer;
  163025. typedef my_marker_writer * my_marker_ptr;
  163026. /*
  163027. * Basic output routines.
  163028. *
  163029. * Note that we do not support suspension while writing a marker.
  163030. * Therefore, an application using suspension must ensure that there is
  163031. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163032. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163033. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163034. * modes are not supported at all with suspension, so those two are the only
  163035. * points where markers will be written.
  163036. */
  163037. LOCAL(void)
  163038. emit_byte (j_compress_ptr cinfo, int val)
  163039. /* Emit a byte */
  163040. {
  163041. struct jpeg_destination_mgr * dest = cinfo->dest;
  163042. *(dest->next_output_byte)++ = (JOCTET) val;
  163043. if (--dest->free_in_buffer == 0) {
  163044. if (! (*dest->empty_output_buffer) (cinfo))
  163045. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163046. }
  163047. }
  163048. LOCAL(void)
  163049. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163050. /* Emit a marker code */
  163051. {
  163052. emit_byte(cinfo, 0xFF);
  163053. emit_byte(cinfo, (int) mark);
  163054. }
  163055. LOCAL(void)
  163056. emit_2bytes (j_compress_ptr cinfo, int value)
  163057. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163058. {
  163059. emit_byte(cinfo, (value >> 8) & 0xFF);
  163060. emit_byte(cinfo, value & 0xFF);
  163061. }
  163062. /*
  163063. * Routines to write specific marker types.
  163064. */
  163065. LOCAL(int)
  163066. emit_dqt (j_compress_ptr cinfo, int index)
  163067. /* Emit a DQT marker */
  163068. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163069. {
  163070. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163071. int prec;
  163072. int i;
  163073. if (qtbl == NULL)
  163074. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163075. prec = 0;
  163076. for (i = 0; i < DCTSIZE2; i++) {
  163077. if (qtbl->quantval[i] > 255)
  163078. prec = 1;
  163079. }
  163080. if (! qtbl->sent_table) {
  163081. emit_marker(cinfo, M_DQT);
  163082. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163083. emit_byte(cinfo, index + (prec<<4));
  163084. for (i = 0; i < DCTSIZE2; i++) {
  163085. /* The table entries must be emitted in zigzag order. */
  163086. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163087. if (prec)
  163088. emit_byte(cinfo, (int) (qval >> 8));
  163089. emit_byte(cinfo, (int) (qval & 0xFF));
  163090. }
  163091. qtbl->sent_table = TRUE;
  163092. }
  163093. return prec;
  163094. }
  163095. LOCAL(void)
  163096. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163097. /* Emit a DHT marker */
  163098. {
  163099. JHUFF_TBL * htbl;
  163100. int length, i;
  163101. if (is_ac) {
  163102. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163103. index += 0x10; /* output index has AC bit set */
  163104. } else {
  163105. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163106. }
  163107. if (htbl == NULL)
  163108. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163109. if (! htbl->sent_table) {
  163110. emit_marker(cinfo, M_DHT);
  163111. length = 0;
  163112. for (i = 1; i <= 16; i++)
  163113. length += htbl->bits[i];
  163114. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163115. emit_byte(cinfo, index);
  163116. for (i = 1; i <= 16; i++)
  163117. emit_byte(cinfo, htbl->bits[i]);
  163118. for (i = 0; i < length; i++)
  163119. emit_byte(cinfo, htbl->huffval[i]);
  163120. htbl->sent_table = TRUE;
  163121. }
  163122. }
  163123. LOCAL(void)
  163124. emit_dac (j_compress_ptr)
  163125. /* Emit a DAC marker */
  163126. /* Since the useful info is so small, we want to emit all the tables in */
  163127. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163128. {
  163129. #ifdef C_ARITH_CODING_SUPPORTED
  163130. char dc_in_use[NUM_ARITH_TBLS];
  163131. char ac_in_use[NUM_ARITH_TBLS];
  163132. int length, i;
  163133. jpeg_component_info *compptr;
  163134. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163135. dc_in_use[i] = ac_in_use[i] = 0;
  163136. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163137. compptr = cinfo->cur_comp_info[i];
  163138. dc_in_use[compptr->dc_tbl_no] = 1;
  163139. ac_in_use[compptr->ac_tbl_no] = 1;
  163140. }
  163141. length = 0;
  163142. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163143. length += dc_in_use[i] + ac_in_use[i];
  163144. emit_marker(cinfo, M_DAC);
  163145. emit_2bytes(cinfo, length*2 + 2);
  163146. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  163147. if (dc_in_use[i]) {
  163148. emit_byte(cinfo, i);
  163149. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  163150. }
  163151. if (ac_in_use[i]) {
  163152. emit_byte(cinfo, i + 0x10);
  163153. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  163154. }
  163155. }
  163156. #endif /* C_ARITH_CODING_SUPPORTED */
  163157. }
  163158. LOCAL(void)
  163159. emit_dri (j_compress_ptr cinfo)
  163160. /* Emit a DRI marker */
  163161. {
  163162. emit_marker(cinfo, M_DRI);
  163163. emit_2bytes(cinfo, 4); /* fixed length */
  163164. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  163165. }
  163166. LOCAL(void)
  163167. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  163168. /* Emit a SOF marker */
  163169. {
  163170. int ci;
  163171. jpeg_component_info *compptr;
  163172. emit_marker(cinfo, code);
  163173. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  163174. /* Make sure image isn't bigger than SOF field can handle */
  163175. if ((long) cinfo->image_height > 65535L ||
  163176. (long) cinfo->image_width > 65535L)
  163177. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  163178. emit_byte(cinfo, cinfo->data_precision);
  163179. emit_2bytes(cinfo, (int) cinfo->image_height);
  163180. emit_2bytes(cinfo, (int) cinfo->image_width);
  163181. emit_byte(cinfo, cinfo->num_components);
  163182. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163183. ci++, compptr++) {
  163184. emit_byte(cinfo, compptr->component_id);
  163185. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  163186. emit_byte(cinfo, compptr->quant_tbl_no);
  163187. }
  163188. }
  163189. LOCAL(void)
  163190. emit_sos (j_compress_ptr cinfo)
  163191. /* Emit a SOS marker */
  163192. {
  163193. int i, td, ta;
  163194. jpeg_component_info *compptr;
  163195. emit_marker(cinfo, M_SOS);
  163196. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  163197. emit_byte(cinfo, cinfo->comps_in_scan);
  163198. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163199. compptr = cinfo->cur_comp_info[i];
  163200. emit_byte(cinfo, compptr->component_id);
  163201. td = compptr->dc_tbl_no;
  163202. ta = compptr->ac_tbl_no;
  163203. if (cinfo->progressive_mode) {
  163204. /* Progressive mode: only DC or only AC tables are used in one scan;
  163205. * furthermore, Huffman coding of DC refinement uses no table at all.
  163206. * We emit 0 for unused field(s); this is recommended by the P&M text
  163207. * but does not seem to be specified in the standard.
  163208. */
  163209. if (cinfo->Ss == 0) {
  163210. ta = 0; /* DC scan */
  163211. if (cinfo->Ah != 0 && !cinfo->arith_code)
  163212. td = 0; /* no DC table either */
  163213. } else {
  163214. td = 0; /* AC scan */
  163215. }
  163216. }
  163217. emit_byte(cinfo, (td << 4) + ta);
  163218. }
  163219. emit_byte(cinfo, cinfo->Ss);
  163220. emit_byte(cinfo, cinfo->Se);
  163221. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  163222. }
  163223. LOCAL(void)
  163224. emit_jfif_app0 (j_compress_ptr cinfo)
  163225. /* Emit a JFIF-compliant APP0 marker */
  163226. {
  163227. /*
  163228. * Length of APP0 block (2 bytes)
  163229. * Block ID (4 bytes - ASCII "JFIF")
  163230. * Zero byte (1 byte to terminate the ID string)
  163231. * Version Major, Minor (2 bytes - major first)
  163232. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  163233. * Xdpu (2 bytes - dots per unit horizontal)
  163234. * Ydpu (2 bytes - dots per unit vertical)
  163235. * Thumbnail X size (1 byte)
  163236. * Thumbnail Y size (1 byte)
  163237. */
  163238. emit_marker(cinfo, M_APP0);
  163239. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  163240. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  163241. emit_byte(cinfo, 0x46);
  163242. emit_byte(cinfo, 0x49);
  163243. emit_byte(cinfo, 0x46);
  163244. emit_byte(cinfo, 0);
  163245. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  163246. emit_byte(cinfo, cinfo->JFIF_minor_version);
  163247. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  163248. emit_2bytes(cinfo, (int) cinfo->X_density);
  163249. emit_2bytes(cinfo, (int) cinfo->Y_density);
  163250. emit_byte(cinfo, 0); /* No thumbnail image */
  163251. emit_byte(cinfo, 0);
  163252. }
  163253. LOCAL(void)
  163254. emit_adobe_app14 (j_compress_ptr cinfo)
  163255. /* Emit an Adobe APP14 marker */
  163256. {
  163257. /*
  163258. * Length of APP14 block (2 bytes)
  163259. * Block ID (5 bytes - ASCII "Adobe")
  163260. * Version Number (2 bytes - currently 100)
  163261. * Flags0 (2 bytes - currently 0)
  163262. * Flags1 (2 bytes - currently 0)
  163263. * Color transform (1 byte)
  163264. *
  163265. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  163266. * now in circulation seem to use Version = 100, so that's what we write.
  163267. *
  163268. * We write the color transform byte as 1 if the JPEG color space is
  163269. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  163270. * whether the encoder performed a transformation, which is pretty useless.
  163271. */
  163272. emit_marker(cinfo, M_APP14);
  163273. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  163274. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  163275. emit_byte(cinfo, 0x64);
  163276. emit_byte(cinfo, 0x6F);
  163277. emit_byte(cinfo, 0x62);
  163278. emit_byte(cinfo, 0x65);
  163279. emit_2bytes(cinfo, 100); /* Version */
  163280. emit_2bytes(cinfo, 0); /* Flags0 */
  163281. emit_2bytes(cinfo, 0); /* Flags1 */
  163282. switch (cinfo->jpeg_color_space) {
  163283. case JCS_YCbCr:
  163284. emit_byte(cinfo, 1); /* Color transform = 1 */
  163285. break;
  163286. case JCS_YCCK:
  163287. emit_byte(cinfo, 2); /* Color transform = 2 */
  163288. break;
  163289. default:
  163290. emit_byte(cinfo, 0); /* Color transform = 0 */
  163291. break;
  163292. }
  163293. }
  163294. /*
  163295. * These routines allow writing an arbitrary marker with parameters.
  163296. * The only intended use is to emit COM or APPn markers after calling
  163297. * write_file_header and before calling write_frame_header.
  163298. * Other uses are not guaranteed to produce desirable results.
  163299. * Counting the parameter bytes properly is the caller's responsibility.
  163300. */
  163301. METHODDEF(void)
  163302. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  163303. /* Emit an arbitrary marker header */
  163304. {
  163305. if (datalen > (unsigned int) 65533) /* safety check */
  163306. ERREXIT(cinfo, JERR_BAD_LENGTH);
  163307. emit_marker(cinfo, (JPEG_MARKER) marker);
  163308. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  163309. }
  163310. METHODDEF(void)
  163311. write_marker_byte (j_compress_ptr cinfo, int val)
  163312. /* Emit one byte of marker parameters following write_marker_header */
  163313. {
  163314. emit_byte(cinfo, val);
  163315. }
  163316. /*
  163317. * Write datastream header.
  163318. * This consists of an SOI and optional APPn markers.
  163319. * We recommend use of the JFIF marker, but not the Adobe marker,
  163320. * when using YCbCr or grayscale data. The JFIF marker should NOT
  163321. * be used for any other JPEG colorspace. The Adobe marker is helpful
  163322. * to distinguish RGB, CMYK, and YCCK colorspaces.
  163323. * Note that an application can write additional header markers after
  163324. * jpeg_start_compress returns.
  163325. */
  163326. METHODDEF(void)
  163327. write_file_header (j_compress_ptr cinfo)
  163328. {
  163329. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163330. emit_marker(cinfo, M_SOI); /* first the SOI */
  163331. /* SOI is defined to reset restart interval to 0 */
  163332. marker->last_restart_interval = 0;
  163333. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  163334. emit_jfif_app0(cinfo);
  163335. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  163336. emit_adobe_app14(cinfo);
  163337. }
  163338. /*
  163339. * Write frame header.
  163340. * This consists of DQT and SOFn markers.
  163341. * Note that we do not emit the SOF until we have emitted the DQT(s).
  163342. * This avoids compatibility problems with incorrect implementations that
  163343. * try to error-check the quant table numbers as soon as they see the SOF.
  163344. */
  163345. METHODDEF(void)
  163346. write_frame_header (j_compress_ptr cinfo)
  163347. {
  163348. int ci, prec;
  163349. boolean is_baseline;
  163350. jpeg_component_info *compptr;
  163351. /* Emit DQT for each quantization table.
  163352. * Note that emit_dqt() suppresses any duplicate tables.
  163353. */
  163354. prec = 0;
  163355. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163356. ci++, compptr++) {
  163357. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  163358. }
  163359. /* now prec is nonzero iff there are any 16-bit quant tables. */
  163360. /* Check for a non-baseline specification.
  163361. * Note we assume that Huffman table numbers won't be changed later.
  163362. */
  163363. if (cinfo->arith_code || cinfo->progressive_mode ||
  163364. cinfo->data_precision != 8) {
  163365. is_baseline = FALSE;
  163366. } else {
  163367. is_baseline = TRUE;
  163368. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163369. ci++, compptr++) {
  163370. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  163371. is_baseline = FALSE;
  163372. }
  163373. if (prec && is_baseline) {
  163374. is_baseline = FALSE;
  163375. /* If it's baseline except for quantizer size, warn the user */
  163376. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  163377. }
  163378. }
  163379. /* Emit the proper SOF marker */
  163380. if (cinfo->arith_code) {
  163381. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  163382. } else {
  163383. if (cinfo->progressive_mode)
  163384. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  163385. else if (is_baseline)
  163386. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  163387. else
  163388. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  163389. }
  163390. }
  163391. /*
  163392. * Write scan header.
  163393. * This consists of DHT or DAC markers, optional DRI, and SOS.
  163394. * Compressed data will be written following the SOS.
  163395. */
  163396. METHODDEF(void)
  163397. write_scan_header (j_compress_ptr cinfo)
  163398. {
  163399. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163400. int i;
  163401. jpeg_component_info *compptr;
  163402. if (cinfo->arith_code) {
  163403. /* Emit arith conditioning info. We may have some duplication
  163404. * if the file has multiple scans, but it's so small it's hardly
  163405. * worth worrying about.
  163406. */
  163407. emit_dac(cinfo);
  163408. } else {
  163409. /* Emit Huffman tables.
  163410. * Note that emit_dht() suppresses any duplicate tables.
  163411. */
  163412. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163413. compptr = cinfo->cur_comp_info[i];
  163414. if (cinfo->progressive_mode) {
  163415. /* Progressive mode: only DC or only AC tables are used in one scan */
  163416. if (cinfo->Ss == 0) {
  163417. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  163418. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  163419. } else {
  163420. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  163421. }
  163422. } else {
  163423. /* Sequential mode: need both DC and AC tables */
  163424. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  163425. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  163426. }
  163427. }
  163428. }
  163429. /* Emit DRI if required --- note that DRI value could change for each scan.
  163430. * We avoid wasting space with unnecessary DRIs, however.
  163431. */
  163432. if (cinfo->restart_interval != marker->last_restart_interval) {
  163433. emit_dri(cinfo);
  163434. marker->last_restart_interval = cinfo->restart_interval;
  163435. }
  163436. emit_sos(cinfo);
  163437. }
  163438. /*
  163439. * Write datastream trailer.
  163440. */
  163441. METHODDEF(void)
  163442. write_file_trailer (j_compress_ptr cinfo)
  163443. {
  163444. emit_marker(cinfo, M_EOI);
  163445. }
  163446. /*
  163447. * Write an abbreviated table-specification datastream.
  163448. * This consists of SOI, DQT and DHT tables, and EOI.
  163449. * Any table that is defined and not marked sent_table = TRUE will be
  163450. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  163451. */
  163452. METHODDEF(void)
  163453. write_tables_only (j_compress_ptr cinfo)
  163454. {
  163455. int i;
  163456. emit_marker(cinfo, M_SOI);
  163457. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163458. if (cinfo->quant_tbl_ptrs[i] != NULL)
  163459. (void) emit_dqt(cinfo, i);
  163460. }
  163461. if (! cinfo->arith_code) {
  163462. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163463. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  163464. emit_dht(cinfo, i, FALSE);
  163465. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  163466. emit_dht(cinfo, i, TRUE);
  163467. }
  163468. }
  163469. emit_marker(cinfo, M_EOI);
  163470. }
  163471. /*
  163472. * Initialize the marker writer module.
  163473. */
  163474. GLOBAL(void)
  163475. jinit_marker_writer (j_compress_ptr cinfo)
  163476. {
  163477. my_marker_ptr marker;
  163478. /* Create the subobject */
  163479. marker = (my_marker_ptr)
  163480. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163481. SIZEOF(my_marker_writer));
  163482. cinfo->marker = (struct jpeg_marker_writer *) marker;
  163483. /* Initialize method pointers */
  163484. marker->pub.write_file_header = write_file_header;
  163485. marker->pub.write_frame_header = write_frame_header;
  163486. marker->pub.write_scan_header = write_scan_header;
  163487. marker->pub.write_file_trailer = write_file_trailer;
  163488. marker->pub.write_tables_only = write_tables_only;
  163489. marker->pub.write_marker_header = write_marker_header;
  163490. marker->pub.write_marker_byte = write_marker_byte;
  163491. /* Initialize private state */
  163492. marker->last_restart_interval = 0;
  163493. }
  163494. /*** End of inlined file: jcmarker.c ***/
  163495. /*** Start of inlined file: jcmaster.c ***/
  163496. #define JPEG_INTERNALS
  163497. /* Private state */
  163498. typedef enum {
  163499. main_pass, /* input data, also do first output step */
  163500. huff_opt_pass, /* Huffman code optimization pass */
  163501. output_pass /* data output pass */
  163502. } c_pass_type;
  163503. typedef struct {
  163504. struct jpeg_comp_master pub; /* public fields */
  163505. c_pass_type pass_type; /* the type of the current pass */
  163506. int pass_number; /* # of passes completed */
  163507. int total_passes; /* total # of passes needed */
  163508. int scan_number; /* current index in scan_info[] */
  163509. } my_comp_master;
  163510. typedef my_comp_master * my_master_ptr;
  163511. /*
  163512. * Support routines that do various essential calculations.
  163513. */
  163514. LOCAL(void)
  163515. initial_setup (j_compress_ptr cinfo)
  163516. /* Do computations that are needed before master selection phase */
  163517. {
  163518. int ci;
  163519. jpeg_component_info *compptr;
  163520. long samplesperrow;
  163521. JDIMENSION jd_samplesperrow;
  163522. /* Sanity check on image dimensions */
  163523. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  163524. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  163525. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  163526. /* Make sure image isn't bigger than I can handle */
  163527. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  163528. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  163529. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  163530. /* Width of an input scanline must be representable as JDIMENSION. */
  163531. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  163532. jd_samplesperrow = (JDIMENSION) samplesperrow;
  163533. if ((long) jd_samplesperrow != samplesperrow)
  163534. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  163535. /* For now, precision must match compiled-in value... */
  163536. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  163537. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  163538. /* Check that number of components won't exceed internal array sizes */
  163539. if (cinfo->num_components > MAX_COMPONENTS)
  163540. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  163541. MAX_COMPONENTS);
  163542. /* Compute maximum sampling factors; check factor validity */
  163543. cinfo->max_h_samp_factor = 1;
  163544. cinfo->max_v_samp_factor = 1;
  163545. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163546. ci++, compptr++) {
  163547. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  163548. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  163549. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  163550. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  163551. compptr->h_samp_factor);
  163552. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  163553. compptr->v_samp_factor);
  163554. }
  163555. /* Compute dimensions of components */
  163556. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163557. ci++, compptr++) {
  163558. /* Fill in the correct component_index value; don't rely on application */
  163559. compptr->component_index = ci;
  163560. /* For compression, we never do DCT scaling. */
  163561. compptr->DCT_scaled_size = DCTSIZE;
  163562. /* Size in DCT blocks */
  163563. compptr->width_in_blocks = (JDIMENSION)
  163564. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163565. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  163566. compptr->height_in_blocks = (JDIMENSION)
  163567. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163568. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  163569. /* Size in samples */
  163570. compptr->downsampled_width = (JDIMENSION)
  163571. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163572. (long) cinfo->max_h_samp_factor);
  163573. compptr->downsampled_height = (JDIMENSION)
  163574. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163575. (long) cinfo->max_v_samp_factor);
  163576. /* Mark component needed (this flag isn't actually used for compression) */
  163577. compptr->component_needed = TRUE;
  163578. }
  163579. /* Compute number of fully interleaved MCU rows (number of times that
  163580. * main controller will call coefficient controller).
  163581. */
  163582. cinfo->total_iMCU_rows = (JDIMENSION)
  163583. jdiv_round_up((long) cinfo->image_height,
  163584. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  163585. }
  163586. #ifdef C_MULTISCAN_FILES_SUPPORTED
  163587. LOCAL(void)
  163588. validate_script (j_compress_ptr cinfo)
  163589. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  163590. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  163591. */
  163592. {
  163593. const jpeg_scan_info * scanptr;
  163594. int scanno, ncomps, ci, coefi, thisi;
  163595. int Ss, Se, Ah, Al;
  163596. boolean component_sent[MAX_COMPONENTS];
  163597. #ifdef C_PROGRESSIVE_SUPPORTED
  163598. int * last_bitpos_ptr;
  163599. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  163600. /* -1 until that coefficient has been seen; then last Al for it */
  163601. #endif
  163602. if (cinfo->num_scans <= 0)
  163603. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  163604. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  163605. * for progressive JPEG, no scan can have this.
  163606. */
  163607. scanptr = cinfo->scan_info;
  163608. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  163609. #ifdef C_PROGRESSIVE_SUPPORTED
  163610. cinfo->progressive_mode = TRUE;
  163611. last_bitpos_ptr = & last_bitpos[0][0];
  163612. for (ci = 0; ci < cinfo->num_components; ci++)
  163613. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  163614. *last_bitpos_ptr++ = -1;
  163615. #else
  163616. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163617. #endif
  163618. } else {
  163619. cinfo->progressive_mode = FALSE;
  163620. for (ci = 0; ci < cinfo->num_components; ci++)
  163621. component_sent[ci] = FALSE;
  163622. }
  163623. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  163624. /* Validate component indexes */
  163625. ncomps = scanptr->comps_in_scan;
  163626. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  163627. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  163628. for (ci = 0; ci < ncomps; ci++) {
  163629. thisi = scanptr->component_index[ci];
  163630. if (thisi < 0 || thisi >= cinfo->num_components)
  163631. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  163632. /* Components must appear in SOF order within each scan */
  163633. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  163634. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  163635. }
  163636. /* Validate progression parameters */
  163637. Ss = scanptr->Ss;
  163638. Se = scanptr->Se;
  163639. Ah = scanptr->Ah;
  163640. Al = scanptr->Al;
  163641. if (cinfo->progressive_mode) {
  163642. #ifdef C_PROGRESSIVE_SUPPORTED
  163643. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  163644. * seems wrong: the upper bound ought to depend on data precision.
  163645. * Perhaps they really meant 0..N+1 for N-bit precision.
  163646. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  163647. * out-of-range reconstructed DC values during the first DC scan,
  163648. * which might cause problems for some decoders.
  163649. */
  163650. #if BITS_IN_JSAMPLE == 8
  163651. #define MAX_AH_AL 10
  163652. #else
  163653. #define MAX_AH_AL 13
  163654. #endif
  163655. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  163656. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  163657. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163658. if (Ss == 0) {
  163659. if (Se != 0) /* DC and AC together not OK */
  163660. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163661. } else {
  163662. if (ncomps != 1) /* AC scans must be for only one component */
  163663. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163664. }
  163665. for (ci = 0; ci < ncomps; ci++) {
  163666. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  163667. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  163668. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163669. for (coefi = Ss; coefi <= Se; coefi++) {
  163670. if (last_bitpos_ptr[coefi] < 0) {
  163671. /* first scan of this coefficient */
  163672. if (Ah != 0)
  163673. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163674. } else {
  163675. /* not first scan */
  163676. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  163677. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163678. }
  163679. last_bitpos_ptr[coefi] = Al;
  163680. }
  163681. }
  163682. #endif
  163683. } else {
  163684. /* For sequential JPEG, all progression parameters must be these: */
  163685. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  163686. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163687. /* Make sure components are not sent twice */
  163688. for (ci = 0; ci < ncomps; ci++) {
  163689. thisi = scanptr->component_index[ci];
  163690. if (component_sent[thisi])
  163691. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  163692. component_sent[thisi] = TRUE;
  163693. }
  163694. }
  163695. }
  163696. /* Now verify that everything got sent. */
  163697. if (cinfo->progressive_mode) {
  163698. #ifdef C_PROGRESSIVE_SUPPORTED
  163699. /* For progressive mode, we only check that at least some DC data
  163700. * got sent for each component; the spec does not require that all bits
  163701. * of all coefficients be transmitted. Would it be wiser to enforce
  163702. * transmission of all coefficient bits??
  163703. */
  163704. for (ci = 0; ci < cinfo->num_components; ci++) {
  163705. if (last_bitpos[ci][0] < 0)
  163706. ERREXIT(cinfo, JERR_MISSING_DATA);
  163707. }
  163708. #endif
  163709. } else {
  163710. for (ci = 0; ci < cinfo->num_components; ci++) {
  163711. if (! component_sent[ci])
  163712. ERREXIT(cinfo, JERR_MISSING_DATA);
  163713. }
  163714. }
  163715. }
  163716. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  163717. LOCAL(void)
  163718. select_scan_parameters (j_compress_ptr cinfo)
  163719. /* Set up the scan parameters for the current scan */
  163720. {
  163721. int ci;
  163722. #ifdef C_MULTISCAN_FILES_SUPPORTED
  163723. if (cinfo->scan_info != NULL) {
  163724. /* Prepare for current scan --- the script is already validated */
  163725. my_master_ptr master = (my_master_ptr) cinfo->master;
  163726. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  163727. cinfo->comps_in_scan = scanptr->comps_in_scan;
  163728. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  163729. cinfo->cur_comp_info[ci] =
  163730. &cinfo->comp_info[scanptr->component_index[ci]];
  163731. }
  163732. cinfo->Ss = scanptr->Ss;
  163733. cinfo->Se = scanptr->Se;
  163734. cinfo->Ah = scanptr->Ah;
  163735. cinfo->Al = scanptr->Al;
  163736. }
  163737. else
  163738. #endif
  163739. {
  163740. /* Prepare for single sequential-JPEG scan containing all components */
  163741. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  163742. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  163743. MAX_COMPS_IN_SCAN);
  163744. cinfo->comps_in_scan = cinfo->num_components;
  163745. for (ci = 0; ci < cinfo->num_components; ci++) {
  163746. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  163747. }
  163748. cinfo->Ss = 0;
  163749. cinfo->Se = DCTSIZE2-1;
  163750. cinfo->Ah = 0;
  163751. cinfo->Al = 0;
  163752. }
  163753. }
  163754. LOCAL(void)
  163755. per_scan_setup (j_compress_ptr cinfo)
  163756. /* Do computations that are needed before processing a JPEG scan */
  163757. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  163758. {
  163759. int ci, mcublks, tmp;
  163760. jpeg_component_info *compptr;
  163761. if (cinfo->comps_in_scan == 1) {
  163762. /* Noninterleaved (single-component) scan */
  163763. compptr = cinfo->cur_comp_info[0];
  163764. /* Overall image size in MCUs */
  163765. cinfo->MCUs_per_row = compptr->width_in_blocks;
  163766. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  163767. /* For noninterleaved scan, always one block per MCU */
  163768. compptr->MCU_width = 1;
  163769. compptr->MCU_height = 1;
  163770. compptr->MCU_blocks = 1;
  163771. compptr->MCU_sample_width = DCTSIZE;
  163772. compptr->last_col_width = 1;
  163773. /* For noninterleaved scans, it is convenient to define last_row_height
  163774. * as the number of block rows present in the last iMCU row.
  163775. */
  163776. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  163777. if (tmp == 0) tmp = compptr->v_samp_factor;
  163778. compptr->last_row_height = tmp;
  163779. /* Prepare array describing MCU composition */
  163780. cinfo->blocks_in_MCU = 1;
  163781. cinfo->MCU_membership[0] = 0;
  163782. } else {
  163783. /* Interleaved (multi-component) scan */
  163784. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  163785. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  163786. MAX_COMPS_IN_SCAN);
  163787. /* Overall image size in MCUs */
  163788. cinfo->MCUs_per_row = (JDIMENSION)
  163789. jdiv_round_up((long) cinfo->image_width,
  163790. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  163791. cinfo->MCU_rows_in_scan = (JDIMENSION)
  163792. jdiv_round_up((long) cinfo->image_height,
  163793. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  163794. cinfo->blocks_in_MCU = 0;
  163795. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163796. compptr = cinfo->cur_comp_info[ci];
  163797. /* Sampling factors give # of blocks of component in each MCU */
  163798. compptr->MCU_width = compptr->h_samp_factor;
  163799. compptr->MCU_height = compptr->v_samp_factor;
  163800. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  163801. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  163802. /* Figure number of non-dummy blocks in last MCU column & row */
  163803. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  163804. if (tmp == 0) tmp = compptr->MCU_width;
  163805. compptr->last_col_width = tmp;
  163806. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  163807. if (tmp == 0) tmp = compptr->MCU_height;
  163808. compptr->last_row_height = tmp;
  163809. /* Prepare array describing MCU composition */
  163810. mcublks = compptr->MCU_blocks;
  163811. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  163812. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  163813. while (mcublks-- > 0) {
  163814. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  163815. }
  163816. }
  163817. }
  163818. /* Convert restart specified in rows to actual MCU count. */
  163819. /* Note that count must fit in 16 bits, so we provide limiting. */
  163820. if (cinfo->restart_in_rows > 0) {
  163821. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  163822. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  163823. }
  163824. }
  163825. /*
  163826. * Per-pass setup.
  163827. * This is called at the beginning of each pass. We determine which modules
  163828. * will be active during this pass and give them appropriate start_pass calls.
  163829. * We also set is_last_pass to indicate whether any more passes will be
  163830. * required.
  163831. */
  163832. METHODDEF(void)
  163833. prepare_for_pass (j_compress_ptr cinfo)
  163834. {
  163835. my_master_ptr master = (my_master_ptr) cinfo->master;
  163836. switch (master->pass_type) {
  163837. case main_pass:
  163838. /* Initial pass: will collect input data, and do either Huffman
  163839. * optimization or data output for the first scan.
  163840. */
  163841. select_scan_parameters(cinfo);
  163842. per_scan_setup(cinfo);
  163843. if (! cinfo->raw_data_in) {
  163844. (*cinfo->cconvert->start_pass) (cinfo);
  163845. (*cinfo->downsample->start_pass) (cinfo);
  163846. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  163847. }
  163848. (*cinfo->fdct->start_pass) (cinfo);
  163849. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  163850. (*cinfo->coef->start_pass) (cinfo,
  163851. (master->total_passes > 1 ?
  163852. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  163853. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  163854. if (cinfo->optimize_coding) {
  163855. /* No immediate data output; postpone writing frame/scan headers */
  163856. master->pub.call_pass_startup = FALSE;
  163857. } else {
  163858. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  163859. master->pub.call_pass_startup = TRUE;
  163860. }
  163861. break;
  163862. #ifdef ENTROPY_OPT_SUPPORTED
  163863. case huff_opt_pass:
  163864. /* Do Huffman optimization for a scan after the first one. */
  163865. select_scan_parameters(cinfo);
  163866. per_scan_setup(cinfo);
  163867. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  163868. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  163869. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  163870. master->pub.call_pass_startup = FALSE;
  163871. break;
  163872. }
  163873. /* Special case: Huffman DC refinement scans need no Huffman table
  163874. * and therefore we can skip the optimization pass for them.
  163875. */
  163876. master->pass_type = output_pass;
  163877. master->pass_number++;
  163878. /*FALLTHROUGH*/
  163879. #endif
  163880. case output_pass:
  163881. /* Do a data-output pass. */
  163882. /* We need not repeat per-scan setup if prior optimization pass did it. */
  163883. if (! cinfo->optimize_coding) {
  163884. select_scan_parameters(cinfo);
  163885. per_scan_setup(cinfo);
  163886. }
  163887. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  163888. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  163889. /* We emit frame/scan headers now */
  163890. if (master->scan_number == 0)
  163891. (*cinfo->marker->write_frame_header) (cinfo);
  163892. (*cinfo->marker->write_scan_header) (cinfo);
  163893. master->pub.call_pass_startup = FALSE;
  163894. break;
  163895. default:
  163896. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163897. }
  163898. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  163899. /* Set up progress monitor's pass info if present */
  163900. if (cinfo->progress != NULL) {
  163901. cinfo->progress->completed_passes = master->pass_number;
  163902. cinfo->progress->total_passes = master->total_passes;
  163903. }
  163904. }
  163905. /*
  163906. * Special start-of-pass hook.
  163907. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  163908. * In single-pass processing, we need this hook because we don't want to
  163909. * write frame/scan headers during jpeg_start_compress; we want to let the
  163910. * application write COM markers etc. between jpeg_start_compress and the
  163911. * jpeg_write_scanlines loop.
  163912. * In multi-pass processing, this routine is not used.
  163913. */
  163914. METHODDEF(void)
  163915. pass_startup (j_compress_ptr cinfo)
  163916. {
  163917. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  163918. (*cinfo->marker->write_frame_header) (cinfo);
  163919. (*cinfo->marker->write_scan_header) (cinfo);
  163920. }
  163921. /*
  163922. * Finish up at end of pass.
  163923. */
  163924. METHODDEF(void)
  163925. finish_pass_master (j_compress_ptr cinfo)
  163926. {
  163927. my_master_ptr master = (my_master_ptr) cinfo->master;
  163928. /* The entropy coder always needs an end-of-pass call,
  163929. * either to analyze statistics or to flush its output buffer.
  163930. */
  163931. (*cinfo->entropy->finish_pass) (cinfo);
  163932. /* Update state for next pass */
  163933. switch (master->pass_type) {
  163934. case main_pass:
  163935. /* next pass is either output of scan 0 (after optimization)
  163936. * or output of scan 1 (if no optimization).
  163937. */
  163938. master->pass_type = output_pass;
  163939. if (! cinfo->optimize_coding)
  163940. master->scan_number++;
  163941. break;
  163942. case huff_opt_pass:
  163943. /* next pass is always output of current scan */
  163944. master->pass_type = output_pass;
  163945. break;
  163946. case output_pass:
  163947. /* next pass is either optimization or output of next scan */
  163948. if (cinfo->optimize_coding)
  163949. master->pass_type = huff_opt_pass;
  163950. master->scan_number++;
  163951. break;
  163952. }
  163953. master->pass_number++;
  163954. }
  163955. /*
  163956. * Initialize master compression control.
  163957. */
  163958. GLOBAL(void)
  163959. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  163960. {
  163961. my_master_ptr master;
  163962. master = (my_master_ptr)
  163963. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163964. SIZEOF(my_comp_master));
  163965. cinfo->master = (struct jpeg_comp_master *) master;
  163966. master->pub.prepare_for_pass = prepare_for_pass;
  163967. master->pub.pass_startup = pass_startup;
  163968. master->pub.finish_pass = finish_pass_master;
  163969. master->pub.is_last_pass = FALSE;
  163970. /* Validate parameters, determine derived values */
  163971. initial_setup(cinfo);
  163972. if (cinfo->scan_info != NULL) {
  163973. #ifdef C_MULTISCAN_FILES_SUPPORTED
  163974. validate_script(cinfo);
  163975. #else
  163976. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163977. #endif
  163978. } else {
  163979. cinfo->progressive_mode = FALSE;
  163980. cinfo->num_scans = 1;
  163981. }
  163982. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  163983. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  163984. /* Initialize my private state */
  163985. if (transcode_only) {
  163986. /* no main pass in transcoding */
  163987. if (cinfo->optimize_coding)
  163988. master->pass_type = huff_opt_pass;
  163989. else
  163990. master->pass_type = output_pass;
  163991. } else {
  163992. /* for normal compression, first pass is always this type: */
  163993. master->pass_type = main_pass;
  163994. }
  163995. master->scan_number = 0;
  163996. master->pass_number = 0;
  163997. if (cinfo->optimize_coding)
  163998. master->total_passes = cinfo->num_scans * 2;
  163999. else
  164000. master->total_passes = cinfo->num_scans;
  164001. }
  164002. /*** End of inlined file: jcmaster.c ***/
  164003. /*** Start of inlined file: jcomapi.c ***/
  164004. #define JPEG_INTERNALS
  164005. /*
  164006. * Abort processing of a JPEG compression or decompression operation,
  164007. * but don't destroy the object itself.
  164008. *
  164009. * For this, we merely clean up all the nonpermanent memory pools.
  164010. * Note that temp files (virtual arrays) are not allowed to belong to
  164011. * the permanent pool, so we will be able to close all temp files here.
  164012. * Closing a data source or destination, if necessary, is the application's
  164013. * responsibility.
  164014. */
  164015. GLOBAL(void)
  164016. jpeg_abort (j_common_ptr cinfo)
  164017. {
  164018. int pool;
  164019. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164020. if (cinfo->mem == NULL)
  164021. return;
  164022. /* Releasing pools in reverse order might help avoid fragmentation
  164023. * with some (brain-damaged) malloc libraries.
  164024. */
  164025. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164026. (*cinfo->mem->free_pool) (cinfo, pool);
  164027. }
  164028. /* Reset overall state for possible reuse of object */
  164029. if (cinfo->is_decompressor) {
  164030. cinfo->global_state = DSTATE_START;
  164031. /* Try to keep application from accessing now-deleted marker list.
  164032. * A bit kludgy to do it here, but this is the most central place.
  164033. */
  164034. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164035. } else {
  164036. cinfo->global_state = CSTATE_START;
  164037. }
  164038. }
  164039. /*
  164040. * Destruction of a JPEG object.
  164041. *
  164042. * Everything gets deallocated except the master jpeg_compress_struct itself
  164043. * and the error manager struct. Both of these are supplied by the application
  164044. * and must be freed, if necessary, by the application. (Often they are on
  164045. * the stack and so don't need to be freed anyway.)
  164046. * Closing a data source or destination, if necessary, is the application's
  164047. * responsibility.
  164048. */
  164049. GLOBAL(void)
  164050. jpeg_destroy (j_common_ptr cinfo)
  164051. {
  164052. /* We need only tell the memory manager to release everything. */
  164053. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164054. if (cinfo->mem != NULL)
  164055. (*cinfo->mem->self_destruct) (cinfo);
  164056. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164057. cinfo->global_state = 0; /* mark it destroyed */
  164058. }
  164059. /*
  164060. * Convenience routines for allocating quantization and Huffman tables.
  164061. * (Would jutils.c be a more reasonable place to put these?)
  164062. */
  164063. GLOBAL(JQUANT_TBL *)
  164064. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164065. {
  164066. JQUANT_TBL *tbl;
  164067. tbl = (JQUANT_TBL *)
  164068. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164069. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164070. return tbl;
  164071. }
  164072. GLOBAL(JHUFF_TBL *)
  164073. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164074. {
  164075. JHUFF_TBL *tbl;
  164076. tbl = (JHUFF_TBL *)
  164077. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164078. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164079. return tbl;
  164080. }
  164081. /*** End of inlined file: jcomapi.c ***/
  164082. /*** Start of inlined file: jcparam.c ***/
  164083. #define JPEG_INTERNALS
  164084. /*
  164085. * Quantization table setup routines
  164086. */
  164087. GLOBAL(void)
  164088. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164089. const unsigned int *basic_table,
  164090. int scale_factor, boolean force_baseline)
  164091. /* Define a quantization table equal to the basic_table times
  164092. * a scale factor (given as a percentage).
  164093. * If force_baseline is TRUE, the computed quantization table entries
  164094. * are limited to 1..255 for JPEG baseline compatibility.
  164095. */
  164096. {
  164097. JQUANT_TBL ** qtblptr;
  164098. int i;
  164099. long temp;
  164100. /* Safety check to ensure start_compress not called yet. */
  164101. if (cinfo->global_state != CSTATE_START)
  164102. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164103. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164104. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164105. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164106. if (*qtblptr == NULL)
  164107. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164108. for (i = 0; i < DCTSIZE2; i++) {
  164109. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164110. /* limit the values to the valid range */
  164111. if (temp <= 0L) temp = 1L;
  164112. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164113. if (force_baseline && temp > 255L)
  164114. temp = 255L; /* limit to baseline range if requested */
  164115. (*qtblptr)->quantval[i] = (UINT16) temp;
  164116. }
  164117. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164118. (*qtblptr)->sent_table = FALSE;
  164119. }
  164120. GLOBAL(void)
  164121. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164122. boolean force_baseline)
  164123. /* Set or change the 'quality' (quantization) setting, using default tables
  164124. * and a straight percentage-scaling quality scale. In most cases it's better
  164125. * to use jpeg_set_quality (below); this entry point is provided for
  164126. * applications that insist on a linear percentage scaling.
  164127. */
  164128. {
  164129. /* These are the sample quantization tables given in JPEG spec section K.1.
  164130. * The spec says that the values given produce "good" quality, and
  164131. * when divided by 2, "very good" quality.
  164132. */
  164133. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164134. 16, 11, 10, 16, 24, 40, 51, 61,
  164135. 12, 12, 14, 19, 26, 58, 60, 55,
  164136. 14, 13, 16, 24, 40, 57, 69, 56,
  164137. 14, 17, 22, 29, 51, 87, 80, 62,
  164138. 18, 22, 37, 56, 68, 109, 103, 77,
  164139. 24, 35, 55, 64, 81, 104, 113, 92,
  164140. 49, 64, 78, 87, 103, 121, 120, 101,
  164141. 72, 92, 95, 98, 112, 100, 103, 99
  164142. };
  164143. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  164144. 17, 18, 24, 47, 99, 99, 99, 99,
  164145. 18, 21, 26, 66, 99, 99, 99, 99,
  164146. 24, 26, 56, 99, 99, 99, 99, 99,
  164147. 47, 66, 99, 99, 99, 99, 99, 99,
  164148. 99, 99, 99, 99, 99, 99, 99, 99,
  164149. 99, 99, 99, 99, 99, 99, 99, 99,
  164150. 99, 99, 99, 99, 99, 99, 99, 99,
  164151. 99, 99, 99, 99, 99, 99, 99, 99
  164152. };
  164153. /* Set up two quantization tables using the specified scaling */
  164154. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  164155. scale_factor, force_baseline);
  164156. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  164157. scale_factor, force_baseline);
  164158. }
  164159. GLOBAL(int)
  164160. jpeg_quality_scaling (int quality)
  164161. /* Convert a user-specified quality rating to a percentage scaling factor
  164162. * for an underlying quantization table, using our recommended scaling curve.
  164163. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  164164. */
  164165. {
  164166. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  164167. if (quality <= 0) quality = 1;
  164168. if (quality > 100) quality = 100;
  164169. /* The basic table is used as-is (scaling 100) for a quality of 50.
  164170. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  164171. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  164172. * to make all the table entries 1 (hence, minimum quantization loss).
  164173. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  164174. */
  164175. if (quality < 50)
  164176. quality = 5000 / quality;
  164177. else
  164178. quality = 200 - quality*2;
  164179. return quality;
  164180. }
  164181. GLOBAL(void)
  164182. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  164183. /* Set or change the 'quality' (quantization) setting, using default tables.
  164184. * This is the standard quality-adjusting entry point for typical user
  164185. * interfaces; only those who want detailed control over quantization tables
  164186. * would use the preceding three routines directly.
  164187. */
  164188. {
  164189. /* Convert user 0-100 rating to percentage scaling */
  164190. quality = jpeg_quality_scaling(quality);
  164191. /* Set up standard quality tables */
  164192. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  164193. }
  164194. /*
  164195. * Huffman table setup routines
  164196. */
  164197. LOCAL(void)
  164198. add_huff_table (j_compress_ptr cinfo,
  164199. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  164200. /* Define a Huffman table */
  164201. {
  164202. int nsymbols, len;
  164203. if (*htblptr == NULL)
  164204. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164205. /* Copy the number-of-symbols-of-each-code-length counts */
  164206. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  164207. /* Validate the counts. We do this here mainly so we can copy the right
  164208. * number of symbols from the val[] array, without risking marching off
  164209. * the end of memory. jchuff.c will do a more thorough test later.
  164210. */
  164211. nsymbols = 0;
  164212. for (len = 1; len <= 16; len++)
  164213. nsymbols += bits[len];
  164214. if (nsymbols < 1 || nsymbols > 256)
  164215. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164216. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  164217. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164218. (*htblptr)->sent_table = FALSE;
  164219. }
  164220. LOCAL(void)
  164221. std_huff_tables (j_compress_ptr cinfo)
  164222. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  164223. /* IMPORTANT: these are only valid for 8-bit data precision! */
  164224. {
  164225. static const UINT8 bits_dc_luminance[17] =
  164226. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  164227. static const UINT8 val_dc_luminance[] =
  164228. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164229. static const UINT8 bits_dc_chrominance[17] =
  164230. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  164231. static const UINT8 val_dc_chrominance[] =
  164232. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164233. static const UINT8 bits_ac_luminance[17] =
  164234. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  164235. static const UINT8 val_ac_luminance[] =
  164236. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  164237. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  164238. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  164239. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  164240. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  164241. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  164242. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  164243. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  164244. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  164245. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  164246. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  164247. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  164248. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  164249. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  164250. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  164251. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  164252. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  164253. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  164254. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  164255. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164256. 0xf9, 0xfa };
  164257. static const UINT8 bits_ac_chrominance[17] =
  164258. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  164259. static const UINT8 val_ac_chrominance[] =
  164260. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  164261. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  164262. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  164263. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  164264. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  164265. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  164266. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  164267. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  164268. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  164269. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  164270. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  164271. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  164272. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  164273. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  164274. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  164275. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  164276. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  164277. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  164278. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  164279. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164280. 0xf9, 0xfa };
  164281. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  164282. bits_dc_luminance, val_dc_luminance);
  164283. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  164284. bits_ac_luminance, val_ac_luminance);
  164285. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  164286. bits_dc_chrominance, val_dc_chrominance);
  164287. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  164288. bits_ac_chrominance, val_ac_chrominance);
  164289. }
  164290. /*
  164291. * Default parameter setup for compression.
  164292. *
  164293. * Applications that don't choose to use this routine must do their
  164294. * own setup of all these parameters. Alternately, you can call this
  164295. * to establish defaults and then alter parameters selectively. This
  164296. * is the recommended approach since, if we add any new parameters,
  164297. * your code will still work (they'll be set to reasonable defaults).
  164298. */
  164299. GLOBAL(void)
  164300. jpeg_set_defaults (j_compress_ptr cinfo)
  164301. {
  164302. int i;
  164303. /* Safety check to ensure start_compress not called yet. */
  164304. if (cinfo->global_state != CSTATE_START)
  164305. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164306. /* Allocate comp_info array large enough for maximum component count.
  164307. * Array is made permanent in case application wants to compress
  164308. * multiple images at same param settings.
  164309. */
  164310. if (cinfo->comp_info == NULL)
  164311. cinfo->comp_info = (jpeg_component_info *)
  164312. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164313. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  164314. /* Initialize everything not dependent on the color space */
  164315. cinfo->data_precision = BITS_IN_JSAMPLE;
  164316. /* Set up two quantization tables using default quality of 75 */
  164317. jpeg_set_quality(cinfo, 75, TRUE);
  164318. /* Set up two Huffman tables */
  164319. std_huff_tables(cinfo);
  164320. /* Initialize default arithmetic coding conditioning */
  164321. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164322. cinfo->arith_dc_L[i] = 0;
  164323. cinfo->arith_dc_U[i] = 1;
  164324. cinfo->arith_ac_K[i] = 5;
  164325. }
  164326. /* Default is no multiple-scan output */
  164327. cinfo->scan_info = NULL;
  164328. cinfo->num_scans = 0;
  164329. /* Expect normal source image, not raw downsampled data */
  164330. cinfo->raw_data_in = FALSE;
  164331. /* Use Huffman coding, not arithmetic coding, by default */
  164332. cinfo->arith_code = FALSE;
  164333. /* By default, don't do extra passes to optimize entropy coding */
  164334. cinfo->optimize_coding = FALSE;
  164335. /* The standard Huffman tables are only valid for 8-bit data precision.
  164336. * If the precision is higher, force optimization on so that usable
  164337. * tables will be computed. This test can be removed if default tables
  164338. * are supplied that are valid for the desired precision.
  164339. */
  164340. if (cinfo->data_precision > 8)
  164341. cinfo->optimize_coding = TRUE;
  164342. /* By default, use the simpler non-cosited sampling alignment */
  164343. cinfo->CCIR601_sampling = FALSE;
  164344. /* No input smoothing */
  164345. cinfo->smoothing_factor = 0;
  164346. /* DCT algorithm preference */
  164347. cinfo->dct_method = JDCT_DEFAULT;
  164348. /* No restart markers */
  164349. cinfo->restart_interval = 0;
  164350. cinfo->restart_in_rows = 0;
  164351. /* Fill in default JFIF marker parameters. Note that whether the marker
  164352. * will actually be written is determined by jpeg_set_colorspace.
  164353. *
  164354. * By default, the library emits JFIF version code 1.01.
  164355. * An application that wants to emit JFIF 1.02 extension markers should set
  164356. * JFIF_minor_version to 2. We could probably get away with just defaulting
  164357. * to 1.02, but there may still be some decoders in use that will complain
  164358. * about that; saying 1.01 should minimize compatibility problems.
  164359. */
  164360. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  164361. cinfo->JFIF_minor_version = 1;
  164362. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  164363. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  164364. cinfo->Y_density = 1;
  164365. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  164366. jpeg_default_colorspace(cinfo);
  164367. }
  164368. /*
  164369. * Select an appropriate JPEG colorspace for in_color_space.
  164370. */
  164371. GLOBAL(void)
  164372. jpeg_default_colorspace (j_compress_ptr cinfo)
  164373. {
  164374. switch (cinfo->in_color_space) {
  164375. case JCS_GRAYSCALE:
  164376. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  164377. break;
  164378. case JCS_RGB:
  164379. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164380. break;
  164381. case JCS_YCbCr:
  164382. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164383. break;
  164384. case JCS_CMYK:
  164385. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  164386. break;
  164387. case JCS_YCCK:
  164388. jpeg_set_colorspace(cinfo, JCS_YCCK);
  164389. break;
  164390. case JCS_UNKNOWN:
  164391. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  164392. break;
  164393. default:
  164394. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  164395. }
  164396. }
  164397. /*
  164398. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  164399. */
  164400. GLOBAL(void)
  164401. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  164402. {
  164403. jpeg_component_info * compptr;
  164404. int ci;
  164405. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  164406. (compptr = &cinfo->comp_info[index], \
  164407. compptr->component_id = (id), \
  164408. compptr->h_samp_factor = (hsamp), \
  164409. compptr->v_samp_factor = (vsamp), \
  164410. compptr->quant_tbl_no = (quant), \
  164411. compptr->dc_tbl_no = (dctbl), \
  164412. compptr->ac_tbl_no = (actbl) )
  164413. /* Safety check to ensure start_compress not called yet. */
  164414. if (cinfo->global_state != CSTATE_START)
  164415. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164416. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  164417. * tables 1 for chrominance components.
  164418. */
  164419. cinfo->jpeg_color_space = colorspace;
  164420. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  164421. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  164422. switch (colorspace) {
  164423. case JCS_GRAYSCALE:
  164424. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  164425. cinfo->num_components = 1;
  164426. /* JFIF specifies component ID 1 */
  164427. SET_COMP(0, 1, 1,1, 0, 0,0);
  164428. break;
  164429. case JCS_RGB:
  164430. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  164431. cinfo->num_components = 3;
  164432. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  164433. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  164434. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  164435. break;
  164436. case JCS_YCbCr:
  164437. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  164438. cinfo->num_components = 3;
  164439. /* JFIF specifies component IDs 1,2,3 */
  164440. /* We default to 2x2 subsamples of chrominance */
  164441. SET_COMP(0, 1, 2,2, 0, 0,0);
  164442. SET_COMP(1, 2, 1,1, 1, 1,1);
  164443. SET_COMP(2, 3, 1,1, 1, 1,1);
  164444. break;
  164445. case JCS_CMYK:
  164446. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  164447. cinfo->num_components = 4;
  164448. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  164449. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  164450. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  164451. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  164452. break;
  164453. case JCS_YCCK:
  164454. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  164455. cinfo->num_components = 4;
  164456. SET_COMP(0, 1, 2,2, 0, 0,0);
  164457. SET_COMP(1, 2, 1,1, 1, 1,1);
  164458. SET_COMP(2, 3, 1,1, 1, 1,1);
  164459. SET_COMP(3, 4, 2,2, 0, 0,0);
  164460. break;
  164461. case JCS_UNKNOWN:
  164462. cinfo->num_components = cinfo->input_components;
  164463. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  164464. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164465. MAX_COMPONENTS);
  164466. for (ci = 0; ci < cinfo->num_components; ci++) {
  164467. SET_COMP(ci, ci, 1,1, 0, 0,0);
  164468. }
  164469. break;
  164470. default:
  164471. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164472. }
  164473. }
  164474. #ifdef C_PROGRESSIVE_SUPPORTED
  164475. LOCAL(jpeg_scan_info *)
  164476. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  164477. int Ss, int Se, int Ah, int Al)
  164478. /* Support routine: generate one scan for specified component */
  164479. {
  164480. scanptr->comps_in_scan = 1;
  164481. scanptr->component_index[0] = ci;
  164482. scanptr->Ss = Ss;
  164483. scanptr->Se = Se;
  164484. scanptr->Ah = Ah;
  164485. scanptr->Al = Al;
  164486. scanptr++;
  164487. return scanptr;
  164488. }
  164489. LOCAL(jpeg_scan_info *)
  164490. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  164491. int Ss, int Se, int Ah, int Al)
  164492. /* Support routine: generate one scan for each component */
  164493. {
  164494. int ci;
  164495. for (ci = 0; ci < ncomps; ci++) {
  164496. scanptr->comps_in_scan = 1;
  164497. scanptr->component_index[0] = ci;
  164498. scanptr->Ss = Ss;
  164499. scanptr->Se = Se;
  164500. scanptr->Ah = Ah;
  164501. scanptr->Al = Al;
  164502. scanptr++;
  164503. }
  164504. return scanptr;
  164505. }
  164506. LOCAL(jpeg_scan_info *)
  164507. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  164508. /* Support routine: generate interleaved DC scan if possible, else N scans */
  164509. {
  164510. int ci;
  164511. if (ncomps <= MAX_COMPS_IN_SCAN) {
  164512. /* Single interleaved DC scan */
  164513. scanptr->comps_in_scan = ncomps;
  164514. for (ci = 0; ci < ncomps; ci++)
  164515. scanptr->component_index[ci] = ci;
  164516. scanptr->Ss = scanptr->Se = 0;
  164517. scanptr->Ah = Ah;
  164518. scanptr->Al = Al;
  164519. scanptr++;
  164520. } else {
  164521. /* Noninterleaved DC scan for each component */
  164522. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  164523. }
  164524. return scanptr;
  164525. }
  164526. /*
  164527. * Create a recommended progressive-JPEG script.
  164528. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  164529. */
  164530. GLOBAL(void)
  164531. jpeg_simple_progression (j_compress_ptr cinfo)
  164532. {
  164533. int ncomps = cinfo->num_components;
  164534. int nscans;
  164535. jpeg_scan_info * scanptr;
  164536. /* Safety check to ensure start_compress not called yet. */
  164537. if (cinfo->global_state != CSTATE_START)
  164538. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164539. /* Figure space needed for script. Calculation must match code below! */
  164540. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  164541. /* Custom script for YCbCr color images. */
  164542. nscans = 10;
  164543. } else {
  164544. /* All-purpose script for other color spaces. */
  164545. if (ncomps > MAX_COMPS_IN_SCAN)
  164546. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  164547. else
  164548. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  164549. }
  164550. /* Allocate space for script.
  164551. * We need to put it in the permanent pool in case the application performs
  164552. * multiple compressions without changing the settings. To avoid a memory
  164553. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  164554. * object, we try to re-use previously allocated space, and we allocate
  164555. * enough space to handle YCbCr even if initially asked for grayscale.
  164556. */
  164557. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  164558. cinfo->script_space_size = MAX(nscans, 10);
  164559. cinfo->script_space = (jpeg_scan_info *)
  164560. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164561. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  164562. }
  164563. scanptr = cinfo->script_space;
  164564. cinfo->scan_info = scanptr;
  164565. cinfo->num_scans = nscans;
  164566. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  164567. /* Custom script for YCbCr color images. */
  164568. /* Initial DC scan */
  164569. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  164570. /* Initial AC scan: get some luma data out in a hurry */
  164571. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  164572. /* Chroma data is too small to be worth expending many scans on */
  164573. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  164574. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  164575. /* Complete spectral selection for luma AC */
  164576. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  164577. /* Refine next bit of luma AC */
  164578. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  164579. /* Finish DC successive approximation */
  164580. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  164581. /* Finish AC successive approximation */
  164582. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  164583. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  164584. /* Luma bottom bit comes last since it's usually largest scan */
  164585. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  164586. } else {
  164587. /* All-purpose script for other color spaces. */
  164588. /* Successive approximation first pass */
  164589. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  164590. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  164591. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  164592. /* Successive approximation second pass */
  164593. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  164594. /* Successive approximation final pass */
  164595. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  164596. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  164597. }
  164598. }
  164599. #endif /* C_PROGRESSIVE_SUPPORTED */
  164600. /*** End of inlined file: jcparam.c ***/
  164601. /*** Start of inlined file: jcphuff.c ***/
  164602. #define JPEG_INTERNALS
  164603. #ifdef C_PROGRESSIVE_SUPPORTED
  164604. /* Expanded entropy encoder object for progressive Huffman encoding. */
  164605. typedef struct {
  164606. struct jpeg_entropy_encoder pub; /* public fields */
  164607. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  164608. boolean gather_statistics;
  164609. /* Bit-level coding status.
  164610. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  164611. */
  164612. JOCTET * next_output_byte; /* => next byte to write in buffer */
  164613. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  164614. INT32 put_buffer; /* current bit-accumulation buffer */
  164615. int put_bits; /* # of bits now in it */
  164616. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  164617. /* Coding status for DC components */
  164618. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  164619. /* Coding status for AC components */
  164620. int ac_tbl_no; /* the table number of the single component */
  164621. unsigned int EOBRUN; /* run length of EOBs */
  164622. unsigned int BE; /* # of buffered correction bits before MCU */
  164623. char * bit_buffer; /* buffer for correction bits (1 per char) */
  164624. /* packing correction bits tightly would save some space but cost time... */
  164625. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  164626. int next_restart_num; /* next restart number to write (0-7) */
  164627. /* Pointers to derived tables (these workspaces have image lifespan).
  164628. * Since any one scan codes only DC or only AC, we only need one set
  164629. * of tables, not one for DC and one for AC.
  164630. */
  164631. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  164632. /* Statistics tables for optimization; again, one set is enough */
  164633. long * count_ptrs[NUM_HUFF_TBLS];
  164634. } phuff_entropy_encoder;
  164635. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  164636. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  164637. * buffer can hold. Larger sizes may slightly improve compression, but
  164638. * 1000 is already well into the realm of overkill.
  164639. * The minimum safe size is 64 bits.
  164640. */
  164641. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  164642. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  164643. * We assume that int right shift is unsigned if INT32 right shift is,
  164644. * which should be safe.
  164645. */
  164646. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  164647. #define ISHIFT_TEMPS int ishift_temp;
  164648. #define IRIGHT_SHIFT(x,shft) \
  164649. ((ishift_temp = (x)) < 0 ? \
  164650. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  164651. (ishift_temp >> (shft)))
  164652. #else
  164653. #define ISHIFT_TEMPS
  164654. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  164655. #endif
  164656. /* Forward declarations */
  164657. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  164658. JBLOCKROW *MCU_data));
  164659. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  164660. JBLOCKROW *MCU_data));
  164661. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  164662. JBLOCKROW *MCU_data));
  164663. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  164664. JBLOCKROW *MCU_data));
  164665. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  164666. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  164667. /*
  164668. * Initialize for a Huffman-compressed scan using progressive JPEG.
  164669. */
  164670. METHODDEF(void)
  164671. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  164672. {
  164673. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  164674. boolean is_DC_band;
  164675. int ci, tbl;
  164676. jpeg_component_info * compptr;
  164677. entropy->cinfo = cinfo;
  164678. entropy->gather_statistics = gather_statistics;
  164679. is_DC_band = (cinfo->Ss == 0);
  164680. /* We assume jcmaster.c already validated the scan parameters. */
  164681. /* Select execution routines */
  164682. if (cinfo->Ah == 0) {
  164683. if (is_DC_band)
  164684. entropy->pub.encode_mcu = encode_mcu_DC_first;
  164685. else
  164686. entropy->pub.encode_mcu = encode_mcu_AC_first;
  164687. } else {
  164688. if (is_DC_band)
  164689. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  164690. else {
  164691. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  164692. /* AC refinement needs a correction bit buffer */
  164693. if (entropy->bit_buffer == NULL)
  164694. entropy->bit_buffer = (char *)
  164695. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164696. MAX_CORR_BITS * SIZEOF(char));
  164697. }
  164698. }
  164699. if (gather_statistics)
  164700. entropy->pub.finish_pass = finish_pass_gather_phuff;
  164701. else
  164702. entropy->pub.finish_pass = finish_pass_phuff;
  164703. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  164704. * for AC coefficients.
  164705. */
  164706. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164707. compptr = cinfo->cur_comp_info[ci];
  164708. /* Initialize DC predictions to 0 */
  164709. entropy->last_dc_val[ci] = 0;
  164710. /* Get table index */
  164711. if (is_DC_band) {
  164712. if (cinfo->Ah != 0) /* DC refinement needs no table */
  164713. continue;
  164714. tbl = compptr->dc_tbl_no;
  164715. } else {
  164716. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  164717. }
  164718. if (gather_statistics) {
  164719. /* Check for invalid table index */
  164720. /* (make_c_derived_tbl does this in the other path) */
  164721. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  164722. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  164723. /* Allocate and zero the statistics tables */
  164724. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  164725. if (entropy->count_ptrs[tbl] == NULL)
  164726. entropy->count_ptrs[tbl] = (long *)
  164727. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164728. 257 * SIZEOF(long));
  164729. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  164730. } else {
  164731. /* Compute derived values for Huffman table */
  164732. /* We may do this more than once for a table, but it's not expensive */
  164733. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  164734. & entropy->derived_tbls[tbl]);
  164735. }
  164736. }
  164737. /* Initialize AC stuff */
  164738. entropy->EOBRUN = 0;
  164739. entropy->BE = 0;
  164740. /* Initialize bit buffer to empty */
  164741. entropy->put_buffer = 0;
  164742. entropy->put_bits = 0;
  164743. /* Initialize restart stuff */
  164744. entropy->restarts_to_go = cinfo->restart_interval;
  164745. entropy->next_restart_num = 0;
  164746. }
  164747. /* Outputting bytes to the file.
  164748. * NB: these must be called only when actually outputting,
  164749. * that is, entropy->gather_statistics == FALSE.
  164750. */
  164751. /* Emit a byte */
  164752. #define emit_byte(entropy,val) \
  164753. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  164754. if (--(entropy)->free_in_buffer == 0) \
  164755. dump_buffer_p(entropy); }
  164756. LOCAL(void)
  164757. dump_buffer_p (phuff_entropy_ptr entropy)
  164758. /* Empty the output buffer; we do not support suspension in this module. */
  164759. {
  164760. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  164761. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  164762. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  164763. /* After a successful buffer dump, must reset buffer pointers */
  164764. entropy->next_output_byte = dest->next_output_byte;
  164765. entropy->free_in_buffer = dest->free_in_buffer;
  164766. }
  164767. /* Outputting bits to the file */
  164768. /* Only the right 24 bits of put_buffer are used; the valid bits are
  164769. * left-justified in this part. At most 16 bits can be passed to emit_bits
  164770. * in one call, and we never retain more than 7 bits in put_buffer
  164771. * between calls, so 24 bits are sufficient.
  164772. */
  164773. INLINE
  164774. LOCAL(void)
  164775. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  164776. /* Emit some bits, unless we are in gather mode */
  164777. {
  164778. /* This routine is heavily used, so it's worth coding tightly. */
  164779. register INT32 put_buffer = (INT32) code;
  164780. register int put_bits = entropy->put_bits;
  164781. /* if size is 0, caller used an invalid Huffman table entry */
  164782. if (size == 0)
  164783. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  164784. if (entropy->gather_statistics)
  164785. return; /* do nothing if we're only getting stats */
  164786. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  164787. put_bits += size; /* new number of bits in buffer */
  164788. put_buffer <<= 24 - put_bits; /* align incoming bits */
  164789. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  164790. while (put_bits >= 8) {
  164791. int c = (int) ((put_buffer >> 16) & 0xFF);
  164792. emit_byte(entropy, c);
  164793. if (c == 0xFF) { /* need to stuff a zero byte? */
  164794. emit_byte(entropy, 0);
  164795. }
  164796. put_buffer <<= 8;
  164797. put_bits -= 8;
  164798. }
  164799. entropy->put_buffer = put_buffer; /* update variables */
  164800. entropy->put_bits = put_bits;
  164801. }
  164802. LOCAL(void)
  164803. flush_bits_p (phuff_entropy_ptr entropy)
  164804. {
  164805. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  164806. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  164807. entropy->put_bits = 0;
  164808. }
  164809. /*
  164810. * Emit (or just count) a Huffman symbol.
  164811. */
  164812. INLINE
  164813. LOCAL(void)
  164814. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  164815. {
  164816. if (entropy->gather_statistics)
  164817. entropy->count_ptrs[tbl_no][symbol]++;
  164818. else {
  164819. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  164820. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  164821. }
  164822. }
  164823. /*
  164824. * Emit bits from a correction bit buffer.
  164825. */
  164826. LOCAL(void)
  164827. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  164828. unsigned int nbits)
  164829. {
  164830. if (entropy->gather_statistics)
  164831. return; /* no real work */
  164832. while (nbits > 0) {
  164833. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  164834. bufstart++;
  164835. nbits--;
  164836. }
  164837. }
  164838. /*
  164839. * Emit any pending EOBRUN symbol.
  164840. */
  164841. LOCAL(void)
  164842. emit_eobrun (phuff_entropy_ptr entropy)
  164843. {
  164844. register int temp, nbits;
  164845. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  164846. temp = entropy->EOBRUN;
  164847. nbits = 0;
  164848. while ((temp >>= 1))
  164849. nbits++;
  164850. /* safety check: shouldn't happen given limited correction-bit buffer */
  164851. if (nbits > 14)
  164852. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  164853. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  164854. if (nbits)
  164855. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  164856. entropy->EOBRUN = 0;
  164857. /* Emit any buffered correction bits */
  164858. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  164859. entropy->BE = 0;
  164860. }
  164861. }
  164862. /*
  164863. * Emit a restart marker & resynchronize predictions.
  164864. */
  164865. LOCAL(void)
  164866. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  164867. {
  164868. int ci;
  164869. emit_eobrun(entropy);
  164870. if (! entropy->gather_statistics) {
  164871. flush_bits_p(entropy);
  164872. emit_byte(entropy, 0xFF);
  164873. emit_byte(entropy, JPEG_RST0 + restart_num);
  164874. }
  164875. if (entropy->cinfo->Ss == 0) {
  164876. /* Re-initialize DC predictions to 0 */
  164877. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  164878. entropy->last_dc_val[ci] = 0;
  164879. } else {
  164880. /* Re-initialize all AC-related fields to 0 */
  164881. entropy->EOBRUN = 0;
  164882. entropy->BE = 0;
  164883. }
  164884. }
  164885. /*
  164886. * MCU encoding for DC initial scan (either spectral selection,
  164887. * or first pass of successive approximation).
  164888. */
  164889. METHODDEF(boolean)
  164890. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  164891. {
  164892. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  164893. register int temp, temp2;
  164894. register int nbits;
  164895. int blkn, ci;
  164896. int Al = cinfo->Al;
  164897. JBLOCKROW block;
  164898. jpeg_component_info * compptr;
  164899. ISHIFT_TEMPS
  164900. entropy->next_output_byte = cinfo->dest->next_output_byte;
  164901. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  164902. /* Emit restart marker if needed */
  164903. if (cinfo->restart_interval)
  164904. if (entropy->restarts_to_go == 0)
  164905. emit_restart_p(entropy, entropy->next_restart_num);
  164906. /* Encode the MCU data blocks */
  164907. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  164908. block = MCU_data[blkn];
  164909. ci = cinfo->MCU_membership[blkn];
  164910. compptr = cinfo->cur_comp_info[ci];
  164911. /* Compute the DC value after the required point transform by Al.
  164912. * This is simply an arithmetic right shift.
  164913. */
  164914. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  164915. /* DC differences are figured on the point-transformed values. */
  164916. temp = temp2 - entropy->last_dc_val[ci];
  164917. entropy->last_dc_val[ci] = temp2;
  164918. /* Encode the DC coefficient difference per section G.1.2.1 */
  164919. temp2 = temp;
  164920. if (temp < 0) {
  164921. temp = -temp; /* temp is abs value of input */
  164922. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  164923. /* This code assumes we are on a two's complement machine */
  164924. temp2--;
  164925. }
  164926. /* Find the number of bits needed for the magnitude of the coefficient */
  164927. nbits = 0;
  164928. while (temp) {
  164929. nbits++;
  164930. temp >>= 1;
  164931. }
  164932. /* Check for out-of-range coefficient values.
  164933. * Since we're encoding a difference, the range limit is twice as much.
  164934. */
  164935. if (nbits > MAX_COEF_BITS+1)
  164936. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  164937. /* Count/emit the Huffman-coded symbol for the number of bits */
  164938. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  164939. /* Emit that number of bits of the value, if positive, */
  164940. /* or the complement of its magnitude, if negative. */
  164941. if (nbits) /* emit_bits rejects calls with size 0 */
  164942. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  164943. }
  164944. cinfo->dest->next_output_byte = entropy->next_output_byte;
  164945. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  164946. /* Update restart-interval state too */
  164947. if (cinfo->restart_interval) {
  164948. if (entropy->restarts_to_go == 0) {
  164949. entropy->restarts_to_go = cinfo->restart_interval;
  164950. entropy->next_restart_num++;
  164951. entropy->next_restart_num &= 7;
  164952. }
  164953. entropy->restarts_to_go--;
  164954. }
  164955. return TRUE;
  164956. }
  164957. /*
  164958. * MCU encoding for AC initial scan (either spectral selection,
  164959. * or first pass of successive approximation).
  164960. */
  164961. METHODDEF(boolean)
  164962. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  164963. {
  164964. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  164965. register int temp, temp2;
  164966. register int nbits;
  164967. register int r, k;
  164968. int Se = cinfo->Se;
  164969. int Al = cinfo->Al;
  164970. JBLOCKROW block;
  164971. entropy->next_output_byte = cinfo->dest->next_output_byte;
  164972. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  164973. /* Emit restart marker if needed */
  164974. if (cinfo->restart_interval)
  164975. if (entropy->restarts_to_go == 0)
  164976. emit_restart_p(entropy, entropy->next_restart_num);
  164977. /* Encode the MCU data block */
  164978. block = MCU_data[0];
  164979. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  164980. r = 0; /* r = run length of zeros */
  164981. for (k = cinfo->Ss; k <= Se; k++) {
  164982. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  164983. r++;
  164984. continue;
  164985. }
  164986. /* We must apply the point transform by Al. For AC coefficients this
  164987. * is an integer division with rounding towards 0. To do this portably
  164988. * in C, we shift after obtaining the absolute value; so the code is
  164989. * interwoven with finding the abs value (temp) and output bits (temp2).
  164990. */
  164991. if (temp < 0) {
  164992. temp = -temp; /* temp is abs value of input */
  164993. temp >>= Al; /* apply the point transform */
  164994. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  164995. temp2 = ~temp;
  164996. } else {
  164997. temp >>= Al; /* apply the point transform */
  164998. temp2 = temp;
  164999. }
  165000. /* Watch out for case that nonzero coef is zero after point transform */
  165001. if (temp == 0) {
  165002. r++;
  165003. continue;
  165004. }
  165005. /* Emit any pending EOBRUN */
  165006. if (entropy->EOBRUN > 0)
  165007. emit_eobrun(entropy);
  165008. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165009. while (r > 15) {
  165010. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165011. r -= 16;
  165012. }
  165013. /* Find the number of bits needed for the magnitude of the coefficient */
  165014. nbits = 1; /* there must be at least one 1 bit */
  165015. while ((temp >>= 1))
  165016. nbits++;
  165017. /* Check for out-of-range coefficient values */
  165018. if (nbits > MAX_COEF_BITS)
  165019. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165020. /* Count/emit Huffman symbol for run length / number of bits */
  165021. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165022. /* Emit that number of bits of the value, if positive, */
  165023. /* or the complement of its magnitude, if negative. */
  165024. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165025. r = 0; /* reset zero run length */
  165026. }
  165027. if (r > 0) { /* If there are trailing zeroes, */
  165028. entropy->EOBRUN++; /* count an EOB */
  165029. if (entropy->EOBRUN == 0x7FFF)
  165030. emit_eobrun(entropy); /* force it out to avoid overflow */
  165031. }
  165032. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165033. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165034. /* Update restart-interval state too */
  165035. if (cinfo->restart_interval) {
  165036. if (entropy->restarts_to_go == 0) {
  165037. entropy->restarts_to_go = cinfo->restart_interval;
  165038. entropy->next_restart_num++;
  165039. entropy->next_restart_num &= 7;
  165040. }
  165041. entropy->restarts_to_go--;
  165042. }
  165043. return TRUE;
  165044. }
  165045. /*
  165046. * MCU encoding for DC successive approximation refinement scan.
  165047. * Note: we assume such scans can be multi-component, although the spec
  165048. * is not very clear on the point.
  165049. */
  165050. METHODDEF(boolean)
  165051. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165052. {
  165053. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165054. register int temp;
  165055. int blkn;
  165056. int Al = cinfo->Al;
  165057. JBLOCKROW block;
  165058. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165059. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165060. /* Emit restart marker if needed */
  165061. if (cinfo->restart_interval)
  165062. if (entropy->restarts_to_go == 0)
  165063. emit_restart_p(entropy, entropy->next_restart_num);
  165064. /* Encode the MCU data blocks */
  165065. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165066. block = MCU_data[blkn];
  165067. /* We simply emit the Al'th bit of the DC coefficient value. */
  165068. temp = (*block)[0];
  165069. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165070. }
  165071. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165072. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165073. /* Update restart-interval state too */
  165074. if (cinfo->restart_interval) {
  165075. if (entropy->restarts_to_go == 0) {
  165076. entropy->restarts_to_go = cinfo->restart_interval;
  165077. entropy->next_restart_num++;
  165078. entropy->next_restart_num &= 7;
  165079. }
  165080. entropy->restarts_to_go--;
  165081. }
  165082. return TRUE;
  165083. }
  165084. /*
  165085. * MCU encoding for AC successive approximation refinement scan.
  165086. */
  165087. METHODDEF(boolean)
  165088. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165089. {
  165090. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165091. register int temp;
  165092. register int r, k;
  165093. int EOB;
  165094. char *BR_buffer;
  165095. unsigned int BR;
  165096. int Se = cinfo->Se;
  165097. int Al = cinfo->Al;
  165098. JBLOCKROW block;
  165099. int absvalues[DCTSIZE2];
  165100. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165101. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165102. /* Emit restart marker if needed */
  165103. if (cinfo->restart_interval)
  165104. if (entropy->restarts_to_go == 0)
  165105. emit_restart_p(entropy, entropy->next_restart_num);
  165106. /* Encode the MCU data block */
  165107. block = MCU_data[0];
  165108. /* It is convenient to make a pre-pass to determine the transformed
  165109. * coefficients' absolute values and the EOB position.
  165110. */
  165111. EOB = 0;
  165112. for (k = cinfo->Ss; k <= Se; k++) {
  165113. temp = (*block)[jpeg_natural_order[k]];
  165114. /* We must apply the point transform by Al. For AC coefficients this
  165115. * is an integer division with rounding towards 0. To do this portably
  165116. * in C, we shift after obtaining the absolute value.
  165117. */
  165118. if (temp < 0)
  165119. temp = -temp; /* temp is abs value of input */
  165120. temp >>= Al; /* apply the point transform */
  165121. absvalues[k] = temp; /* save abs value for main pass */
  165122. if (temp == 1)
  165123. EOB = k; /* EOB = index of last newly-nonzero coef */
  165124. }
  165125. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165126. r = 0; /* r = run length of zeros */
  165127. BR = 0; /* BR = count of buffered bits added now */
  165128. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165129. for (k = cinfo->Ss; k <= Se; k++) {
  165130. if ((temp = absvalues[k]) == 0) {
  165131. r++;
  165132. continue;
  165133. }
  165134. /* Emit any required ZRLs, but not if they can be folded into EOB */
  165135. while (r > 15 && k <= EOB) {
  165136. /* emit any pending EOBRUN and the BE correction bits */
  165137. emit_eobrun(entropy);
  165138. /* Emit ZRL */
  165139. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165140. r -= 16;
  165141. /* Emit buffered correction bits that must be associated with ZRL */
  165142. emit_buffered_bits(entropy, BR_buffer, BR);
  165143. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165144. BR = 0;
  165145. }
  165146. /* If the coef was previously nonzero, it only needs a correction bit.
  165147. * NOTE: a straight translation of the spec's figure G.7 would suggest
  165148. * that we also need to test r > 15. But if r > 15, we can only get here
  165149. * if k > EOB, which implies that this coefficient is not 1.
  165150. */
  165151. if (temp > 1) {
  165152. /* The correction bit is the next bit of the absolute value. */
  165153. BR_buffer[BR++] = (char) (temp & 1);
  165154. continue;
  165155. }
  165156. /* Emit any pending EOBRUN and the BE correction bits */
  165157. emit_eobrun(entropy);
  165158. /* Count/emit Huffman symbol for run length / number of bits */
  165159. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  165160. /* Emit output bit for newly-nonzero coef */
  165161. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  165162. emit_bits_p(entropy, (unsigned int) temp, 1);
  165163. /* Emit buffered correction bits that must be associated with this code */
  165164. emit_buffered_bits(entropy, BR_buffer, BR);
  165165. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165166. BR = 0;
  165167. r = 0; /* reset zero run length */
  165168. }
  165169. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  165170. entropy->EOBRUN++; /* count an EOB */
  165171. entropy->BE += BR; /* concat my correction bits to older ones */
  165172. /* We force out the EOB if we risk either:
  165173. * 1. overflow of the EOB counter;
  165174. * 2. overflow of the correction bit buffer during the next MCU.
  165175. */
  165176. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  165177. emit_eobrun(entropy);
  165178. }
  165179. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165180. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165181. /* Update restart-interval state too */
  165182. if (cinfo->restart_interval) {
  165183. if (entropy->restarts_to_go == 0) {
  165184. entropy->restarts_to_go = cinfo->restart_interval;
  165185. entropy->next_restart_num++;
  165186. entropy->next_restart_num &= 7;
  165187. }
  165188. entropy->restarts_to_go--;
  165189. }
  165190. return TRUE;
  165191. }
  165192. /*
  165193. * Finish up at the end of a Huffman-compressed progressive scan.
  165194. */
  165195. METHODDEF(void)
  165196. finish_pass_phuff (j_compress_ptr cinfo)
  165197. {
  165198. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165199. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165200. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165201. /* Flush out any buffered data */
  165202. emit_eobrun(entropy);
  165203. flush_bits_p(entropy);
  165204. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165205. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165206. }
  165207. /*
  165208. * Finish up a statistics-gathering pass and create the new Huffman tables.
  165209. */
  165210. METHODDEF(void)
  165211. finish_pass_gather_phuff (j_compress_ptr cinfo)
  165212. {
  165213. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165214. boolean is_DC_band;
  165215. int ci, tbl;
  165216. jpeg_component_info * compptr;
  165217. JHUFF_TBL **htblptr;
  165218. boolean did[NUM_HUFF_TBLS];
  165219. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  165220. emit_eobrun(entropy);
  165221. is_DC_band = (cinfo->Ss == 0);
  165222. /* It's important not to apply jpeg_gen_optimal_table more than once
  165223. * per table, because it clobbers the input frequency counts!
  165224. */
  165225. MEMZERO(did, SIZEOF(did));
  165226. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165227. compptr = cinfo->cur_comp_info[ci];
  165228. if (is_DC_band) {
  165229. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165230. continue;
  165231. tbl = compptr->dc_tbl_no;
  165232. } else {
  165233. tbl = compptr->ac_tbl_no;
  165234. }
  165235. if (! did[tbl]) {
  165236. if (is_DC_band)
  165237. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  165238. else
  165239. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  165240. if (*htblptr == NULL)
  165241. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165242. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  165243. did[tbl] = TRUE;
  165244. }
  165245. }
  165246. }
  165247. /*
  165248. * Module initialization routine for progressive Huffman entropy encoding.
  165249. */
  165250. GLOBAL(void)
  165251. jinit_phuff_encoder (j_compress_ptr cinfo)
  165252. {
  165253. phuff_entropy_ptr entropy;
  165254. int i;
  165255. entropy = (phuff_entropy_ptr)
  165256. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165257. SIZEOF(phuff_entropy_encoder));
  165258. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  165259. entropy->pub.start_pass = start_pass_phuff;
  165260. /* Mark tables unallocated */
  165261. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165262. entropy->derived_tbls[i] = NULL;
  165263. entropy->count_ptrs[i] = NULL;
  165264. }
  165265. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  165266. }
  165267. #endif /* C_PROGRESSIVE_SUPPORTED */
  165268. /*** End of inlined file: jcphuff.c ***/
  165269. /*** Start of inlined file: jcprepct.c ***/
  165270. #define JPEG_INTERNALS
  165271. /* At present, jcsample.c can request context rows only for smoothing.
  165272. * In the future, we might also need context rows for CCIR601 sampling
  165273. * or other more-complex downsampling procedures. The code to support
  165274. * context rows should be compiled only if needed.
  165275. */
  165276. #ifdef INPUT_SMOOTHING_SUPPORTED
  165277. #define CONTEXT_ROWS_SUPPORTED
  165278. #endif
  165279. /*
  165280. * For the simple (no-context-row) case, we just need to buffer one
  165281. * row group's worth of pixels for the downsampling step. At the bottom of
  165282. * the image, we pad to a full row group by replicating the last pixel row.
  165283. * The downsampler's last output row is then replicated if needed to pad
  165284. * out to a full iMCU row.
  165285. *
  165286. * When providing context rows, we must buffer three row groups' worth of
  165287. * pixels. Three row groups are physically allocated, but the row pointer
  165288. * arrays are made five row groups high, with the extra pointers above and
  165289. * below "wrapping around" to point to the last and first real row groups.
  165290. * This allows the downsampler to access the proper context rows.
  165291. * At the top and bottom of the image, we create dummy context rows by
  165292. * copying the first or last real pixel row. This copying could be avoided
  165293. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  165294. * trouble on the compression side.
  165295. */
  165296. /* Private buffer controller object */
  165297. typedef struct {
  165298. struct jpeg_c_prep_controller pub; /* public fields */
  165299. /* Downsampling input buffer. This buffer holds color-converted data
  165300. * until we have enough to do a downsample step.
  165301. */
  165302. JSAMPARRAY color_buf[MAX_COMPONENTS];
  165303. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  165304. int next_buf_row; /* index of next row to store in color_buf */
  165305. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  165306. int this_row_group; /* starting row index of group to process */
  165307. int next_buf_stop; /* downsample when we reach this index */
  165308. #endif
  165309. } my_prep_controller;
  165310. typedef my_prep_controller * my_prep_ptr;
  165311. /*
  165312. * Initialize for a processing pass.
  165313. */
  165314. METHODDEF(void)
  165315. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  165316. {
  165317. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165318. if (pass_mode != JBUF_PASS_THRU)
  165319. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165320. /* Initialize total-height counter for detecting bottom of image */
  165321. prep->rows_to_go = cinfo->image_height;
  165322. /* Mark the conversion buffer empty */
  165323. prep->next_buf_row = 0;
  165324. #ifdef CONTEXT_ROWS_SUPPORTED
  165325. /* Preset additional state variables for context mode.
  165326. * These aren't used in non-context mode, so we needn't test which mode.
  165327. */
  165328. prep->this_row_group = 0;
  165329. /* Set next_buf_stop to stop after two row groups have been read in. */
  165330. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  165331. #endif
  165332. }
  165333. /*
  165334. * Expand an image vertically from height input_rows to height output_rows,
  165335. * by duplicating the bottom row.
  165336. */
  165337. LOCAL(void)
  165338. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  165339. int input_rows, int output_rows)
  165340. {
  165341. register int row;
  165342. for (row = input_rows; row < output_rows; row++) {
  165343. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  165344. 1, num_cols);
  165345. }
  165346. }
  165347. /*
  165348. * Process some data in the simple no-context case.
  165349. *
  165350. * Preprocessor output data is counted in "row groups". A row group
  165351. * is defined to be v_samp_factor sample rows of each component.
  165352. * Downsampling will produce this much data from each max_v_samp_factor
  165353. * input rows.
  165354. */
  165355. METHODDEF(void)
  165356. pre_process_data (j_compress_ptr cinfo,
  165357. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165358. JDIMENSION in_rows_avail,
  165359. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165360. JDIMENSION out_row_groups_avail)
  165361. {
  165362. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165363. int numrows, ci;
  165364. JDIMENSION inrows;
  165365. jpeg_component_info * compptr;
  165366. while (*in_row_ctr < in_rows_avail &&
  165367. *out_row_group_ctr < out_row_groups_avail) {
  165368. /* Do color conversion to fill the conversion buffer. */
  165369. inrows = in_rows_avail - *in_row_ctr;
  165370. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  165371. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165372. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165373. prep->color_buf,
  165374. (JDIMENSION) prep->next_buf_row,
  165375. numrows);
  165376. *in_row_ctr += numrows;
  165377. prep->next_buf_row += numrows;
  165378. prep->rows_to_go -= numrows;
  165379. /* If at bottom of image, pad to fill the conversion buffer. */
  165380. if (prep->rows_to_go == 0 &&
  165381. prep->next_buf_row < cinfo->max_v_samp_factor) {
  165382. for (ci = 0; ci < cinfo->num_components; ci++) {
  165383. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  165384. prep->next_buf_row, cinfo->max_v_samp_factor);
  165385. }
  165386. prep->next_buf_row = cinfo->max_v_samp_factor;
  165387. }
  165388. /* If we've filled the conversion buffer, empty it. */
  165389. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  165390. (*cinfo->downsample->downsample) (cinfo,
  165391. prep->color_buf, (JDIMENSION) 0,
  165392. output_buf, *out_row_group_ctr);
  165393. prep->next_buf_row = 0;
  165394. (*out_row_group_ctr)++;
  165395. }
  165396. /* If at bottom of image, pad the output to a full iMCU height.
  165397. * Note we assume the caller is providing a one-iMCU-height output buffer!
  165398. */
  165399. if (prep->rows_to_go == 0 &&
  165400. *out_row_group_ctr < out_row_groups_avail) {
  165401. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165402. ci++, compptr++) {
  165403. expand_bottom_edge(output_buf[ci],
  165404. compptr->width_in_blocks * DCTSIZE,
  165405. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  165406. (int) (out_row_groups_avail * compptr->v_samp_factor));
  165407. }
  165408. *out_row_group_ctr = out_row_groups_avail;
  165409. break; /* can exit outer loop without test */
  165410. }
  165411. }
  165412. }
  165413. #ifdef CONTEXT_ROWS_SUPPORTED
  165414. /*
  165415. * Process some data in the context case.
  165416. */
  165417. METHODDEF(void)
  165418. pre_process_context (j_compress_ptr cinfo,
  165419. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165420. JDIMENSION in_rows_avail,
  165421. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165422. JDIMENSION out_row_groups_avail)
  165423. {
  165424. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165425. int numrows, ci;
  165426. int buf_height = cinfo->max_v_samp_factor * 3;
  165427. JDIMENSION inrows;
  165428. while (*out_row_group_ctr < out_row_groups_avail) {
  165429. if (*in_row_ctr < in_rows_avail) {
  165430. /* Do color conversion to fill the conversion buffer. */
  165431. inrows = in_rows_avail - *in_row_ctr;
  165432. numrows = prep->next_buf_stop - prep->next_buf_row;
  165433. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165434. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165435. prep->color_buf,
  165436. (JDIMENSION) prep->next_buf_row,
  165437. numrows);
  165438. /* Pad at top of image, if first time through */
  165439. if (prep->rows_to_go == cinfo->image_height) {
  165440. for (ci = 0; ci < cinfo->num_components; ci++) {
  165441. int row;
  165442. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  165443. jcopy_sample_rows(prep->color_buf[ci], 0,
  165444. prep->color_buf[ci], -row,
  165445. 1, cinfo->image_width);
  165446. }
  165447. }
  165448. }
  165449. *in_row_ctr += numrows;
  165450. prep->next_buf_row += numrows;
  165451. prep->rows_to_go -= numrows;
  165452. } else {
  165453. /* Return for more data, unless we are at the bottom of the image. */
  165454. if (prep->rows_to_go != 0)
  165455. break;
  165456. /* When at bottom of image, pad to fill the conversion buffer. */
  165457. if (prep->next_buf_row < prep->next_buf_stop) {
  165458. for (ci = 0; ci < cinfo->num_components; ci++) {
  165459. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  165460. prep->next_buf_row, prep->next_buf_stop);
  165461. }
  165462. prep->next_buf_row = prep->next_buf_stop;
  165463. }
  165464. }
  165465. /* If we've gotten enough data, downsample a row group. */
  165466. if (prep->next_buf_row == prep->next_buf_stop) {
  165467. (*cinfo->downsample->downsample) (cinfo,
  165468. prep->color_buf,
  165469. (JDIMENSION) prep->this_row_group,
  165470. output_buf, *out_row_group_ctr);
  165471. (*out_row_group_ctr)++;
  165472. /* Advance pointers with wraparound as necessary. */
  165473. prep->this_row_group += cinfo->max_v_samp_factor;
  165474. if (prep->this_row_group >= buf_height)
  165475. prep->this_row_group = 0;
  165476. if (prep->next_buf_row >= buf_height)
  165477. prep->next_buf_row = 0;
  165478. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  165479. }
  165480. }
  165481. }
  165482. /*
  165483. * Create the wrapped-around downsampling input buffer needed for context mode.
  165484. */
  165485. LOCAL(void)
  165486. create_context_buffer (j_compress_ptr cinfo)
  165487. {
  165488. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165489. int rgroup_height = cinfo->max_v_samp_factor;
  165490. int ci, i;
  165491. jpeg_component_info * compptr;
  165492. JSAMPARRAY true_buffer, fake_buffer;
  165493. /* Grab enough space for fake row pointers for all the components;
  165494. * we need five row groups' worth of pointers for each component.
  165495. */
  165496. fake_buffer = (JSAMPARRAY)
  165497. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165498. (cinfo->num_components * 5 * rgroup_height) *
  165499. SIZEOF(JSAMPROW));
  165500. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165501. ci++, compptr++) {
  165502. /* Allocate the actual buffer space (3 row groups) for this component.
  165503. * We make the buffer wide enough to allow the downsampler to edge-expand
  165504. * horizontally within the buffer, if it so chooses.
  165505. */
  165506. true_buffer = (*cinfo->mem->alloc_sarray)
  165507. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165508. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  165509. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  165510. (JDIMENSION) (3 * rgroup_height));
  165511. /* Copy true buffer row pointers into the middle of the fake row array */
  165512. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  165513. 3 * rgroup_height * SIZEOF(JSAMPROW));
  165514. /* Fill in the above and below wraparound pointers */
  165515. for (i = 0; i < rgroup_height; i++) {
  165516. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  165517. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  165518. }
  165519. prep->color_buf[ci] = fake_buffer + rgroup_height;
  165520. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  165521. }
  165522. }
  165523. #endif /* CONTEXT_ROWS_SUPPORTED */
  165524. /*
  165525. * Initialize preprocessing controller.
  165526. */
  165527. GLOBAL(void)
  165528. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  165529. {
  165530. my_prep_ptr prep;
  165531. int ci;
  165532. jpeg_component_info * compptr;
  165533. if (need_full_buffer) /* safety check */
  165534. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165535. prep = (my_prep_ptr)
  165536. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165537. SIZEOF(my_prep_controller));
  165538. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  165539. prep->pub.start_pass = start_pass_prep;
  165540. /* Allocate the color conversion buffer.
  165541. * We make the buffer wide enough to allow the downsampler to edge-expand
  165542. * horizontally within the buffer, if it so chooses.
  165543. */
  165544. if (cinfo->downsample->need_context_rows) {
  165545. /* Set up to provide context rows */
  165546. #ifdef CONTEXT_ROWS_SUPPORTED
  165547. prep->pub.pre_process_data = pre_process_context;
  165548. create_context_buffer(cinfo);
  165549. #else
  165550. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165551. #endif
  165552. } else {
  165553. /* No context, just make it tall enough for one row group */
  165554. prep->pub.pre_process_data = pre_process_data;
  165555. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165556. ci++, compptr++) {
  165557. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  165558. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165559. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  165560. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  165561. (JDIMENSION) cinfo->max_v_samp_factor);
  165562. }
  165563. }
  165564. }
  165565. /*** End of inlined file: jcprepct.c ***/
  165566. /*** Start of inlined file: jcsample.c ***/
  165567. #define JPEG_INTERNALS
  165568. /* Pointer to routine to downsample a single component */
  165569. typedef JMETHOD(void, downsample1_ptr,
  165570. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165571. JSAMPARRAY input_data, JSAMPARRAY output_data));
  165572. /* Private subobject */
  165573. typedef struct {
  165574. struct jpeg_downsampler pub; /* public fields */
  165575. /* Downsampling method pointers, one per component */
  165576. downsample1_ptr methods[MAX_COMPONENTS];
  165577. } my_downsampler;
  165578. typedef my_downsampler * my_downsample_ptr;
  165579. /*
  165580. * Initialize for a downsampling pass.
  165581. */
  165582. METHODDEF(void)
  165583. start_pass_downsample (j_compress_ptr)
  165584. {
  165585. /* no work for now */
  165586. }
  165587. /*
  165588. * Expand a component horizontally from width input_cols to width output_cols,
  165589. * by duplicating the rightmost samples.
  165590. */
  165591. LOCAL(void)
  165592. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  165593. JDIMENSION input_cols, JDIMENSION output_cols)
  165594. {
  165595. register JSAMPROW ptr;
  165596. register JSAMPLE pixval;
  165597. register int count;
  165598. int row;
  165599. int numcols = (int) (output_cols - input_cols);
  165600. if (numcols > 0) {
  165601. for (row = 0; row < num_rows; row++) {
  165602. ptr = image_data[row] + input_cols;
  165603. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  165604. for (count = numcols; count > 0; count--)
  165605. *ptr++ = pixval;
  165606. }
  165607. }
  165608. }
  165609. /*
  165610. * Do downsampling for a whole row group (all components).
  165611. *
  165612. * In this version we simply downsample each component independently.
  165613. */
  165614. METHODDEF(void)
  165615. sep_downsample (j_compress_ptr cinfo,
  165616. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  165617. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  165618. {
  165619. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  165620. int ci;
  165621. jpeg_component_info * compptr;
  165622. JSAMPARRAY in_ptr, out_ptr;
  165623. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165624. ci++, compptr++) {
  165625. in_ptr = input_buf[ci] + in_row_index;
  165626. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  165627. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  165628. }
  165629. }
  165630. /*
  165631. * Downsample pixel values of a single component.
  165632. * One row group is processed per call.
  165633. * This version handles arbitrary integral sampling ratios, without smoothing.
  165634. * Note that this version is not actually used for customary sampling ratios.
  165635. */
  165636. METHODDEF(void)
  165637. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165638. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165639. {
  165640. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  165641. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  165642. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165643. JSAMPROW inptr, outptr;
  165644. INT32 outvalue;
  165645. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  165646. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  165647. numpix = h_expand * v_expand;
  165648. numpix2 = numpix/2;
  165649. /* Expand input data enough to let all the output samples be generated
  165650. * by the standard loop. Special-casing padded output would be more
  165651. * efficient.
  165652. */
  165653. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  165654. cinfo->image_width, output_cols * h_expand);
  165655. inrow = 0;
  165656. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165657. outptr = output_data[outrow];
  165658. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  165659. outcol++, outcol_h += h_expand) {
  165660. outvalue = 0;
  165661. for (v = 0; v < v_expand; v++) {
  165662. inptr = input_data[inrow+v] + outcol_h;
  165663. for (h = 0; h < h_expand; h++) {
  165664. outvalue += (INT32) GETJSAMPLE(*inptr++);
  165665. }
  165666. }
  165667. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  165668. }
  165669. inrow += v_expand;
  165670. }
  165671. }
  165672. /*
  165673. * Downsample pixel values of a single component.
  165674. * This version handles the special case of a full-size component,
  165675. * without smoothing.
  165676. */
  165677. METHODDEF(void)
  165678. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165679. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165680. {
  165681. /* Copy the data */
  165682. jcopy_sample_rows(input_data, 0, output_data, 0,
  165683. cinfo->max_v_samp_factor, cinfo->image_width);
  165684. /* Edge-expand */
  165685. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  165686. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  165687. }
  165688. /*
  165689. * Downsample pixel values of a single component.
  165690. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  165691. * without smoothing.
  165692. *
  165693. * A note about the "bias" calculations: when rounding fractional values to
  165694. * integer, we do not want to always round 0.5 up to the next integer.
  165695. * If we did that, we'd introduce a noticeable bias towards larger values.
  165696. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  165697. * alternate pixel locations (a simple ordered dither pattern).
  165698. */
  165699. METHODDEF(void)
  165700. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165701. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165702. {
  165703. int outrow;
  165704. JDIMENSION outcol;
  165705. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165706. register JSAMPROW inptr, outptr;
  165707. register int bias;
  165708. /* Expand input data enough to let all the output samples be generated
  165709. * by the standard loop. Special-casing padded output would be more
  165710. * efficient.
  165711. */
  165712. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  165713. cinfo->image_width, output_cols * 2);
  165714. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165715. outptr = output_data[outrow];
  165716. inptr = input_data[outrow];
  165717. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  165718. for (outcol = 0; outcol < output_cols; outcol++) {
  165719. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  165720. + bias) >> 1);
  165721. bias ^= 1; /* 0=>1, 1=>0 */
  165722. inptr += 2;
  165723. }
  165724. }
  165725. }
  165726. /*
  165727. * Downsample pixel values of a single component.
  165728. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  165729. * without smoothing.
  165730. */
  165731. METHODDEF(void)
  165732. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165733. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165734. {
  165735. int inrow, outrow;
  165736. JDIMENSION outcol;
  165737. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165738. register JSAMPROW inptr0, inptr1, outptr;
  165739. register int bias;
  165740. /* Expand input data enough to let all the output samples be generated
  165741. * by the standard loop. Special-casing padded output would be more
  165742. * efficient.
  165743. */
  165744. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  165745. cinfo->image_width, output_cols * 2);
  165746. inrow = 0;
  165747. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165748. outptr = output_data[outrow];
  165749. inptr0 = input_data[inrow];
  165750. inptr1 = input_data[inrow+1];
  165751. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  165752. for (outcol = 0; outcol < output_cols; outcol++) {
  165753. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  165754. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  165755. + bias) >> 2);
  165756. bias ^= 3; /* 1=>2, 2=>1 */
  165757. inptr0 += 2; inptr1 += 2;
  165758. }
  165759. inrow += 2;
  165760. }
  165761. }
  165762. #ifdef INPUT_SMOOTHING_SUPPORTED
  165763. /*
  165764. * Downsample pixel values of a single component.
  165765. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  165766. * with smoothing. One row of context is required.
  165767. */
  165768. METHODDEF(void)
  165769. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165770. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165771. {
  165772. int inrow, outrow;
  165773. JDIMENSION colctr;
  165774. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165775. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  165776. INT32 membersum, neighsum, memberscale, neighscale;
  165777. /* Expand input data enough to let all the output samples be generated
  165778. * by the standard loop. Special-casing padded output would be more
  165779. * efficient.
  165780. */
  165781. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  165782. cinfo->image_width, output_cols * 2);
  165783. /* We don't bother to form the individual "smoothed" input pixel values;
  165784. * we can directly compute the output which is the average of the four
  165785. * smoothed values. Each of the four member pixels contributes a fraction
  165786. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  165787. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  165788. * output. The four corner-adjacent neighbor pixels contribute a fraction
  165789. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  165790. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  165791. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  165792. * factors are scaled by 2^16 = 65536.
  165793. * Also recall that SF = smoothing_factor / 1024.
  165794. */
  165795. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  165796. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  165797. inrow = 0;
  165798. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165799. outptr = output_data[outrow];
  165800. inptr0 = input_data[inrow];
  165801. inptr1 = input_data[inrow+1];
  165802. above_ptr = input_data[inrow-1];
  165803. below_ptr = input_data[inrow+2];
  165804. /* Special case for first column: pretend column -1 is same as column 0 */
  165805. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  165806. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  165807. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  165808. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  165809. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  165810. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  165811. neighsum += neighsum;
  165812. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  165813. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  165814. membersum = membersum * memberscale + neighsum * neighscale;
  165815. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  165816. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  165817. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  165818. /* sum of pixels directly mapped to this output element */
  165819. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  165820. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  165821. /* sum of edge-neighbor pixels */
  165822. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  165823. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  165824. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  165825. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  165826. /* The edge-neighbors count twice as much as corner-neighbors */
  165827. neighsum += neighsum;
  165828. /* Add in the corner-neighbors */
  165829. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  165830. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  165831. /* form final output scaled up by 2^16 */
  165832. membersum = membersum * memberscale + neighsum * neighscale;
  165833. /* round, descale and output it */
  165834. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  165835. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  165836. }
  165837. /* Special case for last column */
  165838. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  165839. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  165840. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  165841. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  165842. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  165843. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  165844. neighsum += neighsum;
  165845. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  165846. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  165847. membersum = membersum * memberscale + neighsum * neighscale;
  165848. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  165849. inrow += 2;
  165850. }
  165851. }
  165852. /*
  165853. * Downsample pixel values of a single component.
  165854. * This version handles the special case of a full-size component,
  165855. * with smoothing. One row of context is required.
  165856. */
  165857. METHODDEF(void)
  165858. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  165859. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165860. {
  165861. int outrow;
  165862. JDIMENSION colctr;
  165863. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165864. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  165865. INT32 membersum, neighsum, memberscale, neighscale;
  165866. int colsum, lastcolsum, nextcolsum;
  165867. /* Expand input data enough to let all the output samples be generated
  165868. * by the standard loop. Special-casing padded output would be more
  165869. * efficient.
  165870. */
  165871. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  165872. cinfo->image_width, output_cols);
  165873. /* Each of the eight neighbor pixels contributes a fraction SF to the
  165874. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  165875. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  165876. * Also recall that SF = smoothing_factor / 1024.
  165877. */
  165878. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  165879. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  165880. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165881. outptr = output_data[outrow];
  165882. inptr = input_data[outrow];
  165883. above_ptr = input_data[outrow-1];
  165884. below_ptr = input_data[outrow+1];
  165885. /* Special case for first column */
  165886. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  165887. GETJSAMPLE(*inptr);
  165888. membersum = GETJSAMPLE(*inptr++);
  165889. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  165890. GETJSAMPLE(*inptr);
  165891. neighsum = colsum + (colsum - membersum) + nextcolsum;
  165892. membersum = membersum * memberscale + neighsum * neighscale;
  165893. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  165894. lastcolsum = colsum; colsum = nextcolsum;
  165895. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  165896. membersum = GETJSAMPLE(*inptr++);
  165897. above_ptr++; below_ptr++;
  165898. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  165899. GETJSAMPLE(*inptr);
  165900. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  165901. membersum = membersum * memberscale + neighsum * neighscale;
  165902. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  165903. lastcolsum = colsum; colsum = nextcolsum;
  165904. }
  165905. /* Special case for last column */
  165906. membersum = GETJSAMPLE(*inptr);
  165907. neighsum = lastcolsum + (colsum - membersum) + colsum;
  165908. membersum = membersum * memberscale + neighsum * neighscale;
  165909. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  165910. }
  165911. }
  165912. #endif /* INPUT_SMOOTHING_SUPPORTED */
  165913. /*
  165914. * Module initialization routine for downsampling.
  165915. * Note that we must select a routine for each component.
  165916. */
  165917. GLOBAL(void)
  165918. jinit_downsampler (j_compress_ptr cinfo)
  165919. {
  165920. my_downsample_ptr downsample;
  165921. int ci;
  165922. jpeg_component_info * compptr;
  165923. boolean smoothok = TRUE;
  165924. downsample = (my_downsample_ptr)
  165925. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165926. SIZEOF(my_downsampler));
  165927. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  165928. downsample->pub.start_pass = start_pass_downsample;
  165929. downsample->pub.downsample = sep_downsample;
  165930. downsample->pub.need_context_rows = FALSE;
  165931. if (cinfo->CCIR601_sampling)
  165932. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  165933. /* Verify we can handle the sampling factors, and set up method pointers */
  165934. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165935. ci++, compptr++) {
  165936. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  165937. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  165938. #ifdef INPUT_SMOOTHING_SUPPORTED
  165939. if (cinfo->smoothing_factor) {
  165940. downsample->methods[ci] = fullsize_smooth_downsample;
  165941. downsample->pub.need_context_rows = TRUE;
  165942. } else
  165943. #endif
  165944. downsample->methods[ci] = fullsize_downsample;
  165945. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  165946. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  165947. smoothok = FALSE;
  165948. downsample->methods[ci] = h2v1_downsample;
  165949. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  165950. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  165951. #ifdef INPUT_SMOOTHING_SUPPORTED
  165952. if (cinfo->smoothing_factor) {
  165953. downsample->methods[ci] = h2v2_smooth_downsample;
  165954. downsample->pub.need_context_rows = TRUE;
  165955. } else
  165956. #endif
  165957. downsample->methods[ci] = h2v2_downsample;
  165958. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  165959. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  165960. smoothok = FALSE;
  165961. downsample->methods[ci] = int_downsample;
  165962. } else
  165963. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  165964. }
  165965. #ifdef INPUT_SMOOTHING_SUPPORTED
  165966. if (cinfo->smoothing_factor && !smoothok)
  165967. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  165968. #endif
  165969. }
  165970. /*** End of inlined file: jcsample.c ***/
  165971. /*** Start of inlined file: jctrans.c ***/
  165972. #define JPEG_INTERNALS
  165973. /* Forward declarations */
  165974. LOCAL(void) transencode_master_selection
  165975. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  165976. LOCAL(void) transencode_coef_controller
  165977. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  165978. /*
  165979. * Compression initialization for writing raw-coefficient data.
  165980. * Before calling this, all parameters and a data destination must be set up.
  165981. * Call jpeg_finish_compress() to actually write the data.
  165982. *
  165983. * The number of passed virtual arrays must match cinfo->num_components.
  165984. * Note that the virtual arrays need not be filled or even realized at
  165985. * the time write_coefficients is called; indeed, if the virtual arrays
  165986. * were requested from this compression object's memory manager, they
  165987. * typically will be realized during this routine and filled afterwards.
  165988. */
  165989. GLOBAL(void)
  165990. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  165991. {
  165992. if (cinfo->global_state != CSTATE_START)
  165993. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165994. /* Mark all tables to be written */
  165995. jpeg_suppress_tables(cinfo, FALSE);
  165996. /* (Re)initialize error mgr and destination modules */
  165997. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  165998. (*cinfo->dest->init_destination) (cinfo);
  165999. /* Perform master selection of active modules */
  166000. transencode_master_selection(cinfo, coef_arrays);
  166001. /* Wait for jpeg_finish_compress() call */
  166002. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166003. cinfo->global_state = CSTATE_WRCOEFS;
  166004. }
  166005. /*
  166006. * Initialize the compression object with default parameters,
  166007. * then copy from the source object all parameters needed for lossless
  166008. * transcoding. Parameters that can be varied without loss (such as
  166009. * scan script and Huffman optimization) are left in their default states.
  166010. */
  166011. GLOBAL(void)
  166012. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166013. j_compress_ptr dstinfo)
  166014. {
  166015. JQUANT_TBL ** qtblptr;
  166016. jpeg_component_info *incomp, *outcomp;
  166017. JQUANT_TBL *c_quant, *slot_quant;
  166018. int tblno, ci, coefi;
  166019. /* Safety check to ensure start_compress not called yet. */
  166020. if (dstinfo->global_state != CSTATE_START)
  166021. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166022. /* Copy fundamental image dimensions */
  166023. dstinfo->image_width = srcinfo->image_width;
  166024. dstinfo->image_height = srcinfo->image_height;
  166025. dstinfo->input_components = srcinfo->num_components;
  166026. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166027. /* Initialize all parameters to default values */
  166028. jpeg_set_defaults(dstinfo);
  166029. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166030. * Fix it to get the right header markers for the image colorspace.
  166031. */
  166032. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166033. dstinfo->data_precision = srcinfo->data_precision;
  166034. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166035. /* Copy the source's quantization tables. */
  166036. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166037. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166038. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166039. if (*qtblptr == NULL)
  166040. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166041. MEMCOPY((*qtblptr)->quantval,
  166042. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166043. SIZEOF((*qtblptr)->quantval));
  166044. (*qtblptr)->sent_table = FALSE;
  166045. }
  166046. }
  166047. /* Copy the source's per-component info.
  166048. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166049. */
  166050. dstinfo->num_components = srcinfo->num_components;
  166051. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166052. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166053. MAX_COMPONENTS);
  166054. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166055. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166056. outcomp->component_id = incomp->component_id;
  166057. outcomp->h_samp_factor = incomp->h_samp_factor;
  166058. outcomp->v_samp_factor = incomp->v_samp_factor;
  166059. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166060. /* Make sure saved quantization table for component matches the qtable
  166061. * slot. If not, the input file re-used this qtable slot.
  166062. * IJG encoder currently cannot duplicate this.
  166063. */
  166064. tblno = outcomp->quant_tbl_no;
  166065. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166066. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166067. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166068. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166069. c_quant = incomp->quant_table;
  166070. if (c_quant != NULL) {
  166071. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166072. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166073. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166074. }
  166075. }
  166076. /* Note: we do not copy the source's Huffman table assignments;
  166077. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166078. */
  166079. }
  166080. /* Also copy JFIF version and resolution information, if available.
  166081. * Strictly speaking this isn't "critical" info, but it's nearly
  166082. * always appropriate to copy it if available. In particular,
  166083. * if the application chooses to copy JFIF 1.02 extension markers from
  166084. * the source file, we need to copy the version to make sure we don't
  166085. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166086. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166087. */
  166088. if (srcinfo->saw_JFIF_marker) {
  166089. if (srcinfo->JFIF_major_version == 1) {
  166090. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166091. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166092. }
  166093. dstinfo->density_unit = srcinfo->density_unit;
  166094. dstinfo->X_density = srcinfo->X_density;
  166095. dstinfo->Y_density = srcinfo->Y_density;
  166096. }
  166097. }
  166098. /*
  166099. * Master selection of compression modules for transcoding.
  166100. * This substitutes for jcinit.c's initialization of the full compressor.
  166101. */
  166102. LOCAL(void)
  166103. transencode_master_selection (j_compress_ptr cinfo,
  166104. jvirt_barray_ptr * coef_arrays)
  166105. {
  166106. /* Although we don't actually use input_components for transcoding,
  166107. * jcmaster.c's initial_setup will complain if input_components is 0.
  166108. */
  166109. cinfo->input_components = 1;
  166110. /* Initialize master control (includes parameter checking/processing) */
  166111. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166112. /* Entropy encoding: either Huffman or arithmetic coding. */
  166113. if (cinfo->arith_code) {
  166114. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166115. } else {
  166116. if (cinfo->progressive_mode) {
  166117. #ifdef C_PROGRESSIVE_SUPPORTED
  166118. jinit_phuff_encoder(cinfo);
  166119. #else
  166120. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166121. #endif
  166122. } else
  166123. jinit_huff_encoder(cinfo);
  166124. }
  166125. /* We need a special coefficient buffer controller. */
  166126. transencode_coef_controller(cinfo, coef_arrays);
  166127. jinit_marker_writer(cinfo);
  166128. /* We can now tell the memory manager to allocate virtual arrays. */
  166129. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166130. /* Write the datastream header (SOI, JFIF) immediately.
  166131. * Frame and scan headers are postponed till later.
  166132. * This lets application insert special markers after the SOI.
  166133. */
  166134. (*cinfo->marker->write_file_header) (cinfo);
  166135. }
  166136. /*
  166137. * The rest of this file is a special implementation of the coefficient
  166138. * buffer controller. This is similar to jccoefct.c, but it handles only
  166139. * output from presupplied virtual arrays. Furthermore, we generate any
  166140. * dummy padding blocks on-the-fly rather than expecting them to be present
  166141. * in the arrays.
  166142. */
  166143. /* Private buffer controller object */
  166144. typedef struct {
  166145. struct jpeg_c_coef_controller pub; /* public fields */
  166146. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  166147. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  166148. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  166149. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  166150. /* Virtual block array for each component. */
  166151. jvirt_barray_ptr * whole_image;
  166152. /* Workspace for constructing dummy blocks at right/bottom edges. */
  166153. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  166154. } my_coef_controller2;
  166155. typedef my_coef_controller2 * my_coef_ptr2;
  166156. LOCAL(void)
  166157. start_iMCU_row2 (j_compress_ptr cinfo)
  166158. /* Reset within-iMCU-row counters for a new row */
  166159. {
  166160. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166161. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  166162. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  166163. * But at the bottom of the image, process only what's left.
  166164. */
  166165. if (cinfo->comps_in_scan > 1) {
  166166. coef->MCU_rows_per_iMCU_row = 1;
  166167. } else {
  166168. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  166169. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  166170. else
  166171. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  166172. }
  166173. coef->mcu_ctr = 0;
  166174. coef->MCU_vert_offset = 0;
  166175. }
  166176. /*
  166177. * Initialize for a processing pass.
  166178. */
  166179. METHODDEF(void)
  166180. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166181. {
  166182. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166183. if (pass_mode != JBUF_CRANK_DEST)
  166184. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166185. coef->iMCU_row_num = 0;
  166186. start_iMCU_row2(cinfo);
  166187. }
  166188. /*
  166189. * Process some data.
  166190. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  166191. * per call, ie, v_samp_factor block rows for each component in the scan.
  166192. * The data is obtained from the virtual arrays and fed to the entropy coder.
  166193. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  166194. *
  166195. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  166196. */
  166197. METHODDEF(boolean)
  166198. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  166199. {
  166200. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166201. JDIMENSION MCU_col_num; /* index of current MCU within row */
  166202. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  166203. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  166204. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  166205. JDIMENSION start_col;
  166206. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  166207. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  166208. JBLOCKROW buffer_ptr;
  166209. jpeg_component_info *compptr;
  166210. /* Align the virtual buffers for the components used in this scan. */
  166211. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166212. compptr = cinfo->cur_comp_info[ci];
  166213. buffer[ci] = (*cinfo->mem->access_virt_barray)
  166214. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  166215. coef->iMCU_row_num * compptr->v_samp_factor,
  166216. (JDIMENSION) compptr->v_samp_factor, FALSE);
  166217. }
  166218. /* Loop to process one whole iMCU row */
  166219. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  166220. yoffset++) {
  166221. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  166222. MCU_col_num++) {
  166223. /* Construct list of pointers to DCT blocks belonging to this MCU */
  166224. blkn = 0; /* index of current DCT block within MCU */
  166225. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166226. compptr = cinfo->cur_comp_info[ci];
  166227. start_col = MCU_col_num * compptr->MCU_width;
  166228. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  166229. : compptr->last_col_width;
  166230. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  166231. if (coef->iMCU_row_num < last_iMCU_row ||
  166232. yindex+yoffset < compptr->last_row_height) {
  166233. /* Fill in pointers to real blocks in this row */
  166234. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  166235. for (xindex = 0; xindex < blockcnt; xindex++)
  166236. MCU_buffer[blkn++] = buffer_ptr++;
  166237. } else {
  166238. /* At bottom of image, need a whole row of dummy blocks */
  166239. xindex = 0;
  166240. }
  166241. /* Fill in any dummy blocks needed in this row.
  166242. * Dummy blocks are filled in the same way as in jccoefct.c:
  166243. * all zeroes in the AC entries, DC entries equal to previous
  166244. * block's DC value. The init routine has already zeroed the
  166245. * AC entries, so we need only set the DC entries correctly.
  166246. */
  166247. for (; xindex < compptr->MCU_width; xindex++) {
  166248. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  166249. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  166250. blkn++;
  166251. }
  166252. }
  166253. }
  166254. /* Try to write the MCU. */
  166255. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  166256. /* Suspension forced; update state counters and exit */
  166257. coef->MCU_vert_offset = yoffset;
  166258. coef->mcu_ctr = MCU_col_num;
  166259. return FALSE;
  166260. }
  166261. }
  166262. /* Completed an MCU row, but perhaps not an iMCU row */
  166263. coef->mcu_ctr = 0;
  166264. }
  166265. /* Completed the iMCU row, advance counters for next one */
  166266. coef->iMCU_row_num++;
  166267. start_iMCU_row2(cinfo);
  166268. return TRUE;
  166269. }
  166270. /*
  166271. * Initialize coefficient buffer controller.
  166272. *
  166273. * Each passed coefficient array must be the right size for that
  166274. * coefficient: width_in_blocks wide and height_in_blocks high,
  166275. * with unitheight at least v_samp_factor.
  166276. */
  166277. LOCAL(void)
  166278. transencode_coef_controller (j_compress_ptr cinfo,
  166279. jvirt_barray_ptr * coef_arrays)
  166280. {
  166281. my_coef_ptr2 coef;
  166282. JBLOCKROW buffer;
  166283. int i;
  166284. coef = (my_coef_ptr2)
  166285. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166286. SIZEOF(my_coef_controller2));
  166287. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  166288. coef->pub.start_pass = start_pass_coef2;
  166289. coef->pub.compress_data = compress_output2;
  166290. /* Save pointer to virtual arrays */
  166291. coef->whole_image = coef_arrays;
  166292. /* Allocate and pre-zero space for dummy DCT blocks. */
  166293. buffer = (JBLOCKROW)
  166294. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166295. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166296. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166297. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  166298. coef->dummy_buffer[i] = buffer + i;
  166299. }
  166300. }
  166301. /*** End of inlined file: jctrans.c ***/
  166302. /*** Start of inlined file: jdapistd.c ***/
  166303. #define JPEG_INTERNALS
  166304. /* Forward declarations */
  166305. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  166306. /*
  166307. * Decompression initialization.
  166308. * jpeg_read_header must be completed before calling this.
  166309. *
  166310. * If a multipass operating mode was selected, this will do all but the
  166311. * last pass, and thus may take a great deal of time.
  166312. *
  166313. * Returns FALSE if suspended. The return value need be inspected only if
  166314. * a suspending data source is used.
  166315. */
  166316. GLOBAL(boolean)
  166317. jpeg_start_decompress (j_decompress_ptr cinfo)
  166318. {
  166319. if (cinfo->global_state == DSTATE_READY) {
  166320. /* First call: initialize master control, select active modules */
  166321. jinit_master_decompress(cinfo);
  166322. if (cinfo->buffered_image) {
  166323. /* No more work here; expecting jpeg_start_output next */
  166324. cinfo->global_state = DSTATE_BUFIMAGE;
  166325. return TRUE;
  166326. }
  166327. cinfo->global_state = DSTATE_PRELOAD;
  166328. }
  166329. if (cinfo->global_state == DSTATE_PRELOAD) {
  166330. /* If file has multiple scans, absorb them all into the coef buffer */
  166331. if (cinfo->inputctl->has_multiple_scans) {
  166332. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166333. for (;;) {
  166334. int retcode;
  166335. /* Call progress monitor hook if present */
  166336. if (cinfo->progress != NULL)
  166337. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166338. /* Absorb some more input */
  166339. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166340. if (retcode == JPEG_SUSPENDED)
  166341. return FALSE;
  166342. if (retcode == JPEG_REACHED_EOI)
  166343. break;
  166344. /* Advance progress counter if appropriate */
  166345. if (cinfo->progress != NULL &&
  166346. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  166347. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  166348. /* jdmaster underestimated number of scans; ratchet up one scan */
  166349. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  166350. }
  166351. }
  166352. }
  166353. #else
  166354. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166355. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166356. }
  166357. cinfo->output_scan_number = cinfo->input_scan_number;
  166358. } else if (cinfo->global_state != DSTATE_PRESCAN)
  166359. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166360. /* Perform any dummy output passes, and set up for the final pass */
  166361. return output_pass_setup(cinfo);
  166362. }
  166363. /*
  166364. * Set up for an output pass, and perform any dummy pass(es) needed.
  166365. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  166366. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  166367. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  166368. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  166369. */
  166370. LOCAL(boolean)
  166371. output_pass_setup (j_decompress_ptr cinfo)
  166372. {
  166373. if (cinfo->global_state != DSTATE_PRESCAN) {
  166374. /* First call: do pass setup */
  166375. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166376. cinfo->output_scanline = 0;
  166377. cinfo->global_state = DSTATE_PRESCAN;
  166378. }
  166379. /* Loop over any required dummy passes */
  166380. while (cinfo->master->is_dummy_pass) {
  166381. #ifdef QUANT_2PASS_SUPPORTED
  166382. /* Crank through the dummy pass */
  166383. while (cinfo->output_scanline < cinfo->output_height) {
  166384. JDIMENSION last_scanline;
  166385. /* Call progress monitor hook if present */
  166386. if (cinfo->progress != NULL) {
  166387. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166388. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166389. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166390. }
  166391. /* Process some data */
  166392. last_scanline = cinfo->output_scanline;
  166393. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  166394. &cinfo->output_scanline, (JDIMENSION) 0);
  166395. if (cinfo->output_scanline == last_scanline)
  166396. return FALSE; /* No progress made, must suspend */
  166397. }
  166398. /* Finish up dummy pass, and set up for another one */
  166399. (*cinfo->master->finish_output_pass) (cinfo);
  166400. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166401. cinfo->output_scanline = 0;
  166402. #else
  166403. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166404. #endif /* QUANT_2PASS_SUPPORTED */
  166405. }
  166406. /* Ready for application to drive output pass through
  166407. * jpeg_read_scanlines or jpeg_read_raw_data.
  166408. */
  166409. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  166410. return TRUE;
  166411. }
  166412. /*
  166413. * Read some scanlines of data from the JPEG decompressor.
  166414. *
  166415. * The return value will be the number of lines actually read.
  166416. * This may be less than the number requested in several cases,
  166417. * including bottom of image, data source suspension, and operating
  166418. * modes that emit multiple scanlines at a time.
  166419. *
  166420. * Note: we warn about excess calls to jpeg_read_scanlines() since
  166421. * this likely signals an application programmer error. However,
  166422. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  166423. */
  166424. GLOBAL(JDIMENSION)
  166425. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  166426. JDIMENSION max_lines)
  166427. {
  166428. JDIMENSION row_ctr;
  166429. if (cinfo->global_state != DSTATE_SCANNING)
  166430. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166431. if (cinfo->output_scanline >= cinfo->output_height) {
  166432. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  166433. return 0;
  166434. }
  166435. /* Call progress monitor hook if present */
  166436. if (cinfo->progress != NULL) {
  166437. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166438. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166439. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166440. }
  166441. /* Process some data */
  166442. row_ctr = 0;
  166443. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  166444. cinfo->output_scanline += row_ctr;
  166445. return row_ctr;
  166446. }
  166447. /*
  166448. * Alternate entry point to read raw data.
  166449. * Processes exactly one iMCU row per call, unless suspended.
  166450. */
  166451. GLOBAL(JDIMENSION)
  166452. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  166453. JDIMENSION max_lines)
  166454. {
  166455. JDIMENSION lines_per_iMCU_row;
  166456. if (cinfo->global_state != DSTATE_RAW_OK)
  166457. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166458. if (cinfo->output_scanline >= cinfo->output_height) {
  166459. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  166460. return 0;
  166461. }
  166462. /* Call progress monitor hook if present */
  166463. if (cinfo->progress != NULL) {
  166464. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166465. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166466. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166467. }
  166468. /* Verify that at least one iMCU row can be returned. */
  166469. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  166470. if (max_lines < lines_per_iMCU_row)
  166471. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  166472. /* Decompress directly into user's buffer. */
  166473. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  166474. return 0; /* suspension forced, can do nothing more */
  166475. /* OK, we processed one iMCU row. */
  166476. cinfo->output_scanline += lines_per_iMCU_row;
  166477. return lines_per_iMCU_row;
  166478. }
  166479. /* Additional entry points for buffered-image mode. */
  166480. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166481. /*
  166482. * Initialize for an output pass in buffered-image mode.
  166483. */
  166484. GLOBAL(boolean)
  166485. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  166486. {
  166487. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  166488. cinfo->global_state != DSTATE_PRESCAN)
  166489. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166490. /* Limit scan number to valid range */
  166491. if (scan_number <= 0)
  166492. scan_number = 1;
  166493. if (cinfo->inputctl->eoi_reached &&
  166494. scan_number > cinfo->input_scan_number)
  166495. scan_number = cinfo->input_scan_number;
  166496. cinfo->output_scan_number = scan_number;
  166497. /* Perform any dummy output passes, and set up for the real pass */
  166498. return output_pass_setup(cinfo);
  166499. }
  166500. /*
  166501. * Finish up after an output pass in buffered-image mode.
  166502. *
  166503. * Returns FALSE if suspended. The return value need be inspected only if
  166504. * a suspending data source is used.
  166505. */
  166506. GLOBAL(boolean)
  166507. jpeg_finish_output (j_decompress_ptr cinfo)
  166508. {
  166509. if ((cinfo->global_state == DSTATE_SCANNING ||
  166510. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  166511. /* Terminate this pass. */
  166512. /* We do not require the whole pass to have been completed. */
  166513. (*cinfo->master->finish_output_pass) (cinfo);
  166514. cinfo->global_state = DSTATE_BUFPOST;
  166515. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  166516. /* BUFPOST = repeat call after a suspension, anything else is error */
  166517. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166518. }
  166519. /* Read markers looking for SOS or EOI */
  166520. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  166521. ! cinfo->inputctl->eoi_reached) {
  166522. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  166523. return FALSE; /* Suspend, come back later */
  166524. }
  166525. cinfo->global_state = DSTATE_BUFIMAGE;
  166526. return TRUE;
  166527. }
  166528. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166529. /*** End of inlined file: jdapistd.c ***/
  166530. /*** Start of inlined file: jdapimin.c ***/
  166531. #define JPEG_INTERNALS
  166532. /*
  166533. * Initialization of a JPEG decompression object.
  166534. * The error manager must already be set up (in case memory manager fails).
  166535. */
  166536. GLOBAL(void)
  166537. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  166538. {
  166539. int i;
  166540. /* Guard against version mismatches between library and caller. */
  166541. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  166542. if (version != JPEG_LIB_VERSION)
  166543. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  166544. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  166545. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  166546. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  166547. /* For debugging purposes, we zero the whole master structure.
  166548. * But the application has already set the err pointer, and may have set
  166549. * client_data, so we have to save and restore those fields.
  166550. * Note: if application hasn't set client_data, tools like Purify may
  166551. * complain here.
  166552. */
  166553. {
  166554. struct jpeg_error_mgr * err = cinfo->err;
  166555. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  166556. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  166557. cinfo->err = err;
  166558. cinfo->client_data = client_data;
  166559. }
  166560. cinfo->is_decompressor = TRUE;
  166561. /* Initialize a memory manager instance for this object */
  166562. jinit_memory_mgr((j_common_ptr) cinfo);
  166563. /* Zero out pointers to permanent structures. */
  166564. cinfo->progress = NULL;
  166565. cinfo->src = NULL;
  166566. for (i = 0; i < NUM_QUANT_TBLS; i++)
  166567. cinfo->quant_tbl_ptrs[i] = NULL;
  166568. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166569. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  166570. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  166571. }
  166572. /* Initialize marker processor so application can override methods
  166573. * for COM, APPn markers before calling jpeg_read_header.
  166574. */
  166575. cinfo->marker_list = NULL;
  166576. jinit_marker_reader(cinfo);
  166577. /* And initialize the overall input controller. */
  166578. jinit_input_controller(cinfo);
  166579. /* OK, I'm ready */
  166580. cinfo->global_state = DSTATE_START;
  166581. }
  166582. /*
  166583. * Destruction of a JPEG decompression object
  166584. */
  166585. GLOBAL(void)
  166586. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  166587. {
  166588. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  166589. }
  166590. /*
  166591. * Abort processing of a JPEG decompression operation,
  166592. * but don't destroy the object itself.
  166593. */
  166594. GLOBAL(void)
  166595. jpeg_abort_decompress (j_decompress_ptr cinfo)
  166596. {
  166597. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  166598. }
  166599. /*
  166600. * Set default decompression parameters.
  166601. */
  166602. LOCAL(void)
  166603. default_decompress_parms (j_decompress_ptr cinfo)
  166604. {
  166605. /* Guess the input colorspace, and set output colorspace accordingly. */
  166606. /* (Wish JPEG committee had provided a real way to specify this...) */
  166607. /* Note application may override our guesses. */
  166608. switch (cinfo->num_components) {
  166609. case 1:
  166610. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  166611. cinfo->out_color_space = JCS_GRAYSCALE;
  166612. break;
  166613. case 3:
  166614. if (cinfo->saw_JFIF_marker) {
  166615. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  166616. } else if (cinfo->saw_Adobe_marker) {
  166617. switch (cinfo->Adobe_transform) {
  166618. case 0:
  166619. cinfo->jpeg_color_space = JCS_RGB;
  166620. break;
  166621. case 1:
  166622. cinfo->jpeg_color_space = JCS_YCbCr;
  166623. break;
  166624. default:
  166625. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  166626. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  166627. break;
  166628. }
  166629. } else {
  166630. /* Saw no special markers, try to guess from the component IDs */
  166631. int cid0 = cinfo->comp_info[0].component_id;
  166632. int cid1 = cinfo->comp_info[1].component_id;
  166633. int cid2 = cinfo->comp_info[2].component_id;
  166634. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  166635. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  166636. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  166637. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  166638. else {
  166639. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  166640. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  166641. }
  166642. }
  166643. /* Always guess RGB is proper output colorspace. */
  166644. cinfo->out_color_space = JCS_RGB;
  166645. break;
  166646. case 4:
  166647. if (cinfo->saw_Adobe_marker) {
  166648. switch (cinfo->Adobe_transform) {
  166649. case 0:
  166650. cinfo->jpeg_color_space = JCS_CMYK;
  166651. break;
  166652. case 2:
  166653. cinfo->jpeg_color_space = JCS_YCCK;
  166654. break;
  166655. default:
  166656. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  166657. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  166658. break;
  166659. }
  166660. } else {
  166661. /* No special markers, assume straight CMYK. */
  166662. cinfo->jpeg_color_space = JCS_CMYK;
  166663. }
  166664. cinfo->out_color_space = JCS_CMYK;
  166665. break;
  166666. default:
  166667. cinfo->jpeg_color_space = JCS_UNKNOWN;
  166668. cinfo->out_color_space = JCS_UNKNOWN;
  166669. break;
  166670. }
  166671. /* Set defaults for other decompression parameters. */
  166672. cinfo->scale_num = 1; /* 1:1 scaling */
  166673. cinfo->scale_denom = 1;
  166674. cinfo->output_gamma = 1.0;
  166675. cinfo->buffered_image = FALSE;
  166676. cinfo->raw_data_out = FALSE;
  166677. cinfo->dct_method = JDCT_DEFAULT;
  166678. cinfo->do_fancy_upsampling = TRUE;
  166679. cinfo->do_block_smoothing = TRUE;
  166680. cinfo->quantize_colors = FALSE;
  166681. /* We set these in case application only sets quantize_colors. */
  166682. cinfo->dither_mode = JDITHER_FS;
  166683. #ifdef QUANT_2PASS_SUPPORTED
  166684. cinfo->two_pass_quantize = TRUE;
  166685. #else
  166686. cinfo->two_pass_quantize = FALSE;
  166687. #endif
  166688. cinfo->desired_number_of_colors = 256;
  166689. cinfo->colormap = NULL;
  166690. /* Initialize for no mode change in buffered-image mode. */
  166691. cinfo->enable_1pass_quant = FALSE;
  166692. cinfo->enable_external_quant = FALSE;
  166693. cinfo->enable_2pass_quant = FALSE;
  166694. }
  166695. /*
  166696. * Decompression startup: read start of JPEG datastream to see what's there.
  166697. * Need only initialize JPEG object and supply a data source before calling.
  166698. *
  166699. * This routine will read as far as the first SOS marker (ie, actual start of
  166700. * compressed data), and will save all tables and parameters in the JPEG
  166701. * object. It will also initialize the decompression parameters to default
  166702. * values, and finally return JPEG_HEADER_OK. On return, the application may
  166703. * adjust the decompression parameters and then call jpeg_start_decompress.
  166704. * (Or, if the application only wanted to determine the image parameters,
  166705. * the data need not be decompressed. In that case, call jpeg_abort or
  166706. * jpeg_destroy to release any temporary space.)
  166707. * If an abbreviated (tables only) datastream is presented, the routine will
  166708. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  166709. * re-use the JPEG object to read the abbreviated image datastream(s).
  166710. * It is unnecessary (but OK) to call jpeg_abort in this case.
  166711. * The JPEG_SUSPENDED return code only occurs if the data source module
  166712. * requests suspension of the decompressor. In this case the application
  166713. * should load more source data and then re-call jpeg_read_header to resume
  166714. * processing.
  166715. * If a non-suspending data source is used and require_image is TRUE, then the
  166716. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  166717. *
  166718. * This routine is now just a front end to jpeg_consume_input, with some
  166719. * extra error checking.
  166720. */
  166721. GLOBAL(int)
  166722. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  166723. {
  166724. int retcode;
  166725. if (cinfo->global_state != DSTATE_START &&
  166726. cinfo->global_state != DSTATE_INHEADER)
  166727. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166728. retcode = jpeg_consume_input(cinfo);
  166729. switch (retcode) {
  166730. case JPEG_REACHED_SOS:
  166731. retcode = JPEG_HEADER_OK;
  166732. break;
  166733. case JPEG_REACHED_EOI:
  166734. if (require_image) /* Complain if application wanted an image */
  166735. ERREXIT(cinfo, JERR_NO_IMAGE);
  166736. /* Reset to start state; it would be safer to require the application to
  166737. * call jpeg_abort, but we can't change it now for compatibility reasons.
  166738. * A side effect is to free any temporary memory (there shouldn't be any).
  166739. */
  166740. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  166741. retcode = JPEG_HEADER_TABLES_ONLY;
  166742. break;
  166743. case JPEG_SUSPENDED:
  166744. /* no work */
  166745. break;
  166746. }
  166747. return retcode;
  166748. }
  166749. /*
  166750. * Consume data in advance of what the decompressor requires.
  166751. * This can be called at any time once the decompressor object has
  166752. * been created and a data source has been set up.
  166753. *
  166754. * This routine is essentially a state machine that handles a couple
  166755. * of critical state-transition actions, namely initial setup and
  166756. * transition from header scanning to ready-for-start_decompress.
  166757. * All the actual input is done via the input controller's consume_input
  166758. * method.
  166759. */
  166760. GLOBAL(int)
  166761. jpeg_consume_input (j_decompress_ptr cinfo)
  166762. {
  166763. int retcode = JPEG_SUSPENDED;
  166764. /* NB: every possible DSTATE value should be listed in this switch */
  166765. switch (cinfo->global_state) {
  166766. case DSTATE_START:
  166767. /* Start-of-datastream actions: reset appropriate modules */
  166768. (*cinfo->inputctl->reset_input_controller) (cinfo);
  166769. /* Initialize application's data source module */
  166770. (*cinfo->src->init_source) (cinfo);
  166771. cinfo->global_state = DSTATE_INHEADER;
  166772. /*FALLTHROUGH*/
  166773. case DSTATE_INHEADER:
  166774. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166775. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  166776. /* Set up default parameters based on header data */
  166777. default_decompress_parms(cinfo);
  166778. /* Set global state: ready for start_decompress */
  166779. cinfo->global_state = DSTATE_READY;
  166780. }
  166781. break;
  166782. case DSTATE_READY:
  166783. /* Can't advance past first SOS until start_decompress is called */
  166784. retcode = JPEG_REACHED_SOS;
  166785. break;
  166786. case DSTATE_PRELOAD:
  166787. case DSTATE_PRESCAN:
  166788. case DSTATE_SCANNING:
  166789. case DSTATE_RAW_OK:
  166790. case DSTATE_BUFIMAGE:
  166791. case DSTATE_BUFPOST:
  166792. case DSTATE_STOPPING:
  166793. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166794. break;
  166795. default:
  166796. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166797. }
  166798. return retcode;
  166799. }
  166800. /*
  166801. * Have we finished reading the input file?
  166802. */
  166803. GLOBAL(boolean)
  166804. jpeg_input_complete (j_decompress_ptr cinfo)
  166805. {
  166806. /* Check for valid jpeg object */
  166807. if (cinfo->global_state < DSTATE_START ||
  166808. cinfo->global_state > DSTATE_STOPPING)
  166809. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166810. return cinfo->inputctl->eoi_reached;
  166811. }
  166812. /*
  166813. * Is there more than one scan?
  166814. */
  166815. GLOBAL(boolean)
  166816. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  166817. {
  166818. /* Only valid after jpeg_read_header completes */
  166819. if (cinfo->global_state < DSTATE_READY ||
  166820. cinfo->global_state > DSTATE_STOPPING)
  166821. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166822. return cinfo->inputctl->has_multiple_scans;
  166823. }
  166824. /*
  166825. * Finish JPEG decompression.
  166826. *
  166827. * This will normally just verify the file trailer and release temp storage.
  166828. *
  166829. * Returns FALSE if suspended. The return value need be inspected only if
  166830. * a suspending data source is used.
  166831. */
  166832. GLOBAL(boolean)
  166833. jpeg_finish_decompress (j_decompress_ptr cinfo)
  166834. {
  166835. if ((cinfo->global_state == DSTATE_SCANNING ||
  166836. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  166837. /* Terminate final pass of non-buffered mode */
  166838. if (cinfo->output_scanline < cinfo->output_height)
  166839. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  166840. (*cinfo->master->finish_output_pass) (cinfo);
  166841. cinfo->global_state = DSTATE_STOPPING;
  166842. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  166843. /* Finishing after a buffered-image operation */
  166844. cinfo->global_state = DSTATE_STOPPING;
  166845. } else if (cinfo->global_state != DSTATE_STOPPING) {
  166846. /* STOPPING = repeat call after a suspension, anything else is error */
  166847. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166848. }
  166849. /* Read until EOI */
  166850. while (! cinfo->inputctl->eoi_reached) {
  166851. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  166852. return FALSE; /* Suspend, come back later */
  166853. }
  166854. /* Do final cleanup */
  166855. (*cinfo->src->term_source) (cinfo);
  166856. /* We can use jpeg_abort to release memory and reset global_state */
  166857. jpeg_abort((j_common_ptr) cinfo);
  166858. return TRUE;
  166859. }
  166860. /*** End of inlined file: jdapimin.c ***/
  166861. /*** Start of inlined file: jdatasrc.c ***/
  166862. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  166863. /*** Start of inlined file: jerror.h ***/
  166864. /*
  166865. * To define the enum list of message codes, include this file without
  166866. * defining macro JMESSAGE. To create a message string table, include it
  166867. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  166868. */
  166869. #ifndef JMESSAGE
  166870. #ifndef JERROR_H
  166871. /* First time through, define the enum list */
  166872. #define JMAKE_ENUM_LIST
  166873. #else
  166874. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  166875. #define JMESSAGE(code,string)
  166876. #endif /* JERROR_H */
  166877. #endif /* JMESSAGE */
  166878. #ifdef JMAKE_ENUM_LIST
  166879. typedef enum {
  166880. #define JMESSAGE(code,string) code ,
  166881. #endif /* JMAKE_ENUM_LIST */
  166882. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  166883. /* For maintenance convenience, list is alphabetical by message code name */
  166884. JMESSAGE(JERR_ARITH_NOTIMPL,
  166885. "Sorry, there are legal restrictions on arithmetic coding")
  166886. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  166887. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  166888. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  166889. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  166890. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  166891. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  166892. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  166893. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  166894. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  166895. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  166896. JMESSAGE(JERR_BAD_LIB_VERSION,
  166897. "Wrong JPEG library version: library is %d, caller expects %d")
  166898. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  166899. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  166900. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  166901. JMESSAGE(JERR_BAD_PROGRESSION,
  166902. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  166903. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  166904. "Invalid progressive parameters at scan script entry %d")
  166905. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  166906. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  166907. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  166908. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  166909. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  166910. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  166911. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  166912. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  166913. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  166914. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  166915. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  166916. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  166917. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  166918. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  166919. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  166920. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  166921. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  166922. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  166923. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  166924. JMESSAGE(JERR_FILE_READ, "Input file read error")
  166925. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  166926. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  166927. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  166928. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  166929. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  166930. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  166931. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  166932. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  166933. "Cannot transcode due to multiple use of quantization table %d")
  166934. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  166935. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  166936. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  166937. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  166938. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  166939. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  166940. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  166941. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  166942. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  166943. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  166944. JMESSAGE(JERR_QUANT_COMPONENTS,
  166945. "Cannot quantize more than %d color components")
  166946. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  166947. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  166948. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  166949. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  166950. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  166951. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  166952. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  166953. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  166954. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  166955. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  166956. JMESSAGE(JERR_TFILE_WRITE,
  166957. "Write failed on temporary file --- out of disk space?")
  166958. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  166959. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  166960. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  166961. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  166962. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  166963. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  166964. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  166965. JMESSAGE(JMSG_VERSION, JVERSION)
  166966. JMESSAGE(JTRC_16BIT_TABLES,
  166967. "Caution: quantization tables are too coarse for baseline JPEG")
  166968. JMESSAGE(JTRC_ADOBE,
  166969. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  166970. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  166971. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  166972. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  166973. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  166974. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  166975. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  166976. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  166977. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  166978. JMESSAGE(JTRC_EOI, "End Of Image")
  166979. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  166980. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  166981. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  166982. "Warning: thumbnail image size does not match data length %u")
  166983. JMESSAGE(JTRC_JFIF_EXTENSION,
  166984. "JFIF extension marker: type 0x%02x, length %u")
  166985. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  166986. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  166987. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  166988. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  166989. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  166990. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  166991. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  166992. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  166993. JMESSAGE(JTRC_RST, "RST%d")
  166994. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  166995. "Smoothing not supported with nonstandard sampling ratios")
  166996. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  166997. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  166998. JMESSAGE(JTRC_SOI, "Start of Image")
  166999. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167000. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167001. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167002. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167003. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167004. JMESSAGE(JTRC_THUMB_JPEG,
  167005. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167006. JMESSAGE(JTRC_THUMB_PALETTE,
  167007. "JFIF extension marker: palette thumbnail image, length %u")
  167008. JMESSAGE(JTRC_THUMB_RGB,
  167009. "JFIF extension marker: RGB thumbnail image, length %u")
  167010. JMESSAGE(JTRC_UNKNOWN_IDS,
  167011. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167012. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167013. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167014. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167015. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167016. "Inconsistent progression sequence for component %d coefficient %d")
  167017. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167018. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167019. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167020. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167021. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167022. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167023. JMESSAGE(JWRN_MUST_RESYNC,
  167024. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167025. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167026. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167027. #ifdef JMAKE_ENUM_LIST
  167028. JMSG_LASTMSGCODE
  167029. } J_MESSAGE_CODE;
  167030. #undef JMAKE_ENUM_LIST
  167031. #endif /* JMAKE_ENUM_LIST */
  167032. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167033. #undef JMESSAGE
  167034. #ifndef JERROR_H
  167035. #define JERROR_H
  167036. /* Macros to simplify using the error and trace message stuff */
  167037. /* The first parameter is either type of cinfo pointer */
  167038. /* Fatal errors (print message and exit) */
  167039. #define ERREXIT(cinfo,code) \
  167040. ((cinfo)->err->msg_code = (code), \
  167041. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167042. #define ERREXIT1(cinfo,code,p1) \
  167043. ((cinfo)->err->msg_code = (code), \
  167044. (cinfo)->err->msg_parm.i[0] = (p1), \
  167045. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167046. #define ERREXIT2(cinfo,code,p1,p2) \
  167047. ((cinfo)->err->msg_code = (code), \
  167048. (cinfo)->err->msg_parm.i[0] = (p1), \
  167049. (cinfo)->err->msg_parm.i[1] = (p2), \
  167050. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167051. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167052. ((cinfo)->err->msg_code = (code), \
  167053. (cinfo)->err->msg_parm.i[0] = (p1), \
  167054. (cinfo)->err->msg_parm.i[1] = (p2), \
  167055. (cinfo)->err->msg_parm.i[2] = (p3), \
  167056. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167057. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167058. ((cinfo)->err->msg_code = (code), \
  167059. (cinfo)->err->msg_parm.i[0] = (p1), \
  167060. (cinfo)->err->msg_parm.i[1] = (p2), \
  167061. (cinfo)->err->msg_parm.i[2] = (p3), \
  167062. (cinfo)->err->msg_parm.i[3] = (p4), \
  167063. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167064. #define ERREXITS(cinfo,code,str) \
  167065. ((cinfo)->err->msg_code = (code), \
  167066. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167067. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167068. #define MAKESTMT(stuff) do { stuff } while (0)
  167069. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167070. #define WARNMS(cinfo,code) \
  167071. ((cinfo)->err->msg_code = (code), \
  167072. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167073. #define WARNMS1(cinfo,code,p1) \
  167074. ((cinfo)->err->msg_code = (code), \
  167075. (cinfo)->err->msg_parm.i[0] = (p1), \
  167076. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167077. #define WARNMS2(cinfo,code,p1,p2) \
  167078. ((cinfo)->err->msg_code = (code), \
  167079. (cinfo)->err->msg_parm.i[0] = (p1), \
  167080. (cinfo)->err->msg_parm.i[1] = (p2), \
  167081. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167082. /* Informational/debugging messages */
  167083. #define TRACEMS(cinfo,lvl,code) \
  167084. ((cinfo)->err->msg_code = (code), \
  167085. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167086. #define TRACEMS1(cinfo,lvl,code,p1) \
  167087. ((cinfo)->err->msg_code = (code), \
  167088. (cinfo)->err->msg_parm.i[0] = (p1), \
  167089. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167090. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167091. ((cinfo)->err->msg_code = (code), \
  167092. (cinfo)->err->msg_parm.i[0] = (p1), \
  167093. (cinfo)->err->msg_parm.i[1] = (p2), \
  167094. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167095. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167096. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167097. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167098. (cinfo)->err->msg_code = (code); \
  167099. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167100. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167101. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167102. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167103. (cinfo)->err->msg_code = (code); \
  167104. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167105. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167106. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167107. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167108. _mp[4] = (p5); \
  167109. (cinfo)->err->msg_code = (code); \
  167110. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167111. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167112. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167113. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167114. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167115. (cinfo)->err->msg_code = (code); \
  167116. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167117. #define TRACEMSS(cinfo,lvl,code,str) \
  167118. ((cinfo)->err->msg_code = (code), \
  167119. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167120. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167121. #endif /* JERROR_H */
  167122. /*** End of inlined file: jerror.h ***/
  167123. /* Expanded data source object for stdio input */
  167124. typedef struct {
  167125. struct jpeg_source_mgr pub; /* public fields */
  167126. FILE * infile; /* source stream */
  167127. JOCTET * buffer; /* start of buffer */
  167128. boolean start_of_file; /* have we gotten any data yet? */
  167129. } my_source_mgr;
  167130. typedef my_source_mgr * my_src_ptr;
  167131. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167132. /*
  167133. * Initialize source --- called by jpeg_read_header
  167134. * before any data is actually read.
  167135. */
  167136. METHODDEF(void)
  167137. init_source (j_decompress_ptr cinfo)
  167138. {
  167139. my_src_ptr src = (my_src_ptr) cinfo->src;
  167140. /* We reset the empty-input-file flag for each image,
  167141. * but we don't clear the input buffer.
  167142. * This is correct behavior for reading a series of images from one source.
  167143. */
  167144. src->start_of_file = TRUE;
  167145. }
  167146. /*
  167147. * Fill the input buffer --- called whenever buffer is emptied.
  167148. *
  167149. * In typical applications, this should read fresh data into the buffer
  167150. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  167151. * reset the pointer & count to the start of the buffer, and return TRUE
  167152. * indicating that the buffer has been reloaded. It is not necessary to
  167153. * fill the buffer entirely, only to obtain at least one more byte.
  167154. *
  167155. * There is no such thing as an EOF return. If the end of the file has been
  167156. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  167157. * the buffer. In most cases, generating a warning message and inserting a
  167158. * fake EOI marker is the best course of action --- this will allow the
  167159. * decompressor to output however much of the image is there. However,
  167160. * the resulting error message is misleading if the real problem is an empty
  167161. * input file, so we handle that case specially.
  167162. *
  167163. * In applications that need to be able to suspend compression due to input
  167164. * not being available yet, a FALSE return indicates that no more data can be
  167165. * obtained right now, but more may be forthcoming later. In this situation,
  167166. * the decompressor will return to its caller (with an indication of the
  167167. * number of scanlines it has read, if any). The application should resume
  167168. * decompression after it has loaded more data into the input buffer. Note
  167169. * that there are substantial restrictions on the use of suspension --- see
  167170. * the documentation.
  167171. *
  167172. * When suspending, the decompressor will back up to a convenient restart point
  167173. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  167174. * indicate where the restart point will be if the current call returns FALSE.
  167175. * Data beyond this point must be rescanned after resumption, so move it to
  167176. * the front of the buffer rather than discarding it.
  167177. */
  167178. METHODDEF(boolean)
  167179. fill_input_buffer (j_decompress_ptr cinfo)
  167180. {
  167181. my_src_ptr src = (my_src_ptr) cinfo->src;
  167182. size_t nbytes;
  167183. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  167184. if (nbytes <= 0) {
  167185. if (src->start_of_file) /* Treat empty input file as fatal error */
  167186. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  167187. WARNMS(cinfo, JWRN_JPEG_EOF);
  167188. /* Insert a fake EOI marker */
  167189. src->buffer[0] = (JOCTET) 0xFF;
  167190. src->buffer[1] = (JOCTET) JPEG_EOI;
  167191. nbytes = 2;
  167192. }
  167193. src->pub.next_input_byte = src->buffer;
  167194. src->pub.bytes_in_buffer = nbytes;
  167195. src->start_of_file = FALSE;
  167196. return TRUE;
  167197. }
  167198. /*
  167199. * Skip data --- used to skip over a potentially large amount of
  167200. * uninteresting data (such as an APPn marker).
  167201. *
  167202. * Writers of suspendable-input applications must note that skip_input_data
  167203. * is not granted the right to give a suspension return. If the skip extends
  167204. * beyond the data currently in the buffer, the buffer can be marked empty so
  167205. * that the next read will cause a fill_input_buffer call that can suspend.
  167206. * Arranging for additional bytes to be discarded before reloading the input
  167207. * buffer is the application writer's problem.
  167208. */
  167209. METHODDEF(void)
  167210. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  167211. {
  167212. my_src_ptr src = (my_src_ptr) cinfo->src;
  167213. /* Just a dumb implementation for now. Could use fseek() except
  167214. * it doesn't work on pipes. Not clear that being smart is worth
  167215. * any trouble anyway --- large skips are infrequent.
  167216. */
  167217. if (num_bytes > 0) {
  167218. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  167219. num_bytes -= (long) src->pub.bytes_in_buffer;
  167220. (void) fill_input_buffer(cinfo);
  167221. /* note we assume that fill_input_buffer will never return FALSE,
  167222. * so suspension need not be handled.
  167223. */
  167224. }
  167225. src->pub.next_input_byte += (size_t) num_bytes;
  167226. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  167227. }
  167228. }
  167229. /*
  167230. * An additional method that can be provided by data source modules is the
  167231. * resync_to_restart method for error recovery in the presence of RST markers.
  167232. * For the moment, this source module just uses the default resync method
  167233. * provided by the JPEG library. That method assumes that no backtracking
  167234. * is possible.
  167235. */
  167236. /*
  167237. * Terminate source --- called by jpeg_finish_decompress
  167238. * after all data has been read. Often a no-op.
  167239. *
  167240. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  167241. * application must deal with any cleanup that should happen even
  167242. * for error exit.
  167243. */
  167244. METHODDEF(void)
  167245. term_source (j_decompress_ptr)
  167246. {
  167247. /* no work necessary here */
  167248. }
  167249. /*
  167250. * Prepare for input from a stdio stream.
  167251. * The caller must have already opened the stream, and is responsible
  167252. * for closing it after finishing decompression.
  167253. */
  167254. GLOBAL(void)
  167255. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  167256. {
  167257. my_src_ptr src;
  167258. /* The source object and input buffer are made permanent so that a series
  167259. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  167260. * only before the first one. (If we discarded the buffer at the end of
  167261. * one image, we'd likely lose the start of the next one.)
  167262. * This makes it unsafe to use this manager and a different source
  167263. * manager serially with the same JPEG object. Caveat programmer.
  167264. */
  167265. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  167266. cinfo->src = (struct jpeg_source_mgr *)
  167267. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167268. SIZEOF(my_source_mgr));
  167269. src = (my_src_ptr) cinfo->src;
  167270. src->buffer = (JOCTET *)
  167271. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167272. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  167273. }
  167274. src = (my_src_ptr) cinfo->src;
  167275. src->pub.init_source = init_source;
  167276. src->pub.fill_input_buffer = fill_input_buffer;
  167277. src->pub.skip_input_data = skip_input_data;
  167278. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  167279. src->pub.term_source = term_source;
  167280. src->infile = infile;
  167281. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  167282. src->pub.next_input_byte = NULL; /* until buffer loaded */
  167283. }
  167284. /*** End of inlined file: jdatasrc.c ***/
  167285. /*** Start of inlined file: jdcoefct.c ***/
  167286. #define JPEG_INTERNALS
  167287. /* Block smoothing is only applicable for progressive JPEG, so: */
  167288. #ifndef D_PROGRESSIVE_SUPPORTED
  167289. #undef BLOCK_SMOOTHING_SUPPORTED
  167290. #endif
  167291. /* Private buffer controller object */
  167292. typedef struct {
  167293. struct jpeg_d_coef_controller pub; /* public fields */
  167294. /* These variables keep track of the current location of the input side. */
  167295. /* cinfo->input_iMCU_row is also used for this. */
  167296. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  167297. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167298. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167299. /* The output side's location is represented by cinfo->output_iMCU_row. */
  167300. /* In single-pass modes, it's sufficient to buffer just one MCU.
  167301. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  167302. * and let the entropy decoder write into that workspace each time.
  167303. * (On 80x86, the workspace is FAR even though it's not really very big;
  167304. * this is to keep the module interfaces unchanged when a large coefficient
  167305. * buffer is necessary.)
  167306. * In multi-pass modes, this array points to the current MCU's blocks
  167307. * within the virtual arrays; it is used only by the input side.
  167308. */
  167309. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  167310. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167311. /* In multi-pass modes, we need a virtual block array for each component. */
  167312. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  167313. #endif
  167314. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167315. /* When doing block smoothing, we latch coefficient Al values here */
  167316. int * coef_bits_latch;
  167317. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  167318. #endif
  167319. } my_coef_controller3;
  167320. typedef my_coef_controller3 * my_coef_ptr3;
  167321. /* Forward declarations */
  167322. METHODDEF(int) decompress_onepass
  167323. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167324. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167325. METHODDEF(int) decompress_data
  167326. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167327. #endif
  167328. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167329. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  167330. METHODDEF(int) decompress_smooth_data
  167331. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167332. #endif
  167333. LOCAL(void)
  167334. start_iMCU_row3 (j_decompress_ptr cinfo)
  167335. /* Reset within-iMCU-row counters for a new row (input side) */
  167336. {
  167337. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167338. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167339. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167340. * But at the bottom of the image, process only what's left.
  167341. */
  167342. if (cinfo->comps_in_scan > 1) {
  167343. coef->MCU_rows_per_iMCU_row = 1;
  167344. } else {
  167345. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  167346. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167347. else
  167348. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167349. }
  167350. coef->MCU_ctr = 0;
  167351. coef->MCU_vert_offset = 0;
  167352. }
  167353. /*
  167354. * Initialize for an input processing pass.
  167355. */
  167356. METHODDEF(void)
  167357. start_input_pass (j_decompress_ptr cinfo)
  167358. {
  167359. cinfo->input_iMCU_row = 0;
  167360. start_iMCU_row3(cinfo);
  167361. }
  167362. /*
  167363. * Initialize for an output processing pass.
  167364. */
  167365. METHODDEF(void)
  167366. start_output_pass (j_decompress_ptr cinfo)
  167367. {
  167368. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167369. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167370. /* If multipass, check to see whether to use block smoothing on this pass */
  167371. if (coef->pub.coef_arrays != NULL) {
  167372. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  167373. coef->pub.decompress_data = decompress_smooth_data;
  167374. else
  167375. coef->pub.decompress_data = decompress_data;
  167376. }
  167377. #endif
  167378. cinfo->output_iMCU_row = 0;
  167379. }
  167380. /*
  167381. * Decompress and return some data in the single-pass case.
  167382. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167383. * Input and output must run in lockstep since we have only a one-MCU buffer.
  167384. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167385. *
  167386. * NB: output_buf contains a plane for each component in image,
  167387. * which we index according to the component's SOF position.
  167388. */
  167389. METHODDEF(int)
  167390. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167391. {
  167392. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167393. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167394. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167395. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167396. int blkn, ci, xindex, yindex, yoffset, useful_width;
  167397. JSAMPARRAY output_ptr;
  167398. JDIMENSION start_col, output_col;
  167399. jpeg_component_info *compptr;
  167400. inverse_DCT_method_ptr inverse_DCT;
  167401. /* Loop to process as much as one whole iMCU row */
  167402. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167403. yoffset++) {
  167404. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  167405. MCU_col_num++) {
  167406. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  167407. jzero_far((void FAR *) coef->MCU_buffer[0],
  167408. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  167409. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  167410. /* Suspension forced; update state counters and exit */
  167411. coef->MCU_vert_offset = yoffset;
  167412. coef->MCU_ctr = MCU_col_num;
  167413. return JPEG_SUSPENDED;
  167414. }
  167415. /* Determine where data should go in output_buf and do the IDCT thing.
  167416. * We skip dummy blocks at the right and bottom edges (but blkn gets
  167417. * incremented past them!). Note the inner loop relies on having
  167418. * allocated the MCU_buffer[] blocks sequentially.
  167419. */
  167420. blkn = 0; /* index of current DCT block within MCU */
  167421. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167422. compptr = cinfo->cur_comp_info[ci];
  167423. /* Don't bother to IDCT an uninteresting component. */
  167424. if (! compptr->component_needed) {
  167425. blkn += compptr->MCU_blocks;
  167426. continue;
  167427. }
  167428. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  167429. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167430. : compptr->last_col_width;
  167431. output_ptr = output_buf[compptr->component_index] +
  167432. yoffset * compptr->DCT_scaled_size;
  167433. start_col = MCU_col_num * compptr->MCU_sample_width;
  167434. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167435. if (cinfo->input_iMCU_row < last_iMCU_row ||
  167436. yoffset+yindex < compptr->last_row_height) {
  167437. output_col = start_col;
  167438. for (xindex = 0; xindex < useful_width; xindex++) {
  167439. (*inverse_DCT) (cinfo, compptr,
  167440. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  167441. output_ptr, output_col);
  167442. output_col += compptr->DCT_scaled_size;
  167443. }
  167444. }
  167445. blkn += compptr->MCU_width;
  167446. output_ptr += compptr->DCT_scaled_size;
  167447. }
  167448. }
  167449. }
  167450. /* Completed an MCU row, but perhaps not an iMCU row */
  167451. coef->MCU_ctr = 0;
  167452. }
  167453. /* Completed the iMCU row, advance counters for next one */
  167454. cinfo->output_iMCU_row++;
  167455. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  167456. start_iMCU_row3(cinfo);
  167457. return JPEG_ROW_COMPLETED;
  167458. }
  167459. /* Completed the scan */
  167460. (*cinfo->inputctl->finish_input_pass) (cinfo);
  167461. return JPEG_SCAN_COMPLETED;
  167462. }
  167463. /*
  167464. * Dummy consume-input routine for single-pass operation.
  167465. */
  167466. METHODDEF(int)
  167467. dummy_consume_data (j_decompress_ptr)
  167468. {
  167469. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  167470. }
  167471. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167472. /*
  167473. * Consume input data and store it in the full-image coefficient buffer.
  167474. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  167475. * ie, v_samp_factor block rows for each component in the scan.
  167476. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167477. */
  167478. METHODDEF(int)
  167479. consume_data (j_decompress_ptr cinfo)
  167480. {
  167481. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167482. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167483. int blkn, ci, xindex, yindex, yoffset;
  167484. JDIMENSION start_col;
  167485. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167486. JBLOCKROW buffer_ptr;
  167487. jpeg_component_info *compptr;
  167488. /* Align the virtual buffers for the components used in this scan. */
  167489. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167490. compptr = cinfo->cur_comp_info[ci];
  167491. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167492. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167493. cinfo->input_iMCU_row * compptr->v_samp_factor,
  167494. (JDIMENSION) compptr->v_samp_factor, TRUE);
  167495. /* Note: entropy decoder expects buffer to be zeroed,
  167496. * but this is handled automatically by the memory manager
  167497. * because we requested a pre-zeroed array.
  167498. */
  167499. }
  167500. /* Loop to process one whole iMCU row */
  167501. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167502. yoffset++) {
  167503. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167504. MCU_col_num++) {
  167505. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167506. blkn = 0; /* index of current DCT block within MCU */
  167507. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167508. compptr = cinfo->cur_comp_info[ci];
  167509. start_col = MCU_col_num * compptr->MCU_width;
  167510. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167511. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167512. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  167513. coef->MCU_buffer[blkn++] = buffer_ptr++;
  167514. }
  167515. }
  167516. }
  167517. /* Try to fetch the MCU. */
  167518. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  167519. /* Suspension forced; update state counters and exit */
  167520. coef->MCU_vert_offset = yoffset;
  167521. coef->MCU_ctr = MCU_col_num;
  167522. return JPEG_SUSPENDED;
  167523. }
  167524. }
  167525. /* Completed an MCU row, but perhaps not an iMCU row */
  167526. coef->MCU_ctr = 0;
  167527. }
  167528. /* Completed the iMCU row, advance counters for next one */
  167529. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  167530. start_iMCU_row3(cinfo);
  167531. return JPEG_ROW_COMPLETED;
  167532. }
  167533. /* Completed the scan */
  167534. (*cinfo->inputctl->finish_input_pass) (cinfo);
  167535. return JPEG_SCAN_COMPLETED;
  167536. }
  167537. /*
  167538. * Decompress and return some data in the multi-pass case.
  167539. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167540. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167541. *
  167542. * NB: output_buf contains a plane for each component in image.
  167543. */
  167544. METHODDEF(int)
  167545. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167546. {
  167547. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167548. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167549. JDIMENSION block_num;
  167550. int ci, block_row, block_rows;
  167551. JBLOCKARRAY buffer;
  167552. JBLOCKROW buffer_ptr;
  167553. JSAMPARRAY output_ptr;
  167554. JDIMENSION output_col;
  167555. jpeg_component_info *compptr;
  167556. inverse_DCT_method_ptr inverse_DCT;
  167557. /* Force some input to be done if we are getting ahead of the input. */
  167558. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  167559. (cinfo->input_scan_number == cinfo->output_scan_number &&
  167560. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  167561. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  167562. return JPEG_SUSPENDED;
  167563. }
  167564. /* OK, output from the virtual arrays. */
  167565. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167566. ci++, compptr++) {
  167567. /* Don't bother to IDCT an uninteresting component. */
  167568. if (! compptr->component_needed)
  167569. continue;
  167570. /* Align the virtual buffer for this component. */
  167571. buffer = (*cinfo->mem->access_virt_barray)
  167572. ((j_common_ptr) cinfo, coef->whole_image[ci],
  167573. cinfo->output_iMCU_row * compptr->v_samp_factor,
  167574. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167575. /* Count non-dummy DCT block rows in this iMCU row. */
  167576. if (cinfo->output_iMCU_row < last_iMCU_row)
  167577. block_rows = compptr->v_samp_factor;
  167578. else {
  167579. /* NB: can't use last_row_height here; it is input-side-dependent! */
  167580. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  167581. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  167582. }
  167583. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  167584. output_ptr = output_buf[ci];
  167585. /* Loop over all DCT blocks to be processed. */
  167586. for (block_row = 0; block_row < block_rows; block_row++) {
  167587. buffer_ptr = buffer[block_row];
  167588. output_col = 0;
  167589. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  167590. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  167591. output_ptr, output_col);
  167592. buffer_ptr++;
  167593. output_col += compptr->DCT_scaled_size;
  167594. }
  167595. output_ptr += compptr->DCT_scaled_size;
  167596. }
  167597. }
  167598. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  167599. return JPEG_ROW_COMPLETED;
  167600. return JPEG_SCAN_COMPLETED;
  167601. }
  167602. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167603. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167604. /*
  167605. * This code applies interblock smoothing as described by section K.8
  167606. * of the JPEG standard: the first 5 AC coefficients are estimated from
  167607. * the DC values of a DCT block and its 8 neighboring blocks.
  167608. * We apply smoothing only for progressive JPEG decoding, and only if
  167609. * the coefficients it can estimate are not yet known to full precision.
  167610. */
  167611. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  167612. #define Q01_POS 1
  167613. #define Q10_POS 8
  167614. #define Q20_POS 16
  167615. #define Q11_POS 9
  167616. #define Q02_POS 2
  167617. /*
  167618. * Determine whether block smoothing is applicable and safe.
  167619. * We also latch the current states of the coef_bits[] entries for the
  167620. * AC coefficients; otherwise, if the input side of the decompressor
  167621. * advances into a new scan, we might think the coefficients are known
  167622. * more accurately than they really are.
  167623. */
  167624. LOCAL(boolean)
  167625. smoothing_ok (j_decompress_ptr cinfo)
  167626. {
  167627. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167628. boolean smoothing_useful = FALSE;
  167629. int ci, coefi;
  167630. jpeg_component_info *compptr;
  167631. JQUANT_TBL * qtable;
  167632. int * coef_bits;
  167633. int * coef_bits_latch;
  167634. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  167635. return FALSE;
  167636. /* Allocate latch area if not already done */
  167637. if (coef->coef_bits_latch == NULL)
  167638. coef->coef_bits_latch = (int *)
  167639. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167640. cinfo->num_components *
  167641. (SAVED_COEFS * SIZEOF(int)));
  167642. coef_bits_latch = coef->coef_bits_latch;
  167643. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167644. ci++, compptr++) {
  167645. /* All components' quantization values must already be latched. */
  167646. if ((qtable = compptr->quant_table) == NULL)
  167647. return FALSE;
  167648. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  167649. if (qtable->quantval[0] == 0 ||
  167650. qtable->quantval[Q01_POS] == 0 ||
  167651. qtable->quantval[Q10_POS] == 0 ||
  167652. qtable->quantval[Q20_POS] == 0 ||
  167653. qtable->quantval[Q11_POS] == 0 ||
  167654. qtable->quantval[Q02_POS] == 0)
  167655. return FALSE;
  167656. /* DC values must be at least partly known for all components. */
  167657. coef_bits = cinfo->coef_bits[ci];
  167658. if (coef_bits[0] < 0)
  167659. return FALSE;
  167660. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  167661. for (coefi = 1; coefi <= 5; coefi++) {
  167662. coef_bits_latch[coefi] = coef_bits[coefi];
  167663. if (coef_bits[coefi] != 0)
  167664. smoothing_useful = TRUE;
  167665. }
  167666. coef_bits_latch += SAVED_COEFS;
  167667. }
  167668. return smoothing_useful;
  167669. }
  167670. /*
  167671. * Variant of decompress_data for use when doing block smoothing.
  167672. */
  167673. METHODDEF(int)
  167674. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167675. {
  167676. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167677. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167678. JDIMENSION block_num, last_block_column;
  167679. int ci, block_row, block_rows, access_rows;
  167680. JBLOCKARRAY buffer;
  167681. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  167682. JSAMPARRAY output_ptr;
  167683. JDIMENSION output_col;
  167684. jpeg_component_info *compptr;
  167685. inverse_DCT_method_ptr inverse_DCT;
  167686. boolean first_row, last_row;
  167687. JBLOCK workspace;
  167688. int *coef_bits;
  167689. JQUANT_TBL *quanttbl;
  167690. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  167691. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  167692. int Al, pred;
  167693. /* Force some input to be done if we are getting ahead of the input. */
  167694. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167695. ! cinfo->inputctl->eoi_reached) {
  167696. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  167697. /* If input is working on current scan, we ordinarily want it to
  167698. * have completed the current row. But if input scan is DC,
  167699. * we want it to keep one row ahead so that next block row's DC
  167700. * values are up to date.
  167701. */
  167702. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  167703. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  167704. break;
  167705. }
  167706. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  167707. return JPEG_SUSPENDED;
  167708. }
  167709. /* OK, output from the virtual arrays. */
  167710. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167711. ci++, compptr++) {
  167712. /* Don't bother to IDCT an uninteresting component. */
  167713. if (! compptr->component_needed)
  167714. continue;
  167715. /* Count non-dummy DCT block rows in this iMCU row. */
  167716. if (cinfo->output_iMCU_row < last_iMCU_row) {
  167717. block_rows = compptr->v_samp_factor;
  167718. access_rows = block_rows * 2; /* this and next iMCU row */
  167719. last_row = FALSE;
  167720. } else {
  167721. /* NB: can't use last_row_height here; it is input-side-dependent! */
  167722. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  167723. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  167724. access_rows = block_rows; /* this iMCU row only */
  167725. last_row = TRUE;
  167726. }
  167727. /* Align the virtual buffer for this component. */
  167728. if (cinfo->output_iMCU_row > 0) {
  167729. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  167730. buffer = (*cinfo->mem->access_virt_barray)
  167731. ((j_common_ptr) cinfo, coef->whole_image[ci],
  167732. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  167733. (JDIMENSION) access_rows, FALSE);
  167734. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  167735. first_row = FALSE;
  167736. } else {
  167737. buffer = (*cinfo->mem->access_virt_barray)
  167738. ((j_common_ptr) cinfo, coef->whole_image[ci],
  167739. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  167740. first_row = TRUE;
  167741. }
  167742. /* Fetch component-dependent info */
  167743. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  167744. quanttbl = compptr->quant_table;
  167745. Q00 = quanttbl->quantval[0];
  167746. Q01 = quanttbl->quantval[Q01_POS];
  167747. Q10 = quanttbl->quantval[Q10_POS];
  167748. Q20 = quanttbl->quantval[Q20_POS];
  167749. Q11 = quanttbl->quantval[Q11_POS];
  167750. Q02 = quanttbl->quantval[Q02_POS];
  167751. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  167752. output_ptr = output_buf[ci];
  167753. /* Loop over all DCT blocks to be processed. */
  167754. for (block_row = 0; block_row < block_rows; block_row++) {
  167755. buffer_ptr = buffer[block_row];
  167756. if (first_row && block_row == 0)
  167757. prev_block_row = buffer_ptr;
  167758. else
  167759. prev_block_row = buffer[block_row-1];
  167760. if (last_row && block_row == block_rows-1)
  167761. next_block_row = buffer_ptr;
  167762. else
  167763. next_block_row = buffer[block_row+1];
  167764. /* We fetch the surrounding DC values using a sliding-register approach.
  167765. * Initialize all nine here so as to do the right thing on narrow pics.
  167766. */
  167767. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  167768. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  167769. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  167770. output_col = 0;
  167771. last_block_column = compptr->width_in_blocks - 1;
  167772. for (block_num = 0; block_num <= last_block_column; block_num++) {
  167773. /* Fetch current DCT block into workspace so we can modify it. */
  167774. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  167775. /* Update DC values */
  167776. if (block_num < last_block_column) {
  167777. DC3 = (int) prev_block_row[1][0];
  167778. DC6 = (int) buffer_ptr[1][0];
  167779. DC9 = (int) next_block_row[1][0];
  167780. }
  167781. /* Compute coefficient estimates per K.8.
  167782. * An estimate is applied only if coefficient is still zero,
  167783. * and is not known to be fully accurate.
  167784. */
  167785. /* AC01 */
  167786. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  167787. num = 36 * Q00 * (DC4 - DC6);
  167788. if (num >= 0) {
  167789. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  167790. if (Al > 0 && pred >= (1<<Al))
  167791. pred = (1<<Al)-1;
  167792. } else {
  167793. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  167794. if (Al > 0 && pred >= (1<<Al))
  167795. pred = (1<<Al)-1;
  167796. pred = -pred;
  167797. }
  167798. workspace[1] = (JCOEF) pred;
  167799. }
  167800. /* AC10 */
  167801. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  167802. num = 36 * Q00 * (DC2 - DC8);
  167803. if (num >= 0) {
  167804. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  167805. if (Al > 0 && pred >= (1<<Al))
  167806. pred = (1<<Al)-1;
  167807. } else {
  167808. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  167809. if (Al > 0 && pred >= (1<<Al))
  167810. pred = (1<<Al)-1;
  167811. pred = -pred;
  167812. }
  167813. workspace[8] = (JCOEF) pred;
  167814. }
  167815. /* AC20 */
  167816. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  167817. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  167818. if (num >= 0) {
  167819. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  167820. if (Al > 0 && pred >= (1<<Al))
  167821. pred = (1<<Al)-1;
  167822. } else {
  167823. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  167824. if (Al > 0 && pred >= (1<<Al))
  167825. pred = (1<<Al)-1;
  167826. pred = -pred;
  167827. }
  167828. workspace[16] = (JCOEF) pred;
  167829. }
  167830. /* AC11 */
  167831. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  167832. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  167833. if (num >= 0) {
  167834. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  167835. if (Al > 0 && pred >= (1<<Al))
  167836. pred = (1<<Al)-1;
  167837. } else {
  167838. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  167839. if (Al > 0 && pred >= (1<<Al))
  167840. pred = (1<<Al)-1;
  167841. pred = -pred;
  167842. }
  167843. workspace[9] = (JCOEF) pred;
  167844. }
  167845. /* AC02 */
  167846. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  167847. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  167848. if (num >= 0) {
  167849. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  167850. if (Al > 0 && pred >= (1<<Al))
  167851. pred = (1<<Al)-1;
  167852. } else {
  167853. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  167854. if (Al > 0 && pred >= (1<<Al))
  167855. pred = (1<<Al)-1;
  167856. pred = -pred;
  167857. }
  167858. workspace[2] = (JCOEF) pred;
  167859. }
  167860. /* OK, do the IDCT */
  167861. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  167862. output_ptr, output_col);
  167863. /* Advance for next column */
  167864. DC1 = DC2; DC2 = DC3;
  167865. DC4 = DC5; DC5 = DC6;
  167866. DC7 = DC8; DC8 = DC9;
  167867. buffer_ptr++, prev_block_row++, next_block_row++;
  167868. output_col += compptr->DCT_scaled_size;
  167869. }
  167870. output_ptr += compptr->DCT_scaled_size;
  167871. }
  167872. }
  167873. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  167874. return JPEG_ROW_COMPLETED;
  167875. return JPEG_SCAN_COMPLETED;
  167876. }
  167877. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  167878. /*
  167879. * Initialize coefficient buffer controller.
  167880. */
  167881. GLOBAL(void)
  167882. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  167883. {
  167884. my_coef_ptr3 coef;
  167885. coef = (my_coef_ptr3)
  167886. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167887. SIZEOF(my_coef_controller3));
  167888. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  167889. coef->pub.start_input_pass = start_input_pass;
  167890. coef->pub.start_output_pass = start_output_pass;
  167891. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167892. coef->coef_bits_latch = NULL;
  167893. #endif
  167894. /* Create the coefficient buffer. */
  167895. if (need_full_buffer) {
  167896. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167897. /* Allocate a full-image virtual array for each component, */
  167898. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  167899. /* Note we ask for a pre-zeroed array. */
  167900. int ci, access_rows;
  167901. jpeg_component_info *compptr;
  167902. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167903. ci++, compptr++) {
  167904. access_rows = compptr->v_samp_factor;
  167905. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167906. /* If block smoothing could be used, need a bigger window */
  167907. if (cinfo->progressive_mode)
  167908. access_rows *= 3;
  167909. #endif
  167910. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  167911. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  167912. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  167913. (long) compptr->h_samp_factor),
  167914. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  167915. (long) compptr->v_samp_factor),
  167916. (JDIMENSION) access_rows);
  167917. }
  167918. coef->pub.consume_data = consume_data;
  167919. coef->pub.decompress_data = decompress_data;
  167920. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  167921. #else
  167922. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167923. #endif
  167924. } else {
  167925. /* We only need a single-MCU buffer. */
  167926. JBLOCKROW buffer;
  167927. int i;
  167928. buffer = (JBLOCKROW)
  167929. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167930. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167931. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  167932. coef->MCU_buffer[i] = buffer + i;
  167933. }
  167934. coef->pub.consume_data = dummy_consume_data;
  167935. coef->pub.decompress_data = decompress_onepass;
  167936. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  167937. }
  167938. }
  167939. /*** End of inlined file: jdcoefct.c ***/
  167940. #undef FIX
  167941. /*** Start of inlined file: jdcolor.c ***/
  167942. #define JPEG_INTERNALS
  167943. /* Private subobject */
  167944. typedef struct {
  167945. struct jpeg_color_deconverter pub; /* public fields */
  167946. /* Private state for YCC->RGB conversion */
  167947. int * Cr_r_tab; /* => table for Cr to R conversion */
  167948. int * Cb_b_tab; /* => table for Cb to B conversion */
  167949. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  167950. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  167951. } my_color_deconverter2;
  167952. typedef my_color_deconverter2 * my_cconvert_ptr2;
  167953. /**************** YCbCr -> RGB conversion: most common case **************/
  167954. /*
  167955. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  167956. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  167957. * The conversion equations to be implemented are therefore
  167958. * R = Y + 1.40200 * Cr
  167959. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  167960. * B = Y + 1.77200 * Cb
  167961. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  167962. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  167963. *
  167964. * To avoid floating-point arithmetic, we represent the fractional constants
  167965. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  167966. * the products by 2^16, with appropriate rounding, to get the correct answer.
  167967. * Notice that Y, being an integral input, does not contribute any fraction
  167968. * so it need not participate in the rounding.
  167969. *
  167970. * For even more speed, we avoid doing any multiplications in the inner loop
  167971. * by precalculating the constants times Cb and Cr for all possible values.
  167972. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  167973. * for 12-bit samples it is still acceptable. It's not very reasonable for
  167974. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  167975. * colorspace anyway.
  167976. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  167977. * values for the G calculation are left scaled up, since we must add them
  167978. * together before rounding.
  167979. */
  167980. #define SCALEBITS 16 /* speediest right-shift on some machines */
  167981. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  167982. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  167983. /*
  167984. * Initialize tables for YCC->RGB colorspace conversion.
  167985. */
  167986. LOCAL(void)
  167987. build_ycc_rgb_table (j_decompress_ptr cinfo)
  167988. {
  167989. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  167990. int i;
  167991. INT32 x;
  167992. SHIFT_TEMPS
  167993. cconvert->Cr_r_tab = (int *)
  167994. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167995. (MAXJSAMPLE+1) * SIZEOF(int));
  167996. cconvert->Cb_b_tab = (int *)
  167997. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167998. (MAXJSAMPLE+1) * SIZEOF(int));
  167999. cconvert->Cr_g_tab = (INT32 *)
  168000. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168001. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168002. cconvert->Cb_g_tab = (INT32 *)
  168003. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168004. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168005. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168006. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168007. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168008. /* Cr=>R value is nearest int to 1.40200 * x */
  168009. cconvert->Cr_r_tab[i] = (int)
  168010. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168011. /* Cb=>B value is nearest int to 1.77200 * x */
  168012. cconvert->Cb_b_tab[i] = (int)
  168013. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168014. /* Cr=>G value is scaled-up -0.71414 * x */
  168015. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168016. /* Cb=>G value is scaled-up -0.34414 * x */
  168017. /* We also add in ONE_HALF so that need not do it in inner loop */
  168018. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168019. }
  168020. }
  168021. /*
  168022. * Convert some rows of samples to the output colorspace.
  168023. *
  168024. * Note that we change from noninterleaved, one-plane-per-component format
  168025. * to interleaved-pixel format. The output buffer is therefore three times
  168026. * as wide as the input buffer.
  168027. * A starting row offset is provided only for the input buffer. The caller
  168028. * can easily adjust the passed output_buf value to accommodate any row
  168029. * offset required on that side.
  168030. */
  168031. METHODDEF(void)
  168032. ycc_rgb_convert (j_decompress_ptr cinfo,
  168033. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168034. JSAMPARRAY output_buf, int num_rows)
  168035. {
  168036. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168037. register int y, cb, cr;
  168038. register JSAMPROW outptr;
  168039. register JSAMPROW inptr0, inptr1, inptr2;
  168040. register JDIMENSION col;
  168041. JDIMENSION num_cols = cinfo->output_width;
  168042. /* copy these pointers into registers if possible */
  168043. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168044. register int * Crrtab = cconvert->Cr_r_tab;
  168045. register int * Cbbtab = cconvert->Cb_b_tab;
  168046. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168047. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168048. SHIFT_TEMPS
  168049. while (--num_rows >= 0) {
  168050. inptr0 = input_buf[0][input_row];
  168051. inptr1 = input_buf[1][input_row];
  168052. inptr2 = input_buf[2][input_row];
  168053. input_row++;
  168054. outptr = *output_buf++;
  168055. for (col = 0; col < num_cols; col++) {
  168056. y = GETJSAMPLE(inptr0[col]);
  168057. cb = GETJSAMPLE(inptr1[col]);
  168058. cr = GETJSAMPLE(inptr2[col]);
  168059. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168060. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168061. outptr[RGB_GREEN] = range_limit[y +
  168062. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168063. SCALEBITS))];
  168064. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168065. outptr += RGB_PIXELSIZE;
  168066. }
  168067. }
  168068. }
  168069. /**************** Cases other than YCbCr -> RGB **************/
  168070. /*
  168071. * Color conversion for no colorspace change: just copy the data,
  168072. * converting from separate-planes to interleaved representation.
  168073. */
  168074. METHODDEF(void)
  168075. null_convert2 (j_decompress_ptr cinfo,
  168076. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168077. JSAMPARRAY output_buf, int num_rows)
  168078. {
  168079. register JSAMPROW inptr, outptr;
  168080. register JDIMENSION count;
  168081. register int num_components = cinfo->num_components;
  168082. JDIMENSION num_cols = cinfo->output_width;
  168083. int ci;
  168084. while (--num_rows >= 0) {
  168085. for (ci = 0; ci < num_components; ci++) {
  168086. inptr = input_buf[ci][input_row];
  168087. outptr = output_buf[0] + ci;
  168088. for (count = num_cols; count > 0; count--) {
  168089. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168090. outptr += num_components;
  168091. }
  168092. }
  168093. input_row++;
  168094. output_buf++;
  168095. }
  168096. }
  168097. /*
  168098. * Color conversion for grayscale: just copy the data.
  168099. * This also works for YCbCr -> grayscale conversion, in which
  168100. * we just copy the Y (luminance) component and ignore chrominance.
  168101. */
  168102. METHODDEF(void)
  168103. grayscale_convert2 (j_decompress_ptr cinfo,
  168104. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168105. JSAMPARRAY output_buf, int num_rows)
  168106. {
  168107. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168108. num_rows, cinfo->output_width);
  168109. }
  168110. /*
  168111. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168112. * This is provided to support applications that don't want to cope
  168113. * with grayscale as a separate case.
  168114. */
  168115. METHODDEF(void)
  168116. gray_rgb_convert (j_decompress_ptr cinfo,
  168117. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168118. JSAMPARRAY output_buf, int num_rows)
  168119. {
  168120. register JSAMPROW inptr, outptr;
  168121. register JDIMENSION col;
  168122. JDIMENSION num_cols = cinfo->output_width;
  168123. while (--num_rows >= 0) {
  168124. inptr = input_buf[0][input_row++];
  168125. outptr = *output_buf++;
  168126. for (col = 0; col < num_cols; col++) {
  168127. /* We can dispense with GETJSAMPLE() here */
  168128. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168129. outptr += RGB_PIXELSIZE;
  168130. }
  168131. }
  168132. }
  168133. /*
  168134. * Adobe-style YCCK->CMYK conversion.
  168135. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  168136. * conversion as above, while passing K (black) unchanged.
  168137. * We assume build_ycc_rgb_table has been called.
  168138. */
  168139. METHODDEF(void)
  168140. ycck_cmyk_convert (j_decompress_ptr cinfo,
  168141. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168142. JSAMPARRAY output_buf, int num_rows)
  168143. {
  168144. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168145. register int y, cb, cr;
  168146. register JSAMPROW outptr;
  168147. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  168148. register JDIMENSION col;
  168149. JDIMENSION num_cols = cinfo->output_width;
  168150. /* copy these pointers into registers if possible */
  168151. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168152. register int * Crrtab = cconvert->Cr_r_tab;
  168153. register int * Cbbtab = cconvert->Cb_b_tab;
  168154. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168155. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168156. SHIFT_TEMPS
  168157. while (--num_rows >= 0) {
  168158. inptr0 = input_buf[0][input_row];
  168159. inptr1 = input_buf[1][input_row];
  168160. inptr2 = input_buf[2][input_row];
  168161. inptr3 = input_buf[3][input_row];
  168162. input_row++;
  168163. outptr = *output_buf++;
  168164. for (col = 0; col < num_cols; col++) {
  168165. y = GETJSAMPLE(inptr0[col]);
  168166. cb = GETJSAMPLE(inptr1[col]);
  168167. cr = GETJSAMPLE(inptr2[col]);
  168168. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168169. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  168170. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  168171. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168172. SCALEBITS)))];
  168173. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  168174. /* K passes through unchanged */
  168175. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  168176. outptr += 4;
  168177. }
  168178. }
  168179. }
  168180. /*
  168181. * Empty method for start_pass.
  168182. */
  168183. METHODDEF(void)
  168184. start_pass_dcolor (j_decompress_ptr)
  168185. {
  168186. /* no work needed */
  168187. }
  168188. /*
  168189. * Module initialization routine for output colorspace conversion.
  168190. */
  168191. GLOBAL(void)
  168192. jinit_color_deconverter (j_decompress_ptr cinfo)
  168193. {
  168194. my_cconvert_ptr2 cconvert;
  168195. int ci;
  168196. cconvert = (my_cconvert_ptr2)
  168197. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168198. SIZEOF(my_color_deconverter2));
  168199. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  168200. cconvert->pub.start_pass = start_pass_dcolor;
  168201. /* Make sure num_components agrees with jpeg_color_space */
  168202. switch (cinfo->jpeg_color_space) {
  168203. case JCS_GRAYSCALE:
  168204. if (cinfo->num_components != 1)
  168205. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168206. break;
  168207. case JCS_RGB:
  168208. case JCS_YCbCr:
  168209. if (cinfo->num_components != 3)
  168210. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168211. break;
  168212. case JCS_CMYK:
  168213. case JCS_YCCK:
  168214. if (cinfo->num_components != 4)
  168215. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168216. break;
  168217. default: /* JCS_UNKNOWN can be anything */
  168218. if (cinfo->num_components < 1)
  168219. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168220. break;
  168221. }
  168222. /* Set out_color_components and conversion method based on requested space.
  168223. * Also clear the component_needed flags for any unused components,
  168224. * so that earlier pipeline stages can avoid useless computation.
  168225. */
  168226. switch (cinfo->out_color_space) {
  168227. case JCS_GRAYSCALE:
  168228. cinfo->out_color_components = 1;
  168229. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  168230. cinfo->jpeg_color_space == JCS_YCbCr) {
  168231. cconvert->pub.color_convert = grayscale_convert2;
  168232. /* For color->grayscale conversion, only the Y (0) component is needed */
  168233. for (ci = 1; ci < cinfo->num_components; ci++)
  168234. cinfo->comp_info[ci].component_needed = FALSE;
  168235. } else
  168236. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168237. break;
  168238. case JCS_RGB:
  168239. cinfo->out_color_components = RGB_PIXELSIZE;
  168240. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  168241. cconvert->pub.color_convert = ycc_rgb_convert;
  168242. build_ycc_rgb_table(cinfo);
  168243. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  168244. cconvert->pub.color_convert = gray_rgb_convert;
  168245. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  168246. cconvert->pub.color_convert = null_convert2;
  168247. } else
  168248. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168249. break;
  168250. case JCS_CMYK:
  168251. cinfo->out_color_components = 4;
  168252. if (cinfo->jpeg_color_space == JCS_YCCK) {
  168253. cconvert->pub.color_convert = ycck_cmyk_convert;
  168254. build_ycc_rgb_table(cinfo);
  168255. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  168256. cconvert->pub.color_convert = null_convert2;
  168257. } else
  168258. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168259. break;
  168260. default:
  168261. /* Permit null conversion to same output space */
  168262. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  168263. cinfo->out_color_components = cinfo->num_components;
  168264. cconvert->pub.color_convert = null_convert2;
  168265. } else /* unsupported non-null conversion */
  168266. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168267. break;
  168268. }
  168269. if (cinfo->quantize_colors)
  168270. cinfo->output_components = 1; /* single colormapped output component */
  168271. else
  168272. cinfo->output_components = cinfo->out_color_components;
  168273. }
  168274. /*** End of inlined file: jdcolor.c ***/
  168275. #undef FIX
  168276. /*** Start of inlined file: jddctmgr.c ***/
  168277. #define JPEG_INTERNALS
  168278. /*
  168279. * The decompressor input side (jdinput.c) saves away the appropriate
  168280. * quantization table for each component at the start of the first scan
  168281. * involving that component. (This is necessary in order to correctly
  168282. * decode files that reuse Q-table slots.)
  168283. * When we are ready to make an output pass, the saved Q-table is converted
  168284. * to a multiplier table that will actually be used by the IDCT routine.
  168285. * The multiplier table contents are IDCT-method-dependent. To support
  168286. * application changes in IDCT method between scans, we can remake the
  168287. * multiplier tables if necessary.
  168288. * In buffered-image mode, the first output pass may occur before any data
  168289. * has been seen for some components, and thus before their Q-tables have
  168290. * been saved away. To handle this case, multiplier tables are preset
  168291. * to zeroes; the result of the IDCT will be a neutral gray level.
  168292. */
  168293. /* Private subobject for this module */
  168294. typedef struct {
  168295. struct jpeg_inverse_dct pub; /* public fields */
  168296. /* This array contains the IDCT method code that each multiplier table
  168297. * is currently set up for, or -1 if it's not yet set up.
  168298. * The actual multiplier tables are pointed to by dct_table in the
  168299. * per-component comp_info structures.
  168300. */
  168301. int cur_method[MAX_COMPONENTS];
  168302. } my_idct_controller;
  168303. typedef my_idct_controller * my_idct_ptr;
  168304. /* Allocated multiplier tables: big enough for any supported variant */
  168305. typedef union {
  168306. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  168307. #ifdef DCT_IFAST_SUPPORTED
  168308. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  168309. #endif
  168310. #ifdef DCT_FLOAT_SUPPORTED
  168311. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  168312. #endif
  168313. } multiplier_table;
  168314. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  168315. * so be sure to compile that code if either ISLOW or SCALING is requested.
  168316. */
  168317. #ifdef DCT_ISLOW_SUPPORTED
  168318. #define PROVIDE_ISLOW_TABLES
  168319. #else
  168320. #ifdef IDCT_SCALING_SUPPORTED
  168321. #define PROVIDE_ISLOW_TABLES
  168322. #endif
  168323. #endif
  168324. /*
  168325. * Prepare for an output pass.
  168326. * Here we select the proper IDCT routine for each component and build
  168327. * a matching multiplier table.
  168328. */
  168329. METHODDEF(void)
  168330. start_pass (j_decompress_ptr cinfo)
  168331. {
  168332. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  168333. int ci, i;
  168334. jpeg_component_info *compptr;
  168335. int method = 0;
  168336. inverse_DCT_method_ptr method_ptr = NULL;
  168337. JQUANT_TBL * qtbl;
  168338. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168339. ci++, compptr++) {
  168340. /* Select the proper IDCT routine for this component's scaling */
  168341. switch (compptr->DCT_scaled_size) {
  168342. #ifdef IDCT_SCALING_SUPPORTED
  168343. case 1:
  168344. method_ptr = jpeg_idct_1x1;
  168345. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168346. break;
  168347. case 2:
  168348. method_ptr = jpeg_idct_2x2;
  168349. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168350. break;
  168351. case 4:
  168352. method_ptr = jpeg_idct_4x4;
  168353. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168354. break;
  168355. #endif
  168356. case DCTSIZE:
  168357. switch (cinfo->dct_method) {
  168358. #ifdef DCT_ISLOW_SUPPORTED
  168359. case JDCT_ISLOW:
  168360. method_ptr = jpeg_idct_islow;
  168361. method = JDCT_ISLOW;
  168362. break;
  168363. #endif
  168364. #ifdef DCT_IFAST_SUPPORTED
  168365. case JDCT_IFAST:
  168366. method_ptr = jpeg_idct_ifast;
  168367. method = JDCT_IFAST;
  168368. break;
  168369. #endif
  168370. #ifdef DCT_FLOAT_SUPPORTED
  168371. case JDCT_FLOAT:
  168372. method_ptr = jpeg_idct_float;
  168373. method = JDCT_FLOAT;
  168374. break;
  168375. #endif
  168376. default:
  168377. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168378. break;
  168379. }
  168380. break;
  168381. default:
  168382. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  168383. break;
  168384. }
  168385. idct->pub.inverse_DCT[ci] = method_ptr;
  168386. /* Create multiplier table from quant table.
  168387. * However, we can skip this if the component is uninteresting
  168388. * or if we already built the table. Also, if no quant table
  168389. * has yet been saved for the component, we leave the
  168390. * multiplier table all-zero; we'll be reading zeroes from the
  168391. * coefficient controller's buffer anyway.
  168392. */
  168393. if (! compptr->component_needed || idct->cur_method[ci] == method)
  168394. continue;
  168395. qtbl = compptr->quant_table;
  168396. if (qtbl == NULL) /* happens if no data yet for component */
  168397. continue;
  168398. idct->cur_method[ci] = method;
  168399. switch (method) {
  168400. #ifdef PROVIDE_ISLOW_TABLES
  168401. case JDCT_ISLOW:
  168402. {
  168403. /* For LL&M IDCT method, multipliers are equal to raw quantization
  168404. * coefficients, but are stored as ints to ensure access efficiency.
  168405. */
  168406. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  168407. for (i = 0; i < DCTSIZE2; i++) {
  168408. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  168409. }
  168410. }
  168411. break;
  168412. #endif
  168413. #ifdef DCT_IFAST_SUPPORTED
  168414. case JDCT_IFAST:
  168415. {
  168416. /* For AA&N IDCT method, multipliers are equal to quantization
  168417. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  168418. * scalefactor[0] = 1
  168419. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  168420. * For integer operation, the multiplier table is to be scaled by
  168421. * IFAST_SCALE_BITS.
  168422. */
  168423. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  168424. #define CONST_BITS 14
  168425. static const INT16 aanscales[DCTSIZE2] = {
  168426. /* precomputed values scaled up by 14 bits */
  168427. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  168428. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  168429. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  168430. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  168431. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  168432. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  168433. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  168434. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  168435. };
  168436. SHIFT_TEMPS
  168437. for (i = 0; i < DCTSIZE2; i++) {
  168438. ifmtbl[i] = (IFAST_MULT_TYPE)
  168439. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  168440. (INT32) aanscales[i]),
  168441. CONST_BITS-IFAST_SCALE_BITS);
  168442. }
  168443. }
  168444. break;
  168445. #endif
  168446. #ifdef DCT_FLOAT_SUPPORTED
  168447. case JDCT_FLOAT:
  168448. {
  168449. /* For float AA&N IDCT method, multipliers are equal to quantization
  168450. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  168451. * scalefactor[0] = 1
  168452. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  168453. */
  168454. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  168455. int row, col;
  168456. static const double aanscalefactor[DCTSIZE] = {
  168457. 1.0, 1.387039845, 1.306562965, 1.175875602,
  168458. 1.0, 0.785694958, 0.541196100, 0.275899379
  168459. };
  168460. i = 0;
  168461. for (row = 0; row < DCTSIZE; row++) {
  168462. for (col = 0; col < DCTSIZE; col++) {
  168463. fmtbl[i] = (FLOAT_MULT_TYPE)
  168464. ((double) qtbl->quantval[i] *
  168465. aanscalefactor[row] * aanscalefactor[col]);
  168466. i++;
  168467. }
  168468. }
  168469. }
  168470. break;
  168471. #endif
  168472. default:
  168473. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168474. break;
  168475. }
  168476. }
  168477. }
  168478. /*
  168479. * Initialize IDCT manager.
  168480. */
  168481. GLOBAL(void)
  168482. jinit_inverse_dct (j_decompress_ptr cinfo)
  168483. {
  168484. my_idct_ptr idct;
  168485. int ci;
  168486. jpeg_component_info *compptr;
  168487. idct = (my_idct_ptr)
  168488. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168489. SIZEOF(my_idct_controller));
  168490. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  168491. idct->pub.start_pass = start_pass;
  168492. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168493. ci++, compptr++) {
  168494. /* Allocate and pre-zero a multiplier table for each component */
  168495. compptr->dct_table =
  168496. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168497. SIZEOF(multiplier_table));
  168498. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  168499. /* Mark multiplier table not yet set up for any method */
  168500. idct->cur_method[ci] = -1;
  168501. }
  168502. }
  168503. /*** End of inlined file: jddctmgr.c ***/
  168504. #undef CONST_BITS
  168505. #undef ASSIGN_STATE
  168506. /*** Start of inlined file: jdhuff.c ***/
  168507. #define JPEG_INTERNALS
  168508. /*** Start of inlined file: jdhuff.h ***/
  168509. /* Short forms of external names for systems with brain-damaged linkers. */
  168510. #ifndef __jdhuff_h__
  168511. #define __jdhuff_h__
  168512. #ifdef NEED_SHORT_EXTERNAL_NAMES
  168513. #define jpeg_make_d_derived_tbl jMkDDerived
  168514. #define jpeg_fill_bit_buffer jFilBitBuf
  168515. #define jpeg_huff_decode jHufDecode
  168516. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  168517. /* Derived data constructed for each Huffman table */
  168518. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  168519. typedef struct {
  168520. /* Basic tables: (element [0] of each array is unused) */
  168521. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  168522. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  168523. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  168524. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  168525. * the smallest code of length k; so given a code of length k, the
  168526. * corresponding symbol is huffval[code + valoffset[k]]
  168527. */
  168528. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  168529. JHUFF_TBL *pub;
  168530. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  168531. * the input data stream. If the next Huffman code is no more
  168532. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  168533. * the corresponding symbol directly from these tables.
  168534. */
  168535. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  168536. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  168537. } d_derived_tbl;
  168538. /* Expand a Huffman table definition into the derived format */
  168539. EXTERN(void) jpeg_make_d_derived_tbl
  168540. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  168541. d_derived_tbl ** pdtbl));
  168542. /*
  168543. * Fetching the next N bits from the input stream is a time-critical operation
  168544. * for the Huffman decoders. We implement it with a combination of inline
  168545. * macros and out-of-line subroutines. Note that N (the number of bits
  168546. * demanded at one time) never exceeds 15 for JPEG use.
  168547. *
  168548. * We read source bytes into get_buffer and dole out bits as needed.
  168549. * If get_buffer already contains enough bits, they are fetched in-line
  168550. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  168551. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  168552. * as full as possible (not just to the number of bits needed; this
  168553. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  168554. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  168555. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  168556. * at least the requested number of bits --- dummy zeroes are inserted if
  168557. * necessary.
  168558. */
  168559. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  168560. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  168561. /* If long is > 32 bits on your machine, and shifting/masking longs is
  168562. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  168563. * appropriately should be a win. Unfortunately we can't define the size
  168564. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  168565. * because not all machines measure sizeof in 8-bit bytes.
  168566. */
  168567. typedef struct { /* Bitreading state saved across MCUs */
  168568. bit_buf_type get_buffer; /* current bit-extraction buffer */
  168569. int bits_left; /* # of unused bits in it */
  168570. } bitread_perm_state;
  168571. typedef struct { /* Bitreading working state within an MCU */
  168572. /* Current data source location */
  168573. /* We need a copy, rather than munging the original, in case of suspension */
  168574. const JOCTET * next_input_byte; /* => next byte to read from source */
  168575. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  168576. /* Bit input buffer --- note these values are kept in register variables,
  168577. * not in this struct, inside the inner loops.
  168578. */
  168579. bit_buf_type get_buffer; /* current bit-extraction buffer */
  168580. int bits_left; /* # of unused bits in it */
  168581. /* Pointer needed by jpeg_fill_bit_buffer. */
  168582. j_decompress_ptr cinfo; /* back link to decompress master record */
  168583. } bitread_working_state;
  168584. /* Macros to declare and load/save bitread local variables. */
  168585. #define BITREAD_STATE_VARS \
  168586. register bit_buf_type get_buffer; \
  168587. register int bits_left; \
  168588. bitread_working_state br_state
  168589. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  168590. br_state.cinfo = cinfop; \
  168591. br_state.next_input_byte = cinfop->src->next_input_byte; \
  168592. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  168593. get_buffer = permstate.get_buffer; \
  168594. bits_left = permstate.bits_left;
  168595. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  168596. cinfop->src->next_input_byte = br_state.next_input_byte; \
  168597. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  168598. permstate.get_buffer = get_buffer; \
  168599. permstate.bits_left = bits_left
  168600. /*
  168601. * These macros provide the in-line portion of bit fetching.
  168602. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  168603. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  168604. * The variables get_buffer and bits_left are assumed to be locals,
  168605. * but the state struct might not be (jpeg_huff_decode needs this).
  168606. * CHECK_BIT_BUFFER(state,n,action);
  168607. * Ensure there are N bits in get_buffer; if suspend, take action.
  168608. * val = GET_BITS(n);
  168609. * Fetch next N bits.
  168610. * val = PEEK_BITS(n);
  168611. * Fetch next N bits without removing them from the buffer.
  168612. * DROP_BITS(n);
  168613. * Discard next N bits.
  168614. * The value N should be a simple variable, not an expression, because it
  168615. * is evaluated multiple times.
  168616. */
  168617. #define CHECK_BIT_BUFFER(state,nbits,action) \
  168618. { if (bits_left < (nbits)) { \
  168619. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  168620. { action; } \
  168621. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  168622. #define GET_BITS(nbits) \
  168623. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  168624. #define PEEK_BITS(nbits) \
  168625. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  168626. #define DROP_BITS(nbits) \
  168627. (bits_left -= (nbits))
  168628. /* Load up the bit buffer to a depth of at least nbits */
  168629. EXTERN(boolean) jpeg_fill_bit_buffer
  168630. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  168631. register int bits_left, int nbits));
  168632. /*
  168633. * Code for extracting next Huffman-coded symbol from input bit stream.
  168634. * Again, this is time-critical and we make the main paths be macros.
  168635. *
  168636. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  168637. * without looping. Usually, more than 95% of the Huffman codes will be 8
  168638. * or fewer bits long. The few overlength codes are handled with a loop,
  168639. * which need not be inline code.
  168640. *
  168641. * Notes about the HUFF_DECODE macro:
  168642. * 1. Near the end of the data segment, we may fail to get enough bits
  168643. * for a lookahead. In that case, we do it the hard way.
  168644. * 2. If the lookahead table contains no entry, the next code must be
  168645. * more than HUFF_LOOKAHEAD bits long.
  168646. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  168647. */
  168648. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  168649. { register int nb, look; \
  168650. if (bits_left < HUFF_LOOKAHEAD) { \
  168651. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  168652. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  168653. if (bits_left < HUFF_LOOKAHEAD) { \
  168654. nb = 1; goto slowlabel; \
  168655. } \
  168656. } \
  168657. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  168658. if ((nb = htbl->look_nbits[look]) != 0) { \
  168659. DROP_BITS(nb); \
  168660. result = htbl->look_sym[look]; \
  168661. } else { \
  168662. nb = HUFF_LOOKAHEAD+1; \
  168663. slowlabel: \
  168664. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  168665. { failaction; } \
  168666. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  168667. } \
  168668. }
  168669. /* Out-of-line case for Huffman code fetching */
  168670. EXTERN(int) jpeg_huff_decode
  168671. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  168672. register int bits_left, d_derived_tbl * htbl, int min_bits));
  168673. #endif
  168674. /*** End of inlined file: jdhuff.h ***/
  168675. /* Declarations shared with jdphuff.c */
  168676. /*
  168677. * Expanded entropy decoder object for Huffman decoding.
  168678. *
  168679. * The savable_state subrecord contains fields that change within an MCU,
  168680. * but must not be updated permanently until we complete the MCU.
  168681. */
  168682. typedef struct {
  168683. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  168684. } savable_state2;
  168685. /* This macro is to work around compilers with missing or broken
  168686. * structure assignment. You'll need to fix this code if you have
  168687. * such a compiler and you change MAX_COMPS_IN_SCAN.
  168688. */
  168689. #ifndef NO_STRUCT_ASSIGN
  168690. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  168691. #else
  168692. #if MAX_COMPS_IN_SCAN == 4
  168693. #define ASSIGN_STATE(dest,src) \
  168694. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  168695. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  168696. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  168697. (dest).last_dc_val[3] = (src).last_dc_val[3])
  168698. #endif
  168699. #endif
  168700. typedef struct {
  168701. struct jpeg_entropy_decoder pub; /* public fields */
  168702. /* These fields are loaded into local variables at start of each MCU.
  168703. * In case of suspension, we exit WITHOUT updating them.
  168704. */
  168705. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  168706. savable_state2 saved; /* Other state at start of MCU */
  168707. /* These fields are NOT loaded into local working state. */
  168708. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  168709. /* Pointers to derived tables (these workspaces have image lifespan) */
  168710. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  168711. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  168712. /* Precalculated info set up by start_pass for use in decode_mcu: */
  168713. /* Pointers to derived tables to be used for each block within an MCU */
  168714. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  168715. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  168716. /* Whether we care about the DC and AC coefficient values for each block */
  168717. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  168718. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  168719. } huff_entropy_decoder2;
  168720. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  168721. /*
  168722. * Initialize for a Huffman-compressed scan.
  168723. */
  168724. METHODDEF(void)
  168725. start_pass_huff_decoder (j_decompress_ptr cinfo)
  168726. {
  168727. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  168728. int ci, blkn, dctbl, actbl;
  168729. jpeg_component_info * compptr;
  168730. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  168731. * This ought to be an error condition, but we make it a warning because
  168732. * there are some baseline files out there with all zeroes in these bytes.
  168733. */
  168734. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  168735. cinfo->Ah != 0 || cinfo->Al != 0)
  168736. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  168737. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168738. compptr = cinfo->cur_comp_info[ci];
  168739. dctbl = compptr->dc_tbl_no;
  168740. actbl = compptr->ac_tbl_no;
  168741. /* Compute derived values for Huffman tables */
  168742. /* We may do this more than once for a table, but it's not expensive */
  168743. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  168744. & entropy->dc_derived_tbls[dctbl]);
  168745. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  168746. & entropy->ac_derived_tbls[actbl]);
  168747. /* Initialize DC predictions to 0 */
  168748. entropy->saved.last_dc_val[ci] = 0;
  168749. }
  168750. /* Precalculate decoding info for each block in an MCU of this scan */
  168751. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168752. ci = cinfo->MCU_membership[blkn];
  168753. compptr = cinfo->cur_comp_info[ci];
  168754. /* Precalculate which table to use for each block */
  168755. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  168756. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  168757. /* Decide whether we really care about the coefficient values */
  168758. if (compptr->component_needed) {
  168759. entropy->dc_needed[blkn] = TRUE;
  168760. /* we don't need the ACs if producing a 1/8th-size image */
  168761. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  168762. } else {
  168763. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  168764. }
  168765. }
  168766. /* Initialize bitread state variables */
  168767. entropy->bitstate.bits_left = 0;
  168768. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  168769. entropy->pub.insufficient_data = FALSE;
  168770. /* Initialize restart counter */
  168771. entropy->restarts_to_go = cinfo->restart_interval;
  168772. }
  168773. /*
  168774. * Compute the derived values for a Huffman table.
  168775. * This routine also performs some validation checks on the table.
  168776. *
  168777. * Note this is also used by jdphuff.c.
  168778. */
  168779. GLOBAL(void)
  168780. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  168781. d_derived_tbl ** pdtbl)
  168782. {
  168783. JHUFF_TBL *htbl;
  168784. d_derived_tbl *dtbl;
  168785. int p, i, l, si, numsymbols;
  168786. int lookbits, ctr;
  168787. char huffsize[257];
  168788. unsigned int huffcode[257];
  168789. unsigned int code;
  168790. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  168791. * paralleling the order of the symbols themselves in htbl->huffval[].
  168792. */
  168793. /* Find the input Huffman table */
  168794. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  168795. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  168796. htbl =
  168797. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  168798. if (htbl == NULL)
  168799. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  168800. /* Allocate a workspace if we haven't already done so. */
  168801. if (*pdtbl == NULL)
  168802. *pdtbl = (d_derived_tbl *)
  168803. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168804. SIZEOF(d_derived_tbl));
  168805. dtbl = *pdtbl;
  168806. dtbl->pub = htbl; /* fill in back link */
  168807. /* Figure C.1: make table of Huffman code length for each symbol */
  168808. p = 0;
  168809. for (l = 1; l <= 16; l++) {
  168810. i = (int) htbl->bits[l];
  168811. if (i < 0 || p + i > 256) /* protect against table overrun */
  168812. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  168813. while (i--)
  168814. huffsize[p++] = (char) l;
  168815. }
  168816. huffsize[p] = 0;
  168817. numsymbols = p;
  168818. /* Figure C.2: generate the codes themselves */
  168819. /* We also validate that the counts represent a legal Huffman code tree. */
  168820. code = 0;
  168821. si = huffsize[0];
  168822. p = 0;
  168823. while (huffsize[p]) {
  168824. while (((int) huffsize[p]) == si) {
  168825. huffcode[p++] = code;
  168826. code++;
  168827. }
  168828. /* code is now 1 more than the last code used for codelength si; but
  168829. * it must still fit in si bits, since no code is allowed to be all ones.
  168830. */
  168831. if (((INT32) code) >= (((INT32) 1) << si))
  168832. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  168833. code <<= 1;
  168834. si++;
  168835. }
  168836. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  168837. p = 0;
  168838. for (l = 1; l <= 16; l++) {
  168839. if (htbl->bits[l]) {
  168840. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  168841. * minus the minimum code of length l
  168842. */
  168843. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  168844. p += htbl->bits[l];
  168845. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  168846. } else {
  168847. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  168848. }
  168849. }
  168850. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  168851. /* Compute lookahead tables to speed up decoding.
  168852. * First we set all the table entries to 0, indicating "too long";
  168853. * then we iterate through the Huffman codes that are short enough and
  168854. * fill in all the entries that correspond to bit sequences starting
  168855. * with that code.
  168856. */
  168857. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  168858. p = 0;
  168859. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  168860. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  168861. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  168862. /* Generate left-justified code followed by all possible bit sequences */
  168863. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  168864. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  168865. dtbl->look_nbits[lookbits] = l;
  168866. dtbl->look_sym[lookbits] = htbl->huffval[p];
  168867. lookbits++;
  168868. }
  168869. }
  168870. }
  168871. /* Validate symbols as being reasonable.
  168872. * For AC tables, we make no check, but accept all byte values 0..255.
  168873. * For DC tables, we require the symbols to be in range 0..15.
  168874. * (Tighter bounds could be applied depending on the data depth and mode,
  168875. * but this is sufficient to ensure safe decoding.)
  168876. */
  168877. if (isDC) {
  168878. for (i = 0; i < numsymbols; i++) {
  168879. int sym = htbl->huffval[i];
  168880. if (sym < 0 || sym > 15)
  168881. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  168882. }
  168883. }
  168884. }
  168885. /*
  168886. * Out-of-line code for bit fetching (shared with jdphuff.c).
  168887. * See jdhuff.h for info about usage.
  168888. * Note: current values of get_buffer and bits_left are passed as parameters,
  168889. * but are returned in the corresponding fields of the state struct.
  168890. *
  168891. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  168892. * of get_buffer to be used. (On machines with wider words, an even larger
  168893. * buffer could be used.) However, on some machines 32-bit shifts are
  168894. * quite slow and take time proportional to the number of places shifted.
  168895. * (This is true with most PC compilers, for instance.) In this case it may
  168896. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  168897. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  168898. */
  168899. #ifdef SLOW_SHIFT_32
  168900. #define MIN_GET_BITS 15 /* minimum allowable value */
  168901. #else
  168902. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  168903. #endif
  168904. GLOBAL(boolean)
  168905. jpeg_fill_bit_buffer (bitread_working_state * state,
  168906. register bit_buf_type get_buffer, register int bits_left,
  168907. int nbits)
  168908. /* Load up the bit buffer to a depth of at least nbits */
  168909. {
  168910. /* Copy heavily used state fields into locals (hopefully registers) */
  168911. register const JOCTET * next_input_byte = state->next_input_byte;
  168912. register size_t bytes_in_buffer = state->bytes_in_buffer;
  168913. j_decompress_ptr cinfo = state->cinfo;
  168914. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  168915. /* (It is assumed that no request will be for more than that many bits.) */
  168916. /* We fail to do so only if we hit a marker or are forced to suspend. */
  168917. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  168918. while (bits_left < MIN_GET_BITS) {
  168919. register int c;
  168920. /* Attempt to read a byte */
  168921. if (bytes_in_buffer == 0) {
  168922. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  168923. return FALSE;
  168924. next_input_byte = cinfo->src->next_input_byte;
  168925. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  168926. }
  168927. bytes_in_buffer--;
  168928. c = GETJOCTET(*next_input_byte++);
  168929. /* If it's 0xFF, check and discard stuffed zero byte */
  168930. if (c == 0xFF) {
  168931. /* Loop here to discard any padding FF's on terminating marker,
  168932. * so that we can save a valid unread_marker value. NOTE: we will
  168933. * accept multiple FF's followed by a 0 as meaning a single FF data
  168934. * byte. This data pattern is not valid according to the standard.
  168935. */
  168936. do {
  168937. if (bytes_in_buffer == 0) {
  168938. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  168939. return FALSE;
  168940. next_input_byte = cinfo->src->next_input_byte;
  168941. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  168942. }
  168943. bytes_in_buffer--;
  168944. c = GETJOCTET(*next_input_byte++);
  168945. } while (c == 0xFF);
  168946. if (c == 0) {
  168947. /* Found FF/00, which represents an FF data byte */
  168948. c = 0xFF;
  168949. } else {
  168950. /* Oops, it's actually a marker indicating end of compressed data.
  168951. * Save the marker code for later use.
  168952. * Fine point: it might appear that we should save the marker into
  168953. * bitread working state, not straight into permanent state. But
  168954. * once we have hit a marker, we cannot need to suspend within the
  168955. * current MCU, because we will read no more bytes from the data
  168956. * source. So it is OK to update permanent state right away.
  168957. */
  168958. cinfo->unread_marker = c;
  168959. /* See if we need to insert some fake zero bits. */
  168960. goto no_more_bytes;
  168961. }
  168962. }
  168963. /* OK, load c into get_buffer */
  168964. get_buffer = (get_buffer << 8) | c;
  168965. bits_left += 8;
  168966. } /* end while */
  168967. } else {
  168968. no_more_bytes:
  168969. /* We get here if we've read the marker that terminates the compressed
  168970. * data segment. There should be enough bits in the buffer register
  168971. * to satisfy the request; if so, no problem.
  168972. */
  168973. if (nbits > bits_left) {
  168974. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  168975. * the data stream, so that we can produce some kind of image.
  168976. * We use a nonvolatile flag to ensure that only one warning message
  168977. * appears per data segment.
  168978. */
  168979. if (! cinfo->entropy->insufficient_data) {
  168980. WARNMS(cinfo, JWRN_HIT_MARKER);
  168981. cinfo->entropy->insufficient_data = TRUE;
  168982. }
  168983. /* Fill the buffer with zero bits */
  168984. get_buffer <<= MIN_GET_BITS - bits_left;
  168985. bits_left = MIN_GET_BITS;
  168986. }
  168987. }
  168988. /* Unload the local registers */
  168989. state->next_input_byte = next_input_byte;
  168990. state->bytes_in_buffer = bytes_in_buffer;
  168991. state->get_buffer = get_buffer;
  168992. state->bits_left = bits_left;
  168993. return TRUE;
  168994. }
  168995. /*
  168996. * Out-of-line code for Huffman code decoding.
  168997. * See jdhuff.h for info about usage.
  168998. */
  168999. GLOBAL(int)
  169000. jpeg_huff_decode (bitread_working_state * state,
  169001. register bit_buf_type get_buffer, register int bits_left,
  169002. d_derived_tbl * htbl, int min_bits)
  169003. {
  169004. register int l = min_bits;
  169005. register INT32 code;
  169006. /* HUFF_DECODE has determined that the code is at least min_bits */
  169007. /* bits long, so fetch that many bits in one swoop. */
  169008. CHECK_BIT_BUFFER(*state, l, return -1);
  169009. code = GET_BITS(l);
  169010. /* Collect the rest of the Huffman code one bit at a time. */
  169011. /* This is per Figure F.16 in the JPEG spec. */
  169012. while (code > htbl->maxcode[l]) {
  169013. code <<= 1;
  169014. CHECK_BIT_BUFFER(*state, 1, return -1);
  169015. code |= GET_BITS(1);
  169016. l++;
  169017. }
  169018. /* Unload the local registers */
  169019. state->get_buffer = get_buffer;
  169020. state->bits_left = bits_left;
  169021. /* With garbage input we may reach the sentinel value l = 17. */
  169022. if (l > 16) {
  169023. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169024. return 0; /* fake a zero as the safest result */
  169025. }
  169026. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169027. }
  169028. /*
  169029. * Check for a restart marker & resynchronize decoder.
  169030. * Returns FALSE if must suspend.
  169031. */
  169032. LOCAL(boolean)
  169033. process_restart (j_decompress_ptr cinfo)
  169034. {
  169035. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169036. int ci;
  169037. /* Throw away any unused bits remaining in bit buffer; */
  169038. /* include any full bytes in next_marker's count of discarded bytes */
  169039. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169040. entropy->bitstate.bits_left = 0;
  169041. /* Advance past the RSTn marker */
  169042. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169043. return FALSE;
  169044. /* Re-initialize DC predictions to 0 */
  169045. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169046. entropy->saved.last_dc_val[ci] = 0;
  169047. /* Reset restart counter */
  169048. entropy->restarts_to_go = cinfo->restart_interval;
  169049. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169050. * against a marker. In that case we will end up treating the next data
  169051. * segment as empty, and we can avoid producing bogus output pixels by
  169052. * leaving the flag set.
  169053. */
  169054. if (cinfo->unread_marker == 0)
  169055. entropy->pub.insufficient_data = FALSE;
  169056. return TRUE;
  169057. }
  169058. /*
  169059. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169060. * The coefficients are reordered from zigzag order into natural array order,
  169061. * but are not dequantized.
  169062. *
  169063. * The i'th block of the MCU is stored into the block pointed to by
  169064. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169065. * (Wholesale zeroing is usually a little faster than retail...)
  169066. *
  169067. * Returns FALSE if data source requested suspension. In that case no
  169068. * changes have been made to permanent state. (Exception: some output
  169069. * coefficients may already have been assigned. This is harmless for
  169070. * this module, since we'll just re-assign them on the next call.)
  169071. */
  169072. METHODDEF(boolean)
  169073. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169074. {
  169075. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169076. int blkn;
  169077. BITREAD_STATE_VARS;
  169078. savable_state2 state;
  169079. /* Process restart marker if needed; may have to suspend */
  169080. if (cinfo->restart_interval) {
  169081. if (entropy->restarts_to_go == 0)
  169082. if (! process_restart(cinfo))
  169083. return FALSE;
  169084. }
  169085. /* If we've run out of data, just leave the MCU set to zeroes.
  169086. * This way, we return uniform gray for the remainder of the segment.
  169087. */
  169088. if (! entropy->pub.insufficient_data) {
  169089. /* Load up working state */
  169090. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169091. ASSIGN_STATE(state, entropy->saved);
  169092. /* Outer loop handles each block in the MCU */
  169093. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169094. JBLOCKROW block = MCU_data[blkn];
  169095. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169096. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169097. register int s, k, r;
  169098. /* Decode a single block's worth of coefficients */
  169099. /* Section F.2.2.1: decode the DC coefficient difference */
  169100. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169101. if (s) {
  169102. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169103. r = GET_BITS(s);
  169104. s = HUFF_EXTEND(r, s);
  169105. }
  169106. if (entropy->dc_needed[blkn]) {
  169107. /* Convert DC difference to actual value, update last_dc_val */
  169108. int ci = cinfo->MCU_membership[blkn];
  169109. s += state.last_dc_val[ci];
  169110. state.last_dc_val[ci] = s;
  169111. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169112. (*block)[0] = (JCOEF) s;
  169113. }
  169114. if (entropy->ac_needed[blkn]) {
  169115. /* Section F.2.2.2: decode the AC coefficients */
  169116. /* Since zeroes are skipped, output area must be cleared beforehand */
  169117. for (k = 1; k < DCTSIZE2; k++) {
  169118. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169119. r = s >> 4;
  169120. s &= 15;
  169121. if (s) {
  169122. k += r;
  169123. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169124. r = GET_BITS(s);
  169125. s = HUFF_EXTEND(r, s);
  169126. /* Output coefficient in natural (dezigzagged) order.
  169127. * Note: the extra entries in jpeg_natural_order[] will save us
  169128. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169129. */
  169130. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169131. } else {
  169132. if (r != 15)
  169133. break;
  169134. k += 15;
  169135. }
  169136. }
  169137. } else {
  169138. /* Section F.2.2.2: decode the AC coefficients */
  169139. /* In this path we just discard the values */
  169140. for (k = 1; k < DCTSIZE2; k++) {
  169141. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  169142. r = s >> 4;
  169143. s &= 15;
  169144. if (s) {
  169145. k += r;
  169146. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169147. DROP_BITS(s);
  169148. } else {
  169149. if (r != 15)
  169150. break;
  169151. k += 15;
  169152. }
  169153. }
  169154. }
  169155. }
  169156. /* Completed MCU, so update state */
  169157. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169158. ASSIGN_STATE(entropy->saved, state);
  169159. }
  169160. /* Account for restart interval (no-op if not using restarts) */
  169161. entropy->restarts_to_go--;
  169162. return TRUE;
  169163. }
  169164. /*
  169165. * Module initialization routine for Huffman entropy decoding.
  169166. */
  169167. GLOBAL(void)
  169168. jinit_huff_decoder (j_decompress_ptr cinfo)
  169169. {
  169170. huff_entropy_ptr2 entropy;
  169171. int i;
  169172. entropy = (huff_entropy_ptr2)
  169173. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169174. SIZEOF(huff_entropy_decoder2));
  169175. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169176. entropy->pub.start_pass = start_pass_huff_decoder;
  169177. entropy->pub.decode_mcu = decode_mcu;
  169178. /* Mark tables unallocated */
  169179. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169180. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  169181. }
  169182. }
  169183. /*** End of inlined file: jdhuff.c ***/
  169184. /*** Start of inlined file: jdinput.c ***/
  169185. #define JPEG_INTERNALS
  169186. /* Private state */
  169187. typedef struct {
  169188. struct jpeg_input_controller pub; /* public fields */
  169189. boolean inheaders; /* TRUE until first SOS is reached */
  169190. } my_input_controller;
  169191. typedef my_input_controller * my_inputctl_ptr;
  169192. /* Forward declarations */
  169193. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  169194. /*
  169195. * Routines to calculate various quantities related to the size of the image.
  169196. */
  169197. LOCAL(void)
  169198. initial_setup2 (j_decompress_ptr cinfo)
  169199. /* Called once, when first SOS marker is reached */
  169200. {
  169201. int ci;
  169202. jpeg_component_info *compptr;
  169203. /* Make sure image isn't bigger than I can handle */
  169204. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  169205. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  169206. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  169207. /* For now, precision must match compiled-in value... */
  169208. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  169209. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  169210. /* Check that number of components won't exceed internal array sizes */
  169211. if (cinfo->num_components > MAX_COMPONENTS)
  169212. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  169213. MAX_COMPONENTS);
  169214. /* Compute maximum sampling factors; check factor validity */
  169215. cinfo->max_h_samp_factor = 1;
  169216. cinfo->max_v_samp_factor = 1;
  169217. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169218. ci++, compptr++) {
  169219. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  169220. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  169221. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  169222. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  169223. compptr->h_samp_factor);
  169224. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  169225. compptr->v_samp_factor);
  169226. }
  169227. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  169228. * In the full decompressor, this will be overridden by jdmaster.c;
  169229. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  169230. */
  169231. cinfo->min_DCT_scaled_size = DCTSIZE;
  169232. /* Compute dimensions of components */
  169233. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169234. ci++, compptr++) {
  169235. compptr->DCT_scaled_size = DCTSIZE;
  169236. /* Size in DCT blocks */
  169237. compptr->width_in_blocks = (JDIMENSION)
  169238. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169239. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  169240. compptr->height_in_blocks = (JDIMENSION)
  169241. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169242. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  169243. /* downsampled_width and downsampled_height will also be overridden by
  169244. * jdmaster.c if we are doing full decompression. The transcoder library
  169245. * doesn't use these values, but the calling application might.
  169246. */
  169247. /* Size in samples */
  169248. compptr->downsampled_width = (JDIMENSION)
  169249. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169250. (long) cinfo->max_h_samp_factor);
  169251. compptr->downsampled_height = (JDIMENSION)
  169252. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169253. (long) cinfo->max_v_samp_factor);
  169254. /* Mark component needed, until color conversion says otherwise */
  169255. compptr->component_needed = TRUE;
  169256. /* Mark no quantization table yet saved for component */
  169257. compptr->quant_table = NULL;
  169258. }
  169259. /* Compute number of fully interleaved MCU rows. */
  169260. cinfo->total_iMCU_rows = (JDIMENSION)
  169261. jdiv_round_up((long) cinfo->image_height,
  169262. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169263. /* Decide whether file contains multiple scans */
  169264. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  169265. cinfo->inputctl->has_multiple_scans = TRUE;
  169266. else
  169267. cinfo->inputctl->has_multiple_scans = FALSE;
  169268. }
  169269. LOCAL(void)
  169270. per_scan_setup2 (j_decompress_ptr cinfo)
  169271. /* Do computations that are needed before processing a JPEG scan */
  169272. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  169273. {
  169274. int ci, mcublks, tmp;
  169275. jpeg_component_info *compptr;
  169276. if (cinfo->comps_in_scan == 1) {
  169277. /* Noninterleaved (single-component) scan */
  169278. compptr = cinfo->cur_comp_info[0];
  169279. /* Overall image size in MCUs */
  169280. cinfo->MCUs_per_row = compptr->width_in_blocks;
  169281. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  169282. /* For noninterleaved scan, always one block per MCU */
  169283. compptr->MCU_width = 1;
  169284. compptr->MCU_height = 1;
  169285. compptr->MCU_blocks = 1;
  169286. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  169287. compptr->last_col_width = 1;
  169288. /* For noninterleaved scans, it is convenient to define last_row_height
  169289. * as the number of block rows present in the last iMCU row.
  169290. */
  169291. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169292. if (tmp == 0) tmp = compptr->v_samp_factor;
  169293. compptr->last_row_height = tmp;
  169294. /* Prepare array describing MCU composition */
  169295. cinfo->blocks_in_MCU = 1;
  169296. cinfo->MCU_membership[0] = 0;
  169297. } else {
  169298. /* Interleaved (multi-component) scan */
  169299. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  169300. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  169301. MAX_COMPS_IN_SCAN);
  169302. /* Overall image size in MCUs */
  169303. cinfo->MCUs_per_row = (JDIMENSION)
  169304. jdiv_round_up((long) cinfo->image_width,
  169305. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  169306. cinfo->MCU_rows_in_scan = (JDIMENSION)
  169307. jdiv_round_up((long) cinfo->image_height,
  169308. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169309. cinfo->blocks_in_MCU = 0;
  169310. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169311. compptr = cinfo->cur_comp_info[ci];
  169312. /* Sampling factors give # of blocks of component in each MCU */
  169313. compptr->MCU_width = compptr->h_samp_factor;
  169314. compptr->MCU_height = compptr->v_samp_factor;
  169315. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  169316. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  169317. /* Figure number of non-dummy blocks in last MCU column & row */
  169318. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  169319. if (tmp == 0) tmp = compptr->MCU_width;
  169320. compptr->last_col_width = tmp;
  169321. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  169322. if (tmp == 0) tmp = compptr->MCU_height;
  169323. compptr->last_row_height = tmp;
  169324. /* Prepare array describing MCU composition */
  169325. mcublks = compptr->MCU_blocks;
  169326. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  169327. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  169328. while (mcublks-- > 0) {
  169329. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  169330. }
  169331. }
  169332. }
  169333. }
  169334. /*
  169335. * Save away a copy of the Q-table referenced by each component present
  169336. * in the current scan, unless already saved during a prior scan.
  169337. *
  169338. * In a multiple-scan JPEG file, the encoder could assign different components
  169339. * the same Q-table slot number, but change table definitions between scans
  169340. * so that each component uses a different Q-table. (The IJG encoder is not
  169341. * currently capable of doing this, but other encoders might.) Since we want
  169342. * to be able to dequantize all the components at the end of the file, this
  169343. * means that we have to save away the table actually used for each component.
  169344. * We do this by copying the table at the start of the first scan containing
  169345. * the component.
  169346. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  169347. * slot between scans of a component using that slot. If the encoder does so
  169348. * anyway, this decoder will simply use the Q-table values that were current
  169349. * at the start of the first scan for the component.
  169350. *
  169351. * The decompressor output side looks only at the saved quant tables,
  169352. * not at the current Q-table slots.
  169353. */
  169354. LOCAL(void)
  169355. latch_quant_tables (j_decompress_ptr cinfo)
  169356. {
  169357. int ci, qtblno;
  169358. jpeg_component_info *compptr;
  169359. JQUANT_TBL * qtbl;
  169360. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169361. compptr = cinfo->cur_comp_info[ci];
  169362. /* No work if we already saved Q-table for this component */
  169363. if (compptr->quant_table != NULL)
  169364. continue;
  169365. /* Make sure specified quantization table is present */
  169366. qtblno = compptr->quant_tbl_no;
  169367. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  169368. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  169369. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  169370. /* OK, save away the quantization table */
  169371. qtbl = (JQUANT_TBL *)
  169372. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169373. SIZEOF(JQUANT_TBL));
  169374. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  169375. compptr->quant_table = qtbl;
  169376. }
  169377. }
  169378. /*
  169379. * Initialize the input modules to read a scan of compressed data.
  169380. * The first call to this is done by jdmaster.c after initializing
  169381. * the entire decompressor (during jpeg_start_decompress).
  169382. * Subsequent calls come from consume_markers, below.
  169383. */
  169384. METHODDEF(void)
  169385. start_input_pass2 (j_decompress_ptr cinfo)
  169386. {
  169387. per_scan_setup2(cinfo);
  169388. latch_quant_tables(cinfo);
  169389. (*cinfo->entropy->start_pass) (cinfo);
  169390. (*cinfo->coef->start_input_pass) (cinfo);
  169391. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  169392. }
  169393. /*
  169394. * Finish up after inputting a compressed-data scan.
  169395. * This is called by the coefficient controller after it's read all
  169396. * the expected data of the scan.
  169397. */
  169398. METHODDEF(void)
  169399. finish_input_pass (j_decompress_ptr cinfo)
  169400. {
  169401. cinfo->inputctl->consume_input = consume_markers;
  169402. }
  169403. /*
  169404. * Read JPEG markers before, between, or after compressed-data scans.
  169405. * Change state as necessary when a new scan is reached.
  169406. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  169407. *
  169408. * The consume_input method pointer points either here or to the
  169409. * coefficient controller's consume_data routine, depending on whether
  169410. * we are reading a compressed data segment or inter-segment markers.
  169411. */
  169412. METHODDEF(int)
  169413. consume_markers (j_decompress_ptr cinfo)
  169414. {
  169415. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  169416. int val;
  169417. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  169418. return JPEG_REACHED_EOI;
  169419. val = (*cinfo->marker->read_markers) (cinfo);
  169420. switch (val) {
  169421. case JPEG_REACHED_SOS: /* Found SOS */
  169422. if (inputctl->inheaders) { /* 1st SOS */
  169423. initial_setup2(cinfo);
  169424. inputctl->inheaders = FALSE;
  169425. /* Note: start_input_pass must be called by jdmaster.c
  169426. * before any more input can be consumed. jdapimin.c is
  169427. * responsible for enforcing this sequencing.
  169428. */
  169429. } else { /* 2nd or later SOS marker */
  169430. if (! inputctl->pub.has_multiple_scans)
  169431. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  169432. start_input_pass2(cinfo);
  169433. }
  169434. break;
  169435. case JPEG_REACHED_EOI: /* Found EOI */
  169436. inputctl->pub.eoi_reached = TRUE;
  169437. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  169438. if (cinfo->marker->saw_SOF)
  169439. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  169440. } else {
  169441. /* Prevent infinite loop in coef ctlr's decompress_data routine
  169442. * if user set output_scan_number larger than number of scans.
  169443. */
  169444. if (cinfo->output_scan_number > cinfo->input_scan_number)
  169445. cinfo->output_scan_number = cinfo->input_scan_number;
  169446. }
  169447. break;
  169448. case JPEG_SUSPENDED:
  169449. break;
  169450. }
  169451. return val;
  169452. }
  169453. /*
  169454. * Reset state to begin a fresh datastream.
  169455. */
  169456. METHODDEF(void)
  169457. reset_input_controller (j_decompress_ptr cinfo)
  169458. {
  169459. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  169460. inputctl->pub.consume_input = consume_markers;
  169461. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  169462. inputctl->pub.eoi_reached = FALSE;
  169463. inputctl->inheaders = TRUE;
  169464. /* Reset other modules */
  169465. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  169466. (*cinfo->marker->reset_marker_reader) (cinfo);
  169467. /* Reset progression state -- would be cleaner if entropy decoder did this */
  169468. cinfo->coef_bits = NULL;
  169469. }
  169470. /*
  169471. * Initialize the input controller module.
  169472. * This is called only once, when the decompression object is created.
  169473. */
  169474. GLOBAL(void)
  169475. jinit_input_controller (j_decompress_ptr cinfo)
  169476. {
  169477. my_inputctl_ptr inputctl;
  169478. /* Create subobject in permanent pool */
  169479. inputctl = (my_inputctl_ptr)
  169480. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  169481. SIZEOF(my_input_controller));
  169482. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  169483. /* Initialize method pointers */
  169484. inputctl->pub.consume_input = consume_markers;
  169485. inputctl->pub.reset_input_controller = reset_input_controller;
  169486. inputctl->pub.start_input_pass = start_input_pass2;
  169487. inputctl->pub.finish_input_pass = finish_input_pass;
  169488. /* Initialize state: can't use reset_input_controller since we don't
  169489. * want to try to reset other modules yet.
  169490. */
  169491. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  169492. inputctl->pub.eoi_reached = FALSE;
  169493. inputctl->inheaders = TRUE;
  169494. }
  169495. /*** End of inlined file: jdinput.c ***/
  169496. /*** Start of inlined file: jdmainct.c ***/
  169497. #define JPEG_INTERNALS
  169498. /*
  169499. * In the current system design, the main buffer need never be a full-image
  169500. * buffer; any full-height buffers will be found inside the coefficient or
  169501. * postprocessing controllers. Nonetheless, the main controller is not
  169502. * trivial. Its responsibility is to provide context rows for upsampling/
  169503. * rescaling, and doing this in an efficient fashion is a bit tricky.
  169504. *
  169505. * Postprocessor input data is counted in "row groups". A row group
  169506. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  169507. * sample rows of each component. (We require DCT_scaled_size values to be
  169508. * chosen such that these numbers are integers. In practice DCT_scaled_size
  169509. * values will likely be powers of two, so we actually have the stronger
  169510. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  169511. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  169512. * row group (times any additional scale factor that the upsampler is
  169513. * applying).
  169514. *
  169515. * The coefficient controller will deliver data to us one iMCU row at a time;
  169516. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  169517. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  169518. * to one row of MCUs when the image is fully interleaved.) Note that the
  169519. * number of sample rows varies across components, but the number of row
  169520. * groups does not. Some garbage sample rows may be included in the last iMCU
  169521. * row at the bottom of the image.
  169522. *
  169523. * Depending on the vertical scaling algorithm used, the upsampler may need
  169524. * access to the sample row(s) above and below its current input row group.
  169525. * The upsampler is required to set need_context_rows TRUE at global selection
  169526. * time if so. When need_context_rows is FALSE, this controller can simply
  169527. * obtain one iMCU row at a time from the coefficient controller and dole it
  169528. * out as row groups to the postprocessor.
  169529. *
  169530. * When need_context_rows is TRUE, this controller guarantees that the buffer
  169531. * passed to postprocessing contains at least one row group's worth of samples
  169532. * above and below the row group(s) being processed. Note that the context
  169533. * rows "above" the first passed row group appear at negative row offsets in
  169534. * the passed buffer. At the top and bottom of the image, the required
  169535. * context rows are manufactured by duplicating the first or last real sample
  169536. * row; this avoids having special cases in the upsampling inner loops.
  169537. *
  169538. * The amount of context is fixed at one row group just because that's a
  169539. * convenient number for this controller to work with. The existing
  169540. * upsamplers really only need one sample row of context. An upsampler
  169541. * supporting arbitrary output rescaling might wish for more than one row
  169542. * group of context when shrinking the image; tough, we don't handle that.
  169543. * (This is justified by the assumption that downsizing will be handled mostly
  169544. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  169545. * the upsample step needn't be much less than one.)
  169546. *
  169547. * To provide the desired context, we have to retain the last two row groups
  169548. * of one iMCU row while reading in the next iMCU row. (The last row group
  169549. * can't be processed until we have another row group for its below-context,
  169550. * and so we have to save the next-to-last group too for its above-context.)
  169551. * We could do this most simply by copying data around in our buffer, but
  169552. * that'd be very slow. We can avoid copying any data by creating a rather
  169553. * strange pointer structure. Here's how it works. We allocate a workspace
  169554. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  169555. * of row groups per iMCU row). We create two sets of redundant pointers to
  169556. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  169557. * pointer lists look like this:
  169558. * M+1 M-1
  169559. * master pointer --> 0 master pointer --> 0
  169560. * 1 1
  169561. * ... ...
  169562. * M-3 M-3
  169563. * M-2 M
  169564. * M-1 M+1
  169565. * M M-2
  169566. * M+1 M-1
  169567. * 0 0
  169568. * We read alternate iMCU rows using each master pointer; thus the last two
  169569. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  169570. * The pointer lists are set up so that the required context rows appear to
  169571. * be adjacent to the proper places when we pass the pointer lists to the
  169572. * upsampler.
  169573. *
  169574. * The above pictures describe the normal state of the pointer lists.
  169575. * At top and bottom of the image, we diddle the pointer lists to duplicate
  169576. * the first or last sample row as necessary (this is cheaper than copying
  169577. * sample rows around).
  169578. *
  169579. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  169580. * situation each iMCU row provides only one row group so the buffering logic
  169581. * must be different (eg, we must read two iMCU rows before we can emit the
  169582. * first row group). For now, we simply do not support providing context
  169583. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  169584. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  169585. * want it quick and dirty, so a context-free upsampler is sufficient.
  169586. */
  169587. /* Private buffer controller object */
  169588. typedef struct {
  169589. struct jpeg_d_main_controller pub; /* public fields */
  169590. /* Pointer to allocated workspace (M or M+2 row groups). */
  169591. JSAMPARRAY buffer[MAX_COMPONENTS];
  169592. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  169593. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  169594. /* Remaining fields are only used in the context case. */
  169595. /* These are the master pointers to the funny-order pointer lists. */
  169596. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  169597. int whichptr; /* indicates which pointer set is now in use */
  169598. int context_state; /* process_data state machine status */
  169599. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  169600. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  169601. } my_main_controller4;
  169602. typedef my_main_controller4 * my_main_ptr4;
  169603. /* context_state values: */
  169604. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  169605. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  169606. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  169607. /* Forward declarations */
  169608. METHODDEF(void) process_data_simple_main2
  169609. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169610. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169611. METHODDEF(void) process_data_context_main
  169612. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169613. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169614. #ifdef QUANT_2PASS_SUPPORTED
  169615. METHODDEF(void) process_data_crank_post
  169616. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169617. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169618. #endif
  169619. LOCAL(void)
  169620. alloc_funny_pointers (j_decompress_ptr cinfo)
  169621. /* Allocate space for the funny pointer lists.
  169622. * This is done only once, not once per pass.
  169623. */
  169624. {
  169625. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169626. int ci, rgroup;
  169627. int M = cinfo->min_DCT_scaled_size;
  169628. jpeg_component_info *compptr;
  169629. JSAMPARRAY xbuf;
  169630. /* Get top-level space for component array pointers.
  169631. * We alloc both arrays with one call to save a few cycles.
  169632. */
  169633. main_->xbuffer[0] = (JSAMPIMAGE)
  169634. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169635. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  169636. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  169637. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169638. ci++, compptr++) {
  169639. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169640. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169641. /* Get space for pointer lists --- M+4 row groups in each list.
  169642. * We alloc both pointer lists with one call to save a few cycles.
  169643. */
  169644. xbuf = (JSAMPARRAY)
  169645. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169646. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  169647. xbuf += rgroup; /* want one row group at negative offsets */
  169648. main_->xbuffer[0][ci] = xbuf;
  169649. xbuf += rgroup * (M + 4);
  169650. main_->xbuffer[1][ci] = xbuf;
  169651. }
  169652. }
  169653. LOCAL(void)
  169654. make_funny_pointers (j_decompress_ptr cinfo)
  169655. /* Create the funny pointer lists discussed in the comments above.
  169656. * The actual workspace is already allocated (in main->buffer),
  169657. * and the space for the pointer lists is allocated too.
  169658. * This routine just fills in the curiously ordered lists.
  169659. * This will be repeated at the beginning of each pass.
  169660. */
  169661. {
  169662. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169663. int ci, i, rgroup;
  169664. int M = cinfo->min_DCT_scaled_size;
  169665. jpeg_component_info *compptr;
  169666. JSAMPARRAY buf, xbuf0, xbuf1;
  169667. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169668. ci++, compptr++) {
  169669. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169670. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169671. xbuf0 = main_->xbuffer[0][ci];
  169672. xbuf1 = main_->xbuffer[1][ci];
  169673. /* First copy the workspace pointers as-is */
  169674. buf = main_->buffer[ci];
  169675. for (i = 0; i < rgroup * (M + 2); i++) {
  169676. xbuf0[i] = xbuf1[i] = buf[i];
  169677. }
  169678. /* In the second list, put the last four row groups in swapped order */
  169679. for (i = 0; i < rgroup * 2; i++) {
  169680. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  169681. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  169682. }
  169683. /* The wraparound pointers at top and bottom will be filled later
  169684. * (see set_wraparound_pointers, below). Initially we want the "above"
  169685. * pointers to duplicate the first actual data line. This only needs
  169686. * to happen in xbuffer[0].
  169687. */
  169688. for (i = 0; i < rgroup; i++) {
  169689. xbuf0[i - rgroup] = xbuf0[0];
  169690. }
  169691. }
  169692. }
  169693. LOCAL(void)
  169694. set_wraparound_pointers (j_decompress_ptr cinfo)
  169695. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  169696. * This changes the pointer list state from top-of-image to the normal state.
  169697. */
  169698. {
  169699. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169700. int ci, i, rgroup;
  169701. int M = cinfo->min_DCT_scaled_size;
  169702. jpeg_component_info *compptr;
  169703. JSAMPARRAY xbuf0, xbuf1;
  169704. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169705. ci++, compptr++) {
  169706. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169707. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169708. xbuf0 = main_->xbuffer[0][ci];
  169709. xbuf1 = main_->xbuffer[1][ci];
  169710. for (i = 0; i < rgroup; i++) {
  169711. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  169712. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  169713. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  169714. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  169715. }
  169716. }
  169717. }
  169718. LOCAL(void)
  169719. set_bottom_pointers (j_decompress_ptr cinfo)
  169720. /* Change the pointer lists to duplicate the last sample row at the bottom
  169721. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  169722. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  169723. */
  169724. {
  169725. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169726. int ci, i, rgroup, iMCUheight, rows_left;
  169727. jpeg_component_info *compptr;
  169728. JSAMPARRAY xbuf;
  169729. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169730. ci++, compptr++) {
  169731. /* Count sample rows in one iMCU row and in one row group */
  169732. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  169733. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  169734. /* Count nondummy sample rows remaining for this component */
  169735. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  169736. if (rows_left == 0) rows_left = iMCUheight;
  169737. /* Count nondummy row groups. Should get same answer for each component,
  169738. * so we need only do it once.
  169739. */
  169740. if (ci == 0) {
  169741. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  169742. }
  169743. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  169744. * last partial rowgroup and ensures at least one full rowgroup of context.
  169745. */
  169746. xbuf = main_->xbuffer[main_->whichptr][ci];
  169747. for (i = 0; i < rgroup * 2; i++) {
  169748. xbuf[rows_left + i] = xbuf[rows_left-1];
  169749. }
  169750. }
  169751. }
  169752. /*
  169753. * Initialize for a processing pass.
  169754. */
  169755. METHODDEF(void)
  169756. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  169757. {
  169758. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169759. switch (pass_mode) {
  169760. case JBUF_PASS_THRU:
  169761. if (cinfo->upsample->need_context_rows) {
  169762. main_->pub.process_data = process_data_context_main;
  169763. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  169764. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  169765. main_->context_state = CTX_PREPARE_FOR_IMCU;
  169766. main_->iMCU_row_ctr = 0;
  169767. } else {
  169768. /* Simple case with no context needed */
  169769. main_->pub.process_data = process_data_simple_main2;
  169770. }
  169771. main_->buffer_full = FALSE; /* Mark buffer empty */
  169772. main_->rowgroup_ctr = 0;
  169773. break;
  169774. #ifdef QUANT_2PASS_SUPPORTED
  169775. case JBUF_CRANK_DEST:
  169776. /* For last pass of 2-pass quantization, just crank the postprocessor */
  169777. main_->pub.process_data = process_data_crank_post;
  169778. break;
  169779. #endif
  169780. default:
  169781. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169782. break;
  169783. }
  169784. }
  169785. /*
  169786. * Process some data.
  169787. * This handles the simple case where no context is required.
  169788. */
  169789. METHODDEF(void)
  169790. process_data_simple_main2 (j_decompress_ptr cinfo,
  169791. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169792. JDIMENSION out_rows_avail)
  169793. {
  169794. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169795. JDIMENSION rowgroups_avail;
  169796. /* Read input data if we haven't filled the main buffer yet */
  169797. if (! main_->buffer_full) {
  169798. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  169799. return; /* suspension forced, can do nothing more */
  169800. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  169801. }
  169802. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  169803. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  169804. /* Note: at the bottom of the image, we may pass extra garbage row groups
  169805. * to the postprocessor. The postprocessor has to check for bottom
  169806. * of image anyway (at row resolution), so no point in us doing it too.
  169807. */
  169808. /* Feed the postprocessor */
  169809. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  169810. &main_->rowgroup_ctr, rowgroups_avail,
  169811. output_buf, out_row_ctr, out_rows_avail);
  169812. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  169813. if (main_->rowgroup_ctr >= rowgroups_avail) {
  169814. main_->buffer_full = FALSE;
  169815. main_->rowgroup_ctr = 0;
  169816. }
  169817. }
  169818. /*
  169819. * Process some data.
  169820. * This handles the case where context rows must be provided.
  169821. */
  169822. METHODDEF(void)
  169823. process_data_context_main (j_decompress_ptr cinfo,
  169824. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169825. JDIMENSION out_rows_avail)
  169826. {
  169827. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169828. /* Read input data if we haven't filled the main buffer yet */
  169829. if (! main_->buffer_full) {
  169830. if (! (*cinfo->coef->decompress_data) (cinfo,
  169831. main_->xbuffer[main_->whichptr]))
  169832. return; /* suspension forced, can do nothing more */
  169833. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  169834. main_->iMCU_row_ctr++; /* count rows received */
  169835. }
  169836. /* Postprocessor typically will not swallow all the input data it is handed
  169837. * in one call (due to filling the output buffer first). Must be prepared
  169838. * to exit and restart. This switch lets us keep track of how far we got.
  169839. * Note that each case falls through to the next on successful completion.
  169840. */
  169841. switch (main_->context_state) {
  169842. case CTX_POSTPONED_ROW:
  169843. /* Call postprocessor using previously set pointers for postponed row */
  169844. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  169845. &main_->rowgroup_ctr, main_->rowgroups_avail,
  169846. output_buf, out_row_ctr, out_rows_avail);
  169847. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  169848. return; /* Need to suspend */
  169849. main_->context_state = CTX_PREPARE_FOR_IMCU;
  169850. if (*out_row_ctr >= out_rows_avail)
  169851. return; /* Postprocessor exactly filled output buf */
  169852. /*FALLTHROUGH*/
  169853. case CTX_PREPARE_FOR_IMCU:
  169854. /* Prepare to process first M-1 row groups of this iMCU row */
  169855. main_->rowgroup_ctr = 0;
  169856. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  169857. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  169858. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  169859. */
  169860. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  169861. set_bottom_pointers(cinfo);
  169862. main_->context_state = CTX_PROCESS_IMCU;
  169863. /*FALLTHROUGH*/
  169864. case CTX_PROCESS_IMCU:
  169865. /* Call postprocessor using previously set pointers */
  169866. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  169867. &main_->rowgroup_ctr, main_->rowgroups_avail,
  169868. output_buf, out_row_ctr, out_rows_avail);
  169869. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  169870. return; /* Need to suspend */
  169871. /* After the first iMCU, change wraparound pointers to normal state */
  169872. if (main_->iMCU_row_ctr == 1)
  169873. set_wraparound_pointers(cinfo);
  169874. /* Prepare to load new iMCU row using other xbuffer list */
  169875. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  169876. main_->buffer_full = FALSE;
  169877. /* Still need to process last row group of this iMCU row, */
  169878. /* which is saved at index M+1 of the other xbuffer */
  169879. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  169880. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  169881. main_->context_state = CTX_POSTPONED_ROW;
  169882. }
  169883. }
  169884. /*
  169885. * Process some data.
  169886. * Final pass of two-pass quantization: just call the postprocessor.
  169887. * Source data will be the postprocessor controller's internal buffer.
  169888. */
  169889. #ifdef QUANT_2PASS_SUPPORTED
  169890. METHODDEF(void)
  169891. process_data_crank_post (j_decompress_ptr cinfo,
  169892. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169893. JDIMENSION out_rows_avail)
  169894. {
  169895. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  169896. (JDIMENSION *) NULL, (JDIMENSION) 0,
  169897. output_buf, out_row_ctr, out_rows_avail);
  169898. }
  169899. #endif /* QUANT_2PASS_SUPPORTED */
  169900. /*
  169901. * Initialize main buffer controller.
  169902. */
  169903. GLOBAL(void)
  169904. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169905. {
  169906. my_main_ptr4 main_;
  169907. int ci, rgroup, ngroups;
  169908. jpeg_component_info *compptr;
  169909. main_ = (my_main_ptr4)
  169910. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169911. SIZEOF(my_main_controller4));
  169912. cinfo->main = (struct jpeg_d_main_controller *) main_;
  169913. main_->pub.start_pass = start_pass_main2;
  169914. if (need_full_buffer) /* shouldn't happen */
  169915. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169916. /* Allocate the workspace.
  169917. * ngroups is the number of row groups we need.
  169918. */
  169919. if (cinfo->upsample->need_context_rows) {
  169920. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  169921. ERREXIT(cinfo, JERR_NOTIMPL);
  169922. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  169923. ngroups = cinfo->min_DCT_scaled_size + 2;
  169924. } else {
  169925. ngroups = cinfo->min_DCT_scaled_size;
  169926. }
  169927. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169928. ci++, compptr++) {
  169929. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169930. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169931. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  169932. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169933. compptr->width_in_blocks * compptr->DCT_scaled_size,
  169934. (JDIMENSION) (rgroup * ngroups));
  169935. }
  169936. }
  169937. /*** End of inlined file: jdmainct.c ***/
  169938. /*** Start of inlined file: jdmarker.c ***/
  169939. #define JPEG_INTERNALS
  169940. /* Private state */
  169941. typedef struct {
  169942. struct jpeg_marker_reader pub; /* public fields */
  169943. /* Application-overridable marker processing methods */
  169944. jpeg_marker_parser_method process_COM;
  169945. jpeg_marker_parser_method process_APPn[16];
  169946. /* Limit on marker data length to save for each marker type */
  169947. unsigned int length_limit_COM;
  169948. unsigned int length_limit_APPn[16];
  169949. /* Status of COM/APPn marker saving */
  169950. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  169951. unsigned int bytes_read; /* data bytes read so far in marker */
  169952. /* Note: cur_marker is not linked into marker_list until it's all read. */
  169953. } my_marker_reader;
  169954. typedef my_marker_reader * my_marker_ptr2;
  169955. /*
  169956. * Macros for fetching data from the data source module.
  169957. *
  169958. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  169959. * the current restart point; we update them only when we have reached a
  169960. * suitable place to restart if a suspension occurs.
  169961. */
  169962. /* Declare and initialize local copies of input pointer/count */
  169963. #define INPUT_VARS(cinfo) \
  169964. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  169965. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  169966. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  169967. /* Unload the local copies --- do this only at a restart boundary */
  169968. #define INPUT_SYNC(cinfo) \
  169969. ( datasrc->next_input_byte = next_input_byte, \
  169970. datasrc->bytes_in_buffer = bytes_in_buffer )
  169971. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  169972. #define INPUT_RELOAD(cinfo) \
  169973. ( next_input_byte = datasrc->next_input_byte, \
  169974. bytes_in_buffer = datasrc->bytes_in_buffer )
  169975. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  169976. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  169977. * but we must reload the local copies after a successful fill.
  169978. */
  169979. #define MAKE_BYTE_AVAIL(cinfo,action) \
  169980. if (bytes_in_buffer == 0) { \
  169981. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  169982. { action; } \
  169983. INPUT_RELOAD(cinfo); \
  169984. }
  169985. /* Read a byte into variable V.
  169986. * If must suspend, take the specified action (typically "return FALSE").
  169987. */
  169988. #define INPUT_BYTE(cinfo,V,action) \
  169989. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  169990. bytes_in_buffer--; \
  169991. V = GETJOCTET(*next_input_byte++); )
  169992. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  169993. * V should be declared unsigned int or perhaps INT32.
  169994. */
  169995. #define INPUT_2BYTES(cinfo,V,action) \
  169996. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  169997. bytes_in_buffer--; \
  169998. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  169999. MAKE_BYTE_AVAIL(cinfo,action); \
  170000. bytes_in_buffer--; \
  170001. V += GETJOCTET(*next_input_byte++); )
  170002. /*
  170003. * Routines to process JPEG markers.
  170004. *
  170005. * Entry condition: JPEG marker itself has been read and its code saved
  170006. * in cinfo->unread_marker; input restart point is just after the marker.
  170007. *
  170008. * Exit: if return TRUE, have read and processed any parameters, and have
  170009. * updated the restart point to point after the parameters.
  170010. * If return FALSE, was forced to suspend before reaching end of
  170011. * marker parameters; restart point has not been moved. Same routine
  170012. * will be called again after application supplies more input data.
  170013. *
  170014. * This approach to suspension assumes that all of a marker's parameters
  170015. * can fit into a single input bufferload. This should hold for "normal"
  170016. * markers. Some COM/APPn markers might have large parameter segments
  170017. * that might not fit. If we are simply dropping such a marker, we use
  170018. * skip_input_data to get past it, and thereby put the problem on the
  170019. * source manager's shoulders. If we are saving the marker's contents
  170020. * into memory, we use a slightly different convention: when forced to
  170021. * suspend, the marker processor updates the restart point to the end of
  170022. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170023. * On resumption, cinfo->unread_marker still contains the marker code,
  170024. * but the data source will point to the next chunk of marker data.
  170025. * The marker processor must retain internal state to deal with this.
  170026. *
  170027. * Note that we don't bother to avoid duplicate trace messages if a
  170028. * suspension occurs within marker parameters. Other side effects
  170029. * require more care.
  170030. */
  170031. LOCAL(boolean)
  170032. get_soi (j_decompress_ptr cinfo)
  170033. /* Process an SOI marker */
  170034. {
  170035. int i;
  170036. TRACEMS(cinfo, 1, JTRC_SOI);
  170037. if (cinfo->marker->saw_SOI)
  170038. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170039. /* Reset all parameters that are defined to be reset by SOI */
  170040. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170041. cinfo->arith_dc_L[i] = 0;
  170042. cinfo->arith_dc_U[i] = 1;
  170043. cinfo->arith_ac_K[i] = 5;
  170044. }
  170045. cinfo->restart_interval = 0;
  170046. /* Set initial assumptions for colorspace etc */
  170047. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170048. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170049. cinfo->saw_JFIF_marker = FALSE;
  170050. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170051. cinfo->JFIF_minor_version = 1;
  170052. cinfo->density_unit = 0;
  170053. cinfo->X_density = 1;
  170054. cinfo->Y_density = 1;
  170055. cinfo->saw_Adobe_marker = FALSE;
  170056. cinfo->Adobe_transform = 0;
  170057. cinfo->marker->saw_SOI = TRUE;
  170058. return TRUE;
  170059. }
  170060. LOCAL(boolean)
  170061. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170062. /* Process a SOFn marker */
  170063. {
  170064. INT32 length;
  170065. int c, ci;
  170066. jpeg_component_info * compptr;
  170067. INPUT_VARS(cinfo);
  170068. cinfo->progressive_mode = is_prog;
  170069. cinfo->arith_code = is_arith;
  170070. INPUT_2BYTES(cinfo, length, return FALSE);
  170071. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170072. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170073. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170074. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170075. length -= 8;
  170076. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170077. (int) cinfo->image_width, (int) cinfo->image_height,
  170078. cinfo->num_components);
  170079. if (cinfo->marker->saw_SOF)
  170080. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170081. /* We don't support files in which the image height is initially specified */
  170082. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170083. /* might as well have a general sanity check. */
  170084. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170085. || cinfo->num_components <= 0)
  170086. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170087. if (length != (cinfo->num_components * 3))
  170088. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170089. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170090. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170091. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170092. cinfo->num_components * SIZEOF(jpeg_component_info));
  170093. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170094. ci++, compptr++) {
  170095. compptr->component_index = ci;
  170096. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170097. INPUT_BYTE(cinfo, c, return FALSE);
  170098. compptr->h_samp_factor = (c >> 4) & 15;
  170099. compptr->v_samp_factor = (c ) & 15;
  170100. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170101. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170102. compptr->component_id, compptr->h_samp_factor,
  170103. compptr->v_samp_factor, compptr->quant_tbl_no);
  170104. }
  170105. cinfo->marker->saw_SOF = TRUE;
  170106. INPUT_SYNC(cinfo);
  170107. return TRUE;
  170108. }
  170109. LOCAL(boolean)
  170110. get_sos (j_decompress_ptr cinfo)
  170111. /* Process a SOS marker */
  170112. {
  170113. INT32 length;
  170114. int i, ci, n, c, cc;
  170115. jpeg_component_info * compptr;
  170116. INPUT_VARS(cinfo);
  170117. if (! cinfo->marker->saw_SOF)
  170118. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170119. INPUT_2BYTES(cinfo, length, return FALSE);
  170120. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170121. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170122. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170123. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170124. cinfo->comps_in_scan = n;
  170125. /* Collect the component-spec parameters */
  170126. for (i = 0; i < n; i++) {
  170127. INPUT_BYTE(cinfo, cc, return FALSE);
  170128. INPUT_BYTE(cinfo, c, return FALSE);
  170129. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170130. ci++, compptr++) {
  170131. if (cc == compptr->component_id)
  170132. goto id_found;
  170133. }
  170134. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  170135. id_found:
  170136. cinfo->cur_comp_info[i] = compptr;
  170137. compptr->dc_tbl_no = (c >> 4) & 15;
  170138. compptr->ac_tbl_no = (c ) & 15;
  170139. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  170140. compptr->dc_tbl_no, compptr->ac_tbl_no);
  170141. }
  170142. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  170143. INPUT_BYTE(cinfo, c, return FALSE);
  170144. cinfo->Ss = c;
  170145. INPUT_BYTE(cinfo, c, return FALSE);
  170146. cinfo->Se = c;
  170147. INPUT_BYTE(cinfo, c, return FALSE);
  170148. cinfo->Ah = (c >> 4) & 15;
  170149. cinfo->Al = (c ) & 15;
  170150. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  170151. cinfo->Ah, cinfo->Al);
  170152. /* Prepare to scan data & restart markers */
  170153. cinfo->marker->next_restart_num = 0;
  170154. /* Count another SOS marker */
  170155. cinfo->input_scan_number++;
  170156. INPUT_SYNC(cinfo);
  170157. return TRUE;
  170158. }
  170159. #ifdef D_ARITH_CODING_SUPPORTED
  170160. LOCAL(boolean)
  170161. get_dac (j_decompress_ptr cinfo)
  170162. /* Process a DAC marker */
  170163. {
  170164. INT32 length;
  170165. int index, val;
  170166. INPUT_VARS(cinfo);
  170167. INPUT_2BYTES(cinfo, length, return FALSE);
  170168. length -= 2;
  170169. while (length > 0) {
  170170. INPUT_BYTE(cinfo, index, return FALSE);
  170171. INPUT_BYTE(cinfo, val, return FALSE);
  170172. length -= 2;
  170173. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  170174. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  170175. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  170176. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  170177. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  170178. } else { /* define DC table */
  170179. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  170180. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  170181. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  170182. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  170183. }
  170184. }
  170185. if (length != 0)
  170186. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170187. INPUT_SYNC(cinfo);
  170188. return TRUE;
  170189. }
  170190. #else /* ! D_ARITH_CODING_SUPPORTED */
  170191. #define get_dac(cinfo) skip_variable(cinfo)
  170192. #endif /* D_ARITH_CODING_SUPPORTED */
  170193. LOCAL(boolean)
  170194. get_dht (j_decompress_ptr cinfo)
  170195. /* Process a DHT marker */
  170196. {
  170197. INT32 length;
  170198. UINT8 bits[17];
  170199. UINT8 huffval[256];
  170200. int i, index, count;
  170201. JHUFF_TBL **htblptr;
  170202. INPUT_VARS(cinfo);
  170203. INPUT_2BYTES(cinfo, length, return FALSE);
  170204. length -= 2;
  170205. while (length > 16) {
  170206. INPUT_BYTE(cinfo, index, return FALSE);
  170207. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  170208. bits[0] = 0;
  170209. count = 0;
  170210. for (i = 1; i <= 16; i++) {
  170211. INPUT_BYTE(cinfo, bits[i], return FALSE);
  170212. count += bits[i];
  170213. }
  170214. length -= 1 + 16;
  170215. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170216. bits[1], bits[2], bits[3], bits[4],
  170217. bits[5], bits[6], bits[7], bits[8]);
  170218. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170219. bits[9], bits[10], bits[11], bits[12],
  170220. bits[13], bits[14], bits[15], bits[16]);
  170221. /* Here we just do minimal validation of the counts to avoid walking
  170222. * off the end of our table space. jdhuff.c will check more carefully.
  170223. */
  170224. if (count > 256 || ((INT32) count) > length)
  170225. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170226. for (i = 0; i < count; i++)
  170227. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  170228. length -= count;
  170229. if (index & 0x10) { /* AC table definition */
  170230. index -= 0x10;
  170231. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  170232. } else { /* DC table definition */
  170233. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  170234. }
  170235. if (index < 0 || index >= NUM_HUFF_TBLS)
  170236. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  170237. if (*htblptr == NULL)
  170238. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  170239. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  170240. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  170241. }
  170242. if (length != 0)
  170243. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170244. INPUT_SYNC(cinfo);
  170245. return TRUE;
  170246. }
  170247. LOCAL(boolean)
  170248. get_dqt (j_decompress_ptr cinfo)
  170249. /* Process a DQT marker */
  170250. {
  170251. INT32 length;
  170252. int n, i, prec;
  170253. unsigned int tmp;
  170254. JQUANT_TBL *quant_ptr;
  170255. INPUT_VARS(cinfo);
  170256. INPUT_2BYTES(cinfo, length, return FALSE);
  170257. length -= 2;
  170258. while (length > 0) {
  170259. INPUT_BYTE(cinfo, n, return FALSE);
  170260. prec = n >> 4;
  170261. n &= 0x0F;
  170262. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  170263. if (n >= NUM_QUANT_TBLS)
  170264. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  170265. if (cinfo->quant_tbl_ptrs[n] == NULL)
  170266. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  170267. quant_ptr = cinfo->quant_tbl_ptrs[n];
  170268. for (i = 0; i < DCTSIZE2; i++) {
  170269. if (prec)
  170270. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170271. else
  170272. INPUT_BYTE(cinfo, tmp, return FALSE);
  170273. /* We convert the zigzag-order table to natural array order. */
  170274. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  170275. }
  170276. if (cinfo->err->trace_level >= 2) {
  170277. for (i = 0; i < DCTSIZE2; i += 8) {
  170278. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  170279. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  170280. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  170281. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  170282. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  170283. }
  170284. }
  170285. length -= DCTSIZE2+1;
  170286. if (prec) length -= DCTSIZE2;
  170287. }
  170288. if (length != 0)
  170289. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170290. INPUT_SYNC(cinfo);
  170291. return TRUE;
  170292. }
  170293. LOCAL(boolean)
  170294. get_dri (j_decompress_ptr cinfo)
  170295. /* Process a DRI marker */
  170296. {
  170297. INT32 length;
  170298. unsigned int tmp;
  170299. INPUT_VARS(cinfo);
  170300. INPUT_2BYTES(cinfo, length, return FALSE);
  170301. if (length != 4)
  170302. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170303. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170304. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  170305. cinfo->restart_interval = tmp;
  170306. INPUT_SYNC(cinfo);
  170307. return TRUE;
  170308. }
  170309. /*
  170310. * Routines for processing APPn and COM markers.
  170311. * These are either saved in memory or discarded, per application request.
  170312. * APP0 and APP14 are specially checked to see if they are
  170313. * JFIF and Adobe markers, respectively.
  170314. */
  170315. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  170316. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  170317. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  170318. LOCAL(void)
  170319. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170320. unsigned int datalen, INT32 remaining)
  170321. /* Examine first few bytes from an APP0.
  170322. * Take appropriate action if it is a JFIF marker.
  170323. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170324. */
  170325. {
  170326. INT32 totallen = (INT32) datalen + remaining;
  170327. if (datalen >= APP0_DATA_LEN &&
  170328. GETJOCTET(data[0]) == 0x4A &&
  170329. GETJOCTET(data[1]) == 0x46 &&
  170330. GETJOCTET(data[2]) == 0x49 &&
  170331. GETJOCTET(data[3]) == 0x46 &&
  170332. GETJOCTET(data[4]) == 0) {
  170333. /* Found JFIF APP0 marker: save info */
  170334. cinfo->saw_JFIF_marker = TRUE;
  170335. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  170336. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  170337. cinfo->density_unit = GETJOCTET(data[7]);
  170338. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  170339. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  170340. /* Check version.
  170341. * Major version must be 1, anything else signals an incompatible change.
  170342. * (We used to treat this as an error, but now it's a nonfatal warning,
  170343. * because some bozo at Hijaak couldn't read the spec.)
  170344. * Minor version should be 0..2, but process anyway if newer.
  170345. */
  170346. if (cinfo->JFIF_major_version != 1)
  170347. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  170348. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  170349. /* Generate trace messages */
  170350. TRACEMS5(cinfo, 1, JTRC_JFIF,
  170351. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  170352. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  170353. /* Validate thumbnail dimensions and issue appropriate messages */
  170354. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  170355. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  170356. GETJOCTET(data[12]), GETJOCTET(data[13]));
  170357. totallen -= APP0_DATA_LEN;
  170358. if (totallen !=
  170359. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  170360. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  170361. } else if (datalen >= 6 &&
  170362. GETJOCTET(data[0]) == 0x4A &&
  170363. GETJOCTET(data[1]) == 0x46 &&
  170364. GETJOCTET(data[2]) == 0x58 &&
  170365. GETJOCTET(data[3]) == 0x58 &&
  170366. GETJOCTET(data[4]) == 0) {
  170367. /* Found JFIF "JFXX" extension APP0 marker */
  170368. /* The library doesn't actually do anything with these,
  170369. * but we try to produce a helpful trace message.
  170370. */
  170371. switch (GETJOCTET(data[5])) {
  170372. case 0x10:
  170373. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  170374. break;
  170375. case 0x11:
  170376. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  170377. break;
  170378. case 0x13:
  170379. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  170380. break;
  170381. default:
  170382. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  170383. GETJOCTET(data[5]), (int) totallen);
  170384. break;
  170385. }
  170386. } else {
  170387. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  170388. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  170389. }
  170390. }
  170391. LOCAL(void)
  170392. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170393. unsigned int datalen, INT32 remaining)
  170394. /* Examine first few bytes from an APP14.
  170395. * Take appropriate action if it is an Adobe marker.
  170396. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170397. */
  170398. {
  170399. unsigned int version, flags0, flags1, transform;
  170400. if (datalen >= APP14_DATA_LEN &&
  170401. GETJOCTET(data[0]) == 0x41 &&
  170402. GETJOCTET(data[1]) == 0x64 &&
  170403. GETJOCTET(data[2]) == 0x6F &&
  170404. GETJOCTET(data[3]) == 0x62 &&
  170405. GETJOCTET(data[4]) == 0x65) {
  170406. /* Found Adobe APP14 marker */
  170407. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  170408. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  170409. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  170410. transform = GETJOCTET(data[11]);
  170411. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  170412. cinfo->saw_Adobe_marker = TRUE;
  170413. cinfo->Adobe_transform = (UINT8) transform;
  170414. } else {
  170415. /* Start of APP14 does not match "Adobe", or too short */
  170416. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  170417. }
  170418. }
  170419. METHODDEF(boolean)
  170420. get_interesting_appn (j_decompress_ptr cinfo)
  170421. /* Process an APP0 or APP14 marker without saving it */
  170422. {
  170423. INT32 length;
  170424. JOCTET b[APPN_DATA_LEN];
  170425. unsigned int i, numtoread;
  170426. INPUT_VARS(cinfo);
  170427. INPUT_2BYTES(cinfo, length, return FALSE);
  170428. length -= 2;
  170429. /* get the interesting part of the marker data */
  170430. if (length >= APPN_DATA_LEN)
  170431. numtoread = APPN_DATA_LEN;
  170432. else if (length > 0)
  170433. numtoread = (unsigned int) length;
  170434. else
  170435. numtoread = 0;
  170436. for (i = 0; i < numtoread; i++)
  170437. INPUT_BYTE(cinfo, b[i], return FALSE);
  170438. length -= numtoread;
  170439. /* process it */
  170440. switch (cinfo->unread_marker) {
  170441. case M_APP0:
  170442. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  170443. break;
  170444. case M_APP14:
  170445. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  170446. break;
  170447. default:
  170448. /* can't get here unless jpeg_save_markers chooses wrong processor */
  170449. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  170450. break;
  170451. }
  170452. /* skip any remaining data -- could be lots */
  170453. INPUT_SYNC(cinfo);
  170454. if (length > 0)
  170455. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170456. return TRUE;
  170457. }
  170458. #ifdef SAVE_MARKERS_SUPPORTED
  170459. METHODDEF(boolean)
  170460. save_marker (j_decompress_ptr cinfo)
  170461. /* Save an APPn or COM marker into the marker list */
  170462. {
  170463. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  170464. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  170465. unsigned int bytes_read, data_length;
  170466. JOCTET FAR * data;
  170467. INT32 length = 0;
  170468. INPUT_VARS(cinfo);
  170469. if (cur_marker == NULL) {
  170470. /* begin reading a marker */
  170471. INPUT_2BYTES(cinfo, length, return FALSE);
  170472. length -= 2;
  170473. if (length >= 0) { /* watch out for bogus length word */
  170474. /* figure out how much we want to save */
  170475. unsigned int limit;
  170476. if (cinfo->unread_marker == (int) M_COM)
  170477. limit = marker->length_limit_COM;
  170478. else
  170479. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  170480. if ((unsigned int) length < limit)
  170481. limit = (unsigned int) length;
  170482. /* allocate and initialize the marker item */
  170483. cur_marker = (jpeg_saved_marker_ptr)
  170484. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170485. SIZEOF(struct jpeg_marker_struct) + limit);
  170486. cur_marker->next = NULL;
  170487. cur_marker->marker = (UINT8) cinfo->unread_marker;
  170488. cur_marker->original_length = (unsigned int) length;
  170489. cur_marker->data_length = limit;
  170490. /* data area is just beyond the jpeg_marker_struct */
  170491. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  170492. marker->cur_marker = cur_marker;
  170493. marker->bytes_read = 0;
  170494. bytes_read = 0;
  170495. data_length = limit;
  170496. } else {
  170497. /* deal with bogus length word */
  170498. bytes_read = data_length = 0;
  170499. data = NULL;
  170500. }
  170501. } else {
  170502. /* resume reading a marker */
  170503. bytes_read = marker->bytes_read;
  170504. data_length = cur_marker->data_length;
  170505. data = cur_marker->data + bytes_read;
  170506. }
  170507. while (bytes_read < data_length) {
  170508. INPUT_SYNC(cinfo); /* move the restart point to here */
  170509. marker->bytes_read = bytes_read;
  170510. /* If there's not at least one byte in buffer, suspend */
  170511. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  170512. /* Copy bytes with reasonable rapidity */
  170513. while (bytes_read < data_length && bytes_in_buffer > 0) {
  170514. *data++ = *next_input_byte++;
  170515. bytes_in_buffer--;
  170516. bytes_read++;
  170517. }
  170518. }
  170519. /* Done reading what we want to read */
  170520. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  170521. /* Add new marker to end of list */
  170522. if (cinfo->marker_list == NULL) {
  170523. cinfo->marker_list = cur_marker;
  170524. } else {
  170525. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  170526. while (prev->next != NULL)
  170527. prev = prev->next;
  170528. prev->next = cur_marker;
  170529. }
  170530. /* Reset pointer & calc remaining data length */
  170531. data = cur_marker->data;
  170532. length = cur_marker->original_length - data_length;
  170533. }
  170534. /* Reset to initial state for next marker */
  170535. marker->cur_marker = NULL;
  170536. /* Process the marker if interesting; else just make a generic trace msg */
  170537. switch (cinfo->unread_marker) {
  170538. case M_APP0:
  170539. examine_app0(cinfo, data, data_length, length);
  170540. break;
  170541. case M_APP14:
  170542. examine_app14(cinfo, data, data_length, length);
  170543. break;
  170544. default:
  170545. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  170546. (int) (data_length + length));
  170547. break;
  170548. }
  170549. /* skip any remaining data -- could be lots */
  170550. INPUT_SYNC(cinfo); /* do before skip_input_data */
  170551. if (length > 0)
  170552. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170553. return TRUE;
  170554. }
  170555. #endif /* SAVE_MARKERS_SUPPORTED */
  170556. METHODDEF(boolean)
  170557. skip_variable (j_decompress_ptr cinfo)
  170558. /* Skip over an unknown or uninteresting variable-length marker */
  170559. {
  170560. INT32 length;
  170561. INPUT_VARS(cinfo);
  170562. INPUT_2BYTES(cinfo, length, return FALSE);
  170563. length -= 2;
  170564. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  170565. INPUT_SYNC(cinfo); /* do before skip_input_data */
  170566. if (length > 0)
  170567. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170568. return TRUE;
  170569. }
  170570. /*
  170571. * Find the next JPEG marker, save it in cinfo->unread_marker.
  170572. * Returns FALSE if had to suspend before reaching a marker;
  170573. * in that case cinfo->unread_marker is unchanged.
  170574. *
  170575. * Note that the result might not be a valid marker code,
  170576. * but it will never be 0 or FF.
  170577. */
  170578. LOCAL(boolean)
  170579. next_marker (j_decompress_ptr cinfo)
  170580. {
  170581. int c;
  170582. INPUT_VARS(cinfo);
  170583. for (;;) {
  170584. INPUT_BYTE(cinfo, c, return FALSE);
  170585. /* Skip any non-FF bytes.
  170586. * This may look a bit inefficient, but it will not occur in a valid file.
  170587. * We sync after each discarded byte so that a suspending data source
  170588. * can discard the byte from its buffer.
  170589. */
  170590. while (c != 0xFF) {
  170591. cinfo->marker->discarded_bytes++;
  170592. INPUT_SYNC(cinfo);
  170593. INPUT_BYTE(cinfo, c, return FALSE);
  170594. }
  170595. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  170596. * pad bytes, so don't count them in discarded_bytes. We assume there
  170597. * will not be so many consecutive FF bytes as to overflow a suspending
  170598. * data source's input buffer.
  170599. */
  170600. do {
  170601. INPUT_BYTE(cinfo, c, return FALSE);
  170602. } while (c == 0xFF);
  170603. if (c != 0)
  170604. break; /* found a valid marker, exit loop */
  170605. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  170606. * Discard it and loop back to try again.
  170607. */
  170608. cinfo->marker->discarded_bytes += 2;
  170609. INPUT_SYNC(cinfo);
  170610. }
  170611. if (cinfo->marker->discarded_bytes != 0) {
  170612. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  170613. cinfo->marker->discarded_bytes = 0;
  170614. }
  170615. cinfo->unread_marker = c;
  170616. INPUT_SYNC(cinfo);
  170617. return TRUE;
  170618. }
  170619. LOCAL(boolean)
  170620. first_marker (j_decompress_ptr cinfo)
  170621. /* Like next_marker, but used to obtain the initial SOI marker. */
  170622. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  170623. * we might well scan an entire input file before realizing it ain't JPEG.
  170624. * If an application wants to process non-JFIF files, it must seek to the
  170625. * SOI before calling the JPEG library.
  170626. */
  170627. {
  170628. int c, c2;
  170629. INPUT_VARS(cinfo);
  170630. INPUT_BYTE(cinfo, c, return FALSE);
  170631. INPUT_BYTE(cinfo, c2, return FALSE);
  170632. if (c != 0xFF || c2 != (int) M_SOI)
  170633. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  170634. cinfo->unread_marker = c2;
  170635. INPUT_SYNC(cinfo);
  170636. return TRUE;
  170637. }
  170638. /*
  170639. * Read markers until SOS or EOI.
  170640. *
  170641. * Returns same codes as are defined for jpeg_consume_input:
  170642. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170643. */
  170644. METHODDEF(int)
  170645. read_markers (j_decompress_ptr cinfo)
  170646. {
  170647. /* Outer loop repeats once for each marker. */
  170648. for (;;) {
  170649. /* Collect the marker proper, unless we already did. */
  170650. /* NB: first_marker() enforces the requirement that SOI appear first. */
  170651. if (cinfo->unread_marker == 0) {
  170652. if (! cinfo->marker->saw_SOI) {
  170653. if (! first_marker(cinfo))
  170654. return JPEG_SUSPENDED;
  170655. } else {
  170656. if (! next_marker(cinfo))
  170657. return JPEG_SUSPENDED;
  170658. }
  170659. }
  170660. /* At this point cinfo->unread_marker contains the marker code and the
  170661. * input point is just past the marker proper, but before any parameters.
  170662. * A suspension will cause us to return with this state still true.
  170663. */
  170664. switch (cinfo->unread_marker) {
  170665. case M_SOI:
  170666. if (! get_soi(cinfo))
  170667. return JPEG_SUSPENDED;
  170668. break;
  170669. case M_SOF0: /* Baseline */
  170670. case M_SOF1: /* Extended sequential, Huffman */
  170671. if (! get_sof(cinfo, FALSE, FALSE))
  170672. return JPEG_SUSPENDED;
  170673. break;
  170674. case M_SOF2: /* Progressive, Huffman */
  170675. if (! get_sof(cinfo, TRUE, FALSE))
  170676. return JPEG_SUSPENDED;
  170677. break;
  170678. case M_SOF9: /* Extended sequential, arithmetic */
  170679. if (! get_sof(cinfo, FALSE, TRUE))
  170680. return JPEG_SUSPENDED;
  170681. break;
  170682. case M_SOF10: /* Progressive, arithmetic */
  170683. if (! get_sof(cinfo, TRUE, TRUE))
  170684. return JPEG_SUSPENDED;
  170685. break;
  170686. /* Currently unsupported SOFn types */
  170687. case M_SOF3: /* Lossless, Huffman */
  170688. case M_SOF5: /* Differential sequential, Huffman */
  170689. case M_SOF6: /* Differential progressive, Huffman */
  170690. case M_SOF7: /* Differential lossless, Huffman */
  170691. case M_JPG: /* Reserved for JPEG extensions */
  170692. case M_SOF11: /* Lossless, arithmetic */
  170693. case M_SOF13: /* Differential sequential, arithmetic */
  170694. case M_SOF14: /* Differential progressive, arithmetic */
  170695. case M_SOF15: /* Differential lossless, arithmetic */
  170696. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  170697. break;
  170698. case M_SOS:
  170699. if (! get_sos(cinfo))
  170700. return JPEG_SUSPENDED;
  170701. cinfo->unread_marker = 0; /* processed the marker */
  170702. return JPEG_REACHED_SOS;
  170703. case M_EOI:
  170704. TRACEMS(cinfo, 1, JTRC_EOI);
  170705. cinfo->unread_marker = 0; /* processed the marker */
  170706. return JPEG_REACHED_EOI;
  170707. case M_DAC:
  170708. if (! get_dac(cinfo))
  170709. return JPEG_SUSPENDED;
  170710. break;
  170711. case M_DHT:
  170712. if (! get_dht(cinfo))
  170713. return JPEG_SUSPENDED;
  170714. break;
  170715. case M_DQT:
  170716. if (! get_dqt(cinfo))
  170717. return JPEG_SUSPENDED;
  170718. break;
  170719. case M_DRI:
  170720. if (! get_dri(cinfo))
  170721. return JPEG_SUSPENDED;
  170722. break;
  170723. case M_APP0:
  170724. case M_APP1:
  170725. case M_APP2:
  170726. case M_APP3:
  170727. case M_APP4:
  170728. case M_APP5:
  170729. case M_APP6:
  170730. case M_APP7:
  170731. case M_APP8:
  170732. case M_APP9:
  170733. case M_APP10:
  170734. case M_APP11:
  170735. case M_APP12:
  170736. case M_APP13:
  170737. case M_APP14:
  170738. case M_APP15:
  170739. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  170740. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  170741. return JPEG_SUSPENDED;
  170742. break;
  170743. case M_COM:
  170744. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  170745. return JPEG_SUSPENDED;
  170746. break;
  170747. case M_RST0: /* these are all parameterless */
  170748. case M_RST1:
  170749. case M_RST2:
  170750. case M_RST3:
  170751. case M_RST4:
  170752. case M_RST5:
  170753. case M_RST6:
  170754. case M_RST7:
  170755. case M_TEM:
  170756. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  170757. break;
  170758. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  170759. if (! skip_variable(cinfo))
  170760. return JPEG_SUSPENDED;
  170761. break;
  170762. default: /* must be DHP, EXP, JPGn, or RESn */
  170763. /* For now, we treat the reserved markers as fatal errors since they are
  170764. * likely to be used to signal incompatible JPEG Part 3 extensions.
  170765. * Once the JPEG 3 version-number marker is well defined, this code
  170766. * ought to change!
  170767. */
  170768. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  170769. break;
  170770. }
  170771. /* Successfully processed marker, so reset state variable */
  170772. cinfo->unread_marker = 0;
  170773. } /* end loop */
  170774. }
  170775. /*
  170776. * Read a restart marker, which is expected to appear next in the datastream;
  170777. * if the marker is not there, take appropriate recovery action.
  170778. * Returns FALSE if suspension is required.
  170779. *
  170780. * This is called by the entropy decoder after it has read an appropriate
  170781. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  170782. * has already read a marker from the data source. Under normal conditions
  170783. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  170784. * it holds a marker which the decoder will be unable to read past.
  170785. */
  170786. METHODDEF(boolean)
  170787. read_restart_marker (j_decompress_ptr cinfo)
  170788. {
  170789. /* Obtain a marker unless we already did. */
  170790. /* Note that next_marker will complain if it skips any data. */
  170791. if (cinfo->unread_marker == 0) {
  170792. if (! next_marker(cinfo))
  170793. return FALSE;
  170794. }
  170795. if (cinfo->unread_marker ==
  170796. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  170797. /* Normal case --- swallow the marker and let entropy decoder continue */
  170798. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  170799. cinfo->unread_marker = 0;
  170800. } else {
  170801. /* Uh-oh, the restart markers have been messed up. */
  170802. /* Let the data source manager determine how to resync. */
  170803. if (! (*cinfo->src->resync_to_restart) (cinfo,
  170804. cinfo->marker->next_restart_num))
  170805. return FALSE;
  170806. }
  170807. /* Update next-restart state */
  170808. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  170809. return TRUE;
  170810. }
  170811. /*
  170812. * This is the default resync_to_restart method for data source managers
  170813. * to use if they don't have any better approach. Some data source managers
  170814. * may be able to back up, or may have additional knowledge about the data
  170815. * which permits a more intelligent recovery strategy; such managers would
  170816. * presumably supply their own resync method.
  170817. *
  170818. * read_restart_marker calls resync_to_restart if it finds a marker other than
  170819. * the restart marker it was expecting. (This code is *not* used unless
  170820. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  170821. * the marker code actually found (might be anything, except 0 or FF).
  170822. * The desired restart marker number (0..7) is passed as a parameter.
  170823. * This routine is supposed to apply whatever error recovery strategy seems
  170824. * appropriate in order to position the input stream to the next data segment.
  170825. * Note that cinfo->unread_marker is treated as a marker appearing before
  170826. * the current data-source input point; usually it should be reset to zero
  170827. * before returning.
  170828. * Returns FALSE if suspension is required.
  170829. *
  170830. * This implementation is substantially constrained by wanting to treat the
  170831. * input as a data stream; this means we can't back up. Therefore, we have
  170832. * only the following actions to work with:
  170833. * 1. Simply discard the marker and let the entropy decoder resume at next
  170834. * byte of file.
  170835. * 2. Read forward until we find another marker, discarding intervening
  170836. * data. (In theory we could look ahead within the current bufferload,
  170837. * without having to discard data if we don't find the desired marker.
  170838. * This idea is not implemented here, in part because it makes behavior
  170839. * dependent on buffer size and chance buffer-boundary positions.)
  170840. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  170841. * This will cause the entropy decoder to process an empty data segment,
  170842. * inserting dummy zeroes, and then we will reprocess the marker.
  170843. *
  170844. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  170845. * appropriate if the found marker is a future restart marker (indicating
  170846. * that we have missed the desired restart marker, probably because it got
  170847. * corrupted).
  170848. * We apply #2 or #3 if the found marker is a restart marker no more than
  170849. * two counts behind or ahead of the expected one. We also apply #2 if the
  170850. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  170851. * If the found marker is a restart marker more than 2 counts away, we do #1
  170852. * (too much risk that the marker is erroneous; with luck we will be able to
  170853. * resync at some future point).
  170854. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  170855. * overrunning the end of a scan. An implementation limited to single-scan
  170856. * files might find it better to apply #2 for markers other than EOI, since
  170857. * any other marker would have to be bogus data in that case.
  170858. */
  170859. GLOBAL(boolean)
  170860. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  170861. {
  170862. int marker = cinfo->unread_marker;
  170863. int action = 1;
  170864. /* Always put up a warning. */
  170865. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  170866. /* Outer loop handles repeated decision after scanning forward. */
  170867. for (;;) {
  170868. if (marker < (int) M_SOF0)
  170869. action = 2; /* invalid marker */
  170870. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  170871. action = 3; /* valid non-restart marker */
  170872. else {
  170873. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  170874. marker == ((int) M_RST0 + ((desired+2) & 7)))
  170875. action = 3; /* one of the next two expected restarts */
  170876. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  170877. marker == ((int) M_RST0 + ((desired-2) & 7)))
  170878. action = 2; /* a prior restart, so advance */
  170879. else
  170880. action = 1; /* desired restart or too far away */
  170881. }
  170882. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  170883. switch (action) {
  170884. case 1:
  170885. /* Discard marker and let entropy decoder resume processing. */
  170886. cinfo->unread_marker = 0;
  170887. return TRUE;
  170888. case 2:
  170889. /* Scan to the next marker, and repeat the decision loop. */
  170890. if (! next_marker(cinfo))
  170891. return FALSE;
  170892. marker = cinfo->unread_marker;
  170893. break;
  170894. case 3:
  170895. /* Return without advancing past this marker. */
  170896. /* Entropy decoder will be forced to process an empty segment. */
  170897. return TRUE;
  170898. }
  170899. } /* end loop */
  170900. }
  170901. /*
  170902. * Reset marker processing state to begin a fresh datastream.
  170903. */
  170904. METHODDEF(void)
  170905. reset_marker_reader (j_decompress_ptr cinfo)
  170906. {
  170907. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  170908. cinfo->comp_info = NULL; /* until allocated by get_sof */
  170909. cinfo->input_scan_number = 0; /* no SOS seen yet */
  170910. cinfo->unread_marker = 0; /* no pending marker */
  170911. marker->pub.saw_SOI = FALSE; /* set internal state too */
  170912. marker->pub.saw_SOF = FALSE;
  170913. marker->pub.discarded_bytes = 0;
  170914. marker->cur_marker = NULL;
  170915. }
  170916. /*
  170917. * Initialize the marker reader module.
  170918. * This is called only once, when the decompression object is created.
  170919. */
  170920. GLOBAL(void)
  170921. jinit_marker_reader (j_decompress_ptr cinfo)
  170922. {
  170923. my_marker_ptr2 marker;
  170924. int i;
  170925. /* Create subobject in permanent pool */
  170926. marker = (my_marker_ptr2)
  170927. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170928. SIZEOF(my_marker_reader));
  170929. cinfo->marker = (struct jpeg_marker_reader *) marker;
  170930. /* Initialize public method pointers */
  170931. marker->pub.reset_marker_reader = reset_marker_reader;
  170932. marker->pub.read_markers = read_markers;
  170933. marker->pub.read_restart_marker = read_restart_marker;
  170934. /* Initialize COM/APPn processing.
  170935. * By default, we examine and then discard APP0 and APP14,
  170936. * but simply discard COM and all other APPn.
  170937. */
  170938. marker->process_COM = skip_variable;
  170939. marker->length_limit_COM = 0;
  170940. for (i = 0; i < 16; i++) {
  170941. marker->process_APPn[i] = skip_variable;
  170942. marker->length_limit_APPn[i] = 0;
  170943. }
  170944. marker->process_APPn[0] = get_interesting_appn;
  170945. marker->process_APPn[14] = get_interesting_appn;
  170946. /* Reset marker processing state */
  170947. reset_marker_reader(cinfo);
  170948. }
  170949. /*
  170950. * Control saving of COM and APPn markers into marker_list.
  170951. */
  170952. #ifdef SAVE_MARKERS_SUPPORTED
  170953. GLOBAL(void)
  170954. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  170955. unsigned int length_limit)
  170956. {
  170957. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  170958. long maxlength;
  170959. jpeg_marker_parser_method processor;
  170960. /* Length limit mustn't be larger than what we can allocate
  170961. * (should only be a concern in a 16-bit environment).
  170962. */
  170963. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  170964. if (((long) length_limit) > maxlength)
  170965. length_limit = (unsigned int) maxlength;
  170966. /* Choose processor routine to use.
  170967. * APP0/APP14 have special requirements.
  170968. */
  170969. if (length_limit) {
  170970. processor = save_marker;
  170971. /* If saving APP0/APP14, save at least enough for our internal use. */
  170972. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  170973. length_limit = APP0_DATA_LEN;
  170974. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  170975. length_limit = APP14_DATA_LEN;
  170976. } else {
  170977. processor = skip_variable;
  170978. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  170979. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  170980. processor = get_interesting_appn;
  170981. }
  170982. if (marker_code == (int) M_COM) {
  170983. marker->process_COM = processor;
  170984. marker->length_limit_COM = length_limit;
  170985. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  170986. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  170987. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  170988. } else
  170989. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  170990. }
  170991. #endif /* SAVE_MARKERS_SUPPORTED */
  170992. /*
  170993. * Install a special processing method for COM or APPn markers.
  170994. */
  170995. GLOBAL(void)
  170996. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  170997. jpeg_marker_parser_method routine)
  170998. {
  170999. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171000. if (marker_code == (int) M_COM)
  171001. marker->process_COM = routine;
  171002. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171003. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171004. else
  171005. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171006. }
  171007. /*** End of inlined file: jdmarker.c ***/
  171008. /*** Start of inlined file: jdmaster.c ***/
  171009. #define JPEG_INTERNALS
  171010. /* Private state */
  171011. typedef struct {
  171012. struct jpeg_decomp_master pub; /* public fields */
  171013. int pass_number; /* # of passes completed */
  171014. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171015. /* Saved references to initialized quantizer modules,
  171016. * in case we need to switch modes.
  171017. */
  171018. struct jpeg_color_quantizer * quantizer_1pass;
  171019. struct jpeg_color_quantizer * quantizer_2pass;
  171020. } my_decomp_master;
  171021. typedef my_decomp_master * my_master_ptr6;
  171022. /*
  171023. * Determine whether merged upsample/color conversion should be used.
  171024. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171025. */
  171026. LOCAL(boolean)
  171027. use_merged_upsample (j_decompress_ptr cinfo)
  171028. {
  171029. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171030. /* Merging is the equivalent of plain box-filter upsampling */
  171031. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171032. return FALSE;
  171033. /* jdmerge.c only supports YCC=>RGB color conversion */
  171034. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171035. cinfo->out_color_space != JCS_RGB ||
  171036. cinfo->out_color_components != RGB_PIXELSIZE)
  171037. return FALSE;
  171038. /* and it only handles 2h1v or 2h2v sampling ratios */
  171039. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171040. cinfo->comp_info[1].h_samp_factor != 1 ||
  171041. cinfo->comp_info[2].h_samp_factor != 1 ||
  171042. cinfo->comp_info[0].v_samp_factor > 2 ||
  171043. cinfo->comp_info[1].v_samp_factor != 1 ||
  171044. cinfo->comp_info[2].v_samp_factor != 1)
  171045. return FALSE;
  171046. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171047. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171048. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171049. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171050. return FALSE;
  171051. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171052. return TRUE; /* by golly, it'll work... */
  171053. #else
  171054. return FALSE;
  171055. #endif
  171056. }
  171057. /*
  171058. * Compute output image dimensions and related values.
  171059. * NOTE: this is exported for possible use by application.
  171060. * Hence it mustn't do anything that can't be done twice.
  171061. * Also note that it may be called before the master module is initialized!
  171062. */
  171063. GLOBAL(void)
  171064. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171065. /* Do computations that are needed before master selection phase */
  171066. {
  171067. #ifdef IDCT_SCALING_SUPPORTED
  171068. int ci;
  171069. jpeg_component_info *compptr;
  171070. #endif
  171071. /* Prevent application from calling me at wrong times */
  171072. if (cinfo->global_state != DSTATE_READY)
  171073. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171074. #ifdef IDCT_SCALING_SUPPORTED
  171075. /* Compute actual output image dimensions and DCT scaling choices. */
  171076. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171077. /* Provide 1/8 scaling */
  171078. cinfo->output_width = (JDIMENSION)
  171079. jdiv_round_up((long) cinfo->image_width, 8L);
  171080. cinfo->output_height = (JDIMENSION)
  171081. jdiv_round_up((long) cinfo->image_height, 8L);
  171082. cinfo->min_DCT_scaled_size = 1;
  171083. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171084. /* Provide 1/4 scaling */
  171085. cinfo->output_width = (JDIMENSION)
  171086. jdiv_round_up((long) cinfo->image_width, 4L);
  171087. cinfo->output_height = (JDIMENSION)
  171088. jdiv_round_up((long) cinfo->image_height, 4L);
  171089. cinfo->min_DCT_scaled_size = 2;
  171090. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171091. /* Provide 1/2 scaling */
  171092. cinfo->output_width = (JDIMENSION)
  171093. jdiv_round_up((long) cinfo->image_width, 2L);
  171094. cinfo->output_height = (JDIMENSION)
  171095. jdiv_round_up((long) cinfo->image_height, 2L);
  171096. cinfo->min_DCT_scaled_size = 4;
  171097. } else {
  171098. /* Provide 1/1 scaling */
  171099. cinfo->output_width = cinfo->image_width;
  171100. cinfo->output_height = cinfo->image_height;
  171101. cinfo->min_DCT_scaled_size = DCTSIZE;
  171102. }
  171103. /* In selecting the actual DCT scaling for each component, we try to
  171104. * scale up the chroma components via IDCT scaling rather than upsampling.
  171105. * This saves time if the upsampler gets to use 1:1 scaling.
  171106. * Note this code assumes that the supported DCT scalings are powers of 2.
  171107. */
  171108. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171109. ci++, compptr++) {
  171110. int ssize = cinfo->min_DCT_scaled_size;
  171111. while (ssize < DCTSIZE &&
  171112. (compptr->h_samp_factor * ssize * 2 <=
  171113. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171114. (compptr->v_samp_factor * ssize * 2 <=
  171115. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171116. ssize = ssize * 2;
  171117. }
  171118. compptr->DCT_scaled_size = ssize;
  171119. }
  171120. /* Recompute downsampled dimensions of components;
  171121. * application needs to know these if using raw downsampled data.
  171122. */
  171123. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171124. ci++, compptr++) {
  171125. /* Size in samples, after IDCT scaling */
  171126. compptr->downsampled_width = (JDIMENSION)
  171127. jdiv_round_up((long) cinfo->image_width *
  171128. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171129. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171130. compptr->downsampled_height = (JDIMENSION)
  171131. jdiv_round_up((long) cinfo->image_height *
  171132. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171133. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171134. }
  171135. #else /* !IDCT_SCALING_SUPPORTED */
  171136. /* Hardwire it to "no scaling" */
  171137. cinfo->output_width = cinfo->image_width;
  171138. cinfo->output_height = cinfo->image_height;
  171139. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  171140. * and has computed unscaled downsampled_width and downsampled_height.
  171141. */
  171142. #endif /* IDCT_SCALING_SUPPORTED */
  171143. /* Report number of components in selected colorspace. */
  171144. /* Probably this should be in the color conversion module... */
  171145. switch (cinfo->out_color_space) {
  171146. case JCS_GRAYSCALE:
  171147. cinfo->out_color_components = 1;
  171148. break;
  171149. case JCS_RGB:
  171150. #if RGB_PIXELSIZE != 3
  171151. cinfo->out_color_components = RGB_PIXELSIZE;
  171152. break;
  171153. #endif /* else share code with YCbCr */
  171154. case JCS_YCbCr:
  171155. cinfo->out_color_components = 3;
  171156. break;
  171157. case JCS_CMYK:
  171158. case JCS_YCCK:
  171159. cinfo->out_color_components = 4;
  171160. break;
  171161. default: /* else must be same colorspace as in file */
  171162. cinfo->out_color_components = cinfo->num_components;
  171163. break;
  171164. }
  171165. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  171166. cinfo->out_color_components);
  171167. /* See if upsampler will want to emit more than one row at a time */
  171168. if (use_merged_upsample(cinfo))
  171169. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  171170. else
  171171. cinfo->rec_outbuf_height = 1;
  171172. }
  171173. /*
  171174. * Several decompression processes need to range-limit values to the range
  171175. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  171176. * due to noise introduced by quantization, roundoff error, etc. These
  171177. * processes are inner loops and need to be as fast as possible. On most
  171178. * machines, particularly CPUs with pipelines or instruction prefetch,
  171179. * a (subscript-check-less) C table lookup
  171180. * x = sample_range_limit[x];
  171181. * is faster than explicit tests
  171182. * if (x < 0) x = 0;
  171183. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  171184. * These processes all use a common table prepared by the routine below.
  171185. *
  171186. * For most steps we can mathematically guarantee that the initial value
  171187. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  171188. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  171189. * limiting step (just after the IDCT), a wildly out-of-range value is
  171190. * possible if the input data is corrupt. To avoid any chance of indexing
  171191. * off the end of memory and getting a bad-pointer trap, we perform the
  171192. * post-IDCT limiting thus:
  171193. * x = range_limit[x & MASK];
  171194. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  171195. * samples. Under normal circumstances this is more than enough range and
  171196. * a correct output will be generated; with bogus input data the mask will
  171197. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  171198. * For the post-IDCT step, we want to convert the data from signed to unsigned
  171199. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  171200. * So the post-IDCT limiting table ends up looking like this:
  171201. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  171202. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171203. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171204. * 0,1,...,CENTERJSAMPLE-1
  171205. * Negative inputs select values from the upper half of the table after
  171206. * masking.
  171207. *
  171208. * We can save some space by overlapping the start of the post-IDCT table
  171209. * with the simpler range limiting table. The post-IDCT table begins at
  171210. * sample_range_limit + CENTERJSAMPLE.
  171211. *
  171212. * Note that the table is allocated in near data space on PCs; it's small
  171213. * enough and used often enough to justify this.
  171214. */
  171215. LOCAL(void)
  171216. prepare_range_limit_table (j_decompress_ptr cinfo)
  171217. /* Allocate and fill in the sample_range_limit table */
  171218. {
  171219. JSAMPLE * table;
  171220. int i;
  171221. table = (JSAMPLE *)
  171222. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171223. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171224. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  171225. cinfo->sample_range_limit = table;
  171226. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  171227. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  171228. /* Main part of "simple" table: limit[x] = x */
  171229. for (i = 0; i <= MAXJSAMPLE; i++)
  171230. table[i] = (JSAMPLE) i;
  171231. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  171232. /* End of simple table, rest of first half of post-IDCT table */
  171233. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  171234. table[i] = MAXJSAMPLE;
  171235. /* Second half of post-IDCT table */
  171236. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  171237. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171238. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  171239. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  171240. }
  171241. /*
  171242. * Master selection of decompression modules.
  171243. * This is done once at jpeg_start_decompress time. We determine
  171244. * which modules will be used and give them appropriate initialization calls.
  171245. * We also initialize the decompressor input side to begin consuming data.
  171246. *
  171247. * Since jpeg_read_header has finished, we know what is in the SOF
  171248. * and (first) SOS markers. We also have all the application parameter
  171249. * settings.
  171250. */
  171251. LOCAL(void)
  171252. master_selection (j_decompress_ptr cinfo)
  171253. {
  171254. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171255. boolean use_c_buffer;
  171256. long samplesperrow;
  171257. JDIMENSION jd_samplesperrow;
  171258. /* Initialize dimensions and other stuff */
  171259. jpeg_calc_output_dimensions(cinfo);
  171260. prepare_range_limit_table(cinfo);
  171261. /* Width of an output scanline must be representable as JDIMENSION. */
  171262. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  171263. jd_samplesperrow = (JDIMENSION) samplesperrow;
  171264. if ((long) jd_samplesperrow != samplesperrow)
  171265. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171266. /* Initialize my private state */
  171267. master->pass_number = 0;
  171268. master->using_merged_upsample = use_merged_upsample(cinfo);
  171269. /* Color quantizer selection */
  171270. master->quantizer_1pass = NULL;
  171271. master->quantizer_2pass = NULL;
  171272. /* No mode changes if not using buffered-image mode. */
  171273. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  171274. cinfo->enable_1pass_quant = FALSE;
  171275. cinfo->enable_external_quant = FALSE;
  171276. cinfo->enable_2pass_quant = FALSE;
  171277. }
  171278. if (cinfo->quantize_colors) {
  171279. if (cinfo->raw_data_out)
  171280. ERREXIT(cinfo, JERR_NOTIMPL);
  171281. /* 2-pass quantizer only works in 3-component color space. */
  171282. if (cinfo->out_color_components != 3) {
  171283. cinfo->enable_1pass_quant = TRUE;
  171284. cinfo->enable_external_quant = FALSE;
  171285. cinfo->enable_2pass_quant = FALSE;
  171286. cinfo->colormap = NULL;
  171287. } else if (cinfo->colormap != NULL) {
  171288. cinfo->enable_external_quant = TRUE;
  171289. } else if (cinfo->two_pass_quantize) {
  171290. cinfo->enable_2pass_quant = TRUE;
  171291. } else {
  171292. cinfo->enable_1pass_quant = TRUE;
  171293. }
  171294. if (cinfo->enable_1pass_quant) {
  171295. #ifdef QUANT_1PASS_SUPPORTED
  171296. jinit_1pass_quantizer(cinfo);
  171297. master->quantizer_1pass = cinfo->cquantize;
  171298. #else
  171299. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171300. #endif
  171301. }
  171302. /* We use the 2-pass code to map to external colormaps. */
  171303. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  171304. #ifdef QUANT_2PASS_SUPPORTED
  171305. jinit_2pass_quantizer(cinfo);
  171306. master->quantizer_2pass = cinfo->cquantize;
  171307. #else
  171308. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171309. #endif
  171310. }
  171311. /* If both quantizers are initialized, the 2-pass one is left active;
  171312. * this is necessary for starting with quantization to an external map.
  171313. */
  171314. }
  171315. /* Post-processing: in particular, color conversion first */
  171316. if (! cinfo->raw_data_out) {
  171317. if (master->using_merged_upsample) {
  171318. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171319. jinit_merged_upsampler(cinfo); /* does color conversion too */
  171320. #else
  171321. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171322. #endif
  171323. } else {
  171324. jinit_color_deconverter(cinfo);
  171325. jinit_upsampler(cinfo);
  171326. }
  171327. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  171328. }
  171329. /* Inverse DCT */
  171330. jinit_inverse_dct(cinfo);
  171331. /* Entropy decoding: either Huffman or arithmetic coding. */
  171332. if (cinfo->arith_code) {
  171333. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  171334. } else {
  171335. if (cinfo->progressive_mode) {
  171336. #ifdef D_PROGRESSIVE_SUPPORTED
  171337. jinit_phuff_decoder(cinfo);
  171338. #else
  171339. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171340. #endif
  171341. } else
  171342. jinit_huff_decoder(cinfo);
  171343. }
  171344. /* Initialize principal buffer controllers. */
  171345. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  171346. jinit_d_coef_controller(cinfo, use_c_buffer);
  171347. if (! cinfo->raw_data_out)
  171348. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  171349. /* We can now tell the memory manager to allocate virtual arrays. */
  171350. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  171351. /* Initialize input side of decompressor to consume first scan. */
  171352. (*cinfo->inputctl->start_input_pass) (cinfo);
  171353. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171354. /* If jpeg_start_decompress will read the whole file, initialize
  171355. * progress monitoring appropriately. The input step is counted
  171356. * as one pass.
  171357. */
  171358. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  171359. cinfo->inputctl->has_multiple_scans) {
  171360. int nscans;
  171361. /* Estimate number of scans to set pass_limit. */
  171362. if (cinfo->progressive_mode) {
  171363. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  171364. nscans = 2 + 3 * cinfo->num_components;
  171365. } else {
  171366. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  171367. nscans = cinfo->num_components;
  171368. }
  171369. cinfo->progress->pass_counter = 0L;
  171370. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  171371. cinfo->progress->completed_passes = 0;
  171372. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  171373. /* Count the input pass as done */
  171374. master->pass_number++;
  171375. }
  171376. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171377. }
  171378. /*
  171379. * Per-pass setup.
  171380. * This is called at the beginning of each output pass. We determine which
  171381. * modules will be active during this pass and give them appropriate
  171382. * start_pass calls. We also set is_dummy_pass to indicate whether this
  171383. * is a "real" output pass or a dummy pass for color quantization.
  171384. * (In the latter case, jdapistd.c will crank the pass to completion.)
  171385. */
  171386. METHODDEF(void)
  171387. prepare_for_output_pass (j_decompress_ptr cinfo)
  171388. {
  171389. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171390. if (master->pub.is_dummy_pass) {
  171391. #ifdef QUANT_2PASS_SUPPORTED
  171392. /* Final pass of 2-pass quantization */
  171393. master->pub.is_dummy_pass = FALSE;
  171394. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  171395. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  171396. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  171397. #else
  171398. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171399. #endif /* QUANT_2PASS_SUPPORTED */
  171400. } else {
  171401. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  171402. /* Select new quantization method */
  171403. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  171404. cinfo->cquantize = master->quantizer_2pass;
  171405. master->pub.is_dummy_pass = TRUE;
  171406. } else if (cinfo->enable_1pass_quant) {
  171407. cinfo->cquantize = master->quantizer_1pass;
  171408. } else {
  171409. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171410. }
  171411. }
  171412. (*cinfo->idct->start_pass) (cinfo);
  171413. (*cinfo->coef->start_output_pass) (cinfo);
  171414. if (! cinfo->raw_data_out) {
  171415. if (! master->using_merged_upsample)
  171416. (*cinfo->cconvert->start_pass) (cinfo);
  171417. (*cinfo->upsample->start_pass) (cinfo);
  171418. if (cinfo->quantize_colors)
  171419. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  171420. (*cinfo->post->start_pass) (cinfo,
  171421. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  171422. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  171423. }
  171424. }
  171425. /* Set up progress monitor's pass info if present */
  171426. if (cinfo->progress != NULL) {
  171427. cinfo->progress->completed_passes = master->pass_number;
  171428. cinfo->progress->total_passes = master->pass_number +
  171429. (master->pub.is_dummy_pass ? 2 : 1);
  171430. /* In buffered-image mode, we assume one more output pass if EOI not
  171431. * yet reached, but no more passes if EOI has been reached.
  171432. */
  171433. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  171434. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  171435. }
  171436. }
  171437. }
  171438. /*
  171439. * Finish up at end of an output pass.
  171440. */
  171441. METHODDEF(void)
  171442. finish_output_pass (j_decompress_ptr cinfo)
  171443. {
  171444. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171445. if (cinfo->quantize_colors)
  171446. (*cinfo->cquantize->finish_pass) (cinfo);
  171447. master->pass_number++;
  171448. }
  171449. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171450. /*
  171451. * Switch to a new external colormap between output passes.
  171452. */
  171453. GLOBAL(void)
  171454. jpeg_new_colormap (j_decompress_ptr cinfo)
  171455. {
  171456. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171457. /* Prevent application from calling me at wrong times */
  171458. if (cinfo->global_state != DSTATE_BUFIMAGE)
  171459. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171460. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  171461. cinfo->colormap != NULL) {
  171462. /* Select 2-pass quantizer for external colormap use */
  171463. cinfo->cquantize = master->quantizer_2pass;
  171464. /* Notify quantizer of colormap change */
  171465. (*cinfo->cquantize->new_color_map) (cinfo);
  171466. master->pub.is_dummy_pass = FALSE; /* just in case */
  171467. } else
  171468. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171469. }
  171470. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171471. /*
  171472. * Initialize master decompression control and select active modules.
  171473. * This is performed at the start of jpeg_start_decompress.
  171474. */
  171475. GLOBAL(void)
  171476. jinit_master_decompress (j_decompress_ptr cinfo)
  171477. {
  171478. my_master_ptr6 master;
  171479. master = (my_master_ptr6)
  171480. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171481. SIZEOF(my_decomp_master));
  171482. cinfo->master = (struct jpeg_decomp_master *) master;
  171483. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  171484. master->pub.finish_output_pass = finish_output_pass;
  171485. master->pub.is_dummy_pass = FALSE;
  171486. master_selection(cinfo);
  171487. }
  171488. /*** End of inlined file: jdmaster.c ***/
  171489. #undef FIX
  171490. /*** Start of inlined file: jdmerge.c ***/
  171491. #define JPEG_INTERNALS
  171492. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171493. /* Private subobject */
  171494. typedef struct {
  171495. struct jpeg_upsampler pub; /* public fields */
  171496. /* Pointer to routine to do actual upsampling/conversion of one row group */
  171497. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  171498. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171499. JSAMPARRAY output_buf));
  171500. /* Private state for YCC->RGB conversion */
  171501. int * Cr_r_tab; /* => table for Cr to R conversion */
  171502. int * Cb_b_tab; /* => table for Cb to B conversion */
  171503. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  171504. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  171505. /* For 2:1 vertical sampling, we produce two output rows at a time.
  171506. * We need a "spare" row buffer to hold the second output row if the
  171507. * application provides just a one-row buffer; we also use the spare
  171508. * to discard the dummy last row if the image height is odd.
  171509. */
  171510. JSAMPROW spare_row;
  171511. boolean spare_full; /* T if spare buffer is occupied */
  171512. JDIMENSION out_row_width; /* samples per output row */
  171513. JDIMENSION rows_to_go; /* counts rows remaining in image */
  171514. } my_upsampler;
  171515. typedef my_upsampler * my_upsample_ptr;
  171516. #define SCALEBITS 16 /* speediest right-shift on some machines */
  171517. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  171518. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  171519. /*
  171520. * Initialize tables for YCC->RGB colorspace conversion.
  171521. * This is taken directly from jdcolor.c; see that file for more info.
  171522. */
  171523. LOCAL(void)
  171524. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  171525. {
  171526. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171527. int i;
  171528. INT32 x;
  171529. SHIFT_TEMPS
  171530. upsample->Cr_r_tab = (int *)
  171531. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171532. (MAXJSAMPLE+1) * SIZEOF(int));
  171533. upsample->Cb_b_tab = (int *)
  171534. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171535. (MAXJSAMPLE+1) * SIZEOF(int));
  171536. upsample->Cr_g_tab = (INT32 *)
  171537. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171538. (MAXJSAMPLE+1) * SIZEOF(INT32));
  171539. upsample->Cb_g_tab = (INT32 *)
  171540. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171541. (MAXJSAMPLE+1) * SIZEOF(INT32));
  171542. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  171543. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  171544. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  171545. /* Cr=>R value is nearest int to 1.40200 * x */
  171546. upsample->Cr_r_tab[i] = (int)
  171547. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  171548. /* Cb=>B value is nearest int to 1.77200 * x */
  171549. upsample->Cb_b_tab[i] = (int)
  171550. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  171551. /* Cr=>G value is scaled-up -0.71414 * x */
  171552. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  171553. /* Cb=>G value is scaled-up -0.34414 * x */
  171554. /* We also add in ONE_HALF so that need not do it in inner loop */
  171555. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  171556. }
  171557. }
  171558. /*
  171559. * Initialize for an upsampling pass.
  171560. */
  171561. METHODDEF(void)
  171562. start_pass_merged_upsample (j_decompress_ptr cinfo)
  171563. {
  171564. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171565. /* Mark the spare buffer empty */
  171566. upsample->spare_full = FALSE;
  171567. /* Initialize total-height counter for detecting bottom of image */
  171568. upsample->rows_to_go = cinfo->output_height;
  171569. }
  171570. /*
  171571. * Control routine to do upsampling (and color conversion).
  171572. *
  171573. * The control routine just handles the row buffering considerations.
  171574. */
  171575. METHODDEF(void)
  171576. merged_2v_upsample (j_decompress_ptr cinfo,
  171577. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  171578. JDIMENSION,
  171579. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171580. JDIMENSION out_rows_avail)
  171581. /* 2:1 vertical sampling case: may need a spare row. */
  171582. {
  171583. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171584. JSAMPROW work_ptrs[2];
  171585. JDIMENSION num_rows; /* number of rows returned to caller */
  171586. if (upsample->spare_full) {
  171587. /* If we have a spare row saved from a previous cycle, just return it. */
  171588. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  171589. 1, upsample->out_row_width);
  171590. num_rows = 1;
  171591. upsample->spare_full = FALSE;
  171592. } else {
  171593. /* Figure number of rows to return to caller. */
  171594. num_rows = 2;
  171595. /* Not more than the distance to the end of the image. */
  171596. if (num_rows > upsample->rows_to_go)
  171597. num_rows = upsample->rows_to_go;
  171598. /* And not more than what the client can accept: */
  171599. out_rows_avail -= *out_row_ctr;
  171600. if (num_rows > out_rows_avail)
  171601. num_rows = out_rows_avail;
  171602. /* Create output pointer array for upsampler. */
  171603. work_ptrs[0] = output_buf[*out_row_ctr];
  171604. if (num_rows > 1) {
  171605. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  171606. } else {
  171607. work_ptrs[1] = upsample->spare_row;
  171608. upsample->spare_full = TRUE;
  171609. }
  171610. /* Now do the upsampling. */
  171611. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  171612. }
  171613. /* Adjust counts */
  171614. *out_row_ctr += num_rows;
  171615. upsample->rows_to_go -= num_rows;
  171616. /* When the buffer is emptied, declare this input row group consumed */
  171617. if (! upsample->spare_full)
  171618. (*in_row_group_ctr)++;
  171619. }
  171620. METHODDEF(void)
  171621. merged_1v_upsample (j_decompress_ptr cinfo,
  171622. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  171623. JDIMENSION,
  171624. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171625. JDIMENSION)
  171626. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  171627. {
  171628. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171629. /* Just do the upsampling. */
  171630. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  171631. output_buf + *out_row_ctr);
  171632. /* Adjust counts */
  171633. (*out_row_ctr)++;
  171634. (*in_row_group_ctr)++;
  171635. }
  171636. /*
  171637. * These are the routines invoked by the control routines to do
  171638. * the actual upsampling/conversion. One row group is processed per call.
  171639. *
  171640. * Note: since we may be writing directly into application-supplied buffers,
  171641. * we have to be honest about the output width; we can't assume the buffer
  171642. * has been rounded up to an even width.
  171643. */
  171644. /*
  171645. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  171646. */
  171647. METHODDEF(void)
  171648. h2v1_merged_upsample (j_decompress_ptr cinfo,
  171649. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171650. JSAMPARRAY output_buf)
  171651. {
  171652. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171653. register int y, cred, cgreen, cblue;
  171654. int cb, cr;
  171655. register JSAMPROW outptr;
  171656. JSAMPROW inptr0, inptr1, inptr2;
  171657. JDIMENSION col;
  171658. /* copy these pointers into registers if possible */
  171659. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  171660. int * Crrtab = upsample->Cr_r_tab;
  171661. int * Cbbtab = upsample->Cb_b_tab;
  171662. INT32 * Crgtab = upsample->Cr_g_tab;
  171663. INT32 * Cbgtab = upsample->Cb_g_tab;
  171664. SHIFT_TEMPS
  171665. inptr0 = input_buf[0][in_row_group_ctr];
  171666. inptr1 = input_buf[1][in_row_group_ctr];
  171667. inptr2 = input_buf[2][in_row_group_ctr];
  171668. outptr = output_buf[0];
  171669. /* Loop for each pair of output pixels */
  171670. for (col = cinfo->output_width >> 1; col > 0; col--) {
  171671. /* Do the chroma part of the calculation */
  171672. cb = GETJSAMPLE(*inptr1++);
  171673. cr = GETJSAMPLE(*inptr2++);
  171674. cred = Crrtab[cr];
  171675. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  171676. cblue = Cbbtab[cb];
  171677. /* Fetch 2 Y values and emit 2 pixels */
  171678. y = GETJSAMPLE(*inptr0++);
  171679. outptr[RGB_RED] = range_limit[y + cred];
  171680. outptr[RGB_GREEN] = range_limit[y + cgreen];
  171681. outptr[RGB_BLUE] = range_limit[y + cblue];
  171682. outptr += RGB_PIXELSIZE;
  171683. y = GETJSAMPLE(*inptr0++);
  171684. outptr[RGB_RED] = range_limit[y + cred];
  171685. outptr[RGB_GREEN] = range_limit[y + cgreen];
  171686. outptr[RGB_BLUE] = range_limit[y + cblue];
  171687. outptr += RGB_PIXELSIZE;
  171688. }
  171689. /* If image width is odd, do the last output column separately */
  171690. if (cinfo->output_width & 1) {
  171691. cb = GETJSAMPLE(*inptr1);
  171692. cr = GETJSAMPLE(*inptr2);
  171693. cred = Crrtab[cr];
  171694. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  171695. cblue = Cbbtab[cb];
  171696. y = GETJSAMPLE(*inptr0);
  171697. outptr[RGB_RED] = range_limit[y + cred];
  171698. outptr[RGB_GREEN] = range_limit[y + cgreen];
  171699. outptr[RGB_BLUE] = range_limit[y + cblue];
  171700. }
  171701. }
  171702. /*
  171703. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  171704. */
  171705. METHODDEF(void)
  171706. h2v2_merged_upsample (j_decompress_ptr cinfo,
  171707. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171708. JSAMPARRAY output_buf)
  171709. {
  171710. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171711. register int y, cred, cgreen, cblue;
  171712. int cb, cr;
  171713. register JSAMPROW outptr0, outptr1;
  171714. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  171715. JDIMENSION col;
  171716. /* copy these pointers into registers if possible */
  171717. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  171718. int * Crrtab = upsample->Cr_r_tab;
  171719. int * Cbbtab = upsample->Cb_b_tab;
  171720. INT32 * Crgtab = upsample->Cr_g_tab;
  171721. INT32 * Cbgtab = upsample->Cb_g_tab;
  171722. SHIFT_TEMPS
  171723. inptr00 = input_buf[0][in_row_group_ctr*2];
  171724. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  171725. inptr1 = input_buf[1][in_row_group_ctr];
  171726. inptr2 = input_buf[2][in_row_group_ctr];
  171727. outptr0 = output_buf[0];
  171728. outptr1 = output_buf[1];
  171729. /* Loop for each group of output pixels */
  171730. for (col = cinfo->output_width >> 1; col > 0; col--) {
  171731. /* Do the chroma part of the calculation */
  171732. cb = GETJSAMPLE(*inptr1++);
  171733. cr = GETJSAMPLE(*inptr2++);
  171734. cred = Crrtab[cr];
  171735. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  171736. cblue = Cbbtab[cb];
  171737. /* Fetch 4 Y values and emit 4 pixels */
  171738. y = GETJSAMPLE(*inptr00++);
  171739. outptr0[RGB_RED] = range_limit[y + cred];
  171740. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  171741. outptr0[RGB_BLUE] = range_limit[y + cblue];
  171742. outptr0 += RGB_PIXELSIZE;
  171743. y = GETJSAMPLE(*inptr00++);
  171744. outptr0[RGB_RED] = range_limit[y + cred];
  171745. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  171746. outptr0[RGB_BLUE] = range_limit[y + cblue];
  171747. outptr0 += RGB_PIXELSIZE;
  171748. y = GETJSAMPLE(*inptr01++);
  171749. outptr1[RGB_RED] = range_limit[y + cred];
  171750. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  171751. outptr1[RGB_BLUE] = range_limit[y + cblue];
  171752. outptr1 += RGB_PIXELSIZE;
  171753. y = GETJSAMPLE(*inptr01++);
  171754. outptr1[RGB_RED] = range_limit[y + cred];
  171755. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  171756. outptr1[RGB_BLUE] = range_limit[y + cblue];
  171757. outptr1 += RGB_PIXELSIZE;
  171758. }
  171759. /* If image width is odd, do the last output column separately */
  171760. if (cinfo->output_width & 1) {
  171761. cb = GETJSAMPLE(*inptr1);
  171762. cr = GETJSAMPLE(*inptr2);
  171763. cred = Crrtab[cr];
  171764. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  171765. cblue = Cbbtab[cb];
  171766. y = GETJSAMPLE(*inptr00);
  171767. outptr0[RGB_RED] = range_limit[y + cred];
  171768. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  171769. outptr0[RGB_BLUE] = range_limit[y + cblue];
  171770. y = GETJSAMPLE(*inptr01);
  171771. outptr1[RGB_RED] = range_limit[y + cred];
  171772. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  171773. outptr1[RGB_BLUE] = range_limit[y + cblue];
  171774. }
  171775. }
  171776. /*
  171777. * Module initialization routine for merged upsampling/color conversion.
  171778. *
  171779. * NB: this is called under the conditions determined by use_merged_upsample()
  171780. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  171781. * of this module; no safety checks are made here.
  171782. */
  171783. GLOBAL(void)
  171784. jinit_merged_upsampler (j_decompress_ptr cinfo)
  171785. {
  171786. my_upsample_ptr upsample;
  171787. upsample = (my_upsample_ptr)
  171788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171789. SIZEOF(my_upsampler));
  171790. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  171791. upsample->pub.start_pass = start_pass_merged_upsample;
  171792. upsample->pub.need_context_rows = FALSE;
  171793. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  171794. if (cinfo->max_v_samp_factor == 2) {
  171795. upsample->pub.upsample = merged_2v_upsample;
  171796. upsample->upmethod = h2v2_merged_upsample;
  171797. /* Allocate a spare row buffer */
  171798. upsample->spare_row = (JSAMPROW)
  171799. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171800. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  171801. } else {
  171802. upsample->pub.upsample = merged_1v_upsample;
  171803. upsample->upmethod = h2v1_merged_upsample;
  171804. /* No spare row needed */
  171805. upsample->spare_row = NULL;
  171806. }
  171807. build_ycc_rgb_table2(cinfo);
  171808. }
  171809. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  171810. /*** End of inlined file: jdmerge.c ***/
  171811. #undef ASSIGN_STATE
  171812. /*** Start of inlined file: jdphuff.c ***/
  171813. #define JPEG_INTERNALS
  171814. #ifdef D_PROGRESSIVE_SUPPORTED
  171815. /*
  171816. * Expanded entropy decoder object for progressive Huffman decoding.
  171817. *
  171818. * The savable_state subrecord contains fields that change within an MCU,
  171819. * but must not be updated permanently until we complete the MCU.
  171820. */
  171821. typedef struct {
  171822. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  171823. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  171824. } savable_state3;
  171825. /* This macro is to work around compilers with missing or broken
  171826. * structure assignment. You'll need to fix this code if you have
  171827. * such a compiler and you change MAX_COMPS_IN_SCAN.
  171828. */
  171829. #ifndef NO_STRUCT_ASSIGN
  171830. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  171831. #else
  171832. #if MAX_COMPS_IN_SCAN == 4
  171833. #define ASSIGN_STATE(dest,src) \
  171834. ((dest).EOBRUN = (src).EOBRUN, \
  171835. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  171836. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  171837. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  171838. (dest).last_dc_val[3] = (src).last_dc_val[3])
  171839. #endif
  171840. #endif
  171841. typedef struct {
  171842. struct jpeg_entropy_decoder pub; /* public fields */
  171843. /* These fields are loaded into local variables at start of each MCU.
  171844. * In case of suspension, we exit WITHOUT updating them.
  171845. */
  171846. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  171847. savable_state3 saved; /* Other state at start of MCU */
  171848. /* These fields are NOT loaded into local working state. */
  171849. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  171850. /* Pointers to derived tables (these workspaces have image lifespan) */
  171851. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  171852. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  171853. } phuff_entropy_decoder;
  171854. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  171855. /* Forward declarations */
  171856. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  171857. JBLOCKROW *MCU_data));
  171858. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  171859. JBLOCKROW *MCU_data));
  171860. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  171861. JBLOCKROW *MCU_data));
  171862. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  171863. JBLOCKROW *MCU_data));
  171864. /*
  171865. * Initialize for a Huffman-compressed scan.
  171866. */
  171867. METHODDEF(void)
  171868. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  171869. {
  171870. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  171871. boolean is_DC_band, bad;
  171872. int ci, coefi, tbl;
  171873. int *coef_bit_ptr;
  171874. jpeg_component_info * compptr;
  171875. is_DC_band = (cinfo->Ss == 0);
  171876. /* Validate scan parameters */
  171877. bad = FALSE;
  171878. if (is_DC_band) {
  171879. if (cinfo->Se != 0)
  171880. bad = TRUE;
  171881. } else {
  171882. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  171883. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  171884. bad = TRUE;
  171885. /* AC scans may have only one component */
  171886. if (cinfo->comps_in_scan != 1)
  171887. bad = TRUE;
  171888. }
  171889. if (cinfo->Ah != 0) {
  171890. /* Successive approximation refinement scan: must have Al = Ah-1. */
  171891. if (cinfo->Al != cinfo->Ah-1)
  171892. bad = TRUE;
  171893. }
  171894. if (cinfo->Al > 13) /* need not check for < 0 */
  171895. bad = TRUE;
  171896. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  171897. * but the spec doesn't say so, and we try to be liberal about what we
  171898. * accept. Note: large Al values could result in out-of-range DC
  171899. * coefficients during early scans, leading to bizarre displays due to
  171900. * overflows in the IDCT math. But we won't crash.
  171901. */
  171902. if (bad)
  171903. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  171904. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  171905. /* Update progression status, and verify that scan order is legal.
  171906. * Note that inter-scan inconsistencies are treated as warnings
  171907. * not fatal errors ... not clear if this is right way to behave.
  171908. */
  171909. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  171910. int cindex = cinfo->cur_comp_info[ci]->component_index;
  171911. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  171912. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  171913. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  171914. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  171915. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  171916. if (cinfo->Ah != expected)
  171917. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  171918. coef_bit_ptr[coefi] = cinfo->Al;
  171919. }
  171920. }
  171921. /* Select MCU decoding routine */
  171922. if (cinfo->Ah == 0) {
  171923. if (is_DC_band)
  171924. entropy->pub.decode_mcu = decode_mcu_DC_first;
  171925. else
  171926. entropy->pub.decode_mcu = decode_mcu_AC_first;
  171927. } else {
  171928. if (is_DC_band)
  171929. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  171930. else
  171931. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  171932. }
  171933. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  171934. compptr = cinfo->cur_comp_info[ci];
  171935. /* Make sure requested tables are present, and compute derived tables.
  171936. * We may build same derived table more than once, but it's not expensive.
  171937. */
  171938. if (is_DC_band) {
  171939. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  171940. tbl = compptr->dc_tbl_no;
  171941. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  171942. & entropy->derived_tbls[tbl]);
  171943. }
  171944. } else {
  171945. tbl = compptr->ac_tbl_no;
  171946. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  171947. & entropy->derived_tbls[tbl]);
  171948. /* remember the single active table */
  171949. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  171950. }
  171951. /* Initialize DC predictions to 0 */
  171952. entropy->saved.last_dc_val[ci] = 0;
  171953. }
  171954. /* Initialize bitread state variables */
  171955. entropy->bitstate.bits_left = 0;
  171956. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  171957. entropy->pub.insufficient_data = FALSE;
  171958. /* Initialize private state variables */
  171959. entropy->saved.EOBRUN = 0;
  171960. /* Initialize restart counter */
  171961. entropy->restarts_to_go = cinfo->restart_interval;
  171962. }
  171963. /*
  171964. * Check for a restart marker & resynchronize decoder.
  171965. * Returns FALSE if must suspend.
  171966. */
  171967. LOCAL(boolean)
  171968. process_restartp (j_decompress_ptr cinfo)
  171969. {
  171970. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  171971. int ci;
  171972. /* Throw away any unused bits remaining in bit buffer; */
  171973. /* include any full bytes in next_marker's count of discarded bytes */
  171974. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  171975. entropy->bitstate.bits_left = 0;
  171976. /* Advance past the RSTn marker */
  171977. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  171978. return FALSE;
  171979. /* Re-initialize DC predictions to 0 */
  171980. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  171981. entropy->saved.last_dc_val[ci] = 0;
  171982. /* Re-init EOB run count, too */
  171983. entropy->saved.EOBRUN = 0;
  171984. /* Reset restart counter */
  171985. entropy->restarts_to_go = cinfo->restart_interval;
  171986. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  171987. * against a marker. In that case we will end up treating the next data
  171988. * segment as empty, and we can avoid producing bogus output pixels by
  171989. * leaving the flag set.
  171990. */
  171991. if (cinfo->unread_marker == 0)
  171992. entropy->pub.insufficient_data = FALSE;
  171993. return TRUE;
  171994. }
  171995. /*
  171996. * Huffman MCU decoding.
  171997. * Each of these routines decodes and returns one MCU's worth of
  171998. * Huffman-compressed coefficients.
  171999. * The coefficients are reordered from zigzag order into natural array order,
  172000. * but are not dequantized.
  172001. *
  172002. * The i'th block of the MCU is stored into the block pointed to by
  172003. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172004. *
  172005. * We return FALSE if data source requested suspension. In that case no
  172006. * changes have been made to permanent state. (Exception: some output
  172007. * coefficients may already have been assigned. This is harmless for
  172008. * spectral selection, since we'll just re-assign them on the next call.
  172009. * Successive approximation AC refinement has to be more careful, however.)
  172010. */
  172011. /*
  172012. * MCU decoding for DC initial scan (either spectral selection,
  172013. * or first pass of successive approximation).
  172014. */
  172015. METHODDEF(boolean)
  172016. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172017. {
  172018. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172019. int Al = cinfo->Al;
  172020. register int s, r;
  172021. int blkn, ci;
  172022. JBLOCKROW block;
  172023. BITREAD_STATE_VARS;
  172024. savable_state3 state;
  172025. d_derived_tbl * tbl;
  172026. jpeg_component_info * compptr;
  172027. /* Process restart marker if needed; may have to suspend */
  172028. if (cinfo->restart_interval) {
  172029. if (entropy->restarts_to_go == 0)
  172030. if (! process_restartp(cinfo))
  172031. return FALSE;
  172032. }
  172033. /* If we've run out of data, just leave the MCU set to zeroes.
  172034. * This way, we return uniform gray for the remainder of the segment.
  172035. */
  172036. if (! entropy->pub.insufficient_data) {
  172037. /* Load up working state */
  172038. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172039. ASSIGN_STATE(state, entropy->saved);
  172040. /* Outer loop handles each block in the MCU */
  172041. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172042. block = MCU_data[blkn];
  172043. ci = cinfo->MCU_membership[blkn];
  172044. compptr = cinfo->cur_comp_info[ci];
  172045. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172046. /* Decode a single block's worth of coefficients */
  172047. /* Section F.2.2.1: decode the DC coefficient difference */
  172048. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172049. if (s) {
  172050. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172051. r = GET_BITS(s);
  172052. s = HUFF_EXTEND(r, s);
  172053. }
  172054. /* Convert DC difference to actual value, update last_dc_val */
  172055. s += state.last_dc_val[ci];
  172056. state.last_dc_val[ci] = s;
  172057. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172058. (*block)[0] = (JCOEF) (s << Al);
  172059. }
  172060. /* Completed MCU, so update state */
  172061. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172062. ASSIGN_STATE(entropy->saved, state);
  172063. }
  172064. /* Account for restart interval (no-op if not using restarts) */
  172065. entropy->restarts_to_go--;
  172066. return TRUE;
  172067. }
  172068. /*
  172069. * MCU decoding for AC initial scan (either spectral selection,
  172070. * or first pass of successive approximation).
  172071. */
  172072. METHODDEF(boolean)
  172073. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172074. {
  172075. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172076. int Se = cinfo->Se;
  172077. int Al = cinfo->Al;
  172078. register int s, k, r;
  172079. unsigned int EOBRUN;
  172080. JBLOCKROW block;
  172081. BITREAD_STATE_VARS;
  172082. d_derived_tbl * tbl;
  172083. /* Process restart marker if needed; may have to suspend */
  172084. if (cinfo->restart_interval) {
  172085. if (entropy->restarts_to_go == 0)
  172086. if (! process_restartp(cinfo))
  172087. return FALSE;
  172088. }
  172089. /* If we've run out of data, just leave the MCU set to zeroes.
  172090. * This way, we return uniform gray for the remainder of the segment.
  172091. */
  172092. if (! entropy->pub.insufficient_data) {
  172093. /* Load up working state.
  172094. * We can avoid loading/saving bitread state if in an EOB run.
  172095. */
  172096. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172097. /* There is always only one block per MCU */
  172098. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172099. EOBRUN--; /* ...process it now (we do nothing) */
  172100. else {
  172101. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172102. block = MCU_data[0];
  172103. tbl = entropy->ac_derived_tbl;
  172104. for (k = cinfo->Ss; k <= Se; k++) {
  172105. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172106. r = s >> 4;
  172107. s &= 15;
  172108. if (s) {
  172109. k += r;
  172110. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172111. r = GET_BITS(s);
  172112. s = HUFF_EXTEND(r, s);
  172113. /* Scale and output coefficient in natural (dezigzagged) order */
  172114. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172115. } else {
  172116. if (r == 15) { /* ZRL */
  172117. k += 15; /* skip 15 zeroes in band */
  172118. } else { /* EOBr, run length is 2^r + appended bits */
  172119. EOBRUN = 1 << r;
  172120. if (r) { /* EOBr, r > 0 */
  172121. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172122. r = GET_BITS(r);
  172123. EOBRUN += r;
  172124. }
  172125. EOBRUN--; /* this band is processed at this moment */
  172126. break; /* force end-of-band */
  172127. }
  172128. }
  172129. }
  172130. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172131. }
  172132. /* Completed MCU, so update state */
  172133. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172134. }
  172135. /* Account for restart interval (no-op if not using restarts) */
  172136. entropy->restarts_to_go--;
  172137. return TRUE;
  172138. }
  172139. /*
  172140. * MCU decoding for DC successive approximation refinement scan.
  172141. * Note: we assume such scans can be multi-component, although the spec
  172142. * is not very clear on the point.
  172143. */
  172144. METHODDEF(boolean)
  172145. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172146. {
  172147. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172148. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172149. int blkn;
  172150. JBLOCKROW block;
  172151. BITREAD_STATE_VARS;
  172152. /* Process restart marker if needed; may have to suspend */
  172153. if (cinfo->restart_interval) {
  172154. if (entropy->restarts_to_go == 0)
  172155. if (! process_restartp(cinfo))
  172156. return FALSE;
  172157. }
  172158. /* Not worth the cycles to check insufficient_data here,
  172159. * since we will not change the data anyway if we read zeroes.
  172160. */
  172161. /* Load up working state */
  172162. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172163. /* Outer loop handles each block in the MCU */
  172164. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172165. block = MCU_data[blkn];
  172166. /* Encoded data is simply the next bit of the two's-complement DC value */
  172167. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  172168. if (GET_BITS(1))
  172169. (*block)[0] |= p1;
  172170. /* Note: since we use |=, repeating the assignment later is safe */
  172171. }
  172172. /* Completed MCU, so update state */
  172173. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172174. /* Account for restart interval (no-op if not using restarts) */
  172175. entropy->restarts_to_go--;
  172176. return TRUE;
  172177. }
  172178. /*
  172179. * MCU decoding for AC successive approximation refinement scan.
  172180. */
  172181. METHODDEF(boolean)
  172182. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172183. {
  172184. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172185. int Se = cinfo->Se;
  172186. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172187. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  172188. register int s, k, r;
  172189. unsigned int EOBRUN;
  172190. JBLOCKROW block;
  172191. JCOEFPTR thiscoef;
  172192. BITREAD_STATE_VARS;
  172193. d_derived_tbl * tbl;
  172194. int num_newnz;
  172195. int newnz_pos[DCTSIZE2];
  172196. /* Process restart marker if needed; may have to suspend */
  172197. if (cinfo->restart_interval) {
  172198. if (entropy->restarts_to_go == 0)
  172199. if (! process_restartp(cinfo))
  172200. return FALSE;
  172201. }
  172202. /* If we've run out of data, don't modify the MCU.
  172203. */
  172204. if (! entropy->pub.insufficient_data) {
  172205. /* Load up working state */
  172206. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172207. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172208. /* There is always only one block per MCU */
  172209. block = MCU_data[0];
  172210. tbl = entropy->ac_derived_tbl;
  172211. /* If we are forced to suspend, we must undo the assignments to any newly
  172212. * nonzero coefficients in the block, because otherwise we'd get confused
  172213. * next time about which coefficients were already nonzero.
  172214. * But we need not undo addition of bits to already-nonzero coefficients;
  172215. * instead, we can test the current bit to see if we already did it.
  172216. */
  172217. num_newnz = 0;
  172218. /* initialize coefficient loop counter to start of band */
  172219. k = cinfo->Ss;
  172220. if (EOBRUN == 0) {
  172221. for (; k <= Se; k++) {
  172222. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  172223. r = s >> 4;
  172224. s &= 15;
  172225. if (s) {
  172226. if (s != 1) /* size of new coef should always be 1 */
  172227. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  172228. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172229. if (GET_BITS(1))
  172230. s = p1; /* newly nonzero coef is positive */
  172231. else
  172232. s = m1; /* newly nonzero coef is negative */
  172233. } else {
  172234. if (r != 15) {
  172235. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  172236. if (r) {
  172237. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  172238. r = GET_BITS(r);
  172239. EOBRUN += r;
  172240. }
  172241. break; /* rest of block is handled by EOB logic */
  172242. }
  172243. /* note s = 0 for processing ZRL */
  172244. }
  172245. /* Advance over already-nonzero coefs and r still-zero coefs,
  172246. * appending correction bits to the nonzeroes. A correction bit is 1
  172247. * if the absolute value of the coefficient must be increased.
  172248. */
  172249. do {
  172250. thiscoef = *block + jpeg_natural_order[k];
  172251. if (*thiscoef != 0) {
  172252. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172253. if (GET_BITS(1)) {
  172254. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  172255. if (*thiscoef >= 0)
  172256. *thiscoef += p1;
  172257. else
  172258. *thiscoef += m1;
  172259. }
  172260. }
  172261. } else {
  172262. if (--r < 0)
  172263. break; /* reached target zero coefficient */
  172264. }
  172265. k++;
  172266. } while (k <= Se);
  172267. if (s) {
  172268. int pos = jpeg_natural_order[k];
  172269. /* Output newly nonzero coefficient */
  172270. (*block)[pos] = (JCOEF) s;
  172271. /* Remember its position in case we have to suspend */
  172272. newnz_pos[num_newnz++] = pos;
  172273. }
  172274. }
  172275. }
  172276. if (EOBRUN > 0) {
  172277. /* Scan any remaining coefficient positions after the end-of-band
  172278. * (the last newly nonzero coefficient, if any). Append a correction
  172279. * bit to each already-nonzero coefficient. A correction bit is 1
  172280. * if the absolute value of the coefficient must be increased.
  172281. */
  172282. for (; k <= Se; k++) {
  172283. thiscoef = *block + jpeg_natural_order[k];
  172284. if (*thiscoef != 0) {
  172285. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172286. if (GET_BITS(1)) {
  172287. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  172288. if (*thiscoef >= 0)
  172289. *thiscoef += p1;
  172290. else
  172291. *thiscoef += m1;
  172292. }
  172293. }
  172294. }
  172295. }
  172296. /* Count one block completed in EOB run */
  172297. EOBRUN--;
  172298. }
  172299. /* Completed MCU, so update state */
  172300. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172301. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172302. }
  172303. /* Account for restart interval (no-op if not using restarts) */
  172304. entropy->restarts_to_go--;
  172305. return TRUE;
  172306. undoit:
  172307. /* Re-zero any output coefficients that we made newly nonzero */
  172308. while (num_newnz > 0)
  172309. (*block)[newnz_pos[--num_newnz]] = 0;
  172310. return FALSE;
  172311. }
  172312. /*
  172313. * Module initialization routine for progressive Huffman entropy decoding.
  172314. */
  172315. GLOBAL(void)
  172316. jinit_phuff_decoder (j_decompress_ptr cinfo)
  172317. {
  172318. phuff_entropy_ptr2 entropy;
  172319. int *coef_bit_ptr;
  172320. int ci, i;
  172321. entropy = (phuff_entropy_ptr2)
  172322. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172323. SIZEOF(phuff_entropy_decoder));
  172324. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  172325. entropy->pub.start_pass = start_pass_phuff_decoder;
  172326. /* Mark derived tables unallocated */
  172327. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  172328. entropy->derived_tbls[i] = NULL;
  172329. }
  172330. /* Create progression status table */
  172331. cinfo->coef_bits = (int (*)[DCTSIZE2])
  172332. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172333. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  172334. coef_bit_ptr = & cinfo->coef_bits[0][0];
  172335. for (ci = 0; ci < cinfo->num_components; ci++)
  172336. for (i = 0; i < DCTSIZE2; i++)
  172337. *coef_bit_ptr++ = -1;
  172338. }
  172339. #endif /* D_PROGRESSIVE_SUPPORTED */
  172340. /*** End of inlined file: jdphuff.c ***/
  172341. /*** Start of inlined file: jdpostct.c ***/
  172342. #define JPEG_INTERNALS
  172343. /* Private buffer controller object */
  172344. typedef struct {
  172345. struct jpeg_d_post_controller pub; /* public fields */
  172346. /* Color quantization source buffer: this holds output data from
  172347. * the upsample/color conversion step to be passed to the quantizer.
  172348. * For two-pass color quantization, we need a full-image buffer;
  172349. * for one-pass operation, a strip buffer is sufficient.
  172350. */
  172351. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  172352. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  172353. JDIMENSION strip_height; /* buffer size in rows */
  172354. /* for two-pass mode only: */
  172355. JDIMENSION starting_row; /* row # of first row in current strip */
  172356. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  172357. } my_post_controller;
  172358. typedef my_post_controller * my_post_ptr;
  172359. /* Forward declarations */
  172360. METHODDEF(void) post_process_1pass
  172361. JPP((j_decompress_ptr cinfo,
  172362. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172363. JDIMENSION in_row_groups_avail,
  172364. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172365. JDIMENSION out_rows_avail));
  172366. #ifdef QUANT_2PASS_SUPPORTED
  172367. METHODDEF(void) post_process_prepass
  172368. JPP((j_decompress_ptr cinfo,
  172369. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172370. JDIMENSION in_row_groups_avail,
  172371. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172372. JDIMENSION out_rows_avail));
  172373. METHODDEF(void) post_process_2pass
  172374. JPP((j_decompress_ptr cinfo,
  172375. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172376. JDIMENSION in_row_groups_avail,
  172377. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172378. JDIMENSION out_rows_avail));
  172379. #endif
  172380. /*
  172381. * Initialize for a processing pass.
  172382. */
  172383. METHODDEF(void)
  172384. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  172385. {
  172386. my_post_ptr post = (my_post_ptr) cinfo->post;
  172387. switch (pass_mode) {
  172388. case JBUF_PASS_THRU:
  172389. if (cinfo->quantize_colors) {
  172390. /* Single-pass processing with color quantization. */
  172391. post->pub.post_process_data = post_process_1pass;
  172392. /* We could be doing buffered-image output before starting a 2-pass
  172393. * color quantization; in that case, jinit_d_post_controller did not
  172394. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  172395. */
  172396. if (post->buffer == NULL) {
  172397. post->buffer = (*cinfo->mem->access_virt_sarray)
  172398. ((j_common_ptr) cinfo, post->whole_image,
  172399. (JDIMENSION) 0, post->strip_height, TRUE);
  172400. }
  172401. } else {
  172402. /* For single-pass processing without color quantization,
  172403. * I have no work to do; just call the upsampler directly.
  172404. */
  172405. post->pub.post_process_data = cinfo->upsample->upsample;
  172406. }
  172407. break;
  172408. #ifdef QUANT_2PASS_SUPPORTED
  172409. case JBUF_SAVE_AND_PASS:
  172410. /* First pass of 2-pass quantization */
  172411. if (post->whole_image == NULL)
  172412. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172413. post->pub.post_process_data = post_process_prepass;
  172414. break;
  172415. case JBUF_CRANK_DEST:
  172416. /* Second pass of 2-pass quantization */
  172417. if (post->whole_image == NULL)
  172418. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172419. post->pub.post_process_data = post_process_2pass;
  172420. break;
  172421. #endif /* QUANT_2PASS_SUPPORTED */
  172422. default:
  172423. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172424. break;
  172425. }
  172426. post->starting_row = post->next_row = 0;
  172427. }
  172428. /*
  172429. * Process some data in the one-pass (strip buffer) case.
  172430. * This is used for color precision reduction as well as one-pass quantization.
  172431. */
  172432. METHODDEF(void)
  172433. post_process_1pass (j_decompress_ptr cinfo,
  172434. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172435. JDIMENSION in_row_groups_avail,
  172436. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172437. JDIMENSION out_rows_avail)
  172438. {
  172439. my_post_ptr post = (my_post_ptr) cinfo->post;
  172440. JDIMENSION num_rows, max_rows;
  172441. /* Fill the buffer, but not more than what we can dump out in one go. */
  172442. /* Note we rely on the upsampler to detect bottom of image. */
  172443. max_rows = out_rows_avail - *out_row_ctr;
  172444. if (max_rows > post->strip_height)
  172445. max_rows = post->strip_height;
  172446. num_rows = 0;
  172447. (*cinfo->upsample->upsample) (cinfo,
  172448. input_buf, in_row_group_ctr, in_row_groups_avail,
  172449. post->buffer, &num_rows, max_rows);
  172450. /* Quantize and emit data. */
  172451. (*cinfo->cquantize->color_quantize) (cinfo,
  172452. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  172453. *out_row_ctr += num_rows;
  172454. }
  172455. #ifdef QUANT_2PASS_SUPPORTED
  172456. /*
  172457. * Process some data in the first pass of 2-pass quantization.
  172458. */
  172459. METHODDEF(void)
  172460. post_process_prepass (j_decompress_ptr cinfo,
  172461. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172462. JDIMENSION in_row_groups_avail,
  172463. JSAMPARRAY, JDIMENSION *out_row_ctr,
  172464. JDIMENSION)
  172465. {
  172466. my_post_ptr post = (my_post_ptr) cinfo->post;
  172467. JDIMENSION old_next_row, num_rows;
  172468. /* Reposition virtual buffer if at start of strip. */
  172469. if (post->next_row == 0) {
  172470. post->buffer = (*cinfo->mem->access_virt_sarray)
  172471. ((j_common_ptr) cinfo, post->whole_image,
  172472. post->starting_row, post->strip_height, TRUE);
  172473. }
  172474. /* Upsample some data (up to a strip height's worth). */
  172475. old_next_row = post->next_row;
  172476. (*cinfo->upsample->upsample) (cinfo,
  172477. input_buf, in_row_group_ctr, in_row_groups_avail,
  172478. post->buffer, &post->next_row, post->strip_height);
  172479. /* Allow quantizer to scan new data. No data is emitted, */
  172480. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  172481. if (post->next_row > old_next_row) {
  172482. num_rows = post->next_row - old_next_row;
  172483. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  172484. (JSAMPARRAY) NULL, (int) num_rows);
  172485. *out_row_ctr += num_rows;
  172486. }
  172487. /* Advance if we filled the strip. */
  172488. if (post->next_row >= post->strip_height) {
  172489. post->starting_row += post->strip_height;
  172490. post->next_row = 0;
  172491. }
  172492. }
  172493. /*
  172494. * Process some data in the second pass of 2-pass quantization.
  172495. */
  172496. METHODDEF(void)
  172497. post_process_2pass (j_decompress_ptr cinfo,
  172498. JSAMPIMAGE, JDIMENSION *,
  172499. JDIMENSION,
  172500. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172501. JDIMENSION out_rows_avail)
  172502. {
  172503. my_post_ptr post = (my_post_ptr) cinfo->post;
  172504. JDIMENSION num_rows, max_rows;
  172505. /* Reposition virtual buffer if at start of strip. */
  172506. if (post->next_row == 0) {
  172507. post->buffer = (*cinfo->mem->access_virt_sarray)
  172508. ((j_common_ptr) cinfo, post->whole_image,
  172509. post->starting_row, post->strip_height, FALSE);
  172510. }
  172511. /* Determine number of rows to emit. */
  172512. num_rows = post->strip_height - post->next_row; /* available in strip */
  172513. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  172514. if (num_rows > max_rows)
  172515. num_rows = max_rows;
  172516. /* We have to check bottom of image here, can't depend on upsampler. */
  172517. max_rows = cinfo->output_height - post->starting_row;
  172518. if (num_rows > max_rows)
  172519. num_rows = max_rows;
  172520. /* Quantize and emit data. */
  172521. (*cinfo->cquantize->color_quantize) (cinfo,
  172522. post->buffer + post->next_row, output_buf + *out_row_ctr,
  172523. (int) num_rows);
  172524. *out_row_ctr += num_rows;
  172525. /* Advance if we filled the strip. */
  172526. post->next_row += num_rows;
  172527. if (post->next_row >= post->strip_height) {
  172528. post->starting_row += post->strip_height;
  172529. post->next_row = 0;
  172530. }
  172531. }
  172532. #endif /* QUANT_2PASS_SUPPORTED */
  172533. /*
  172534. * Initialize postprocessing controller.
  172535. */
  172536. GLOBAL(void)
  172537. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  172538. {
  172539. my_post_ptr post;
  172540. post = (my_post_ptr)
  172541. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172542. SIZEOF(my_post_controller));
  172543. cinfo->post = (struct jpeg_d_post_controller *) post;
  172544. post->pub.start_pass = start_pass_dpost;
  172545. post->whole_image = NULL; /* flag for no virtual arrays */
  172546. post->buffer = NULL; /* flag for no strip buffer */
  172547. /* Create the quantization buffer, if needed */
  172548. if (cinfo->quantize_colors) {
  172549. /* The buffer strip height is max_v_samp_factor, which is typically
  172550. * an efficient number of rows for upsampling to return.
  172551. * (In the presence of output rescaling, we might want to be smarter?)
  172552. */
  172553. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  172554. if (need_full_buffer) {
  172555. /* Two-pass color quantization: need full-image storage. */
  172556. /* We round up the number of rows to a multiple of the strip height. */
  172557. #ifdef QUANT_2PASS_SUPPORTED
  172558. post->whole_image = (*cinfo->mem->request_virt_sarray)
  172559. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  172560. cinfo->output_width * cinfo->out_color_components,
  172561. (JDIMENSION) jround_up((long) cinfo->output_height,
  172562. (long) post->strip_height),
  172563. post->strip_height);
  172564. #else
  172565. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172566. #endif /* QUANT_2PASS_SUPPORTED */
  172567. } else {
  172568. /* One-pass color quantization: just make a strip buffer. */
  172569. post->buffer = (*cinfo->mem->alloc_sarray)
  172570. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172571. cinfo->output_width * cinfo->out_color_components,
  172572. post->strip_height);
  172573. }
  172574. }
  172575. }
  172576. /*** End of inlined file: jdpostct.c ***/
  172577. #undef FIX
  172578. /*** Start of inlined file: jdsample.c ***/
  172579. #define JPEG_INTERNALS
  172580. /* Pointer to routine to upsample a single component */
  172581. typedef JMETHOD(void, upsample1_ptr,
  172582. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172583. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  172584. /* Private subobject */
  172585. typedef struct {
  172586. struct jpeg_upsampler pub; /* public fields */
  172587. /* Color conversion buffer. When using separate upsampling and color
  172588. * conversion steps, this buffer holds one upsampled row group until it
  172589. * has been color converted and output.
  172590. * Note: we do not allocate any storage for component(s) which are full-size,
  172591. * ie do not need rescaling. The corresponding entry of color_buf[] is
  172592. * simply set to point to the input data array, thereby avoiding copying.
  172593. */
  172594. JSAMPARRAY color_buf[MAX_COMPONENTS];
  172595. /* Per-component upsampling method pointers */
  172596. upsample1_ptr methods[MAX_COMPONENTS];
  172597. int next_row_out; /* counts rows emitted from color_buf */
  172598. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172599. /* Height of an input row group for each component. */
  172600. int rowgroup_height[MAX_COMPONENTS];
  172601. /* These arrays save pixel expansion factors so that int_expand need not
  172602. * recompute them each time. They are unused for other upsampling methods.
  172603. */
  172604. UINT8 h_expand[MAX_COMPONENTS];
  172605. UINT8 v_expand[MAX_COMPONENTS];
  172606. } my_upsampler2;
  172607. typedef my_upsampler2 * my_upsample_ptr2;
  172608. /*
  172609. * Initialize for an upsampling pass.
  172610. */
  172611. METHODDEF(void)
  172612. start_pass_upsample (j_decompress_ptr cinfo)
  172613. {
  172614. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  172615. /* Mark the conversion buffer empty */
  172616. upsample->next_row_out = cinfo->max_v_samp_factor;
  172617. /* Initialize total-height counter for detecting bottom of image */
  172618. upsample->rows_to_go = cinfo->output_height;
  172619. }
  172620. /*
  172621. * Control routine to do upsampling (and color conversion).
  172622. *
  172623. * In this version we upsample each component independently.
  172624. * We upsample one row group into the conversion buffer, then apply
  172625. * color conversion a row at a time.
  172626. */
  172627. METHODDEF(void)
  172628. sep_upsample (j_decompress_ptr cinfo,
  172629. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172630. JDIMENSION,
  172631. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172632. JDIMENSION out_rows_avail)
  172633. {
  172634. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  172635. int ci;
  172636. jpeg_component_info * compptr;
  172637. JDIMENSION num_rows;
  172638. /* Fill the conversion buffer, if it's empty */
  172639. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  172640. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172641. ci++, compptr++) {
  172642. /* Invoke per-component upsample method. Notice we pass a POINTER
  172643. * to color_buf[ci], so that fullsize_upsample can change it.
  172644. */
  172645. (*upsample->methods[ci]) (cinfo, compptr,
  172646. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  172647. upsample->color_buf + ci);
  172648. }
  172649. upsample->next_row_out = 0;
  172650. }
  172651. /* Color-convert and emit rows */
  172652. /* How many we have in the buffer: */
  172653. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  172654. /* Not more than the distance to the end of the image. Need this test
  172655. * in case the image height is not a multiple of max_v_samp_factor:
  172656. */
  172657. if (num_rows > upsample->rows_to_go)
  172658. num_rows = upsample->rows_to_go;
  172659. /* And not more than what the client can accept: */
  172660. out_rows_avail -= *out_row_ctr;
  172661. if (num_rows > out_rows_avail)
  172662. num_rows = out_rows_avail;
  172663. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  172664. (JDIMENSION) upsample->next_row_out,
  172665. output_buf + *out_row_ctr,
  172666. (int) num_rows);
  172667. /* Adjust counts */
  172668. *out_row_ctr += num_rows;
  172669. upsample->rows_to_go -= num_rows;
  172670. upsample->next_row_out += num_rows;
  172671. /* When the buffer is emptied, declare this input row group consumed */
  172672. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  172673. (*in_row_group_ctr)++;
  172674. }
  172675. /*
  172676. * These are the routines invoked by sep_upsample to upsample pixel values
  172677. * of a single component. One row group is processed per call.
  172678. */
  172679. /*
  172680. * For full-size components, we just make color_buf[ci] point at the
  172681. * input buffer, and thus avoid copying any data. Note that this is
  172682. * safe only because sep_upsample doesn't declare the input row group
  172683. * "consumed" until we are done color converting and emitting it.
  172684. */
  172685. METHODDEF(void)
  172686. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  172687. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172688. {
  172689. *output_data_ptr = input_data;
  172690. }
  172691. /*
  172692. * This is a no-op version used for "uninteresting" components.
  172693. * These components will not be referenced by color conversion.
  172694. */
  172695. METHODDEF(void)
  172696. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  172697. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  172698. {
  172699. *output_data_ptr = NULL; /* safety check */
  172700. }
  172701. /*
  172702. * This version handles any integral sampling ratios.
  172703. * This is not used for typical JPEG files, so it need not be fast.
  172704. * Nor, for that matter, is it particularly accurate: the algorithm is
  172705. * simple replication of the input pixel onto the corresponding output
  172706. * pixels. The hi-falutin sampling literature refers to this as a
  172707. * "box filter". A box filter tends to introduce visible artifacts,
  172708. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  172709. * you would be well advised to improve this code.
  172710. */
  172711. METHODDEF(void)
  172712. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172713. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172714. {
  172715. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  172716. JSAMPARRAY output_data = *output_data_ptr;
  172717. register JSAMPROW inptr, outptr;
  172718. register JSAMPLE invalue;
  172719. register int h;
  172720. JSAMPROW outend;
  172721. int h_expand, v_expand;
  172722. int inrow, outrow;
  172723. h_expand = upsample->h_expand[compptr->component_index];
  172724. v_expand = upsample->v_expand[compptr->component_index];
  172725. inrow = outrow = 0;
  172726. while (outrow < cinfo->max_v_samp_factor) {
  172727. /* Generate one output row with proper horizontal expansion */
  172728. inptr = input_data[inrow];
  172729. outptr = output_data[outrow];
  172730. outend = outptr + cinfo->output_width;
  172731. while (outptr < outend) {
  172732. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  172733. for (h = h_expand; h > 0; h--) {
  172734. *outptr++ = invalue;
  172735. }
  172736. }
  172737. /* Generate any additional output rows by duplicating the first one */
  172738. if (v_expand > 1) {
  172739. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  172740. v_expand-1, cinfo->output_width);
  172741. }
  172742. inrow++;
  172743. outrow += v_expand;
  172744. }
  172745. }
  172746. /*
  172747. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  172748. * It's still a box filter.
  172749. */
  172750. METHODDEF(void)
  172751. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  172752. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172753. {
  172754. JSAMPARRAY output_data = *output_data_ptr;
  172755. register JSAMPROW inptr, outptr;
  172756. register JSAMPLE invalue;
  172757. JSAMPROW outend;
  172758. int inrow;
  172759. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  172760. inptr = input_data[inrow];
  172761. outptr = output_data[inrow];
  172762. outend = outptr + cinfo->output_width;
  172763. while (outptr < outend) {
  172764. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  172765. *outptr++ = invalue;
  172766. *outptr++ = invalue;
  172767. }
  172768. }
  172769. }
  172770. /*
  172771. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  172772. * It's still a box filter.
  172773. */
  172774. METHODDEF(void)
  172775. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  172776. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172777. {
  172778. JSAMPARRAY output_data = *output_data_ptr;
  172779. register JSAMPROW inptr, outptr;
  172780. register JSAMPLE invalue;
  172781. JSAMPROW outend;
  172782. int inrow, outrow;
  172783. inrow = outrow = 0;
  172784. while (outrow < cinfo->max_v_samp_factor) {
  172785. inptr = input_data[inrow];
  172786. outptr = output_data[outrow];
  172787. outend = outptr + cinfo->output_width;
  172788. while (outptr < outend) {
  172789. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  172790. *outptr++ = invalue;
  172791. *outptr++ = invalue;
  172792. }
  172793. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  172794. 1, cinfo->output_width);
  172795. inrow++;
  172796. outrow += 2;
  172797. }
  172798. }
  172799. /*
  172800. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  172801. *
  172802. * The upsampling algorithm is linear interpolation between pixel centers,
  172803. * also known as a "triangle filter". This is a good compromise between
  172804. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  172805. * of the way between input pixel centers.
  172806. *
  172807. * A note about the "bias" calculations: when rounding fractional values to
  172808. * integer, we do not want to always round 0.5 up to the next integer.
  172809. * If we did that, we'd introduce a noticeable bias towards larger values.
  172810. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  172811. * alternate pixel locations (a simple ordered dither pattern).
  172812. */
  172813. METHODDEF(void)
  172814. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172815. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172816. {
  172817. JSAMPARRAY output_data = *output_data_ptr;
  172818. register JSAMPROW inptr, outptr;
  172819. register int invalue;
  172820. register JDIMENSION colctr;
  172821. int inrow;
  172822. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  172823. inptr = input_data[inrow];
  172824. outptr = output_data[inrow];
  172825. /* Special case for first column */
  172826. invalue = GETJSAMPLE(*inptr++);
  172827. *outptr++ = (JSAMPLE) invalue;
  172828. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  172829. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  172830. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  172831. invalue = GETJSAMPLE(*inptr++) * 3;
  172832. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  172833. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  172834. }
  172835. /* Special case for last column */
  172836. invalue = GETJSAMPLE(*inptr);
  172837. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  172838. *outptr++ = (JSAMPLE) invalue;
  172839. }
  172840. }
  172841. /*
  172842. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  172843. * Again a triangle filter; see comments for h2v1 case, above.
  172844. *
  172845. * It is OK for us to reference the adjacent input rows because we demanded
  172846. * context from the main buffer controller (see initialization code).
  172847. */
  172848. METHODDEF(void)
  172849. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172850. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172851. {
  172852. JSAMPARRAY output_data = *output_data_ptr;
  172853. register JSAMPROW inptr0, inptr1, outptr;
  172854. #if BITS_IN_JSAMPLE == 8
  172855. register int thiscolsum, lastcolsum, nextcolsum;
  172856. #else
  172857. register INT32 thiscolsum, lastcolsum, nextcolsum;
  172858. #endif
  172859. register JDIMENSION colctr;
  172860. int inrow, outrow, v;
  172861. inrow = outrow = 0;
  172862. while (outrow < cinfo->max_v_samp_factor) {
  172863. for (v = 0; v < 2; v++) {
  172864. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  172865. inptr0 = input_data[inrow];
  172866. if (v == 0) /* next nearest is row above */
  172867. inptr1 = input_data[inrow-1];
  172868. else /* next nearest is row below */
  172869. inptr1 = input_data[inrow+1];
  172870. outptr = output_data[outrow++];
  172871. /* Special case for first column */
  172872. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  172873. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  172874. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  172875. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  172876. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  172877. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  172878. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  172879. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  172880. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  172881. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  172882. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  172883. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  172884. }
  172885. /* Special case for last column */
  172886. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  172887. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  172888. }
  172889. inrow++;
  172890. }
  172891. }
  172892. /*
  172893. * Module initialization routine for upsampling.
  172894. */
  172895. GLOBAL(void)
  172896. jinit_upsampler (j_decompress_ptr cinfo)
  172897. {
  172898. my_upsample_ptr2 upsample;
  172899. int ci;
  172900. jpeg_component_info * compptr;
  172901. boolean need_buffer, do_fancy;
  172902. int h_in_group, v_in_group, h_out_group, v_out_group;
  172903. upsample = (my_upsample_ptr2)
  172904. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172905. SIZEOF(my_upsampler2));
  172906. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172907. upsample->pub.start_pass = start_pass_upsample;
  172908. upsample->pub.upsample = sep_upsample;
  172909. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  172910. if (cinfo->CCIR601_sampling) /* this isn't supported */
  172911. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  172912. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  172913. * so don't ask for it.
  172914. */
  172915. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  172916. /* Verify we can handle the sampling factors, select per-component methods,
  172917. * and create storage as needed.
  172918. */
  172919. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172920. ci++, compptr++) {
  172921. /* Compute size of an "input group" after IDCT scaling. This many samples
  172922. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  172923. */
  172924. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  172925. cinfo->min_DCT_scaled_size;
  172926. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  172927. cinfo->min_DCT_scaled_size;
  172928. h_out_group = cinfo->max_h_samp_factor;
  172929. v_out_group = cinfo->max_v_samp_factor;
  172930. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  172931. need_buffer = TRUE;
  172932. if (! compptr->component_needed) {
  172933. /* Don't bother to upsample an uninteresting component. */
  172934. upsample->methods[ci] = noop_upsample;
  172935. need_buffer = FALSE;
  172936. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  172937. /* Fullsize components can be processed without any work. */
  172938. upsample->methods[ci] = fullsize_upsample;
  172939. need_buffer = FALSE;
  172940. } else if (h_in_group * 2 == h_out_group &&
  172941. v_in_group == v_out_group) {
  172942. /* Special cases for 2h1v upsampling */
  172943. if (do_fancy && compptr->downsampled_width > 2)
  172944. upsample->methods[ci] = h2v1_fancy_upsample;
  172945. else
  172946. upsample->methods[ci] = h2v1_upsample;
  172947. } else if (h_in_group * 2 == h_out_group &&
  172948. v_in_group * 2 == v_out_group) {
  172949. /* Special cases for 2h2v upsampling */
  172950. if (do_fancy && compptr->downsampled_width > 2) {
  172951. upsample->methods[ci] = h2v2_fancy_upsample;
  172952. upsample->pub.need_context_rows = TRUE;
  172953. } else
  172954. upsample->methods[ci] = h2v2_upsample;
  172955. } else if ((h_out_group % h_in_group) == 0 &&
  172956. (v_out_group % v_in_group) == 0) {
  172957. /* Generic integral-factors upsampling method */
  172958. upsample->methods[ci] = int_upsample;
  172959. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  172960. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  172961. } else
  172962. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  172963. if (need_buffer) {
  172964. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  172965. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172966. (JDIMENSION) jround_up((long) cinfo->output_width,
  172967. (long) cinfo->max_h_samp_factor),
  172968. (JDIMENSION) cinfo->max_v_samp_factor);
  172969. }
  172970. }
  172971. }
  172972. /*** End of inlined file: jdsample.c ***/
  172973. /*** Start of inlined file: jdtrans.c ***/
  172974. #define JPEG_INTERNALS
  172975. /* Forward declarations */
  172976. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  172977. /*
  172978. * Read the coefficient arrays from a JPEG file.
  172979. * jpeg_read_header must be completed before calling this.
  172980. *
  172981. * The entire image is read into a set of virtual coefficient-block arrays,
  172982. * one per component. The return value is a pointer to the array of
  172983. * virtual-array descriptors. These can be manipulated directly via the
  172984. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  172985. * To release the memory occupied by the virtual arrays, call
  172986. * jpeg_finish_decompress() when done with the data.
  172987. *
  172988. * An alternative usage is to simply obtain access to the coefficient arrays
  172989. * during a buffered-image-mode decompression operation. This is allowed
  172990. * after any jpeg_finish_output() call. The arrays can be accessed until
  172991. * jpeg_finish_decompress() is called. (Note that any call to the library
  172992. * may reposition the arrays, so don't rely on access_virt_barray() results
  172993. * to stay valid across library calls.)
  172994. *
  172995. * Returns NULL if suspended. This case need be checked only if
  172996. * a suspending data source is used.
  172997. */
  172998. GLOBAL(jvirt_barray_ptr *)
  172999. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173000. {
  173001. if (cinfo->global_state == DSTATE_READY) {
  173002. /* First call: initialize active modules */
  173003. transdecode_master_selection(cinfo);
  173004. cinfo->global_state = DSTATE_RDCOEFS;
  173005. }
  173006. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173007. /* Absorb whole file into the coef buffer */
  173008. for (;;) {
  173009. int retcode;
  173010. /* Call progress monitor hook if present */
  173011. if (cinfo->progress != NULL)
  173012. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173013. /* Absorb some more input */
  173014. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173015. if (retcode == JPEG_SUSPENDED)
  173016. return NULL;
  173017. if (retcode == JPEG_REACHED_EOI)
  173018. break;
  173019. /* Advance progress counter if appropriate */
  173020. if (cinfo->progress != NULL &&
  173021. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173022. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173023. /* startup underestimated number of scans; ratchet up one scan */
  173024. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173025. }
  173026. }
  173027. }
  173028. /* Set state so that jpeg_finish_decompress does the right thing */
  173029. cinfo->global_state = DSTATE_STOPPING;
  173030. }
  173031. /* At this point we should be in state DSTATE_STOPPING if being used
  173032. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173033. * to the coefficients during a full buffered-image-mode decompression.
  173034. */
  173035. if ((cinfo->global_state == DSTATE_STOPPING ||
  173036. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173037. return cinfo->coef->coef_arrays;
  173038. }
  173039. /* Oops, improper usage */
  173040. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173041. return NULL; /* keep compiler happy */
  173042. }
  173043. /*
  173044. * Master selection of decompression modules for transcoding.
  173045. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173046. */
  173047. LOCAL(void)
  173048. transdecode_master_selection (j_decompress_ptr cinfo)
  173049. {
  173050. /* This is effectively a buffered-image operation. */
  173051. cinfo->buffered_image = TRUE;
  173052. /* Entropy decoding: either Huffman or arithmetic coding. */
  173053. if (cinfo->arith_code) {
  173054. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173055. } else {
  173056. if (cinfo->progressive_mode) {
  173057. #ifdef D_PROGRESSIVE_SUPPORTED
  173058. jinit_phuff_decoder(cinfo);
  173059. #else
  173060. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173061. #endif
  173062. } else
  173063. jinit_huff_decoder(cinfo);
  173064. }
  173065. /* Always get a full-image coefficient buffer. */
  173066. jinit_d_coef_controller(cinfo, TRUE);
  173067. /* We can now tell the memory manager to allocate virtual arrays. */
  173068. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173069. /* Initialize input side of decompressor to consume first scan. */
  173070. (*cinfo->inputctl->start_input_pass) (cinfo);
  173071. /* Initialize progress monitoring. */
  173072. if (cinfo->progress != NULL) {
  173073. int nscans;
  173074. /* Estimate number of scans to set pass_limit. */
  173075. if (cinfo->progressive_mode) {
  173076. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173077. nscans = 2 + 3 * cinfo->num_components;
  173078. } else if (cinfo->inputctl->has_multiple_scans) {
  173079. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173080. nscans = cinfo->num_components;
  173081. } else {
  173082. nscans = 1;
  173083. }
  173084. cinfo->progress->pass_counter = 0L;
  173085. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173086. cinfo->progress->completed_passes = 0;
  173087. cinfo->progress->total_passes = 1;
  173088. }
  173089. }
  173090. /*** End of inlined file: jdtrans.c ***/
  173091. /*** Start of inlined file: jfdctflt.c ***/
  173092. #define JPEG_INTERNALS
  173093. #ifdef DCT_FLOAT_SUPPORTED
  173094. /*
  173095. * This module is specialized to the case DCTSIZE = 8.
  173096. */
  173097. #if DCTSIZE != 8
  173098. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173099. #endif
  173100. /*
  173101. * Perform the forward DCT on one block of samples.
  173102. */
  173103. GLOBAL(void)
  173104. jpeg_fdct_float (FAST_FLOAT * data)
  173105. {
  173106. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173107. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173108. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173109. FAST_FLOAT *dataptr;
  173110. int ctr;
  173111. /* Pass 1: process rows. */
  173112. dataptr = data;
  173113. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173114. tmp0 = dataptr[0] + dataptr[7];
  173115. tmp7 = dataptr[0] - dataptr[7];
  173116. tmp1 = dataptr[1] + dataptr[6];
  173117. tmp6 = dataptr[1] - dataptr[6];
  173118. tmp2 = dataptr[2] + dataptr[5];
  173119. tmp5 = dataptr[2] - dataptr[5];
  173120. tmp3 = dataptr[3] + dataptr[4];
  173121. tmp4 = dataptr[3] - dataptr[4];
  173122. /* Even part */
  173123. tmp10 = tmp0 + tmp3; /* phase 2 */
  173124. tmp13 = tmp0 - tmp3;
  173125. tmp11 = tmp1 + tmp2;
  173126. tmp12 = tmp1 - tmp2;
  173127. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173128. dataptr[4] = tmp10 - tmp11;
  173129. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173130. dataptr[2] = tmp13 + z1; /* phase 5 */
  173131. dataptr[6] = tmp13 - z1;
  173132. /* Odd part */
  173133. tmp10 = tmp4 + tmp5; /* phase 2 */
  173134. tmp11 = tmp5 + tmp6;
  173135. tmp12 = tmp6 + tmp7;
  173136. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173137. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173138. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173139. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173140. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173141. z11 = tmp7 + z3; /* phase 5 */
  173142. z13 = tmp7 - z3;
  173143. dataptr[5] = z13 + z2; /* phase 6 */
  173144. dataptr[3] = z13 - z2;
  173145. dataptr[1] = z11 + z4;
  173146. dataptr[7] = z11 - z4;
  173147. dataptr += DCTSIZE; /* advance pointer to next row */
  173148. }
  173149. /* Pass 2: process columns. */
  173150. dataptr = data;
  173151. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173152. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173153. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173154. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173155. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173156. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173157. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173158. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173159. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173160. /* Even part */
  173161. tmp10 = tmp0 + tmp3; /* phase 2 */
  173162. tmp13 = tmp0 - tmp3;
  173163. tmp11 = tmp1 + tmp2;
  173164. tmp12 = tmp1 - tmp2;
  173165. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173166. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173167. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173168. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173169. dataptr[DCTSIZE*6] = tmp13 - z1;
  173170. /* Odd part */
  173171. tmp10 = tmp4 + tmp5; /* phase 2 */
  173172. tmp11 = tmp5 + tmp6;
  173173. tmp12 = tmp6 + tmp7;
  173174. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173175. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173176. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173177. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173178. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173179. z11 = tmp7 + z3; /* phase 5 */
  173180. z13 = tmp7 - z3;
  173181. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173182. dataptr[DCTSIZE*3] = z13 - z2;
  173183. dataptr[DCTSIZE*1] = z11 + z4;
  173184. dataptr[DCTSIZE*7] = z11 - z4;
  173185. dataptr++; /* advance pointer to next column */
  173186. }
  173187. }
  173188. #endif /* DCT_FLOAT_SUPPORTED */
  173189. /*** End of inlined file: jfdctflt.c ***/
  173190. /*** Start of inlined file: jfdctint.c ***/
  173191. #define JPEG_INTERNALS
  173192. #ifdef DCT_ISLOW_SUPPORTED
  173193. /*
  173194. * This module is specialized to the case DCTSIZE = 8.
  173195. */
  173196. #if DCTSIZE != 8
  173197. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173198. #endif
  173199. /*
  173200. * The poop on this scaling stuff is as follows:
  173201. *
  173202. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  173203. * larger than the true DCT outputs. The final outputs are therefore
  173204. * a factor of N larger than desired; since N=8 this can be cured by
  173205. * a simple right shift at the end of the algorithm. The advantage of
  173206. * this arrangement is that we save two multiplications per 1-D DCT,
  173207. * because the y0 and y4 outputs need not be divided by sqrt(N).
  173208. * In the IJG code, this factor of 8 is removed by the quantization step
  173209. * (in jcdctmgr.c), NOT in this module.
  173210. *
  173211. * We have to do addition and subtraction of the integer inputs, which
  173212. * is no problem, and multiplication by fractional constants, which is
  173213. * a problem to do in integer arithmetic. We multiply all the constants
  173214. * by CONST_SCALE and convert them to integer constants (thus retaining
  173215. * CONST_BITS bits of precision in the constants). After doing a
  173216. * multiplication we have to divide the product by CONST_SCALE, with proper
  173217. * rounding, to produce the correct output. This division can be done
  173218. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  173219. * as long as possible so that partial sums can be added together with
  173220. * full fractional precision.
  173221. *
  173222. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  173223. * they are represented to better-than-integral precision. These outputs
  173224. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  173225. * with the recommended scaling. (For 12-bit sample data, the intermediate
  173226. * array is INT32 anyway.)
  173227. *
  173228. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  173229. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  173230. * shows that the values given below are the most effective.
  173231. */
  173232. #if BITS_IN_JSAMPLE == 8
  173233. #define CONST_BITS 13
  173234. #define PASS1_BITS 2
  173235. #else
  173236. #define CONST_BITS 13
  173237. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  173238. #endif
  173239. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173240. * causing a lot of useless floating-point operations at run time.
  173241. * To get around this we use the following pre-calculated constants.
  173242. * If you change CONST_BITS you may want to add appropriate values.
  173243. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173244. */
  173245. #if CONST_BITS == 13
  173246. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  173247. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  173248. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  173249. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  173250. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  173251. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  173252. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  173253. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  173254. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  173255. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  173256. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  173257. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  173258. #else
  173259. #define FIX_0_298631336 FIX(0.298631336)
  173260. #define FIX_0_390180644 FIX(0.390180644)
  173261. #define FIX_0_541196100 FIX(0.541196100)
  173262. #define FIX_0_765366865 FIX(0.765366865)
  173263. #define FIX_0_899976223 FIX(0.899976223)
  173264. #define FIX_1_175875602 FIX(1.175875602)
  173265. #define FIX_1_501321110 FIX(1.501321110)
  173266. #define FIX_1_847759065 FIX(1.847759065)
  173267. #define FIX_1_961570560 FIX(1.961570560)
  173268. #define FIX_2_053119869 FIX(2.053119869)
  173269. #define FIX_2_562915447 FIX(2.562915447)
  173270. #define FIX_3_072711026 FIX(3.072711026)
  173271. #endif
  173272. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  173273. * For 8-bit samples with the recommended scaling, all the variable
  173274. * and constant values involved are no more than 16 bits wide, so a
  173275. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  173276. * For 12-bit samples, a full 32-bit multiplication will be needed.
  173277. */
  173278. #if BITS_IN_JSAMPLE == 8
  173279. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  173280. #else
  173281. #define MULTIPLY(var,const) ((var) * (const))
  173282. #endif
  173283. /*
  173284. * Perform the forward DCT on one block of samples.
  173285. */
  173286. GLOBAL(void)
  173287. jpeg_fdct_islow (DCTELEM * data)
  173288. {
  173289. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173290. INT32 tmp10, tmp11, tmp12, tmp13;
  173291. INT32 z1, z2, z3, z4, z5;
  173292. DCTELEM *dataptr;
  173293. int ctr;
  173294. SHIFT_TEMPS
  173295. /* Pass 1: process rows. */
  173296. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  173297. /* furthermore, we scale the results by 2**PASS1_BITS. */
  173298. dataptr = data;
  173299. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173300. tmp0 = dataptr[0] + dataptr[7];
  173301. tmp7 = dataptr[0] - dataptr[7];
  173302. tmp1 = dataptr[1] + dataptr[6];
  173303. tmp6 = dataptr[1] - dataptr[6];
  173304. tmp2 = dataptr[2] + dataptr[5];
  173305. tmp5 = dataptr[2] - dataptr[5];
  173306. tmp3 = dataptr[3] + dataptr[4];
  173307. tmp4 = dataptr[3] - dataptr[4];
  173308. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173309. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173310. */
  173311. tmp10 = tmp0 + tmp3;
  173312. tmp13 = tmp0 - tmp3;
  173313. tmp11 = tmp1 + tmp2;
  173314. tmp12 = tmp1 - tmp2;
  173315. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  173316. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  173317. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173318. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173319. CONST_BITS-PASS1_BITS);
  173320. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173321. CONST_BITS-PASS1_BITS);
  173322. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173323. * cK represents cos(K*pi/16).
  173324. * i0..i3 in the paper are tmp4..tmp7 here.
  173325. */
  173326. z1 = tmp4 + tmp7;
  173327. z2 = tmp5 + tmp6;
  173328. z3 = tmp4 + tmp6;
  173329. z4 = tmp5 + tmp7;
  173330. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173331. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173332. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173333. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173334. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173335. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173336. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173337. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173338. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173339. z3 += z5;
  173340. z4 += z5;
  173341. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  173342. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  173343. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  173344. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  173345. dataptr += DCTSIZE; /* advance pointer to next row */
  173346. }
  173347. /* Pass 2: process columns.
  173348. * We remove the PASS1_BITS scaling, but leave the results scaled up
  173349. * by an overall factor of 8.
  173350. */
  173351. dataptr = data;
  173352. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173353. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173354. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173355. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173356. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173357. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173358. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173359. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173360. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173361. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173362. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173363. */
  173364. tmp10 = tmp0 + tmp3;
  173365. tmp13 = tmp0 - tmp3;
  173366. tmp11 = tmp1 + tmp2;
  173367. tmp12 = tmp1 - tmp2;
  173368. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  173369. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  173370. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173371. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173372. CONST_BITS+PASS1_BITS);
  173373. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173374. CONST_BITS+PASS1_BITS);
  173375. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173376. * cK represents cos(K*pi/16).
  173377. * i0..i3 in the paper are tmp4..tmp7 here.
  173378. */
  173379. z1 = tmp4 + tmp7;
  173380. z2 = tmp5 + tmp6;
  173381. z3 = tmp4 + tmp6;
  173382. z4 = tmp5 + tmp7;
  173383. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173384. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173385. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173386. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173387. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173388. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173389. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173390. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173391. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173392. z3 += z5;
  173393. z4 += z5;
  173394. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  173395. CONST_BITS+PASS1_BITS);
  173396. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  173397. CONST_BITS+PASS1_BITS);
  173398. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  173399. CONST_BITS+PASS1_BITS);
  173400. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  173401. CONST_BITS+PASS1_BITS);
  173402. dataptr++; /* advance pointer to next column */
  173403. }
  173404. }
  173405. #endif /* DCT_ISLOW_SUPPORTED */
  173406. /*** End of inlined file: jfdctint.c ***/
  173407. #undef CONST_BITS
  173408. #undef MULTIPLY
  173409. #undef FIX_0_541196100
  173410. /*** Start of inlined file: jfdctfst.c ***/
  173411. #define JPEG_INTERNALS
  173412. #ifdef DCT_IFAST_SUPPORTED
  173413. /*
  173414. * This module is specialized to the case DCTSIZE = 8.
  173415. */
  173416. #if DCTSIZE != 8
  173417. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173418. #endif
  173419. /* Scaling decisions are generally the same as in the LL&M algorithm;
  173420. * see jfdctint.c for more details. However, we choose to descale
  173421. * (right shift) multiplication products as soon as they are formed,
  173422. * rather than carrying additional fractional bits into subsequent additions.
  173423. * This compromises accuracy slightly, but it lets us save a few shifts.
  173424. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  173425. * everywhere except in the multiplications proper; this saves a good deal
  173426. * of work on 16-bit-int machines.
  173427. *
  173428. * Again to save a few shifts, the intermediate results between pass 1 and
  173429. * pass 2 are not upscaled, but are represented only to integral precision.
  173430. *
  173431. * A final compromise is to represent the multiplicative constants to only
  173432. * 8 fractional bits, rather than 13. This saves some shifting work on some
  173433. * machines, and may also reduce the cost of multiplication (since there
  173434. * are fewer one-bits in the constants).
  173435. */
  173436. #define CONST_BITS 8
  173437. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173438. * causing a lot of useless floating-point operations at run time.
  173439. * To get around this we use the following pre-calculated constants.
  173440. * If you change CONST_BITS you may want to add appropriate values.
  173441. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173442. */
  173443. #if CONST_BITS == 8
  173444. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  173445. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  173446. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  173447. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  173448. #else
  173449. #define FIX_0_382683433 FIX(0.382683433)
  173450. #define FIX_0_541196100 FIX(0.541196100)
  173451. #define FIX_0_707106781 FIX(0.707106781)
  173452. #define FIX_1_306562965 FIX(1.306562965)
  173453. #endif
  173454. /* We can gain a little more speed, with a further compromise in accuracy,
  173455. * by omitting the addition in a descaling shift. This yields an incorrectly
  173456. * rounded result half the time...
  173457. */
  173458. #ifndef USE_ACCURATE_ROUNDING
  173459. #undef DESCALE
  173460. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  173461. #endif
  173462. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  173463. * descale to yield a DCTELEM result.
  173464. */
  173465. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  173466. /*
  173467. * Perform the forward DCT on one block of samples.
  173468. */
  173469. GLOBAL(void)
  173470. jpeg_fdct_ifast (DCTELEM * data)
  173471. {
  173472. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173473. DCTELEM tmp10, tmp11, tmp12, tmp13;
  173474. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  173475. DCTELEM *dataptr;
  173476. int ctr;
  173477. SHIFT_TEMPS
  173478. /* Pass 1: process rows. */
  173479. dataptr = data;
  173480. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173481. tmp0 = dataptr[0] + dataptr[7];
  173482. tmp7 = dataptr[0] - dataptr[7];
  173483. tmp1 = dataptr[1] + dataptr[6];
  173484. tmp6 = dataptr[1] - dataptr[6];
  173485. tmp2 = dataptr[2] + dataptr[5];
  173486. tmp5 = dataptr[2] - dataptr[5];
  173487. tmp3 = dataptr[3] + dataptr[4];
  173488. tmp4 = dataptr[3] - dataptr[4];
  173489. /* Even part */
  173490. tmp10 = tmp0 + tmp3; /* phase 2 */
  173491. tmp13 = tmp0 - tmp3;
  173492. tmp11 = tmp1 + tmp2;
  173493. tmp12 = tmp1 - tmp2;
  173494. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173495. dataptr[4] = tmp10 - tmp11;
  173496. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  173497. dataptr[2] = tmp13 + z1; /* phase 5 */
  173498. dataptr[6] = tmp13 - z1;
  173499. /* Odd part */
  173500. tmp10 = tmp4 + tmp5; /* phase 2 */
  173501. tmp11 = tmp5 + tmp6;
  173502. tmp12 = tmp6 + tmp7;
  173503. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173504. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  173505. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  173506. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  173507. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  173508. z11 = tmp7 + z3; /* phase 5 */
  173509. z13 = tmp7 - z3;
  173510. dataptr[5] = z13 + z2; /* phase 6 */
  173511. dataptr[3] = z13 - z2;
  173512. dataptr[1] = z11 + z4;
  173513. dataptr[7] = z11 - z4;
  173514. dataptr += DCTSIZE; /* advance pointer to next row */
  173515. }
  173516. /* Pass 2: process columns. */
  173517. dataptr = data;
  173518. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173519. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173520. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173521. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173522. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173523. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173524. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173525. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173526. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173527. /* Even part */
  173528. tmp10 = tmp0 + tmp3; /* phase 2 */
  173529. tmp13 = tmp0 - tmp3;
  173530. tmp11 = tmp1 + tmp2;
  173531. tmp12 = tmp1 - tmp2;
  173532. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173533. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173534. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  173535. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173536. dataptr[DCTSIZE*6] = tmp13 - z1;
  173537. /* Odd part */
  173538. tmp10 = tmp4 + tmp5; /* phase 2 */
  173539. tmp11 = tmp5 + tmp6;
  173540. tmp12 = tmp6 + tmp7;
  173541. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173542. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  173543. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  173544. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  173545. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  173546. z11 = tmp7 + z3; /* phase 5 */
  173547. z13 = tmp7 - z3;
  173548. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173549. dataptr[DCTSIZE*3] = z13 - z2;
  173550. dataptr[DCTSIZE*1] = z11 + z4;
  173551. dataptr[DCTSIZE*7] = z11 - z4;
  173552. dataptr++; /* advance pointer to next column */
  173553. }
  173554. }
  173555. #endif /* DCT_IFAST_SUPPORTED */
  173556. /*** End of inlined file: jfdctfst.c ***/
  173557. #undef FIX_0_541196100
  173558. /*** Start of inlined file: jidctflt.c ***/
  173559. #define JPEG_INTERNALS
  173560. #ifdef DCT_FLOAT_SUPPORTED
  173561. /*
  173562. * This module is specialized to the case DCTSIZE = 8.
  173563. */
  173564. #if DCTSIZE != 8
  173565. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173566. #endif
  173567. /* Dequantize a coefficient by multiplying it by the multiplier-table
  173568. * entry; produce a float result.
  173569. */
  173570. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  173571. /*
  173572. * Perform dequantization and inverse DCT on one block of coefficients.
  173573. */
  173574. GLOBAL(void)
  173575. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173576. JCOEFPTR coef_block,
  173577. JSAMPARRAY output_buf, JDIMENSION output_col)
  173578. {
  173579. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173580. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173581. FAST_FLOAT z5, z10, z11, z12, z13;
  173582. JCOEFPTR inptr;
  173583. FLOAT_MULT_TYPE * quantptr;
  173584. FAST_FLOAT * wsptr;
  173585. JSAMPROW outptr;
  173586. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  173587. int ctr;
  173588. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  173589. SHIFT_TEMPS
  173590. /* Pass 1: process columns from input, store into work array. */
  173591. inptr = coef_block;
  173592. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  173593. wsptr = workspace;
  173594. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  173595. /* Due to quantization, we will usually find that many of the input
  173596. * coefficients are zero, especially the AC terms. We can exploit this
  173597. * by short-circuiting the IDCT calculation for any column in which all
  173598. * the AC terms are zero. In that case each output is equal to the
  173599. * DC coefficient (with scale factor as needed).
  173600. * With typical images and quantization tables, half or more of the
  173601. * column DCT calculations can be simplified this way.
  173602. */
  173603. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  173604. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  173605. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  173606. inptr[DCTSIZE*7] == 0) {
  173607. /* AC terms all zero */
  173608. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  173609. wsptr[DCTSIZE*0] = dcval;
  173610. wsptr[DCTSIZE*1] = dcval;
  173611. wsptr[DCTSIZE*2] = dcval;
  173612. wsptr[DCTSIZE*3] = dcval;
  173613. wsptr[DCTSIZE*4] = dcval;
  173614. wsptr[DCTSIZE*5] = dcval;
  173615. wsptr[DCTSIZE*6] = dcval;
  173616. wsptr[DCTSIZE*7] = dcval;
  173617. inptr++; /* advance pointers to next column */
  173618. quantptr++;
  173619. wsptr++;
  173620. continue;
  173621. }
  173622. /* Even part */
  173623. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  173624. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  173625. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  173626. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  173627. tmp10 = tmp0 + tmp2; /* phase 3 */
  173628. tmp11 = tmp0 - tmp2;
  173629. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  173630. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  173631. tmp0 = tmp10 + tmp13; /* phase 2 */
  173632. tmp3 = tmp10 - tmp13;
  173633. tmp1 = tmp11 + tmp12;
  173634. tmp2 = tmp11 - tmp12;
  173635. /* Odd part */
  173636. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  173637. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  173638. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  173639. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  173640. z13 = tmp6 + tmp5; /* phase 6 */
  173641. z10 = tmp6 - tmp5;
  173642. z11 = tmp4 + tmp7;
  173643. z12 = tmp4 - tmp7;
  173644. tmp7 = z11 + z13; /* phase 5 */
  173645. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  173646. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  173647. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  173648. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  173649. tmp6 = tmp12 - tmp7; /* phase 2 */
  173650. tmp5 = tmp11 - tmp6;
  173651. tmp4 = tmp10 + tmp5;
  173652. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  173653. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  173654. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  173655. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  173656. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  173657. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  173658. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  173659. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  173660. inptr++; /* advance pointers to next column */
  173661. quantptr++;
  173662. wsptr++;
  173663. }
  173664. /* Pass 2: process rows from work array, store into output array. */
  173665. /* Note that we must descale the results by a factor of 8 == 2**3. */
  173666. wsptr = workspace;
  173667. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  173668. outptr = output_buf[ctr] + output_col;
  173669. /* Rows of zeroes can be exploited in the same way as we did with columns.
  173670. * However, the column calculation has created many nonzero AC terms, so
  173671. * the simplification applies less often (typically 5% to 10% of the time).
  173672. * And testing floats for zero is relatively expensive, so we don't bother.
  173673. */
  173674. /* Even part */
  173675. tmp10 = wsptr[0] + wsptr[4];
  173676. tmp11 = wsptr[0] - wsptr[4];
  173677. tmp13 = wsptr[2] + wsptr[6];
  173678. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  173679. tmp0 = tmp10 + tmp13;
  173680. tmp3 = tmp10 - tmp13;
  173681. tmp1 = tmp11 + tmp12;
  173682. tmp2 = tmp11 - tmp12;
  173683. /* Odd part */
  173684. z13 = wsptr[5] + wsptr[3];
  173685. z10 = wsptr[5] - wsptr[3];
  173686. z11 = wsptr[1] + wsptr[7];
  173687. z12 = wsptr[1] - wsptr[7];
  173688. tmp7 = z11 + z13;
  173689. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  173690. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  173691. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  173692. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  173693. tmp6 = tmp12 - tmp7;
  173694. tmp5 = tmp11 - tmp6;
  173695. tmp4 = tmp10 + tmp5;
  173696. /* Final output stage: scale down by a factor of 8 and range-limit */
  173697. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  173698. & RANGE_MASK];
  173699. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  173700. & RANGE_MASK];
  173701. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  173702. & RANGE_MASK];
  173703. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  173704. & RANGE_MASK];
  173705. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  173706. & RANGE_MASK];
  173707. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  173708. & RANGE_MASK];
  173709. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  173710. & RANGE_MASK];
  173711. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  173712. & RANGE_MASK];
  173713. wsptr += DCTSIZE; /* advance pointer to next row */
  173714. }
  173715. }
  173716. #endif /* DCT_FLOAT_SUPPORTED */
  173717. /*** End of inlined file: jidctflt.c ***/
  173718. #undef CONST_BITS
  173719. #undef FIX_1_847759065
  173720. #undef MULTIPLY
  173721. #undef DEQUANTIZE
  173722. #undef DESCALE
  173723. /*** Start of inlined file: jidctfst.c ***/
  173724. #define JPEG_INTERNALS
  173725. #ifdef DCT_IFAST_SUPPORTED
  173726. /*
  173727. * This module is specialized to the case DCTSIZE = 8.
  173728. */
  173729. #if DCTSIZE != 8
  173730. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173731. #endif
  173732. /* Scaling decisions are generally the same as in the LL&M algorithm;
  173733. * see jidctint.c for more details. However, we choose to descale
  173734. * (right shift) multiplication products as soon as they are formed,
  173735. * rather than carrying additional fractional bits into subsequent additions.
  173736. * This compromises accuracy slightly, but it lets us save a few shifts.
  173737. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  173738. * everywhere except in the multiplications proper; this saves a good deal
  173739. * of work on 16-bit-int machines.
  173740. *
  173741. * The dequantized coefficients are not integers because the AA&N scaling
  173742. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  173743. * so that the first and second IDCT rounds have the same input scaling.
  173744. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  173745. * avoid a descaling shift; this compromises accuracy rather drastically
  173746. * for small quantization table entries, but it saves a lot of shifts.
  173747. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  173748. * so we use a much larger scaling factor to preserve accuracy.
  173749. *
  173750. * A final compromise is to represent the multiplicative constants to only
  173751. * 8 fractional bits, rather than 13. This saves some shifting work on some
  173752. * machines, and may also reduce the cost of multiplication (since there
  173753. * are fewer one-bits in the constants).
  173754. */
  173755. #if BITS_IN_JSAMPLE == 8
  173756. #define CONST_BITS 8
  173757. #define PASS1_BITS 2
  173758. #else
  173759. #define CONST_BITS 8
  173760. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  173761. #endif
  173762. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173763. * causing a lot of useless floating-point operations at run time.
  173764. * To get around this we use the following pre-calculated constants.
  173765. * If you change CONST_BITS you may want to add appropriate values.
  173766. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173767. */
  173768. #if CONST_BITS == 8
  173769. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  173770. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  173771. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  173772. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  173773. #else
  173774. #define FIX_1_082392200 FIX(1.082392200)
  173775. #define FIX_1_414213562 FIX(1.414213562)
  173776. #define FIX_1_847759065 FIX(1.847759065)
  173777. #define FIX_2_613125930 FIX(2.613125930)
  173778. #endif
  173779. /* We can gain a little more speed, with a further compromise in accuracy,
  173780. * by omitting the addition in a descaling shift. This yields an incorrectly
  173781. * rounded result half the time...
  173782. */
  173783. #ifndef USE_ACCURATE_ROUNDING
  173784. #undef DESCALE
  173785. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  173786. #endif
  173787. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  173788. * descale to yield a DCTELEM result.
  173789. */
  173790. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  173791. /* Dequantize a coefficient by multiplying it by the multiplier-table
  173792. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  173793. * multiplication will do. For 12-bit data, the multiplier table is
  173794. * declared INT32, so a 32-bit multiply will be used.
  173795. */
  173796. #if BITS_IN_JSAMPLE == 8
  173797. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  173798. #else
  173799. #define DEQUANTIZE(coef,quantval) \
  173800. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  173801. #endif
  173802. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  173803. * We assume that int right shift is unsigned if INT32 right shift is.
  173804. */
  173805. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  173806. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  173807. #if BITS_IN_JSAMPLE == 8
  173808. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  173809. #else
  173810. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  173811. #endif
  173812. #define IRIGHT_SHIFT(x,shft) \
  173813. ((ishift_temp = (x)) < 0 ? \
  173814. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  173815. (ishift_temp >> (shft)))
  173816. #else
  173817. #define ISHIFT_TEMPS
  173818. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  173819. #endif
  173820. #ifdef USE_ACCURATE_ROUNDING
  173821. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  173822. #else
  173823. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  173824. #endif
  173825. /*
  173826. * Perform dequantization and inverse DCT on one block of coefficients.
  173827. */
  173828. GLOBAL(void)
  173829. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173830. JCOEFPTR coef_block,
  173831. JSAMPARRAY output_buf, JDIMENSION output_col)
  173832. {
  173833. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173834. DCTELEM tmp10, tmp11, tmp12, tmp13;
  173835. DCTELEM z5, z10, z11, z12, z13;
  173836. JCOEFPTR inptr;
  173837. IFAST_MULT_TYPE * quantptr;
  173838. int * wsptr;
  173839. JSAMPROW outptr;
  173840. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  173841. int ctr;
  173842. int workspace[DCTSIZE2]; /* buffers data between passes */
  173843. SHIFT_TEMPS /* for DESCALE */
  173844. ISHIFT_TEMPS /* for IDESCALE */
  173845. /* Pass 1: process columns from input, store into work array. */
  173846. inptr = coef_block;
  173847. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  173848. wsptr = workspace;
  173849. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  173850. /* Due to quantization, we will usually find that many of the input
  173851. * coefficients are zero, especially the AC terms. We can exploit this
  173852. * by short-circuiting the IDCT calculation for any column in which all
  173853. * the AC terms are zero. In that case each output is equal to the
  173854. * DC coefficient (with scale factor as needed).
  173855. * With typical images and quantization tables, half or more of the
  173856. * column DCT calculations can be simplified this way.
  173857. */
  173858. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  173859. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  173860. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  173861. inptr[DCTSIZE*7] == 0) {
  173862. /* AC terms all zero */
  173863. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  173864. wsptr[DCTSIZE*0] = dcval;
  173865. wsptr[DCTSIZE*1] = dcval;
  173866. wsptr[DCTSIZE*2] = dcval;
  173867. wsptr[DCTSIZE*3] = dcval;
  173868. wsptr[DCTSIZE*4] = dcval;
  173869. wsptr[DCTSIZE*5] = dcval;
  173870. wsptr[DCTSIZE*6] = dcval;
  173871. wsptr[DCTSIZE*7] = dcval;
  173872. inptr++; /* advance pointers to next column */
  173873. quantptr++;
  173874. wsptr++;
  173875. continue;
  173876. }
  173877. /* Even part */
  173878. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  173879. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  173880. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  173881. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  173882. tmp10 = tmp0 + tmp2; /* phase 3 */
  173883. tmp11 = tmp0 - tmp2;
  173884. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  173885. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  173886. tmp0 = tmp10 + tmp13; /* phase 2 */
  173887. tmp3 = tmp10 - tmp13;
  173888. tmp1 = tmp11 + tmp12;
  173889. tmp2 = tmp11 - tmp12;
  173890. /* Odd part */
  173891. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  173892. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  173893. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  173894. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  173895. z13 = tmp6 + tmp5; /* phase 6 */
  173896. z10 = tmp6 - tmp5;
  173897. z11 = tmp4 + tmp7;
  173898. z12 = tmp4 - tmp7;
  173899. tmp7 = z11 + z13; /* phase 5 */
  173900. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  173901. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  173902. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  173903. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  173904. tmp6 = tmp12 - tmp7; /* phase 2 */
  173905. tmp5 = tmp11 - tmp6;
  173906. tmp4 = tmp10 + tmp5;
  173907. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  173908. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  173909. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  173910. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  173911. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  173912. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  173913. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  173914. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  173915. inptr++; /* advance pointers to next column */
  173916. quantptr++;
  173917. wsptr++;
  173918. }
  173919. /* Pass 2: process rows from work array, store into output array. */
  173920. /* Note that we must descale the results by a factor of 8 == 2**3, */
  173921. /* and also undo the PASS1_BITS scaling. */
  173922. wsptr = workspace;
  173923. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  173924. outptr = output_buf[ctr] + output_col;
  173925. /* Rows of zeroes can be exploited in the same way as we did with columns.
  173926. * However, the column calculation has created many nonzero AC terms, so
  173927. * the simplification applies less often (typically 5% to 10% of the time).
  173928. * On machines with very fast multiplication, it's possible that the
  173929. * test takes more time than it's worth. In that case this section
  173930. * may be commented out.
  173931. */
  173932. #ifndef NO_ZERO_ROW_TEST
  173933. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  173934. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  173935. /* AC terms all zero */
  173936. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  173937. & RANGE_MASK];
  173938. outptr[0] = dcval;
  173939. outptr[1] = dcval;
  173940. outptr[2] = dcval;
  173941. outptr[3] = dcval;
  173942. outptr[4] = dcval;
  173943. outptr[5] = dcval;
  173944. outptr[6] = dcval;
  173945. outptr[7] = dcval;
  173946. wsptr += DCTSIZE; /* advance pointer to next row */
  173947. continue;
  173948. }
  173949. #endif
  173950. /* Even part */
  173951. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  173952. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  173953. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  173954. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  173955. - tmp13;
  173956. tmp0 = tmp10 + tmp13;
  173957. tmp3 = tmp10 - tmp13;
  173958. tmp1 = tmp11 + tmp12;
  173959. tmp2 = tmp11 - tmp12;
  173960. /* Odd part */
  173961. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  173962. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  173963. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  173964. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  173965. tmp7 = z11 + z13; /* phase 5 */
  173966. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  173967. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  173968. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  173969. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  173970. tmp6 = tmp12 - tmp7; /* phase 2 */
  173971. tmp5 = tmp11 - tmp6;
  173972. tmp4 = tmp10 + tmp5;
  173973. /* Final output stage: scale down by a factor of 8 and range-limit */
  173974. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  173975. & RANGE_MASK];
  173976. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  173977. & RANGE_MASK];
  173978. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  173979. & RANGE_MASK];
  173980. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  173981. & RANGE_MASK];
  173982. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  173983. & RANGE_MASK];
  173984. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  173985. & RANGE_MASK];
  173986. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  173987. & RANGE_MASK];
  173988. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  173989. & RANGE_MASK];
  173990. wsptr += DCTSIZE; /* advance pointer to next row */
  173991. }
  173992. }
  173993. #endif /* DCT_IFAST_SUPPORTED */
  173994. /*** End of inlined file: jidctfst.c ***/
  173995. #undef CONST_BITS
  173996. #undef FIX_1_847759065
  173997. #undef MULTIPLY
  173998. #undef DEQUANTIZE
  173999. /*** Start of inlined file: jidctint.c ***/
  174000. #define JPEG_INTERNALS
  174001. #ifdef DCT_ISLOW_SUPPORTED
  174002. /*
  174003. * This module is specialized to the case DCTSIZE = 8.
  174004. */
  174005. #if DCTSIZE != 8
  174006. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174007. #endif
  174008. /*
  174009. * The poop on this scaling stuff is as follows:
  174010. *
  174011. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174012. * larger than the true IDCT outputs. The final outputs are therefore
  174013. * a factor of N larger than desired; since N=8 this can be cured by
  174014. * a simple right shift at the end of the algorithm. The advantage of
  174015. * this arrangement is that we save two multiplications per 1-D IDCT,
  174016. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174017. *
  174018. * We have to do addition and subtraction of the integer inputs, which
  174019. * is no problem, and multiplication by fractional constants, which is
  174020. * a problem to do in integer arithmetic. We multiply all the constants
  174021. * by CONST_SCALE and convert them to integer constants (thus retaining
  174022. * CONST_BITS bits of precision in the constants). After doing a
  174023. * multiplication we have to divide the product by CONST_SCALE, with proper
  174024. * rounding, to produce the correct output. This division can be done
  174025. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174026. * as long as possible so that partial sums can be added together with
  174027. * full fractional precision.
  174028. *
  174029. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174030. * they are represented to better-than-integral precision. These outputs
  174031. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174032. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174033. * intermediate INT32 array would be needed.)
  174034. *
  174035. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174036. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174037. * shows that the values given below are the most effective.
  174038. */
  174039. #if BITS_IN_JSAMPLE == 8
  174040. #define CONST_BITS 13
  174041. #define PASS1_BITS 2
  174042. #else
  174043. #define CONST_BITS 13
  174044. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174045. #endif
  174046. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174047. * causing a lot of useless floating-point operations at run time.
  174048. * To get around this we use the following pre-calculated constants.
  174049. * If you change CONST_BITS you may want to add appropriate values.
  174050. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174051. */
  174052. #if CONST_BITS == 13
  174053. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174054. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174055. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174056. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174057. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174058. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174059. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174060. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174061. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174062. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174063. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174064. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174065. #else
  174066. #define FIX_0_298631336 FIX(0.298631336)
  174067. #define FIX_0_390180644 FIX(0.390180644)
  174068. #define FIX_0_541196100 FIX(0.541196100)
  174069. #define FIX_0_765366865 FIX(0.765366865)
  174070. #define FIX_0_899976223 FIX(0.899976223)
  174071. #define FIX_1_175875602 FIX(1.175875602)
  174072. #define FIX_1_501321110 FIX(1.501321110)
  174073. #define FIX_1_847759065 FIX(1.847759065)
  174074. #define FIX_1_961570560 FIX(1.961570560)
  174075. #define FIX_2_053119869 FIX(2.053119869)
  174076. #define FIX_2_562915447 FIX(2.562915447)
  174077. #define FIX_3_072711026 FIX(3.072711026)
  174078. #endif
  174079. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174080. * For 8-bit samples with the recommended scaling, all the variable
  174081. * and constant values involved are no more than 16 bits wide, so a
  174082. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174083. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174084. */
  174085. #if BITS_IN_JSAMPLE == 8
  174086. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174087. #else
  174088. #define MULTIPLY(var,const) ((var) * (const))
  174089. #endif
  174090. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174091. * entry; produce an int result. In this module, both inputs and result
  174092. * are 16 bits or less, so either int or short multiply will work.
  174093. */
  174094. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174095. /*
  174096. * Perform dequantization and inverse DCT on one block of coefficients.
  174097. */
  174098. GLOBAL(void)
  174099. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174100. JCOEFPTR coef_block,
  174101. JSAMPARRAY output_buf, JDIMENSION output_col)
  174102. {
  174103. INT32 tmp0, tmp1, tmp2, tmp3;
  174104. INT32 tmp10, tmp11, tmp12, tmp13;
  174105. INT32 z1, z2, z3, z4, z5;
  174106. JCOEFPTR inptr;
  174107. ISLOW_MULT_TYPE * quantptr;
  174108. int * wsptr;
  174109. JSAMPROW outptr;
  174110. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174111. int ctr;
  174112. int workspace[DCTSIZE2]; /* buffers data between passes */
  174113. SHIFT_TEMPS
  174114. /* Pass 1: process columns from input, store into work array. */
  174115. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174116. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174117. inptr = coef_block;
  174118. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174119. wsptr = workspace;
  174120. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174121. /* Due to quantization, we will usually find that many of the input
  174122. * coefficients are zero, especially the AC terms. We can exploit this
  174123. * by short-circuiting the IDCT calculation for any column in which all
  174124. * the AC terms are zero. In that case each output is equal to the
  174125. * DC coefficient (with scale factor as needed).
  174126. * With typical images and quantization tables, half or more of the
  174127. * column DCT calculations can be simplified this way.
  174128. */
  174129. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174130. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174131. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174132. inptr[DCTSIZE*7] == 0) {
  174133. /* AC terms all zero */
  174134. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174135. wsptr[DCTSIZE*0] = dcval;
  174136. wsptr[DCTSIZE*1] = dcval;
  174137. wsptr[DCTSIZE*2] = dcval;
  174138. wsptr[DCTSIZE*3] = dcval;
  174139. wsptr[DCTSIZE*4] = dcval;
  174140. wsptr[DCTSIZE*5] = dcval;
  174141. wsptr[DCTSIZE*6] = dcval;
  174142. wsptr[DCTSIZE*7] = dcval;
  174143. inptr++; /* advance pointers to next column */
  174144. quantptr++;
  174145. wsptr++;
  174146. continue;
  174147. }
  174148. /* Even part: reverse the even part of the forward DCT. */
  174149. /* The rotator is sqrt(2)*c(-6). */
  174150. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174151. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174152. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174153. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174154. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174155. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174156. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174157. tmp0 = (z2 + z3) << CONST_BITS;
  174158. tmp1 = (z2 - z3) << CONST_BITS;
  174159. tmp10 = tmp0 + tmp3;
  174160. tmp13 = tmp0 - tmp3;
  174161. tmp11 = tmp1 + tmp2;
  174162. tmp12 = tmp1 - tmp2;
  174163. /* Odd part per figure 8; the matrix is unitary and hence its
  174164. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174165. */
  174166. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174167. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174168. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174169. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174170. z1 = tmp0 + tmp3;
  174171. z2 = tmp1 + tmp2;
  174172. z3 = tmp0 + tmp2;
  174173. z4 = tmp1 + tmp3;
  174174. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174175. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174176. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174177. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174178. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174179. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174180. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174181. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174182. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174183. z3 += z5;
  174184. z4 += z5;
  174185. tmp0 += z1 + z3;
  174186. tmp1 += z2 + z4;
  174187. tmp2 += z2 + z3;
  174188. tmp3 += z1 + z4;
  174189. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174190. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  174191. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  174192. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  174193. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  174194. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  174195. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  174196. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  174197. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  174198. inptr++; /* advance pointers to next column */
  174199. quantptr++;
  174200. wsptr++;
  174201. }
  174202. /* Pass 2: process rows from work array, store into output array. */
  174203. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174204. /* and also undo the PASS1_BITS scaling. */
  174205. wsptr = workspace;
  174206. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174207. outptr = output_buf[ctr] + output_col;
  174208. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174209. * However, the column calculation has created many nonzero AC terms, so
  174210. * the simplification applies less often (typically 5% to 10% of the time).
  174211. * On machines with very fast multiplication, it's possible that the
  174212. * test takes more time than it's worth. In that case this section
  174213. * may be commented out.
  174214. */
  174215. #ifndef NO_ZERO_ROW_TEST
  174216. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174217. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174218. /* AC terms all zero */
  174219. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174220. & RANGE_MASK];
  174221. outptr[0] = dcval;
  174222. outptr[1] = dcval;
  174223. outptr[2] = dcval;
  174224. outptr[3] = dcval;
  174225. outptr[4] = dcval;
  174226. outptr[5] = dcval;
  174227. outptr[6] = dcval;
  174228. outptr[7] = dcval;
  174229. wsptr += DCTSIZE; /* advance pointer to next row */
  174230. continue;
  174231. }
  174232. #endif
  174233. /* Even part: reverse the even part of the forward DCT. */
  174234. /* The rotator is sqrt(2)*c(-6). */
  174235. z2 = (INT32) wsptr[2];
  174236. z3 = (INT32) wsptr[6];
  174237. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174238. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174239. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174240. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  174241. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  174242. tmp10 = tmp0 + tmp3;
  174243. tmp13 = tmp0 - tmp3;
  174244. tmp11 = tmp1 + tmp2;
  174245. tmp12 = tmp1 - tmp2;
  174246. /* Odd part per figure 8; the matrix is unitary and hence its
  174247. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174248. */
  174249. tmp0 = (INT32) wsptr[7];
  174250. tmp1 = (INT32) wsptr[5];
  174251. tmp2 = (INT32) wsptr[3];
  174252. tmp3 = (INT32) wsptr[1];
  174253. z1 = tmp0 + tmp3;
  174254. z2 = tmp1 + tmp2;
  174255. z3 = tmp0 + tmp2;
  174256. z4 = tmp1 + tmp3;
  174257. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174258. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174259. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174260. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174261. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174262. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174263. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174264. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174265. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174266. z3 += z5;
  174267. z4 += z5;
  174268. tmp0 += z1 + z3;
  174269. tmp1 += z2 + z4;
  174270. tmp2 += z2 + z3;
  174271. tmp3 += z1 + z4;
  174272. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174273. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  174274. CONST_BITS+PASS1_BITS+3)
  174275. & RANGE_MASK];
  174276. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  174277. CONST_BITS+PASS1_BITS+3)
  174278. & RANGE_MASK];
  174279. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  174280. CONST_BITS+PASS1_BITS+3)
  174281. & RANGE_MASK];
  174282. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  174283. CONST_BITS+PASS1_BITS+3)
  174284. & RANGE_MASK];
  174285. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  174286. CONST_BITS+PASS1_BITS+3)
  174287. & RANGE_MASK];
  174288. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  174289. CONST_BITS+PASS1_BITS+3)
  174290. & RANGE_MASK];
  174291. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  174292. CONST_BITS+PASS1_BITS+3)
  174293. & RANGE_MASK];
  174294. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  174295. CONST_BITS+PASS1_BITS+3)
  174296. & RANGE_MASK];
  174297. wsptr += DCTSIZE; /* advance pointer to next row */
  174298. }
  174299. }
  174300. #endif /* DCT_ISLOW_SUPPORTED */
  174301. /*** End of inlined file: jidctint.c ***/
  174302. /*** Start of inlined file: jidctred.c ***/
  174303. #define JPEG_INTERNALS
  174304. #ifdef IDCT_SCALING_SUPPORTED
  174305. /*
  174306. * This module is specialized to the case DCTSIZE = 8.
  174307. */
  174308. #if DCTSIZE != 8
  174309. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174310. #endif
  174311. /* Scaling is the same as in jidctint.c. */
  174312. #if BITS_IN_JSAMPLE == 8
  174313. #define CONST_BITS 13
  174314. #define PASS1_BITS 2
  174315. #else
  174316. #define CONST_BITS 13
  174317. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174318. #endif
  174319. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174320. * causing a lot of useless floating-point operations at run time.
  174321. * To get around this we use the following pre-calculated constants.
  174322. * If you change CONST_BITS you may want to add appropriate values.
  174323. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174324. */
  174325. #if CONST_BITS == 13
  174326. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  174327. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  174328. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  174329. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  174330. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174331. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  174332. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174333. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  174334. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  174335. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  174336. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174337. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  174338. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174339. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  174340. #else
  174341. #define FIX_0_211164243 FIX(0.211164243)
  174342. #define FIX_0_509795579 FIX(0.509795579)
  174343. #define FIX_0_601344887 FIX(0.601344887)
  174344. #define FIX_0_720959822 FIX(0.720959822)
  174345. #define FIX_0_765366865 FIX(0.765366865)
  174346. #define FIX_0_850430095 FIX(0.850430095)
  174347. #define FIX_0_899976223 FIX(0.899976223)
  174348. #define FIX_1_061594337 FIX(1.061594337)
  174349. #define FIX_1_272758580 FIX(1.272758580)
  174350. #define FIX_1_451774981 FIX(1.451774981)
  174351. #define FIX_1_847759065 FIX(1.847759065)
  174352. #define FIX_2_172734803 FIX(2.172734803)
  174353. #define FIX_2_562915447 FIX(2.562915447)
  174354. #define FIX_3_624509785 FIX(3.624509785)
  174355. #endif
  174356. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174357. * For 8-bit samples with the recommended scaling, all the variable
  174358. * and constant values involved are no more than 16 bits wide, so a
  174359. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174360. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174361. */
  174362. #if BITS_IN_JSAMPLE == 8
  174363. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174364. #else
  174365. #define MULTIPLY(var,const) ((var) * (const))
  174366. #endif
  174367. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174368. * entry; produce an int result. In this module, both inputs and result
  174369. * are 16 bits or less, so either int or short multiply will work.
  174370. */
  174371. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174372. /*
  174373. * Perform dequantization and inverse DCT on one block of coefficients,
  174374. * producing a reduced-size 4x4 output block.
  174375. */
  174376. GLOBAL(void)
  174377. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174378. JCOEFPTR coef_block,
  174379. JSAMPARRAY output_buf, JDIMENSION output_col)
  174380. {
  174381. INT32 tmp0, tmp2, tmp10, tmp12;
  174382. INT32 z1, z2, z3, z4;
  174383. JCOEFPTR inptr;
  174384. ISLOW_MULT_TYPE * quantptr;
  174385. int * wsptr;
  174386. JSAMPROW outptr;
  174387. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174388. int ctr;
  174389. int workspace[DCTSIZE*4]; /* buffers data between passes */
  174390. SHIFT_TEMPS
  174391. /* Pass 1: process columns from input, store into work array. */
  174392. inptr = coef_block;
  174393. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174394. wsptr = workspace;
  174395. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  174396. /* Don't bother to process column 4, because second pass won't use it */
  174397. if (ctr == DCTSIZE-4)
  174398. continue;
  174399. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174400. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  174401. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  174402. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  174403. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174404. wsptr[DCTSIZE*0] = dcval;
  174405. wsptr[DCTSIZE*1] = dcval;
  174406. wsptr[DCTSIZE*2] = dcval;
  174407. wsptr[DCTSIZE*3] = dcval;
  174408. continue;
  174409. }
  174410. /* Even part */
  174411. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174412. tmp0 <<= (CONST_BITS+1);
  174413. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174414. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174415. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  174416. tmp10 = tmp0 + tmp2;
  174417. tmp12 = tmp0 - tmp2;
  174418. /* Odd part */
  174419. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174420. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174421. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174422. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174423. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  174424. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  174425. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  174426. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  174427. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  174428. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  174429. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  174430. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  174431. /* Final output stage */
  174432. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  174433. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  174434. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  174435. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  174436. }
  174437. /* Pass 2: process 4 rows from work array, store into output array. */
  174438. wsptr = workspace;
  174439. for (ctr = 0; ctr < 4; ctr++) {
  174440. outptr = output_buf[ctr] + output_col;
  174441. /* It's not clear whether a zero row test is worthwhile here ... */
  174442. #ifndef NO_ZERO_ROW_TEST
  174443. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  174444. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174445. /* AC terms all zero */
  174446. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174447. & RANGE_MASK];
  174448. outptr[0] = dcval;
  174449. outptr[1] = dcval;
  174450. outptr[2] = dcval;
  174451. outptr[3] = dcval;
  174452. wsptr += DCTSIZE; /* advance pointer to next row */
  174453. continue;
  174454. }
  174455. #endif
  174456. /* Even part */
  174457. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  174458. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  174459. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  174460. tmp10 = tmp0 + tmp2;
  174461. tmp12 = tmp0 - tmp2;
  174462. /* Odd part */
  174463. z1 = (INT32) wsptr[7];
  174464. z2 = (INT32) wsptr[5];
  174465. z3 = (INT32) wsptr[3];
  174466. z4 = (INT32) wsptr[1];
  174467. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  174468. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  174469. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  174470. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  174471. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  174472. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  174473. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  174474. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  174475. /* Final output stage */
  174476. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  174477. CONST_BITS+PASS1_BITS+3+1)
  174478. & RANGE_MASK];
  174479. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  174480. CONST_BITS+PASS1_BITS+3+1)
  174481. & RANGE_MASK];
  174482. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  174483. CONST_BITS+PASS1_BITS+3+1)
  174484. & RANGE_MASK];
  174485. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  174486. CONST_BITS+PASS1_BITS+3+1)
  174487. & RANGE_MASK];
  174488. wsptr += DCTSIZE; /* advance pointer to next row */
  174489. }
  174490. }
  174491. /*
  174492. * Perform dequantization and inverse DCT on one block of coefficients,
  174493. * producing a reduced-size 2x2 output block.
  174494. */
  174495. GLOBAL(void)
  174496. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174497. JCOEFPTR coef_block,
  174498. JSAMPARRAY output_buf, JDIMENSION output_col)
  174499. {
  174500. INT32 tmp0, tmp10, z1;
  174501. JCOEFPTR inptr;
  174502. ISLOW_MULT_TYPE * quantptr;
  174503. int * wsptr;
  174504. JSAMPROW outptr;
  174505. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174506. int ctr;
  174507. int workspace[DCTSIZE*2]; /* buffers data between passes */
  174508. SHIFT_TEMPS
  174509. /* Pass 1: process columns from input, store into work array. */
  174510. inptr = coef_block;
  174511. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174512. wsptr = workspace;
  174513. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  174514. /* Don't bother to process columns 2,4,6 */
  174515. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  174516. continue;
  174517. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  174518. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  174519. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  174520. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174521. wsptr[DCTSIZE*0] = dcval;
  174522. wsptr[DCTSIZE*1] = dcval;
  174523. continue;
  174524. }
  174525. /* Even part */
  174526. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174527. tmp10 = z1 << (CONST_BITS+2);
  174528. /* Odd part */
  174529. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174530. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  174531. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174532. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  174533. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174534. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  174535. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174536. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  174537. /* Final output stage */
  174538. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  174539. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  174540. }
  174541. /* Pass 2: process 2 rows from work array, store into output array. */
  174542. wsptr = workspace;
  174543. for (ctr = 0; ctr < 2; ctr++) {
  174544. outptr = output_buf[ctr] + output_col;
  174545. /* It's not clear whether a zero row test is worthwhile here ... */
  174546. #ifndef NO_ZERO_ROW_TEST
  174547. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  174548. /* AC terms all zero */
  174549. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174550. & RANGE_MASK];
  174551. outptr[0] = dcval;
  174552. outptr[1] = dcval;
  174553. wsptr += DCTSIZE; /* advance pointer to next row */
  174554. continue;
  174555. }
  174556. #endif
  174557. /* Even part */
  174558. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  174559. /* Odd part */
  174560. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  174561. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  174562. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  174563. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  174564. /* Final output stage */
  174565. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  174566. CONST_BITS+PASS1_BITS+3+2)
  174567. & RANGE_MASK];
  174568. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  174569. CONST_BITS+PASS1_BITS+3+2)
  174570. & RANGE_MASK];
  174571. wsptr += DCTSIZE; /* advance pointer to next row */
  174572. }
  174573. }
  174574. /*
  174575. * Perform dequantization and inverse DCT on one block of coefficients,
  174576. * producing a reduced-size 1x1 output block.
  174577. */
  174578. GLOBAL(void)
  174579. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174580. JCOEFPTR coef_block,
  174581. JSAMPARRAY output_buf, JDIMENSION output_col)
  174582. {
  174583. int dcval;
  174584. ISLOW_MULT_TYPE * quantptr;
  174585. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174586. SHIFT_TEMPS
  174587. /* We hardly need an inverse DCT routine for this: just take the
  174588. * average pixel value, which is one-eighth of the DC coefficient.
  174589. */
  174590. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174591. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  174592. dcval = (int) DESCALE((INT32) dcval, 3);
  174593. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  174594. }
  174595. #endif /* IDCT_SCALING_SUPPORTED */
  174596. /*** End of inlined file: jidctred.c ***/
  174597. /*** Start of inlined file: jmemmgr.c ***/
  174598. #define JPEG_INTERNALS
  174599. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  174600. /*** Start of inlined file: jmemsys.h ***/
  174601. #ifndef __jmemsys_h__
  174602. #define __jmemsys_h__
  174603. /* Short forms of external names for systems with brain-damaged linkers. */
  174604. #ifdef NEED_SHORT_EXTERNAL_NAMES
  174605. #define jpeg_get_small jGetSmall
  174606. #define jpeg_free_small jFreeSmall
  174607. #define jpeg_get_large jGetLarge
  174608. #define jpeg_free_large jFreeLarge
  174609. #define jpeg_mem_available jMemAvail
  174610. #define jpeg_open_backing_store jOpenBackStore
  174611. #define jpeg_mem_init jMemInit
  174612. #define jpeg_mem_term jMemTerm
  174613. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  174614. /*
  174615. * These two functions are used to allocate and release small chunks of
  174616. * memory. (Typically the total amount requested through jpeg_get_small is
  174617. * no more than 20K or so; this will be requested in chunks of a few K each.)
  174618. * Behavior should be the same as for the standard library functions malloc
  174619. * and free; in particular, jpeg_get_small must return NULL on failure.
  174620. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  174621. * size of the object being freed, just in case it's needed.
  174622. * On an 80x86 machine using small-data memory model, these manage near heap.
  174623. */
  174624. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  174625. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  174626. size_t sizeofobject));
  174627. /*
  174628. * These two functions are used to allocate and release large chunks of
  174629. * memory (up to the total free space designated by jpeg_mem_available).
  174630. * The interface is the same as above, except that on an 80x86 machine,
  174631. * far pointers are used. On most other machines these are identical to
  174632. * the jpeg_get/free_small routines; but we keep them separate anyway,
  174633. * in case a different allocation strategy is desirable for large chunks.
  174634. */
  174635. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  174636. size_t sizeofobject));
  174637. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  174638. size_t sizeofobject));
  174639. /*
  174640. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  174641. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  174642. * matter, but that case should never come into play). This macro is needed
  174643. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  174644. * On those machines, we expect that jconfig.h will provide a proper value.
  174645. * On machines with 32-bit flat address spaces, any large constant may be used.
  174646. *
  174647. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  174648. * size_t and will be a multiple of sizeof(align_type).
  174649. */
  174650. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  174651. #define MAX_ALLOC_CHUNK 1000000000L
  174652. #endif
  174653. /*
  174654. * This routine computes the total space still available for allocation by
  174655. * jpeg_get_large. If more space than this is needed, backing store will be
  174656. * used. NOTE: any memory already allocated must not be counted.
  174657. *
  174658. * There is a minimum space requirement, corresponding to the minimum
  174659. * feasible buffer sizes; jmemmgr.c will request that much space even if
  174660. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  174661. * all working storage in memory, is also passed in case it is useful.
  174662. * Finally, the total space already allocated is passed. If no better
  174663. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  174664. * is often a suitable calculation.
  174665. *
  174666. * It is OK for jpeg_mem_available to underestimate the space available
  174667. * (that'll just lead to more backing-store access than is really necessary).
  174668. * However, an overestimate will lead to failure. Hence it's wise to subtract
  174669. * a slop factor from the true available space. 5% should be enough.
  174670. *
  174671. * On machines with lots of virtual memory, any large constant may be returned.
  174672. * Conversely, zero may be returned to always use the minimum amount of memory.
  174673. */
  174674. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  174675. long min_bytes_needed,
  174676. long max_bytes_needed,
  174677. long already_allocated));
  174678. /*
  174679. * This structure holds whatever state is needed to access a single
  174680. * backing-store object. The read/write/close method pointers are called
  174681. * by jmemmgr.c to manipulate the backing-store object; all other fields
  174682. * are private to the system-dependent backing store routines.
  174683. */
  174684. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  174685. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  174686. typedef unsigned short XMSH; /* type of extended-memory handles */
  174687. typedef unsigned short EMSH; /* type of expanded-memory handles */
  174688. typedef union {
  174689. short file_handle; /* DOS file handle if it's a temp file */
  174690. XMSH xms_handle; /* handle if it's a chunk of XMS */
  174691. EMSH ems_handle; /* handle if it's a chunk of EMS */
  174692. } handle_union;
  174693. #endif /* USE_MSDOS_MEMMGR */
  174694. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  174695. #include <Files.h>
  174696. #endif /* USE_MAC_MEMMGR */
  174697. //typedef struct backing_store_struct * backing_store_ptr;
  174698. typedef struct backing_store_struct {
  174699. /* Methods for reading/writing/closing this backing-store object */
  174700. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  174701. struct backing_store_struct *info,
  174702. void FAR * buffer_address,
  174703. long file_offset, long byte_count));
  174704. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  174705. struct backing_store_struct *info,
  174706. void FAR * buffer_address,
  174707. long file_offset, long byte_count));
  174708. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  174709. struct backing_store_struct *info));
  174710. /* Private fields for system-dependent backing-store management */
  174711. #ifdef USE_MSDOS_MEMMGR
  174712. /* For the MS-DOS manager (jmemdos.c), we need: */
  174713. handle_union handle; /* reference to backing-store storage object */
  174714. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  174715. #else
  174716. #ifdef USE_MAC_MEMMGR
  174717. /* For the Mac manager (jmemmac.c), we need: */
  174718. short temp_file; /* file reference number to temp file */
  174719. FSSpec tempSpec; /* the FSSpec for the temp file */
  174720. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  174721. #else
  174722. /* For a typical implementation with temp files, we need: */
  174723. FILE * temp_file; /* stdio reference to temp file */
  174724. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  174725. #endif
  174726. #endif
  174727. } backing_store_info;
  174728. /*
  174729. * Initial opening of a backing-store object. This must fill in the
  174730. * read/write/close pointers in the object. The read/write routines
  174731. * may take an error exit if the specified maximum file size is exceeded.
  174732. * (If jpeg_mem_available always returns a large value, this routine can
  174733. * just take an error exit.)
  174734. */
  174735. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  174736. struct backing_store_struct *info,
  174737. long total_bytes_needed));
  174738. /*
  174739. * These routines take care of any system-dependent initialization and
  174740. * cleanup required. jpeg_mem_init will be called before anything is
  174741. * allocated (and, therefore, nothing in cinfo is of use except the error
  174742. * manager pointer). It should return a suitable default value for
  174743. * max_memory_to_use; this may subsequently be overridden by the surrounding
  174744. * application. (Note that max_memory_to_use is only important if
  174745. * jpeg_mem_available chooses to consult it ... no one else will.)
  174746. * jpeg_mem_term may assume that all requested memory has been freed and that
  174747. * all opened backing-store objects have been closed.
  174748. */
  174749. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  174750. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  174751. #endif
  174752. /*** End of inlined file: jmemsys.h ***/
  174753. /* import the system-dependent declarations */
  174754. #ifndef NO_GETENV
  174755. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  174756. extern char * getenv JPP((const char * name));
  174757. #endif
  174758. #endif
  174759. /*
  174760. * Some important notes:
  174761. * The allocation routines provided here must never return NULL.
  174762. * They should exit to error_exit if unsuccessful.
  174763. *
  174764. * It's not a good idea to try to merge the sarray and barray routines,
  174765. * even though they are textually almost the same, because samples are
  174766. * usually stored as bytes while coefficients are shorts or ints. Thus,
  174767. * in machines where byte pointers have a different representation from
  174768. * word pointers, the resulting machine code could not be the same.
  174769. */
  174770. /*
  174771. * Many machines require storage alignment: longs must start on 4-byte
  174772. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  174773. * always returns pointers that are multiples of the worst-case alignment
  174774. * requirement, and we had better do so too.
  174775. * There isn't any really portable way to determine the worst-case alignment
  174776. * requirement. This module assumes that the alignment requirement is
  174777. * multiples of sizeof(ALIGN_TYPE).
  174778. * By default, we define ALIGN_TYPE as double. This is necessary on some
  174779. * workstations (where doubles really do need 8-byte alignment) and will work
  174780. * fine on nearly everything. If your machine has lesser alignment needs,
  174781. * you can save a few bytes by making ALIGN_TYPE smaller.
  174782. * The only place I know of where this will NOT work is certain Macintosh
  174783. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  174784. * Doing 10-byte alignment is counterproductive because longwords won't be
  174785. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  174786. * such a compiler.
  174787. */
  174788. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  174789. #define ALIGN_TYPE double
  174790. #endif
  174791. /*
  174792. * We allocate objects from "pools", where each pool is gotten with a single
  174793. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  174794. * overhead within a pool, except for alignment padding. Each pool has a
  174795. * header with a link to the next pool of the same class.
  174796. * Small and large pool headers are identical except that the latter's
  174797. * link pointer must be FAR on 80x86 machines.
  174798. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  174799. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  174800. * of the alignment requirement of ALIGN_TYPE.
  174801. */
  174802. typedef union small_pool_struct * small_pool_ptr;
  174803. typedef union small_pool_struct {
  174804. struct {
  174805. small_pool_ptr next; /* next in list of pools */
  174806. size_t bytes_used; /* how many bytes already used within pool */
  174807. size_t bytes_left; /* bytes still available in this pool */
  174808. } hdr;
  174809. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  174810. } small_pool_hdr;
  174811. typedef union large_pool_struct FAR * large_pool_ptr;
  174812. typedef union large_pool_struct {
  174813. struct {
  174814. large_pool_ptr next; /* next in list of pools */
  174815. size_t bytes_used; /* how many bytes already used within pool */
  174816. size_t bytes_left; /* bytes still available in this pool */
  174817. } hdr;
  174818. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  174819. } large_pool_hdr;
  174820. /*
  174821. * Here is the full definition of a memory manager object.
  174822. */
  174823. typedef struct {
  174824. struct jpeg_memory_mgr pub; /* public fields */
  174825. /* Each pool identifier (lifetime class) names a linked list of pools. */
  174826. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  174827. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  174828. /* Since we only have one lifetime class of virtual arrays, only one
  174829. * linked list is necessary (for each datatype). Note that the virtual
  174830. * array control blocks being linked together are actually stored somewhere
  174831. * in the small-pool list.
  174832. */
  174833. jvirt_sarray_ptr virt_sarray_list;
  174834. jvirt_barray_ptr virt_barray_list;
  174835. /* This counts total space obtained from jpeg_get_small/large */
  174836. long total_space_allocated;
  174837. /* alloc_sarray and alloc_barray set this value for use by virtual
  174838. * array routines.
  174839. */
  174840. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  174841. } my_memory_mgr;
  174842. typedef my_memory_mgr * my_mem_ptr;
  174843. /*
  174844. * The control blocks for virtual arrays.
  174845. * Note that these blocks are allocated in the "small" pool area.
  174846. * System-dependent info for the associated backing store (if any) is hidden
  174847. * inside the backing_store_info struct.
  174848. */
  174849. struct jvirt_sarray_control {
  174850. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  174851. JDIMENSION rows_in_array; /* total virtual array height */
  174852. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  174853. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  174854. JDIMENSION rows_in_mem; /* height of memory buffer */
  174855. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  174856. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  174857. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  174858. boolean pre_zero; /* pre-zero mode requested? */
  174859. boolean dirty; /* do current buffer contents need written? */
  174860. boolean b_s_open; /* is backing-store data valid? */
  174861. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  174862. backing_store_info b_s_info; /* System-dependent control info */
  174863. };
  174864. struct jvirt_barray_control {
  174865. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  174866. JDIMENSION rows_in_array; /* total virtual array height */
  174867. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  174868. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  174869. JDIMENSION rows_in_mem; /* height of memory buffer */
  174870. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  174871. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  174872. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  174873. boolean pre_zero; /* pre-zero mode requested? */
  174874. boolean dirty; /* do current buffer contents need written? */
  174875. boolean b_s_open; /* is backing-store data valid? */
  174876. jvirt_barray_ptr next; /* link to next virtual barray control block */
  174877. backing_store_info b_s_info; /* System-dependent control info */
  174878. };
  174879. #ifdef MEM_STATS /* optional extra stuff for statistics */
  174880. LOCAL(void)
  174881. print_mem_stats (j_common_ptr cinfo, int pool_id)
  174882. {
  174883. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  174884. small_pool_ptr shdr_ptr;
  174885. large_pool_ptr lhdr_ptr;
  174886. /* Since this is only a debugging stub, we can cheat a little by using
  174887. * fprintf directly rather than going through the trace message code.
  174888. * This is helpful because message parm array can't handle longs.
  174889. */
  174890. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  174891. pool_id, mem->total_space_allocated);
  174892. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  174893. lhdr_ptr = lhdr_ptr->hdr.next) {
  174894. fprintf(stderr, " Large chunk used %ld\n",
  174895. (long) lhdr_ptr->hdr.bytes_used);
  174896. }
  174897. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  174898. shdr_ptr = shdr_ptr->hdr.next) {
  174899. fprintf(stderr, " Small chunk used %ld free %ld\n",
  174900. (long) shdr_ptr->hdr.bytes_used,
  174901. (long) shdr_ptr->hdr.bytes_left);
  174902. }
  174903. }
  174904. #endif /* MEM_STATS */
  174905. LOCAL(void)
  174906. out_of_memory (j_common_ptr cinfo, int which)
  174907. /* Report an out-of-memory error and stop execution */
  174908. /* If we compiled MEM_STATS support, report alloc requests before dying */
  174909. {
  174910. #ifdef MEM_STATS
  174911. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  174912. #endif
  174913. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  174914. }
  174915. /*
  174916. * Allocation of "small" objects.
  174917. *
  174918. * For these, we use pooled storage. When a new pool must be created,
  174919. * we try to get enough space for the current request plus a "slop" factor,
  174920. * where the slop will be the amount of leftover space in the new pool.
  174921. * The speed vs. space tradeoff is largely determined by the slop values.
  174922. * A different slop value is provided for each pool class (lifetime),
  174923. * and we also distinguish the first pool of a class from later ones.
  174924. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  174925. * machines, but may be too small if longs are 64 bits or more.
  174926. */
  174927. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  174928. {
  174929. 1600, /* first PERMANENT pool */
  174930. 16000 /* first IMAGE pool */
  174931. };
  174932. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  174933. {
  174934. 0, /* additional PERMANENT pools */
  174935. 5000 /* additional IMAGE pools */
  174936. };
  174937. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  174938. METHODDEF(void *)
  174939. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  174940. /* Allocate a "small" object */
  174941. {
  174942. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  174943. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  174944. char * data_ptr;
  174945. size_t odd_bytes, min_request, slop;
  174946. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  174947. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  174948. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  174949. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  174950. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  174951. if (odd_bytes > 0)
  174952. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  174953. /* See if space is available in any existing pool */
  174954. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  174955. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  174956. prev_hdr_ptr = NULL;
  174957. hdr_ptr = mem->small_list[pool_id];
  174958. while (hdr_ptr != NULL) {
  174959. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  174960. break; /* found pool with enough space */
  174961. prev_hdr_ptr = hdr_ptr;
  174962. hdr_ptr = hdr_ptr->hdr.next;
  174963. }
  174964. /* Time to make a new pool? */
  174965. if (hdr_ptr == NULL) {
  174966. /* min_request is what we need now, slop is what will be leftover */
  174967. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  174968. if (prev_hdr_ptr == NULL) /* first pool in class? */
  174969. slop = first_pool_slop[pool_id];
  174970. else
  174971. slop = extra_pool_slop[pool_id];
  174972. /* Don't ask for more than MAX_ALLOC_CHUNK */
  174973. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  174974. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  174975. /* Try to get space, if fail reduce slop and try again */
  174976. for (;;) {
  174977. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  174978. if (hdr_ptr != NULL)
  174979. break;
  174980. slop /= 2;
  174981. if (slop < MIN_SLOP) /* give up when it gets real small */
  174982. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  174983. }
  174984. mem->total_space_allocated += min_request + slop;
  174985. /* Success, initialize the new pool header and add to end of list */
  174986. hdr_ptr->hdr.next = NULL;
  174987. hdr_ptr->hdr.bytes_used = 0;
  174988. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  174989. if (prev_hdr_ptr == NULL) /* first pool in class? */
  174990. mem->small_list[pool_id] = hdr_ptr;
  174991. else
  174992. prev_hdr_ptr->hdr.next = hdr_ptr;
  174993. }
  174994. /* OK, allocate the object from the current pool */
  174995. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  174996. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  174997. hdr_ptr->hdr.bytes_used += sizeofobject;
  174998. hdr_ptr->hdr.bytes_left -= sizeofobject;
  174999. return (void *) data_ptr;
  175000. }
  175001. /*
  175002. * Allocation of "large" objects.
  175003. *
  175004. * The external semantics of these are the same as "small" objects,
  175005. * except that FAR pointers are used on 80x86. However the pool
  175006. * management heuristics are quite different. We assume that each
  175007. * request is large enough that it may as well be passed directly to
  175008. * jpeg_get_large; the pool management just links everything together
  175009. * so that we can free it all on demand.
  175010. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175011. * structures. The routines that create these structures (see below)
  175012. * deliberately bunch rows together to ensure a large request size.
  175013. */
  175014. METHODDEF(void FAR *)
  175015. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175016. /* Allocate a "large" object */
  175017. {
  175018. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175019. large_pool_ptr hdr_ptr;
  175020. size_t odd_bytes;
  175021. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175022. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175023. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175024. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175025. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175026. if (odd_bytes > 0)
  175027. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175028. /* Always make a new pool */
  175029. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175030. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175031. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175032. SIZEOF(large_pool_hdr));
  175033. if (hdr_ptr == NULL)
  175034. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175035. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175036. /* Success, initialize the new pool header and add to list */
  175037. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175038. /* We maintain space counts in each pool header for statistical purposes,
  175039. * even though they are not needed for allocation.
  175040. */
  175041. hdr_ptr->hdr.bytes_used = sizeofobject;
  175042. hdr_ptr->hdr.bytes_left = 0;
  175043. mem->large_list[pool_id] = hdr_ptr;
  175044. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175045. }
  175046. /*
  175047. * Creation of 2-D sample arrays.
  175048. * The pointers are in near heap, the samples themselves in FAR heap.
  175049. *
  175050. * To minimize allocation overhead and to allow I/O of large contiguous
  175051. * blocks, we allocate the sample rows in groups of as many rows as possible
  175052. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175053. * NB: the virtual array control routines, later in this file, know about
  175054. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175055. * object so that it can be saved away if this sarray is the workspace for
  175056. * a virtual array.
  175057. */
  175058. METHODDEF(JSAMPARRAY)
  175059. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175060. JDIMENSION samplesperrow, JDIMENSION numrows)
  175061. /* Allocate a 2-D sample array */
  175062. {
  175063. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175064. JSAMPARRAY result;
  175065. JSAMPROW workspace;
  175066. JDIMENSION rowsperchunk, currow, i;
  175067. long ltemp;
  175068. /* Calculate max # of rows allowed in one allocation chunk */
  175069. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175070. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175071. if (ltemp <= 0)
  175072. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175073. if (ltemp < (long) numrows)
  175074. rowsperchunk = (JDIMENSION) ltemp;
  175075. else
  175076. rowsperchunk = numrows;
  175077. mem->last_rowsperchunk = rowsperchunk;
  175078. /* Get space for row pointers (small object) */
  175079. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175080. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175081. /* Get the rows themselves (large objects) */
  175082. currow = 0;
  175083. while (currow < numrows) {
  175084. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175085. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175086. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175087. * SIZEOF(JSAMPLE)));
  175088. for (i = rowsperchunk; i > 0; i--) {
  175089. result[currow++] = workspace;
  175090. workspace += samplesperrow;
  175091. }
  175092. }
  175093. return result;
  175094. }
  175095. /*
  175096. * Creation of 2-D coefficient-block arrays.
  175097. * This is essentially the same as the code for sample arrays, above.
  175098. */
  175099. METHODDEF(JBLOCKARRAY)
  175100. alloc_barray (j_common_ptr cinfo, int pool_id,
  175101. JDIMENSION blocksperrow, JDIMENSION numrows)
  175102. /* Allocate a 2-D coefficient-block array */
  175103. {
  175104. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175105. JBLOCKARRAY result;
  175106. JBLOCKROW workspace;
  175107. JDIMENSION rowsperchunk, currow, i;
  175108. long ltemp;
  175109. /* Calculate max # of rows allowed in one allocation chunk */
  175110. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175111. ((long) blocksperrow * SIZEOF(JBLOCK));
  175112. if (ltemp <= 0)
  175113. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175114. if (ltemp < (long) numrows)
  175115. rowsperchunk = (JDIMENSION) ltemp;
  175116. else
  175117. rowsperchunk = numrows;
  175118. mem->last_rowsperchunk = rowsperchunk;
  175119. /* Get space for row pointers (small object) */
  175120. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175121. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175122. /* Get the rows themselves (large objects) */
  175123. currow = 0;
  175124. while (currow < numrows) {
  175125. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175126. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175127. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175128. * SIZEOF(JBLOCK)));
  175129. for (i = rowsperchunk; i > 0; i--) {
  175130. result[currow++] = workspace;
  175131. workspace += blocksperrow;
  175132. }
  175133. }
  175134. return result;
  175135. }
  175136. /*
  175137. * About virtual array management:
  175138. *
  175139. * The above "normal" array routines are only used to allocate strip buffers
  175140. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  175141. * are handled as "virtual" arrays. The array is still accessed a strip at a
  175142. * time, but the memory manager must save the whole array for repeated
  175143. * accesses. The intended implementation is that there is a strip buffer in
  175144. * memory (as high as is possible given the desired memory limit), plus a
  175145. * backing file that holds the rest of the array.
  175146. *
  175147. * The request_virt_array routines are told the total size of the image and
  175148. * the maximum number of rows that will be accessed at once. The in-memory
  175149. * buffer must be at least as large as the maxaccess value.
  175150. *
  175151. * The request routines create control blocks but not the in-memory buffers.
  175152. * That is postponed until realize_virt_arrays is called. At that time the
  175153. * total amount of space needed is known (approximately, anyway), so free
  175154. * memory can be divided up fairly.
  175155. *
  175156. * The access_virt_array routines are responsible for making a specific strip
  175157. * area accessible (after reading or writing the backing file, if necessary).
  175158. * Note that the access routines are told whether the caller intends to modify
  175159. * the accessed strip; during a read-only pass this saves having to rewrite
  175160. * data to disk. The access routines are also responsible for pre-zeroing
  175161. * any newly accessed rows, if pre-zeroing was requested.
  175162. *
  175163. * In current usage, the access requests are usually for nonoverlapping
  175164. * strips; that is, successive access start_row numbers differ by exactly
  175165. * num_rows = maxaccess. This means we can get good performance with simple
  175166. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  175167. * of the access height; then there will never be accesses across bufferload
  175168. * boundaries. The code will still work with overlapping access requests,
  175169. * but it doesn't handle bufferload overlaps very efficiently.
  175170. */
  175171. METHODDEF(jvirt_sarray_ptr)
  175172. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175173. JDIMENSION samplesperrow, JDIMENSION numrows,
  175174. JDIMENSION maxaccess)
  175175. /* Request a virtual 2-D sample array */
  175176. {
  175177. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175178. jvirt_sarray_ptr result;
  175179. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175180. if (pool_id != JPOOL_IMAGE)
  175181. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175182. /* get control block */
  175183. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  175184. SIZEOF(struct jvirt_sarray_control));
  175185. result->mem_buffer = NULL; /* marks array not yet realized */
  175186. result->rows_in_array = numrows;
  175187. result->samplesperrow = samplesperrow;
  175188. result->maxaccess = maxaccess;
  175189. result->pre_zero = pre_zero;
  175190. result->b_s_open = FALSE; /* no associated backing-store object */
  175191. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  175192. mem->virt_sarray_list = result;
  175193. return result;
  175194. }
  175195. METHODDEF(jvirt_barray_ptr)
  175196. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175197. JDIMENSION blocksperrow, JDIMENSION numrows,
  175198. JDIMENSION maxaccess)
  175199. /* Request a virtual 2-D coefficient-block array */
  175200. {
  175201. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175202. jvirt_barray_ptr result;
  175203. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175204. if (pool_id != JPOOL_IMAGE)
  175205. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175206. /* get control block */
  175207. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  175208. SIZEOF(struct jvirt_barray_control));
  175209. result->mem_buffer = NULL; /* marks array not yet realized */
  175210. result->rows_in_array = numrows;
  175211. result->blocksperrow = blocksperrow;
  175212. result->maxaccess = maxaccess;
  175213. result->pre_zero = pre_zero;
  175214. result->b_s_open = FALSE; /* no associated backing-store object */
  175215. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  175216. mem->virt_barray_list = result;
  175217. return result;
  175218. }
  175219. METHODDEF(void)
  175220. realize_virt_arrays (j_common_ptr cinfo)
  175221. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  175222. {
  175223. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175224. long space_per_minheight, maximum_space, avail_mem;
  175225. long minheights, max_minheights;
  175226. jvirt_sarray_ptr sptr;
  175227. jvirt_barray_ptr bptr;
  175228. /* Compute the minimum space needed (maxaccess rows in each buffer)
  175229. * and the maximum space needed (full image height in each buffer).
  175230. * These may be of use to the system-dependent jpeg_mem_available routine.
  175231. */
  175232. space_per_minheight = 0;
  175233. maximum_space = 0;
  175234. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175235. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175236. space_per_minheight += (long) sptr->maxaccess *
  175237. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175238. maximum_space += (long) sptr->rows_in_array *
  175239. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175240. }
  175241. }
  175242. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175243. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175244. space_per_minheight += (long) bptr->maxaccess *
  175245. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175246. maximum_space += (long) bptr->rows_in_array *
  175247. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175248. }
  175249. }
  175250. if (space_per_minheight <= 0)
  175251. return; /* no unrealized arrays, no work */
  175252. /* Determine amount of memory to actually use; this is system-dependent. */
  175253. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  175254. mem->total_space_allocated);
  175255. /* If the maximum space needed is available, make all the buffers full
  175256. * height; otherwise parcel it out with the same number of minheights
  175257. * in each buffer.
  175258. */
  175259. if (avail_mem >= maximum_space)
  175260. max_minheights = 1000000000L;
  175261. else {
  175262. max_minheights = avail_mem / space_per_minheight;
  175263. /* If there doesn't seem to be enough space, try to get the minimum
  175264. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  175265. */
  175266. if (max_minheights <= 0)
  175267. max_minheights = 1;
  175268. }
  175269. /* Allocate the in-memory buffers and initialize backing store as needed. */
  175270. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175271. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175272. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  175273. if (minheights <= max_minheights) {
  175274. /* This buffer fits in memory */
  175275. sptr->rows_in_mem = sptr->rows_in_array;
  175276. } else {
  175277. /* It doesn't fit in memory, create backing store. */
  175278. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  175279. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  175280. (long) sptr->rows_in_array *
  175281. (long) sptr->samplesperrow *
  175282. (long) SIZEOF(JSAMPLE));
  175283. sptr->b_s_open = TRUE;
  175284. }
  175285. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  175286. sptr->samplesperrow, sptr->rows_in_mem);
  175287. sptr->rowsperchunk = mem->last_rowsperchunk;
  175288. sptr->cur_start_row = 0;
  175289. sptr->first_undef_row = 0;
  175290. sptr->dirty = FALSE;
  175291. }
  175292. }
  175293. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175294. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175295. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  175296. if (minheights <= max_minheights) {
  175297. /* This buffer fits in memory */
  175298. bptr->rows_in_mem = bptr->rows_in_array;
  175299. } else {
  175300. /* It doesn't fit in memory, create backing store. */
  175301. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  175302. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  175303. (long) bptr->rows_in_array *
  175304. (long) bptr->blocksperrow *
  175305. (long) SIZEOF(JBLOCK));
  175306. bptr->b_s_open = TRUE;
  175307. }
  175308. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  175309. bptr->blocksperrow, bptr->rows_in_mem);
  175310. bptr->rowsperchunk = mem->last_rowsperchunk;
  175311. bptr->cur_start_row = 0;
  175312. bptr->first_undef_row = 0;
  175313. bptr->dirty = FALSE;
  175314. }
  175315. }
  175316. }
  175317. LOCAL(void)
  175318. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  175319. /* Do backing store read or write of a virtual sample array */
  175320. {
  175321. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175322. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175323. file_offset = ptr->cur_start_row * bytesperrow;
  175324. /* Loop to read or write each allocation chunk in mem_buffer */
  175325. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175326. /* One chunk, but check for short chunk at end of buffer */
  175327. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175328. /* Transfer no more than is currently defined */
  175329. thisrow = (long) ptr->cur_start_row + i;
  175330. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175331. /* Transfer no more than fits in file */
  175332. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175333. if (rows <= 0) /* this chunk might be past end of file! */
  175334. break;
  175335. byte_count = rows * bytesperrow;
  175336. if (writing)
  175337. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175338. (void FAR *) ptr->mem_buffer[i],
  175339. file_offset, byte_count);
  175340. else
  175341. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175342. (void FAR *) ptr->mem_buffer[i],
  175343. file_offset, byte_count);
  175344. file_offset += byte_count;
  175345. }
  175346. }
  175347. LOCAL(void)
  175348. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  175349. /* Do backing store read or write of a virtual coefficient-block array */
  175350. {
  175351. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175352. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  175353. file_offset = ptr->cur_start_row * bytesperrow;
  175354. /* Loop to read or write each allocation chunk in mem_buffer */
  175355. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175356. /* One chunk, but check for short chunk at end of buffer */
  175357. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175358. /* Transfer no more than is currently defined */
  175359. thisrow = (long) ptr->cur_start_row + i;
  175360. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175361. /* Transfer no more than fits in file */
  175362. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175363. if (rows <= 0) /* this chunk might be past end of file! */
  175364. break;
  175365. byte_count = rows * bytesperrow;
  175366. if (writing)
  175367. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175368. (void FAR *) ptr->mem_buffer[i],
  175369. file_offset, byte_count);
  175370. else
  175371. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175372. (void FAR *) ptr->mem_buffer[i],
  175373. file_offset, byte_count);
  175374. file_offset += byte_count;
  175375. }
  175376. }
  175377. METHODDEF(JSAMPARRAY)
  175378. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  175379. JDIMENSION start_row, JDIMENSION num_rows,
  175380. boolean writable)
  175381. /* Access the part of a virtual sample array starting at start_row */
  175382. /* and extending for num_rows rows. writable is true if */
  175383. /* caller intends to modify the accessed area. */
  175384. {
  175385. JDIMENSION end_row = start_row + num_rows;
  175386. JDIMENSION undef_row;
  175387. /* debugging check */
  175388. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  175389. ptr->mem_buffer == NULL)
  175390. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175391. /* Make the desired part of the virtual array accessible */
  175392. if (start_row < ptr->cur_start_row ||
  175393. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  175394. if (! ptr->b_s_open)
  175395. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  175396. /* Flush old buffer contents if necessary */
  175397. if (ptr->dirty) {
  175398. do_sarray_io(cinfo, ptr, TRUE);
  175399. ptr->dirty = FALSE;
  175400. }
  175401. /* Decide what part of virtual array to access.
  175402. * Algorithm: if target address > current window, assume forward scan,
  175403. * load starting at target address. If target address < current window,
  175404. * assume backward scan, load so that target area is top of window.
  175405. * Note that when switching from forward write to forward read, will have
  175406. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  175407. */
  175408. if (start_row > ptr->cur_start_row) {
  175409. ptr->cur_start_row = start_row;
  175410. } else {
  175411. /* use long arithmetic here to avoid overflow & unsigned problems */
  175412. long ltemp;
  175413. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  175414. if (ltemp < 0)
  175415. ltemp = 0; /* don't fall off front end of file */
  175416. ptr->cur_start_row = (JDIMENSION) ltemp;
  175417. }
  175418. /* Read in the selected part of the array.
  175419. * During the initial write pass, we will do no actual read
  175420. * because the selected part is all undefined.
  175421. */
  175422. do_sarray_io(cinfo, ptr, FALSE);
  175423. }
  175424. /* Ensure the accessed part of the array is defined; prezero if needed.
  175425. * To improve locality of access, we only prezero the part of the array
  175426. * that the caller is about to access, not the entire in-memory array.
  175427. */
  175428. if (ptr->first_undef_row < end_row) {
  175429. if (ptr->first_undef_row < start_row) {
  175430. if (writable) /* writer skipped over a section of array */
  175431. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175432. undef_row = start_row; /* but reader is allowed to read ahead */
  175433. } else {
  175434. undef_row = ptr->first_undef_row;
  175435. }
  175436. if (writable)
  175437. ptr->first_undef_row = end_row;
  175438. if (ptr->pre_zero) {
  175439. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175440. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  175441. end_row -= ptr->cur_start_row;
  175442. while (undef_row < end_row) {
  175443. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  175444. undef_row++;
  175445. }
  175446. } else {
  175447. if (! writable) /* reader looking at undefined data */
  175448. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175449. }
  175450. }
  175451. /* Flag the buffer dirty if caller will write in it */
  175452. if (writable)
  175453. ptr->dirty = TRUE;
  175454. /* Return address of proper part of the buffer */
  175455. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  175456. }
  175457. METHODDEF(JBLOCKARRAY)
  175458. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  175459. JDIMENSION start_row, JDIMENSION num_rows,
  175460. boolean writable)
  175461. /* Access the part of a virtual block array starting at start_row */
  175462. /* and extending for num_rows rows. writable is true if */
  175463. /* caller intends to modify the accessed area. */
  175464. {
  175465. JDIMENSION end_row = start_row + num_rows;
  175466. JDIMENSION undef_row;
  175467. /* debugging check */
  175468. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  175469. ptr->mem_buffer == NULL)
  175470. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175471. /* Make the desired part of the virtual array accessible */
  175472. if (start_row < ptr->cur_start_row ||
  175473. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  175474. if (! ptr->b_s_open)
  175475. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  175476. /* Flush old buffer contents if necessary */
  175477. if (ptr->dirty) {
  175478. do_barray_io(cinfo, ptr, TRUE);
  175479. ptr->dirty = FALSE;
  175480. }
  175481. /* Decide what part of virtual array to access.
  175482. * Algorithm: if target address > current window, assume forward scan,
  175483. * load starting at target address. If target address < current window,
  175484. * assume backward scan, load so that target area is top of window.
  175485. * Note that when switching from forward write to forward read, will have
  175486. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  175487. */
  175488. if (start_row > ptr->cur_start_row) {
  175489. ptr->cur_start_row = start_row;
  175490. } else {
  175491. /* use long arithmetic here to avoid overflow & unsigned problems */
  175492. long ltemp;
  175493. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  175494. if (ltemp < 0)
  175495. ltemp = 0; /* don't fall off front end of file */
  175496. ptr->cur_start_row = (JDIMENSION) ltemp;
  175497. }
  175498. /* Read in the selected part of the array.
  175499. * During the initial write pass, we will do no actual read
  175500. * because the selected part is all undefined.
  175501. */
  175502. do_barray_io(cinfo, ptr, FALSE);
  175503. }
  175504. /* Ensure the accessed part of the array is defined; prezero if needed.
  175505. * To improve locality of access, we only prezero the part of the array
  175506. * that the caller is about to access, not the entire in-memory array.
  175507. */
  175508. if (ptr->first_undef_row < end_row) {
  175509. if (ptr->first_undef_row < start_row) {
  175510. if (writable) /* writer skipped over a section of array */
  175511. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175512. undef_row = start_row; /* but reader is allowed to read ahead */
  175513. } else {
  175514. undef_row = ptr->first_undef_row;
  175515. }
  175516. if (writable)
  175517. ptr->first_undef_row = end_row;
  175518. if (ptr->pre_zero) {
  175519. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  175520. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  175521. end_row -= ptr->cur_start_row;
  175522. while (undef_row < end_row) {
  175523. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  175524. undef_row++;
  175525. }
  175526. } else {
  175527. if (! writable) /* reader looking at undefined data */
  175528. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175529. }
  175530. }
  175531. /* Flag the buffer dirty if caller will write in it */
  175532. if (writable)
  175533. ptr->dirty = TRUE;
  175534. /* Return address of proper part of the buffer */
  175535. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  175536. }
  175537. /*
  175538. * Release all objects belonging to a specified pool.
  175539. */
  175540. METHODDEF(void)
  175541. free_pool (j_common_ptr cinfo, int pool_id)
  175542. {
  175543. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175544. small_pool_ptr shdr_ptr;
  175545. large_pool_ptr lhdr_ptr;
  175546. size_t space_freed;
  175547. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175548. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175549. #ifdef MEM_STATS
  175550. if (cinfo->err->trace_level > 1)
  175551. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  175552. #endif
  175553. /* If freeing IMAGE pool, close any virtual arrays first */
  175554. if (pool_id == JPOOL_IMAGE) {
  175555. jvirt_sarray_ptr sptr;
  175556. jvirt_barray_ptr bptr;
  175557. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175558. if (sptr->b_s_open) { /* there may be no backing store */
  175559. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  175560. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  175561. }
  175562. }
  175563. mem->virt_sarray_list = NULL;
  175564. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175565. if (bptr->b_s_open) { /* there may be no backing store */
  175566. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  175567. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  175568. }
  175569. }
  175570. mem->virt_barray_list = NULL;
  175571. }
  175572. /* Release large objects */
  175573. lhdr_ptr = mem->large_list[pool_id];
  175574. mem->large_list[pool_id] = NULL;
  175575. while (lhdr_ptr != NULL) {
  175576. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  175577. space_freed = lhdr_ptr->hdr.bytes_used +
  175578. lhdr_ptr->hdr.bytes_left +
  175579. SIZEOF(large_pool_hdr);
  175580. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  175581. mem->total_space_allocated -= space_freed;
  175582. lhdr_ptr = next_lhdr_ptr;
  175583. }
  175584. /* Release small objects */
  175585. shdr_ptr = mem->small_list[pool_id];
  175586. mem->small_list[pool_id] = NULL;
  175587. while (shdr_ptr != NULL) {
  175588. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  175589. space_freed = shdr_ptr->hdr.bytes_used +
  175590. shdr_ptr->hdr.bytes_left +
  175591. SIZEOF(small_pool_hdr);
  175592. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  175593. mem->total_space_allocated -= space_freed;
  175594. shdr_ptr = next_shdr_ptr;
  175595. }
  175596. }
  175597. /*
  175598. * Close up shop entirely.
  175599. * Note that this cannot be called unless cinfo->mem is non-NULL.
  175600. */
  175601. METHODDEF(void)
  175602. self_destruct (j_common_ptr cinfo)
  175603. {
  175604. int pool;
  175605. /* Close all backing store, release all memory.
  175606. * Releasing pools in reverse order might help avoid fragmentation
  175607. * with some (brain-damaged) malloc libraries.
  175608. */
  175609. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  175610. free_pool(cinfo, pool);
  175611. }
  175612. /* Release the memory manager control block too. */
  175613. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  175614. cinfo->mem = NULL; /* ensures I will be called only once */
  175615. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  175616. }
  175617. /*
  175618. * Memory manager initialization.
  175619. * When this is called, only the error manager pointer is valid in cinfo!
  175620. */
  175621. GLOBAL(void)
  175622. jinit_memory_mgr (j_common_ptr cinfo)
  175623. {
  175624. my_mem_ptr mem;
  175625. long max_to_use;
  175626. int pool;
  175627. size_t test_mac;
  175628. cinfo->mem = NULL; /* for safety if init fails */
  175629. /* Check for configuration errors.
  175630. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  175631. * doesn't reflect any real hardware alignment requirement.
  175632. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  175633. * in common if and only if X is a power of 2, ie has only one one-bit.
  175634. * Some compilers may give an "unreachable code" warning here; ignore it.
  175635. */
  175636. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  175637. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  175638. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  175639. * a multiple of SIZEOF(ALIGN_TYPE).
  175640. * Again, an "unreachable code" warning may be ignored here.
  175641. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  175642. */
  175643. test_mac = (size_t) MAX_ALLOC_CHUNK;
  175644. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  175645. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  175646. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  175647. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  175648. /* Attempt to allocate memory manager's control block */
  175649. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  175650. if (mem == NULL) {
  175651. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  175652. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  175653. }
  175654. /* OK, fill in the method pointers */
  175655. mem->pub.alloc_small = alloc_small;
  175656. mem->pub.alloc_large = alloc_large;
  175657. mem->pub.alloc_sarray = alloc_sarray;
  175658. mem->pub.alloc_barray = alloc_barray;
  175659. mem->pub.request_virt_sarray = request_virt_sarray;
  175660. mem->pub.request_virt_barray = request_virt_barray;
  175661. mem->pub.realize_virt_arrays = realize_virt_arrays;
  175662. mem->pub.access_virt_sarray = access_virt_sarray;
  175663. mem->pub.access_virt_barray = access_virt_barray;
  175664. mem->pub.free_pool = free_pool;
  175665. mem->pub.self_destruct = self_destruct;
  175666. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  175667. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  175668. /* Initialize working state */
  175669. mem->pub.max_memory_to_use = max_to_use;
  175670. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  175671. mem->small_list[pool] = NULL;
  175672. mem->large_list[pool] = NULL;
  175673. }
  175674. mem->virt_sarray_list = NULL;
  175675. mem->virt_barray_list = NULL;
  175676. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  175677. /* Declare ourselves open for business */
  175678. cinfo->mem = & mem->pub;
  175679. /* Check for an environment variable JPEGMEM; if found, override the
  175680. * default max_memory setting from jpeg_mem_init. Note that the
  175681. * surrounding application may again override this value.
  175682. * If your system doesn't support getenv(), define NO_GETENV to disable
  175683. * this feature.
  175684. */
  175685. #ifndef NO_GETENV
  175686. { char * memenv;
  175687. if ((memenv = getenv("JPEGMEM")) != NULL) {
  175688. char ch = 'x';
  175689. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  175690. if (ch == 'm' || ch == 'M')
  175691. max_to_use *= 1000L;
  175692. mem->pub.max_memory_to_use = max_to_use * 1000L;
  175693. }
  175694. }
  175695. }
  175696. #endif
  175697. }
  175698. /*** End of inlined file: jmemmgr.c ***/
  175699. /*** Start of inlined file: jmemnobs.c ***/
  175700. #define JPEG_INTERNALS
  175701. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  175702. extern void * malloc JPP((size_t size));
  175703. extern void free JPP((void *ptr));
  175704. #endif
  175705. /*
  175706. * Memory allocation and freeing are controlled by the regular library
  175707. * routines malloc() and free().
  175708. */
  175709. GLOBAL(void *)
  175710. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  175711. {
  175712. return (void *) malloc(sizeofobject);
  175713. }
  175714. GLOBAL(void)
  175715. jpeg_free_small (j_common_ptr , void * object, size_t)
  175716. {
  175717. free(object);
  175718. }
  175719. /*
  175720. * "Large" objects are treated the same as "small" ones.
  175721. * NB: although we include FAR keywords in the routine declarations,
  175722. * this file won't actually work in 80x86 small/medium model; at least,
  175723. * you probably won't be able to process useful-size images in only 64KB.
  175724. */
  175725. GLOBAL(void FAR *)
  175726. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  175727. {
  175728. return (void FAR *) malloc(sizeofobject);
  175729. }
  175730. GLOBAL(void)
  175731. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  175732. {
  175733. free(object);
  175734. }
  175735. /*
  175736. * This routine computes the total memory space available for allocation.
  175737. * Here we always say, "we got all you want bud!"
  175738. */
  175739. GLOBAL(long)
  175740. jpeg_mem_available (j_common_ptr, long,
  175741. long max_bytes_needed, long)
  175742. {
  175743. return max_bytes_needed;
  175744. }
  175745. /*
  175746. * Backing store (temporary file) management.
  175747. * Since jpeg_mem_available always promised the moon,
  175748. * this should never be called and we can just error out.
  175749. */
  175750. GLOBAL(void)
  175751. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  175752. long )
  175753. {
  175754. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  175755. }
  175756. /*
  175757. * These routines take care of any system-dependent initialization and
  175758. * cleanup required. Here, there isn't any.
  175759. */
  175760. GLOBAL(long)
  175761. jpeg_mem_init (j_common_ptr)
  175762. {
  175763. return 0; /* just set max_memory_to_use to 0 */
  175764. }
  175765. GLOBAL(void)
  175766. jpeg_mem_term (j_common_ptr)
  175767. {
  175768. /* no work */
  175769. }
  175770. /*** End of inlined file: jmemnobs.c ***/
  175771. /*** Start of inlined file: jquant1.c ***/
  175772. #define JPEG_INTERNALS
  175773. #ifdef QUANT_1PASS_SUPPORTED
  175774. /*
  175775. * The main purpose of 1-pass quantization is to provide a fast, if not very
  175776. * high quality, colormapped output capability. A 2-pass quantizer usually
  175777. * gives better visual quality; however, for quantized grayscale output this
  175778. * quantizer is perfectly adequate. Dithering is highly recommended with this
  175779. * quantizer, though you can turn it off if you really want to.
  175780. *
  175781. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  175782. * image. We use a map consisting of all combinations of Ncolors[i] color
  175783. * values for the i'th component. The Ncolors[] values are chosen so that
  175784. * their product, the total number of colors, is no more than that requested.
  175785. * (In most cases, the product will be somewhat less.)
  175786. *
  175787. * Since the colormap is orthogonal, the representative value for each color
  175788. * component can be determined without considering the other components;
  175789. * then these indexes can be combined into a colormap index by a standard
  175790. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  175791. * can be precalculated and stored in the lookup table colorindex[].
  175792. * colorindex[i][j] maps pixel value j in component i to the nearest
  175793. * representative value (grid plane) for that component; this index is
  175794. * multiplied by the array stride for component i, so that the
  175795. * index of the colormap entry closest to a given pixel value is just
  175796. * sum( colorindex[component-number][pixel-component-value] )
  175797. * Aside from being fast, this scheme allows for variable spacing between
  175798. * representative values with no additional lookup cost.
  175799. *
  175800. * If gamma correction has been applied in color conversion, it might be wise
  175801. * to adjust the color grid spacing so that the representative colors are
  175802. * equidistant in linear space. At this writing, gamma correction is not
  175803. * implemented by jdcolor, so nothing is done here.
  175804. */
  175805. /* Declarations for ordered dithering.
  175806. *
  175807. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  175808. * dithering is described in many references, for instance Dale Schumacher's
  175809. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  175810. * In place of Schumacher's comparisons against a "threshold" value, we add a
  175811. * "dither" value to the input pixel and then round the result to the nearest
  175812. * output value. The dither value is equivalent to (0.5 - threshold) times
  175813. * the distance between output values. For ordered dithering, we assume that
  175814. * the output colors are equally spaced; if not, results will probably be
  175815. * worse, since the dither may be too much or too little at a given point.
  175816. *
  175817. * The normal calculation would be to form pixel value + dither, range-limit
  175818. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  175819. * We can skip the separate range-limiting step by extending the colorindex
  175820. * table in both directions.
  175821. */
  175822. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  175823. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  175824. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  175825. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  175826. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  175827. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  175828. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  175829. /* Bayer's order-4 dither array. Generated by the code given in
  175830. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  175831. * The values in this array must range from 0 to ODITHER_CELLS-1.
  175832. */
  175833. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  175834. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  175835. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  175836. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  175837. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  175838. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  175839. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  175840. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  175841. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  175842. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  175843. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  175844. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  175845. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  175846. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  175847. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  175848. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  175849. };
  175850. /* Declarations for Floyd-Steinberg dithering.
  175851. *
  175852. * Errors are accumulated into the array fserrors[], at a resolution of
  175853. * 1/16th of a pixel count. The error at a given pixel is propagated
  175854. * to its not-yet-processed neighbors using the standard F-S fractions,
  175855. * ... (here) 7/16
  175856. * 3/16 5/16 1/16
  175857. * We work left-to-right on even rows, right-to-left on odd rows.
  175858. *
  175859. * We can get away with a single array (holding one row's worth of errors)
  175860. * by using it to store the current row's errors at pixel columns not yet
  175861. * processed, but the next row's errors at columns already processed. We
  175862. * need only a few extra variables to hold the errors immediately around the
  175863. * current column. (If we are lucky, those variables are in registers, but
  175864. * even if not, they're probably cheaper to access than array elements are.)
  175865. *
  175866. * The fserrors[] array is indexed [component#][position].
  175867. * We provide (#columns + 2) entries per component; the extra entry at each
  175868. * end saves us from special-casing the first and last pixels.
  175869. *
  175870. * Note: on a wide image, we might not have enough room in a PC's near data
  175871. * segment to hold the error array; so it is allocated with alloc_large.
  175872. */
  175873. #if BITS_IN_JSAMPLE == 8
  175874. typedef INT16 FSERROR; /* 16 bits should be enough */
  175875. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  175876. #else
  175877. typedef INT32 FSERROR; /* may need more than 16 bits */
  175878. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  175879. #endif
  175880. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  175881. /* Private subobject */
  175882. #define MAX_Q_COMPS 4 /* max components I can handle */
  175883. typedef struct {
  175884. struct jpeg_color_quantizer pub; /* public fields */
  175885. /* Initially allocated colormap is saved here */
  175886. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  175887. int sv_actual; /* number of entries in use */
  175888. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  175889. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  175890. * premultiplied as described above. Since colormap indexes must fit into
  175891. * JSAMPLEs, the entries of this array will too.
  175892. */
  175893. boolean is_padded; /* is the colorindex padded for odither? */
  175894. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  175895. /* Variables for ordered dithering */
  175896. int row_index; /* cur row's vertical index in dither matrix */
  175897. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  175898. /* Variables for Floyd-Steinberg dithering */
  175899. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  175900. boolean on_odd_row; /* flag to remember which row we are on */
  175901. } my_cquantizer;
  175902. typedef my_cquantizer * my_cquantize_ptr;
  175903. /*
  175904. * Policy-making subroutines for create_colormap and create_colorindex.
  175905. * These routines determine the colormap to be used. The rest of the module
  175906. * only assumes that the colormap is orthogonal.
  175907. *
  175908. * * select_ncolors decides how to divvy up the available colors
  175909. * among the components.
  175910. * * output_value defines the set of representative values for a component.
  175911. * * largest_input_value defines the mapping from input values to
  175912. * representative values for a component.
  175913. * Note that the latter two routines may impose different policies for
  175914. * different components, though this is not currently done.
  175915. */
  175916. LOCAL(int)
  175917. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  175918. /* Determine allocation of desired colors to components, */
  175919. /* and fill in Ncolors[] array to indicate choice. */
  175920. /* Return value is total number of colors (product of Ncolors[] values). */
  175921. {
  175922. int nc = cinfo->out_color_components; /* number of color components */
  175923. int max_colors = cinfo->desired_number_of_colors;
  175924. int total_colors, iroot, i, j;
  175925. boolean changed;
  175926. long temp;
  175927. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  175928. /* We can allocate at least the nc'th root of max_colors per component. */
  175929. /* Compute floor(nc'th root of max_colors). */
  175930. iroot = 1;
  175931. do {
  175932. iroot++;
  175933. temp = iroot; /* set temp = iroot ** nc */
  175934. for (i = 1; i < nc; i++)
  175935. temp *= iroot;
  175936. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  175937. iroot--; /* now iroot = floor(root) */
  175938. /* Must have at least 2 color values per component */
  175939. if (iroot < 2)
  175940. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  175941. /* Initialize to iroot color values for each component */
  175942. total_colors = 1;
  175943. for (i = 0; i < nc; i++) {
  175944. Ncolors[i] = iroot;
  175945. total_colors *= iroot;
  175946. }
  175947. /* We may be able to increment the count for one or more components without
  175948. * exceeding max_colors, though we know not all can be incremented.
  175949. * Sometimes, the first component can be incremented more than once!
  175950. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  175951. * In RGB colorspace, try to increment G first, then R, then B.
  175952. */
  175953. do {
  175954. changed = FALSE;
  175955. for (i = 0; i < nc; i++) {
  175956. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  175957. /* calculate new total_colors if Ncolors[j] is incremented */
  175958. temp = total_colors / Ncolors[j];
  175959. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  175960. if (temp > (long) max_colors)
  175961. break; /* won't fit, done with this pass */
  175962. Ncolors[j]++; /* OK, apply the increment */
  175963. total_colors = (int) temp;
  175964. changed = TRUE;
  175965. }
  175966. } while (changed);
  175967. return total_colors;
  175968. }
  175969. LOCAL(int)
  175970. output_value (j_decompress_ptr, int, int j, int maxj)
  175971. /* Return j'th output value, where j will range from 0 to maxj */
  175972. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  175973. {
  175974. /* We always provide values 0 and MAXJSAMPLE for each component;
  175975. * any additional values are equally spaced between these limits.
  175976. * (Forcing the upper and lower values to the limits ensures that
  175977. * dithering can't produce a color outside the selected gamut.)
  175978. */
  175979. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  175980. }
  175981. LOCAL(int)
  175982. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  175983. /* Return largest input value that should map to j'th output value */
  175984. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  175985. {
  175986. /* Breakpoints are halfway between values returned by output_value */
  175987. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  175988. }
  175989. /*
  175990. * Create the colormap.
  175991. */
  175992. LOCAL(void)
  175993. create_colormap (j_decompress_ptr cinfo)
  175994. {
  175995. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  175996. JSAMPARRAY colormap; /* Created colormap */
  175997. int total_colors; /* Number of distinct output colors */
  175998. int i,j,k, nci, blksize, blkdist, ptr, val;
  175999. /* Select number of colors for each component */
  176000. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176001. /* Report selected color counts */
  176002. if (cinfo->out_color_components == 3)
  176003. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176004. total_colors, cquantize->Ncolors[0],
  176005. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176006. else
  176007. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176008. /* Allocate and fill in the colormap. */
  176009. /* The colors are ordered in the map in standard row-major order, */
  176010. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176011. colormap = (*cinfo->mem->alloc_sarray)
  176012. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176013. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176014. /* blksize is number of adjacent repeated entries for a component */
  176015. /* blkdist is distance between groups of identical entries for a component */
  176016. blkdist = total_colors;
  176017. for (i = 0; i < cinfo->out_color_components; i++) {
  176018. /* fill in colormap entries for i'th color component */
  176019. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176020. blksize = blkdist / nci;
  176021. for (j = 0; j < nci; j++) {
  176022. /* Compute j'th output value (out of nci) for component */
  176023. val = output_value(cinfo, i, j, nci-1);
  176024. /* Fill in all colormap entries that have this value of this component */
  176025. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176026. /* fill in blksize entries beginning at ptr */
  176027. for (k = 0; k < blksize; k++)
  176028. colormap[i][ptr+k] = (JSAMPLE) val;
  176029. }
  176030. }
  176031. blkdist = blksize; /* blksize of this color is blkdist of next */
  176032. }
  176033. /* Save the colormap in private storage,
  176034. * where it will survive color quantization mode changes.
  176035. */
  176036. cquantize->sv_colormap = colormap;
  176037. cquantize->sv_actual = total_colors;
  176038. }
  176039. /*
  176040. * Create the color index table.
  176041. */
  176042. LOCAL(void)
  176043. create_colorindex (j_decompress_ptr cinfo)
  176044. {
  176045. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176046. JSAMPROW indexptr;
  176047. int i,j,k, nci, blksize, val, pad;
  176048. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176049. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176050. * This is not necessary in the other dithering modes. However, we
  176051. * flag whether it was done in case user changes dithering mode.
  176052. */
  176053. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176054. pad = MAXJSAMPLE*2;
  176055. cquantize->is_padded = TRUE;
  176056. } else {
  176057. pad = 0;
  176058. cquantize->is_padded = FALSE;
  176059. }
  176060. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176061. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176062. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176063. (JDIMENSION) cinfo->out_color_components);
  176064. /* blksize is number of adjacent repeated entries for a component */
  176065. blksize = cquantize->sv_actual;
  176066. for (i = 0; i < cinfo->out_color_components; i++) {
  176067. /* fill in colorindex entries for i'th color component */
  176068. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176069. blksize = blksize / nci;
  176070. /* adjust colorindex pointers to provide padding at negative indexes. */
  176071. if (pad)
  176072. cquantize->colorindex[i] += MAXJSAMPLE;
  176073. /* in loop, val = index of current output value, */
  176074. /* and k = largest j that maps to current val */
  176075. indexptr = cquantize->colorindex[i];
  176076. val = 0;
  176077. k = largest_input_value(cinfo, i, 0, nci-1);
  176078. for (j = 0; j <= MAXJSAMPLE; j++) {
  176079. while (j > k) /* advance val if past boundary */
  176080. k = largest_input_value(cinfo, i, ++val, nci-1);
  176081. /* premultiply so that no multiplication needed in main processing */
  176082. indexptr[j] = (JSAMPLE) (val * blksize);
  176083. }
  176084. /* Pad at both ends if necessary */
  176085. if (pad)
  176086. for (j = 1; j <= MAXJSAMPLE; j++) {
  176087. indexptr[-j] = indexptr[0];
  176088. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176089. }
  176090. }
  176091. }
  176092. /*
  176093. * Create an ordered-dither array for a component having ncolors
  176094. * distinct output values.
  176095. */
  176096. LOCAL(ODITHER_MATRIX_PTR)
  176097. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176098. {
  176099. ODITHER_MATRIX_PTR odither;
  176100. int j,k;
  176101. INT32 num,den;
  176102. odither = (ODITHER_MATRIX_PTR)
  176103. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176104. SIZEOF(ODITHER_MATRIX));
  176105. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176106. * Hence the dither value for the matrix cell with fill order f
  176107. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176108. * On 16-bit-int machine, be careful to avoid overflow.
  176109. */
  176110. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176111. for (j = 0; j < ODITHER_SIZE; j++) {
  176112. for (k = 0; k < ODITHER_SIZE; k++) {
  176113. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176114. * MAXJSAMPLE;
  176115. /* Ensure round towards zero despite C's lack of consistency
  176116. * about rounding negative values in integer division...
  176117. */
  176118. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176119. }
  176120. }
  176121. return odither;
  176122. }
  176123. /*
  176124. * Create the ordered-dither tables.
  176125. * Components having the same number of representative colors may
  176126. * share a dither table.
  176127. */
  176128. LOCAL(void)
  176129. create_odither_tables (j_decompress_ptr cinfo)
  176130. {
  176131. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176132. ODITHER_MATRIX_PTR odither;
  176133. int i, j, nci;
  176134. for (i = 0; i < cinfo->out_color_components; i++) {
  176135. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176136. odither = NULL; /* search for matching prior component */
  176137. for (j = 0; j < i; j++) {
  176138. if (nci == cquantize->Ncolors[j]) {
  176139. odither = cquantize->odither[j];
  176140. break;
  176141. }
  176142. }
  176143. if (odither == NULL) /* need a new table? */
  176144. odither = make_odither_array(cinfo, nci);
  176145. cquantize->odither[i] = odither;
  176146. }
  176147. }
  176148. /*
  176149. * Map some rows of pixels to the output colormapped representation.
  176150. */
  176151. METHODDEF(void)
  176152. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176153. JSAMPARRAY output_buf, int num_rows)
  176154. /* General case, no dithering */
  176155. {
  176156. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176157. JSAMPARRAY colorindex = cquantize->colorindex;
  176158. register int pixcode, ci;
  176159. register JSAMPROW ptrin, ptrout;
  176160. int row;
  176161. JDIMENSION col;
  176162. JDIMENSION width = cinfo->output_width;
  176163. register int nc = cinfo->out_color_components;
  176164. for (row = 0; row < num_rows; row++) {
  176165. ptrin = input_buf[row];
  176166. ptrout = output_buf[row];
  176167. for (col = width; col > 0; col--) {
  176168. pixcode = 0;
  176169. for (ci = 0; ci < nc; ci++) {
  176170. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  176171. }
  176172. *ptrout++ = (JSAMPLE) pixcode;
  176173. }
  176174. }
  176175. }
  176176. METHODDEF(void)
  176177. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176178. JSAMPARRAY output_buf, int num_rows)
  176179. /* Fast path for out_color_components==3, no dithering */
  176180. {
  176181. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176182. register int pixcode;
  176183. register JSAMPROW ptrin, ptrout;
  176184. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176185. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176186. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176187. int row;
  176188. JDIMENSION col;
  176189. JDIMENSION width = cinfo->output_width;
  176190. for (row = 0; row < num_rows; row++) {
  176191. ptrin = input_buf[row];
  176192. ptrout = output_buf[row];
  176193. for (col = width; col > 0; col--) {
  176194. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  176195. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  176196. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  176197. *ptrout++ = (JSAMPLE) pixcode;
  176198. }
  176199. }
  176200. }
  176201. METHODDEF(void)
  176202. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176203. JSAMPARRAY output_buf, int num_rows)
  176204. /* General case, with ordered dithering */
  176205. {
  176206. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176207. register JSAMPROW input_ptr;
  176208. register JSAMPROW output_ptr;
  176209. JSAMPROW colorindex_ci;
  176210. int * dither; /* points to active row of dither matrix */
  176211. int row_index, col_index; /* current indexes into dither matrix */
  176212. int nc = cinfo->out_color_components;
  176213. int ci;
  176214. int row;
  176215. JDIMENSION col;
  176216. JDIMENSION width = cinfo->output_width;
  176217. for (row = 0; row < num_rows; row++) {
  176218. /* Initialize output values to 0 so can process components separately */
  176219. jzero_far((void FAR *) output_buf[row],
  176220. (size_t) (width * SIZEOF(JSAMPLE)));
  176221. row_index = cquantize->row_index;
  176222. for (ci = 0; ci < nc; ci++) {
  176223. input_ptr = input_buf[row] + ci;
  176224. output_ptr = output_buf[row];
  176225. colorindex_ci = cquantize->colorindex[ci];
  176226. dither = cquantize->odither[ci][row_index];
  176227. col_index = 0;
  176228. for (col = width; col > 0; col--) {
  176229. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  176230. * select output value, accumulate into output code for this pixel.
  176231. * Range-limiting need not be done explicitly, as we have extended
  176232. * the colorindex table to produce the right answers for out-of-range
  176233. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  176234. * required amount of padding.
  176235. */
  176236. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  176237. input_ptr += nc;
  176238. output_ptr++;
  176239. col_index = (col_index + 1) & ODITHER_MASK;
  176240. }
  176241. }
  176242. /* Advance row index for next row */
  176243. row_index = (row_index + 1) & ODITHER_MASK;
  176244. cquantize->row_index = row_index;
  176245. }
  176246. }
  176247. METHODDEF(void)
  176248. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176249. JSAMPARRAY output_buf, int num_rows)
  176250. /* Fast path for out_color_components==3, with ordered dithering */
  176251. {
  176252. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176253. register int pixcode;
  176254. register JSAMPROW input_ptr;
  176255. register JSAMPROW output_ptr;
  176256. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176257. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176258. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176259. int * dither0; /* points to active row of dither matrix */
  176260. int * dither1;
  176261. int * dither2;
  176262. int row_index, col_index; /* current indexes into dither matrix */
  176263. int row;
  176264. JDIMENSION col;
  176265. JDIMENSION width = cinfo->output_width;
  176266. for (row = 0; row < num_rows; row++) {
  176267. row_index = cquantize->row_index;
  176268. input_ptr = input_buf[row];
  176269. output_ptr = output_buf[row];
  176270. dither0 = cquantize->odither[0][row_index];
  176271. dither1 = cquantize->odither[1][row_index];
  176272. dither2 = cquantize->odither[2][row_index];
  176273. col_index = 0;
  176274. for (col = width; col > 0; col--) {
  176275. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  176276. dither0[col_index]]);
  176277. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  176278. dither1[col_index]]);
  176279. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  176280. dither2[col_index]]);
  176281. *output_ptr++ = (JSAMPLE) pixcode;
  176282. col_index = (col_index + 1) & ODITHER_MASK;
  176283. }
  176284. row_index = (row_index + 1) & ODITHER_MASK;
  176285. cquantize->row_index = row_index;
  176286. }
  176287. }
  176288. METHODDEF(void)
  176289. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176290. JSAMPARRAY output_buf, int num_rows)
  176291. /* General case, with Floyd-Steinberg dithering */
  176292. {
  176293. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176294. register LOCFSERROR cur; /* current error or pixel value */
  176295. LOCFSERROR belowerr; /* error for pixel below cur */
  176296. LOCFSERROR bpreverr; /* error for below/prev col */
  176297. LOCFSERROR bnexterr; /* error for below/next col */
  176298. LOCFSERROR delta;
  176299. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  176300. register JSAMPROW input_ptr;
  176301. register JSAMPROW output_ptr;
  176302. JSAMPROW colorindex_ci;
  176303. JSAMPROW colormap_ci;
  176304. int pixcode;
  176305. int nc = cinfo->out_color_components;
  176306. int dir; /* 1 for left-to-right, -1 for right-to-left */
  176307. int dirnc; /* dir * nc */
  176308. int ci;
  176309. int row;
  176310. JDIMENSION col;
  176311. JDIMENSION width = cinfo->output_width;
  176312. JSAMPLE *range_limit = cinfo->sample_range_limit;
  176313. SHIFT_TEMPS
  176314. for (row = 0; row < num_rows; row++) {
  176315. /* Initialize output values to 0 so can process components separately */
  176316. jzero_far((void FAR *) output_buf[row],
  176317. (size_t) (width * SIZEOF(JSAMPLE)));
  176318. for (ci = 0; ci < nc; ci++) {
  176319. input_ptr = input_buf[row] + ci;
  176320. output_ptr = output_buf[row];
  176321. if (cquantize->on_odd_row) {
  176322. /* work right to left in this row */
  176323. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  176324. output_ptr += width-1;
  176325. dir = -1;
  176326. dirnc = -nc;
  176327. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  176328. } else {
  176329. /* work left to right in this row */
  176330. dir = 1;
  176331. dirnc = nc;
  176332. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  176333. }
  176334. colorindex_ci = cquantize->colorindex[ci];
  176335. colormap_ci = cquantize->sv_colormap[ci];
  176336. /* Preset error values: no error propagated to first pixel from left */
  176337. cur = 0;
  176338. /* and no error propagated to row below yet */
  176339. belowerr = bpreverr = 0;
  176340. for (col = width; col > 0; col--) {
  176341. /* cur holds the error propagated from the previous pixel on the
  176342. * current line. Add the error propagated from the previous line
  176343. * to form the complete error correction term for this pixel, and
  176344. * round the error term (which is expressed * 16) to an integer.
  176345. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  176346. * for either sign of the error value.
  176347. * Note: errorptr points to *previous* column's array entry.
  176348. */
  176349. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  176350. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  176351. * The maximum error is +- MAXJSAMPLE; this sets the required size
  176352. * of the range_limit array.
  176353. */
  176354. cur += GETJSAMPLE(*input_ptr);
  176355. cur = GETJSAMPLE(range_limit[cur]);
  176356. /* Select output value, accumulate into output code for this pixel */
  176357. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  176358. *output_ptr += (JSAMPLE) pixcode;
  176359. /* Compute actual representation error at this pixel */
  176360. /* Note: we can do this even though we don't have the final */
  176361. /* pixel code, because the colormap is orthogonal. */
  176362. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  176363. /* Compute error fractions to be propagated to adjacent pixels.
  176364. * Add these into the running sums, and simultaneously shift the
  176365. * next-line error sums left by 1 column.
  176366. */
  176367. bnexterr = cur;
  176368. delta = cur * 2;
  176369. cur += delta; /* form error * 3 */
  176370. errorptr[0] = (FSERROR) (bpreverr + cur);
  176371. cur += delta; /* form error * 5 */
  176372. bpreverr = belowerr + cur;
  176373. belowerr = bnexterr;
  176374. cur += delta; /* form error * 7 */
  176375. /* At this point cur contains the 7/16 error value to be propagated
  176376. * to the next pixel on the current line, and all the errors for the
  176377. * next line have been shifted over. We are therefore ready to move on.
  176378. */
  176379. input_ptr += dirnc; /* advance input ptr to next column */
  176380. output_ptr += dir; /* advance output ptr to next column */
  176381. errorptr += dir; /* advance errorptr to current column */
  176382. }
  176383. /* Post-loop cleanup: we must unload the final error value into the
  176384. * final fserrors[] entry. Note we need not unload belowerr because
  176385. * it is for the dummy column before or after the actual array.
  176386. */
  176387. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  176388. }
  176389. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  176390. }
  176391. }
  176392. /*
  176393. * Allocate workspace for Floyd-Steinberg errors.
  176394. */
  176395. LOCAL(void)
  176396. alloc_fs_workspace (j_decompress_ptr cinfo)
  176397. {
  176398. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176399. size_t arraysize;
  176400. int i;
  176401. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  176402. for (i = 0; i < cinfo->out_color_components; i++) {
  176403. cquantize->fserrors[i] = (FSERRPTR)
  176404. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  176405. }
  176406. }
  176407. /*
  176408. * Initialize for one-pass color quantization.
  176409. */
  176410. METHODDEF(void)
  176411. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  176412. {
  176413. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176414. size_t arraysize;
  176415. int i;
  176416. /* Install my colormap. */
  176417. cinfo->colormap = cquantize->sv_colormap;
  176418. cinfo->actual_number_of_colors = cquantize->sv_actual;
  176419. /* Initialize for desired dithering mode. */
  176420. switch (cinfo->dither_mode) {
  176421. case JDITHER_NONE:
  176422. if (cinfo->out_color_components == 3)
  176423. cquantize->pub.color_quantize = color_quantize3;
  176424. else
  176425. cquantize->pub.color_quantize = color_quantize;
  176426. break;
  176427. case JDITHER_ORDERED:
  176428. if (cinfo->out_color_components == 3)
  176429. cquantize->pub.color_quantize = quantize3_ord_dither;
  176430. else
  176431. cquantize->pub.color_quantize = quantize_ord_dither;
  176432. cquantize->row_index = 0; /* initialize state for ordered dither */
  176433. /* If user changed to ordered dither from another mode,
  176434. * we must recreate the color index table with padding.
  176435. * This will cost extra space, but probably isn't very likely.
  176436. */
  176437. if (! cquantize->is_padded)
  176438. create_colorindex(cinfo);
  176439. /* Create ordered-dither tables if we didn't already. */
  176440. if (cquantize->odither[0] == NULL)
  176441. create_odither_tables(cinfo);
  176442. break;
  176443. case JDITHER_FS:
  176444. cquantize->pub.color_quantize = quantize_fs_dither;
  176445. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  176446. /* Allocate Floyd-Steinberg workspace if didn't already. */
  176447. if (cquantize->fserrors[0] == NULL)
  176448. alloc_fs_workspace(cinfo);
  176449. /* Initialize the propagated errors to zero. */
  176450. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  176451. for (i = 0; i < cinfo->out_color_components; i++)
  176452. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  176453. break;
  176454. default:
  176455. ERREXIT(cinfo, JERR_NOT_COMPILED);
  176456. break;
  176457. }
  176458. }
  176459. /*
  176460. * Finish up at the end of the pass.
  176461. */
  176462. METHODDEF(void)
  176463. finish_pass_1_quant (j_decompress_ptr)
  176464. {
  176465. /* no work in 1-pass case */
  176466. }
  176467. /*
  176468. * Switch to a new external colormap between output passes.
  176469. * Shouldn't get to this module!
  176470. */
  176471. METHODDEF(void)
  176472. new_color_map_1_quant (j_decompress_ptr cinfo)
  176473. {
  176474. ERREXIT(cinfo, JERR_MODE_CHANGE);
  176475. }
  176476. /*
  176477. * Module initialization routine for 1-pass color quantization.
  176478. */
  176479. GLOBAL(void)
  176480. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  176481. {
  176482. my_cquantize_ptr cquantize;
  176483. cquantize = (my_cquantize_ptr)
  176484. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176485. SIZEOF(my_cquantizer));
  176486. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  176487. cquantize->pub.start_pass = start_pass_1_quant;
  176488. cquantize->pub.finish_pass = finish_pass_1_quant;
  176489. cquantize->pub.new_color_map = new_color_map_1_quant;
  176490. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  176491. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  176492. /* Make sure my internal arrays won't overflow */
  176493. if (cinfo->out_color_components > MAX_Q_COMPS)
  176494. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  176495. /* Make sure colormap indexes can be represented by JSAMPLEs */
  176496. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  176497. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  176498. /* Create the colormap and color index table. */
  176499. create_colormap(cinfo);
  176500. create_colorindex(cinfo);
  176501. /* Allocate Floyd-Steinberg workspace now if requested.
  176502. * We do this now since it is FAR storage and may affect the memory
  176503. * manager's space calculations. If the user changes to FS dither
  176504. * mode in a later pass, we will allocate the space then, and will
  176505. * possibly overrun the max_memory_to_use setting.
  176506. */
  176507. if (cinfo->dither_mode == JDITHER_FS)
  176508. alloc_fs_workspace(cinfo);
  176509. }
  176510. #endif /* QUANT_1PASS_SUPPORTED */
  176511. /*** End of inlined file: jquant1.c ***/
  176512. /*** Start of inlined file: jquant2.c ***/
  176513. #define JPEG_INTERNALS
  176514. #ifdef QUANT_2PASS_SUPPORTED
  176515. /*
  176516. * This module implements the well-known Heckbert paradigm for color
  176517. * quantization. Most of the ideas used here can be traced back to
  176518. * Heckbert's seminal paper
  176519. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  176520. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  176521. *
  176522. * In the first pass over the image, we accumulate a histogram showing the
  176523. * usage count of each possible color. To keep the histogram to a reasonable
  176524. * size, we reduce the precision of the input; typical practice is to retain
  176525. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  176526. * in the same histogram cell.
  176527. *
  176528. * Next, the color-selection step begins with a box representing the whole
  176529. * color space, and repeatedly splits the "largest" remaining box until we
  176530. * have as many boxes as desired colors. Then the mean color in each
  176531. * remaining box becomes one of the possible output colors.
  176532. *
  176533. * The second pass over the image maps each input pixel to the closest output
  176534. * color (optionally after applying a Floyd-Steinberg dithering correction).
  176535. * This mapping is logically trivial, but making it go fast enough requires
  176536. * considerable care.
  176537. *
  176538. * Heckbert-style quantizers vary a good deal in their policies for choosing
  176539. * the "largest" box and deciding where to cut it. The particular policies
  176540. * used here have proved out well in experimental comparisons, but better ones
  176541. * may yet be found.
  176542. *
  176543. * In earlier versions of the IJG code, this module quantized in YCbCr color
  176544. * space, processing the raw upsampled data without a color conversion step.
  176545. * This allowed the color conversion math to be done only once per colormap
  176546. * entry, not once per pixel. However, that optimization precluded other
  176547. * useful optimizations (such as merging color conversion with upsampling)
  176548. * and it also interfered with desired capabilities such as quantizing to an
  176549. * externally-supplied colormap. We have therefore abandoned that approach.
  176550. * The present code works in the post-conversion color space, typically RGB.
  176551. *
  176552. * To improve the visual quality of the results, we actually work in scaled
  176553. * RGB space, giving G distances more weight than R, and R in turn more than
  176554. * B. To do everything in integer math, we must use integer scale factors.
  176555. * The 2/3/1 scale factors used here correspond loosely to the relative
  176556. * weights of the colors in the NTSC grayscale equation.
  176557. * If you want to use this code to quantize a non-RGB color space, you'll
  176558. * probably need to change these scale factors.
  176559. */
  176560. #define R_SCALE 2 /* scale R distances by this much */
  176561. #define G_SCALE 3 /* scale G distances by this much */
  176562. #define B_SCALE 1 /* and B by this much */
  176563. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  176564. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  176565. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  176566. * you'll get compile errors until you extend this logic. In that case
  176567. * you'll probably want to tweak the histogram sizes too.
  176568. */
  176569. #if RGB_RED == 0
  176570. #define C0_SCALE R_SCALE
  176571. #endif
  176572. #if RGB_BLUE == 0
  176573. #define C0_SCALE B_SCALE
  176574. #endif
  176575. #if RGB_GREEN == 1
  176576. #define C1_SCALE G_SCALE
  176577. #endif
  176578. #if RGB_RED == 2
  176579. #define C2_SCALE R_SCALE
  176580. #endif
  176581. #if RGB_BLUE == 2
  176582. #define C2_SCALE B_SCALE
  176583. #endif
  176584. /*
  176585. * First we have the histogram data structure and routines for creating it.
  176586. *
  176587. * The number of bits of precision can be adjusted by changing these symbols.
  176588. * We recommend keeping 6 bits for G and 5 each for R and B.
  176589. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  176590. * better results; if you are short of memory, 5 bits all around will save
  176591. * some space but degrade the results.
  176592. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  176593. * (preferably unsigned long) for each cell. In practice this is overkill;
  176594. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  176595. * and clamping those that do overflow to the maximum value will give close-
  176596. * enough results. This reduces the recommended histogram size from 256Kb
  176597. * to 128Kb, which is a useful savings on PC-class machines.
  176598. * (In the second pass the histogram space is re-used for pixel mapping data;
  176599. * in that capacity, each cell must be able to store zero to the number of
  176600. * desired colors. 16 bits/cell is plenty for that too.)
  176601. * Since the JPEG code is intended to run in small memory model on 80x86
  176602. * machines, we can't just allocate the histogram in one chunk. Instead
  176603. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  176604. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  176605. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  176606. * on 80x86 machines, the pointer row is in near memory but the actual
  176607. * arrays are in far memory (same arrangement as we use for image arrays).
  176608. */
  176609. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  176610. /* These will do the right thing for either R,G,B or B,G,R color order,
  176611. * but you may not like the results for other color orders.
  176612. */
  176613. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  176614. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  176615. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  176616. /* Number of elements along histogram axes. */
  176617. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  176618. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  176619. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  176620. /* These are the amounts to shift an input value to get a histogram index. */
  176621. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  176622. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  176623. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  176624. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  176625. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  176626. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  176627. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  176628. typedef hist2d * hist3d; /* type for top-level pointer */
  176629. /* Declarations for Floyd-Steinberg dithering.
  176630. *
  176631. * Errors are accumulated into the array fserrors[], at a resolution of
  176632. * 1/16th of a pixel count. The error at a given pixel is propagated
  176633. * to its not-yet-processed neighbors using the standard F-S fractions,
  176634. * ... (here) 7/16
  176635. * 3/16 5/16 1/16
  176636. * We work left-to-right on even rows, right-to-left on odd rows.
  176637. *
  176638. * We can get away with a single array (holding one row's worth of errors)
  176639. * by using it to store the current row's errors at pixel columns not yet
  176640. * processed, but the next row's errors at columns already processed. We
  176641. * need only a few extra variables to hold the errors immediately around the
  176642. * current column. (If we are lucky, those variables are in registers, but
  176643. * even if not, they're probably cheaper to access than array elements are.)
  176644. *
  176645. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  176646. * each end saves us from special-casing the first and last pixels.
  176647. * Each entry is three values long, one value for each color component.
  176648. *
  176649. * Note: on a wide image, we might not have enough room in a PC's near data
  176650. * segment to hold the error array; so it is allocated with alloc_large.
  176651. */
  176652. #if BITS_IN_JSAMPLE == 8
  176653. typedef INT16 FSERROR; /* 16 bits should be enough */
  176654. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176655. #else
  176656. typedef INT32 FSERROR; /* may need more than 16 bits */
  176657. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176658. #endif
  176659. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176660. /* Private subobject */
  176661. typedef struct {
  176662. struct jpeg_color_quantizer pub; /* public fields */
  176663. /* Space for the eventually created colormap is stashed here */
  176664. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  176665. int desired; /* desired # of colors = size of colormap */
  176666. /* Variables for accumulating image statistics */
  176667. hist3d histogram; /* pointer to the histogram */
  176668. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  176669. /* Variables for Floyd-Steinberg dithering */
  176670. FSERRPTR fserrors; /* accumulated errors */
  176671. boolean on_odd_row; /* flag to remember which row we are on */
  176672. int * error_limiter; /* table for clamping the applied error */
  176673. } my_cquantizer2;
  176674. typedef my_cquantizer2 * my_cquantize_ptr2;
  176675. /*
  176676. * Prescan some rows of pixels.
  176677. * In this module the prescan simply updates the histogram, which has been
  176678. * initialized to zeroes by start_pass.
  176679. * An output_buf parameter is required by the method signature, but no data
  176680. * is actually output (in fact the buffer controller is probably passing a
  176681. * NULL pointer).
  176682. */
  176683. METHODDEF(void)
  176684. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176685. JSAMPARRAY, int num_rows)
  176686. {
  176687. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  176688. register JSAMPROW ptr;
  176689. register histptr histp;
  176690. register hist3d histogram = cquantize->histogram;
  176691. int row;
  176692. JDIMENSION col;
  176693. JDIMENSION width = cinfo->output_width;
  176694. for (row = 0; row < num_rows; row++) {
  176695. ptr = input_buf[row];
  176696. for (col = width; col > 0; col--) {
  176697. /* get pixel value and index into the histogram */
  176698. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  176699. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  176700. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  176701. /* increment, check for overflow and undo increment if so. */
  176702. if (++(*histp) <= 0)
  176703. (*histp)--;
  176704. ptr += 3;
  176705. }
  176706. }
  176707. }
  176708. /*
  176709. * Next we have the really interesting routines: selection of a colormap
  176710. * given the completed histogram.
  176711. * These routines work with a list of "boxes", each representing a rectangular
  176712. * subset of the input color space (to histogram precision).
  176713. */
  176714. typedef struct {
  176715. /* The bounds of the box (inclusive); expressed as histogram indexes */
  176716. int c0min, c0max;
  176717. int c1min, c1max;
  176718. int c2min, c2max;
  176719. /* The volume (actually 2-norm) of the box */
  176720. INT32 volume;
  176721. /* The number of nonzero histogram cells within this box */
  176722. long colorcount;
  176723. } box;
  176724. typedef box * boxptr;
  176725. LOCAL(boxptr)
  176726. find_biggest_color_pop (boxptr boxlist, int numboxes)
  176727. /* Find the splittable box with the largest color population */
  176728. /* Returns NULL if no splittable boxes remain */
  176729. {
  176730. register boxptr boxp;
  176731. register int i;
  176732. register long maxc = 0;
  176733. boxptr which = NULL;
  176734. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  176735. if (boxp->colorcount > maxc && boxp->volume > 0) {
  176736. which = boxp;
  176737. maxc = boxp->colorcount;
  176738. }
  176739. }
  176740. return which;
  176741. }
  176742. LOCAL(boxptr)
  176743. find_biggest_volume (boxptr boxlist, int numboxes)
  176744. /* Find the splittable box with the largest (scaled) volume */
  176745. /* Returns NULL if no splittable boxes remain */
  176746. {
  176747. register boxptr boxp;
  176748. register int i;
  176749. register INT32 maxv = 0;
  176750. boxptr which = NULL;
  176751. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  176752. if (boxp->volume > maxv) {
  176753. which = boxp;
  176754. maxv = boxp->volume;
  176755. }
  176756. }
  176757. return which;
  176758. }
  176759. LOCAL(void)
  176760. update_box (j_decompress_ptr cinfo, boxptr boxp)
  176761. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  176762. /* and recompute its volume and population */
  176763. {
  176764. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  176765. hist3d histogram = cquantize->histogram;
  176766. histptr histp;
  176767. int c0,c1,c2;
  176768. int c0min,c0max,c1min,c1max,c2min,c2max;
  176769. INT32 dist0,dist1,dist2;
  176770. long ccount;
  176771. c0min = boxp->c0min; c0max = boxp->c0max;
  176772. c1min = boxp->c1min; c1max = boxp->c1max;
  176773. c2min = boxp->c2min; c2max = boxp->c2max;
  176774. if (c0max > c0min)
  176775. for (c0 = c0min; c0 <= c0max; c0++)
  176776. for (c1 = c1min; c1 <= c1max; c1++) {
  176777. histp = & histogram[c0][c1][c2min];
  176778. for (c2 = c2min; c2 <= c2max; c2++)
  176779. if (*histp++ != 0) {
  176780. boxp->c0min = c0min = c0;
  176781. goto have_c0min;
  176782. }
  176783. }
  176784. have_c0min:
  176785. if (c0max > c0min)
  176786. for (c0 = c0max; c0 >= c0min; c0--)
  176787. for (c1 = c1min; c1 <= c1max; c1++) {
  176788. histp = & histogram[c0][c1][c2min];
  176789. for (c2 = c2min; c2 <= c2max; c2++)
  176790. if (*histp++ != 0) {
  176791. boxp->c0max = c0max = c0;
  176792. goto have_c0max;
  176793. }
  176794. }
  176795. have_c0max:
  176796. if (c1max > c1min)
  176797. for (c1 = c1min; c1 <= c1max; c1++)
  176798. for (c0 = c0min; c0 <= c0max; c0++) {
  176799. histp = & histogram[c0][c1][c2min];
  176800. for (c2 = c2min; c2 <= c2max; c2++)
  176801. if (*histp++ != 0) {
  176802. boxp->c1min = c1min = c1;
  176803. goto have_c1min;
  176804. }
  176805. }
  176806. have_c1min:
  176807. if (c1max > c1min)
  176808. for (c1 = c1max; c1 >= c1min; c1--)
  176809. for (c0 = c0min; c0 <= c0max; c0++) {
  176810. histp = & histogram[c0][c1][c2min];
  176811. for (c2 = c2min; c2 <= c2max; c2++)
  176812. if (*histp++ != 0) {
  176813. boxp->c1max = c1max = c1;
  176814. goto have_c1max;
  176815. }
  176816. }
  176817. have_c1max:
  176818. if (c2max > c2min)
  176819. for (c2 = c2min; c2 <= c2max; c2++)
  176820. for (c0 = c0min; c0 <= c0max; c0++) {
  176821. histp = & histogram[c0][c1min][c2];
  176822. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  176823. if (*histp != 0) {
  176824. boxp->c2min = c2min = c2;
  176825. goto have_c2min;
  176826. }
  176827. }
  176828. have_c2min:
  176829. if (c2max > c2min)
  176830. for (c2 = c2max; c2 >= c2min; c2--)
  176831. for (c0 = c0min; c0 <= c0max; c0++) {
  176832. histp = & histogram[c0][c1min][c2];
  176833. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  176834. if (*histp != 0) {
  176835. boxp->c2max = c2max = c2;
  176836. goto have_c2max;
  176837. }
  176838. }
  176839. have_c2max:
  176840. /* Update box volume.
  176841. * We use 2-norm rather than real volume here; this biases the method
  176842. * against making long narrow boxes, and it has the side benefit that
  176843. * a box is splittable iff norm > 0.
  176844. * Since the differences are expressed in histogram-cell units,
  176845. * we have to shift back to JSAMPLE units to get consistent distances;
  176846. * after which, we scale according to the selected distance scale factors.
  176847. */
  176848. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  176849. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  176850. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  176851. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  176852. /* Now scan remaining volume of box and compute population */
  176853. ccount = 0;
  176854. for (c0 = c0min; c0 <= c0max; c0++)
  176855. for (c1 = c1min; c1 <= c1max; c1++) {
  176856. histp = & histogram[c0][c1][c2min];
  176857. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  176858. if (*histp != 0) {
  176859. ccount++;
  176860. }
  176861. }
  176862. boxp->colorcount = ccount;
  176863. }
  176864. LOCAL(int)
  176865. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  176866. int desired_colors)
  176867. /* Repeatedly select and split the largest box until we have enough boxes */
  176868. {
  176869. int n,lb;
  176870. int c0,c1,c2,cmax;
  176871. register boxptr b1,b2;
  176872. while (numboxes < desired_colors) {
  176873. /* Select box to split.
  176874. * Current algorithm: by population for first half, then by volume.
  176875. */
  176876. if (numboxes*2 <= desired_colors) {
  176877. b1 = find_biggest_color_pop(boxlist, numboxes);
  176878. } else {
  176879. b1 = find_biggest_volume(boxlist, numboxes);
  176880. }
  176881. if (b1 == NULL) /* no splittable boxes left! */
  176882. break;
  176883. b2 = &boxlist[numboxes]; /* where new box will go */
  176884. /* Copy the color bounds to the new box. */
  176885. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  176886. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  176887. /* Choose which axis to split the box on.
  176888. * Current algorithm: longest scaled axis.
  176889. * See notes in update_box about scaling distances.
  176890. */
  176891. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  176892. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  176893. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  176894. /* We want to break any ties in favor of green, then red, blue last.
  176895. * This code does the right thing for R,G,B or B,G,R color orders only.
  176896. */
  176897. #if RGB_RED == 0
  176898. cmax = c1; n = 1;
  176899. if (c0 > cmax) { cmax = c0; n = 0; }
  176900. if (c2 > cmax) { n = 2; }
  176901. #else
  176902. cmax = c1; n = 1;
  176903. if (c2 > cmax) { cmax = c2; n = 2; }
  176904. if (c0 > cmax) { n = 0; }
  176905. #endif
  176906. /* Choose split point along selected axis, and update box bounds.
  176907. * Current algorithm: split at halfway point.
  176908. * (Since the box has been shrunk to minimum volume,
  176909. * any split will produce two nonempty subboxes.)
  176910. * Note that lb value is max for lower box, so must be < old max.
  176911. */
  176912. switch (n) {
  176913. case 0:
  176914. lb = (b1->c0max + b1->c0min) / 2;
  176915. b1->c0max = lb;
  176916. b2->c0min = lb+1;
  176917. break;
  176918. case 1:
  176919. lb = (b1->c1max + b1->c1min) / 2;
  176920. b1->c1max = lb;
  176921. b2->c1min = lb+1;
  176922. break;
  176923. case 2:
  176924. lb = (b1->c2max + b1->c2min) / 2;
  176925. b1->c2max = lb;
  176926. b2->c2min = lb+1;
  176927. break;
  176928. }
  176929. /* Update stats for boxes */
  176930. update_box(cinfo, b1);
  176931. update_box(cinfo, b2);
  176932. numboxes++;
  176933. }
  176934. return numboxes;
  176935. }
  176936. LOCAL(void)
  176937. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  176938. /* Compute representative color for a box, put it in colormap[icolor] */
  176939. {
  176940. /* Current algorithm: mean weighted by pixels (not colors) */
  176941. /* Note it is important to get the rounding correct! */
  176942. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  176943. hist3d histogram = cquantize->histogram;
  176944. histptr histp;
  176945. int c0,c1,c2;
  176946. int c0min,c0max,c1min,c1max,c2min,c2max;
  176947. long count;
  176948. long total = 0;
  176949. long c0total = 0;
  176950. long c1total = 0;
  176951. long c2total = 0;
  176952. c0min = boxp->c0min; c0max = boxp->c0max;
  176953. c1min = boxp->c1min; c1max = boxp->c1max;
  176954. c2min = boxp->c2min; c2max = boxp->c2max;
  176955. for (c0 = c0min; c0 <= c0max; c0++)
  176956. for (c1 = c1min; c1 <= c1max; c1++) {
  176957. histp = & histogram[c0][c1][c2min];
  176958. for (c2 = c2min; c2 <= c2max; c2++) {
  176959. if ((count = *histp++) != 0) {
  176960. total += count;
  176961. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  176962. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  176963. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  176964. }
  176965. }
  176966. }
  176967. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  176968. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  176969. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  176970. }
  176971. LOCAL(void)
  176972. select_colors (j_decompress_ptr cinfo, int desired_colors)
  176973. /* Master routine for color selection */
  176974. {
  176975. boxptr boxlist;
  176976. int numboxes;
  176977. int i;
  176978. /* Allocate workspace for box list */
  176979. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  176980. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  176981. /* Initialize one box containing whole space */
  176982. numboxes = 1;
  176983. boxlist[0].c0min = 0;
  176984. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  176985. boxlist[0].c1min = 0;
  176986. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  176987. boxlist[0].c2min = 0;
  176988. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  176989. /* Shrink it to actually-used volume and set its statistics */
  176990. update_box(cinfo, & boxlist[0]);
  176991. /* Perform median-cut to produce final box list */
  176992. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  176993. /* Compute the representative color for each box, fill colormap */
  176994. for (i = 0; i < numboxes; i++)
  176995. compute_color(cinfo, & boxlist[i], i);
  176996. cinfo->actual_number_of_colors = numboxes;
  176997. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  176998. }
  176999. /*
  177000. * These routines are concerned with the time-critical task of mapping input
  177001. * colors to the nearest color in the selected colormap.
  177002. *
  177003. * We re-use the histogram space as an "inverse color map", essentially a
  177004. * cache for the results of nearest-color searches. All colors within a
  177005. * histogram cell will be mapped to the same colormap entry, namely the one
  177006. * closest to the cell's center. This may not be quite the closest entry to
  177007. * the actual input color, but it's almost as good. A zero in the cache
  177008. * indicates we haven't found the nearest color for that cell yet; the array
  177009. * is cleared to zeroes before starting the mapping pass. When we find the
  177010. * nearest color for a cell, its colormap index plus one is recorded in the
  177011. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177012. * when they need to use an unfilled entry in the cache.
  177013. *
  177014. * Our method of efficiently finding nearest colors is based on the "locally
  177015. * sorted search" idea described by Heckbert and on the incremental distance
  177016. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177017. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177018. * the distances from a given colormap entry to each cell of the histogram can
  177019. * be computed quickly using an incremental method: the differences between
  177020. * distances to adjacent cells themselves differ by a constant. This allows a
  177021. * fairly fast implementation of the "brute force" approach of computing the
  177022. * distance from every colormap entry to every histogram cell. Unfortunately,
  177023. * it needs a work array to hold the best-distance-so-far for each histogram
  177024. * cell (because the inner loop has to be over cells, not colormap entries).
  177025. * The work array elements have to be INT32s, so the work array would need
  177026. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177027. *
  177028. * To get around these problems, we apply Thomas' method to compute the
  177029. * nearest colors for only the cells within a small subbox of the histogram.
  177030. * The work array need be only as big as the subbox, so the memory usage
  177031. * problem is solved. Furthermore, we need not fill subboxes that are never
  177032. * referenced in pass2; many images use only part of the color gamut, so a
  177033. * fair amount of work is saved. An additional advantage of this
  177034. * approach is that we can apply Heckbert's locality criterion to quickly
  177035. * eliminate colormap entries that are far away from the subbox; typically
  177036. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177037. * and we need not compute their distances to individual cells in the subbox.
  177038. * The speed of this approach is heavily influenced by the subbox size: too
  177039. * small means too much overhead, too big loses because Heckbert's criterion
  177040. * can't eliminate as many colormap entries. Empirically the best subbox
  177041. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177042. *
  177043. * Thomas' article also describes a refined method which is asymptotically
  177044. * faster than the brute-force method, but it is also far more complex and
  177045. * cannot efficiently be applied to small subboxes. It is therefore not
  177046. * useful for programs intended to be portable to DOS machines. On machines
  177047. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177048. * refined method might be faster than the present code --- but then again,
  177049. * it might not be any faster, and it's certainly more complicated.
  177050. */
  177051. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177052. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177053. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177054. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177055. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177056. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177057. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177058. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177059. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177060. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177061. /*
  177062. * The next three routines implement inverse colormap filling. They could
  177063. * all be folded into one big routine, but splitting them up this way saves
  177064. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177065. * and may allow some compilers to produce better code by registerizing more
  177066. * inner-loop variables.
  177067. */
  177068. LOCAL(int)
  177069. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177070. JSAMPLE colorlist[])
  177071. /* Locate the colormap entries close enough to an update box to be candidates
  177072. * for the nearest entry to some cell(s) in the update box. The update box
  177073. * is specified by the center coordinates of its first cell. The number of
  177074. * candidate colormap entries is returned, and their colormap indexes are
  177075. * placed in colorlist[].
  177076. * This routine uses Heckbert's "locally sorted search" criterion to select
  177077. * the colors that need further consideration.
  177078. */
  177079. {
  177080. int numcolors = cinfo->actual_number_of_colors;
  177081. int maxc0, maxc1, maxc2;
  177082. int centerc0, centerc1, centerc2;
  177083. int i, x, ncolors;
  177084. INT32 minmaxdist, min_dist, max_dist, tdist;
  177085. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177086. /* Compute true coordinates of update box's upper corner and center.
  177087. * Actually we compute the coordinates of the center of the upper-corner
  177088. * histogram cell, which are the upper bounds of the volume we care about.
  177089. * Note that since ">>" rounds down, the "center" values may be closer to
  177090. * min than to max; hence comparisons to them must be "<=", not "<".
  177091. */
  177092. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177093. centerc0 = (minc0 + maxc0) >> 1;
  177094. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177095. centerc1 = (minc1 + maxc1) >> 1;
  177096. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177097. centerc2 = (minc2 + maxc2) >> 1;
  177098. /* For each color in colormap, find:
  177099. * 1. its minimum squared-distance to any point in the update box
  177100. * (zero if color is within update box);
  177101. * 2. its maximum squared-distance to any point in the update box.
  177102. * Both of these can be found by considering only the corners of the box.
  177103. * We save the minimum distance for each color in mindist[];
  177104. * only the smallest maximum distance is of interest.
  177105. */
  177106. minmaxdist = 0x7FFFFFFFL;
  177107. for (i = 0; i < numcolors; i++) {
  177108. /* We compute the squared-c0-distance term, then add in the other two. */
  177109. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177110. if (x < minc0) {
  177111. tdist = (x - minc0) * C0_SCALE;
  177112. min_dist = tdist*tdist;
  177113. tdist = (x - maxc0) * C0_SCALE;
  177114. max_dist = tdist*tdist;
  177115. } else if (x > maxc0) {
  177116. tdist = (x - maxc0) * C0_SCALE;
  177117. min_dist = tdist*tdist;
  177118. tdist = (x - minc0) * C0_SCALE;
  177119. max_dist = tdist*tdist;
  177120. } else {
  177121. /* within cell range so no contribution to min_dist */
  177122. min_dist = 0;
  177123. if (x <= centerc0) {
  177124. tdist = (x - maxc0) * C0_SCALE;
  177125. max_dist = tdist*tdist;
  177126. } else {
  177127. tdist = (x - minc0) * C0_SCALE;
  177128. max_dist = tdist*tdist;
  177129. }
  177130. }
  177131. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177132. if (x < minc1) {
  177133. tdist = (x - minc1) * C1_SCALE;
  177134. min_dist += tdist*tdist;
  177135. tdist = (x - maxc1) * C1_SCALE;
  177136. max_dist += tdist*tdist;
  177137. } else if (x > maxc1) {
  177138. tdist = (x - maxc1) * C1_SCALE;
  177139. min_dist += tdist*tdist;
  177140. tdist = (x - minc1) * C1_SCALE;
  177141. max_dist += tdist*tdist;
  177142. } else {
  177143. /* within cell range so no contribution to min_dist */
  177144. if (x <= centerc1) {
  177145. tdist = (x - maxc1) * C1_SCALE;
  177146. max_dist += tdist*tdist;
  177147. } else {
  177148. tdist = (x - minc1) * C1_SCALE;
  177149. max_dist += tdist*tdist;
  177150. }
  177151. }
  177152. x = GETJSAMPLE(cinfo->colormap[2][i]);
  177153. if (x < minc2) {
  177154. tdist = (x - minc2) * C2_SCALE;
  177155. min_dist += tdist*tdist;
  177156. tdist = (x - maxc2) * C2_SCALE;
  177157. max_dist += tdist*tdist;
  177158. } else if (x > maxc2) {
  177159. tdist = (x - maxc2) * C2_SCALE;
  177160. min_dist += tdist*tdist;
  177161. tdist = (x - minc2) * C2_SCALE;
  177162. max_dist += tdist*tdist;
  177163. } else {
  177164. /* within cell range so no contribution to min_dist */
  177165. if (x <= centerc2) {
  177166. tdist = (x - maxc2) * C2_SCALE;
  177167. max_dist += tdist*tdist;
  177168. } else {
  177169. tdist = (x - minc2) * C2_SCALE;
  177170. max_dist += tdist*tdist;
  177171. }
  177172. }
  177173. mindist[i] = min_dist; /* save away the results */
  177174. if (max_dist < minmaxdist)
  177175. minmaxdist = max_dist;
  177176. }
  177177. /* Now we know that no cell in the update box is more than minmaxdist
  177178. * away from some colormap entry. Therefore, only colors that are
  177179. * within minmaxdist of some part of the box need be considered.
  177180. */
  177181. ncolors = 0;
  177182. for (i = 0; i < numcolors; i++) {
  177183. if (mindist[i] <= minmaxdist)
  177184. colorlist[ncolors++] = (JSAMPLE) i;
  177185. }
  177186. return ncolors;
  177187. }
  177188. LOCAL(void)
  177189. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177190. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  177191. /* Find the closest colormap entry for each cell in the update box,
  177192. * given the list of candidate colors prepared by find_nearby_colors.
  177193. * Return the indexes of the closest entries in the bestcolor[] array.
  177194. * This routine uses Thomas' incremental distance calculation method to
  177195. * find the distance from a colormap entry to successive cells in the box.
  177196. */
  177197. {
  177198. int ic0, ic1, ic2;
  177199. int i, icolor;
  177200. register INT32 * bptr; /* pointer into bestdist[] array */
  177201. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177202. INT32 dist0, dist1; /* initial distance values */
  177203. register INT32 dist2; /* current distance in inner loop */
  177204. INT32 xx0, xx1; /* distance increments */
  177205. register INT32 xx2;
  177206. INT32 inc0, inc1, inc2; /* initial values for increments */
  177207. /* This array holds the distance to the nearest-so-far color for each cell */
  177208. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177209. /* Initialize best-distance for each cell of the update box */
  177210. bptr = bestdist;
  177211. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  177212. *bptr++ = 0x7FFFFFFFL;
  177213. /* For each color selected by find_nearby_colors,
  177214. * compute its distance to the center of each cell in the box.
  177215. * If that's less than best-so-far, update best distance and color number.
  177216. */
  177217. /* Nominal steps between cell centers ("x" in Thomas article) */
  177218. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  177219. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  177220. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  177221. for (i = 0; i < numcolors; i++) {
  177222. icolor = GETJSAMPLE(colorlist[i]);
  177223. /* Compute (square of) distance from minc0/c1/c2 to this color */
  177224. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  177225. dist0 = inc0*inc0;
  177226. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  177227. dist0 += inc1*inc1;
  177228. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  177229. dist0 += inc2*inc2;
  177230. /* Form the initial difference increments */
  177231. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  177232. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  177233. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  177234. /* Now loop over all cells in box, updating distance per Thomas method */
  177235. bptr = bestdist;
  177236. cptr = bestcolor;
  177237. xx0 = inc0;
  177238. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  177239. dist1 = dist0;
  177240. xx1 = inc1;
  177241. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  177242. dist2 = dist1;
  177243. xx2 = inc2;
  177244. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  177245. if (dist2 < *bptr) {
  177246. *bptr = dist2;
  177247. *cptr = (JSAMPLE) icolor;
  177248. }
  177249. dist2 += xx2;
  177250. xx2 += 2 * STEP_C2 * STEP_C2;
  177251. bptr++;
  177252. cptr++;
  177253. }
  177254. dist1 += xx1;
  177255. xx1 += 2 * STEP_C1 * STEP_C1;
  177256. }
  177257. dist0 += xx0;
  177258. xx0 += 2 * STEP_C0 * STEP_C0;
  177259. }
  177260. }
  177261. }
  177262. LOCAL(void)
  177263. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  177264. /* Fill the inverse-colormap entries in the update box that contains */
  177265. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  177266. /* we can fill as many others as we wish.) */
  177267. {
  177268. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177269. hist3d histogram = cquantize->histogram;
  177270. int minc0, minc1, minc2; /* lower left corner of update box */
  177271. int ic0, ic1, ic2;
  177272. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177273. register histptr cachep; /* pointer into main cache array */
  177274. /* This array lists the candidate colormap indexes. */
  177275. JSAMPLE colorlist[MAXNUMCOLORS];
  177276. int numcolors; /* number of candidate colors */
  177277. /* This array holds the actually closest colormap index for each cell. */
  177278. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177279. /* Convert cell coordinates to update box ID */
  177280. c0 >>= BOX_C0_LOG;
  177281. c1 >>= BOX_C1_LOG;
  177282. c2 >>= BOX_C2_LOG;
  177283. /* Compute true coordinates of update box's origin corner.
  177284. * Actually we compute the coordinates of the center of the corner
  177285. * histogram cell, which are the lower bounds of the volume we care about.
  177286. */
  177287. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  177288. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  177289. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  177290. /* Determine which colormap entries are close enough to be candidates
  177291. * for the nearest entry to some cell in the update box.
  177292. */
  177293. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  177294. /* Determine the actually nearest colors. */
  177295. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  177296. bestcolor);
  177297. /* Save the best color numbers (plus 1) in the main cache array */
  177298. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  177299. c1 <<= BOX_C1_LOG;
  177300. c2 <<= BOX_C2_LOG;
  177301. cptr = bestcolor;
  177302. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  177303. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  177304. cachep = & histogram[c0+ic0][c1+ic1][c2];
  177305. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  177306. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  177307. }
  177308. }
  177309. }
  177310. }
  177311. /*
  177312. * Map some rows of pixels to the output colormapped representation.
  177313. */
  177314. METHODDEF(void)
  177315. pass2_no_dither (j_decompress_ptr cinfo,
  177316. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177317. /* This version performs no dithering */
  177318. {
  177319. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177320. hist3d histogram = cquantize->histogram;
  177321. register JSAMPROW inptr, outptr;
  177322. register histptr cachep;
  177323. register int c0, c1, c2;
  177324. int row;
  177325. JDIMENSION col;
  177326. JDIMENSION width = cinfo->output_width;
  177327. for (row = 0; row < num_rows; row++) {
  177328. inptr = input_buf[row];
  177329. outptr = output_buf[row];
  177330. for (col = width; col > 0; col--) {
  177331. /* get pixel value and index into the cache */
  177332. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  177333. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  177334. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  177335. cachep = & histogram[c0][c1][c2];
  177336. /* If we have not seen this color before, find nearest colormap entry */
  177337. /* and update the cache */
  177338. if (*cachep == 0)
  177339. fill_inverse_cmap(cinfo, c0,c1,c2);
  177340. /* Now emit the colormap index for this cell */
  177341. *outptr++ = (JSAMPLE) (*cachep - 1);
  177342. }
  177343. }
  177344. }
  177345. METHODDEF(void)
  177346. pass2_fs_dither (j_decompress_ptr cinfo,
  177347. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177348. /* This version performs Floyd-Steinberg dithering */
  177349. {
  177350. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177351. hist3d histogram = cquantize->histogram;
  177352. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  177353. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  177354. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  177355. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177356. JSAMPROW inptr; /* => current input pixel */
  177357. JSAMPROW outptr; /* => current output pixel */
  177358. histptr cachep;
  177359. int dir; /* +1 or -1 depending on direction */
  177360. int dir3; /* 3*dir, for advancing inptr & errorptr */
  177361. int row;
  177362. JDIMENSION col;
  177363. JDIMENSION width = cinfo->output_width;
  177364. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177365. int *error_limit = cquantize->error_limiter;
  177366. JSAMPROW colormap0 = cinfo->colormap[0];
  177367. JSAMPROW colormap1 = cinfo->colormap[1];
  177368. JSAMPROW colormap2 = cinfo->colormap[2];
  177369. SHIFT_TEMPS
  177370. for (row = 0; row < num_rows; row++) {
  177371. inptr = input_buf[row];
  177372. outptr = output_buf[row];
  177373. if (cquantize->on_odd_row) {
  177374. /* work right to left in this row */
  177375. inptr += (width-1) * 3; /* so point to rightmost pixel */
  177376. outptr += width-1;
  177377. dir = -1;
  177378. dir3 = -3;
  177379. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  177380. cquantize->on_odd_row = FALSE; /* flip for next time */
  177381. } else {
  177382. /* work left to right in this row */
  177383. dir = 1;
  177384. dir3 = 3;
  177385. errorptr = cquantize->fserrors; /* => entry before first real column */
  177386. cquantize->on_odd_row = TRUE; /* flip for next time */
  177387. }
  177388. /* Preset error values: no error propagated to first pixel from left */
  177389. cur0 = cur1 = cur2 = 0;
  177390. /* and no error propagated to row below yet */
  177391. belowerr0 = belowerr1 = belowerr2 = 0;
  177392. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  177393. for (col = width; col > 0; col--) {
  177394. /* curN holds the error propagated from the previous pixel on the
  177395. * current line. Add the error propagated from the previous line
  177396. * to form the complete error correction term for this pixel, and
  177397. * round the error term (which is expressed * 16) to an integer.
  177398. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177399. * for either sign of the error value.
  177400. * Note: errorptr points to *previous* column's array entry.
  177401. */
  177402. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  177403. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  177404. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  177405. /* Limit the error using transfer function set by init_error_limit.
  177406. * See comments with init_error_limit for rationale.
  177407. */
  177408. cur0 = error_limit[cur0];
  177409. cur1 = error_limit[cur1];
  177410. cur2 = error_limit[cur2];
  177411. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177412. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  177413. * this sets the required size of the range_limit array.
  177414. */
  177415. cur0 += GETJSAMPLE(inptr[0]);
  177416. cur1 += GETJSAMPLE(inptr[1]);
  177417. cur2 += GETJSAMPLE(inptr[2]);
  177418. cur0 = GETJSAMPLE(range_limit[cur0]);
  177419. cur1 = GETJSAMPLE(range_limit[cur1]);
  177420. cur2 = GETJSAMPLE(range_limit[cur2]);
  177421. /* Index into the cache with adjusted pixel value */
  177422. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  177423. /* If we have not seen this color before, find nearest colormap */
  177424. /* entry and update the cache */
  177425. if (*cachep == 0)
  177426. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  177427. /* Now emit the colormap index for this cell */
  177428. { register int pixcode = *cachep - 1;
  177429. *outptr = (JSAMPLE) pixcode;
  177430. /* Compute representation error for this pixel */
  177431. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  177432. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  177433. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  177434. }
  177435. /* Compute error fractions to be propagated to adjacent pixels.
  177436. * Add these into the running sums, and simultaneously shift the
  177437. * next-line error sums left by 1 column.
  177438. */
  177439. { register LOCFSERROR bnexterr, delta;
  177440. bnexterr = cur0; /* Process component 0 */
  177441. delta = cur0 * 2;
  177442. cur0 += delta; /* form error * 3 */
  177443. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  177444. cur0 += delta; /* form error * 5 */
  177445. bpreverr0 = belowerr0 + cur0;
  177446. belowerr0 = bnexterr;
  177447. cur0 += delta; /* form error * 7 */
  177448. bnexterr = cur1; /* Process component 1 */
  177449. delta = cur1 * 2;
  177450. cur1 += delta; /* form error * 3 */
  177451. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  177452. cur1 += delta; /* form error * 5 */
  177453. bpreverr1 = belowerr1 + cur1;
  177454. belowerr1 = bnexterr;
  177455. cur1 += delta; /* form error * 7 */
  177456. bnexterr = cur2; /* Process component 2 */
  177457. delta = cur2 * 2;
  177458. cur2 += delta; /* form error * 3 */
  177459. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  177460. cur2 += delta; /* form error * 5 */
  177461. bpreverr2 = belowerr2 + cur2;
  177462. belowerr2 = bnexterr;
  177463. cur2 += delta; /* form error * 7 */
  177464. }
  177465. /* At this point curN contains the 7/16 error value to be propagated
  177466. * to the next pixel on the current line, and all the errors for the
  177467. * next line have been shifted over. We are therefore ready to move on.
  177468. */
  177469. inptr += dir3; /* Advance pixel pointers to next column */
  177470. outptr += dir;
  177471. errorptr += dir3; /* advance errorptr to current column */
  177472. }
  177473. /* Post-loop cleanup: we must unload the final error values into the
  177474. * final fserrors[] entry. Note we need not unload belowerrN because
  177475. * it is for the dummy column before or after the actual array.
  177476. */
  177477. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  177478. errorptr[1] = (FSERROR) bpreverr1;
  177479. errorptr[2] = (FSERROR) bpreverr2;
  177480. }
  177481. }
  177482. /*
  177483. * Initialize the error-limiting transfer function (lookup table).
  177484. * The raw F-S error computation can potentially compute error values of up to
  177485. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  177486. * much less, otherwise obviously wrong pixels will be created. (Typical
  177487. * effects include weird fringes at color-area boundaries, isolated bright
  177488. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  177489. * is to ensure that the "corners" of the color cube are allocated as output
  177490. * colors; then repeated errors in the same direction cannot cause cascading
  177491. * error buildup. However, that only prevents the error from getting
  177492. * completely out of hand; Aaron Giles reports that error limiting improves
  177493. * the results even with corner colors allocated.
  177494. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  177495. * well, but the smoother transfer function used below is even better. Thanks
  177496. * to Aaron Giles for this idea.
  177497. */
  177498. LOCAL(void)
  177499. init_error_limit (j_decompress_ptr cinfo)
  177500. /* Allocate and fill in the error_limiter table */
  177501. {
  177502. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177503. int * table;
  177504. int in, out;
  177505. table = (int *) (*cinfo->mem->alloc_small)
  177506. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  177507. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  177508. cquantize->error_limiter = table;
  177509. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  177510. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  177511. out = 0;
  177512. for (in = 0; in < STEPSIZE; in++, out++) {
  177513. table[in] = out; table[-in] = -out;
  177514. }
  177515. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  177516. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  177517. table[in] = out; table[-in] = -out;
  177518. }
  177519. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  177520. for (; in <= MAXJSAMPLE; in++) {
  177521. table[in] = out; table[-in] = -out;
  177522. }
  177523. #undef STEPSIZE
  177524. }
  177525. /*
  177526. * Finish up at the end of each pass.
  177527. */
  177528. METHODDEF(void)
  177529. finish_pass1 (j_decompress_ptr cinfo)
  177530. {
  177531. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177532. /* Select the representative colors and fill in cinfo->colormap */
  177533. cinfo->colormap = cquantize->sv_colormap;
  177534. select_colors(cinfo, cquantize->desired);
  177535. /* Force next pass to zero the color index table */
  177536. cquantize->needs_zeroed = TRUE;
  177537. }
  177538. METHODDEF(void)
  177539. finish_pass2 (j_decompress_ptr)
  177540. {
  177541. /* no work */
  177542. }
  177543. /*
  177544. * Initialize for each processing pass.
  177545. */
  177546. METHODDEF(void)
  177547. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  177548. {
  177549. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177550. hist3d histogram = cquantize->histogram;
  177551. int i;
  177552. /* Only F-S dithering or no dithering is supported. */
  177553. /* If user asks for ordered dither, give him F-S. */
  177554. if (cinfo->dither_mode != JDITHER_NONE)
  177555. cinfo->dither_mode = JDITHER_FS;
  177556. if (is_pre_scan) {
  177557. /* Set up method pointers */
  177558. cquantize->pub.color_quantize = prescan_quantize;
  177559. cquantize->pub.finish_pass = finish_pass1;
  177560. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  177561. } else {
  177562. /* Set up method pointers */
  177563. if (cinfo->dither_mode == JDITHER_FS)
  177564. cquantize->pub.color_quantize = pass2_fs_dither;
  177565. else
  177566. cquantize->pub.color_quantize = pass2_no_dither;
  177567. cquantize->pub.finish_pass = finish_pass2;
  177568. /* Make sure color count is acceptable */
  177569. i = cinfo->actual_number_of_colors;
  177570. if (i < 1)
  177571. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  177572. if (i > MAXNUMCOLORS)
  177573. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  177574. if (cinfo->dither_mode == JDITHER_FS) {
  177575. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  177576. (3 * SIZEOF(FSERROR)));
  177577. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  177578. if (cquantize->fserrors == NULL)
  177579. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  177580. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177581. /* Initialize the propagated errors to zero. */
  177582. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  177583. /* Make the error-limit table if we didn't already. */
  177584. if (cquantize->error_limiter == NULL)
  177585. init_error_limit(cinfo);
  177586. cquantize->on_odd_row = FALSE;
  177587. }
  177588. }
  177589. /* Zero the histogram or inverse color map, if necessary */
  177590. if (cquantize->needs_zeroed) {
  177591. for (i = 0; i < HIST_C0_ELEMS; i++) {
  177592. jzero_far((void FAR *) histogram[i],
  177593. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  177594. }
  177595. cquantize->needs_zeroed = FALSE;
  177596. }
  177597. }
  177598. /*
  177599. * Switch to a new external colormap between output passes.
  177600. */
  177601. METHODDEF(void)
  177602. new_color_map_2_quant (j_decompress_ptr cinfo)
  177603. {
  177604. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177605. /* Reset the inverse color map */
  177606. cquantize->needs_zeroed = TRUE;
  177607. }
  177608. /*
  177609. * Module initialization routine for 2-pass color quantization.
  177610. */
  177611. GLOBAL(void)
  177612. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  177613. {
  177614. my_cquantize_ptr2 cquantize;
  177615. int i;
  177616. cquantize = (my_cquantize_ptr2)
  177617. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177618. SIZEOF(my_cquantizer2));
  177619. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177620. cquantize->pub.start_pass = start_pass_2_quant;
  177621. cquantize->pub.new_color_map = new_color_map_2_quant;
  177622. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  177623. cquantize->error_limiter = NULL;
  177624. /* Make sure jdmaster didn't give me a case I can't handle */
  177625. if (cinfo->out_color_components != 3)
  177626. ERREXIT(cinfo, JERR_NOTIMPL);
  177627. /* Allocate the histogram/inverse colormap storage */
  177628. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  177629. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  177630. for (i = 0; i < HIST_C0_ELEMS; i++) {
  177631. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  177632. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177633. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  177634. }
  177635. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  177636. /* Allocate storage for the completed colormap, if required.
  177637. * We do this now since it is FAR storage and may affect
  177638. * the memory manager's space calculations.
  177639. */
  177640. if (cinfo->enable_2pass_quant) {
  177641. /* Make sure color count is acceptable */
  177642. int desired = cinfo->desired_number_of_colors;
  177643. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  177644. if (desired < 8)
  177645. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  177646. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177647. if (desired > MAXNUMCOLORS)
  177648. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  177649. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  177650. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  177651. cquantize->desired = desired;
  177652. } else
  177653. cquantize->sv_colormap = NULL;
  177654. /* Only F-S dithering or no dithering is supported. */
  177655. /* If user asks for ordered dither, give him F-S. */
  177656. if (cinfo->dither_mode != JDITHER_NONE)
  177657. cinfo->dither_mode = JDITHER_FS;
  177658. /* Allocate Floyd-Steinberg workspace if necessary.
  177659. * This isn't really needed until pass 2, but again it is FAR storage.
  177660. * Although we will cope with a later change in dither_mode,
  177661. * we do not promise to honor max_memory_to_use if dither_mode changes.
  177662. */
  177663. if (cinfo->dither_mode == JDITHER_FS) {
  177664. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  177665. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177666. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  177667. /* Might as well create the error-limiting table too. */
  177668. init_error_limit(cinfo);
  177669. }
  177670. }
  177671. #endif /* QUANT_2PASS_SUPPORTED */
  177672. /*** End of inlined file: jquant2.c ***/
  177673. /*** Start of inlined file: jutils.c ***/
  177674. #define JPEG_INTERNALS
  177675. /*
  177676. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  177677. * of a DCT block read in natural order (left to right, top to bottom).
  177678. */
  177679. #if 0 /* This table is not actually needed in v6a */
  177680. const int jpeg_zigzag_order[DCTSIZE2] = {
  177681. 0, 1, 5, 6, 14, 15, 27, 28,
  177682. 2, 4, 7, 13, 16, 26, 29, 42,
  177683. 3, 8, 12, 17, 25, 30, 41, 43,
  177684. 9, 11, 18, 24, 31, 40, 44, 53,
  177685. 10, 19, 23, 32, 39, 45, 52, 54,
  177686. 20, 22, 33, 38, 46, 51, 55, 60,
  177687. 21, 34, 37, 47, 50, 56, 59, 61,
  177688. 35, 36, 48, 49, 57, 58, 62, 63
  177689. };
  177690. #endif
  177691. /*
  177692. * jpeg_natural_order[i] is the natural-order position of the i'th element
  177693. * of zigzag order.
  177694. *
  177695. * When reading corrupted data, the Huffman decoders could attempt
  177696. * to reference an entry beyond the end of this array (if the decoded
  177697. * zero run length reaches past the end of the block). To prevent
  177698. * wild stores without adding an inner-loop test, we put some extra
  177699. * "63"s after the real entries. This will cause the extra coefficient
  177700. * to be stored in location 63 of the block, not somewhere random.
  177701. * The worst case would be a run-length of 15, which means we need 16
  177702. * fake entries.
  177703. */
  177704. const int jpeg_natural_order[DCTSIZE2+16] = {
  177705. 0, 1, 8, 16, 9, 2, 3, 10,
  177706. 17, 24, 32, 25, 18, 11, 4, 5,
  177707. 12, 19, 26, 33, 40, 48, 41, 34,
  177708. 27, 20, 13, 6, 7, 14, 21, 28,
  177709. 35, 42, 49, 56, 57, 50, 43, 36,
  177710. 29, 22, 15, 23, 30, 37, 44, 51,
  177711. 58, 59, 52, 45, 38, 31, 39, 46,
  177712. 53, 60, 61, 54, 47, 55, 62, 63,
  177713. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  177714. 63, 63, 63, 63, 63, 63, 63, 63
  177715. };
  177716. /*
  177717. * Arithmetic utilities
  177718. */
  177719. GLOBAL(long)
  177720. jdiv_round_up (long a, long b)
  177721. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  177722. /* Assumes a >= 0, b > 0 */
  177723. {
  177724. return (a + b - 1L) / b;
  177725. }
  177726. GLOBAL(long)
  177727. jround_up (long a, long b)
  177728. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  177729. /* Assumes a >= 0, b > 0 */
  177730. {
  177731. a += b - 1L;
  177732. return a - (a % b);
  177733. }
  177734. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  177735. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  177736. * are FAR and we're assuming a small-pointer memory model. However, some
  177737. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  177738. * in the small-model libraries. These will be used if USE_FMEM is defined.
  177739. * Otherwise, the routines below do it the hard way. (The performance cost
  177740. * is not all that great, because these routines aren't very heavily used.)
  177741. */
  177742. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  177743. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  177744. #define FMEMZERO(target,size) MEMZERO(target,size)
  177745. #else /* 80x86 case, define if we can */
  177746. #ifdef USE_FMEM
  177747. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  177748. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  177749. #endif
  177750. #endif
  177751. GLOBAL(void)
  177752. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  177753. JSAMPARRAY output_array, int dest_row,
  177754. int num_rows, JDIMENSION num_cols)
  177755. /* Copy some rows of samples from one place to another.
  177756. * num_rows rows are copied from input_array[source_row++]
  177757. * to output_array[dest_row++]; these areas may overlap for duplication.
  177758. * The source and destination arrays must be at least as wide as num_cols.
  177759. */
  177760. {
  177761. register JSAMPROW inptr, outptr;
  177762. #ifdef FMEMCOPY
  177763. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  177764. #else
  177765. register JDIMENSION count;
  177766. #endif
  177767. register int row;
  177768. input_array += source_row;
  177769. output_array += dest_row;
  177770. for (row = num_rows; row > 0; row--) {
  177771. inptr = *input_array++;
  177772. outptr = *output_array++;
  177773. #ifdef FMEMCOPY
  177774. FMEMCOPY(outptr, inptr, count);
  177775. #else
  177776. for (count = num_cols; count > 0; count--)
  177777. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  177778. #endif
  177779. }
  177780. }
  177781. GLOBAL(void)
  177782. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  177783. JDIMENSION num_blocks)
  177784. /* Copy a row of coefficient blocks from one place to another. */
  177785. {
  177786. #ifdef FMEMCOPY
  177787. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  177788. #else
  177789. register JCOEFPTR inptr, outptr;
  177790. register long count;
  177791. inptr = (JCOEFPTR) input_row;
  177792. outptr = (JCOEFPTR) output_row;
  177793. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  177794. *outptr++ = *inptr++;
  177795. }
  177796. #endif
  177797. }
  177798. GLOBAL(void)
  177799. jzero_far (void FAR * target, size_t bytestozero)
  177800. /* Zero out a chunk of FAR memory. */
  177801. /* This might be sample-array data, block-array data, or alloc_large data. */
  177802. {
  177803. #ifdef FMEMZERO
  177804. FMEMZERO(target, bytestozero);
  177805. #else
  177806. register char FAR * ptr = (char FAR *) target;
  177807. register size_t count;
  177808. for (count = bytestozero; count > 0; count--) {
  177809. *ptr++ = 0;
  177810. }
  177811. #endif
  177812. }
  177813. /*** End of inlined file: jutils.c ***/
  177814. /*** Start of inlined file: transupp.c ***/
  177815. /* Although this file really shouldn't have access to the library internals,
  177816. * it's helpful to let it call jround_up() and jcopy_block_row().
  177817. */
  177818. #define JPEG_INTERNALS
  177819. /*** Start of inlined file: transupp.h ***/
  177820. /* If you happen not to want the image transform support, disable it here */
  177821. #ifndef TRANSFORMS_SUPPORTED
  177822. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  177823. #endif
  177824. /* Short forms of external names for systems with brain-damaged linkers. */
  177825. #ifdef NEED_SHORT_EXTERNAL_NAMES
  177826. #define jtransform_request_workspace jTrRequest
  177827. #define jtransform_adjust_parameters jTrAdjust
  177828. #define jtransform_execute_transformation jTrExec
  177829. #define jcopy_markers_setup jCMrkSetup
  177830. #define jcopy_markers_execute jCMrkExec
  177831. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  177832. /*
  177833. * Codes for supported types of image transformations.
  177834. */
  177835. typedef enum {
  177836. JXFORM_NONE, /* no transformation */
  177837. JXFORM_FLIP_H, /* horizontal flip */
  177838. JXFORM_FLIP_V, /* vertical flip */
  177839. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  177840. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  177841. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  177842. JXFORM_ROT_180, /* 180-degree rotation */
  177843. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  177844. } JXFORM_CODE;
  177845. /*
  177846. * Although rotating and flipping data expressed as DCT coefficients is not
  177847. * hard, there is an asymmetry in the JPEG format specification for images
  177848. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  177849. * image edges are padded out to the next iMCU boundary with junk data; but
  177850. * no padding is possible at the top and left edges. If we were to flip
  177851. * the whole image including the pad data, then pad garbage would become
  177852. * visible at the top and/or left, and real pixels would disappear into the
  177853. * pad margins --- perhaps permanently, since encoders & decoders may not
  177854. * bother to preserve DCT blocks that appear to be completely outside the
  177855. * nominal image area. So, we have to exclude any partial iMCUs from the
  177856. * basic transformation.
  177857. *
  177858. * Transpose is the only transformation that can handle partial iMCUs at the
  177859. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  177860. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  177861. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  177862. * The other transforms are defined as combinations of these basic transforms
  177863. * and process edge blocks in a way that preserves the equivalence.
  177864. *
  177865. * The "trim" option causes untransformable partial iMCUs to be dropped;
  177866. * this is not strictly lossless, but it usually gives the best-looking
  177867. * result for odd-size images. Note that when this option is active,
  177868. * the expected mathematical equivalences between the transforms may not hold.
  177869. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  177870. * followed by -rot 180 -trim trims both edges.)
  177871. *
  177872. * We also offer a "force to grayscale" option, which simply discards the
  177873. * chrominance channels of a YCbCr image. This is lossless in the sense that
  177874. * the luminance channel is preserved exactly. It's not the same kind of
  177875. * thing as the rotate/flip transformations, but it's convenient to handle it
  177876. * as part of this package, mainly because the transformation routines have to
  177877. * be aware of the option to know how many components to work on.
  177878. */
  177879. typedef struct {
  177880. /* Options: set by caller */
  177881. JXFORM_CODE transform; /* image transform operator */
  177882. boolean trim; /* if TRUE, trim partial MCUs as needed */
  177883. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  177884. /* Internal workspace: caller should not touch these */
  177885. int num_components; /* # of components in workspace */
  177886. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  177887. } jpeg_transform_info;
  177888. #if TRANSFORMS_SUPPORTED
  177889. /* Request any required workspace */
  177890. EXTERN(void) jtransform_request_workspace
  177891. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  177892. /* Adjust output image parameters */
  177893. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  177894. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  177895. jvirt_barray_ptr *src_coef_arrays,
  177896. jpeg_transform_info *info));
  177897. /* Execute the actual transformation, if any */
  177898. EXTERN(void) jtransform_execute_transformation
  177899. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  177900. jvirt_barray_ptr *src_coef_arrays,
  177901. jpeg_transform_info *info));
  177902. #endif /* TRANSFORMS_SUPPORTED */
  177903. /*
  177904. * Support for copying optional markers from source to destination file.
  177905. */
  177906. typedef enum {
  177907. JCOPYOPT_NONE, /* copy no optional markers */
  177908. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  177909. JCOPYOPT_ALL /* copy all optional markers */
  177910. } JCOPY_OPTION;
  177911. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  177912. /* Setup decompression object to save desired markers in memory */
  177913. EXTERN(void) jcopy_markers_setup
  177914. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  177915. /* Copy markers saved in the given source object to the destination object */
  177916. EXTERN(void) jcopy_markers_execute
  177917. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  177918. JCOPY_OPTION option));
  177919. /*** End of inlined file: transupp.h ***/
  177920. /* My own external interface */
  177921. #if TRANSFORMS_SUPPORTED
  177922. /*
  177923. * Lossless image transformation routines. These routines work on DCT
  177924. * coefficient arrays and thus do not require any lossy decompression
  177925. * or recompression of the image.
  177926. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  177927. *
  177928. * Horizontal flipping is done in-place, using a single top-to-bottom
  177929. * pass through the virtual source array. It will thus be much the
  177930. * fastest option for images larger than main memory.
  177931. *
  177932. * The other routines require a set of destination virtual arrays, so they
  177933. * need twice as much memory as jpegtran normally does. The destination
  177934. * arrays are always written in normal scan order (top to bottom) because
  177935. * the virtual array manager expects this. The source arrays will be scanned
  177936. * in the corresponding order, which means multiple passes through the source
  177937. * arrays for most of the transforms. That could result in much thrashing
  177938. * if the image is larger than main memory.
  177939. *
  177940. * Some notes about the operating environment of the individual transform
  177941. * routines:
  177942. * 1. Both the source and destination virtual arrays are allocated from the
  177943. * source JPEG object, and therefore should be manipulated by calling the
  177944. * source's memory manager.
  177945. * 2. The destination's component count should be used. It may be smaller
  177946. * than the source's when forcing to grayscale.
  177947. * 3. Likewise the destination's sampling factors should be used. When
  177948. * forcing to grayscale the destination's sampling factors will be all 1,
  177949. * and we may as well take that as the effective iMCU size.
  177950. * 4. When "trim" is in effect, the destination's dimensions will be the
  177951. * trimmed values but the source's will be untrimmed.
  177952. * 5. All the routines assume that the source and destination buffers are
  177953. * padded out to a full iMCU boundary. This is true, although for the
  177954. * source buffer it is an undocumented property of jdcoefct.c.
  177955. * Notes 2,3,4 boil down to this: generally we should use the destination's
  177956. * dimensions and ignore the source's.
  177957. */
  177958. LOCAL(void)
  177959. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  177960. jvirt_barray_ptr *src_coef_arrays)
  177961. /* Horizontal flip; done in-place, so no separate dest array is required */
  177962. {
  177963. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  177964. int ci, k, offset_y;
  177965. JBLOCKARRAY buffer;
  177966. JCOEFPTR ptr1, ptr2;
  177967. JCOEF temp1, temp2;
  177968. jpeg_component_info *compptr;
  177969. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  177970. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  177971. * mirroring by changing the signs of odd-numbered columns.
  177972. * Partial iMCUs at the right edge are left untouched.
  177973. */
  177974. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  177975. for (ci = 0; ci < dstinfo->num_components; ci++) {
  177976. compptr = dstinfo->comp_info + ci;
  177977. comp_width = MCU_cols * compptr->h_samp_factor;
  177978. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  177979. blk_y += compptr->v_samp_factor) {
  177980. buffer = (*srcinfo->mem->access_virt_barray)
  177981. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  177982. (JDIMENSION) compptr->v_samp_factor, TRUE);
  177983. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  177984. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  177985. ptr1 = buffer[offset_y][blk_x];
  177986. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  177987. /* this unrolled loop doesn't need to know which row it's on... */
  177988. for (k = 0; k < DCTSIZE2; k += 2) {
  177989. temp1 = *ptr1; /* swap even column */
  177990. temp2 = *ptr2;
  177991. *ptr1++ = temp2;
  177992. *ptr2++ = temp1;
  177993. temp1 = *ptr1; /* swap odd column with sign change */
  177994. temp2 = *ptr2;
  177995. *ptr1++ = -temp2;
  177996. *ptr2++ = -temp1;
  177997. }
  177998. }
  177999. }
  178000. }
  178001. }
  178002. }
  178003. LOCAL(void)
  178004. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178005. jvirt_barray_ptr *src_coef_arrays,
  178006. jvirt_barray_ptr *dst_coef_arrays)
  178007. /* Vertical flip */
  178008. {
  178009. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178010. int ci, i, j, offset_y;
  178011. JBLOCKARRAY src_buffer, dst_buffer;
  178012. JBLOCKROW src_row_ptr, dst_row_ptr;
  178013. JCOEFPTR src_ptr, dst_ptr;
  178014. jpeg_component_info *compptr;
  178015. /* We output into a separate array because we can't touch different
  178016. * rows of the source virtual array simultaneously. Otherwise, this
  178017. * is a pretty straightforward analog of horizontal flip.
  178018. * Within a DCT block, vertical mirroring is done by changing the signs
  178019. * of odd-numbered rows.
  178020. * Partial iMCUs at the bottom edge are copied verbatim.
  178021. */
  178022. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178023. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178024. compptr = dstinfo->comp_info + ci;
  178025. comp_height = MCU_rows * compptr->v_samp_factor;
  178026. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178027. dst_blk_y += compptr->v_samp_factor) {
  178028. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178029. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178030. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178031. if (dst_blk_y < comp_height) {
  178032. /* Row is within the mirrorable area. */
  178033. src_buffer = (*srcinfo->mem->access_virt_barray)
  178034. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178035. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178036. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178037. } else {
  178038. /* Bottom-edge blocks will be copied verbatim. */
  178039. src_buffer = (*srcinfo->mem->access_virt_barray)
  178040. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178041. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178042. }
  178043. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178044. if (dst_blk_y < comp_height) {
  178045. /* Row is within the mirrorable area. */
  178046. dst_row_ptr = dst_buffer[offset_y];
  178047. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178048. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178049. dst_blk_x++) {
  178050. dst_ptr = dst_row_ptr[dst_blk_x];
  178051. src_ptr = src_row_ptr[dst_blk_x];
  178052. for (i = 0; i < DCTSIZE; i += 2) {
  178053. /* copy even row */
  178054. for (j = 0; j < DCTSIZE; j++)
  178055. *dst_ptr++ = *src_ptr++;
  178056. /* copy odd row with sign change */
  178057. for (j = 0; j < DCTSIZE; j++)
  178058. *dst_ptr++ = - *src_ptr++;
  178059. }
  178060. }
  178061. } else {
  178062. /* Just copy row verbatim. */
  178063. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178064. compptr->width_in_blocks);
  178065. }
  178066. }
  178067. }
  178068. }
  178069. }
  178070. LOCAL(void)
  178071. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178072. jvirt_barray_ptr *src_coef_arrays,
  178073. jvirt_barray_ptr *dst_coef_arrays)
  178074. /* Transpose source into destination */
  178075. {
  178076. JDIMENSION dst_blk_x, dst_blk_y;
  178077. int ci, i, j, offset_x, offset_y;
  178078. JBLOCKARRAY src_buffer, dst_buffer;
  178079. JCOEFPTR src_ptr, dst_ptr;
  178080. jpeg_component_info *compptr;
  178081. /* Transposing pixels within a block just requires transposing the
  178082. * DCT coefficients.
  178083. * Partial iMCUs at the edges require no special treatment; we simply
  178084. * process all the available DCT blocks for every component.
  178085. */
  178086. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178087. compptr = dstinfo->comp_info + ci;
  178088. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178089. dst_blk_y += compptr->v_samp_factor) {
  178090. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178091. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178092. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178093. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178094. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178095. dst_blk_x += compptr->h_samp_factor) {
  178096. src_buffer = (*srcinfo->mem->access_virt_barray)
  178097. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178098. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178099. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178100. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178101. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178102. for (i = 0; i < DCTSIZE; i++)
  178103. for (j = 0; j < DCTSIZE; j++)
  178104. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178105. }
  178106. }
  178107. }
  178108. }
  178109. }
  178110. }
  178111. LOCAL(void)
  178112. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178113. jvirt_barray_ptr *src_coef_arrays,
  178114. jvirt_barray_ptr *dst_coef_arrays)
  178115. /* 90 degree rotation is equivalent to
  178116. * 1. Transposing the image;
  178117. * 2. Horizontal mirroring.
  178118. * These two steps are merged into a single processing routine.
  178119. */
  178120. {
  178121. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178122. int ci, i, j, offset_x, offset_y;
  178123. JBLOCKARRAY src_buffer, dst_buffer;
  178124. JCOEFPTR src_ptr, dst_ptr;
  178125. jpeg_component_info *compptr;
  178126. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178127. * at the (output) right edge properly. They just get transposed and
  178128. * not mirrored.
  178129. */
  178130. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178131. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178132. compptr = dstinfo->comp_info + ci;
  178133. comp_width = MCU_cols * compptr->h_samp_factor;
  178134. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178135. dst_blk_y += compptr->v_samp_factor) {
  178136. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178137. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178138. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178139. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178140. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178141. dst_blk_x += compptr->h_samp_factor) {
  178142. src_buffer = (*srcinfo->mem->access_virt_barray)
  178143. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178144. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178145. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178146. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178147. if (dst_blk_x < comp_width) {
  178148. /* Block is within the mirrorable area. */
  178149. dst_ptr = dst_buffer[offset_y]
  178150. [comp_width - dst_blk_x - offset_x - 1];
  178151. for (i = 0; i < DCTSIZE; i++) {
  178152. for (j = 0; j < DCTSIZE; j++)
  178153. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178154. i++;
  178155. for (j = 0; j < DCTSIZE; j++)
  178156. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178157. }
  178158. } else {
  178159. /* Edge blocks are transposed but not mirrored. */
  178160. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178161. for (i = 0; i < DCTSIZE; i++)
  178162. for (j = 0; j < DCTSIZE; j++)
  178163. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178164. }
  178165. }
  178166. }
  178167. }
  178168. }
  178169. }
  178170. }
  178171. LOCAL(void)
  178172. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178173. jvirt_barray_ptr *src_coef_arrays,
  178174. jvirt_barray_ptr *dst_coef_arrays)
  178175. /* 270 degree rotation is equivalent to
  178176. * 1. Horizontal mirroring;
  178177. * 2. Transposing the image.
  178178. * These two steps are merged into a single processing routine.
  178179. */
  178180. {
  178181. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178182. int ci, i, j, offset_x, offset_y;
  178183. JBLOCKARRAY src_buffer, dst_buffer;
  178184. JCOEFPTR src_ptr, dst_ptr;
  178185. jpeg_component_info *compptr;
  178186. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178187. * at the (output) bottom edge properly. They just get transposed and
  178188. * not mirrored.
  178189. */
  178190. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178191. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178192. compptr = dstinfo->comp_info + ci;
  178193. comp_height = MCU_rows * compptr->v_samp_factor;
  178194. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178195. dst_blk_y += compptr->v_samp_factor) {
  178196. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178197. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178198. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178199. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178200. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178201. dst_blk_x += compptr->h_samp_factor) {
  178202. src_buffer = (*srcinfo->mem->access_virt_barray)
  178203. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178204. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178205. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178206. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178207. if (dst_blk_y < comp_height) {
  178208. /* Block is within the mirrorable area. */
  178209. src_ptr = src_buffer[offset_x]
  178210. [comp_height - dst_blk_y - offset_y - 1];
  178211. for (i = 0; i < DCTSIZE; i++) {
  178212. for (j = 0; j < DCTSIZE; j++) {
  178213. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178214. j++;
  178215. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178216. }
  178217. }
  178218. } else {
  178219. /* Edge blocks are transposed but not mirrored. */
  178220. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178221. for (i = 0; i < DCTSIZE; i++)
  178222. for (j = 0; j < DCTSIZE; j++)
  178223. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178224. }
  178225. }
  178226. }
  178227. }
  178228. }
  178229. }
  178230. }
  178231. LOCAL(void)
  178232. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178233. jvirt_barray_ptr *src_coef_arrays,
  178234. jvirt_barray_ptr *dst_coef_arrays)
  178235. /* 180 degree rotation is equivalent to
  178236. * 1. Vertical mirroring;
  178237. * 2. Horizontal mirroring.
  178238. * These two steps are merged into a single processing routine.
  178239. */
  178240. {
  178241. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178242. int ci, i, j, offset_y;
  178243. JBLOCKARRAY src_buffer, dst_buffer;
  178244. JBLOCKROW src_row_ptr, dst_row_ptr;
  178245. JCOEFPTR src_ptr, dst_ptr;
  178246. jpeg_component_info *compptr;
  178247. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178248. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178249. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178250. compptr = dstinfo->comp_info + ci;
  178251. comp_width = MCU_cols * compptr->h_samp_factor;
  178252. comp_height = MCU_rows * compptr->v_samp_factor;
  178253. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178254. dst_blk_y += compptr->v_samp_factor) {
  178255. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178256. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178257. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178258. if (dst_blk_y < comp_height) {
  178259. /* Row is within the vertically mirrorable area. */
  178260. src_buffer = (*srcinfo->mem->access_virt_barray)
  178261. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178262. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178263. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178264. } else {
  178265. /* Bottom-edge rows are only mirrored horizontally. */
  178266. src_buffer = (*srcinfo->mem->access_virt_barray)
  178267. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178268. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178269. }
  178270. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178271. if (dst_blk_y < comp_height) {
  178272. /* Row is within the mirrorable area. */
  178273. dst_row_ptr = dst_buffer[offset_y];
  178274. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178275. /* Process the blocks that can be mirrored both ways. */
  178276. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178277. dst_ptr = dst_row_ptr[dst_blk_x];
  178278. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178279. for (i = 0; i < DCTSIZE; i += 2) {
  178280. /* For even row, negate every odd column. */
  178281. for (j = 0; j < DCTSIZE; j += 2) {
  178282. *dst_ptr++ = *src_ptr++;
  178283. *dst_ptr++ = - *src_ptr++;
  178284. }
  178285. /* For odd row, negate every even column. */
  178286. for (j = 0; j < DCTSIZE; j += 2) {
  178287. *dst_ptr++ = - *src_ptr++;
  178288. *dst_ptr++ = *src_ptr++;
  178289. }
  178290. }
  178291. }
  178292. /* Any remaining right-edge blocks are only mirrored vertically. */
  178293. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178294. dst_ptr = dst_row_ptr[dst_blk_x];
  178295. src_ptr = src_row_ptr[dst_blk_x];
  178296. for (i = 0; i < DCTSIZE; i += 2) {
  178297. for (j = 0; j < DCTSIZE; j++)
  178298. *dst_ptr++ = *src_ptr++;
  178299. for (j = 0; j < DCTSIZE; j++)
  178300. *dst_ptr++ = - *src_ptr++;
  178301. }
  178302. }
  178303. } else {
  178304. /* Remaining rows are just mirrored horizontally. */
  178305. dst_row_ptr = dst_buffer[offset_y];
  178306. src_row_ptr = src_buffer[offset_y];
  178307. /* Process the blocks that can be mirrored. */
  178308. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178309. dst_ptr = dst_row_ptr[dst_blk_x];
  178310. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178311. for (i = 0; i < DCTSIZE2; i += 2) {
  178312. *dst_ptr++ = *src_ptr++;
  178313. *dst_ptr++ = - *src_ptr++;
  178314. }
  178315. }
  178316. /* Any remaining right-edge blocks are only copied. */
  178317. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178318. dst_ptr = dst_row_ptr[dst_blk_x];
  178319. src_ptr = src_row_ptr[dst_blk_x];
  178320. for (i = 0; i < DCTSIZE2; i++)
  178321. *dst_ptr++ = *src_ptr++;
  178322. }
  178323. }
  178324. }
  178325. }
  178326. }
  178327. }
  178328. LOCAL(void)
  178329. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178330. jvirt_barray_ptr *src_coef_arrays,
  178331. jvirt_barray_ptr *dst_coef_arrays)
  178332. /* Transverse transpose is equivalent to
  178333. * 1. 180 degree rotation;
  178334. * 2. Transposition;
  178335. * or
  178336. * 1. Horizontal mirroring;
  178337. * 2. Transposition;
  178338. * 3. Horizontal mirroring.
  178339. * These steps are merged into a single processing routine.
  178340. */
  178341. {
  178342. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178343. int ci, i, j, offset_x, offset_y;
  178344. JBLOCKARRAY src_buffer, dst_buffer;
  178345. JCOEFPTR src_ptr, dst_ptr;
  178346. jpeg_component_info *compptr;
  178347. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178348. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178349. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178350. compptr = dstinfo->comp_info + ci;
  178351. comp_width = MCU_cols * compptr->h_samp_factor;
  178352. comp_height = MCU_rows * compptr->v_samp_factor;
  178353. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178354. dst_blk_y += compptr->v_samp_factor) {
  178355. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178356. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178357. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178358. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178359. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178360. dst_blk_x += compptr->h_samp_factor) {
  178361. src_buffer = (*srcinfo->mem->access_virt_barray)
  178362. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178363. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178364. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178365. if (dst_blk_y < comp_height) {
  178366. src_ptr = src_buffer[offset_x]
  178367. [comp_height - dst_blk_y - offset_y - 1];
  178368. if (dst_blk_x < comp_width) {
  178369. /* Block is within the mirrorable area. */
  178370. dst_ptr = dst_buffer[offset_y]
  178371. [comp_width - dst_blk_x - offset_x - 1];
  178372. for (i = 0; i < DCTSIZE; i++) {
  178373. for (j = 0; j < DCTSIZE; j++) {
  178374. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178375. j++;
  178376. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178377. }
  178378. i++;
  178379. for (j = 0; j < DCTSIZE; j++) {
  178380. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178381. j++;
  178382. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178383. }
  178384. }
  178385. } else {
  178386. /* Right-edge blocks are mirrored in y only */
  178387. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178388. for (i = 0; i < DCTSIZE; i++) {
  178389. for (j = 0; j < DCTSIZE; j++) {
  178390. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178391. j++;
  178392. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178393. }
  178394. }
  178395. }
  178396. } else {
  178397. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178398. if (dst_blk_x < comp_width) {
  178399. /* Bottom-edge blocks are mirrored in x only */
  178400. dst_ptr = dst_buffer[offset_y]
  178401. [comp_width - dst_blk_x - offset_x - 1];
  178402. for (i = 0; i < DCTSIZE; i++) {
  178403. for (j = 0; j < DCTSIZE; j++)
  178404. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178405. i++;
  178406. for (j = 0; j < DCTSIZE; j++)
  178407. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178408. }
  178409. } else {
  178410. /* At lower right corner, just transpose, no mirroring */
  178411. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178412. for (i = 0; i < DCTSIZE; i++)
  178413. for (j = 0; j < DCTSIZE; j++)
  178414. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178415. }
  178416. }
  178417. }
  178418. }
  178419. }
  178420. }
  178421. }
  178422. }
  178423. /* Request any required workspace.
  178424. *
  178425. * We allocate the workspace virtual arrays from the source decompression
  178426. * object, so that all the arrays (both the original data and the workspace)
  178427. * will be taken into account while making memory management decisions.
  178428. * Hence, this routine must be called after jpeg_read_header (which reads
  178429. * the image dimensions) and before jpeg_read_coefficients (which realizes
  178430. * the source's virtual arrays).
  178431. */
  178432. GLOBAL(void)
  178433. jtransform_request_workspace (j_decompress_ptr srcinfo,
  178434. jpeg_transform_info *info)
  178435. {
  178436. jvirt_barray_ptr *coef_arrays = NULL;
  178437. jpeg_component_info *compptr;
  178438. int ci;
  178439. if (info->force_grayscale &&
  178440. srcinfo->jpeg_color_space == JCS_YCbCr &&
  178441. srcinfo->num_components == 3) {
  178442. /* We'll only process the first component */
  178443. info->num_components = 1;
  178444. } else {
  178445. /* Process all the components */
  178446. info->num_components = srcinfo->num_components;
  178447. }
  178448. switch (info->transform) {
  178449. case JXFORM_NONE:
  178450. case JXFORM_FLIP_H:
  178451. /* Don't need a workspace array */
  178452. break;
  178453. case JXFORM_FLIP_V:
  178454. case JXFORM_ROT_180:
  178455. /* Need workspace arrays having same dimensions as source image.
  178456. * Note that we allocate arrays padded out to the next iMCU boundary,
  178457. * so that transform routines need not worry about missing edge blocks.
  178458. */
  178459. coef_arrays = (jvirt_barray_ptr *)
  178460. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  178461. SIZEOF(jvirt_barray_ptr) * info->num_components);
  178462. for (ci = 0; ci < info->num_components; ci++) {
  178463. compptr = srcinfo->comp_info + ci;
  178464. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  178465. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  178466. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  178467. (long) compptr->h_samp_factor),
  178468. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  178469. (long) compptr->v_samp_factor),
  178470. (JDIMENSION) compptr->v_samp_factor);
  178471. }
  178472. break;
  178473. case JXFORM_TRANSPOSE:
  178474. case JXFORM_TRANSVERSE:
  178475. case JXFORM_ROT_90:
  178476. case JXFORM_ROT_270:
  178477. /* Need workspace arrays having transposed dimensions.
  178478. * Note that we allocate arrays padded out to the next iMCU boundary,
  178479. * so that transform routines need not worry about missing edge blocks.
  178480. */
  178481. coef_arrays = (jvirt_barray_ptr *)
  178482. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  178483. SIZEOF(jvirt_barray_ptr) * info->num_components);
  178484. for (ci = 0; ci < info->num_components; ci++) {
  178485. compptr = srcinfo->comp_info + ci;
  178486. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  178487. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  178488. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  178489. (long) compptr->v_samp_factor),
  178490. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  178491. (long) compptr->h_samp_factor),
  178492. (JDIMENSION) compptr->h_samp_factor);
  178493. }
  178494. break;
  178495. }
  178496. info->workspace_coef_arrays = coef_arrays;
  178497. }
  178498. /* Transpose destination image parameters */
  178499. LOCAL(void)
  178500. transpose_critical_parameters (j_compress_ptr dstinfo)
  178501. {
  178502. int tblno, i, j, ci, itemp;
  178503. jpeg_component_info *compptr;
  178504. JQUANT_TBL *qtblptr;
  178505. JDIMENSION dtemp;
  178506. UINT16 qtemp;
  178507. /* Transpose basic image dimensions */
  178508. dtemp = dstinfo->image_width;
  178509. dstinfo->image_width = dstinfo->image_height;
  178510. dstinfo->image_height = dtemp;
  178511. /* Transpose sampling factors */
  178512. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178513. compptr = dstinfo->comp_info + ci;
  178514. itemp = compptr->h_samp_factor;
  178515. compptr->h_samp_factor = compptr->v_samp_factor;
  178516. compptr->v_samp_factor = itemp;
  178517. }
  178518. /* Transpose quantization tables */
  178519. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  178520. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  178521. if (qtblptr != NULL) {
  178522. for (i = 0; i < DCTSIZE; i++) {
  178523. for (j = 0; j < i; j++) {
  178524. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  178525. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  178526. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  178527. }
  178528. }
  178529. }
  178530. }
  178531. }
  178532. /* Trim off any partial iMCUs on the indicated destination edge */
  178533. LOCAL(void)
  178534. trim_right_edge (j_compress_ptr dstinfo)
  178535. {
  178536. int ci, max_h_samp_factor;
  178537. JDIMENSION MCU_cols;
  178538. /* We have to compute max_h_samp_factor ourselves,
  178539. * because it hasn't been set yet in the destination
  178540. * (and we don't want to use the source's value).
  178541. */
  178542. max_h_samp_factor = 1;
  178543. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178544. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  178545. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  178546. }
  178547. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  178548. if (MCU_cols > 0) /* can't trim to 0 pixels */
  178549. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  178550. }
  178551. LOCAL(void)
  178552. trim_bottom_edge (j_compress_ptr dstinfo)
  178553. {
  178554. int ci, max_v_samp_factor;
  178555. JDIMENSION MCU_rows;
  178556. /* We have to compute max_v_samp_factor ourselves,
  178557. * because it hasn't been set yet in the destination
  178558. * (and we don't want to use the source's value).
  178559. */
  178560. max_v_samp_factor = 1;
  178561. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178562. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  178563. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  178564. }
  178565. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  178566. if (MCU_rows > 0) /* can't trim to 0 pixels */
  178567. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  178568. }
  178569. /* Adjust output image parameters as needed.
  178570. *
  178571. * This must be called after jpeg_copy_critical_parameters()
  178572. * and before jpeg_write_coefficients().
  178573. *
  178574. * The return value is the set of virtual coefficient arrays to be written
  178575. * (either the ones allocated by jtransform_request_workspace, or the
  178576. * original source data arrays). The caller will need to pass this value
  178577. * to jpeg_write_coefficients().
  178578. */
  178579. GLOBAL(jvirt_barray_ptr *)
  178580. jtransform_adjust_parameters (j_decompress_ptr,
  178581. j_compress_ptr dstinfo,
  178582. jvirt_barray_ptr *src_coef_arrays,
  178583. jpeg_transform_info *info)
  178584. {
  178585. /* If force-to-grayscale is requested, adjust destination parameters */
  178586. if (info->force_grayscale) {
  178587. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  178588. * properly. Among other things, the target h_samp_factor & v_samp_factor
  178589. * will get set to 1, which typically won't match the source.
  178590. * In fact we do this even if the source is already grayscale; that
  178591. * provides an easy way of coercing a grayscale JPEG with funny sampling
  178592. * factors to the customary 1,1. (Some decoders fail on other factors.)
  178593. */
  178594. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  178595. dstinfo->num_components == 3) ||
  178596. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  178597. dstinfo->num_components == 1)) {
  178598. /* We have to preserve the source's quantization table number. */
  178599. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  178600. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  178601. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  178602. } else {
  178603. /* Sorry, can't do it */
  178604. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  178605. }
  178606. }
  178607. /* Correct the destination's image dimensions etc if necessary */
  178608. switch (info->transform) {
  178609. case JXFORM_NONE:
  178610. /* Nothing to do */
  178611. break;
  178612. case JXFORM_FLIP_H:
  178613. if (info->trim)
  178614. trim_right_edge(dstinfo);
  178615. break;
  178616. case JXFORM_FLIP_V:
  178617. if (info->trim)
  178618. trim_bottom_edge(dstinfo);
  178619. break;
  178620. case JXFORM_TRANSPOSE:
  178621. transpose_critical_parameters(dstinfo);
  178622. /* transpose does NOT have to trim anything */
  178623. break;
  178624. case JXFORM_TRANSVERSE:
  178625. transpose_critical_parameters(dstinfo);
  178626. if (info->trim) {
  178627. trim_right_edge(dstinfo);
  178628. trim_bottom_edge(dstinfo);
  178629. }
  178630. break;
  178631. case JXFORM_ROT_90:
  178632. transpose_critical_parameters(dstinfo);
  178633. if (info->trim)
  178634. trim_right_edge(dstinfo);
  178635. break;
  178636. case JXFORM_ROT_180:
  178637. if (info->trim) {
  178638. trim_right_edge(dstinfo);
  178639. trim_bottom_edge(dstinfo);
  178640. }
  178641. break;
  178642. case JXFORM_ROT_270:
  178643. transpose_critical_parameters(dstinfo);
  178644. if (info->trim)
  178645. trim_bottom_edge(dstinfo);
  178646. break;
  178647. }
  178648. /* Return the appropriate output data set */
  178649. if (info->workspace_coef_arrays != NULL)
  178650. return info->workspace_coef_arrays;
  178651. return src_coef_arrays;
  178652. }
  178653. /* Execute the actual transformation, if any.
  178654. *
  178655. * This must be called *after* jpeg_write_coefficients, because it depends
  178656. * on jpeg_write_coefficients to have computed subsidiary values such as
  178657. * the per-component width and height fields in the destination object.
  178658. *
  178659. * Note that some transformations will modify the source data arrays!
  178660. */
  178661. GLOBAL(void)
  178662. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  178663. j_compress_ptr dstinfo,
  178664. jvirt_barray_ptr *src_coef_arrays,
  178665. jpeg_transform_info *info)
  178666. {
  178667. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  178668. switch (info->transform) {
  178669. case JXFORM_NONE:
  178670. break;
  178671. case JXFORM_FLIP_H:
  178672. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  178673. break;
  178674. case JXFORM_FLIP_V:
  178675. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178676. break;
  178677. case JXFORM_TRANSPOSE:
  178678. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178679. break;
  178680. case JXFORM_TRANSVERSE:
  178681. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178682. break;
  178683. case JXFORM_ROT_90:
  178684. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178685. break;
  178686. case JXFORM_ROT_180:
  178687. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178688. break;
  178689. case JXFORM_ROT_270:
  178690. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178691. break;
  178692. }
  178693. }
  178694. #endif /* TRANSFORMS_SUPPORTED */
  178695. /* Setup decompression object to save desired markers in memory.
  178696. * This must be called before jpeg_read_header() to have the desired effect.
  178697. */
  178698. GLOBAL(void)
  178699. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  178700. {
  178701. #ifdef SAVE_MARKERS_SUPPORTED
  178702. int m;
  178703. /* Save comments except under NONE option */
  178704. if (option != JCOPYOPT_NONE) {
  178705. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  178706. }
  178707. /* Save all types of APPn markers iff ALL option */
  178708. if (option == JCOPYOPT_ALL) {
  178709. for (m = 0; m < 16; m++)
  178710. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  178711. }
  178712. #endif /* SAVE_MARKERS_SUPPORTED */
  178713. }
  178714. /* Copy markers saved in the given source object to the destination object.
  178715. * This should be called just after jpeg_start_compress() or
  178716. * jpeg_write_coefficients().
  178717. * Note that those routines will have written the SOI, and also the
  178718. * JFIF APP0 or Adobe APP14 markers if selected.
  178719. */
  178720. GLOBAL(void)
  178721. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178722. JCOPY_OPTION)
  178723. {
  178724. jpeg_saved_marker_ptr marker;
  178725. /* In the current implementation, we don't actually need to examine the
  178726. * option flag here; we just copy everything that got saved.
  178727. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  178728. * if the encoder library already wrote one.
  178729. */
  178730. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  178731. if (dstinfo->write_JFIF_header &&
  178732. marker->marker == JPEG_APP0 &&
  178733. marker->data_length >= 5 &&
  178734. GETJOCTET(marker->data[0]) == 0x4A &&
  178735. GETJOCTET(marker->data[1]) == 0x46 &&
  178736. GETJOCTET(marker->data[2]) == 0x49 &&
  178737. GETJOCTET(marker->data[3]) == 0x46 &&
  178738. GETJOCTET(marker->data[4]) == 0)
  178739. continue; /* reject duplicate JFIF */
  178740. if (dstinfo->write_Adobe_marker &&
  178741. marker->marker == JPEG_APP0+14 &&
  178742. marker->data_length >= 5 &&
  178743. GETJOCTET(marker->data[0]) == 0x41 &&
  178744. GETJOCTET(marker->data[1]) == 0x64 &&
  178745. GETJOCTET(marker->data[2]) == 0x6F &&
  178746. GETJOCTET(marker->data[3]) == 0x62 &&
  178747. GETJOCTET(marker->data[4]) == 0x65)
  178748. continue; /* reject duplicate Adobe */
  178749. #ifdef NEED_FAR_POINTERS
  178750. /* We could use jpeg_write_marker if the data weren't FAR... */
  178751. {
  178752. unsigned int i;
  178753. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  178754. for (i = 0; i < marker->data_length; i++)
  178755. jpeg_write_m_byte(dstinfo, marker->data[i]);
  178756. }
  178757. #else
  178758. jpeg_write_marker(dstinfo, marker->marker,
  178759. marker->data, marker->data_length);
  178760. #endif
  178761. }
  178762. }
  178763. /*** End of inlined file: transupp.c ***/
  178764. }
  178765. #else
  178766. #define JPEG_INTERNALS
  178767. #undef FAR
  178768. #include <jpeglib.h>
  178769. #endif
  178770. }
  178771. #undef max
  178772. #undef min
  178773. #if JUCE_MSVC
  178774. #pragma warning (pop)
  178775. #endif
  178776. BEGIN_JUCE_NAMESPACE
  178777. namespace JPEGHelpers
  178778. {
  178779. using namespace jpeglibNamespace;
  178780. #if ! JUCE_MSVC
  178781. using jpeglibNamespace::boolean;
  178782. #endif
  178783. struct JPEGDecodingFailure {};
  178784. static void fatalErrorHandler (j_common_ptr)
  178785. {
  178786. throw JPEGDecodingFailure();
  178787. }
  178788. static void silentErrorCallback1 (j_common_ptr) {}
  178789. static void silentErrorCallback2 (j_common_ptr, int) {}
  178790. static void silentErrorCallback3 (j_common_ptr, char*) {}
  178791. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  178792. {
  178793. zerostruct (err);
  178794. err.error_exit = fatalErrorHandler;
  178795. err.emit_message = silentErrorCallback2;
  178796. err.output_message = silentErrorCallback1;
  178797. err.format_message = silentErrorCallback3;
  178798. err.reset_error_mgr = silentErrorCallback1;
  178799. }
  178800. static void dummyCallback1 (j_decompress_ptr)
  178801. {
  178802. }
  178803. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  178804. {
  178805. decompStruct->src->next_input_byte += num;
  178806. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  178807. decompStruct->src->bytes_in_buffer -= num;
  178808. }
  178809. static boolean jpegFill (j_decompress_ptr)
  178810. {
  178811. return 0;
  178812. }
  178813. static const int jpegBufferSize = 512;
  178814. struct JuceJpegDest : public jpeg_destination_mgr
  178815. {
  178816. OutputStream* output;
  178817. char* buffer;
  178818. };
  178819. static void jpegWriteInit (j_compress_ptr)
  178820. {
  178821. }
  178822. static void jpegWriteTerminate (j_compress_ptr cinfo)
  178823. {
  178824. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  178825. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  178826. dest->output->write (dest->buffer, (int) numToWrite);
  178827. }
  178828. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  178829. {
  178830. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  178831. const int numToWrite = jpegBufferSize;
  178832. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  178833. dest->free_in_buffer = jpegBufferSize;
  178834. return dest->output->write (dest->buffer, numToWrite);
  178835. }
  178836. }
  178837. JPEGImageFormat::JPEGImageFormat()
  178838. : quality (-1.0f)
  178839. {
  178840. }
  178841. JPEGImageFormat::~JPEGImageFormat() {}
  178842. void JPEGImageFormat::setQuality (const float newQuality)
  178843. {
  178844. quality = newQuality;
  178845. }
  178846. const String JPEGImageFormat::getFormatName()
  178847. {
  178848. return "JPEG";
  178849. }
  178850. bool JPEGImageFormat::canUnderstand (InputStream& in)
  178851. {
  178852. const int bytesNeeded = 10;
  178853. uint8 header [bytesNeeded];
  178854. if (in.read (header, bytesNeeded) == bytesNeeded)
  178855. {
  178856. return header[0] == 0xff
  178857. && header[1] == 0xd8
  178858. && header[2] == 0xff
  178859. && (header[3] == 0xe0 || header[3] == 0xe1);
  178860. }
  178861. return false;
  178862. }
  178863. const Image JPEGImageFormat::decodeImage (InputStream& in)
  178864. {
  178865. using namespace jpeglibNamespace;
  178866. using namespace JPEGHelpers;
  178867. MemoryBlock mb;
  178868. in.readIntoMemoryBlock (mb);
  178869. Image image;
  178870. if (mb.getSize() > 16)
  178871. {
  178872. struct jpeg_decompress_struct jpegDecompStruct;
  178873. struct jpeg_error_mgr jerr;
  178874. setupSilentErrorHandler (jerr);
  178875. jpegDecompStruct.err = &jerr;
  178876. jpeg_create_decompress (&jpegDecompStruct);
  178877. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  178878. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  178879. jpegDecompStruct.src->init_source = dummyCallback1;
  178880. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  178881. jpegDecompStruct.src->skip_input_data = jpegSkip;
  178882. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  178883. jpegDecompStruct.src->term_source = dummyCallback1;
  178884. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  178885. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  178886. try
  178887. {
  178888. jpeg_read_header (&jpegDecompStruct, TRUE);
  178889. jpeg_calc_output_dimensions (&jpegDecompStruct);
  178890. const int width = jpegDecompStruct.output_width;
  178891. const int height = jpegDecompStruct.output_height;
  178892. jpegDecompStruct.out_color_space = JCS_RGB;
  178893. JSAMPARRAY buffer
  178894. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  178895. JPOOL_IMAGE,
  178896. width * 3, 1);
  178897. if (jpeg_start_decompress (&jpegDecompStruct))
  178898. {
  178899. image = Image (Image::RGB, width, height, false);
  178900. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  178901. const Image::BitmapData destData (image, 0, 0, width, height, true);
  178902. for (int y = 0; y < height; ++y)
  178903. {
  178904. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  178905. const uint8* src = *buffer;
  178906. uint8* dest = destData.getLinePointer (y);
  178907. if (hasAlphaChan)
  178908. {
  178909. for (int i = width; --i >= 0;)
  178910. {
  178911. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  178912. ((PixelARGB*) dest)->premultiply();
  178913. dest += destData.pixelStride;
  178914. src += 3;
  178915. }
  178916. }
  178917. else
  178918. {
  178919. for (int i = width; --i >= 0;)
  178920. {
  178921. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  178922. dest += destData.pixelStride;
  178923. src += 3;
  178924. }
  178925. }
  178926. }
  178927. jpeg_finish_decompress (&jpegDecompStruct);
  178928. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  178929. }
  178930. jpeg_destroy_decompress (&jpegDecompStruct);
  178931. }
  178932. catch (...)
  178933. {}
  178934. }
  178935. return image;
  178936. }
  178937. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  178938. {
  178939. using namespace jpeglibNamespace;
  178940. using namespace JPEGHelpers;
  178941. if (image.hasAlphaChannel())
  178942. {
  178943. // this method could fill the background in white and still save the image..
  178944. jassertfalse;
  178945. return true;
  178946. }
  178947. struct jpeg_compress_struct jpegCompStruct;
  178948. struct jpeg_error_mgr jerr;
  178949. setupSilentErrorHandler (jerr);
  178950. jpegCompStruct.err = &jerr;
  178951. jpeg_create_compress (&jpegCompStruct);
  178952. JuceJpegDest dest;
  178953. jpegCompStruct.dest = &dest;
  178954. dest.output = &out;
  178955. HeapBlock <char> tempBuffer (jpegBufferSize);
  178956. dest.buffer = tempBuffer;
  178957. dest.next_output_byte = (JOCTET*) dest.buffer;
  178958. dest.free_in_buffer = jpegBufferSize;
  178959. dest.init_destination = jpegWriteInit;
  178960. dest.empty_output_buffer = jpegWriteFlush;
  178961. dest.term_destination = jpegWriteTerminate;
  178962. jpegCompStruct.image_width = image.getWidth();
  178963. jpegCompStruct.image_height = image.getHeight();
  178964. jpegCompStruct.input_components = 3;
  178965. jpegCompStruct.in_color_space = JCS_RGB;
  178966. jpegCompStruct.write_JFIF_header = 1;
  178967. jpegCompStruct.X_density = 72;
  178968. jpegCompStruct.Y_density = 72;
  178969. jpeg_set_defaults (&jpegCompStruct);
  178970. jpegCompStruct.dct_method = JDCT_FLOAT;
  178971. jpegCompStruct.optimize_coding = 1;
  178972. //jpegCompStruct.smoothing_factor = 10;
  178973. if (quality < 0.0f)
  178974. quality = 0.85f;
  178975. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  178976. jpeg_start_compress (&jpegCompStruct, TRUE);
  178977. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  178978. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  178979. JPOOL_IMAGE, strideBytes, 1);
  178980. const Image::BitmapData srcData (image, 0, 0, jpegCompStruct.image_width, jpegCompStruct.image_height);
  178981. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  178982. {
  178983. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  178984. uint8* dst = *buffer;
  178985. for (int i = jpegCompStruct.image_width; --i >= 0;)
  178986. {
  178987. *dst++ = ((const PixelRGB*) src)->getRed();
  178988. *dst++ = ((const PixelRGB*) src)->getGreen();
  178989. *dst++ = ((const PixelRGB*) src)->getBlue();
  178990. src += srcData.pixelStride;
  178991. }
  178992. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  178993. }
  178994. jpeg_finish_compress (&jpegCompStruct);
  178995. jpeg_destroy_compress (&jpegCompStruct);
  178996. out.flush();
  178997. return true;
  178998. }
  178999. END_JUCE_NAMESPACE
  179000. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179001. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179002. #if JUCE_MSVC
  179003. #pragma warning (push)
  179004. #pragma warning (disable: 4390 4611)
  179005. #endif
  179006. namespace zlibNamespace
  179007. {
  179008. #if JUCE_INCLUDE_ZLIB_CODE
  179009. #undef OS_CODE
  179010. #undef fdopen
  179011. #undef OS_CODE
  179012. #else
  179013. #include <zlib.h>
  179014. #endif
  179015. }
  179016. namespace pnglibNamespace
  179017. {
  179018. using namespace zlibNamespace;
  179019. #if JUCE_INCLUDE_PNGLIB_CODE
  179020. #if _MSC_VER != 1310
  179021. using ::calloc; // (causes conflict in VS.NET 2003)
  179022. using ::malloc;
  179023. using ::free;
  179024. #endif
  179025. extern "C"
  179026. {
  179027. using ::abs;
  179028. #define PNG_INTERNAL
  179029. #define NO_DUMMY_DECL
  179030. #define PNG_SETJMP_NOT_SUPPORTED
  179031. /*** Start of inlined file: png.h ***/
  179032. /* png.h - header file for PNG reference library
  179033. *
  179034. * libpng version 1.2.21 - October 4, 2007
  179035. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179036. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179037. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179038. *
  179039. * Authors and maintainers:
  179040. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179041. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179042. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179043. * See also "Contributing Authors", below.
  179044. *
  179045. * Note about libpng version numbers:
  179046. *
  179047. * Due to various miscommunications, unforeseen code incompatibilities
  179048. * and occasional factors outside the authors' control, version numbering
  179049. * on the library has not always been consistent and straightforward.
  179050. * The following table summarizes matters since version 0.89c, which was
  179051. * the first widely used release:
  179052. *
  179053. * source png.h png.h shared-lib
  179054. * version string int version
  179055. * ------- ------ ----- ----------
  179056. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179057. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179058. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179059. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179060. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179061. * 0.97c 0.97 97 2.0.97
  179062. * 0.98 0.98 98 2.0.98
  179063. * 0.99 0.99 98 2.0.99
  179064. * 0.99a-m 0.99 99 2.0.99
  179065. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179066. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179067. * 1.0.1 png.h string is 10001 2.1.0
  179068. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179069. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179070. * 1.0.2a-b 10003 version, except as noted.
  179071. * 1.0.3 10003
  179072. * 1.0.3a-d 10004
  179073. * 1.0.4 10004
  179074. * 1.0.4a-f 10005
  179075. * 1.0.5 (+ 2 patches) 10005
  179076. * 1.0.5a-d 10006
  179077. * 1.0.5e-r 10100 (not source compatible)
  179078. * 1.0.5s-v 10006 (not binary compatible)
  179079. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179080. * 1.0.6d-f 10007 (still binary incompatible)
  179081. * 1.0.6g 10007
  179082. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179083. * 1.0.6i 10007 10.6i
  179084. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179085. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179086. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179087. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179088. * 1.0.7 1 10007 (still compatible)
  179089. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179090. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179091. * 1.0.8 1 10008 2.1.0.8
  179092. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179093. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179094. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179095. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179096. * 1.0.9 1 10009 2.1.0.9
  179097. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179098. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179099. * 1.0.10 1 10010 2.1.0.10
  179100. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179101. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179102. * 1.0.11 1 10011 2.1.0.11
  179103. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179104. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179105. * 1.0.12 2 10012 2.1.0.12
  179106. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179107. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179108. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179109. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179110. * 1.2.0 3 10200 3.1.2.0
  179111. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179112. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179113. * 1.2.1 3 10201 3.1.2.1
  179114. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179115. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179116. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179117. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179118. * 1.0.13 10 10013 10.so.0.1.0.13
  179119. * 1.2.2 12 10202 12.so.0.1.2.2
  179120. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179121. * 1.2.3 12 10203 12.so.0.1.2.3
  179122. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179123. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179124. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179125. * 1.0.14 10 10014 10.so.0.1.0.14
  179126. * 1.2.4 13 10204 12.so.0.1.2.4
  179127. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  179128. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  179129. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  179130. * 1.0.15 10 10015 10.so.0.1.0.15
  179131. * 1.2.5 13 10205 12.so.0.1.2.5
  179132. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  179133. * 1.0.16 10 10016 10.so.0.1.0.16
  179134. * 1.2.6 13 10206 12.so.0.1.2.6
  179135. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  179136. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  179137. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  179138. * 1.0.17 10 10017 10.so.0.1.0.17
  179139. * 1.2.7 13 10207 12.so.0.1.2.7
  179140. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  179141. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  179142. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  179143. * 1.0.18 10 10018 10.so.0.1.0.18
  179144. * 1.2.8 13 10208 12.so.0.1.2.8
  179145. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  179146. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  179147. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  179148. * 1.2.9 13 10209 12.so.0.9[.0]
  179149. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  179150. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  179151. * 1.2.10 13 10210 12.so.0.10[.0]
  179152. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  179153. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  179154. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  179155. * 1.0.19 10 10019 10.so.0.19[.0]
  179156. * 1.2.11 13 10211 12.so.0.11[.0]
  179157. * 1.0.20 10 10020 10.so.0.20[.0]
  179158. * 1.2.12 13 10212 12.so.0.12[.0]
  179159. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  179160. * 1.0.21 10 10021 10.so.0.21[.0]
  179161. * 1.2.13 13 10213 12.so.0.13[.0]
  179162. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  179163. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  179164. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  179165. * 1.0.22 10 10022 10.so.0.22[.0]
  179166. * 1.2.14 13 10214 12.so.0.14[.0]
  179167. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  179168. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  179169. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  179170. * 1.0.23 10 10023 10.so.0.23[.0]
  179171. * 1.2.15 13 10215 12.so.0.15[.0]
  179172. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  179173. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  179174. * 1.0.24 10 10024 10.so.0.24[.0]
  179175. * 1.2.16 13 10216 12.so.0.16[.0]
  179176. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  179177. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  179178. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  179179. * 1.0.25 10 10025 10.so.0.25[.0]
  179180. * 1.2.17 13 10217 12.so.0.17[.0]
  179181. * 1.0.26 10 10026 10.so.0.26[.0]
  179182. * 1.2.18 13 10218 12.so.0.18[.0]
  179183. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  179184. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  179185. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  179186. * 1.0.27 10 10027 10.so.0.27[.0]
  179187. * 1.2.19 13 10219 12.so.0.19[.0]
  179188. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  179189. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  179190. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  179191. * 1.0.28 10 10028 10.so.0.28[.0]
  179192. * 1.2.20 13 10220 12.so.0.20[.0]
  179193. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  179194. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  179195. * 1.0.29 10 10029 10.so.0.29[.0]
  179196. * 1.2.21 13 10221 12.so.0.21[.0]
  179197. *
  179198. * Henceforth the source version will match the shared-library major
  179199. * and minor numbers; the shared-library major version number will be
  179200. * used for changes in backward compatibility, as it is intended. The
  179201. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  179202. * for applications, is an unsigned integer of the form xyyzz corresponding
  179203. * to the source version x.y.z (leading zeros in y and z). Beta versions
  179204. * were given the previous public release number plus a letter, until
  179205. * version 1.0.6j; from then on they were given the upcoming public
  179206. * release number plus "betaNN" or "rcN".
  179207. *
  179208. * Binary incompatibility exists only when applications make direct access
  179209. * to the info_ptr or png_ptr members through png.h, and the compiled
  179210. * application is loaded with a different version of the library.
  179211. *
  179212. * DLLNUM will change each time there are forward or backward changes
  179213. * in binary compatibility (e.g., when a new feature is added).
  179214. *
  179215. * See libpng.txt or libpng.3 for more information. The PNG specification
  179216. * is available as a W3C Recommendation and as an ISO Specification,
  179217. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  179218. */
  179219. /*
  179220. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  179221. *
  179222. * If you modify libpng you may insert additional notices immediately following
  179223. * this sentence.
  179224. *
  179225. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  179226. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  179227. * distributed according to the same disclaimer and license as libpng-1.2.5
  179228. * with the following individual added to the list of Contributing Authors:
  179229. *
  179230. * Cosmin Truta
  179231. *
  179232. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  179233. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  179234. * distributed according to the same disclaimer and license as libpng-1.0.6
  179235. * with the following individuals added to the list of Contributing Authors:
  179236. *
  179237. * Simon-Pierre Cadieux
  179238. * Eric S. Raymond
  179239. * Gilles Vollant
  179240. *
  179241. * and with the following additions to the disclaimer:
  179242. *
  179243. * There is no warranty against interference with your enjoyment of the
  179244. * library or against infringement. There is no warranty that our
  179245. * efforts or the library will fulfill any of your particular purposes
  179246. * or needs. This library is provided with all faults, and the entire
  179247. * risk of satisfactory quality, performance, accuracy, and effort is with
  179248. * the user.
  179249. *
  179250. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  179251. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  179252. * distributed according to the same disclaimer and license as libpng-0.96,
  179253. * with the following individuals added to the list of Contributing Authors:
  179254. *
  179255. * Tom Lane
  179256. * Glenn Randers-Pehrson
  179257. * Willem van Schaik
  179258. *
  179259. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  179260. * Copyright (c) 1996, 1997 Andreas Dilger
  179261. * Distributed according to the same disclaimer and license as libpng-0.88,
  179262. * with the following individuals added to the list of Contributing Authors:
  179263. *
  179264. * John Bowler
  179265. * Kevin Bracey
  179266. * Sam Bushell
  179267. * Magnus Holmgren
  179268. * Greg Roelofs
  179269. * Tom Tanner
  179270. *
  179271. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  179272. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  179273. *
  179274. * For the purposes of this copyright and license, "Contributing Authors"
  179275. * is defined as the following set of individuals:
  179276. *
  179277. * Andreas Dilger
  179278. * Dave Martindale
  179279. * Guy Eric Schalnat
  179280. * Paul Schmidt
  179281. * Tim Wegner
  179282. *
  179283. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  179284. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  179285. * including, without limitation, the warranties of merchantability and of
  179286. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  179287. * assume no liability for direct, indirect, incidental, special, exemplary,
  179288. * or consequential damages, which may result from the use of the PNG
  179289. * Reference Library, even if advised of the possibility of such damage.
  179290. *
  179291. * Permission is hereby granted to use, copy, modify, and distribute this
  179292. * source code, or portions hereof, for any purpose, without fee, subject
  179293. * to the following restrictions:
  179294. *
  179295. * 1. The origin of this source code must not be misrepresented.
  179296. *
  179297. * 2. Altered versions must be plainly marked as such and
  179298. * must not be misrepresented as being the original source.
  179299. *
  179300. * 3. This Copyright notice may not be removed or altered from
  179301. * any source or altered source distribution.
  179302. *
  179303. * The Contributing Authors and Group 42, Inc. specifically permit, without
  179304. * fee, and encourage the use of this source code as a component to
  179305. * supporting the PNG file format in commercial products. If you use this
  179306. * source code in a product, acknowledgment is not required but would be
  179307. * appreciated.
  179308. */
  179309. /*
  179310. * A "png_get_copyright" function is available, for convenient use in "about"
  179311. * boxes and the like:
  179312. *
  179313. * printf("%s",png_get_copyright(NULL));
  179314. *
  179315. * Also, the PNG logo (in PNG format, of course) is supplied in the
  179316. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  179317. */
  179318. /*
  179319. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  179320. * certification mark of the Open Source Initiative.
  179321. */
  179322. /*
  179323. * The contributing authors would like to thank all those who helped
  179324. * with testing, bug fixes, and patience. This wouldn't have been
  179325. * possible without all of you.
  179326. *
  179327. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  179328. */
  179329. /*
  179330. * Y2K compliance in libpng:
  179331. * =========================
  179332. *
  179333. * October 4, 2007
  179334. *
  179335. * Since the PNG Development group is an ad-hoc body, we can't make
  179336. * an official declaration.
  179337. *
  179338. * This is your unofficial assurance that libpng from version 0.71 and
  179339. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  179340. * versions were also Y2K compliant.
  179341. *
  179342. * Libpng only has three year fields. One is a 2-byte unsigned integer
  179343. * that will hold years up to 65535. The other two hold the date in text
  179344. * format, and will hold years up to 9999.
  179345. *
  179346. * The integer is
  179347. * "png_uint_16 year" in png_time_struct.
  179348. *
  179349. * The strings are
  179350. * "png_charp time_buffer" in png_struct and
  179351. * "near_time_buffer", which is a local character string in png.c.
  179352. *
  179353. * There are seven time-related functions:
  179354. * png.c: png_convert_to_rfc_1123() in png.c
  179355. * (formerly png_convert_to_rfc_1152() in error)
  179356. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  179357. * png_convert_from_time_t() in pngwrite.c
  179358. * png_get_tIME() in pngget.c
  179359. * png_handle_tIME() in pngrutil.c, called in pngread.c
  179360. * png_set_tIME() in pngset.c
  179361. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  179362. *
  179363. * All handle dates properly in a Y2K environment. The
  179364. * png_convert_from_time_t() function calls gmtime() to convert from system
  179365. * clock time, which returns (year - 1900), which we properly convert to
  179366. * the full 4-digit year. There is a possibility that applications using
  179367. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  179368. * function, or that they are incorrectly passing only a 2-digit year
  179369. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  179370. * but this is not under our control. The libpng documentation has always
  179371. * stated that it works with 4-digit years, and the APIs have been
  179372. * documented as such.
  179373. *
  179374. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  179375. * integer to hold the year, and can hold years as large as 65535.
  179376. *
  179377. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  179378. * no date-related code.
  179379. *
  179380. * Glenn Randers-Pehrson
  179381. * libpng maintainer
  179382. * PNG Development Group
  179383. */
  179384. #ifndef PNG_H
  179385. #define PNG_H
  179386. /* This is not the place to learn how to use libpng. The file libpng.txt
  179387. * describes how to use libpng, and the file example.c summarizes it
  179388. * with some code on which to build. This file is useful for looking
  179389. * at the actual function definitions and structure components.
  179390. */
  179391. /* Version information for png.h - this should match the version in png.c */
  179392. #define PNG_LIBPNG_VER_STRING "1.2.21"
  179393. #define PNG_HEADER_VERSION_STRING \
  179394. " libpng version 1.2.21 - October 4, 2007\n"
  179395. #define PNG_LIBPNG_VER_SONUM 0
  179396. #define PNG_LIBPNG_VER_DLLNUM 13
  179397. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  179398. #define PNG_LIBPNG_VER_MAJOR 1
  179399. #define PNG_LIBPNG_VER_MINOR 2
  179400. #define PNG_LIBPNG_VER_RELEASE 21
  179401. /* This should match the numeric part of the final component of
  179402. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  179403. #define PNG_LIBPNG_VER_BUILD 0
  179404. /* Release Status */
  179405. #define PNG_LIBPNG_BUILD_ALPHA 1
  179406. #define PNG_LIBPNG_BUILD_BETA 2
  179407. #define PNG_LIBPNG_BUILD_RC 3
  179408. #define PNG_LIBPNG_BUILD_STABLE 4
  179409. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  179410. /* Release-Specific Flags */
  179411. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  179412. PNG_LIBPNG_BUILD_STABLE only */
  179413. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  179414. PNG_LIBPNG_BUILD_SPECIAL */
  179415. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  179416. PNG_LIBPNG_BUILD_PRIVATE */
  179417. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  179418. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  179419. * We must not include leading zeros.
  179420. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  179421. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  179422. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  179423. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  179424. #ifndef PNG_VERSION_INFO_ONLY
  179425. /* include the compression library's header */
  179426. #endif
  179427. /* include all user configurable info, including optional assembler routines */
  179428. /*** Start of inlined file: pngconf.h ***/
  179429. /* pngconf.h - machine configurable file for libpng
  179430. *
  179431. * libpng version 1.2.21 - October 4, 2007
  179432. * For conditions of distribution and use, see copyright notice in png.h
  179433. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179434. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179435. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179436. */
  179437. /* Any machine specific code is near the front of this file, so if you
  179438. * are configuring libpng for a machine, you may want to read the section
  179439. * starting here down to where it starts to typedef png_color, png_text,
  179440. * and png_info.
  179441. */
  179442. #ifndef PNGCONF_H
  179443. #define PNGCONF_H
  179444. #define PNG_1_2_X
  179445. // These are some Juce config settings that should remove any unnecessary code bloat..
  179446. #define PNG_NO_STDIO 1
  179447. #define PNG_DEBUG 0
  179448. #define PNG_NO_WARNINGS 1
  179449. #define PNG_NO_ERROR_TEXT 1
  179450. #define PNG_NO_ERROR_NUMBERS 1
  179451. #define PNG_NO_USER_MEM 1
  179452. #define PNG_NO_READ_iCCP 1
  179453. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  179454. #define PNG_NO_READ_USER_CHUNKS 1
  179455. #define PNG_NO_READ_iTXt 1
  179456. #define PNG_NO_READ_sCAL 1
  179457. #define PNG_NO_READ_sPLT 1
  179458. #define png_error(a, b) png_err(a)
  179459. #define png_warning(a, b)
  179460. #define png_chunk_error(a, b) png_err(a)
  179461. #define png_chunk_warning(a, b)
  179462. /*
  179463. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  179464. * includes the resource compiler for Windows DLL configurations.
  179465. */
  179466. #ifdef PNG_USER_CONFIG
  179467. # ifndef PNG_USER_PRIVATEBUILD
  179468. # define PNG_USER_PRIVATEBUILD
  179469. # endif
  179470. #include "pngusr.h"
  179471. #endif
  179472. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  179473. #ifdef PNG_CONFIGURE_LIBPNG
  179474. #ifdef HAVE_CONFIG_H
  179475. #include "config.h"
  179476. #endif
  179477. #endif
  179478. /*
  179479. * Added at libpng-1.2.8
  179480. *
  179481. * If you create a private DLL you need to define in "pngusr.h" the followings:
  179482. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  179483. * the DLL was built>
  179484. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  179485. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  179486. * distinguish your DLL from those of the official release. These
  179487. * correspond to the trailing letters that come after the version
  179488. * number and must match your private DLL name>
  179489. * e.g. // private DLL "libpng13gx.dll"
  179490. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  179491. *
  179492. * The following macros are also at your disposal if you want to complete the
  179493. * DLL VERSIONINFO structure.
  179494. * - PNG_USER_VERSIONINFO_COMMENTS
  179495. * - PNG_USER_VERSIONINFO_COMPANYNAME
  179496. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  179497. */
  179498. #ifdef __STDC__
  179499. #ifdef SPECIALBUILD
  179500. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  179501. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  179502. #endif
  179503. #ifdef PRIVATEBUILD
  179504. # pragma message("PRIVATEBUILD is deprecated.\
  179505. Use PNG_USER_PRIVATEBUILD instead.")
  179506. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  179507. #endif
  179508. #endif /* __STDC__ */
  179509. #ifndef PNG_VERSION_INFO_ONLY
  179510. /* End of material added to libpng-1.2.8 */
  179511. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  179512. Restored at libpng-1.2.21 */
  179513. # define PNG_WARN_UNINITIALIZED_ROW 1
  179514. /* End of material added at libpng-1.2.19/1.2.21 */
  179515. /* This is the size of the compression buffer, and thus the size of
  179516. * an IDAT chunk. Make this whatever size you feel is best for your
  179517. * machine. One of these will be allocated per png_struct. When this
  179518. * is full, it writes the data to the disk, and does some other
  179519. * calculations. Making this an extremely small size will slow
  179520. * the library down, but you may want to experiment to determine
  179521. * where it becomes significant, if you are concerned with memory
  179522. * usage. Note that zlib allocates at least 32Kb also. For readers,
  179523. * this describes the size of the buffer available to read the data in.
  179524. * Unless this gets smaller than the size of a row (compressed),
  179525. * it should not make much difference how big this is.
  179526. */
  179527. #ifndef PNG_ZBUF_SIZE
  179528. # define PNG_ZBUF_SIZE 8192
  179529. #endif
  179530. /* Enable if you want a write-only libpng */
  179531. #ifndef PNG_NO_READ_SUPPORTED
  179532. # define PNG_READ_SUPPORTED
  179533. #endif
  179534. /* Enable if you want a read-only libpng */
  179535. #ifndef PNG_NO_WRITE_SUPPORTED
  179536. # define PNG_WRITE_SUPPORTED
  179537. #endif
  179538. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  179539. support PNGs that are embedded in MNG datastreams */
  179540. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  179541. # ifndef PNG_MNG_FEATURES_SUPPORTED
  179542. # define PNG_MNG_FEATURES_SUPPORTED
  179543. # endif
  179544. #endif
  179545. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  179546. # ifndef PNG_FLOATING_POINT_SUPPORTED
  179547. # define PNG_FLOATING_POINT_SUPPORTED
  179548. # endif
  179549. #endif
  179550. /* If you are running on a machine where you cannot allocate more
  179551. * than 64K of memory at once, uncomment this. While libpng will not
  179552. * normally need that much memory in a chunk (unless you load up a very
  179553. * large file), zlib needs to know how big of a chunk it can use, and
  179554. * libpng thus makes sure to check any memory allocation to verify it
  179555. * will fit into memory.
  179556. #define PNG_MAX_MALLOC_64K
  179557. */
  179558. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  179559. # define PNG_MAX_MALLOC_64K
  179560. #endif
  179561. /* Special munging to support doing things the 'cygwin' way:
  179562. * 'Normal' png-on-win32 defines/defaults:
  179563. * PNG_BUILD_DLL -- building dll
  179564. * PNG_USE_DLL -- building an application, linking to dll
  179565. * (no define) -- building static library, or building an
  179566. * application and linking to the static lib
  179567. * 'Cygwin' defines/defaults:
  179568. * PNG_BUILD_DLL -- (ignored) building the dll
  179569. * (no define) -- (ignored) building an application, linking to the dll
  179570. * PNG_STATIC -- (ignored) building the static lib, or building an
  179571. * application that links to the static lib.
  179572. * ALL_STATIC -- (ignored) building various static libs, or building an
  179573. * application that links to the static libs.
  179574. * Thus,
  179575. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  179576. * this bit of #ifdefs will define the 'correct' config variables based on
  179577. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  179578. * unnecessary.
  179579. *
  179580. * Also, the precedence order is:
  179581. * ALL_STATIC (since we can't #undef something outside our namespace)
  179582. * PNG_BUILD_DLL
  179583. * PNG_STATIC
  179584. * (nothing) == PNG_USE_DLL
  179585. *
  179586. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  179587. * of auto-import in binutils, we no longer need to worry about
  179588. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  179589. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  179590. * to __declspec() stuff. However, we DO need to worry about
  179591. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  179592. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  179593. */
  179594. #if defined(__CYGWIN__)
  179595. # if defined(ALL_STATIC)
  179596. # if defined(PNG_BUILD_DLL)
  179597. # undef PNG_BUILD_DLL
  179598. # endif
  179599. # if defined(PNG_USE_DLL)
  179600. # undef PNG_USE_DLL
  179601. # endif
  179602. # if defined(PNG_DLL)
  179603. # undef PNG_DLL
  179604. # endif
  179605. # if !defined(PNG_STATIC)
  179606. # define PNG_STATIC
  179607. # endif
  179608. # else
  179609. # if defined (PNG_BUILD_DLL)
  179610. # if defined(PNG_STATIC)
  179611. # undef PNG_STATIC
  179612. # endif
  179613. # if defined(PNG_USE_DLL)
  179614. # undef PNG_USE_DLL
  179615. # endif
  179616. # if !defined(PNG_DLL)
  179617. # define PNG_DLL
  179618. # endif
  179619. # else
  179620. # if defined(PNG_STATIC)
  179621. # if defined(PNG_USE_DLL)
  179622. # undef PNG_USE_DLL
  179623. # endif
  179624. # if defined(PNG_DLL)
  179625. # undef PNG_DLL
  179626. # endif
  179627. # else
  179628. # if !defined(PNG_USE_DLL)
  179629. # define PNG_USE_DLL
  179630. # endif
  179631. # if !defined(PNG_DLL)
  179632. # define PNG_DLL
  179633. # endif
  179634. # endif
  179635. # endif
  179636. # endif
  179637. #endif
  179638. /* This protects us against compilers that run on a windowing system
  179639. * and thus don't have or would rather us not use the stdio types:
  179640. * stdin, stdout, and stderr. The only one currently used is stderr
  179641. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  179642. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  179643. * will also prevent these, plus will prevent the entire set of stdio
  179644. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  179645. * unless (PNG_DEBUG > 0) has been #defined.
  179646. *
  179647. * #define PNG_NO_CONSOLE_IO
  179648. * #define PNG_NO_STDIO
  179649. */
  179650. #if defined(_WIN32_WCE)
  179651. # include <windows.h>
  179652. /* Console I/O functions are not supported on WindowsCE */
  179653. # define PNG_NO_CONSOLE_IO
  179654. # ifdef PNG_DEBUG
  179655. # undef PNG_DEBUG
  179656. # endif
  179657. #endif
  179658. #ifdef PNG_BUILD_DLL
  179659. # ifndef PNG_CONSOLE_IO_SUPPORTED
  179660. # ifndef PNG_NO_CONSOLE_IO
  179661. # define PNG_NO_CONSOLE_IO
  179662. # endif
  179663. # endif
  179664. #endif
  179665. # ifdef PNG_NO_STDIO
  179666. # ifndef PNG_NO_CONSOLE_IO
  179667. # define PNG_NO_CONSOLE_IO
  179668. # endif
  179669. # ifdef PNG_DEBUG
  179670. # if (PNG_DEBUG > 0)
  179671. # include <stdio.h>
  179672. # endif
  179673. # endif
  179674. # else
  179675. # if !defined(_WIN32_WCE)
  179676. /* "stdio.h" functions are not supported on WindowsCE */
  179677. # include <stdio.h>
  179678. # endif
  179679. # endif
  179680. /* This macro protects us against machines that don't have function
  179681. * prototypes (ie K&R style headers). If your compiler does not handle
  179682. * function prototypes, define this macro and use the included ansi2knr.
  179683. * I've always been able to use _NO_PROTO as the indicator, but you may
  179684. * need to drag the empty declaration out in front of here, or change the
  179685. * ifdef to suit your own needs.
  179686. */
  179687. #ifndef PNGARG
  179688. #ifdef OF /* zlib prototype munger */
  179689. # define PNGARG(arglist) OF(arglist)
  179690. #else
  179691. #ifdef _NO_PROTO
  179692. # define PNGARG(arglist) ()
  179693. # ifndef PNG_TYPECAST_NULL
  179694. # define PNG_TYPECAST_NULL
  179695. # endif
  179696. #else
  179697. # define PNGARG(arglist) arglist
  179698. #endif /* _NO_PROTO */
  179699. #endif /* OF */
  179700. #endif /* PNGARG */
  179701. /* Try to determine if we are compiling on a Mac. Note that testing for
  179702. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  179703. * on non-Mac platforms.
  179704. */
  179705. #ifndef MACOS
  179706. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  179707. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  179708. # define MACOS
  179709. # endif
  179710. #endif
  179711. /* enough people need this for various reasons to include it here */
  179712. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  179713. # include <sys/types.h>
  179714. #endif
  179715. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  179716. # define PNG_SETJMP_SUPPORTED
  179717. #endif
  179718. #ifdef PNG_SETJMP_SUPPORTED
  179719. /* This is an attempt to force a single setjmp behaviour on Linux. If
  179720. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  179721. */
  179722. # ifdef __linux__
  179723. # ifdef _BSD_SOURCE
  179724. # define PNG_SAVE_BSD_SOURCE
  179725. # undef _BSD_SOURCE
  179726. # endif
  179727. # ifdef _SETJMP_H
  179728. /* If you encounter a compiler error here, see the explanation
  179729. * near the end of INSTALL.
  179730. */
  179731. __png.h__ already includes setjmp.h;
  179732. __dont__ include it again.;
  179733. # endif
  179734. # endif /* __linux__ */
  179735. /* include setjmp.h for error handling */
  179736. # include <setjmp.h>
  179737. # ifdef __linux__
  179738. # ifdef PNG_SAVE_BSD_SOURCE
  179739. # define _BSD_SOURCE
  179740. # undef PNG_SAVE_BSD_SOURCE
  179741. # endif
  179742. # endif /* __linux__ */
  179743. #endif /* PNG_SETJMP_SUPPORTED */
  179744. #ifdef BSD
  179745. #if ! JUCE_MAC
  179746. # include <strings.h>
  179747. #endif
  179748. #else
  179749. # include <string.h>
  179750. #endif
  179751. /* Other defines for things like memory and the like can go here. */
  179752. #ifdef PNG_INTERNAL
  179753. #include <stdlib.h>
  179754. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  179755. * aren't usually used outside the library (as far as I know), so it is
  179756. * debatable if they should be exported at all. In the future, when it is
  179757. * possible to have run-time registry of chunk-handling functions, some of
  179758. * these will be made available again.
  179759. #define PNG_EXTERN extern
  179760. */
  179761. #define PNG_EXTERN
  179762. /* Other defines specific to compilers can go here. Try to keep
  179763. * them inside an appropriate ifdef/endif pair for portability.
  179764. */
  179765. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  179766. # if defined(MACOS)
  179767. /* We need to check that <math.h> hasn't already been included earlier
  179768. * as it seems it doesn't agree with <fp.h>, yet we should really use
  179769. * <fp.h> if possible.
  179770. */
  179771. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  179772. # include <fp.h>
  179773. # endif
  179774. # else
  179775. # include <math.h>
  179776. # endif
  179777. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  179778. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  179779. * MATH=68881
  179780. */
  179781. # include <m68881.h>
  179782. # endif
  179783. #endif
  179784. /* Codewarrior on NT has linking problems without this. */
  179785. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  179786. # define PNG_ALWAYS_EXTERN
  179787. #endif
  179788. /* This provides the non-ANSI (far) memory allocation routines. */
  179789. #if defined(__TURBOC__) && defined(__MSDOS__)
  179790. # include <mem.h>
  179791. # include <alloc.h>
  179792. #endif
  179793. /* I have no idea why is this necessary... */
  179794. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  179795. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  179796. # include <malloc.h>
  179797. #endif
  179798. /* This controls how fine the dithering gets. As this allocates
  179799. * a largish chunk of memory (32K), those who are not as concerned
  179800. * with dithering quality can decrease some or all of these.
  179801. */
  179802. #ifndef PNG_DITHER_RED_BITS
  179803. # define PNG_DITHER_RED_BITS 5
  179804. #endif
  179805. #ifndef PNG_DITHER_GREEN_BITS
  179806. # define PNG_DITHER_GREEN_BITS 5
  179807. #endif
  179808. #ifndef PNG_DITHER_BLUE_BITS
  179809. # define PNG_DITHER_BLUE_BITS 5
  179810. #endif
  179811. /* This controls how fine the gamma correction becomes when you
  179812. * are only interested in 8 bits anyway. Increasing this value
  179813. * results in more memory being used, and more pow() functions
  179814. * being called to fill in the gamma tables. Don't set this value
  179815. * less then 8, and even that may not work (I haven't tested it).
  179816. */
  179817. #ifndef PNG_MAX_GAMMA_8
  179818. # define PNG_MAX_GAMMA_8 11
  179819. #endif
  179820. /* This controls how much a difference in gamma we can tolerate before
  179821. * we actually start doing gamma conversion.
  179822. */
  179823. #ifndef PNG_GAMMA_THRESHOLD
  179824. # define PNG_GAMMA_THRESHOLD 0.05
  179825. #endif
  179826. #endif /* PNG_INTERNAL */
  179827. /* The following uses const char * instead of char * for error
  179828. * and warning message functions, so some compilers won't complain.
  179829. * If you do not want to use const, define PNG_NO_CONST here.
  179830. */
  179831. #ifndef PNG_NO_CONST
  179832. # define PNG_CONST const
  179833. #else
  179834. # define PNG_CONST
  179835. #endif
  179836. /* The following defines give you the ability to remove code from the
  179837. * library that you will not be using. I wish I could figure out how to
  179838. * automate this, but I can't do that without making it seriously hard
  179839. * on the users. So if you are not using an ability, change the #define
  179840. * to and #undef, and that part of the library will not be compiled. If
  179841. * your linker can't find a function, you may want to make sure the
  179842. * ability is defined here. Some of these depend upon some others being
  179843. * defined. I haven't figured out all the interactions here, so you may
  179844. * have to experiment awhile to get everything to compile. If you are
  179845. * creating or using a shared library, you probably shouldn't touch this,
  179846. * as it will affect the size of the structures, and this will cause bad
  179847. * things to happen if the library and/or application ever change.
  179848. */
  179849. /* Any features you will not be using can be undef'ed here */
  179850. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  179851. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  179852. * on the compile line, then pick and choose which ones to define without
  179853. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  179854. * if you only want to have a png-compliant reader/writer but don't need
  179855. * any of the extra transformations. This saves about 80 kbytes in a
  179856. * typical installation of the library. (PNG_NO_* form added in version
  179857. * 1.0.1c, for consistency)
  179858. */
  179859. /* The size of the png_text structure changed in libpng-1.0.6 when
  179860. * iTXt support was added. iTXt support was turned off by default through
  179861. * libpng-1.2.x, to support old apps that malloc the png_text structure
  179862. * instead of calling png_set_text() and letting libpng malloc it. It
  179863. * was turned on by default in libpng-1.3.0.
  179864. */
  179865. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179866. # ifndef PNG_NO_iTXt_SUPPORTED
  179867. # define PNG_NO_iTXt_SUPPORTED
  179868. # endif
  179869. # ifndef PNG_NO_READ_iTXt
  179870. # define PNG_NO_READ_iTXt
  179871. # endif
  179872. # ifndef PNG_NO_WRITE_iTXt
  179873. # define PNG_NO_WRITE_iTXt
  179874. # endif
  179875. #endif
  179876. #if !defined(PNG_NO_iTXt_SUPPORTED)
  179877. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  179878. # define PNG_READ_iTXt
  179879. # endif
  179880. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  179881. # define PNG_WRITE_iTXt
  179882. # endif
  179883. #endif
  179884. /* The following support, added after version 1.0.0, can be turned off here en
  179885. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  179886. * with old applications that require the length of png_struct and png_info
  179887. * to remain unchanged.
  179888. */
  179889. #ifdef PNG_LEGACY_SUPPORTED
  179890. # define PNG_NO_FREE_ME
  179891. # define PNG_NO_READ_UNKNOWN_CHUNKS
  179892. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  179893. # define PNG_NO_READ_USER_CHUNKS
  179894. # define PNG_NO_READ_iCCP
  179895. # define PNG_NO_WRITE_iCCP
  179896. # define PNG_NO_READ_iTXt
  179897. # define PNG_NO_WRITE_iTXt
  179898. # define PNG_NO_READ_sCAL
  179899. # define PNG_NO_WRITE_sCAL
  179900. # define PNG_NO_READ_sPLT
  179901. # define PNG_NO_WRITE_sPLT
  179902. # define PNG_NO_INFO_IMAGE
  179903. # define PNG_NO_READ_RGB_TO_GRAY
  179904. # define PNG_NO_READ_USER_TRANSFORM
  179905. # define PNG_NO_WRITE_USER_TRANSFORM
  179906. # define PNG_NO_USER_MEM
  179907. # define PNG_NO_READ_EMPTY_PLTE
  179908. # define PNG_NO_MNG_FEATURES
  179909. # define PNG_NO_FIXED_POINT_SUPPORTED
  179910. #endif
  179911. /* Ignore attempt to turn off both floating and fixed point support */
  179912. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  179913. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  179914. # define PNG_FIXED_POINT_SUPPORTED
  179915. #endif
  179916. #ifndef PNG_NO_FREE_ME
  179917. # define PNG_FREE_ME_SUPPORTED
  179918. #endif
  179919. #if defined(PNG_READ_SUPPORTED)
  179920. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  179921. !defined(PNG_NO_READ_TRANSFORMS)
  179922. # define PNG_READ_TRANSFORMS_SUPPORTED
  179923. #endif
  179924. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  179925. # ifndef PNG_NO_READ_EXPAND
  179926. # define PNG_READ_EXPAND_SUPPORTED
  179927. # endif
  179928. # ifndef PNG_NO_READ_SHIFT
  179929. # define PNG_READ_SHIFT_SUPPORTED
  179930. # endif
  179931. # ifndef PNG_NO_READ_PACK
  179932. # define PNG_READ_PACK_SUPPORTED
  179933. # endif
  179934. # ifndef PNG_NO_READ_BGR
  179935. # define PNG_READ_BGR_SUPPORTED
  179936. # endif
  179937. # ifndef PNG_NO_READ_SWAP
  179938. # define PNG_READ_SWAP_SUPPORTED
  179939. # endif
  179940. # ifndef PNG_NO_READ_PACKSWAP
  179941. # define PNG_READ_PACKSWAP_SUPPORTED
  179942. # endif
  179943. # ifndef PNG_NO_READ_INVERT
  179944. # define PNG_READ_INVERT_SUPPORTED
  179945. # endif
  179946. # ifndef PNG_NO_READ_DITHER
  179947. # define PNG_READ_DITHER_SUPPORTED
  179948. # endif
  179949. # ifndef PNG_NO_READ_BACKGROUND
  179950. # define PNG_READ_BACKGROUND_SUPPORTED
  179951. # endif
  179952. # ifndef PNG_NO_READ_16_TO_8
  179953. # define PNG_READ_16_TO_8_SUPPORTED
  179954. # endif
  179955. # ifndef PNG_NO_READ_FILLER
  179956. # define PNG_READ_FILLER_SUPPORTED
  179957. # endif
  179958. # ifndef PNG_NO_READ_GAMMA
  179959. # define PNG_READ_GAMMA_SUPPORTED
  179960. # endif
  179961. # ifndef PNG_NO_READ_GRAY_TO_RGB
  179962. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  179963. # endif
  179964. # ifndef PNG_NO_READ_SWAP_ALPHA
  179965. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  179966. # endif
  179967. # ifndef PNG_NO_READ_INVERT_ALPHA
  179968. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  179969. # endif
  179970. # ifndef PNG_NO_READ_STRIP_ALPHA
  179971. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  179972. # endif
  179973. # ifndef PNG_NO_READ_USER_TRANSFORM
  179974. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  179975. # endif
  179976. # ifndef PNG_NO_READ_RGB_TO_GRAY
  179977. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  179978. # endif
  179979. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  179980. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  179981. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  179982. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  179983. #endif /* about interlacing capability! You'll */
  179984. /* still have interlacing unless you change the following line: */
  179985. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  179986. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  179987. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  179988. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  179989. # endif
  179990. #endif
  179991. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179992. /* Deprecated, will be removed from version 2.0.0.
  179993. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  179994. #ifndef PNG_NO_READ_EMPTY_PLTE
  179995. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  179996. #endif
  179997. #endif
  179998. #endif /* PNG_READ_SUPPORTED */
  179999. #if defined(PNG_WRITE_SUPPORTED)
  180000. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180001. !defined(PNG_NO_WRITE_TRANSFORMS)
  180002. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180003. #endif
  180004. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180005. # ifndef PNG_NO_WRITE_SHIFT
  180006. # define PNG_WRITE_SHIFT_SUPPORTED
  180007. # endif
  180008. # ifndef PNG_NO_WRITE_PACK
  180009. # define PNG_WRITE_PACK_SUPPORTED
  180010. # endif
  180011. # ifndef PNG_NO_WRITE_BGR
  180012. # define PNG_WRITE_BGR_SUPPORTED
  180013. # endif
  180014. # ifndef PNG_NO_WRITE_SWAP
  180015. # define PNG_WRITE_SWAP_SUPPORTED
  180016. # endif
  180017. # ifndef PNG_NO_WRITE_PACKSWAP
  180018. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180019. # endif
  180020. # ifndef PNG_NO_WRITE_INVERT
  180021. # define PNG_WRITE_INVERT_SUPPORTED
  180022. # endif
  180023. # ifndef PNG_NO_WRITE_FILLER
  180024. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180025. # endif
  180026. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180027. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180028. # endif
  180029. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180030. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180031. # endif
  180032. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180033. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180034. # endif
  180035. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180036. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180037. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180038. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180039. encoders, but can cause trouble
  180040. if left undefined */
  180041. #endif
  180042. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180043. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180044. defined(PNG_FLOATING_POINT_SUPPORTED)
  180045. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180046. #endif
  180047. #ifndef PNG_NO_WRITE_FLUSH
  180048. # define PNG_WRITE_FLUSH_SUPPORTED
  180049. #endif
  180050. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180051. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180052. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180053. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180054. #endif
  180055. #endif
  180056. #endif /* PNG_WRITE_SUPPORTED */
  180057. #ifndef PNG_1_0_X
  180058. # ifndef PNG_NO_ERROR_NUMBERS
  180059. # define PNG_ERROR_NUMBERS_SUPPORTED
  180060. # endif
  180061. #endif /* PNG_1_0_X */
  180062. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180063. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180064. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180065. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180066. # endif
  180067. #endif
  180068. #ifndef PNG_NO_STDIO
  180069. # define PNG_TIME_RFC1123_SUPPORTED
  180070. #endif
  180071. /* This adds extra functions in pngget.c for accessing data from the
  180072. * info pointer (added in version 0.99)
  180073. * png_get_image_width()
  180074. * png_get_image_height()
  180075. * png_get_bit_depth()
  180076. * png_get_color_type()
  180077. * png_get_compression_type()
  180078. * png_get_filter_type()
  180079. * png_get_interlace_type()
  180080. * png_get_pixel_aspect_ratio()
  180081. * png_get_pixels_per_meter()
  180082. * png_get_x_offset_pixels()
  180083. * png_get_y_offset_pixels()
  180084. * png_get_x_offset_microns()
  180085. * png_get_y_offset_microns()
  180086. */
  180087. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180088. # define PNG_EASY_ACCESS_SUPPORTED
  180089. #endif
  180090. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180091. * and removed from version 1.2.20. The following will be removed
  180092. * from libpng-1.4.0
  180093. */
  180094. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180095. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180096. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180097. # endif
  180098. #endif
  180099. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180100. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180101. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180102. # endif
  180103. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180104. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180105. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180106. # define PNG_NO_MMX_CODE
  180107. # endif
  180108. # endif
  180109. # if defined(__APPLE__)
  180110. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180111. # define PNG_NO_MMX_CODE
  180112. # endif
  180113. # endif
  180114. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180115. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180116. # define PNG_NO_MMX_CODE
  180117. # endif
  180118. # endif
  180119. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180120. # define PNG_MMX_CODE_SUPPORTED
  180121. # endif
  180122. #endif
  180123. /* end of obsolete code to be removed from libpng-1.4.0 */
  180124. #if !defined(PNG_1_0_X)
  180125. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180126. # define PNG_USER_MEM_SUPPORTED
  180127. #endif
  180128. #endif /* PNG_1_0_X */
  180129. /* Added at libpng-1.2.6 */
  180130. #if !defined(PNG_1_0_X)
  180131. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  180132. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  180133. # define PNG_SET_USER_LIMITS_SUPPORTED
  180134. #endif
  180135. #endif
  180136. #endif /* PNG_1_0_X */
  180137. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  180138. * how large, set these limits to 0x7fffffffL
  180139. */
  180140. #ifndef PNG_USER_WIDTH_MAX
  180141. # define PNG_USER_WIDTH_MAX 1000000L
  180142. #endif
  180143. #ifndef PNG_USER_HEIGHT_MAX
  180144. # define PNG_USER_HEIGHT_MAX 1000000L
  180145. #endif
  180146. /* These are currently experimental features, define them if you want */
  180147. /* very little testing */
  180148. /*
  180149. #ifdef PNG_READ_SUPPORTED
  180150. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180151. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180152. # endif
  180153. #endif
  180154. */
  180155. /* This is only for PowerPC big-endian and 680x0 systems */
  180156. /* some testing */
  180157. /*
  180158. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  180159. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  180160. #endif
  180161. */
  180162. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  180163. /*
  180164. #define PNG_NO_POINTER_INDEXING
  180165. */
  180166. /* These functions are turned off by default, as they will be phased out. */
  180167. /*
  180168. #define PNG_USELESS_TESTS_SUPPORTED
  180169. #define PNG_CORRECT_PALETTE_SUPPORTED
  180170. */
  180171. /* Any chunks you are not interested in, you can undef here. The
  180172. * ones that allocate memory may be expecially important (hIST,
  180173. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  180174. * a bit smaller.
  180175. */
  180176. #if defined(PNG_READ_SUPPORTED) && \
  180177. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180178. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  180179. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180180. #endif
  180181. #if defined(PNG_WRITE_SUPPORTED) && \
  180182. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180183. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  180184. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180185. #endif
  180186. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180187. #ifdef PNG_NO_READ_TEXT
  180188. # define PNG_NO_READ_iTXt
  180189. # define PNG_NO_READ_tEXt
  180190. # define PNG_NO_READ_zTXt
  180191. #endif
  180192. #ifndef PNG_NO_READ_bKGD
  180193. # define PNG_READ_bKGD_SUPPORTED
  180194. # define PNG_bKGD_SUPPORTED
  180195. #endif
  180196. #ifndef PNG_NO_READ_cHRM
  180197. # define PNG_READ_cHRM_SUPPORTED
  180198. # define PNG_cHRM_SUPPORTED
  180199. #endif
  180200. #ifndef PNG_NO_READ_gAMA
  180201. # define PNG_READ_gAMA_SUPPORTED
  180202. # define PNG_gAMA_SUPPORTED
  180203. #endif
  180204. #ifndef PNG_NO_READ_hIST
  180205. # define PNG_READ_hIST_SUPPORTED
  180206. # define PNG_hIST_SUPPORTED
  180207. #endif
  180208. #ifndef PNG_NO_READ_iCCP
  180209. # define PNG_READ_iCCP_SUPPORTED
  180210. # define PNG_iCCP_SUPPORTED
  180211. #endif
  180212. #ifndef PNG_NO_READ_iTXt
  180213. # ifndef PNG_READ_iTXt_SUPPORTED
  180214. # define PNG_READ_iTXt_SUPPORTED
  180215. # endif
  180216. # ifndef PNG_iTXt_SUPPORTED
  180217. # define PNG_iTXt_SUPPORTED
  180218. # endif
  180219. #endif
  180220. #ifndef PNG_NO_READ_oFFs
  180221. # define PNG_READ_oFFs_SUPPORTED
  180222. # define PNG_oFFs_SUPPORTED
  180223. #endif
  180224. #ifndef PNG_NO_READ_pCAL
  180225. # define PNG_READ_pCAL_SUPPORTED
  180226. # define PNG_pCAL_SUPPORTED
  180227. #endif
  180228. #ifndef PNG_NO_READ_sCAL
  180229. # define PNG_READ_sCAL_SUPPORTED
  180230. # define PNG_sCAL_SUPPORTED
  180231. #endif
  180232. #ifndef PNG_NO_READ_pHYs
  180233. # define PNG_READ_pHYs_SUPPORTED
  180234. # define PNG_pHYs_SUPPORTED
  180235. #endif
  180236. #ifndef PNG_NO_READ_sBIT
  180237. # define PNG_READ_sBIT_SUPPORTED
  180238. # define PNG_sBIT_SUPPORTED
  180239. #endif
  180240. #ifndef PNG_NO_READ_sPLT
  180241. # define PNG_READ_sPLT_SUPPORTED
  180242. # define PNG_sPLT_SUPPORTED
  180243. #endif
  180244. #ifndef PNG_NO_READ_sRGB
  180245. # define PNG_READ_sRGB_SUPPORTED
  180246. # define PNG_sRGB_SUPPORTED
  180247. #endif
  180248. #ifndef PNG_NO_READ_tEXt
  180249. # define PNG_READ_tEXt_SUPPORTED
  180250. # define PNG_tEXt_SUPPORTED
  180251. #endif
  180252. #ifndef PNG_NO_READ_tIME
  180253. # define PNG_READ_tIME_SUPPORTED
  180254. # define PNG_tIME_SUPPORTED
  180255. #endif
  180256. #ifndef PNG_NO_READ_tRNS
  180257. # define PNG_READ_tRNS_SUPPORTED
  180258. # define PNG_tRNS_SUPPORTED
  180259. #endif
  180260. #ifndef PNG_NO_READ_zTXt
  180261. # define PNG_READ_zTXt_SUPPORTED
  180262. # define PNG_zTXt_SUPPORTED
  180263. #endif
  180264. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  180265. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  180266. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180267. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180268. # endif
  180269. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180270. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180271. # endif
  180272. #endif
  180273. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  180274. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  180275. # define PNG_READ_USER_CHUNKS_SUPPORTED
  180276. # define PNG_USER_CHUNKS_SUPPORTED
  180277. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  180278. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  180279. # endif
  180280. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  180281. # undef PNG_NO_HANDLE_AS_UNKNOWN
  180282. # endif
  180283. #endif
  180284. #ifndef PNG_NO_READ_OPT_PLTE
  180285. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  180286. #endif /* optional PLTE chunk in RGB and RGBA images */
  180287. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  180288. defined(PNG_READ_zTXt_SUPPORTED)
  180289. # define PNG_READ_TEXT_SUPPORTED
  180290. # define PNG_TEXT_SUPPORTED
  180291. #endif
  180292. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  180293. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180294. #ifdef PNG_NO_WRITE_TEXT
  180295. # define PNG_NO_WRITE_iTXt
  180296. # define PNG_NO_WRITE_tEXt
  180297. # define PNG_NO_WRITE_zTXt
  180298. #endif
  180299. #ifndef PNG_NO_WRITE_bKGD
  180300. # define PNG_WRITE_bKGD_SUPPORTED
  180301. # ifndef PNG_bKGD_SUPPORTED
  180302. # define PNG_bKGD_SUPPORTED
  180303. # endif
  180304. #endif
  180305. #ifndef PNG_NO_WRITE_cHRM
  180306. # define PNG_WRITE_cHRM_SUPPORTED
  180307. # ifndef PNG_cHRM_SUPPORTED
  180308. # define PNG_cHRM_SUPPORTED
  180309. # endif
  180310. #endif
  180311. #ifndef PNG_NO_WRITE_gAMA
  180312. # define PNG_WRITE_gAMA_SUPPORTED
  180313. # ifndef PNG_gAMA_SUPPORTED
  180314. # define PNG_gAMA_SUPPORTED
  180315. # endif
  180316. #endif
  180317. #ifndef PNG_NO_WRITE_hIST
  180318. # define PNG_WRITE_hIST_SUPPORTED
  180319. # ifndef PNG_hIST_SUPPORTED
  180320. # define PNG_hIST_SUPPORTED
  180321. # endif
  180322. #endif
  180323. #ifndef PNG_NO_WRITE_iCCP
  180324. # define PNG_WRITE_iCCP_SUPPORTED
  180325. # ifndef PNG_iCCP_SUPPORTED
  180326. # define PNG_iCCP_SUPPORTED
  180327. # endif
  180328. #endif
  180329. #ifndef PNG_NO_WRITE_iTXt
  180330. # ifndef PNG_WRITE_iTXt_SUPPORTED
  180331. # define PNG_WRITE_iTXt_SUPPORTED
  180332. # endif
  180333. # ifndef PNG_iTXt_SUPPORTED
  180334. # define PNG_iTXt_SUPPORTED
  180335. # endif
  180336. #endif
  180337. #ifndef PNG_NO_WRITE_oFFs
  180338. # define PNG_WRITE_oFFs_SUPPORTED
  180339. # ifndef PNG_oFFs_SUPPORTED
  180340. # define PNG_oFFs_SUPPORTED
  180341. # endif
  180342. #endif
  180343. #ifndef PNG_NO_WRITE_pCAL
  180344. # define PNG_WRITE_pCAL_SUPPORTED
  180345. # ifndef PNG_pCAL_SUPPORTED
  180346. # define PNG_pCAL_SUPPORTED
  180347. # endif
  180348. #endif
  180349. #ifndef PNG_NO_WRITE_sCAL
  180350. # define PNG_WRITE_sCAL_SUPPORTED
  180351. # ifndef PNG_sCAL_SUPPORTED
  180352. # define PNG_sCAL_SUPPORTED
  180353. # endif
  180354. #endif
  180355. #ifndef PNG_NO_WRITE_pHYs
  180356. # define PNG_WRITE_pHYs_SUPPORTED
  180357. # ifndef PNG_pHYs_SUPPORTED
  180358. # define PNG_pHYs_SUPPORTED
  180359. # endif
  180360. #endif
  180361. #ifndef PNG_NO_WRITE_sBIT
  180362. # define PNG_WRITE_sBIT_SUPPORTED
  180363. # ifndef PNG_sBIT_SUPPORTED
  180364. # define PNG_sBIT_SUPPORTED
  180365. # endif
  180366. #endif
  180367. #ifndef PNG_NO_WRITE_sPLT
  180368. # define PNG_WRITE_sPLT_SUPPORTED
  180369. # ifndef PNG_sPLT_SUPPORTED
  180370. # define PNG_sPLT_SUPPORTED
  180371. # endif
  180372. #endif
  180373. #ifndef PNG_NO_WRITE_sRGB
  180374. # define PNG_WRITE_sRGB_SUPPORTED
  180375. # ifndef PNG_sRGB_SUPPORTED
  180376. # define PNG_sRGB_SUPPORTED
  180377. # endif
  180378. #endif
  180379. #ifndef PNG_NO_WRITE_tEXt
  180380. # define PNG_WRITE_tEXt_SUPPORTED
  180381. # ifndef PNG_tEXt_SUPPORTED
  180382. # define PNG_tEXt_SUPPORTED
  180383. # endif
  180384. #endif
  180385. #ifndef PNG_NO_WRITE_tIME
  180386. # define PNG_WRITE_tIME_SUPPORTED
  180387. # ifndef PNG_tIME_SUPPORTED
  180388. # define PNG_tIME_SUPPORTED
  180389. # endif
  180390. #endif
  180391. #ifndef PNG_NO_WRITE_tRNS
  180392. # define PNG_WRITE_tRNS_SUPPORTED
  180393. # ifndef PNG_tRNS_SUPPORTED
  180394. # define PNG_tRNS_SUPPORTED
  180395. # endif
  180396. #endif
  180397. #ifndef PNG_NO_WRITE_zTXt
  180398. # define PNG_WRITE_zTXt_SUPPORTED
  180399. # ifndef PNG_zTXt_SUPPORTED
  180400. # define PNG_zTXt_SUPPORTED
  180401. # endif
  180402. #endif
  180403. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  180404. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  180405. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180406. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180407. # endif
  180408. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180409. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180410. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180411. # endif
  180412. # endif
  180413. #endif
  180414. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  180415. defined(PNG_WRITE_zTXt_SUPPORTED)
  180416. # define PNG_WRITE_TEXT_SUPPORTED
  180417. # ifndef PNG_TEXT_SUPPORTED
  180418. # define PNG_TEXT_SUPPORTED
  180419. # endif
  180420. #endif
  180421. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  180422. /* Turn this off to disable png_read_png() and
  180423. * png_write_png() and leave the row_pointers member
  180424. * out of the info structure.
  180425. */
  180426. #ifndef PNG_NO_INFO_IMAGE
  180427. # define PNG_INFO_IMAGE_SUPPORTED
  180428. #endif
  180429. /* need the time information for reading tIME chunks */
  180430. #if defined(PNG_tIME_SUPPORTED)
  180431. # if !defined(_WIN32_WCE)
  180432. /* "time.h" functions are not supported on WindowsCE */
  180433. # include <time.h>
  180434. # endif
  180435. #endif
  180436. /* Some typedefs to get us started. These should be safe on most of the
  180437. * common platforms. The typedefs should be at least as large as the
  180438. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  180439. * don't have to be exactly that size. Some compilers dislike passing
  180440. * unsigned shorts as function parameters, so you may be better off using
  180441. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  180442. * want to have unsigned int for png_uint_32 instead of unsigned long.
  180443. */
  180444. typedef unsigned long png_uint_32;
  180445. typedef long png_int_32;
  180446. typedef unsigned short png_uint_16;
  180447. typedef short png_int_16;
  180448. typedef unsigned char png_byte;
  180449. /* This is usually size_t. It is typedef'ed just in case you need it to
  180450. change (I'm not sure if you will or not, so I thought I'd be safe) */
  180451. #ifdef PNG_SIZE_T
  180452. typedef PNG_SIZE_T png_size_t;
  180453. # define png_sizeof(x) png_convert_size(sizeof (x))
  180454. #else
  180455. typedef size_t png_size_t;
  180456. # define png_sizeof(x) sizeof (x)
  180457. #endif
  180458. /* The following is needed for medium model support. It cannot be in the
  180459. * PNG_INTERNAL section. Needs modification for other compilers besides
  180460. * MSC. Model independent support declares all arrays and pointers to be
  180461. * large using the far keyword. The zlib version used must also support
  180462. * model independent data. As of version zlib 1.0.4, the necessary changes
  180463. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  180464. * changes that are needed. (Tim Wegner)
  180465. */
  180466. /* Separate compiler dependencies (problem here is that zlib.h always
  180467. defines FAR. (SJT) */
  180468. #ifdef __BORLANDC__
  180469. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  180470. # define LDATA 1
  180471. # else
  180472. # define LDATA 0
  180473. # endif
  180474. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  180475. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  180476. # define PNG_MAX_MALLOC_64K
  180477. # if (LDATA != 1)
  180478. # ifndef FAR
  180479. # define FAR __far
  180480. # endif
  180481. # define USE_FAR_KEYWORD
  180482. # endif /* LDATA != 1 */
  180483. /* Possibly useful for moving data out of default segment.
  180484. * Uncomment it if you want. Could also define FARDATA as
  180485. * const if your compiler supports it. (SJT)
  180486. # define FARDATA FAR
  180487. */
  180488. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  180489. #endif /* __BORLANDC__ */
  180490. /* Suggest testing for specific compiler first before testing for
  180491. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  180492. * making reliance oncertain keywords suspect. (SJT)
  180493. */
  180494. /* MSC Medium model */
  180495. #if defined(FAR)
  180496. # if defined(M_I86MM)
  180497. # define USE_FAR_KEYWORD
  180498. # define FARDATA FAR
  180499. # include <dos.h>
  180500. # endif
  180501. #endif
  180502. /* SJT: default case */
  180503. #ifndef FAR
  180504. # define FAR
  180505. #endif
  180506. /* At this point FAR is always defined */
  180507. #ifndef FARDATA
  180508. # define FARDATA
  180509. #endif
  180510. /* Typedef for floating-point numbers that are converted
  180511. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  180512. typedef png_int_32 png_fixed_point;
  180513. /* Add typedefs for pointers */
  180514. typedef void FAR * png_voidp;
  180515. typedef png_byte FAR * png_bytep;
  180516. typedef png_uint_32 FAR * png_uint_32p;
  180517. typedef png_int_32 FAR * png_int_32p;
  180518. typedef png_uint_16 FAR * png_uint_16p;
  180519. typedef png_int_16 FAR * png_int_16p;
  180520. typedef PNG_CONST char FAR * png_const_charp;
  180521. typedef char FAR * png_charp;
  180522. typedef png_fixed_point FAR * png_fixed_point_p;
  180523. #ifndef PNG_NO_STDIO
  180524. #if defined(_WIN32_WCE)
  180525. typedef HANDLE png_FILE_p;
  180526. #else
  180527. typedef FILE * png_FILE_p;
  180528. #endif
  180529. #endif
  180530. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180531. typedef double FAR * png_doublep;
  180532. #endif
  180533. /* Pointers to pointers; i.e. arrays */
  180534. typedef png_byte FAR * FAR * png_bytepp;
  180535. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  180536. typedef png_int_32 FAR * FAR * png_int_32pp;
  180537. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  180538. typedef png_int_16 FAR * FAR * png_int_16pp;
  180539. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  180540. typedef char FAR * FAR * png_charpp;
  180541. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  180542. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180543. typedef double FAR * FAR * png_doublepp;
  180544. #endif
  180545. /* Pointers to pointers to pointers; i.e., pointer to array */
  180546. typedef char FAR * FAR * FAR * png_charppp;
  180547. #if 0
  180548. /* SPC - Is this stuff deprecated? */
  180549. /* It'll be removed as of libpng-1.3.0 - GR-P */
  180550. /* libpng typedefs for types in zlib. If zlib changes
  180551. * or another compression library is used, then change these.
  180552. * Eliminates need to change all the source files.
  180553. */
  180554. typedef charf * png_zcharp;
  180555. typedef charf * FAR * png_zcharpp;
  180556. typedef z_stream FAR * png_zstreamp;
  180557. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  180558. /*
  180559. * Define PNG_BUILD_DLL if the module being built is a Windows
  180560. * LIBPNG DLL.
  180561. *
  180562. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  180563. * It is equivalent to Microsoft predefined macro _DLL that is
  180564. * automatically defined when you compile using the share
  180565. * version of the CRT (C Run-Time library)
  180566. *
  180567. * The cygwin mods make this behavior a little different:
  180568. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  180569. * Define PNG_STATIC if you are building a static library for use with cygwin,
  180570. * -or- if you are building an application that you want to link to the
  180571. * static library.
  180572. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  180573. * the other flags is defined.
  180574. */
  180575. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  180576. # define PNG_DLL
  180577. #endif
  180578. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  180579. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  180580. * command-line override
  180581. */
  180582. #if defined(__CYGWIN__)
  180583. # if !defined(PNG_STATIC)
  180584. # if defined(PNG_USE_GLOBAL_ARRAYS)
  180585. # undef PNG_USE_GLOBAL_ARRAYS
  180586. # endif
  180587. # if !defined(PNG_USE_LOCAL_ARRAYS)
  180588. # define PNG_USE_LOCAL_ARRAYS
  180589. # endif
  180590. # else
  180591. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  180592. # if defined(PNG_USE_GLOBAL_ARRAYS)
  180593. # undef PNG_USE_GLOBAL_ARRAYS
  180594. # endif
  180595. # endif
  180596. # endif
  180597. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  180598. # define PNG_USE_LOCAL_ARRAYS
  180599. # endif
  180600. #endif
  180601. /* Do not use global arrays (helps with building DLL's)
  180602. * They are no longer used in libpng itself, since version 1.0.5c,
  180603. * but might be required for some pre-1.0.5c applications.
  180604. */
  180605. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  180606. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  180607. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  180608. # define PNG_USE_LOCAL_ARRAYS
  180609. # else
  180610. # define PNG_USE_GLOBAL_ARRAYS
  180611. # endif
  180612. #endif
  180613. #if defined(__CYGWIN__)
  180614. # undef PNGAPI
  180615. # define PNGAPI __cdecl
  180616. # undef PNG_IMPEXP
  180617. # define PNG_IMPEXP
  180618. #endif
  180619. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  180620. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  180621. * Don't ignore those warnings; you must also reset the default calling
  180622. * convention in your compiler to match your PNGAPI, and you must build
  180623. * zlib and your applications the same way you build libpng.
  180624. */
  180625. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  180626. # ifndef PNG_NO_MODULEDEF
  180627. # define PNG_NO_MODULEDEF
  180628. # endif
  180629. #endif
  180630. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  180631. # define PNG_IMPEXP
  180632. #endif
  180633. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  180634. (( defined(_Windows) || defined(_WINDOWS) || \
  180635. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  180636. # ifndef PNGAPI
  180637. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  180638. # define PNGAPI __cdecl
  180639. # else
  180640. # define PNGAPI _cdecl
  180641. # endif
  180642. # endif
  180643. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  180644. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  180645. # define PNG_IMPEXP
  180646. # endif
  180647. # if !defined(PNG_IMPEXP)
  180648. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  180649. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  180650. /* Borland/Microsoft */
  180651. # if defined(_MSC_VER) || defined(__BORLANDC__)
  180652. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  180653. # define PNG_EXPORT PNG_EXPORT_TYPE1
  180654. # else
  180655. # define PNG_EXPORT PNG_EXPORT_TYPE2
  180656. # if defined(PNG_BUILD_DLL)
  180657. # define PNG_IMPEXP __export
  180658. # else
  180659. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  180660. VC++ */
  180661. # endif /* Exists in Borland C++ for
  180662. C++ classes (== huge) */
  180663. # endif
  180664. # endif
  180665. # if !defined(PNG_IMPEXP)
  180666. # if defined(PNG_BUILD_DLL)
  180667. # define PNG_IMPEXP __declspec(dllexport)
  180668. # else
  180669. # define PNG_IMPEXP __declspec(dllimport)
  180670. # endif
  180671. # endif
  180672. # endif /* PNG_IMPEXP */
  180673. #else /* !(DLL || non-cygwin WINDOWS) */
  180674. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  180675. # ifndef PNGAPI
  180676. # define PNGAPI _System
  180677. # endif
  180678. # else
  180679. # if 0 /* ... other platforms, with other meanings */
  180680. # endif
  180681. # endif
  180682. #endif
  180683. #ifndef PNGAPI
  180684. # define PNGAPI
  180685. #endif
  180686. #ifndef PNG_IMPEXP
  180687. # define PNG_IMPEXP
  180688. #endif
  180689. #ifdef PNG_BUILDSYMS
  180690. # ifndef PNG_EXPORT
  180691. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  180692. # endif
  180693. # ifdef PNG_USE_GLOBAL_ARRAYS
  180694. # ifndef PNG_EXPORT_VAR
  180695. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  180696. # endif
  180697. # endif
  180698. #endif
  180699. #ifndef PNG_EXPORT
  180700. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  180701. #endif
  180702. #ifdef PNG_USE_GLOBAL_ARRAYS
  180703. # ifndef PNG_EXPORT_VAR
  180704. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  180705. # endif
  180706. #endif
  180707. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  180708. * functions that are passed far data must be model independent.
  180709. */
  180710. #ifndef PNG_ABORT
  180711. # define PNG_ABORT() abort()
  180712. #endif
  180713. #ifdef PNG_SETJMP_SUPPORTED
  180714. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  180715. #else
  180716. # define png_jmpbuf(png_ptr) \
  180717. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  180718. #endif
  180719. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  180720. /* use this to make far-to-near assignments */
  180721. # define CHECK 1
  180722. # define NOCHECK 0
  180723. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  180724. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  180725. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  180726. # define png_strcpy _fstrcpy
  180727. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  180728. # define png_strlen _fstrlen
  180729. # define png_memcmp _fmemcmp /* SJT: added */
  180730. # define png_memcpy _fmemcpy
  180731. # define png_memset _fmemset
  180732. #else /* use the usual functions */
  180733. # define CVT_PTR(ptr) (ptr)
  180734. # define CVT_PTR_NOCHECK(ptr) (ptr)
  180735. # ifndef PNG_NO_SNPRINTF
  180736. # ifdef _MSC_VER
  180737. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  180738. # define png_snprintf2 _snprintf
  180739. # define png_snprintf6 _snprintf
  180740. # else
  180741. # define png_snprintf snprintf /* Added to v 1.2.19 */
  180742. # define png_snprintf2 snprintf
  180743. # define png_snprintf6 snprintf
  180744. # endif
  180745. # else
  180746. /* You don't have or don't want to use snprintf(). Caution: Using
  180747. * sprintf instead of snprintf exposes your application to accidental
  180748. * or malevolent buffer overflows. If you don't have snprintf()
  180749. * as a general rule you should provide one (you can get one from
  180750. * Portable OpenSSH). */
  180751. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  180752. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  180753. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  180754. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  180755. # endif
  180756. # define png_strcpy strcpy
  180757. # define png_strncpy strncpy /* Added to v 1.2.6 */
  180758. # define png_strlen strlen
  180759. # define png_memcmp memcmp /* SJT: added */
  180760. # define png_memcpy memcpy
  180761. # define png_memset memset
  180762. #endif
  180763. /* End of memory model independent support */
  180764. /* Just a little check that someone hasn't tried to define something
  180765. * contradictory.
  180766. */
  180767. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  180768. # undef PNG_ZBUF_SIZE
  180769. # define PNG_ZBUF_SIZE 65536L
  180770. #endif
  180771. /* Added at libpng-1.2.8 */
  180772. #endif /* PNG_VERSION_INFO_ONLY */
  180773. #endif /* PNGCONF_H */
  180774. /*** End of inlined file: pngconf.h ***/
  180775. #ifdef _MSC_VER
  180776. #pragma warning (disable: 4996 4100)
  180777. #endif
  180778. /*
  180779. * Added at libpng-1.2.8 */
  180780. /* Ref MSDN: Private as priority over Special
  180781. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  180782. * procedures. If this value is given, the StringFileInfo block must
  180783. * contain a PrivateBuild string.
  180784. *
  180785. * VS_FF_SPECIALBUILD File *was* built by the original company using
  180786. * standard release procedures but is a variation of the standard
  180787. * file of the same version number. If this value is given, the
  180788. * StringFileInfo block must contain a SpecialBuild string.
  180789. */
  180790. #if defined(PNG_USER_PRIVATEBUILD)
  180791. # define PNG_LIBPNG_BUILD_TYPE \
  180792. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  180793. #else
  180794. # if defined(PNG_LIBPNG_SPECIALBUILD)
  180795. # define PNG_LIBPNG_BUILD_TYPE \
  180796. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  180797. # else
  180798. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  180799. # endif
  180800. #endif
  180801. #ifndef PNG_VERSION_INFO_ONLY
  180802. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  180803. #ifdef __cplusplus
  180804. extern "C" {
  180805. #endif /* __cplusplus */
  180806. /* This file is arranged in several sections. The first section contains
  180807. * structure and type definitions. The second section contains the external
  180808. * library functions, while the third has the internal library functions,
  180809. * which applications aren't expected to use directly.
  180810. */
  180811. #ifndef PNG_NO_TYPECAST_NULL
  180812. #define int_p_NULL (int *)NULL
  180813. #define png_bytep_NULL (png_bytep)NULL
  180814. #define png_bytepp_NULL (png_bytepp)NULL
  180815. #define png_doublep_NULL (png_doublep)NULL
  180816. #define png_error_ptr_NULL (png_error_ptr)NULL
  180817. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  180818. #define png_free_ptr_NULL (png_free_ptr)NULL
  180819. #define png_infopp_NULL (png_infopp)NULL
  180820. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  180821. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  180822. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  180823. #define png_structp_NULL (png_structp)NULL
  180824. #define png_uint_16p_NULL (png_uint_16p)NULL
  180825. #define png_voidp_NULL (png_voidp)NULL
  180826. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  180827. #else
  180828. #define int_p_NULL NULL
  180829. #define png_bytep_NULL NULL
  180830. #define png_bytepp_NULL NULL
  180831. #define png_doublep_NULL NULL
  180832. #define png_error_ptr_NULL NULL
  180833. #define png_flush_ptr_NULL NULL
  180834. #define png_free_ptr_NULL NULL
  180835. #define png_infopp_NULL NULL
  180836. #define png_malloc_ptr_NULL NULL
  180837. #define png_read_status_ptr_NULL NULL
  180838. #define png_rw_ptr_NULL NULL
  180839. #define png_structp_NULL NULL
  180840. #define png_uint_16p_NULL NULL
  180841. #define png_voidp_NULL NULL
  180842. #define png_write_status_ptr_NULL NULL
  180843. #endif
  180844. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  180845. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  180846. /* Version information for C files, stored in png.c. This had better match
  180847. * the version above.
  180848. */
  180849. #ifdef PNG_USE_GLOBAL_ARRAYS
  180850. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  180851. /* need room for 99.99.99beta99z */
  180852. #else
  180853. #define png_libpng_ver png_get_header_ver(NULL)
  180854. #endif
  180855. #ifdef PNG_USE_GLOBAL_ARRAYS
  180856. /* This was removed in version 1.0.5c */
  180857. /* Structures to facilitate easy interlacing. See png.c for more details */
  180858. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  180859. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  180860. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  180861. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  180862. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  180863. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  180864. /* This isn't currently used. If you need it, see png.c for more details.
  180865. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  180866. */
  180867. #endif
  180868. #endif /* PNG_NO_EXTERN */
  180869. /* Three color definitions. The order of the red, green, and blue, (and the
  180870. * exact size) is not important, although the size of the fields need to
  180871. * be png_byte or png_uint_16 (as defined below).
  180872. */
  180873. typedef struct png_color_struct
  180874. {
  180875. png_byte red;
  180876. png_byte green;
  180877. png_byte blue;
  180878. } png_color;
  180879. typedef png_color FAR * png_colorp;
  180880. typedef png_color FAR * FAR * png_colorpp;
  180881. typedef struct png_color_16_struct
  180882. {
  180883. png_byte index; /* used for palette files */
  180884. png_uint_16 red; /* for use in red green blue files */
  180885. png_uint_16 green;
  180886. png_uint_16 blue;
  180887. png_uint_16 gray; /* for use in grayscale files */
  180888. } png_color_16;
  180889. typedef png_color_16 FAR * png_color_16p;
  180890. typedef png_color_16 FAR * FAR * png_color_16pp;
  180891. typedef struct png_color_8_struct
  180892. {
  180893. png_byte red; /* for use in red green blue files */
  180894. png_byte green;
  180895. png_byte blue;
  180896. png_byte gray; /* for use in grayscale files */
  180897. png_byte alpha; /* for alpha channel files */
  180898. } png_color_8;
  180899. typedef png_color_8 FAR * png_color_8p;
  180900. typedef png_color_8 FAR * FAR * png_color_8pp;
  180901. /*
  180902. * The following two structures are used for the in-core representation
  180903. * of sPLT chunks.
  180904. */
  180905. typedef struct png_sPLT_entry_struct
  180906. {
  180907. png_uint_16 red;
  180908. png_uint_16 green;
  180909. png_uint_16 blue;
  180910. png_uint_16 alpha;
  180911. png_uint_16 frequency;
  180912. } png_sPLT_entry;
  180913. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  180914. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  180915. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  180916. * occupy the LSB of their respective members, and the MSB of each member
  180917. * is zero-filled. The frequency member always occupies the full 16 bits.
  180918. */
  180919. typedef struct png_sPLT_struct
  180920. {
  180921. png_charp name; /* palette name */
  180922. png_byte depth; /* depth of palette samples */
  180923. png_sPLT_entryp entries; /* palette entries */
  180924. png_int_32 nentries; /* number of palette entries */
  180925. } png_sPLT_t;
  180926. typedef png_sPLT_t FAR * png_sPLT_tp;
  180927. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  180928. #ifdef PNG_TEXT_SUPPORTED
  180929. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  180930. * and whether that contents is compressed or not. The "key" field
  180931. * points to a regular zero-terminated C string. The "text", "lang", and
  180932. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  180933. * However, the * structure returned by png_get_text() will always contain
  180934. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  180935. * so they can be safely used in printf() and other string-handling functions.
  180936. */
  180937. typedef struct png_text_struct
  180938. {
  180939. int compression; /* compression value:
  180940. -1: tEXt, none
  180941. 0: zTXt, deflate
  180942. 1: iTXt, none
  180943. 2: iTXt, deflate */
  180944. png_charp key; /* keyword, 1-79 character description of "text" */
  180945. png_charp text; /* comment, may be an empty string (ie "")
  180946. or a NULL pointer */
  180947. png_size_t text_length; /* length of the text string */
  180948. #ifdef PNG_iTXt_SUPPORTED
  180949. png_size_t itxt_length; /* length of the itxt string */
  180950. png_charp lang; /* language code, 0-79 characters
  180951. or a NULL pointer */
  180952. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  180953. chars or a NULL pointer */
  180954. #endif
  180955. } png_text;
  180956. typedef png_text FAR * png_textp;
  180957. typedef png_text FAR * FAR * png_textpp;
  180958. #endif
  180959. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  180960. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  180961. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  180962. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  180963. #define PNG_TEXT_COMPRESSION_NONE -1
  180964. #define PNG_TEXT_COMPRESSION_zTXt 0
  180965. #define PNG_ITXT_COMPRESSION_NONE 1
  180966. #define PNG_ITXT_COMPRESSION_zTXt 2
  180967. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  180968. /* png_time is a way to hold the time in an machine independent way.
  180969. * Two conversions are provided, both from time_t and struct tm. There
  180970. * is no portable way to convert to either of these structures, as far
  180971. * as I know. If you know of a portable way, send it to me. As a side
  180972. * note - PNG has always been Year 2000 compliant!
  180973. */
  180974. typedef struct png_time_struct
  180975. {
  180976. png_uint_16 year; /* full year, as in, 1995 */
  180977. png_byte month; /* month of year, 1 - 12 */
  180978. png_byte day; /* day of month, 1 - 31 */
  180979. png_byte hour; /* hour of day, 0 - 23 */
  180980. png_byte minute; /* minute of hour, 0 - 59 */
  180981. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  180982. } png_time;
  180983. typedef png_time FAR * png_timep;
  180984. typedef png_time FAR * FAR * png_timepp;
  180985. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180986. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  180987. * no specific support. The idea is that we can use this to queue
  180988. * up private chunks for output even though the library doesn't actually
  180989. * know about their semantics.
  180990. */
  180991. typedef struct png_unknown_chunk_t
  180992. {
  180993. png_byte name[5];
  180994. png_byte *data;
  180995. png_size_t size;
  180996. /* libpng-using applications should NOT directly modify this byte. */
  180997. png_byte location; /* mode of operation at read time */
  180998. }
  180999. png_unknown_chunk;
  181000. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181001. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181002. #endif
  181003. /* png_info is a structure that holds the information in a PNG file so
  181004. * that the application can find out the characteristics of the image.
  181005. * If you are reading the file, this structure will tell you what is
  181006. * in the PNG file. If you are writing the file, fill in the information
  181007. * you want to put into the PNG file, then call png_write_info().
  181008. * The names chosen should be very close to the PNG specification, so
  181009. * consult that document for information about the meaning of each field.
  181010. *
  181011. * With libpng < 0.95, it was only possible to directly set and read the
  181012. * the values in the png_info_struct, which meant that the contents and
  181013. * order of the values had to remain fixed. With libpng 0.95 and later,
  181014. * however, there are now functions that abstract the contents of
  181015. * png_info_struct from the application, so this makes it easier to use
  181016. * libpng with dynamic libraries, and even makes it possible to use
  181017. * libraries that don't have all of the libpng ancillary chunk-handing
  181018. * functionality.
  181019. *
  181020. * In any case, the order of the parameters in png_info_struct should NOT
  181021. * be changed for as long as possible to keep compatibility with applications
  181022. * that use the old direct-access method with png_info_struct.
  181023. *
  181024. * The following members may have allocated storage attached that should be
  181025. * cleaned up before the structure is discarded: palette, trans, text,
  181026. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181027. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181028. * are automatically freed when the info structure is deallocated, if they were
  181029. * allocated internally by libpng. This behavior can be changed by means
  181030. * of the png_data_freer() function.
  181031. *
  181032. * More allocation details: all the chunk-reading functions that
  181033. * change these members go through the corresponding png_set_*
  181034. * functions. A function to clear these members is available: see
  181035. * png_free_data(). The png_set_* functions do not depend on being
  181036. * able to point info structure members to any of the storage they are
  181037. * passed (they make their own copies), EXCEPT that the png_set_text
  181038. * functions use the same storage passed to them in the text_ptr or
  181039. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181040. * functions do not make their own copies.
  181041. */
  181042. typedef struct png_info_struct
  181043. {
  181044. /* the following are necessary for every PNG file */
  181045. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181046. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181047. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181048. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181049. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181050. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181051. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181052. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181053. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181054. /* The following three should have been named *_method not *_type */
  181055. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181056. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181057. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181058. /* The following is informational only on read, and not used on writes. */
  181059. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181060. png_byte pixel_depth; /* number of bits per pixel */
  181061. png_byte spare_byte; /* to align the data, and for future use */
  181062. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181063. /* The rest of the data is optional. If you are reading, check the
  181064. * valid field to see if the information in these are valid. If you
  181065. * are writing, set the valid field to those chunks you want written,
  181066. * and initialize the appropriate fields below.
  181067. */
  181068. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181069. /* The gAMA chunk describes the gamma characteristics of the system
  181070. * on which the image was created, normally in the range [1.0, 2.5].
  181071. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181072. */
  181073. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181074. #endif
  181075. #if defined(PNG_sRGB_SUPPORTED)
  181076. /* GR-P, 0.96a */
  181077. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181078. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181079. #endif
  181080. #if defined(PNG_TEXT_SUPPORTED)
  181081. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181082. * uncompressed, compressed, and optionally compressed forms, respectively.
  181083. * The data in "text" is an array of pointers to uncompressed,
  181084. * null-terminated C strings. Each chunk has a keyword that describes the
  181085. * textual data contained in that chunk. Keywords are not required to be
  181086. * unique, and the text string may be empty. Any number of text chunks may
  181087. * be in an image.
  181088. */
  181089. int num_text; /* number of comments read/to write */
  181090. int max_text; /* current size of text array */
  181091. png_textp text; /* array of comments read/to write */
  181092. #endif /* PNG_TEXT_SUPPORTED */
  181093. #if defined(PNG_tIME_SUPPORTED)
  181094. /* The tIME chunk holds the last time the displayed image data was
  181095. * modified. See the png_time struct for the contents of this struct.
  181096. */
  181097. png_time mod_time;
  181098. #endif
  181099. #if defined(PNG_sBIT_SUPPORTED)
  181100. /* The sBIT chunk specifies the number of significant high-order bits
  181101. * in the pixel data. Values are in the range [1, bit_depth], and are
  181102. * only specified for the channels in the pixel data. The contents of
  181103. * the low-order bits is not specified. Data is valid if
  181104. * (valid & PNG_INFO_sBIT) is non-zero.
  181105. */
  181106. png_color_8 sig_bit; /* significant bits in color channels */
  181107. #endif
  181108. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181109. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181110. /* The tRNS chunk supplies transparency data for paletted images and
  181111. * other image types that don't need a full alpha channel. There are
  181112. * "num_trans" transparency values for a paletted image, stored in the
  181113. * same order as the palette colors, starting from index 0. Values
  181114. * for the data are in the range [0, 255], ranging from fully transparent
  181115. * to fully opaque, respectively. For non-paletted images, there is a
  181116. * single color specified that should be treated as fully transparent.
  181117. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181118. */
  181119. png_bytep trans; /* transparent values for paletted image */
  181120. png_color_16 trans_values; /* transparent color for non-palette image */
  181121. #endif
  181122. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181123. /* The bKGD chunk gives the suggested image background color if the
  181124. * display program does not have its own background color and the image
  181125. * is needs to composited onto a background before display. The colors
  181126. * in "background" are normally in the same color space/depth as the
  181127. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  181128. */
  181129. png_color_16 background;
  181130. #endif
  181131. #if defined(PNG_oFFs_SUPPORTED)
  181132. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  181133. * and downwards from the top-left corner of the display, page, or other
  181134. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  181135. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  181136. */
  181137. png_int_32 x_offset; /* x offset on page */
  181138. png_int_32 y_offset; /* y offset on page */
  181139. png_byte offset_unit_type; /* offset units type */
  181140. #endif
  181141. #if defined(PNG_pHYs_SUPPORTED)
  181142. /* The pHYs chunk gives the physical pixel density of the image for
  181143. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  181144. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  181145. */
  181146. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  181147. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  181148. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  181149. #endif
  181150. #if defined(PNG_hIST_SUPPORTED)
  181151. /* The hIST chunk contains the relative frequency or importance of the
  181152. * various palette entries, so that a viewer can intelligently select a
  181153. * reduced-color palette, if required. Data is an array of "num_palette"
  181154. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  181155. * is non-zero.
  181156. */
  181157. png_uint_16p hist;
  181158. #endif
  181159. #ifdef PNG_cHRM_SUPPORTED
  181160. /* The cHRM chunk describes the CIE color characteristics of the monitor
  181161. * on which the PNG was created. This data allows the viewer to do gamut
  181162. * mapping of the input image to ensure that the viewer sees the same
  181163. * colors in the image as the creator. Values are in the range
  181164. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  181165. */
  181166. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181167. float x_white;
  181168. float y_white;
  181169. float x_red;
  181170. float y_red;
  181171. float x_green;
  181172. float y_green;
  181173. float x_blue;
  181174. float y_blue;
  181175. #endif
  181176. #endif
  181177. #if defined(PNG_pCAL_SUPPORTED)
  181178. /* The pCAL chunk describes a transformation between the stored pixel
  181179. * values and original physical data values used to create the image.
  181180. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  181181. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  181182. * (possibly non-linear) transformation function given by "pcal_type"
  181183. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  181184. * defines below, and the PNG-Group's PNG extensions document for a
  181185. * complete description of the transformations and how they should be
  181186. * implemented, and for a description of the ASCII parameter strings.
  181187. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  181188. */
  181189. png_charp pcal_purpose; /* pCAL chunk description string */
  181190. png_int_32 pcal_X0; /* minimum value */
  181191. png_int_32 pcal_X1; /* maximum value */
  181192. png_charp pcal_units; /* Latin-1 string giving physical units */
  181193. png_charpp pcal_params; /* ASCII strings containing parameter values */
  181194. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  181195. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  181196. #endif
  181197. /* New members added in libpng-1.0.6 */
  181198. #ifdef PNG_FREE_ME_SUPPORTED
  181199. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181200. #endif
  181201. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181202. /* storage for unknown chunks that the library doesn't recognize. */
  181203. png_unknown_chunkp unknown_chunks;
  181204. png_size_t unknown_chunks_num;
  181205. #endif
  181206. #if defined(PNG_iCCP_SUPPORTED)
  181207. /* iCCP chunk data. */
  181208. png_charp iccp_name; /* profile name */
  181209. png_charp iccp_profile; /* International Color Consortium profile data */
  181210. /* Note to maintainer: should be png_bytep */
  181211. png_uint_32 iccp_proflen; /* ICC profile data length */
  181212. png_byte iccp_compression; /* Always zero */
  181213. #endif
  181214. #if defined(PNG_sPLT_SUPPORTED)
  181215. /* data on sPLT chunks (there may be more than one). */
  181216. png_sPLT_tp splt_palettes;
  181217. png_uint_32 splt_palettes_num;
  181218. #endif
  181219. #if defined(PNG_sCAL_SUPPORTED)
  181220. /* The sCAL chunk describes the actual physical dimensions of the
  181221. * subject matter of the graphic. The chunk contains a unit specification
  181222. * a byte value, and two ASCII strings representing floating-point
  181223. * values. The values are width and height corresponsing to one pixel
  181224. * in the image. This external representation is converted to double
  181225. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  181226. */
  181227. png_byte scal_unit; /* unit of physical scale */
  181228. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181229. double scal_pixel_width; /* width of one pixel */
  181230. double scal_pixel_height; /* height of one pixel */
  181231. #endif
  181232. #ifdef PNG_FIXED_POINT_SUPPORTED
  181233. png_charp scal_s_width; /* string containing height */
  181234. png_charp scal_s_height; /* string containing width */
  181235. #endif
  181236. #endif
  181237. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181238. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  181239. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  181240. png_bytepp row_pointers; /* the image bits */
  181241. #endif
  181242. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  181243. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  181244. #endif
  181245. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  181246. png_fixed_point int_x_white;
  181247. png_fixed_point int_y_white;
  181248. png_fixed_point int_x_red;
  181249. png_fixed_point int_y_red;
  181250. png_fixed_point int_x_green;
  181251. png_fixed_point int_y_green;
  181252. png_fixed_point int_x_blue;
  181253. png_fixed_point int_y_blue;
  181254. #endif
  181255. } png_info;
  181256. typedef png_info FAR * png_infop;
  181257. typedef png_info FAR * FAR * png_infopp;
  181258. /* Maximum positive integer used in PNG is (2^31)-1 */
  181259. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  181260. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  181261. #define PNG_SIZE_MAX ((png_size_t)(-1))
  181262. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181263. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  181264. #define PNG_MAX_UINT PNG_UINT_31_MAX
  181265. #endif
  181266. /* These describe the color_type field in png_info. */
  181267. /* color type masks */
  181268. #define PNG_COLOR_MASK_PALETTE 1
  181269. #define PNG_COLOR_MASK_COLOR 2
  181270. #define PNG_COLOR_MASK_ALPHA 4
  181271. /* color types. Note that not all combinations are legal */
  181272. #define PNG_COLOR_TYPE_GRAY 0
  181273. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  181274. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  181275. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  181276. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  181277. /* aliases */
  181278. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  181279. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  181280. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  181281. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  181282. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  181283. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  181284. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  181285. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  181286. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  181287. /* These are for the interlacing type. These values should NOT be changed. */
  181288. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  181289. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  181290. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  181291. /* These are for the oFFs chunk. These values should NOT be changed. */
  181292. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  181293. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  181294. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  181295. /* These are for the pCAL chunk. These values should NOT be changed. */
  181296. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  181297. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  181298. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  181299. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  181300. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  181301. /* These are for the sCAL chunk. These values should NOT be changed. */
  181302. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  181303. #define PNG_SCALE_METER 1 /* meters per pixel */
  181304. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  181305. #define PNG_SCALE_LAST 3 /* Not a valid value */
  181306. /* These are for the pHYs chunk. These values should NOT be changed. */
  181307. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  181308. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  181309. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  181310. /* These are for the sRGB chunk. These values should NOT be changed. */
  181311. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  181312. #define PNG_sRGB_INTENT_RELATIVE 1
  181313. #define PNG_sRGB_INTENT_SATURATION 2
  181314. #define PNG_sRGB_INTENT_ABSOLUTE 3
  181315. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  181316. /* This is for text chunks */
  181317. #define PNG_KEYWORD_MAX_LENGTH 79
  181318. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  181319. #define PNG_MAX_PALETTE_LENGTH 256
  181320. /* These determine if an ancillary chunk's data has been successfully read
  181321. * from the PNG header, or if the application has filled in the corresponding
  181322. * data in the info_struct to be written into the output file. The values
  181323. * of the PNG_INFO_<chunk> defines should NOT be changed.
  181324. */
  181325. #define PNG_INFO_gAMA 0x0001
  181326. #define PNG_INFO_sBIT 0x0002
  181327. #define PNG_INFO_cHRM 0x0004
  181328. #define PNG_INFO_PLTE 0x0008
  181329. #define PNG_INFO_tRNS 0x0010
  181330. #define PNG_INFO_bKGD 0x0020
  181331. #define PNG_INFO_hIST 0x0040
  181332. #define PNG_INFO_pHYs 0x0080
  181333. #define PNG_INFO_oFFs 0x0100
  181334. #define PNG_INFO_tIME 0x0200
  181335. #define PNG_INFO_pCAL 0x0400
  181336. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  181337. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  181338. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  181339. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  181340. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  181341. /* This is used for the transformation routines, as some of them
  181342. * change these values for the row. It also should enable using
  181343. * the routines for other purposes.
  181344. */
  181345. typedef struct png_row_info_struct
  181346. {
  181347. png_uint_32 width; /* width of row */
  181348. png_uint_32 rowbytes; /* number of bytes in row */
  181349. png_byte color_type; /* color type of row */
  181350. png_byte bit_depth; /* bit depth of row */
  181351. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  181352. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  181353. } png_row_info;
  181354. typedef png_row_info FAR * png_row_infop;
  181355. typedef png_row_info FAR * FAR * png_row_infopp;
  181356. /* These are the function types for the I/O functions and for the functions
  181357. * that allow the user to override the default I/O functions with his or her
  181358. * own. The png_error_ptr type should match that of user-supplied warning
  181359. * and error functions, while the png_rw_ptr type should match that of the
  181360. * user read/write data functions.
  181361. */
  181362. typedef struct png_struct_def png_struct;
  181363. typedef png_struct FAR * png_structp;
  181364. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  181365. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  181366. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  181367. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  181368. int));
  181369. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  181370. int));
  181371. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181372. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  181373. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  181374. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  181375. png_uint_32, int));
  181376. #endif
  181377. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181378. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  181379. defined(PNG_LEGACY_SUPPORTED)
  181380. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  181381. png_row_infop, png_bytep));
  181382. #endif
  181383. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181384. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  181385. #endif
  181386. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181387. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  181388. #endif
  181389. /* Transform masks for the high-level interface */
  181390. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  181391. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  181392. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  181393. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  181394. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  181395. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  181396. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  181397. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  181398. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  181399. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  181400. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  181401. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  181402. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  181403. /* Flags for MNG supported features */
  181404. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  181405. #define PNG_FLAG_MNG_FILTER_64 0x04
  181406. #define PNG_ALL_MNG_FEATURES 0x05
  181407. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  181408. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  181409. /* The structure that holds the information to read and write PNG files.
  181410. * The only people who need to care about what is inside of this are the
  181411. * people who will be modifying the library for their own special needs.
  181412. * It should NOT be accessed directly by an application, except to store
  181413. * the jmp_buf.
  181414. */
  181415. struct png_struct_def
  181416. {
  181417. #ifdef PNG_SETJMP_SUPPORTED
  181418. jmp_buf jmpbuf; /* used in png_error */
  181419. #endif
  181420. png_error_ptr error_fn; /* function for printing errors and aborting */
  181421. png_error_ptr warning_fn; /* function for printing warnings */
  181422. png_voidp error_ptr; /* user supplied struct for error functions */
  181423. png_rw_ptr write_data_fn; /* function for writing output data */
  181424. png_rw_ptr read_data_fn; /* function for reading input data */
  181425. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  181426. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  181427. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  181428. #endif
  181429. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181430. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  181431. #endif
  181432. /* These were added in libpng-1.0.2 */
  181433. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  181434. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181435. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181436. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  181437. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  181438. png_byte user_transform_channels; /* channels in user transformed pixels */
  181439. #endif
  181440. #endif
  181441. png_uint_32 mode; /* tells us where we are in the PNG file */
  181442. png_uint_32 flags; /* flags indicating various things to libpng */
  181443. png_uint_32 transformations; /* which transformations to perform */
  181444. z_stream zstream; /* pointer to decompression structure (below) */
  181445. png_bytep zbuf; /* buffer for zlib */
  181446. png_size_t zbuf_size; /* size of zbuf */
  181447. int zlib_level; /* holds zlib compression level */
  181448. int zlib_method; /* holds zlib compression method */
  181449. int zlib_window_bits; /* holds zlib compression window bits */
  181450. int zlib_mem_level; /* holds zlib compression memory level */
  181451. int zlib_strategy; /* holds zlib compression strategy */
  181452. png_uint_32 width; /* width of image in pixels */
  181453. png_uint_32 height; /* height of image in pixels */
  181454. png_uint_32 num_rows; /* number of rows in current pass */
  181455. png_uint_32 usr_width; /* width of row at start of write */
  181456. png_uint_32 rowbytes; /* size of row in bytes */
  181457. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  181458. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  181459. png_uint_32 row_number; /* current row in interlace pass */
  181460. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  181461. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  181462. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  181463. png_bytep up_row; /* buffer to save "up" row when filtering */
  181464. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  181465. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  181466. png_row_info row_info; /* used for transformation routines */
  181467. png_uint_32 idat_size; /* current IDAT size for read */
  181468. png_uint_32 crc; /* current chunk CRC value */
  181469. png_colorp palette; /* palette from the input file */
  181470. png_uint_16 num_palette; /* number of color entries in palette */
  181471. png_uint_16 num_trans; /* number of transparency values */
  181472. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  181473. png_byte compression; /* file compression type (always 0) */
  181474. png_byte filter; /* file filter type (always 0) */
  181475. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181476. png_byte pass; /* current interlace pass (0 - 6) */
  181477. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  181478. png_byte color_type; /* color type of file */
  181479. png_byte bit_depth; /* bit depth of file */
  181480. png_byte usr_bit_depth; /* bit depth of users row */
  181481. png_byte pixel_depth; /* number of bits per pixel */
  181482. png_byte channels; /* number of channels in file */
  181483. png_byte usr_channels; /* channels at start of write */
  181484. png_byte sig_bytes; /* magic bytes read/written from start of file */
  181485. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  181486. #ifdef PNG_LEGACY_SUPPORTED
  181487. png_byte filler; /* filler byte for pixel expansion */
  181488. #else
  181489. png_uint_16 filler; /* filler bytes for pixel expansion */
  181490. #endif
  181491. #endif
  181492. #if defined(PNG_bKGD_SUPPORTED)
  181493. png_byte background_gamma_type;
  181494. # ifdef PNG_FLOATING_POINT_SUPPORTED
  181495. float background_gamma;
  181496. # endif
  181497. png_color_16 background; /* background color in screen gamma space */
  181498. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181499. png_color_16 background_1; /* background normalized to gamma 1.0 */
  181500. #endif
  181501. #endif /* PNG_bKGD_SUPPORTED */
  181502. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  181503. png_flush_ptr output_flush_fn;/* Function for flushing output */
  181504. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  181505. png_uint_32 flush_rows; /* number of rows written since last flush */
  181506. #endif
  181507. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181508. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  181509. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181510. float gamma; /* file gamma value */
  181511. float screen_gamma; /* screen gamma value (display_exponent) */
  181512. #endif
  181513. #endif
  181514. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181515. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  181516. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  181517. png_bytep gamma_to_1; /* converts from file to 1.0 */
  181518. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  181519. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  181520. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  181521. #endif
  181522. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  181523. png_color_8 sig_bit; /* significant bits in each available channel */
  181524. #endif
  181525. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  181526. png_color_8 shift; /* shift for significant bit tranformation */
  181527. #endif
  181528. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  181529. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181530. png_bytep trans; /* transparency values for paletted files */
  181531. png_color_16 trans_values; /* transparency values for non-paletted files */
  181532. #endif
  181533. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  181534. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  181535. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181536. png_progressive_info_ptr info_fn; /* called after header data fully read */
  181537. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  181538. png_progressive_end_ptr end_fn; /* called after image is complete */
  181539. png_bytep save_buffer_ptr; /* current location in save_buffer */
  181540. png_bytep save_buffer; /* buffer for previously read data */
  181541. png_bytep current_buffer_ptr; /* current location in current_buffer */
  181542. png_bytep current_buffer; /* buffer for recently used data */
  181543. png_uint_32 push_length; /* size of current input chunk */
  181544. png_uint_32 skip_length; /* bytes to skip in input data */
  181545. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  181546. png_size_t save_buffer_max; /* total size of save_buffer */
  181547. png_size_t buffer_size; /* total amount of available input data */
  181548. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  181549. int process_mode; /* what push library is currently doing */
  181550. int cur_palette; /* current push library palette index */
  181551. # if defined(PNG_TEXT_SUPPORTED)
  181552. png_size_t current_text_size; /* current size of text input data */
  181553. png_size_t current_text_left; /* how much text left to read in input */
  181554. png_charp current_text; /* current text chunk buffer */
  181555. png_charp current_text_ptr; /* current location in current_text */
  181556. # endif /* PNG_TEXT_SUPPORTED */
  181557. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181558. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  181559. /* for the Borland special 64K segment handler */
  181560. png_bytepp offset_table_ptr;
  181561. png_bytep offset_table;
  181562. png_uint_16 offset_table_number;
  181563. png_uint_16 offset_table_count;
  181564. png_uint_16 offset_table_count_free;
  181565. #endif
  181566. #if defined(PNG_READ_DITHER_SUPPORTED)
  181567. png_bytep palette_lookup; /* lookup table for dithering */
  181568. png_bytep dither_index; /* index translation for palette files */
  181569. #endif
  181570. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  181571. png_uint_16p hist; /* histogram */
  181572. #endif
  181573. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  181574. png_byte heuristic_method; /* heuristic for row filter selection */
  181575. png_byte num_prev_filters; /* number of weights for previous rows */
  181576. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  181577. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  181578. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  181579. png_uint_16p filter_costs; /* relative filter calculation cost */
  181580. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  181581. #endif
  181582. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  181583. png_charp time_buffer; /* String to hold RFC 1123 time text */
  181584. #endif
  181585. /* New members added in libpng-1.0.6 */
  181586. #ifdef PNG_FREE_ME_SUPPORTED
  181587. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181588. #endif
  181589. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181590. png_voidp user_chunk_ptr;
  181591. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  181592. #endif
  181593. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181594. int num_chunk_list;
  181595. png_bytep chunk_list;
  181596. #endif
  181597. /* New members added in libpng-1.0.3 */
  181598. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181599. png_byte rgb_to_gray_status;
  181600. /* These were changed from png_byte in libpng-1.0.6 */
  181601. png_uint_16 rgb_to_gray_red_coeff;
  181602. png_uint_16 rgb_to_gray_green_coeff;
  181603. png_uint_16 rgb_to_gray_blue_coeff;
  181604. #endif
  181605. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  181606. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  181607. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  181608. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  181609. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  181610. #ifdef PNG_1_0_X
  181611. png_byte mng_features_permitted;
  181612. #else
  181613. png_uint_32 mng_features_permitted;
  181614. #endif /* PNG_1_0_X */
  181615. #endif
  181616. /* New member added in libpng-1.0.7 */
  181617. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181618. png_fixed_point int_gamma;
  181619. #endif
  181620. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  181621. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  181622. png_byte filter_type;
  181623. #endif
  181624. #if defined(PNG_1_0_X)
  181625. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  181626. png_uint_32 row_buf_size;
  181627. #endif
  181628. /* New members added in libpng-1.2.0 */
  181629. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181630. # if !defined(PNG_1_0_X)
  181631. # if defined(PNG_MMX_CODE_SUPPORTED)
  181632. png_byte mmx_bitdepth_threshold;
  181633. png_uint_32 mmx_rowbytes_threshold;
  181634. # endif
  181635. png_uint_32 asm_flags;
  181636. # endif
  181637. #endif
  181638. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  181639. #ifdef PNG_USER_MEM_SUPPORTED
  181640. png_voidp mem_ptr; /* user supplied struct for mem functions */
  181641. png_malloc_ptr malloc_fn; /* function for allocating memory */
  181642. png_free_ptr free_fn; /* function for freeing memory */
  181643. #endif
  181644. /* New member added in libpng-1.0.13 and 1.2.0 */
  181645. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  181646. #if defined(PNG_READ_DITHER_SUPPORTED)
  181647. /* The following three members were added at version 1.0.14 and 1.2.4 */
  181648. png_bytep dither_sort; /* working sort array */
  181649. png_bytep index_to_palette; /* where the original index currently is */
  181650. /* in the palette */
  181651. png_bytep palette_to_index; /* which original index points to this */
  181652. /* palette color */
  181653. #endif
  181654. /* New members added in libpng-1.0.16 and 1.2.6 */
  181655. png_byte compression_type;
  181656. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181657. png_uint_32 user_width_max;
  181658. png_uint_32 user_height_max;
  181659. #endif
  181660. /* New member added in libpng-1.0.25 and 1.2.17 */
  181661. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181662. /* storage for unknown chunk that the library doesn't recognize. */
  181663. png_unknown_chunk unknown_chunk;
  181664. #endif
  181665. };
  181666. /* This triggers a compiler error in png.c, if png.c and png.h
  181667. * do not agree upon the version number.
  181668. */
  181669. typedef png_structp version_1_2_21;
  181670. typedef png_struct FAR * FAR * png_structpp;
  181671. /* Here are the function definitions most commonly used. This is not
  181672. * the place to find out how to use libpng. See libpng.txt for the
  181673. * full explanation, see example.c for the summary. This just provides
  181674. * a simple one line description of the use of each function.
  181675. */
  181676. /* Returns the version number of the library */
  181677. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  181678. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  181679. * Handling more than 8 bytes from the beginning of the file is an error.
  181680. */
  181681. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  181682. int num_bytes));
  181683. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  181684. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  181685. * signature, and non-zero otherwise. Having num_to_check == 0 or
  181686. * start > 7 will always fail (ie return non-zero).
  181687. */
  181688. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  181689. png_size_t num_to_check));
  181690. /* Simple signature checking function. This is the same as calling
  181691. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  181692. */
  181693. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  181694. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  181695. extern PNG_EXPORT(png_structp,png_create_read_struct)
  181696. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  181697. png_error_ptr error_fn, png_error_ptr warn_fn));
  181698. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  181699. extern PNG_EXPORT(png_structp,png_create_write_struct)
  181700. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  181701. png_error_ptr error_fn, png_error_ptr warn_fn));
  181702. #ifdef PNG_WRITE_SUPPORTED
  181703. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  181704. PNGARG((png_structp png_ptr));
  181705. #endif
  181706. #ifdef PNG_WRITE_SUPPORTED
  181707. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  181708. PNGARG((png_structp png_ptr, png_uint_32 size));
  181709. #endif
  181710. /* Reset the compression stream */
  181711. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  181712. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  181713. #ifdef PNG_USER_MEM_SUPPORTED
  181714. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  181715. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  181716. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  181717. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  181718. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  181719. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  181720. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  181721. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  181722. #endif
  181723. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  181724. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  181725. png_bytep chunk_name, png_bytep data, png_size_t length));
  181726. /* Write the start of a PNG chunk - length and chunk name. */
  181727. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  181728. png_bytep chunk_name, png_uint_32 length));
  181729. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  181730. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  181731. png_bytep data, png_size_t length));
  181732. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  181733. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  181734. /* Allocate and initialize the info structure */
  181735. extern PNG_EXPORT(png_infop,png_create_info_struct)
  181736. PNGARG((png_structp png_ptr));
  181737. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181738. /* Initialize the info structure (old interface - DEPRECATED) */
  181739. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  181740. #undef png_info_init
  181741. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  181742. png_sizeof(png_info));
  181743. #endif
  181744. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  181745. png_size_t png_info_struct_size));
  181746. /* Writes all the PNG information before the image. */
  181747. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  181748. png_infop info_ptr));
  181749. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  181750. png_infop info_ptr));
  181751. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181752. /* read the information before the actual image data. */
  181753. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  181754. png_infop info_ptr));
  181755. #endif
  181756. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  181757. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  181758. PNGARG((png_structp png_ptr, png_timep ptime));
  181759. #endif
  181760. #if !defined(_WIN32_WCE)
  181761. /* "time.h" functions are not supported on WindowsCE */
  181762. #if defined(PNG_WRITE_tIME_SUPPORTED)
  181763. /* convert from a struct tm to png_time */
  181764. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  181765. struct tm FAR * ttime));
  181766. /* convert from time_t to png_time. Uses gmtime() */
  181767. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  181768. time_t ttime));
  181769. #endif /* PNG_WRITE_tIME_SUPPORTED */
  181770. #endif /* _WIN32_WCE */
  181771. #if defined(PNG_READ_EXPAND_SUPPORTED)
  181772. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  181773. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  181774. #if !defined(PNG_1_0_X)
  181775. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  181776. png_ptr));
  181777. #endif
  181778. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  181779. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  181780. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181781. /* Deprecated */
  181782. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  181783. #endif
  181784. #endif
  181785. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  181786. /* Use blue, green, red order for pixels. */
  181787. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  181788. #endif
  181789. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  181790. /* Expand the grayscale to 24-bit RGB if necessary. */
  181791. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  181792. #endif
  181793. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181794. /* Reduce RGB to grayscale. */
  181795. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181796. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  181797. int error_action, double red, double green ));
  181798. #endif
  181799. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  181800. int error_action, png_fixed_point red, png_fixed_point green ));
  181801. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  181802. png_ptr));
  181803. #endif
  181804. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  181805. png_colorp palette));
  181806. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  181807. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  181808. #endif
  181809. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  181810. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  181811. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  181812. #endif
  181813. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  181814. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  181815. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  181816. #endif
  181817. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  181818. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  181819. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  181820. png_uint_32 filler, int flags));
  181821. /* The values of the PNG_FILLER_ defines should NOT be changed */
  181822. #define PNG_FILLER_BEFORE 0
  181823. #define PNG_FILLER_AFTER 1
  181824. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  181825. #if !defined(PNG_1_0_X)
  181826. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  181827. png_uint_32 filler, int flags));
  181828. #endif
  181829. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  181830. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  181831. /* Swap bytes in 16-bit depth files. */
  181832. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  181833. #endif
  181834. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  181835. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  181836. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  181837. #endif
  181838. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  181839. /* Swap packing order of pixels in bytes. */
  181840. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  181841. #endif
  181842. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  181843. /* Converts files to legal bit depths. */
  181844. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  181845. png_color_8p true_bits));
  181846. #endif
  181847. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  181848. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181849. /* Have the code handle the interlacing. Returns the number of passes. */
  181850. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  181851. #endif
  181852. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  181853. /* Invert monochrome files */
  181854. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  181855. #endif
  181856. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  181857. /* Handle alpha and tRNS by replacing with a background color. */
  181858. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181859. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  181860. png_color_16p background_color, int background_gamma_code,
  181861. int need_expand, double background_gamma));
  181862. #endif
  181863. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  181864. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  181865. #define PNG_BACKGROUND_GAMMA_FILE 2
  181866. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  181867. #endif
  181868. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  181869. /* strip the second byte of information from a 16-bit depth file. */
  181870. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  181871. #endif
  181872. #if defined(PNG_READ_DITHER_SUPPORTED)
  181873. /* Turn on dithering, and reduce the palette to the number of colors available. */
  181874. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  181875. png_colorp palette, int num_palette, int maximum_colors,
  181876. png_uint_16p histogram, int full_dither));
  181877. #endif
  181878. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181879. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  181880. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181881. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  181882. double screen_gamma, double default_file_gamma));
  181883. #endif
  181884. #endif
  181885. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181886. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  181887. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  181888. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  181889. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  181890. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  181891. int empty_plte_permitted));
  181892. #endif
  181893. #endif
  181894. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  181895. /* Set how many lines between output flushes - 0 for no flushing */
  181896. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  181897. /* Flush the current PNG output buffer */
  181898. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  181899. #endif
  181900. /* optional update palette with requested transformations */
  181901. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  181902. /* optional call to update the users info structure */
  181903. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  181904. png_infop info_ptr));
  181905. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181906. /* read one or more rows of image data. */
  181907. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  181908. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  181909. #endif
  181910. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181911. /* read a row of data. */
  181912. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  181913. png_bytep row,
  181914. png_bytep display_row));
  181915. #endif
  181916. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181917. /* read the whole image into memory at once. */
  181918. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  181919. png_bytepp image));
  181920. #endif
  181921. /* write a row of image data */
  181922. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  181923. png_bytep row));
  181924. /* write a few rows of image data */
  181925. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  181926. png_bytepp row, png_uint_32 num_rows));
  181927. /* write the image data */
  181928. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  181929. png_bytepp image));
  181930. /* writes the end of the PNG file. */
  181931. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  181932. png_infop info_ptr));
  181933. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181934. /* read the end of the PNG file. */
  181935. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  181936. png_infop info_ptr));
  181937. #endif
  181938. /* free any memory associated with the png_info_struct */
  181939. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  181940. png_infopp info_ptr_ptr));
  181941. /* free any memory associated with the png_struct and the png_info_structs */
  181942. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  181943. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  181944. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  181945. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  181946. png_infop end_info_ptr));
  181947. /* free any memory associated with the png_struct and the png_info_structs */
  181948. extern PNG_EXPORT(void,png_destroy_write_struct)
  181949. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  181950. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  181951. extern void png_write_destroy PNGARG((png_structp png_ptr));
  181952. /* set the libpng method of handling chunk CRC errors */
  181953. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  181954. int crit_action, int ancil_action));
  181955. /* Values for png_set_crc_action() to say how to handle CRC errors in
  181956. * ancillary and critical chunks, and whether to use the data contained
  181957. * therein. Note that it is impossible to "discard" data in a critical
  181958. * chunk. For versions prior to 0.90, the action was always error/quit,
  181959. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  181960. * chunks is warn/discard. These values should NOT be changed.
  181961. *
  181962. * value action:critical action:ancillary
  181963. */
  181964. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  181965. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  181966. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  181967. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  181968. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  181969. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  181970. /* These functions give the user control over the scan-line filtering in
  181971. * libpng and the compression methods used by zlib. These functions are
  181972. * mainly useful for testing, as the defaults should work with most users.
  181973. * Those users who are tight on memory or want faster performance at the
  181974. * expense of compression can modify them. See the compression library
  181975. * header file (zlib.h) for an explination of the compression functions.
  181976. */
  181977. /* set the filtering method(s) used by libpng. Currently, the only valid
  181978. * value for "method" is 0.
  181979. */
  181980. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  181981. int filters));
  181982. /* Flags for png_set_filter() to say which filters to use. The flags
  181983. * are chosen so that they don't conflict with real filter types
  181984. * below, in case they are supplied instead of the #defined constants.
  181985. * These values should NOT be changed.
  181986. */
  181987. #define PNG_NO_FILTERS 0x00
  181988. #define PNG_FILTER_NONE 0x08
  181989. #define PNG_FILTER_SUB 0x10
  181990. #define PNG_FILTER_UP 0x20
  181991. #define PNG_FILTER_AVG 0x40
  181992. #define PNG_FILTER_PAETH 0x80
  181993. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  181994. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  181995. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  181996. * These defines should NOT be changed.
  181997. */
  181998. #define PNG_FILTER_VALUE_NONE 0
  181999. #define PNG_FILTER_VALUE_SUB 1
  182000. #define PNG_FILTER_VALUE_UP 2
  182001. #define PNG_FILTER_VALUE_AVG 3
  182002. #define PNG_FILTER_VALUE_PAETH 4
  182003. #define PNG_FILTER_VALUE_LAST 5
  182004. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182005. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182006. * defines, either the default (minimum-sum-of-absolute-differences), or
  182007. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182008. *
  182009. * Weights are factors >= 1.0, indicating how important it is to keep the
  182010. * filter type consistent between rows. Larger numbers mean the current
  182011. * filter is that many times as likely to be the same as the "num_weights"
  182012. * previous filters. This is cumulative for each previous row with a weight.
  182013. * There needs to be "num_weights" values in "filter_weights", or it can be
  182014. * NULL if the weights aren't being specified. Weights have no influence on
  182015. * the selection of the first row filter. Well chosen weights can (in theory)
  182016. * improve the compression for a given image.
  182017. *
  182018. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182019. * filter type. Higher costs indicate more decoding expense, and are
  182020. * therefore less likely to be selected over a filter with lower computational
  182021. * costs. There needs to be a value in "filter_costs" for each valid filter
  182022. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182023. * setting the costs. Costs try to improve the speed of decompression without
  182024. * unduly increasing the compressed image size.
  182025. *
  182026. * A negative weight or cost indicates the default value is to be used, and
  182027. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182028. * The default values for both weights and costs are currently 1.0, but may
  182029. * change if good general weighting/cost heuristics can be found. If both
  182030. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182031. * to the UNWEIGHTED method, but with added encoding time/computation.
  182032. */
  182033. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182034. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182035. int heuristic_method, int num_weights, png_doublep filter_weights,
  182036. png_doublep filter_costs));
  182037. #endif
  182038. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182039. /* Heuristic used for row filter selection. These defines should NOT be
  182040. * changed.
  182041. */
  182042. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182043. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182044. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182045. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182046. /* Set the library compression level. Currently, valid values range from
  182047. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182048. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182049. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182050. * for PNG images, and do considerably fewer caclulations. In the future,
  182051. * these values may not correspond directly to the zlib compression levels.
  182052. */
  182053. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182054. int level));
  182055. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182056. PNGARG((png_structp png_ptr, int mem_level));
  182057. extern PNG_EXPORT(void,png_set_compression_strategy)
  182058. PNGARG((png_structp png_ptr, int strategy));
  182059. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182060. PNGARG((png_structp png_ptr, int window_bits));
  182061. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182062. int method));
  182063. /* These next functions are called for input/output, memory, and error
  182064. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182065. * and call standard C I/O routines such as fread(), fwrite(), and
  182066. * fprintf(). These functions can be made to use other I/O routines
  182067. * at run time for those applications that need to handle I/O in a
  182068. * different manner by calling png_set_???_fn(). See libpng.txt for
  182069. * more information.
  182070. */
  182071. #if !defined(PNG_NO_STDIO)
  182072. /* Initialize the input/output for the PNG file to the default functions. */
  182073. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182074. #endif
  182075. /* Replace the (error and abort), and warning functions with user
  182076. * supplied functions. If no messages are to be printed you must still
  182077. * write and use replacement functions. The replacement error_fn should
  182078. * still do a longjmp to the last setjmp location if you are using this
  182079. * method of error handling. If error_fn or warning_fn is NULL, the
  182080. * default function will be used.
  182081. */
  182082. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182083. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182084. /* Return the user pointer associated with the error functions */
  182085. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182086. /* Replace the default data output functions with a user supplied one(s).
  182087. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182088. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182089. * output_flush_fn will be ignored (and thus can be NULL).
  182090. */
  182091. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182092. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182093. /* Replace the default data input function with a user supplied one. */
  182094. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182095. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182096. /* Return the user pointer associated with the I/O functions */
  182097. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182098. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182099. png_read_status_ptr read_row_fn));
  182100. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182101. png_write_status_ptr write_row_fn));
  182102. #ifdef PNG_USER_MEM_SUPPORTED
  182103. /* Replace the default memory allocation functions with user supplied one(s). */
  182104. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182105. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182106. /* Return the user pointer associated with the memory functions */
  182107. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182108. #endif
  182109. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182110. defined(PNG_LEGACY_SUPPORTED)
  182111. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182112. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182113. #endif
  182114. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182115. defined(PNG_LEGACY_SUPPORTED)
  182116. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182117. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182118. #endif
  182119. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182120. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182121. defined(PNG_LEGACY_SUPPORTED)
  182122. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182123. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182124. int user_transform_channels));
  182125. /* Return the user pointer associated with the user transform functions */
  182126. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  182127. PNGARG((png_structp png_ptr));
  182128. #endif
  182129. #ifdef PNG_USER_CHUNKS_SUPPORTED
  182130. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  182131. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  182132. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  182133. png_ptr));
  182134. #endif
  182135. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182136. /* Sets the function callbacks for the push reader, and a pointer to a
  182137. * user-defined structure available to the callback functions.
  182138. */
  182139. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  182140. png_voidp progressive_ptr,
  182141. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  182142. png_progressive_end_ptr end_fn));
  182143. /* returns the user pointer associated with the push read functions */
  182144. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  182145. PNGARG((png_structp png_ptr));
  182146. /* function to be called when data becomes available */
  182147. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  182148. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  182149. /* function that combines rows. Not very much different than the
  182150. * png_combine_row() call. Is this even used?????
  182151. */
  182152. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  182153. png_bytep old_row, png_bytep new_row));
  182154. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182155. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  182156. png_uint_32 size));
  182157. #if defined(PNG_1_0_X)
  182158. # define png_malloc_warn png_malloc
  182159. #else
  182160. /* Added at libpng version 1.2.4 */
  182161. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  182162. png_uint_32 size));
  182163. #endif
  182164. /* frees a pointer allocated by png_malloc() */
  182165. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  182166. #if defined(PNG_1_0_X)
  182167. /* Function to allocate memory for zlib. */
  182168. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  182169. uInt size));
  182170. /* Function to free memory for zlib */
  182171. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  182172. #endif
  182173. /* Free data that was allocated internally */
  182174. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  182175. png_infop info_ptr, png_uint_32 free_me, int num));
  182176. #ifdef PNG_FREE_ME_SUPPORTED
  182177. /* Reassign responsibility for freeing existing data, whether allocated
  182178. * by libpng or by the application */
  182179. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  182180. png_infop info_ptr, int freer, png_uint_32 mask));
  182181. #endif
  182182. /* assignments for png_data_freer */
  182183. #define PNG_DESTROY_WILL_FREE_DATA 1
  182184. #define PNG_SET_WILL_FREE_DATA 1
  182185. #define PNG_USER_WILL_FREE_DATA 2
  182186. /* Flags for png_ptr->free_me and info_ptr->free_me */
  182187. #define PNG_FREE_HIST 0x0008
  182188. #define PNG_FREE_ICCP 0x0010
  182189. #define PNG_FREE_SPLT 0x0020
  182190. #define PNG_FREE_ROWS 0x0040
  182191. #define PNG_FREE_PCAL 0x0080
  182192. #define PNG_FREE_SCAL 0x0100
  182193. #define PNG_FREE_UNKN 0x0200
  182194. #define PNG_FREE_LIST 0x0400
  182195. #define PNG_FREE_PLTE 0x1000
  182196. #define PNG_FREE_TRNS 0x2000
  182197. #define PNG_FREE_TEXT 0x4000
  182198. #define PNG_FREE_ALL 0x7fff
  182199. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  182200. #ifdef PNG_USER_MEM_SUPPORTED
  182201. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  182202. png_uint_32 size));
  182203. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  182204. png_voidp ptr));
  182205. #endif
  182206. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  182207. png_voidp s1, png_voidp s2, png_uint_32 size));
  182208. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  182209. png_voidp s1, int value, png_uint_32 size));
  182210. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  182211. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  182212. int check));
  182213. #endif /* USE_FAR_KEYWORD */
  182214. #ifndef PNG_NO_ERROR_TEXT
  182215. /* Fatal error in PNG image of libpng - can't continue */
  182216. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  182217. png_const_charp error_message));
  182218. /* The same, but the chunk name is prepended to the error string. */
  182219. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  182220. png_const_charp error_message));
  182221. #else
  182222. /* Fatal error in PNG image of libpng - can't continue */
  182223. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  182224. #endif
  182225. #ifndef PNG_NO_WARNINGS
  182226. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  182227. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  182228. png_const_charp warning_message));
  182229. #ifdef PNG_READ_SUPPORTED
  182230. /* Non-fatal error in libpng, chunk name is prepended to message. */
  182231. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  182232. png_const_charp warning_message));
  182233. #endif /* PNG_READ_SUPPORTED */
  182234. #endif /* PNG_NO_WARNINGS */
  182235. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  182236. * Similarly, the png_get_<chunk> calls are used to read values from the
  182237. * png_info_struct, either storing the parameters in the passed variables, or
  182238. * setting pointers into the png_info_struct where the data is stored. The
  182239. * png_get_<chunk> functions return a non-zero value if the data was available
  182240. * in info_ptr, or return zero and do not change any of the parameters if the
  182241. * data was not available.
  182242. *
  182243. * These functions should be used instead of directly accessing png_info
  182244. * to avoid problems with future changes in the size and internal layout of
  182245. * png_info_struct.
  182246. */
  182247. /* Returns "flag" if chunk data is valid in info_ptr. */
  182248. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  182249. png_infop info_ptr, png_uint_32 flag));
  182250. /* Returns number of bytes needed to hold a transformed row. */
  182251. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  182252. png_infop info_ptr));
  182253. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182254. /* Returns row_pointers, which is an array of pointers to scanlines that was
  182255. returned from png_read_png(). */
  182256. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  182257. png_infop info_ptr));
  182258. /* Set row_pointers, which is an array of pointers to scanlines for use
  182259. by png_write_png(). */
  182260. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  182261. png_infop info_ptr, png_bytepp row_pointers));
  182262. #endif
  182263. /* Returns number of color channels in image. */
  182264. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  182265. png_infop info_ptr));
  182266. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182267. /* Returns image width in pixels. */
  182268. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  182269. png_ptr, png_infop info_ptr));
  182270. /* Returns image height in pixels. */
  182271. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  182272. png_ptr, png_infop info_ptr));
  182273. /* Returns image bit_depth. */
  182274. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  182275. png_ptr, png_infop info_ptr));
  182276. /* Returns image color_type. */
  182277. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  182278. png_ptr, png_infop info_ptr));
  182279. /* Returns image filter_type. */
  182280. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  182281. png_ptr, png_infop info_ptr));
  182282. /* Returns image interlace_type. */
  182283. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  182284. png_ptr, png_infop info_ptr));
  182285. /* Returns image compression_type. */
  182286. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  182287. png_ptr, png_infop info_ptr));
  182288. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  182289. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  182290. png_ptr, png_infop info_ptr));
  182291. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  182292. png_ptr, png_infop info_ptr));
  182293. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  182294. png_ptr, png_infop info_ptr));
  182295. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  182296. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182297. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  182298. png_ptr, png_infop info_ptr));
  182299. #endif
  182300. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  182301. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  182302. png_ptr, png_infop info_ptr));
  182303. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  182304. png_ptr, png_infop info_ptr));
  182305. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  182306. png_ptr, png_infop info_ptr));
  182307. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  182308. png_ptr, png_infop info_ptr));
  182309. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182310. /* Returns pointer to signature string read from PNG header */
  182311. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  182312. png_infop info_ptr));
  182313. #if defined(PNG_bKGD_SUPPORTED)
  182314. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  182315. png_infop info_ptr, png_color_16p *background));
  182316. #endif
  182317. #if defined(PNG_bKGD_SUPPORTED)
  182318. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  182319. png_infop info_ptr, png_color_16p background));
  182320. #endif
  182321. #if defined(PNG_cHRM_SUPPORTED)
  182322. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182323. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  182324. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  182325. double *red_y, double *green_x, double *green_y, double *blue_x,
  182326. double *blue_y));
  182327. #endif
  182328. #ifdef PNG_FIXED_POINT_SUPPORTED
  182329. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  182330. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  182331. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  182332. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  182333. *int_blue_x, png_fixed_point *int_blue_y));
  182334. #endif
  182335. #endif
  182336. #if defined(PNG_cHRM_SUPPORTED)
  182337. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182338. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  182339. png_infop info_ptr, double white_x, double white_y, double red_x,
  182340. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  182341. #endif
  182342. #ifdef PNG_FIXED_POINT_SUPPORTED
  182343. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  182344. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  182345. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  182346. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  182347. png_fixed_point int_blue_y));
  182348. #endif
  182349. #endif
  182350. #if defined(PNG_gAMA_SUPPORTED)
  182351. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182352. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  182353. png_infop info_ptr, double *file_gamma));
  182354. #endif
  182355. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  182356. png_infop info_ptr, png_fixed_point *int_file_gamma));
  182357. #endif
  182358. #if defined(PNG_gAMA_SUPPORTED)
  182359. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182360. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  182361. png_infop info_ptr, double file_gamma));
  182362. #endif
  182363. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  182364. png_infop info_ptr, png_fixed_point int_file_gamma));
  182365. #endif
  182366. #if defined(PNG_hIST_SUPPORTED)
  182367. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  182368. png_infop info_ptr, png_uint_16p *hist));
  182369. #endif
  182370. #if defined(PNG_hIST_SUPPORTED)
  182371. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  182372. png_infop info_ptr, png_uint_16p hist));
  182373. #endif
  182374. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  182375. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  182376. int *bit_depth, int *color_type, int *interlace_method,
  182377. int *compression_method, int *filter_method));
  182378. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  182379. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  182380. int color_type, int interlace_method, int compression_method,
  182381. int filter_method));
  182382. #if defined(PNG_oFFs_SUPPORTED)
  182383. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  182384. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  182385. int *unit_type));
  182386. #endif
  182387. #if defined(PNG_oFFs_SUPPORTED)
  182388. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  182389. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  182390. int unit_type));
  182391. #endif
  182392. #if defined(PNG_pCAL_SUPPORTED)
  182393. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  182394. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  182395. int *type, int *nparams, png_charp *units, png_charpp *params));
  182396. #endif
  182397. #if defined(PNG_pCAL_SUPPORTED)
  182398. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  182399. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  182400. int type, int nparams, png_charp units, png_charpp params));
  182401. #endif
  182402. #if defined(PNG_pHYs_SUPPORTED)
  182403. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  182404. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  182405. #endif
  182406. #if defined(PNG_pHYs_SUPPORTED)
  182407. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  182408. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  182409. #endif
  182410. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  182411. png_infop info_ptr, png_colorp *palette, int *num_palette));
  182412. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  182413. png_infop info_ptr, png_colorp palette, int num_palette));
  182414. #if defined(PNG_sBIT_SUPPORTED)
  182415. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  182416. png_infop info_ptr, png_color_8p *sig_bit));
  182417. #endif
  182418. #if defined(PNG_sBIT_SUPPORTED)
  182419. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  182420. png_infop info_ptr, png_color_8p sig_bit));
  182421. #endif
  182422. #if defined(PNG_sRGB_SUPPORTED)
  182423. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  182424. png_infop info_ptr, int *intent));
  182425. #endif
  182426. #if defined(PNG_sRGB_SUPPORTED)
  182427. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  182428. png_infop info_ptr, int intent));
  182429. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  182430. png_infop info_ptr, int intent));
  182431. #endif
  182432. #if defined(PNG_iCCP_SUPPORTED)
  182433. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  182434. png_infop info_ptr, png_charpp name, int *compression_type,
  182435. png_charpp profile, png_uint_32 *proflen));
  182436. /* Note to maintainer: profile should be png_bytepp */
  182437. #endif
  182438. #if defined(PNG_iCCP_SUPPORTED)
  182439. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  182440. png_infop info_ptr, png_charp name, int compression_type,
  182441. png_charp profile, png_uint_32 proflen));
  182442. /* Note to maintainer: profile should be png_bytep */
  182443. #endif
  182444. #if defined(PNG_sPLT_SUPPORTED)
  182445. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  182446. png_infop info_ptr, png_sPLT_tpp entries));
  182447. #endif
  182448. #if defined(PNG_sPLT_SUPPORTED)
  182449. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  182450. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  182451. #endif
  182452. #if defined(PNG_TEXT_SUPPORTED)
  182453. /* png_get_text also returns the number of text chunks in *num_text */
  182454. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  182455. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  182456. #endif
  182457. /*
  182458. * Note while png_set_text() will accept a structure whose text,
  182459. * language, and translated keywords are NULL pointers, the structure
  182460. * returned by png_get_text will always contain regular
  182461. * zero-terminated C strings. They might be empty strings but
  182462. * they will never be NULL pointers.
  182463. */
  182464. #if defined(PNG_TEXT_SUPPORTED)
  182465. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  182466. png_infop info_ptr, png_textp text_ptr, int num_text));
  182467. #endif
  182468. #if defined(PNG_tIME_SUPPORTED)
  182469. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  182470. png_infop info_ptr, png_timep *mod_time));
  182471. #endif
  182472. #if defined(PNG_tIME_SUPPORTED)
  182473. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  182474. png_infop info_ptr, png_timep mod_time));
  182475. #endif
  182476. #if defined(PNG_tRNS_SUPPORTED)
  182477. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  182478. png_infop info_ptr, png_bytep *trans, int *num_trans,
  182479. png_color_16p *trans_values));
  182480. #endif
  182481. #if defined(PNG_tRNS_SUPPORTED)
  182482. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  182483. png_infop info_ptr, png_bytep trans, int num_trans,
  182484. png_color_16p trans_values));
  182485. #endif
  182486. #if defined(PNG_tRNS_SUPPORTED)
  182487. #endif
  182488. #if defined(PNG_sCAL_SUPPORTED)
  182489. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182490. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  182491. png_infop info_ptr, int *unit, double *width, double *height));
  182492. #else
  182493. #ifdef PNG_FIXED_POINT_SUPPORTED
  182494. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  182495. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  182496. #endif
  182497. #endif
  182498. #endif /* PNG_sCAL_SUPPORTED */
  182499. #if defined(PNG_sCAL_SUPPORTED)
  182500. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182501. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  182502. png_infop info_ptr, int unit, double width, double height));
  182503. #else
  182504. #ifdef PNG_FIXED_POINT_SUPPORTED
  182505. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  182506. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  182507. #endif
  182508. #endif
  182509. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  182510. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182511. /* provide a list of chunks and how they are to be handled, if the built-in
  182512. handling or default unknown chunk handling is not desired. Any chunks not
  182513. listed will be handled in the default manner. The IHDR and IEND chunks
  182514. must not be listed.
  182515. keep = 0: follow default behaviour
  182516. = 1: do not keep
  182517. = 2: keep only if safe-to-copy
  182518. = 3: keep even if unsafe-to-copy
  182519. */
  182520. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  182521. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  182522. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  182523. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  182524. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  182525. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  182526. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  182527. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  182528. #endif
  182529. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182530. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  182531. chunk_name));
  182532. #endif
  182533. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  182534. If you need to turn it off for a chunk that your application has freed,
  182535. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  182536. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  182537. png_infop info_ptr, int mask));
  182538. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182539. /* The "params" pointer is currently not used and is for future expansion. */
  182540. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  182541. png_infop info_ptr,
  182542. int transforms,
  182543. png_voidp params));
  182544. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  182545. png_infop info_ptr,
  182546. int transforms,
  182547. png_voidp params));
  182548. #endif
  182549. /* Define PNG_DEBUG at compile time for debugging information. Higher
  182550. * numbers for PNG_DEBUG mean more debugging information. This has
  182551. * only been added since version 0.95 so it is not implemented throughout
  182552. * libpng yet, but more support will be added as needed.
  182553. */
  182554. #ifdef PNG_DEBUG
  182555. #if (PNG_DEBUG > 0)
  182556. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  182557. #include <crtdbg.h>
  182558. #if (PNG_DEBUG > 1)
  182559. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  182560. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  182561. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  182562. #endif
  182563. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  182564. #ifndef PNG_DEBUG_FILE
  182565. #define PNG_DEBUG_FILE stderr
  182566. #endif /* PNG_DEBUG_FILE */
  182567. #if (PNG_DEBUG > 1)
  182568. #define png_debug(l,m) \
  182569. { \
  182570. int num_tabs=l; \
  182571. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182572. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  182573. }
  182574. #define png_debug1(l,m,p1) \
  182575. { \
  182576. int num_tabs=l; \
  182577. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182578. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  182579. }
  182580. #define png_debug2(l,m,p1,p2) \
  182581. { \
  182582. int num_tabs=l; \
  182583. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182584. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  182585. }
  182586. #endif /* (PNG_DEBUG > 1) */
  182587. #endif /* _MSC_VER */
  182588. #endif /* (PNG_DEBUG > 0) */
  182589. #endif /* PNG_DEBUG */
  182590. #ifndef png_debug
  182591. #define png_debug(l, m)
  182592. #endif
  182593. #ifndef png_debug1
  182594. #define png_debug1(l, m, p1)
  182595. #endif
  182596. #ifndef png_debug2
  182597. #define png_debug2(l, m, p1, p2)
  182598. #endif
  182599. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  182600. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  182601. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  182602. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  182603. #ifdef PNG_MNG_FEATURES_SUPPORTED
  182604. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  182605. png_ptr, png_uint_32 mng_features_permitted));
  182606. #endif
  182607. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  182608. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  182609. #define PNG_HANDLE_CHUNK_NEVER 1
  182610. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  182611. #define PNG_HANDLE_CHUNK_ALWAYS 3
  182612. /* Added to version 1.2.0 */
  182613. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182614. #if defined(PNG_MMX_CODE_SUPPORTED)
  182615. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  182616. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  182617. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  182618. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  182619. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  182620. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  182621. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  182622. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  182623. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  182624. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  182625. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  182626. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  182627. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  182628. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  182629. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  182630. #define PNG_MMX_WRITE_FLAGS ( 0 )
  182631. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  182632. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  182633. | PNG_MMX_READ_FLAGS \
  182634. | PNG_MMX_WRITE_FLAGS )
  182635. #define PNG_SELECT_READ 1
  182636. #define PNG_SELECT_WRITE 2
  182637. #endif /* PNG_MMX_CODE_SUPPORTED */
  182638. #if !defined(PNG_1_0_X)
  182639. /* pngget.c */
  182640. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  182641. PNGARG((int flag_select, int *compilerID));
  182642. /* pngget.c */
  182643. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  182644. PNGARG((int flag_select));
  182645. /* pngget.c */
  182646. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  182647. PNGARG((png_structp png_ptr));
  182648. /* pngget.c */
  182649. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  182650. PNGARG((png_structp png_ptr));
  182651. /* pngget.c */
  182652. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  182653. PNGARG((png_structp png_ptr));
  182654. /* pngset.c */
  182655. extern PNG_EXPORT(void,png_set_asm_flags)
  182656. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  182657. /* pngset.c */
  182658. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  182659. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  182660. png_uint_32 mmx_rowbytes_threshold));
  182661. #endif /* PNG_1_0_X */
  182662. #if !defined(PNG_1_0_X)
  182663. /* png.c, pnggccrd.c, or pngvcrd.c */
  182664. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  182665. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  182666. /* Strip the prepended error numbers ("#nnn ") from error and warning
  182667. * messages before passing them to the error or warning handler. */
  182668. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182669. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  182670. png_ptr, png_uint_32 strip_mode));
  182671. #endif
  182672. #endif /* PNG_1_0_X */
  182673. /* Added at libpng-1.2.6 */
  182674. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182675. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  182676. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  182677. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  182678. png_ptr));
  182679. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  182680. png_ptr));
  182681. #endif
  182682. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  182683. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  182684. /* With these routines we avoid an integer divide, which will be slower on
  182685. * most machines. However, it does take more operations than the corresponding
  182686. * divide method, so it may be slower on a few RISC systems. There are two
  182687. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  182688. *
  182689. * Note that the rounding factors are NOT supposed to be the same! 128 and
  182690. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  182691. * standard method.
  182692. *
  182693. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  182694. */
  182695. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  182696. # define png_composite(composite, fg, alpha, bg) \
  182697. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  182698. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  182699. (png_uint_16)(alpha)) + (png_uint_16)128); \
  182700. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  182701. # define png_composite_16(composite, fg, alpha, bg) \
  182702. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  182703. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  182704. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  182705. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  182706. #else /* standard method using integer division */
  182707. # define png_composite(composite, fg, alpha, bg) \
  182708. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  182709. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  182710. (png_uint_16)127) / 255)
  182711. # define png_composite_16(composite, fg, alpha, bg) \
  182712. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  182713. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  182714. (png_uint_32)32767) / (png_uint_32)65535L)
  182715. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  182716. /* Inline macros to do direct reads of bytes from the input buffer. These
  182717. * require that you are using an architecture that uses PNG byte ordering
  182718. * (MSB first) and supports unaligned data storage. I think that PowerPC
  182719. * in big-endian mode and 680x0 are the only ones that will support this.
  182720. * The x86 line of processors definitely do not. The png_get_int_32()
  182721. * routine also assumes we are using two's complement format for negative
  182722. * values, which is almost certainly true.
  182723. */
  182724. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  182725. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  182726. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  182727. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  182728. #else
  182729. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  182730. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  182731. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  182732. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  182733. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  182734. PNGARG((png_structp png_ptr, png_bytep buf));
  182735. /* No png_get_int_16 -- may be added if there's a real need for it. */
  182736. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  182737. */
  182738. extern PNG_EXPORT(void,png_save_uint_32)
  182739. PNGARG((png_bytep buf, png_uint_32 i));
  182740. extern PNG_EXPORT(void,png_save_int_32)
  182741. PNGARG((png_bytep buf, png_int_32 i));
  182742. /* Place a 16-bit number into a buffer in PNG byte order.
  182743. * The parameter is declared unsigned int, not png_uint_16,
  182744. * just to avoid potential problems on pre-ANSI C compilers.
  182745. */
  182746. extern PNG_EXPORT(void,png_save_uint_16)
  182747. PNGARG((png_bytep buf, unsigned int i));
  182748. /* No png_save_int_16 -- may be added if there's a real need for it. */
  182749. /* ************************************************************************* */
  182750. /* These next functions are used internally in the code. They generally
  182751. * shouldn't be used unless you are writing code to add or replace some
  182752. * functionality in libpng. More information about most functions can
  182753. * be found in the files where the functions are located.
  182754. */
  182755. /* Various modes of operation, that are visible to applications because
  182756. * they are used for unknown chunk location.
  182757. */
  182758. #define PNG_HAVE_IHDR 0x01
  182759. #define PNG_HAVE_PLTE 0x02
  182760. #define PNG_HAVE_IDAT 0x04
  182761. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  182762. #define PNG_HAVE_IEND 0x10
  182763. #if defined(PNG_INTERNAL)
  182764. /* More modes of operation. Note that after an init, mode is set to
  182765. * zero automatically when the structure is created.
  182766. */
  182767. #define PNG_HAVE_gAMA 0x20
  182768. #define PNG_HAVE_cHRM 0x40
  182769. #define PNG_HAVE_sRGB 0x80
  182770. #define PNG_HAVE_CHUNK_HEADER 0x100
  182771. #define PNG_WROTE_tIME 0x200
  182772. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  182773. #define PNG_BACKGROUND_IS_GRAY 0x800
  182774. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  182775. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  182776. /* flags for the transformations the PNG library does on the image data */
  182777. #define PNG_BGR 0x0001
  182778. #define PNG_INTERLACE 0x0002
  182779. #define PNG_PACK 0x0004
  182780. #define PNG_SHIFT 0x0008
  182781. #define PNG_SWAP_BYTES 0x0010
  182782. #define PNG_INVERT_MONO 0x0020
  182783. #define PNG_DITHER 0x0040
  182784. #define PNG_BACKGROUND 0x0080
  182785. #define PNG_BACKGROUND_EXPAND 0x0100
  182786. /* 0x0200 unused */
  182787. #define PNG_16_TO_8 0x0400
  182788. #define PNG_RGBA 0x0800
  182789. #define PNG_EXPAND 0x1000
  182790. #define PNG_GAMMA 0x2000
  182791. #define PNG_GRAY_TO_RGB 0x4000
  182792. #define PNG_FILLER 0x8000L
  182793. #define PNG_PACKSWAP 0x10000L
  182794. #define PNG_SWAP_ALPHA 0x20000L
  182795. #define PNG_STRIP_ALPHA 0x40000L
  182796. #define PNG_INVERT_ALPHA 0x80000L
  182797. #define PNG_USER_TRANSFORM 0x100000L
  182798. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  182799. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  182800. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  182801. /* 0x800000L Unused */
  182802. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  182803. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  182804. /* 0x4000000L unused */
  182805. /* 0x8000000L unused */
  182806. /* 0x10000000L unused */
  182807. /* 0x20000000L unused */
  182808. /* 0x40000000L unused */
  182809. /* flags for png_create_struct */
  182810. #define PNG_STRUCT_PNG 0x0001
  182811. #define PNG_STRUCT_INFO 0x0002
  182812. /* Scaling factor for filter heuristic weighting calculations */
  182813. #define PNG_WEIGHT_SHIFT 8
  182814. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  182815. #define PNG_COST_SHIFT 3
  182816. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  182817. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  182818. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  182819. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  182820. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  182821. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  182822. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  182823. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  182824. #define PNG_FLAG_ROW_INIT 0x0040
  182825. #define PNG_FLAG_FILLER_AFTER 0x0080
  182826. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  182827. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  182828. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  182829. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  182830. #define PNG_FLAG_FREE_PLTE 0x1000
  182831. #define PNG_FLAG_FREE_TRNS 0x2000
  182832. #define PNG_FLAG_FREE_HIST 0x4000
  182833. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  182834. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  182835. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  182836. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  182837. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  182838. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  182839. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  182840. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  182841. /* 0x800000L unused */
  182842. /* 0x1000000L unused */
  182843. /* 0x2000000L unused */
  182844. /* 0x4000000L unused */
  182845. /* 0x8000000L unused */
  182846. /* 0x10000000L unused */
  182847. /* 0x20000000L unused */
  182848. /* 0x40000000L unused */
  182849. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  182850. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  182851. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  182852. PNG_FLAG_CRC_CRITICAL_IGNORE)
  182853. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  182854. PNG_FLAG_CRC_CRITICAL_MASK)
  182855. /* save typing and make code easier to understand */
  182856. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  182857. abs((int)((c1).green) - (int)((c2).green)) + \
  182858. abs((int)((c1).blue) - (int)((c2).blue)))
  182859. /* Added to libpng-1.2.6 JB */
  182860. #define PNG_ROWBYTES(pixel_bits, width) \
  182861. ((pixel_bits) >= 8 ? \
  182862. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  182863. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  182864. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  182865. ideal-delta..ideal+delta. Each argument is evaluated twice.
  182866. "ideal" and "delta" should be constants, normally simple
  182867. integers, "value" a variable. Added to libpng-1.2.6 JB */
  182868. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  182869. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  182870. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182871. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182872. /* place to hold the signature string for a PNG file. */
  182873. #ifdef PNG_USE_GLOBAL_ARRAYS
  182874. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  182875. #else
  182876. #endif
  182877. #endif /* PNG_NO_EXTERN */
  182878. /* Constant strings for known chunk types. If you need to add a chunk,
  182879. * define the name here, and add an invocation of the macro in png.c and
  182880. * wherever it's needed.
  182881. */
  182882. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  182883. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  182884. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  182885. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  182886. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  182887. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  182888. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  182889. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  182890. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  182891. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  182892. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  182893. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  182894. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  182895. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  182896. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  182897. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  182898. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  182899. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  182900. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  182901. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  182902. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  182903. #ifdef PNG_USE_GLOBAL_ARRAYS
  182904. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  182905. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  182906. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  182907. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  182908. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  182909. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  182910. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  182911. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  182912. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  182913. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  182914. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  182915. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  182916. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  182917. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  182918. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  182919. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  182920. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  182921. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  182922. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  182923. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  182924. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  182925. #endif /* PNG_USE_GLOBAL_ARRAYS */
  182926. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182927. /* Initialize png_ptr struct for reading, and allocate any other memory.
  182928. * (old interface - DEPRECATED - use png_create_read_struct instead).
  182929. */
  182930. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  182931. #undef png_read_init
  182932. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  182933. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  182934. #endif
  182935. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  182936. png_const_charp user_png_ver, png_size_t png_struct_size));
  182937. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182938. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  182939. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  182940. png_info_size));
  182941. #endif
  182942. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182943. /* Initialize png_ptr struct for writing, and allocate any other memory.
  182944. * (old interface - DEPRECATED - use png_create_write_struct instead).
  182945. */
  182946. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  182947. #undef png_write_init
  182948. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  182949. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  182950. #endif
  182951. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  182952. png_const_charp user_png_ver, png_size_t png_struct_size));
  182953. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  182954. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  182955. png_info_size));
  182956. /* Allocate memory for an internal libpng struct */
  182957. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  182958. /* Free memory from internal libpng struct */
  182959. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  182960. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  182961. malloc_fn, png_voidp mem_ptr));
  182962. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  182963. png_free_ptr free_fn, png_voidp mem_ptr));
  182964. /* Free any memory that info_ptr points to and reset struct. */
  182965. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  182966. png_infop info_ptr));
  182967. #ifndef PNG_1_0_X
  182968. /* Function to allocate memory for zlib. */
  182969. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  182970. /* Function to free memory for zlib */
  182971. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  182972. #ifdef PNG_SIZE_T
  182973. /* Function to convert a sizeof an item to png_sizeof item */
  182974. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  182975. #endif
  182976. /* Next four functions are used internally as callbacks. PNGAPI is required
  182977. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  182978. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  182979. png_bytep data, png_size_t length));
  182980. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182981. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  182982. png_bytep buffer, png_size_t length));
  182983. #endif
  182984. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  182985. png_bytep data, png_size_t length));
  182986. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182987. #if !defined(PNG_NO_STDIO)
  182988. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  182989. #endif
  182990. #endif
  182991. #else /* PNG_1_0_X */
  182992. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182993. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  182994. png_bytep buffer, png_size_t length));
  182995. #endif
  182996. #endif /* PNG_1_0_X */
  182997. /* Reset the CRC variable */
  182998. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  182999. /* Write the "data" buffer to whatever output you are using. */
  183000. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183001. png_size_t length));
  183002. /* Read data from whatever input you are using into the "data" buffer */
  183003. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183004. png_size_t length));
  183005. /* Read bytes into buf, and update png_ptr->crc */
  183006. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183007. png_size_t length));
  183008. /* Decompress data in a chunk that uses compression */
  183009. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183010. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183011. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183012. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183013. png_size_t prefix_length, png_size_t *data_length));
  183014. #endif
  183015. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183016. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183017. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183018. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183019. /* Calculate the CRC over a section of data. Note that we are only
  183020. * passing a maximum of 64K on systems that have this as a memory limit,
  183021. * since this is the maximum buffer size we can specify.
  183022. */
  183023. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183024. png_size_t length));
  183025. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183026. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183027. #endif
  183028. /* simple function to write the signature */
  183029. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183030. /* write various chunks */
  183031. /* Write the IHDR chunk, and update the png_struct with the necessary
  183032. * information.
  183033. */
  183034. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183035. png_uint_32 height,
  183036. int bit_depth, int color_type, int compression_method, int filter_method,
  183037. int interlace_method));
  183038. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183039. png_uint_32 num_pal));
  183040. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183041. png_size_t length));
  183042. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183043. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183044. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183045. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183046. #endif
  183047. #ifdef PNG_FIXED_POINT_SUPPORTED
  183048. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183049. file_gamma));
  183050. #endif
  183051. #endif
  183052. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183053. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183054. int color_type));
  183055. #endif
  183056. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183057. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183058. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183059. double white_x, double white_y,
  183060. double red_x, double red_y, double green_x, double green_y,
  183061. double blue_x, double blue_y));
  183062. #endif
  183063. #ifdef PNG_FIXED_POINT_SUPPORTED
  183064. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183065. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183066. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183067. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183068. png_fixed_point int_blue_y));
  183069. #endif
  183070. #endif
  183071. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183072. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183073. int intent));
  183074. #endif
  183075. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183076. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183077. png_charp name, int compression_type,
  183078. png_charp profile, int proflen));
  183079. /* Note to maintainer: profile should be png_bytep */
  183080. #endif
  183081. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183082. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183083. png_sPLT_tp palette));
  183084. #endif
  183085. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183086. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183087. png_color_16p values, int number, int color_type));
  183088. #endif
  183089. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183090. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183091. png_color_16p values, int color_type));
  183092. #endif
  183093. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183094. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183095. int num_hist));
  183096. #endif
  183097. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183098. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183099. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183100. png_charp key, png_charpp new_key));
  183101. #endif
  183102. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183103. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183104. png_charp text, png_size_t text_len));
  183105. #endif
  183106. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183107. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183108. png_charp text, png_size_t text_len, int compression));
  183109. #endif
  183110. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183111. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183112. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183113. png_charp text));
  183114. #endif
  183115. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183116. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183117. png_infop info_ptr, png_textp text_ptr, int num_text));
  183118. #endif
  183119. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183120. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183121. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183122. #endif
  183123. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183124. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183125. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183126. png_charp units, png_charpp params));
  183127. #endif
  183128. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  183129. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  183130. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  183131. int unit_type));
  183132. #endif
  183133. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183134. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  183135. png_timep mod_time));
  183136. #endif
  183137. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  183138. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  183139. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  183140. int unit, double width, double height));
  183141. #else
  183142. #ifdef PNG_FIXED_POINT_SUPPORTED
  183143. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  183144. int unit, png_charp width, png_charp height));
  183145. #endif
  183146. #endif
  183147. #endif
  183148. /* Called when finished processing a row of data */
  183149. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  183150. /* Internal use only. Called before first row of data */
  183151. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  183152. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183153. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  183154. #endif
  183155. /* combine a row of data, dealing with alpha, etc. if requested */
  183156. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  183157. int mask));
  183158. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183159. /* expand an interlaced row */
  183160. /* OLD pre-1.0.9 interface:
  183161. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  183162. png_bytep row, int pass, png_uint_32 transformations));
  183163. */
  183164. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  183165. #endif
  183166. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  183167. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183168. /* grab pixels out of a row for an interlaced pass */
  183169. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  183170. png_bytep row, int pass));
  183171. #endif
  183172. /* unfilter a row */
  183173. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  183174. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  183175. /* Choose the best filter to use and filter the row data */
  183176. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  183177. png_row_infop row_info));
  183178. /* Write out the filtered row. */
  183179. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  183180. png_bytep filtered_row));
  183181. /* finish a row while reading, dealing with interlacing passes, etc. */
  183182. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  183183. /* initialize the row buffers, etc. */
  183184. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  183185. /* optional call to update the users info structure */
  183186. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  183187. png_infop info_ptr));
  183188. /* these are the functions that do the transformations */
  183189. #if defined(PNG_READ_FILLER_SUPPORTED)
  183190. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  183191. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  183192. #endif
  183193. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183194. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  183195. png_bytep row));
  183196. #endif
  183197. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183198. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  183199. png_bytep row));
  183200. #endif
  183201. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183202. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  183203. png_bytep row));
  183204. #endif
  183205. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183206. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  183207. png_bytep row));
  183208. #endif
  183209. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  183210. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183211. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  183212. png_bytep row, png_uint_32 flags));
  183213. #endif
  183214. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183215. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  183216. #endif
  183217. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183218. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  183219. #endif
  183220. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183221. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  183222. row_info, png_bytep row));
  183223. #endif
  183224. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183225. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  183226. png_bytep row));
  183227. #endif
  183228. #if defined(PNG_READ_PACK_SUPPORTED)
  183229. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  183230. #endif
  183231. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183232. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  183233. png_color_8p sig_bits));
  183234. #endif
  183235. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183236. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  183237. #endif
  183238. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183239. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  183240. #endif
  183241. #if defined(PNG_READ_DITHER_SUPPORTED)
  183242. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  183243. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  183244. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  183245. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  183246. png_colorp palette, int num_palette));
  183247. # endif
  183248. #endif
  183249. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183250. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  183251. #endif
  183252. #if defined(PNG_WRITE_PACK_SUPPORTED)
  183253. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  183254. png_bytep row, png_uint_32 bit_depth));
  183255. #endif
  183256. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  183257. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  183258. png_color_8p bit_depth));
  183259. #endif
  183260. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183261. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183262. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183263. png_color_16p trans_values, png_color_16p background,
  183264. png_color_16p background_1,
  183265. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  183266. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  183267. png_uint_16pp gamma_16_to_1, int gamma_shift));
  183268. #else
  183269. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183270. png_color_16p trans_values, png_color_16p background));
  183271. #endif
  183272. #endif
  183273. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183274. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  183275. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  183276. int gamma_shift));
  183277. #endif
  183278. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183279. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  183280. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  183281. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  183282. png_bytep row, png_color_16p trans_value));
  183283. #endif
  183284. /* The following decodes the appropriate chunks, and does error correction,
  183285. * then calls the appropriate callback for the chunk if it is valid.
  183286. */
  183287. /* decode the IHDR chunk */
  183288. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  183289. png_uint_32 length));
  183290. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  183291. png_uint_32 length));
  183292. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  183293. png_uint_32 length));
  183294. #if defined(PNG_READ_bKGD_SUPPORTED)
  183295. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  183296. png_uint_32 length));
  183297. #endif
  183298. #if defined(PNG_READ_cHRM_SUPPORTED)
  183299. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  183300. png_uint_32 length));
  183301. #endif
  183302. #if defined(PNG_READ_gAMA_SUPPORTED)
  183303. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  183304. png_uint_32 length));
  183305. #endif
  183306. #if defined(PNG_READ_hIST_SUPPORTED)
  183307. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  183308. png_uint_32 length));
  183309. #endif
  183310. #if defined(PNG_READ_iCCP_SUPPORTED)
  183311. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  183312. png_uint_32 length));
  183313. #endif /* PNG_READ_iCCP_SUPPORTED */
  183314. #if defined(PNG_READ_iTXt_SUPPORTED)
  183315. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183316. png_uint_32 length));
  183317. #endif
  183318. #if defined(PNG_READ_oFFs_SUPPORTED)
  183319. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183320. png_uint_32 length));
  183321. #endif
  183322. #if defined(PNG_READ_pCAL_SUPPORTED)
  183323. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183324. png_uint_32 length));
  183325. #endif
  183326. #if defined(PNG_READ_pHYs_SUPPORTED)
  183327. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183328. png_uint_32 length));
  183329. #endif
  183330. #if defined(PNG_READ_sBIT_SUPPORTED)
  183331. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183332. png_uint_32 length));
  183333. #endif
  183334. #if defined(PNG_READ_sCAL_SUPPORTED)
  183335. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183336. png_uint_32 length));
  183337. #endif
  183338. #if defined(PNG_READ_sPLT_SUPPORTED)
  183339. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183340. png_uint_32 length));
  183341. #endif /* PNG_READ_sPLT_SUPPORTED */
  183342. #if defined(PNG_READ_sRGB_SUPPORTED)
  183343. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  183344. png_uint_32 length));
  183345. #endif
  183346. #if defined(PNG_READ_tEXt_SUPPORTED)
  183347. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183348. png_uint_32 length));
  183349. #endif
  183350. #if defined(PNG_READ_tIME_SUPPORTED)
  183351. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  183352. png_uint_32 length));
  183353. #endif
  183354. #if defined(PNG_READ_tRNS_SUPPORTED)
  183355. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  183356. png_uint_32 length));
  183357. #endif
  183358. #if defined(PNG_READ_zTXt_SUPPORTED)
  183359. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183360. png_uint_32 length));
  183361. #endif
  183362. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  183363. png_infop info_ptr, png_uint_32 length));
  183364. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  183365. png_bytep chunk_name));
  183366. /* handle the transformations for reading and writing */
  183367. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  183368. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  183369. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  183370. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183371. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  183372. png_infop info_ptr));
  183373. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  183374. png_infop info_ptr));
  183375. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  183376. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  183377. png_uint_32 length));
  183378. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  183379. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  183380. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  183381. png_bytep buffer, png_size_t buffer_length));
  183382. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  183383. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  183384. png_bytep buffer, png_size_t buffer_length));
  183385. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  183386. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  183387. png_infop info_ptr, png_uint_32 length));
  183388. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  183389. png_infop info_ptr));
  183390. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  183391. png_infop info_ptr));
  183392. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  183393. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  183394. png_infop info_ptr));
  183395. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  183396. png_infop info_ptr));
  183397. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  183398. #if defined(PNG_READ_tEXt_SUPPORTED)
  183399. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  183400. png_infop info_ptr, png_uint_32 length));
  183401. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  183402. png_infop info_ptr));
  183403. #endif
  183404. #if defined(PNG_READ_zTXt_SUPPORTED)
  183405. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  183406. png_infop info_ptr, png_uint_32 length));
  183407. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  183408. png_infop info_ptr));
  183409. #endif
  183410. #if defined(PNG_READ_iTXt_SUPPORTED)
  183411. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  183412. png_infop info_ptr, png_uint_32 length));
  183413. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  183414. png_infop info_ptr));
  183415. #endif
  183416. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183417. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183418. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  183419. png_bytep row));
  183420. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  183421. png_bytep row));
  183422. #endif
  183423. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183424. #if defined(PNG_MMX_CODE_SUPPORTED)
  183425. /* png.c */ /* PRIVATE */
  183426. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  183427. #endif
  183428. #endif
  183429. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  183430. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  183431. png_infop info_ptr));
  183432. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  183433. png_infop info_ptr));
  183434. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  183435. png_infop info_ptr));
  183436. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  183437. png_infop info_ptr));
  183438. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  183439. png_infop info_ptr));
  183440. #if defined(PNG_pHYs_SUPPORTED)
  183441. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  183442. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183443. #endif /* PNG_pHYs_SUPPORTED */
  183444. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  183445. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  183446. #endif /* PNG_INTERNAL */
  183447. #ifdef __cplusplus
  183448. }
  183449. #endif
  183450. #endif /* PNG_VERSION_INFO_ONLY */
  183451. /* do not put anything past this line */
  183452. #endif /* PNG_H */
  183453. /*** End of inlined file: png.h ***/
  183454. #define PNG_NO_EXTERN
  183455. /*** Start of inlined file: png.c ***/
  183456. /* png.c - location for general purpose libpng functions
  183457. *
  183458. * Last changed in libpng 1.2.21 [October 4, 2007]
  183459. * For conditions of distribution and use, see copyright notice in png.h
  183460. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183461. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183462. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183463. */
  183464. #define PNG_INTERNAL
  183465. #define PNG_NO_EXTERN
  183466. /* Generate a compiler error if there is an old png.h in the search path. */
  183467. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  183468. /* Version information for C files. This had better match the version
  183469. * string defined in png.h. */
  183470. #ifdef PNG_USE_GLOBAL_ARRAYS
  183471. /* png_libpng_ver was changed to a function in version 1.0.5c */
  183472. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  183473. #ifdef PNG_READ_SUPPORTED
  183474. /* png_sig was changed to a function in version 1.0.5c */
  183475. /* Place to hold the signature string for a PNG file. */
  183476. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  183477. #endif /* PNG_READ_SUPPORTED */
  183478. /* Invoke global declarations for constant strings for known chunk types */
  183479. PNG_IHDR;
  183480. PNG_IDAT;
  183481. PNG_IEND;
  183482. PNG_PLTE;
  183483. PNG_bKGD;
  183484. PNG_cHRM;
  183485. PNG_gAMA;
  183486. PNG_hIST;
  183487. PNG_iCCP;
  183488. PNG_iTXt;
  183489. PNG_oFFs;
  183490. PNG_pCAL;
  183491. PNG_sCAL;
  183492. PNG_pHYs;
  183493. PNG_sBIT;
  183494. PNG_sPLT;
  183495. PNG_sRGB;
  183496. PNG_tEXt;
  183497. PNG_tIME;
  183498. PNG_tRNS;
  183499. PNG_zTXt;
  183500. #ifdef PNG_READ_SUPPORTED
  183501. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  183502. /* start of interlace block */
  183503. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  183504. /* offset to next interlace block */
  183505. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  183506. /* start of interlace block in the y direction */
  183507. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  183508. /* offset to next interlace block in the y direction */
  183509. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  183510. /* Height of interlace block. This is not currently used - if you need
  183511. * it, uncomment it here and in png.h
  183512. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  183513. */
  183514. /* Mask to determine which pixels are valid in a pass */
  183515. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  183516. /* Mask to determine which pixels to overwrite while displaying */
  183517. PNG_CONST int FARDATA png_pass_dsp_mask[]
  183518. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  183519. #endif /* PNG_READ_SUPPORTED */
  183520. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183521. /* Tells libpng that we have already handled the first "num_bytes" bytes
  183522. * of the PNG file signature. If the PNG data is embedded into another
  183523. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  183524. * or write any of the magic bytes before it starts on the IHDR.
  183525. */
  183526. #ifdef PNG_READ_SUPPORTED
  183527. void PNGAPI
  183528. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  183529. {
  183530. if(png_ptr == NULL) return;
  183531. png_debug(1, "in png_set_sig_bytes\n");
  183532. if (num_bytes > 8)
  183533. png_error(png_ptr, "Too many bytes for PNG signature.");
  183534. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  183535. }
  183536. /* Checks whether the supplied bytes match the PNG signature. We allow
  183537. * checking less than the full 8-byte signature so that those apps that
  183538. * already read the first few bytes of a file to determine the file type
  183539. * can simply check the remaining bytes for extra assurance. Returns
  183540. * an integer less than, equal to, or greater than zero if sig is found,
  183541. * respectively, to be less than, to match, or be greater than the correct
  183542. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  183543. */
  183544. int PNGAPI
  183545. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  183546. {
  183547. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  183548. if (num_to_check > 8)
  183549. num_to_check = 8;
  183550. else if (num_to_check < 1)
  183551. return (-1);
  183552. if (start > 7)
  183553. return (-1);
  183554. if (start + num_to_check > 8)
  183555. num_to_check = 8 - start;
  183556. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  183557. }
  183558. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183559. /* (Obsolete) function to check signature bytes. It does not allow one
  183560. * to check a partial signature. This function might be removed in the
  183561. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  183562. */
  183563. int PNGAPI
  183564. png_check_sig(png_bytep sig, int num)
  183565. {
  183566. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  183567. }
  183568. #endif
  183569. #endif /* PNG_READ_SUPPORTED */
  183570. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  183571. /* Function to allocate memory for zlib and clear it to 0. */
  183572. #ifdef PNG_1_0_X
  183573. voidpf PNGAPI
  183574. #else
  183575. voidpf /* private */
  183576. #endif
  183577. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  183578. {
  183579. png_voidp ptr;
  183580. png_structp p=(png_structp)png_ptr;
  183581. png_uint_32 save_flags=p->flags;
  183582. png_uint_32 num_bytes;
  183583. if(png_ptr == NULL) return (NULL);
  183584. if (items > PNG_UINT_32_MAX/size)
  183585. {
  183586. png_warning (p, "Potential overflow in png_zalloc()");
  183587. return (NULL);
  183588. }
  183589. num_bytes = (png_uint_32)items * size;
  183590. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  183591. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  183592. p->flags=save_flags;
  183593. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  183594. if (ptr == NULL)
  183595. return ((voidpf)ptr);
  183596. if (num_bytes > (png_uint_32)0x8000L)
  183597. {
  183598. png_memset(ptr, 0, (png_size_t)0x8000L);
  183599. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  183600. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  183601. }
  183602. else
  183603. {
  183604. png_memset(ptr, 0, (png_size_t)num_bytes);
  183605. }
  183606. #endif
  183607. return ((voidpf)ptr);
  183608. }
  183609. /* function to free memory for zlib */
  183610. #ifdef PNG_1_0_X
  183611. void PNGAPI
  183612. #else
  183613. void /* private */
  183614. #endif
  183615. png_zfree(voidpf png_ptr, voidpf ptr)
  183616. {
  183617. png_free((png_structp)png_ptr, (png_voidp)ptr);
  183618. }
  183619. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  183620. * in case CRC is > 32 bits to leave the top bits 0.
  183621. */
  183622. void /* PRIVATE */
  183623. png_reset_crc(png_structp png_ptr)
  183624. {
  183625. png_ptr->crc = crc32(0, Z_NULL, 0);
  183626. }
  183627. /* Calculate the CRC over a section of data. We can only pass as
  183628. * much data to this routine as the largest single buffer size. We
  183629. * also check that this data will actually be used before going to the
  183630. * trouble of calculating it.
  183631. */
  183632. void /* PRIVATE */
  183633. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  183634. {
  183635. int need_crc = 1;
  183636. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  183637. {
  183638. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  183639. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  183640. need_crc = 0;
  183641. }
  183642. else /* critical */
  183643. {
  183644. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  183645. need_crc = 0;
  183646. }
  183647. if (need_crc)
  183648. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  183649. }
  183650. /* Allocate the memory for an info_struct for the application. We don't
  183651. * really need the png_ptr, but it could potentially be useful in the
  183652. * future. This should be used in favour of malloc(png_sizeof(png_info))
  183653. * and png_info_init() so that applications that want to use a shared
  183654. * libpng don't have to be recompiled if png_info changes size.
  183655. */
  183656. png_infop PNGAPI
  183657. png_create_info_struct(png_structp png_ptr)
  183658. {
  183659. png_infop info_ptr;
  183660. png_debug(1, "in png_create_info_struct\n");
  183661. if(png_ptr == NULL) return (NULL);
  183662. #ifdef PNG_USER_MEM_SUPPORTED
  183663. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  183664. png_ptr->malloc_fn, png_ptr->mem_ptr);
  183665. #else
  183666. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  183667. #endif
  183668. if (info_ptr != NULL)
  183669. png_info_init_3(&info_ptr, png_sizeof(png_info));
  183670. return (info_ptr);
  183671. }
  183672. /* This function frees the memory associated with a single info struct.
  183673. * Normally, one would use either png_destroy_read_struct() or
  183674. * png_destroy_write_struct() to free an info struct, but this may be
  183675. * useful for some applications.
  183676. */
  183677. void PNGAPI
  183678. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  183679. {
  183680. png_infop info_ptr = NULL;
  183681. if(png_ptr == NULL) return;
  183682. png_debug(1, "in png_destroy_info_struct\n");
  183683. if (info_ptr_ptr != NULL)
  183684. info_ptr = *info_ptr_ptr;
  183685. if (info_ptr != NULL)
  183686. {
  183687. png_info_destroy(png_ptr, info_ptr);
  183688. #ifdef PNG_USER_MEM_SUPPORTED
  183689. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  183690. png_ptr->mem_ptr);
  183691. #else
  183692. png_destroy_struct((png_voidp)info_ptr);
  183693. #endif
  183694. *info_ptr_ptr = NULL;
  183695. }
  183696. }
  183697. /* Initialize the info structure. This is now an internal function (0.89)
  183698. * and applications using it are urged to use png_create_info_struct()
  183699. * instead.
  183700. */
  183701. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183702. #undef png_info_init
  183703. void PNGAPI
  183704. png_info_init(png_infop info_ptr)
  183705. {
  183706. /* We only come here via pre-1.0.12-compiled applications */
  183707. png_info_init_3(&info_ptr, 0);
  183708. }
  183709. #endif
  183710. void PNGAPI
  183711. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  183712. {
  183713. png_infop info_ptr = *ptr_ptr;
  183714. if(info_ptr == NULL) return;
  183715. png_debug(1, "in png_info_init_3\n");
  183716. if(png_sizeof(png_info) > png_info_struct_size)
  183717. {
  183718. png_destroy_struct(info_ptr);
  183719. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  183720. *ptr_ptr = info_ptr;
  183721. }
  183722. /* set everything to 0 */
  183723. png_memset(info_ptr, 0, png_sizeof (png_info));
  183724. }
  183725. #ifdef PNG_FREE_ME_SUPPORTED
  183726. void PNGAPI
  183727. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  183728. int freer, png_uint_32 mask)
  183729. {
  183730. png_debug(1, "in png_data_freer\n");
  183731. if (png_ptr == NULL || info_ptr == NULL)
  183732. return;
  183733. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  183734. info_ptr->free_me |= mask;
  183735. else if(freer == PNG_USER_WILL_FREE_DATA)
  183736. info_ptr->free_me &= ~mask;
  183737. else
  183738. png_warning(png_ptr,
  183739. "Unknown freer parameter in png_data_freer.");
  183740. }
  183741. #endif
  183742. void PNGAPI
  183743. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  183744. int num)
  183745. {
  183746. png_debug(1, "in png_free_data\n");
  183747. if (png_ptr == NULL || info_ptr == NULL)
  183748. return;
  183749. #if defined(PNG_TEXT_SUPPORTED)
  183750. /* free text item num or (if num == -1) all text items */
  183751. #ifdef PNG_FREE_ME_SUPPORTED
  183752. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  183753. #else
  183754. if (mask & PNG_FREE_TEXT)
  183755. #endif
  183756. {
  183757. if (num != -1)
  183758. {
  183759. if (info_ptr->text && info_ptr->text[num].key)
  183760. {
  183761. png_free(png_ptr, info_ptr->text[num].key);
  183762. info_ptr->text[num].key = NULL;
  183763. }
  183764. }
  183765. else
  183766. {
  183767. int i;
  183768. for (i = 0; i < info_ptr->num_text; i++)
  183769. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  183770. png_free(png_ptr, info_ptr->text);
  183771. info_ptr->text = NULL;
  183772. info_ptr->num_text=0;
  183773. }
  183774. }
  183775. #endif
  183776. #if defined(PNG_tRNS_SUPPORTED)
  183777. /* free any tRNS entry */
  183778. #ifdef PNG_FREE_ME_SUPPORTED
  183779. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  183780. #else
  183781. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  183782. #endif
  183783. {
  183784. png_free(png_ptr, info_ptr->trans);
  183785. info_ptr->valid &= ~PNG_INFO_tRNS;
  183786. #ifndef PNG_FREE_ME_SUPPORTED
  183787. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  183788. #endif
  183789. info_ptr->trans = NULL;
  183790. }
  183791. #endif
  183792. #if defined(PNG_sCAL_SUPPORTED)
  183793. /* free any sCAL entry */
  183794. #ifdef PNG_FREE_ME_SUPPORTED
  183795. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  183796. #else
  183797. if (mask & PNG_FREE_SCAL)
  183798. #endif
  183799. {
  183800. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  183801. png_free(png_ptr, info_ptr->scal_s_width);
  183802. png_free(png_ptr, info_ptr->scal_s_height);
  183803. info_ptr->scal_s_width = NULL;
  183804. info_ptr->scal_s_height = NULL;
  183805. #endif
  183806. info_ptr->valid &= ~PNG_INFO_sCAL;
  183807. }
  183808. #endif
  183809. #if defined(PNG_pCAL_SUPPORTED)
  183810. /* free any pCAL entry */
  183811. #ifdef PNG_FREE_ME_SUPPORTED
  183812. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  183813. #else
  183814. if (mask & PNG_FREE_PCAL)
  183815. #endif
  183816. {
  183817. png_free(png_ptr, info_ptr->pcal_purpose);
  183818. png_free(png_ptr, info_ptr->pcal_units);
  183819. info_ptr->pcal_purpose = NULL;
  183820. info_ptr->pcal_units = NULL;
  183821. if (info_ptr->pcal_params != NULL)
  183822. {
  183823. int i;
  183824. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  183825. {
  183826. png_free(png_ptr, info_ptr->pcal_params[i]);
  183827. info_ptr->pcal_params[i]=NULL;
  183828. }
  183829. png_free(png_ptr, info_ptr->pcal_params);
  183830. info_ptr->pcal_params = NULL;
  183831. }
  183832. info_ptr->valid &= ~PNG_INFO_pCAL;
  183833. }
  183834. #endif
  183835. #if defined(PNG_iCCP_SUPPORTED)
  183836. /* free any iCCP entry */
  183837. #ifdef PNG_FREE_ME_SUPPORTED
  183838. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  183839. #else
  183840. if (mask & PNG_FREE_ICCP)
  183841. #endif
  183842. {
  183843. png_free(png_ptr, info_ptr->iccp_name);
  183844. png_free(png_ptr, info_ptr->iccp_profile);
  183845. info_ptr->iccp_name = NULL;
  183846. info_ptr->iccp_profile = NULL;
  183847. info_ptr->valid &= ~PNG_INFO_iCCP;
  183848. }
  183849. #endif
  183850. #if defined(PNG_sPLT_SUPPORTED)
  183851. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  183852. #ifdef PNG_FREE_ME_SUPPORTED
  183853. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  183854. #else
  183855. if (mask & PNG_FREE_SPLT)
  183856. #endif
  183857. {
  183858. if (num != -1)
  183859. {
  183860. if(info_ptr->splt_palettes)
  183861. {
  183862. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  183863. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  183864. info_ptr->splt_palettes[num].name = NULL;
  183865. info_ptr->splt_palettes[num].entries = NULL;
  183866. }
  183867. }
  183868. else
  183869. {
  183870. if(info_ptr->splt_palettes_num)
  183871. {
  183872. int i;
  183873. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  183874. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  183875. png_free(png_ptr, info_ptr->splt_palettes);
  183876. info_ptr->splt_palettes = NULL;
  183877. info_ptr->splt_palettes_num = 0;
  183878. }
  183879. info_ptr->valid &= ~PNG_INFO_sPLT;
  183880. }
  183881. }
  183882. #endif
  183883. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183884. if(png_ptr->unknown_chunk.data)
  183885. {
  183886. png_free(png_ptr, png_ptr->unknown_chunk.data);
  183887. png_ptr->unknown_chunk.data = NULL;
  183888. }
  183889. #ifdef PNG_FREE_ME_SUPPORTED
  183890. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  183891. #else
  183892. if (mask & PNG_FREE_UNKN)
  183893. #endif
  183894. {
  183895. if (num != -1)
  183896. {
  183897. if(info_ptr->unknown_chunks)
  183898. {
  183899. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  183900. info_ptr->unknown_chunks[num].data = NULL;
  183901. }
  183902. }
  183903. else
  183904. {
  183905. int i;
  183906. if(info_ptr->unknown_chunks_num)
  183907. {
  183908. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  183909. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  183910. png_free(png_ptr, info_ptr->unknown_chunks);
  183911. info_ptr->unknown_chunks = NULL;
  183912. info_ptr->unknown_chunks_num = 0;
  183913. }
  183914. }
  183915. }
  183916. #endif
  183917. #if defined(PNG_hIST_SUPPORTED)
  183918. /* free any hIST entry */
  183919. #ifdef PNG_FREE_ME_SUPPORTED
  183920. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  183921. #else
  183922. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  183923. #endif
  183924. {
  183925. png_free(png_ptr, info_ptr->hist);
  183926. info_ptr->hist = NULL;
  183927. info_ptr->valid &= ~PNG_INFO_hIST;
  183928. #ifndef PNG_FREE_ME_SUPPORTED
  183929. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  183930. #endif
  183931. }
  183932. #endif
  183933. /* free any PLTE entry that was internally allocated */
  183934. #ifdef PNG_FREE_ME_SUPPORTED
  183935. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  183936. #else
  183937. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  183938. #endif
  183939. {
  183940. png_zfree(png_ptr, info_ptr->palette);
  183941. info_ptr->palette = NULL;
  183942. info_ptr->valid &= ~PNG_INFO_PLTE;
  183943. #ifndef PNG_FREE_ME_SUPPORTED
  183944. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  183945. #endif
  183946. info_ptr->num_palette = 0;
  183947. }
  183948. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183949. /* free any image bits attached to the info structure */
  183950. #ifdef PNG_FREE_ME_SUPPORTED
  183951. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  183952. #else
  183953. if (mask & PNG_FREE_ROWS)
  183954. #endif
  183955. {
  183956. if(info_ptr->row_pointers)
  183957. {
  183958. int row;
  183959. for (row = 0; row < (int)info_ptr->height; row++)
  183960. {
  183961. png_free(png_ptr, info_ptr->row_pointers[row]);
  183962. info_ptr->row_pointers[row]=NULL;
  183963. }
  183964. png_free(png_ptr, info_ptr->row_pointers);
  183965. info_ptr->row_pointers=NULL;
  183966. }
  183967. info_ptr->valid &= ~PNG_INFO_IDAT;
  183968. }
  183969. #endif
  183970. #ifdef PNG_FREE_ME_SUPPORTED
  183971. if(num == -1)
  183972. info_ptr->free_me &= ~mask;
  183973. else
  183974. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  183975. #endif
  183976. }
  183977. /* This is an internal routine to free any memory that the info struct is
  183978. * pointing to before re-using it or freeing the struct itself. Recall
  183979. * that png_free() checks for NULL pointers for us.
  183980. */
  183981. void /* PRIVATE */
  183982. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  183983. {
  183984. png_debug(1, "in png_info_destroy\n");
  183985. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  183986. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183987. if (png_ptr->num_chunk_list)
  183988. {
  183989. png_free(png_ptr, png_ptr->chunk_list);
  183990. png_ptr->chunk_list=NULL;
  183991. png_ptr->num_chunk_list=0;
  183992. }
  183993. #endif
  183994. png_info_init_3(&info_ptr, png_sizeof(png_info));
  183995. }
  183996. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  183997. /* This function returns a pointer to the io_ptr associated with the user
  183998. * functions. The application should free any memory associated with this
  183999. * pointer before png_write_destroy() or png_read_destroy() are called.
  184000. */
  184001. png_voidp PNGAPI
  184002. png_get_io_ptr(png_structp png_ptr)
  184003. {
  184004. if(png_ptr == NULL) return (NULL);
  184005. return (png_ptr->io_ptr);
  184006. }
  184007. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184008. #if !defined(PNG_NO_STDIO)
  184009. /* Initialize the default input/output functions for the PNG file. If you
  184010. * use your own read or write routines, you can call either png_set_read_fn()
  184011. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184012. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184013. * necessarily available.
  184014. */
  184015. void PNGAPI
  184016. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184017. {
  184018. png_debug(1, "in png_init_io\n");
  184019. if(png_ptr == NULL) return;
  184020. png_ptr->io_ptr = (png_voidp)fp;
  184021. }
  184022. #endif
  184023. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184024. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184025. * a "Creation Time" or other text-based time string.
  184026. */
  184027. png_charp PNGAPI
  184028. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184029. {
  184030. static PNG_CONST char short_months[12][4] =
  184031. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184032. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184033. if(png_ptr == NULL) return (NULL);
  184034. if (png_ptr->time_buffer == NULL)
  184035. {
  184036. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184037. png_sizeof(char)));
  184038. }
  184039. #if defined(_WIN32_WCE)
  184040. {
  184041. wchar_t time_buf[29];
  184042. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184043. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184044. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184045. ptime->second % 61);
  184046. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184047. NULL, NULL);
  184048. }
  184049. #else
  184050. #ifdef USE_FAR_KEYWORD
  184051. {
  184052. char near_time_buf[29];
  184053. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184054. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184055. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184056. ptime->second % 61);
  184057. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184058. 29*png_sizeof(char));
  184059. }
  184060. #else
  184061. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184062. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184063. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184064. ptime->second % 61);
  184065. #endif
  184066. #endif /* _WIN32_WCE */
  184067. return ((png_charp)png_ptr->time_buffer);
  184068. }
  184069. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184070. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184071. png_charp PNGAPI
  184072. png_get_copyright(png_structp png_ptr)
  184073. {
  184074. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184075. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184076. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184077. Copyright (c) 1996-1997 Andreas Dilger\n\
  184078. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184079. }
  184080. /* The following return the library version as a short string in the
  184081. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184082. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184083. * is defined in png.h.
  184084. * Note: now there is no difference between png_get_libpng_ver() and
  184085. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184086. * it is guaranteed that png.c uses the correct version of png.h.
  184087. */
  184088. png_charp PNGAPI
  184089. png_get_libpng_ver(png_structp png_ptr)
  184090. {
  184091. /* Version of *.c files used when building libpng */
  184092. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184093. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184094. }
  184095. png_charp PNGAPI
  184096. png_get_header_ver(png_structp png_ptr)
  184097. {
  184098. /* Version of *.h files used when building libpng */
  184099. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184100. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184101. }
  184102. png_charp PNGAPI
  184103. png_get_header_version(png_structp png_ptr)
  184104. {
  184105. /* Returns longer string containing both version and date */
  184106. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184107. return ((png_charp) PNG_HEADER_VERSION_STRING
  184108. #ifndef PNG_READ_SUPPORTED
  184109. " (NO READ SUPPORT)"
  184110. #endif
  184111. "\n");
  184112. }
  184113. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184114. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184115. int PNGAPI
  184116. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184117. {
  184118. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184119. int i;
  184120. png_bytep p;
  184121. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184122. return 0;
  184123. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184124. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184125. if (!png_memcmp(chunk_name, p, 4))
  184126. return ((int)*(p+4));
  184127. return 0;
  184128. }
  184129. #endif
  184130. /* This function, added to libpng-1.0.6g, is untested. */
  184131. int PNGAPI
  184132. png_reset_zstream(png_structp png_ptr)
  184133. {
  184134. if (png_ptr == NULL) return Z_STREAM_ERROR;
  184135. return (inflateReset(&png_ptr->zstream));
  184136. }
  184137. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184138. /* This function was added to libpng-1.0.7 */
  184139. png_uint_32 PNGAPI
  184140. png_access_version_number(void)
  184141. {
  184142. /* Version of *.c files used when building libpng */
  184143. return((png_uint_32) PNG_LIBPNG_VER);
  184144. }
  184145. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184146. #if !defined(PNG_1_0_X)
  184147. /* this function was added to libpng 1.2.0 */
  184148. int PNGAPI
  184149. png_mmx_support(void)
  184150. {
  184151. /* obsolete, to be removed from libpng-1.4.0 */
  184152. return -1;
  184153. }
  184154. #endif /* PNG_1_0_X */
  184155. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  184156. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184157. #ifdef PNG_SIZE_T
  184158. /* Added at libpng version 1.2.6 */
  184159. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184160. png_size_t PNGAPI
  184161. png_convert_size(size_t size)
  184162. {
  184163. if (size > (png_size_t)-1)
  184164. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  184165. return ((png_size_t)size);
  184166. }
  184167. #endif /* PNG_SIZE_T */
  184168. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184169. /*** End of inlined file: png.c ***/
  184170. /*** Start of inlined file: pngerror.c ***/
  184171. /* pngerror.c - stub functions for i/o and memory allocation
  184172. *
  184173. * Last changed in libpng 1.2.20 October 4, 2007
  184174. * For conditions of distribution and use, see copyright notice in png.h
  184175. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184176. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184177. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184178. *
  184179. * This file provides a location for all error handling. Users who
  184180. * need special error handling are expected to write replacement functions
  184181. * and use png_set_error_fn() to use those functions. See the instructions
  184182. * at each function.
  184183. */
  184184. #define PNG_INTERNAL
  184185. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184186. static void /* PRIVATE */
  184187. png_default_error PNGARG((png_structp png_ptr,
  184188. png_const_charp error_message));
  184189. #ifndef PNG_NO_WARNINGS
  184190. static void /* PRIVATE */
  184191. png_default_warning PNGARG((png_structp png_ptr,
  184192. png_const_charp warning_message));
  184193. #endif /* PNG_NO_WARNINGS */
  184194. /* This function is called whenever there is a fatal error. This function
  184195. * should not be changed. If there is a need to handle errors differently,
  184196. * you should supply a replacement error function and use png_set_error_fn()
  184197. * to replace the error function at run-time.
  184198. */
  184199. #ifndef PNG_NO_ERROR_TEXT
  184200. void PNGAPI
  184201. png_error(png_structp png_ptr, png_const_charp error_message)
  184202. {
  184203. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184204. char msg[16];
  184205. if (png_ptr != NULL)
  184206. {
  184207. if (png_ptr->flags&
  184208. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184209. {
  184210. if (*error_message == '#')
  184211. {
  184212. int offset;
  184213. for (offset=1; offset<15; offset++)
  184214. if (*(error_message+offset) == ' ')
  184215. break;
  184216. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184217. {
  184218. int i;
  184219. for (i=0; i<offset-1; i++)
  184220. msg[i]=error_message[i+1];
  184221. msg[i]='\0';
  184222. error_message=msg;
  184223. }
  184224. else
  184225. error_message+=offset;
  184226. }
  184227. else
  184228. {
  184229. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184230. {
  184231. msg[0]='0';
  184232. msg[1]='\0';
  184233. error_message=msg;
  184234. }
  184235. }
  184236. }
  184237. }
  184238. #endif
  184239. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184240. (*(png_ptr->error_fn))(png_ptr, error_message);
  184241. /* If the custom handler doesn't exist, or if it returns,
  184242. use the default handler, which will not return. */
  184243. png_default_error(png_ptr, error_message);
  184244. }
  184245. #else
  184246. void PNGAPI
  184247. png_err(png_structp png_ptr)
  184248. {
  184249. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184250. (*(png_ptr->error_fn))(png_ptr, '\0');
  184251. /* If the custom handler doesn't exist, or if it returns,
  184252. use the default handler, which will not return. */
  184253. png_default_error(png_ptr, '\0');
  184254. }
  184255. #endif /* PNG_NO_ERROR_TEXT */
  184256. #ifndef PNG_NO_WARNINGS
  184257. /* This function is called whenever there is a non-fatal error. This function
  184258. * should not be changed. If there is a need to handle warnings differently,
  184259. * you should supply a replacement warning function and use
  184260. * png_set_error_fn() to replace the warning function at run-time.
  184261. */
  184262. void PNGAPI
  184263. png_warning(png_structp png_ptr, png_const_charp warning_message)
  184264. {
  184265. int offset = 0;
  184266. if (png_ptr != NULL)
  184267. {
  184268. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184269. if (png_ptr->flags&
  184270. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184271. #endif
  184272. {
  184273. if (*warning_message == '#')
  184274. {
  184275. for (offset=1; offset<15; offset++)
  184276. if (*(warning_message+offset) == ' ')
  184277. break;
  184278. }
  184279. }
  184280. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  184281. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  184282. }
  184283. else
  184284. png_default_warning(png_ptr, warning_message+offset);
  184285. }
  184286. #endif /* PNG_NO_WARNINGS */
  184287. /* These utilities are used internally to build an error message that relates
  184288. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  184289. * this is used to prefix the message. The message is limited in length
  184290. * to 63 bytes, the name characters are output as hex digits wrapped in []
  184291. * if the character is invalid.
  184292. */
  184293. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  184294. /*static PNG_CONST char png_digit[16] = {
  184295. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  184296. 'A', 'B', 'C', 'D', 'E', 'F'
  184297. };*/
  184298. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  184299. static void /* PRIVATE */
  184300. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  184301. error_message)
  184302. {
  184303. int iout = 0, iin = 0;
  184304. while (iin < 4)
  184305. {
  184306. int c = png_ptr->chunk_name[iin++];
  184307. if (isnonalpha(c))
  184308. {
  184309. buffer[iout++] = '[';
  184310. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  184311. buffer[iout++] = png_digit[c & 0x0f];
  184312. buffer[iout++] = ']';
  184313. }
  184314. else
  184315. {
  184316. buffer[iout++] = (png_byte)c;
  184317. }
  184318. }
  184319. if (error_message == NULL)
  184320. buffer[iout] = 0;
  184321. else
  184322. {
  184323. buffer[iout++] = ':';
  184324. buffer[iout++] = ' ';
  184325. png_strncpy(buffer+iout, error_message, 63);
  184326. buffer[iout+63] = 0;
  184327. }
  184328. }
  184329. #ifdef PNG_READ_SUPPORTED
  184330. void PNGAPI
  184331. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  184332. {
  184333. char msg[18+64];
  184334. if (png_ptr == NULL)
  184335. png_error(png_ptr, error_message);
  184336. else
  184337. {
  184338. png_format_buffer(png_ptr, msg, error_message);
  184339. png_error(png_ptr, msg);
  184340. }
  184341. }
  184342. #endif /* PNG_READ_SUPPORTED */
  184343. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  184344. #ifndef PNG_NO_WARNINGS
  184345. void PNGAPI
  184346. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  184347. {
  184348. char msg[18+64];
  184349. if (png_ptr == NULL)
  184350. png_warning(png_ptr, warning_message);
  184351. else
  184352. {
  184353. png_format_buffer(png_ptr, msg, warning_message);
  184354. png_warning(png_ptr, msg);
  184355. }
  184356. }
  184357. #endif /* PNG_NO_WARNINGS */
  184358. /* This is the default error handling function. Note that replacements for
  184359. * this function MUST NOT RETURN, or the program will likely crash. This
  184360. * function is used by default, or if the program supplies NULL for the
  184361. * error function pointer in png_set_error_fn().
  184362. */
  184363. static void /* PRIVATE */
  184364. png_default_error(png_structp, png_const_charp error_message)
  184365. {
  184366. #ifndef PNG_NO_CONSOLE_IO
  184367. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184368. if (*error_message == '#')
  184369. {
  184370. int offset;
  184371. char error_number[16];
  184372. for (offset=0; offset<15; offset++)
  184373. {
  184374. error_number[offset] = *(error_message+offset+1);
  184375. if (*(error_message+offset) == ' ')
  184376. break;
  184377. }
  184378. if((offset > 1) && (offset < 15))
  184379. {
  184380. error_number[offset-1]='\0';
  184381. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  184382. error_message+offset);
  184383. }
  184384. else
  184385. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  184386. }
  184387. else
  184388. #endif
  184389. fprintf(stderr, "libpng error: %s\n", error_message);
  184390. #endif
  184391. #ifdef PNG_SETJMP_SUPPORTED
  184392. if (png_ptr)
  184393. {
  184394. # ifdef USE_FAR_KEYWORD
  184395. {
  184396. jmp_buf jmpbuf;
  184397. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  184398. longjmp(jmpbuf, 1);
  184399. }
  184400. # else
  184401. longjmp(png_ptr->jmpbuf, 1);
  184402. # endif
  184403. }
  184404. #else
  184405. PNG_ABORT();
  184406. #endif
  184407. #ifdef PNG_NO_CONSOLE_IO
  184408. error_message = error_message; /* make compiler happy */
  184409. #endif
  184410. }
  184411. #ifndef PNG_NO_WARNINGS
  184412. /* This function is called when there is a warning, but the library thinks
  184413. * it can continue anyway. Replacement functions don't have to do anything
  184414. * here if you don't want them to. In the default configuration, png_ptr is
  184415. * not used, but it is passed in case it may be useful.
  184416. */
  184417. static void /* PRIVATE */
  184418. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  184419. {
  184420. #ifndef PNG_NO_CONSOLE_IO
  184421. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184422. if (*warning_message == '#')
  184423. {
  184424. int offset;
  184425. char warning_number[16];
  184426. for (offset=0; offset<15; offset++)
  184427. {
  184428. warning_number[offset]=*(warning_message+offset+1);
  184429. if (*(warning_message+offset) == ' ')
  184430. break;
  184431. }
  184432. if((offset > 1) && (offset < 15))
  184433. {
  184434. warning_number[offset-1]='\0';
  184435. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  184436. warning_message+offset);
  184437. }
  184438. else
  184439. fprintf(stderr, "libpng warning: %s\n", warning_message);
  184440. }
  184441. else
  184442. # endif
  184443. fprintf(stderr, "libpng warning: %s\n", warning_message);
  184444. #else
  184445. warning_message = warning_message; /* make compiler happy */
  184446. #endif
  184447. png_ptr = png_ptr; /* make compiler happy */
  184448. }
  184449. #endif /* PNG_NO_WARNINGS */
  184450. /* This function is called when the application wants to use another method
  184451. * of handling errors and warnings. Note that the error function MUST NOT
  184452. * return to the calling routine or serious problems will occur. The return
  184453. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  184454. */
  184455. void PNGAPI
  184456. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  184457. png_error_ptr error_fn, png_error_ptr warning_fn)
  184458. {
  184459. if (png_ptr == NULL)
  184460. return;
  184461. png_ptr->error_ptr = error_ptr;
  184462. png_ptr->error_fn = error_fn;
  184463. png_ptr->warning_fn = warning_fn;
  184464. }
  184465. /* This function returns a pointer to the error_ptr associated with the user
  184466. * functions. The application should free any memory associated with this
  184467. * pointer before png_write_destroy and png_read_destroy are called.
  184468. */
  184469. png_voidp PNGAPI
  184470. png_get_error_ptr(png_structp png_ptr)
  184471. {
  184472. if (png_ptr == NULL)
  184473. return NULL;
  184474. return ((png_voidp)png_ptr->error_ptr);
  184475. }
  184476. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184477. void PNGAPI
  184478. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  184479. {
  184480. if(png_ptr != NULL)
  184481. {
  184482. png_ptr->flags &=
  184483. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  184484. }
  184485. }
  184486. #endif
  184487. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  184488. /*** End of inlined file: pngerror.c ***/
  184489. /*** Start of inlined file: pngget.c ***/
  184490. /* pngget.c - retrieval of values from info struct
  184491. *
  184492. * Last changed in libpng 1.2.15 January 5, 2007
  184493. * For conditions of distribution and use, see copyright notice in png.h
  184494. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184495. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184496. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184497. */
  184498. #define PNG_INTERNAL
  184499. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184500. png_uint_32 PNGAPI
  184501. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  184502. {
  184503. if (png_ptr != NULL && info_ptr != NULL)
  184504. return(info_ptr->valid & flag);
  184505. else
  184506. return(0);
  184507. }
  184508. png_uint_32 PNGAPI
  184509. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  184510. {
  184511. if (png_ptr != NULL && info_ptr != NULL)
  184512. return(info_ptr->rowbytes);
  184513. else
  184514. return(0);
  184515. }
  184516. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184517. png_bytepp PNGAPI
  184518. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  184519. {
  184520. if (png_ptr != NULL && info_ptr != NULL)
  184521. return(info_ptr->row_pointers);
  184522. else
  184523. return(0);
  184524. }
  184525. #endif
  184526. #ifdef PNG_EASY_ACCESS_SUPPORTED
  184527. /* easy access to info, added in libpng-0.99 */
  184528. png_uint_32 PNGAPI
  184529. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  184530. {
  184531. if (png_ptr != NULL && info_ptr != NULL)
  184532. {
  184533. return info_ptr->width;
  184534. }
  184535. return (0);
  184536. }
  184537. png_uint_32 PNGAPI
  184538. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  184539. {
  184540. if (png_ptr != NULL && info_ptr != NULL)
  184541. {
  184542. return info_ptr->height;
  184543. }
  184544. return (0);
  184545. }
  184546. png_byte PNGAPI
  184547. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  184548. {
  184549. if (png_ptr != NULL && info_ptr != NULL)
  184550. {
  184551. return info_ptr->bit_depth;
  184552. }
  184553. return (0);
  184554. }
  184555. png_byte PNGAPI
  184556. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  184557. {
  184558. if (png_ptr != NULL && info_ptr != NULL)
  184559. {
  184560. return info_ptr->color_type;
  184561. }
  184562. return (0);
  184563. }
  184564. png_byte PNGAPI
  184565. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  184566. {
  184567. if (png_ptr != NULL && info_ptr != NULL)
  184568. {
  184569. return info_ptr->filter_type;
  184570. }
  184571. return (0);
  184572. }
  184573. png_byte PNGAPI
  184574. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  184575. {
  184576. if (png_ptr != NULL && info_ptr != NULL)
  184577. {
  184578. return info_ptr->interlace_type;
  184579. }
  184580. return (0);
  184581. }
  184582. png_byte PNGAPI
  184583. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  184584. {
  184585. if (png_ptr != NULL && info_ptr != NULL)
  184586. {
  184587. return info_ptr->compression_type;
  184588. }
  184589. return (0);
  184590. }
  184591. png_uint_32 PNGAPI
  184592. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184593. {
  184594. if (png_ptr != NULL && info_ptr != NULL)
  184595. #if defined(PNG_pHYs_SUPPORTED)
  184596. if (info_ptr->valid & PNG_INFO_pHYs)
  184597. {
  184598. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  184599. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  184600. return (0);
  184601. else return (info_ptr->x_pixels_per_unit);
  184602. }
  184603. #else
  184604. return (0);
  184605. #endif
  184606. return (0);
  184607. }
  184608. png_uint_32 PNGAPI
  184609. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184610. {
  184611. if (png_ptr != NULL && info_ptr != NULL)
  184612. #if defined(PNG_pHYs_SUPPORTED)
  184613. if (info_ptr->valid & PNG_INFO_pHYs)
  184614. {
  184615. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  184616. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  184617. return (0);
  184618. else return (info_ptr->y_pixels_per_unit);
  184619. }
  184620. #else
  184621. return (0);
  184622. #endif
  184623. return (0);
  184624. }
  184625. png_uint_32 PNGAPI
  184626. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184627. {
  184628. if (png_ptr != NULL && info_ptr != NULL)
  184629. #if defined(PNG_pHYs_SUPPORTED)
  184630. if (info_ptr->valid & PNG_INFO_pHYs)
  184631. {
  184632. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  184633. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  184634. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  184635. return (0);
  184636. else return (info_ptr->x_pixels_per_unit);
  184637. }
  184638. #else
  184639. return (0);
  184640. #endif
  184641. return (0);
  184642. }
  184643. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184644. float PNGAPI
  184645. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  184646. {
  184647. if (png_ptr != NULL && info_ptr != NULL)
  184648. #if defined(PNG_pHYs_SUPPORTED)
  184649. if (info_ptr->valid & PNG_INFO_pHYs)
  184650. {
  184651. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  184652. if (info_ptr->x_pixels_per_unit == 0)
  184653. return ((float)0.0);
  184654. else
  184655. return ((float)((float)info_ptr->y_pixels_per_unit
  184656. /(float)info_ptr->x_pixels_per_unit));
  184657. }
  184658. #else
  184659. return (0.0);
  184660. #endif
  184661. return ((float)0.0);
  184662. }
  184663. #endif
  184664. png_int_32 PNGAPI
  184665. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  184666. {
  184667. if (png_ptr != NULL && info_ptr != NULL)
  184668. #if defined(PNG_oFFs_SUPPORTED)
  184669. if (info_ptr->valid & PNG_INFO_oFFs)
  184670. {
  184671. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  184672. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  184673. return (0);
  184674. else return (info_ptr->x_offset);
  184675. }
  184676. #else
  184677. return (0);
  184678. #endif
  184679. return (0);
  184680. }
  184681. png_int_32 PNGAPI
  184682. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  184683. {
  184684. if (png_ptr != NULL && info_ptr != NULL)
  184685. #if defined(PNG_oFFs_SUPPORTED)
  184686. if (info_ptr->valid & PNG_INFO_oFFs)
  184687. {
  184688. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  184689. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  184690. return (0);
  184691. else return (info_ptr->y_offset);
  184692. }
  184693. #else
  184694. return (0);
  184695. #endif
  184696. return (0);
  184697. }
  184698. png_int_32 PNGAPI
  184699. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  184700. {
  184701. if (png_ptr != NULL && info_ptr != NULL)
  184702. #if defined(PNG_oFFs_SUPPORTED)
  184703. if (info_ptr->valid & PNG_INFO_oFFs)
  184704. {
  184705. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  184706. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  184707. return (0);
  184708. else return (info_ptr->x_offset);
  184709. }
  184710. #else
  184711. return (0);
  184712. #endif
  184713. return (0);
  184714. }
  184715. png_int_32 PNGAPI
  184716. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  184717. {
  184718. if (png_ptr != NULL && info_ptr != NULL)
  184719. #if defined(PNG_oFFs_SUPPORTED)
  184720. if (info_ptr->valid & PNG_INFO_oFFs)
  184721. {
  184722. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  184723. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  184724. return (0);
  184725. else return (info_ptr->y_offset);
  184726. }
  184727. #else
  184728. return (0);
  184729. #endif
  184730. return (0);
  184731. }
  184732. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184733. png_uint_32 PNGAPI
  184734. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  184735. {
  184736. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  184737. *.0254 +.5));
  184738. }
  184739. png_uint_32 PNGAPI
  184740. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  184741. {
  184742. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  184743. *.0254 +.5));
  184744. }
  184745. png_uint_32 PNGAPI
  184746. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  184747. {
  184748. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  184749. *.0254 +.5));
  184750. }
  184751. float PNGAPI
  184752. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  184753. {
  184754. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  184755. *.00003937);
  184756. }
  184757. float PNGAPI
  184758. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  184759. {
  184760. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  184761. *.00003937);
  184762. }
  184763. #if defined(PNG_pHYs_SUPPORTED)
  184764. png_uint_32 PNGAPI
  184765. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  184766. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  184767. {
  184768. png_uint_32 retval = 0;
  184769. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  184770. {
  184771. png_debug1(1, "in %s retrieval function\n", "pHYs");
  184772. if (res_x != NULL)
  184773. {
  184774. *res_x = info_ptr->x_pixels_per_unit;
  184775. retval |= PNG_INFO_pHYs;
  184776. }
  184777. if (res_y != NULL)
  184778. {
  184779. *res_y = info_ptr->y_pixels_per_unit;
  184780. retval |= PNG_INFO_pHYs;
  184781. }
  184782. if (unit_type != NULL)
  184783. {
  184784. *unit_type = (int)info_ptr->phys_unit_type;
  184785. retval |= PNG_INFO_pHYs;
  184786. if(*unit_type == 1)
  184787. {
  184788. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  184789. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  184790. }
  184791. }
  184792. }
  184793. return (retval);
  184794. }
  184795. #endif /* PNG_pHYs_SUPPORTED */
  184796. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184797. /* png_get_channels really belongs in here, too, but it's been around longer */
  184798. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  184799. png_byte PNGAPI
  184800. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  184801. {
  184802. if (png_ptr != NULL && info_ptr != NULL)
  184803. return(info_ptr->channels);
  184804. else
  184805. return (0);
  184806. }
  184807. png_bytep PNGAPI
  184808. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  184809. {
  184810. if (png_ptr != NULL && info_ptr != NULL)
  184811. return(info_ptr->signature);
  184812. else
  184813. return (NULL);
  184814. }
  184815. #if defined(PNG_bKGD_SUPPORTED)
  184816. png_uint_32 PNGAPI
  184817. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  184818. png_color_16p *background)
  184819. {
  184820. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  184821. && background != NULL)
  184822. {
  184823. png_debug1(1, "in %s retrieval function\n", "bKGD");
  184824. *background = &(info_ptr->background);
  184825. return (PNG_INFO_bKGD);
  184826. }
  184827. return (0);
  184828. }
  184829. #endif
  184830. #if defined(PNG_cHRM_SUPPORTED)
  184831. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184832. png_uint_32 PNGAPI
  184833. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  184834. double *white_x, double *white_y, double *red_x, double *red_y,
  184835. double *green_x, double *green_y, double *blue_x, double *blue_y)
  184836. {
  184837. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  184838. {
  184839. png_debug1(1, "in %s retrieval function\n", "cHRM");
  184840. if (white_x != NULL)
  184841. *white_x = (double)info_ptr->x_white;
  184842. if (white_y != NULL)
  184843. *white_y = (double)info_ptr->y_white;
  184844. if (red_x != NULL)
  184845. *red_x = (double)info_ptr->x_red;
  184846. if (red_y != NULL)
  184847. *red_y = (double)info_ptr->y_red;
  184848. if (green_x != NULL)
  184849. *green_x = (double)info_ptr->x_green;
  184850. if (green_y != NULL)
  184851. *green_y = (double)info_ptr->y_green;
  184852. if (blue_x != NULL)
  184853. *blue_x = (double)info_ptr->x_blue;
  184854. if (blue_y != NULL)
  184855. *blue_y = (double)info_ptr->y_blue;
  184856. return (PNG_INFO_cHRM);
  184857. }
  184858. return (0);
  184859. }
  184860. #endif
  184861. #ifdef PNG_FIXED_POINT_SUPPORTED
  184862. png_uint_32 PNGAPI
  184863. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  184864. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  184865. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  184866. png_fixed_point *blue_x, png_fixed_point *blue_y)
  184867. {
  184868. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  184869. {
  184870. png_debug1(1, "in %s retrieval function\n", "cHRM");
  184871. if (white_x != NULL)
  184872. *white_x = info_ptr->int_x_white;
  184873. if (white_y != NULL)
  184874. *white_y = info_ptr->int_y_white;
  184875. if (red_x != NULL)
  184876. *red_x = info_ptr->int_x_red;
  184877. if (red_y != NULL)
  184878. *red_y = info_ptr->int_y_red;
  184879. if (green_x != NULL)
  184880. *green_x = info_ptr->int_x_green;
  184881. if (green_y != NULL)
  184882. *green_y = info_ptr->int_y_green;
  184883. if (blue_x != NULL)
  184884. *blue_x = info_ptr->int_x_blue;
  184885. if (blue_y != NULL)
  184886. *blue_y = info_ptr->int_y_blue;
  184887. return (PNG_INFO_cHRM);
  184888. }
  184889. return (0);
  184890. }
  184891. #endif
  184892. #endif
  184893. #if defined(PNG_gAMA_SUPPORTED)
  184894. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184895. png_uint_32 PNGAPI
  184896. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  184897. {
  184898. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  184899. && file_gamma != NULL)
  184900. {
  184901. png_debug1(1, "in %s retrieval function\n", "gAMA");
  184902. *file_gamma = (double)info_ptr->gamma;
  184903. return (PNG_INFO_gAMA);
  184904. }
  184905. return (0);
  184906. }
  184907. #endif
  184908. #ifdef PNG_FIXED_POINT_SUPPORTED
  184909. png_uint_32 PNGAPI
  184910. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  184911. png_fixed_point *int_file_gamma)
  184912. {
  184913. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  184914. && int_file_gamma != NULL)
  184915. {
  184916. png_debug1(1, "in %s retrieval function\n", "gAMA");
  184917. *int_file_gamma = info_ptr->int_gamma;
  184918. return (PNG_INFO_gAMA);
  184919. }
  184920. return (0);
  184921. }
  184922. #endif
  184923. #endif
  184924. #if defined(PNG_sRGB_SUPPORTED)
  184925. png_uint_32 PNGAPI
  184926. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  184927. {
  184928. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  184929. && file_srgb_intent != NULL)
  184930. {
  184931. png_debug1(1, "in %s retrieval function\n", "sRGB");
  184932. *file_srgb_intent = (int)info_ptr->srgb_intent;
  184933. return (PNG_INFO_sRGB);
  184934. }
  184935. return (0);
  184936. }
  184937. #endif
  184938. #if defined(PNG_iCCP_SUPPORTED)
  184939. png_uint_32 PNGAPI
  184940. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  184941. png_charpp name, int *compression_type,
  184942. png_charpp profile, png_uint_32 *proflen)
  184943. {
  184944. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  184945. && name != NULL && profile != NULL && proflen != NULL)
  184946. {
  184947. png_debug1(1, "in %s retrieval function\n", "iCCP");
  184948. *name = info_ptr->iccp_name;
  184949. *profile = info_ptr->iccp_profile;
  184950. /* compression_type is a dummy so the API won't have to change
  184951. if we introduce multiple compression types later. */
  184952. *proflen = (int)info_ptr->iccp_proflen;
  184953. *compression_type = (int)info_ptr->iccp_compression;
  184954. return (PNG_INFO_iCCP);
  184955. }
  184956. return (0);
  184957. }
  184958. #endif
  184959. #if defined(PNG_sPLT_SUPPORTED)
  184960. png_uint_32 PNGAPI
  184961. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  184962. png_sPLT_tpp spalettes)
  184963. {
  184964. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  184965. {
  184966. *spalettes = info_ptr->splt_palettes;
  184967. return ((png_uint_32)info_ptr->splt_palettes_num);
  184968. }
  184969. return (0);
  184970. }
  184971. #endif
  184972. #if defined(PNG_hIST_SUPPORTED)
  184973. png_uint_32 PNGAPI
  184974. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  184975. {
  184976. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  184977. && hist != NULL)
  184978. {
  184979. png_debug1(1, "in %s retrieval function\n", "hIST");
  184980. *hist = info_ptr->hist;
  184981. return (PNG_INFO_hIST);
  184982. }
  184983. return (0);
  184984. }
  184985. #endif
  184986. png_uint_32 PNGAPI
  184987. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  184988. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  184989. int *color_type, int *interlace_type, int *compression_type,
  184990. int *filter_type)
  184991. {
  184992. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  184993. bit_depth != NULL && color_type != NULL)
  184994. {
  184995. png_debug1(1, "in %s retrieval function\n", "IHDR");
  184996. *width = info_ptr->width;
  184997. *height = info_ptr->height;
  184998. *bit_depth = info_ptr->bit_depth;
  184999. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185000. png_error(png_ptr, "Invalid bit depth");
  185001. *color_type = info_ptr->color_type;
  185002. if (info_ptr->color_type > 6)
  185003. png_error(png_ptr, "Invalid color type");
  185004. if (compression_type != NULL)
  185005. *compression_type = info_ptr->compression_type;
  185006. if (filter_type != NULL)
  185007. *filter_type = info_ptr->filter_type;
  185008. if (interlace_type != NULL)
  185009. *interlace_type = info_ptr->interlace_type;
  185010. /* check for potential overflow of rowbytes */
  185011. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185012. png_error(png_ptr, "Invalid image width");
  185013. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185014. png_error(png_ptr, "Invalid image height");
  185015. if (info_ptr->width > (PNG_UINT_32_MAX
  185016. >> 3) /* 8-byte RGBA pixels */
  185017. - 64 /* bigrowbuf hack */
  185018. - 1 /* filter byte */
  185019. - 7*8 /* rounding of width to multiple of 8 pixels */
  185020. - 8) /* extra max_pixel_depth pad */
  185021. {
  185022. png_warning(png_ptr,
  185023. "Width too large for libpng to process image data.");
  185024. }
  185025. return (1);
  185026. }
  185027. return (0);
  185028. }
  185029. #if defined(PNG_oFFs_SUPPORTED)
  185030. png_uint_32 PNGAPI
  185031. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185032. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185033. {
  185034. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185035. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185036. {
  185037. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185038. *offset_x = info_ptr->x_offset;
  185039. *offset_y = info_ptr->y_offset;
  185040. *unit_type = (int)info_ptr->offset_unit_type;
  185041. return (PNG_INFO_oFFs);
  185042. }
  185043. return (0);
  185044. }
  185045. #endif
  185046. #if defined(PNG_pCAL_SUPPORTED)
  185047. png_uint_32 PNGAPI
  185048. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185049. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185050. png_charp *units, png_charpp *params)
  185051. {
  185052. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185053. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185054. nparams != NULL && units != NULL && params != NULL)
  185055. {
  185056. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185057. *purpose = info_ptr->pcal_purpose;
  185058. *X0 = info_ptr->pcal_X0;
  185059. *X1 = info_ptr->pcal_X1;
  185060. *type = (int)info_ptr->pcal_type;
  185061. *nparams = (int)info_ptr->pcal_nparams;
  185062. *units = info_ptr->pcal_units;
  185063. *params = info_ptr->pcal_params;
  185064. return (PNG_INFO_pCAL);
  185065. }
  185066. return (0);
  185067. }
  185068. #endif
  185069. #if defined(PNG_sCAL_SUPPORTED)
  185070. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185071. png_uint_32 PNGAPI
  185072. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185073. int *unit, double *width, double *height)
  185074. {
  185075. if (png_ptr != NULL && info_ptr != NULL &&
  185076. (info_ptr->valid & PNG_INFO_sCAL))
  185077. {
  185078. *unit = info_ptr->scal_unit;
  185079. *width = info_ptr->scal_pixel_width;
  185080. *height = info_ptr->scal_pixel_height;
  185081. return (PNG_INFO_sCAL);
  185082. }
  185083. return(0);
  185084. }
  185085. #else
  185086. #ifdef PNG_FIXED_POINT_SUPPORTED
  185087. png_uint_32 PNGAPI
  185088. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185089. int *unit, png_charpp width, png_charpp height)
  185090. {
  185091. if (png_ptr != NULL && info_ptr != NULL &&
  185092. (info_ptr->valid & PNG_INFO_sCAL))
  185093. {
  185094. *unit = info_ptr->scal_unit;
  185095. *width = info_ptr->scal_s_width;
  185096. *height = info_ptr->scal_s_height;
  185097. return (PNG_INFO_sCAL);
  185098. }
  185099. return(0);
  185100. }
  185101. #endif
  185102. #endif
  185103. #endif
  185104. #if defined(PNG_pHYs_SUPPORTED)
  185105. png_uint_32 PNGAPI
  185106. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185107. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185108. {
  185109. png_uint_32 retval = 0;
  185110. if (png_ptr != NULL && info_ptr != NULL &&
  185111. (info_ptr->valid & PNG_INFO_pHYs))
  185112. {
  185113. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185114. if (res_x != NULL)
  185115. {
  185116. *res_x = info_ptr->x_pixels_per_unit;
  185117. retval |= PNG_INFO_pHYs;
  185118. }
  185119. if (res_y != NULL)
  185120. {
  185121. *res_y = info_ptr->y_pixels_per_unit;
  185122. retval |= PNG_INFO_pHYs;
  185123. }
  185124. if (unit_type != NULL)
  185125. {
  185126. *unit_type = (int)info_ptr->phys_unit_type;
  185127. retval |= PNG_INFO_pHYs;
  185128. }
  185129. }
  185130. return (retval);
  185131. }
  185132. #endif
  185133. png_uint_32 PNGAPI
  185134. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  185135. int *num_palette)
  185136. {
  185137. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  185138. && palette != NULL)
  185139. {
  185140. png_debug1(1, "in %s retrieval function\n", "PLTE");
  185141. *palette = info_ptr->palette;
  185142. *num_palette = info_ptr->num_palette;
  185143. png_debug1(3, "num_palette = %d\n", *num_palette);
  185144. return (PNG_INFO_PLTE);
  185145. }
  185146. return (0);
  185147. }
  185148. #if defined(PNG_sBIT_SUPPORTED)
  185149. png_uint_32 PNGAPI
  185150. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  185151. {
  185152. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  185153. && sig_bit != NULL)
  185154. {
  185155. png_debug1(1, "in %s retrieval function\n", "sBIT");
  185156. *sig_bit = &(info_ptr->sig_bit);
  185157. return (PNG_INFO_sBIT);
  185158. }
  185159. return (0);
  185160. }
  185161. #endif
  185162. #if defined(PNG_TEXT_SUPPORTED)
  185163. png_uint_32 PNGAPI
  185164. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  185165. int *num_text)
  185166. {
  185167. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  185168. {
  185169. png_debug1(1, "in %s retrieval function\n",
  185170. (png_ptr->chunk_name[0] == '\0' ? "text"
  185171. : (png_const_charp)png_ptr->chunk_name));
  185172. if (text_ptr != NULL)
  185173. *text_ptr = info_ptr->text;
  185174. if (num_text != NULL)
  185175. *num_text = info_ptr->num_text;
  185176. return ((png_uint_32)info_ptr->num_text);
  185177. }
  185178. if (num_text != NULL)
  185179. *num_text = 0;
  185180. return(0);
  185181. }
  185182. #endif
  185183. #if defined(PNG_tIME_SUPPORTED)
  185184. png_uint_32 PNGAPI
  185185. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  185186. {
  185187. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  185188. && mod_time != NULL)
  185189. {
  185190. png_debug1(1, "in %s retrieval function\n", "tIME");
  185191. *mod_time = &(info_ptr->mod_time);
  185192. return (PNG_INFO_tIME);
  185193. }
  185194. return (0);
  185195. }
  185196. #endif
  185197. #if defined(PNG_tRNS_SUPPORTED)
  185198. png_uint_32 PNGAPI
  185199. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  185200. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  185201. {
  185202. png_uint_32 retval = 0;
  185203. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  185204. {
  185205. png_debug1(1, "in %s retrieval function\n", "tRNS");
  185206. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185207. {
  185208. if (trans != NULL)
  185209. {
  185210. *trans = info_ptr->trans;
  185211. retval |= PNG_INFO_tRNS;
  185212. }
  185213. if (trans_values != NULL)
  185214. *trans_values = &(info_ptr->trans_values);
  185215. }
  185216. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  185217. {
  185218. if (trans_values != NULL)
  185219. {
  185220. *trans_values = &(info_ptr->trans_values);
  185221. retval |= PNG_INFO_tRNS;
  185222. }
  185223. if(trans != NULL)
  185224. *trans = NULL;
  185225. }
  185226. if(num_trans != NULL)
  185227. {
  185228. *num_trans = info_ptr->num_trans;
  185229. retval |= PNG_INFO_tRNS;
  185230. }
  185231. }
  185232. return (retval);
  185233. }
  185234. #endif
  185235. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185236. png_uint_32 PNGAPI
  185237. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  185238. png_unknown_chunkpp unknowns)
  185239. {
  185240. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  185241. {
  185242. *unknowns = info_ptr->unknown_chunks;
  185243. return ((png_uint_32)info_ptr->unknown_chunks_num);
  185244. }
  185245. return (0);
  185246. }
  185247. #endif
  185248. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185249. png_byte PNGAPI
  185250. png_get_rgb_to_gray_status (png_structp png_ptr)
  185251. {
  185252. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  185253. }
  185254. #endif
  185255. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  185256. png_voidp PNGAPI
  185257. png_get_user_chunk_ptr(png_structp png_ptr)
  185258. {
  185259. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  185260. }
  185261. #endif
  185262. #ifdef PNG_WRITE_SUPPORTED
  185263. png_uint_32 PNGAPI
  185264. png_get_compression_buffer_size(png_structp png_ptr)
  185265. {
  185266. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  185267. }
  185268. #endif
  185269. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  185270. #ifndef PNG_1_0_X
  185271. /* this function was added to libpng 1.2.0 and should exist by default */
  185272. png_uint_32 PNGAPI
  185273. png_get_asm_flags (png_structp png_ptr)
  185274. {
  185275. /* obsolete, to be removed from libpng-1.4.0 */
  185276. return (png_ptr? 0L: 0L);
  185277. }
  185278. /* this function was added to libpng 1.2.0 and should exist by default */
  185279. png_uint_32 PNGAPI
  185280. png_get_asm_flagmask (int flag_select)
  185281. {
  185282. /* obsolete, to be removed from libpng-1.4.0 */
  185283. flag_select=flag_select;
  185284. return 0L;
  185285. }
  185286. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  185287. /* this function was added to libpng 1.2.0 */
  185288. png_uint_32 PNGAPI
  185289. png_get_mmx_flagmask (int flag_select, int *compilerID)
  185290. {
  185291. /* obsolete, to be removed from libpng-1.4.0 */
  185292. flag_select=flag_select;
  185293. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  185294. return 0L;
  185295. }
  185296. /* this function was added to libpng 1.2.0 */
  185297. png_byte PNGAPI
  185298. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  185299. {
  185300. /* obsolete, to be removed from libpng-1.4.0 */
  185301. return (png_ptr? 0: 0);
  185302. }
  185303. /* this function was added to libpng 1.2.0 */
  185304. png_uint_32 PNGAPI
  185305. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  185306. {
  185307. /* obsolete, to be removed from libpng-1.4.0 */
  185308. return (png_ptr? 0L: 0L);
  185309. }
  185310. #endif /* ?PNG_1_0_X */
  185311. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  185312. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  185313. /* these functions were added to libpng 1.2.6 */
  185314. png_uint_32 PNGAPI
  185315. png_get_user_width_max (png_structp png_ptr)
  185316. {
  185317. return (png_ptr? png_ptr->user_width_max : 0);
  185318. }
  185319. png_uint_32 PNGAPI
  185320. png_get_user_height_max (png_structp png_ptr)
  185321. {
  185322. return (png_ptr? png_ptr->user_height_max : 0);
  185323. }
  185324. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  185325. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185326. /*** End of inlined file: pngget.c ***/
  185327. /*** Start of inlined file: pngmem.c ***/
  185328. /* pngmem.c - stub functions for memory allocation
  185329. *
  185330. * Last changed in libpng 1.2.13 November 13, 2006
  185331. * For conditions of distribution and use, see copyright notice in png.h
  185332. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185333. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185334. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185335. *
  185336. * This file provides a location for all memory allocation. Users who
  185337. * need special memory handling are expected to supply replacement
  185338. * functions for png_malloc() and png_free(), and to use
  185339. * png_create_read_struct_2() and png_create_write_struct_2() to
  185340. * identify the replacement functions.
  185341. */
  185342. #define PNG_INTERNAL
  185343. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185344. /* Borland DOS special memory handler */
  185345. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  185346. /* if you change this, be sure to change the one in png.h also */
  185347. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  185348. by a single call to calloc() if this is thought to improve performance. */
  185349. png_voidp /* PRIVATE */
  185350. png_create_struct(int type)
  185351. {
  185352. #ifdef PNG_USER_MEM_SUPPORTED
  185353. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185354. }
  185355. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  185356. png_voidp /* PRIVATE */
  185357. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185358. {
  185359. #endif /* PNG_USER_MEM_SUPPORTED */
  185360. png_size_t size;
  185361. png_voidp struct_ptr;
  185362. if (type == PNG_STRUCT_INFO)
  185363. size = png_sizeof(png_info);
  185364. else if (type == PNG_STRUCT_PNG)
  185365. size = png_sizeof(png_struct);
  185366. else
  185367. return (png_get_copyright(NULL));
  185368. #ifdef PNG_USER_MEM_SUPPORTED
  185369. if(malloc_fn != NULL)
  185370. {
  185371. png_struct dummy_struct;
  185372. png_structp png_ptr = &dummy_struct;
  185373. png_ptr->mem_ptr=mem_ptr;
  185374. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  185375. }
  185376. else
  185377. #endif /* PNG_USER_MEM_SUPPORTED */
  185378. struct_ptr = (png_voidp)farmalloc(size);
  185379. if (struct_ptr != NULL)
  185380. png_memset(struct_ptr, 0, size);
  185381. return (struct_ptr);
  185382. }
  185383. /* Free memory allocated by a png_create_struct() call */
  185384. void /* PRIVATE */
  185385. png_destroy_struct(png_voidp struct_ptr)
  185386. {
  185387. #ifdef PNG_USER_MEM_SUPPORTED
  185388. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  185389. }
  185390. /* Free memory allocated by a png_create_struct() call */
  185391. void /* PRIVATE */
  185392. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  185393. png_voidp mem_ptr)
  185394. {
  185395. #endif
  185396. if (struct_ptr != NULL)
  185397. {
  185398. #ifdef PNG_USER_MEM_SUPPORTED
  185399. if(free_fn != NULL)
  185400. {
  185401. png_struct dummy_struct;
  185402. png_structp png_ptr = &dummy_struct;
  185403. png_ptr->mem_ptr=mem_ptr;
  185404. (*(free_fn))(png_ptr, struct_ptr);
  185405. return;
  185406. }
  185407. #endif /* PNG_USER_MEM_SUPPORTED */
  185408. farfree (struct_ptr);
  185409. }
  185410. }
  185411. /* Allocate memory. For reasonable files, size should never exceed
  185412. * 64K. However, zlib may allocate more then 64K if you don't tell
  185413. * it not to. See zconf.h and png.h for more information. zlib does
  185414. * need to allocate exactly 64K, so whatever you call here must
  185415. * have the ability to do that.
  185416. *
  185417. * Borland seems to have a problem in DOS mode for exactly 64K.
  185418. * It gives you a segment with an offset of 8 (perhaps to store its
  185419. * memory stuff). zlib doesn't like this at all, so we have to
  185420. * detect and deal with it. This code should not be needed in
  185421. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  185422. * been updated by Alexander Lehmann for version 0.89 to waste less
  185423. * memory.
  185424. *
  185425. * Note that we can't use png_size_t for the "size" declaration,
  185426. * since on some systems a png_size_t is a 16-bit quantity, and as a
  185427. * result, we would be truncating potentially larger memory requests
  185428. * (which should cause a fatal error) and introducing major problems.
  185429. */
  185430. png_voidp PNGAPI
  185431. png_malloc(png_structp png_ptr, png_uint_32 size)
  185432. {
  185433. png_voidp ret;
  185434. if (png_ptr == NULL || size == 0)
  185435. return (NULL);
  185436. #ifdef PNG_USER_MEM_SUPPORTED
  185437. if(png_ptr->malloc_fn != NULL)
  185438. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  185439. else
  185440. ret = (png_malloc_default(png_ptr, size));
  185441. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185442. png_error(png_ptr, "Out of memory!");
  185443. return (ret);
  185444. }
  185445. png_voidp PNGAPI
  185446. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  185447. {
  185448. png_voidp ret;
  185449. #endif /* PNG_USER_MEM_SUPPORTED */
  185450. if (png_ptr == NULL || size == 0)
  185451. return (NULL);
  185452. #ifdef PNG_MAX_MALLOC_64K
  185453. if (size > (png_uint_32)65536L)
  185454. {
  185455. png_warning(png_ptr, "Cannot Allocate > 64K");
  185456. ret = NULL;
  185457. }
  185458. else
  185459. #endif
  185460. if (size != (size_t)size)
  185461. ret = NULL;
  185462. else if (size == (png_uint_32)65536L)
  185463. {
  185464. if (png_ptr->offset_table == NULL)
  185465. {
  185466. /* try to see if we need to do any of this fancy stuff */
  185467. ret = farmalloc(size);
  185468. if (ret == NULL || ((png_size_t)ret & 0xffff))
  185469. {
  185470. int num_blocks;
  185471. png_uint_32 total_size;
  185472. png_bytep table;
  185473. int i;
  185474. png_byte huge * hptr;
  185475. if (ret != NULL)
  185476. {
  185477. farfree(ret);
  185478. ret = NULL;
  185479. }
  185480. if(png_ptr->zlib_window_bits > 14)
  185481. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  185482. else
  185483. num_blocks = 1;
  185484. if (png_ptr->zlib_mem_level >= 7)
  185485. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  185486. else
  185487. num_blocks++;
  185488. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  185489. table = farmalloc(total_size);
  185490. if (table == NULL)
  185491. {
  185492. #ifndef PNG_USER_MEM_SUPPORTED
  185493. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185494. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  185495. else
  185496. png_warning(png_ptr, "Out Of Memory.");
  185497. #endif
  185498. return (NULL);
  185499. }
  185500. if ((png_size_t)table & 0xfff0)
  185501. {
  185502. #ifndef PNG_USER_MEM_SUPPORTED
  185503. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185504. png_error(png_ptr,
  185505. "Farmalloc didn't return normalized pointer");
  185506. else
  185507. png_warning(png_ptr,
  185508. "Farmalloc didn't return normalized pointer");
  185509. #endif
  185510. return (NULL);
  185511. }
  185512. png_ptr->offset_table = table;
  185513. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  185514. png_sizeof (png_bytep));
  185515. if (png_ptr->offset_table_ptr == NULL)
  185516. {
  185517. #ifndef PNG_USER_MEM_SUPPORTED
  185518. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185519. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  185520. else
  185521. png_warning(png_ptr, "Out Of memory.");
  185522. #endif
  185523. return (NULL);
  185524. }
  185525. hptr = (png_byte huge *)table;
  185526. if ((png_size_t)hptr & 0xf)
  185527. {
  185528. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  185529. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  185530. }
  185531. for (i = 0; i < num_blocks; i++)
  185532. {
  185533. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  185534. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  185535. }
  185536. png_ptr->offset_table_number = num_blocks;
  185537. png_ptr->offset_table_count = 0;
  185538. png_ptr->offset_table_count_free = 0;
  185539. }
  185540. }
  185541. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  185542. {
  185543. #ifndef PNG_USER_MEM_SUPPORTED
  185544. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185545. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  185546. else
  185547. png_warning(png_ptr, "Out of Memory.");
  185548. #endif
  185549. return (NULL);
  185550. }
  185551. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  185552. }
  185553. else
  185554. ret = farmalloc(size);
  185555. #ifndef PNG_USER_MEM_SUPPORTED
  185556. if (ret == NULL)
  185557. {
  185558. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185559. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  185560. else
  185561. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  185562. }
  185563. #endif
  185564. return (ret);
  185565. }
  185566. /* free a pointer allocated by png_malloc(). In the default
  185567. configuration, png_ptr is not used, but is passed in case it
  185568. is needed. If ptr is NULL, return without taking any action. */
  185569. void PNGAPI
  185570. png_free(png_structp png_ptr, png_voidp ptr)
  185571. {
  185572. if (png_ptr == NULL || ptr == NULL)
  185573. return;
  185574. #ifdef PNG_USER_MEM_SUPPORTED
  185575. if (png_ptr->free_fn != NULL)
  185576. {
  185577. (*(png_ptr->free_fn))(png_ptr, ptr);
  185578. return;
  185579. }
  185580. else png_free_default(png_ptr, ptr);
  185581. }
  185582. void PNGAPI
  185583. png_free_default(png_structp png_ptr, png_voidp ptr)
  185584. {
  185585. #endif /* PNG_USER_MEM_SUPPORTED */
  185586. if(png_ptr == NULL) return;
  185587. if (png_ptr->offset_table != NULL)
  185588. {
  185589. int i;
  185590. for (i = 0; i < png_ptr->offset_table_count; i++)
  185591. {
  185592. if (ptr == png_ptr->offset_table_ptr[i])
  185593. {
  185594. ptr = NULL;
  185595. png_ptr->offset_table_count_free++;
  185596. break;
  185597. }
  185598. }
  185599. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  185600. {
  185601. farfree(png_ptr->offset_table);
  185602. farfree(png_ptr->offset_table_ptr);
  185603. png_ptr->offset_table = NULL;
  185604. png_ptr->offset_table_ptr = NULL;
  185605. }
  185606. }
  185607. if (ptr != NULL)
  185608. {
  185609. farfree(ptr);
  185610. }
  185611. }
  185612. #else /* Not the Borland DOS special memory handler */
  185613. /* Allocate memory for a png_struct or a png_info. The malloc and
  185614. memset can be replaced by a single call to calloc() if this is thought
  185615. to improve performance noticably. */
  185616. png_voidp /* PRIVATE */
  185617. png_create_struct(int type)
  185618. {
  185619. #ifdef PNG_USER_MEM_SUPPORTED
  185620. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185621. }
  185622. /* Allocate memory for a png_struct or a png_info. The malloc and
  185623. memset can be replaced by a single call to calloc() if this is thought
  185624. to improve performance noticably. */
  185625. png_voidp /* PRIVATE */
  185626. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185627. {
  185628. #endif /* PNG_USER_MEM_SUPPORTED */
  185629. png_size_t size;
  185630. png_voidp struct_ptr;
  185631. if (type == PNG_STRUCT_INFO)
  185632. size = png_sizeof(png_info);
  185633. else if (type == PNG_STRUCT_PNG)
  185634. size = png_sizeof(png_struct);
  185635. else
  185636. return (NULL);
  185637. #ifdef PNG_USER_MEM_SUPPORTED
  185638. if(malloc_fn != NULL)
  185639. {
  185640. png_struct dummy_struct;
  185641. png_structp png_ptr = &dummy_struct;
  185642. png_ptr->mem_ptr=mem_ptr;
  185643. struct_ptr = (*(malloc_fn))(png_ptr, size);
  185644. if (struct_ptr != NULL)
  185645. png_memset(struct_ptr, 0, size);
  185646. return (struct_ptr);
  185647. }
  185648. #endif /* PNG_USER_MEM_SUPPORTED */
  185649. #if defined(__TURBOC__) && !defined(__FLAT__)
  185650. struct_ptr = (png_voidp)farmalloc(size);
  185651. #else
  185652. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185653. struct_ptr = (png_voidp)halloc(size,1);
  185654. # else
  185655. struct_ptr = (png_voidp)malloc(size);
  185656. # endif
  185657. #endif
  185658. if (struct_ptr != NULL)
  185659. png_memset(struct_ptr, 0, size);
  185660. return (struct_ptr);
  185661. }
  185662. /* Free memory allocated by a png_create_struct() call */
  185663. void /* PRIVATE */
  185664. png_destroy_struct(png_voidp struct_ptr)
  185665. {
  185666. #ifdef PNG_USER_MEM_SUPPORTED
  185667. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  185668. }
  185669. /* Free memory allocated by a png_create_struct() call */
  185670. void /* PRIVATE */
  185671. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  185672. png_voidp mem_ptr)
  185673. {
  185674. #endif /* PNG_USER_MEM_SUPPORTED */
  185675. if (struct_ptr != NULL)
  185676. {
  185677. #ifdef PNG_USER_MEM_SUPPORTED
  185678. if(free_fn != NULL)
  185679. {
  185680. png_struct dummy_struct;
  185681. png_structp png_ptr = &dummy_struct;
  185682. png_ptr->mem_ptr=mem_ptr;
  185683. (*(free_fn))(png_ptr, struct_ptr);
  185684. return;
  185685. }
  185686. #endif /* PNG_USER_MEM_SUPPORTED */
  185687. #if defined(__TURBOC__) && !defined(__FLAT__)
  185688. farfree(struct_ptr);
  185689. #else
  185690. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185691. hfree(struct_ptr);
  185692. # else
  185693. free(struct_ptr);
  185694. # endif
  185695. #endif
  185696. }
  185697. }
  185698. /* Allocate memory. For reasonable files, size should never exceed
  185699. 64K. However, zlib may allocate more then 64K if you don't tell
  185700. it not to. See zconf.h and png.h for more information. zlib does
  185701. need to allocate exactly 64K, so whatever you call here must
  185702. have the ability to do that. */
  185703. png_voidp PNGAPI
  185704. png_malloc(png_structp png_ptr, png_uint_32 size)
  185705. {
  185706. png_voidp ret;
  185707. #ifdef PNG_USER_MEM_SUPPORTED
  185708. if (png_ptr == NULL || size == 0)
  185709. return (NULL);
  185710. if(png_ptr->malloc_fn != NULL)
  185711. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  185712. else
  185713. ret = (png_malloc_default(png_ptr, size));
  185714. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185715. png_error(png_ptr, "Out of Memory!");
  185716. return (ret);
  185717. }
  185718. png_voidp PNGAPI
  185719. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  185720. {
  185721. png_voidp ret;
  185722. #endif /* PNG_USER_MEM_SUPPORTED */
  185723. if (png_ptr == NULL || size == 0)
  185724. return (NULL);
  185725. #ifdef PNG_MAX_MALLOC_64K
  185726. if (size > (png_uint_32)65536L)
  185727. {
  185728. #ifndef PNG_USER_MEM_SUPPORTED
  185729. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185730. png_error(png_ptr, "Cannot Allocate > 64K");
  185731. else
  185732. #endif
  185733. return NULL;
  185734. }
  185735. #endif
  185736. /* Check for overflow */
  185737. #if defined(__TURBOC__) && !defined(__FLAT__)
  185738. if (size != (unsigned long)size)
  185739. ret = NULL;
  185740. else
  185741. ret = farmalloc(size);
  185742. #else
  185743. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185744. if (size != (unsigned long)size)
  185745. ret = NULL;
  185746. else
  185747. ret = halloc(size, 1);
  185748. # else
  185749. if (size != (size_t)size)
  185750. ret = NULL;
  185751. else
  185752. ret = malloc((size_t)size);
  185753. # endif
  185754. #endif
  185755. #ifndef PNG_USER_MEM_SUPPORTED
  185756. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185757. png_error(png_ptr, "Out of Memory");
  185758. #endif
  185759. return (ret);
  185760. }
  185761. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  185762. without taking any action. */
  185763. void PNGAPI
  185764. png_free(png_structp png_ptr, png_voidp ptr)
  185765. {
  185766. if (png_ptr == NULL || ptr == NULL)
  185767. return;
  185768. #ifdef PNG_USER_MEM_SUPPORTED
  185769. if (png_ptr->free_fn != NULL)
  185770. {
  185771. (*(png_ptr->free_fn))(png_ptr, ptr);
  185772. return;
  185773. }
  185774. else png_free_default(png_ptr, ptr);
  185775. }
  185776. void PNGAPI
  185777. png_free_default(png_structp png_ptr, png_voidp ptr)
  185778. {
  185779. if (png_ptr == NULL || ptr == NULL)
  185780. return;
  185781. #endif /* PNG_USER_MEM_SUPPORTED */
  185782. #if defined(__TURBOC__) && !defined(__FLAT__)
  185783. farfree(ptr);
  185784. #else
  185785. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185786. hfree(ptr);
  185787. # else
  185788. free(ptr);
  185789. # endif
  185790. #endif
  185791. }
  185792. #endif /* Not Borland DOS special memory handler */
  185793. #if defined(PNG_1_0_X)
  185794. # define png_malloc_warn png_malloc
  185795. #else
  185796. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  185797. * function will set up png_malloc() to issue a png_warning and return NULL
  185798. * instead of issuing a png_error, if it fails to allocate the requested
  185799. * memory.
  185800. */
  185801. png_voidp PNGAPI
  185802. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  185803. {
  185804. png_voidp ptr;
  185805. png_uint_32 save_flags;
  185806. if(png_ptr == NULL) return (NULL);
  185807. save_flags=png_ptr->flags;
  185808. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  185809. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  185810. png_ptr->flags=save_flags;
  185811. return(ptr);
  185812. }
  185813. #endif
  185814. png_voidp PNGAPI
  185815. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  185816. png_uint_32 length)
  185817. {
  185818. png_size_t size;
  185819. size = (png_size_t)length;
  185820. if ((png_uint_32)size != length)
  185821. png_error(png_ptr,"Overflow in png_memcpy_check.");
  185822. return(png_memcpy (s1, s2, size));
  185823. }
  185824. png_voidp PNGAPI
  185825. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  185826. png_uint_32 length)
  185827. {
  185828. png_size_t size;
  185829. size = (png_size_t)length;
  185830. if ((png_uint_32)size != length)
  185831. png_error(png_ptr,"Overflow in png_memset_check.");
  185832. return (png_memset (s1, value, size));
  185833. }
  185834. #ifdef PNG_USER_MEM_SUPPORTED
  185835. /* This function is called when the application wants to use another method
  185836. * of allocating and freeing memory.
  185837. */
  185838. void PNGAPI
  185839. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  185840. malloc_fn, png_free_ptr free_fn)
  185841. {
  185842. if(png_ptr != NULL) {
  185843. png_ptr->mem_ptr = mem_ptr;
  185844. png_ptr->malloc_fn = malloc_fn;
  185845. png_ptr->free_fn = free_fn;
  185846. }
  185847. }
  185848. /* This function returns a pointer to the mem_ptr associated with the user
  185849. * functions. The application should free any memory associated with this
  185850. * pointer before png_write_destroy and png_read_destroy are called.
  185851. */
  185852. png_voidp PNGAPI
  185853. png_get_mem_ptr(png_structp png_ptr)
  185854. {
  185855. if(png_ptr == NULL) return (NULL);
  185856. return ((png_voidp)png_ptr->mem_ptr);
  185857. }
  185858. #endif /* PNG_USER_MEM_SUPPORTED */
  185859. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185860. /*** End of inlined file: pngmem.c ***/
  185861. /*** Start of inlined file: pngread.c ***/
  185862. /* pngread.c - read a PNG file
  185863. *
  185864. * Last changed in libpng 1.2.20 September 7, 2007
  185865. * For conditions of distribution and use, see copyright notice in png.h
  185866. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185867. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185868. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185869. *
  185870. * This file contains routines that an application calls directly to
  185871. * read a PNG file or stream.
  185872. */
  185873. #define PNG_INTERNAL
  185874. #if defined(PNG_READ_SUPPORTED)
  185875. /* Create a PNG structure for reading, and allocate any memory needed. */
  185876. png_structp PNGAPI
  185877. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  185878. png_error_ptr error_fn, png_error_ptr warn_fn)
  185879. {
  185880. #ifdef PNG_USER_MEM_SUPPORTED
  185881. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  185882. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  185883. }
  185884. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  185885. png_structp PNGAPI
  185886. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  185887. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  185888. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  185889. {
  185890. #endif /* PNG_USER_MEM_SUPPORTED */
  185891. png_structp png_ptr;
  185892. #ifdef PNG_SETJMP_SUPPORTED
  185893. #ifdef USE_FAR_KEYWORD
  185894. jmp_buf jmpbuf;
  185895. #endif
  185896. #endif
  185897. int i;
  185898. png_debug(1, "in png_create_read_struct\n");
  185899. #ifdef PNG_USER_MEM_SUPPORTED
  185900. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  185901. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  185902. #else
  185903. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  185904. #endif
  185905. if (png_ptr == NULL)
  185906. return (NULL);
  185907. /* added at libpng-1.2.6 */
  185908. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  185909. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  185910. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  185911. #endif
  185912. #ifdef PNG_SETJMP_SUPPORTED
  185913. #ifdef USE_FAR_KEYWORD
  185914. if (setjmp(jmpbuf))
  185915. #else
  185916. if (setjmp(png_ptr->jmpbuf))
  185917. #endif
  185918. {
  185919. png_free(png_ptr, png_ptr->zbuf);
  185920. png_ptr->zbuf=NULL;
  185921. #ifdef PNG_USER_MEM_SUPPORTED
  185922. png_destroy_struct_2((png_voidp)png_ptr,
  185923. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  185924. #else
  185925. png_destroy_struct((png_voidp)png_ptr);
  185926. #endif
  185927. return (NULL);
  185928. }
  185929. #ifdef USE_FAR_KEYWORD
  185930. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  185931. #endif
  185932. #endif
  185933. #ifdef PNG_USER_MEM_SUPPORTED
  185934. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  185935. #endif
  185936. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  185937. i=0;
  185938. do
  185939. {
  185940. if(user_png_ver[i] != png_libpng_ver[i])
  185941. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  185942. } while (png_libpng_ver[i++]);
  185943. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  185944. {
  185945. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  185946. * we must recompile any applications that use any older library version.
  185947. * For versions after libpng 1.0, we will be compatible, so we need
  185948. * only check the first digit.
  185949. */
  185950. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  185951. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  185952. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  185953. {
  185954. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  185955. char msg[80];
  185956. if (user_png_ver)
  185957. {
  185958. png_snprintf(msg, 80,
  185959. "Application was compiled with png.h from libpng-%.20s",
  185960. user_png_ver);
  185961. png_warning(png_ptr, msg);
  185962. }
  185963. png_snprintf(msg, 80,
  185964. "Application is running with png.c from libpng-%.20s",
  185965. png_libpng_ver);
  185966. png_warning(png_ptr, msg);
  185967. #endif
  185968. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185969. png_ptr->flags=0;
  185970. #endif
  185971. png_error(png_ptr,
  185972. "Incompatible libpng version in application and library");
  185973. }
  185974. }
  185975. /* initialize zbuf - compression buffer */
  185976. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  185977. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  185978. (png_uint_32)png_ptr->zbuf_size);
  185979. png_ptr->zstream.zalloc = png_zalloc;
  185980. png_ptr->zstream.zfree = png_zfree;
  185981. png_ptr->zstream.opaque = (voidpf)png_ptr;
  185982. switch (inflateInit(&png_ptr->zstream))
  185983. {
  185984. case Z_OK: /* Do nothing */ break;
  185985. case Z_MEM_ERROR:
  185986. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  185987. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  185988. default: png_error(png_ptr, "Unknown zlib error");
  185989. }
  185990. png_ptr->zstream.next_out = png_ptr->zbuf;
  185991. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  185992. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  185993. #ifdef PNG_SETJMP_SUPPORTED
  185994. /* Applications that neglect to set up their own setjmp() and then encounter
  185995. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  185996. abort instead of returning. */
  185997. #ifdef USE_FAR_KEYWORD
  185998. if (setjmp(jmpbuf))
  185999. PNG_ABORT();
  186000. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186001. #else
  186002. if (setjmp(png_ptr->jmpbuf))
  186003. PNG_ABORT();
  186004. #endif
  186005. #endif
  186006. return (png_ptr);
  186007. }
  186008. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186009. /* Initialize PNG structure for reading, and allocate any memory needed.
  186010. This interface is deprecated in favour of the png_create_read_struct(),
  186011. and it will disappear as of libpng-1.3.0. */
  186012. #undef png_read_init
  186013. void PNGAPI
  186014. png_read_init(png_structp png_ptr)
  186015. {
  186016. /* We only come here via pre-1.0.7-compiled applications */
  186017. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186018. }
  186019. void PNGAPI
  186020. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186021. png_size_t png_struct_size, png_size_t png_info_size)
  186022. {
  186023. /* We only come here via pre-1.0.12-compiled applications */
  186024. if(png_ptr == NULL) return;
  186025. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186026. if(png_sizeof(png_struct) > png_struct_size ||
  186027. png_sizeof(png_info) > png_info_size)
  186028. {
  186029. char msg[80];
  186030. png_ptr->warning_fn=NULL;
  186031. if (user_png_ver)
  186032. {
  186033. png_snprintf(msg, 80,
  186034. "Application was compiled with png.h from libpng-%.20s",
  186035. user_png_ver);
  186036. png_warning(png_ptr, msg);
  186037. }
  186038. png_snprintf(msg, 80,
  186039. "Application is running with png.c from libpng-%.20s",
  186040. png_libpng_ver);
  186041. png_warning(png_ptr, msg);
  186042. }
  186043. #endif
  186044. if(png_sizeof(png_struct) > png_struct_size)
  186045. {
  186046. png_ptr->error_fn=NULL;
  186047. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186048. png_ptr->flags=0;
  186049. #endif
  186050. png_error(png_ptr,
  186051. "The png struct allocated by the application for reading is too small.");
  186052. }
  186053. if(png_sizeof(png_info) > png_info_size)
  186054. {
  186055. png_ptr->error_fn=NULL;
  186056. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186057. png_ptr->flags=0;
  186058. #endif
  186059. png_error(png_ptr,
  186060. "The info struct allocated by application for reading is too small.");
  186061. }
  186062. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186063. }
  186064. #endif /* PNG_1_0_X || PNG_1_2_X */
  186065. void PNGAPI
  186066. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186067. png_size_t png_struct_size)
  186068. {
  186069. #ifdef PNG_SETJMP_SUPPORTED
  186070. jmp_buf tmp_jmp; /* to save current jump buffer */
  186071. #endif
  186072. int i=0;
  186073. png_structp png_ptr=*ptr_ptr;
  186074. if(png_ptr == NULL) return;
  186075. do
  186076. {
  186077. if(user_png_ver[i] != png_libpng_ver[i])
  186078. {
  186079. #ifdef PNG_LEGACY_SUPPORTED
  186080. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186081. #else
  186082. png_ptr->warning_fn=NULL;
  186083. png_warning(png_ptr,
  186084. "Application uses deprecated png_read_init() and should be recompiled.");
  186085. break;
  186086. #endif
  186087. }
  186088. } while (png_libpng_ver[i++]);
  186089. png_debug(1, "in png_read_init_3\n");
  186090. #ifdef PNG_SETJMP_SUPPORTED
  186091. /* save jump buffer and error functions */
  186092. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186093. #endif
  186094. if(png_sizeof(png_struct) > png_struct_size)
  186095. {
  186096. png_destroy_struct(png_ptr);
  186097. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186098. png_ptr = *ptr_ptr;
  186099. }
  186100. /* reset all variables to 0 */
  186101. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186102. #ifdef PNG_SETJMP_SUPPORTED
  186103. /* restore jump buffer */
  186104. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186105. #endif
  186106. /* added at libpng-1.2.6 */
  186107. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186108. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186109. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186110. #endif
  186111. /* initialize zbuf - compression buffer */
  186112. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186113. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186114. (png_uint_32)png_ptr->zbuf_size);
  186115. png_ptr->zstream.zalloc = png_zalloc;
  186116. png_ptr->zstream.zfree = png_zfree;
  186117. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186118. switch (inflateInit(&png_ptr->zstream))
  186119. {
  186120. case Z_OK: /* Do nothing */ break;
  186121. case Z_MEM_ERROR:
  186122. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186123. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186124. default: png_error(png_ptr, "Unknown zlib error");
  186125. }
  186126. png_ptr->zstream.next_out = png_ptr->zbuf;
  186127. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186128. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186129. }
  186130. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186131. /* Read the information before the actual image data. This has been
  186132. * changed in v0.90 to allow reading a file that already has the magic
  186133. * bytes read from the stream. You can tell libpng how many bytes have
  186134. * been read from the beginning of the stream (up to the maximum of 8)
  186135. * via png_set_sig_bytes(), and we will only check the remaining bytes
  186136. * here. The application can then have access to the signature bytes we
  186137. * read if it is determined that this isn't a valid PNG file.
  186138. */
  186139. void PNGAPI
  186140. png_read_info(png_structp png_ptr, png_infop info_ptr)
  186141. {
  186142. if(png_ptr == NULL) return;
  186143. png_debug(1, "in png_read_info\n");
  186144. /* If we haven't checked all of the PNG signature bytes, do so now. */
  186145. if (png_ptr->sig_bytes < 8)
  186146. {
  186147. png_size_t num_checked = png_ptr->sig_bytes,
  186148. num_to_check = 8 - num_checked;
  186149. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  186150. png_ptr->sig_bytes = 8;
  186151. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  186152. {
  186153. if (num_checked < 4 &&
  186154. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  186155. png_error(png_ptr, "Not a PNG file");
  186156. else
  186157. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  186158. }
  186159. if (num_checked < 3)
  186160. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  186161. }
  186162. for(;;)
  186163. {
  186164. #ifdef PNG_USE_LOCAL_ARRAYS
  186165. PNG_CONST PNG_IHDR;
  186166. PNG_CONST PNG_IDAT;
  186167. PNG_CONST PNG_IEND;
  186168. PNG_CONST PNG_PLTE;
  186169. #if defined(PNG_READ_bKGD_SUPPORTED)
  186170. PNG_CONST PNG_bKGD;
  186171. #endif
  186172. #if defined(PNG_READ_cHRM_SUPPORTED)
  186173. PNG_CONST PNG_cHRM;
  186174. #endif
  186175. #if defined(PNG_READ_gAMA_SUPPORTED)
  186176. PNG_CONST PNG_gAMA;
  186177. #endif
  186178. #if defined(PNG_READ_hIST_SUPPORTED)
  186179. PNG_CONST PNG_hIST;
  186180. #endif
  186181. #if defined(PNG_READ_iCCP_SUPPORTED)
  186182. PNG_CONST PNG_iCCP;
  186183. #endif
  186184. #if defined(PNG_READ_iTXt_SUPPORTED)
  186185. PNG_CONST PNG_iTXt;
  186186. #endif
  186187. #if defined(PNG_READ_oFFs_SUPPORTED)
  186188. PNG_CONST PNG_oFFs;
  186189. #endif
  186190. #if defined(PNG_READ_pCAL_SUPPORTED)
  186191. PNG_CONST PNG_pCAL;
  186192. #endif
  186193. #if defined(PNG_READ_pHYs_SUPPORTED)
  186194. PNG_CONST PNG_pHYs;
  186195. #endif
  186196. #if defined(PNG_READ_sBIT_SUPPORTED)
  186197. PNG_CONST PNG_sBIT;
  186198. #endif
  186199. #if defined(PNG_READ_sCAL_SUPPORTED)
  186200. PNG_CONST PNG_sCAL;
  186201. #endif
  186202. #if defined(PNG_READ_sPLT_SUPPORTED)
  186203. PNG_CONST PNG_sPLT;
  186204. #endif
  186205. #if defined(PNG_READ_sRGB_SUPPORTED)
  186206. PNG_CONST PNG_sRGB;
  186207. #endif
  186208. #if defined(PNG_READ_tEXt_SUPPORTED)
  186209. PNG_CONST PNG_tEXt;
  186210. #endif
  186211. #if defined(PNG_READ_tIME_SUPPORTED)
  186212. PNG_CONST PNG_tIME;
  186213. #endif
  186214. #if defined(PNG_READ_tRNS_SUPPORTED)
  186215. PNG_CONST PNG_tRNS;
  186216. #endif
  186217. #if defined(PNG_READ_zTXt_SUPPORTED)
  186218. PNG_CONST PNG_zTXt;
  186219. #endif
  186220. #endif /* PNG_USE_LOCAL_ARRAYS */
  186221. png_byte chunk_length[4];
  186222. png_uint_32 length;
  186223. png_read_data(png_ptr, chunk_length, 4);
  186224. length = png_get_uint_31(png_ptr,chunk_length);
  186225. png_reset_crc(png_ptr);
  186226. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186227. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  186228. length);
  186229. /* This should be a binary subdivision search or a hash for
  186230. * matching the chunk name rather than a linear search.
  186231. */
  186232. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186233. if(png_ptr->mode & PNG_AFTER_IDAT)
  186234. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  186235. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  186236. png_handle_IHDR(png_ptr, info_ptr, length);
  186237. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  186238. png_handle_IEND(png_ptr, info_ptr, length);
  186239. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186240. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  186241. {
  186242. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186243. png_ptr->mode |= PNG_HAVE_IDAT;
  186244. png_handle_unknown(png_ptr, info_ptr, length);
  186245. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186246. png_ptr->mode |= PNG_HAVE_PLTE;
  186247. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186248. {
  186249. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186250. png_error(png_ptr, "Missing IHDR before IDAT");
  186251. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186252. !(png_ptr->mode & PNG_HAVE_PLTE))
  186253. png_error(png_ptr, "Missing PLTE before IDAT");
  186254. break;
  186255. }
  186256. }
  186257. #endif
  186258. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186259. png_handle_PLTE(png_ptr, info_ptr, length);
  186260. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186261. {
  186262. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186263. png_error(png_ptr, "Missing IHDR before IDAT");
  186264. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186265. !(png_ptr->mode & PNG_HAVE_PLTE))
  186266. png_error(png_ptr, "Missing PLTE before IDAT");
  186267. png_ptr->idat_size = length;
  186268. png_ptr->mode |= PNG_HAVE_IDAT;
  186269. break;
  186270. }
  186271. #if defined(PNG_READ_bKGD_SUPPORTED)
  186272. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  186273. png_handle_bKGD(png_ptr, info_ptr, length);
  186274. #endif
  186275. #if defined(PNG_READ_cHRM_SUPPORTED)
  186276. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  186277. png_handle_cHRM(png_ptr, info_ptr, length);
  186278. #endif
  186279. #if defined(PNG_READ_gAMA_SUPPORTED)
  186280. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  186281. png_handle_gAMA(png_ptr, info_ptr, length);
  186282. #endif
  186283. #if defined(PNG_READ_hIST_SUPPORTED)
  186284. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  186285. png_handle_hIST(png_ptr, info_ptr, length);
  186286. #endif
  186287. #if defined(PNG_READ_oFFs_SUPPORTED)
  186288. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  186289. png_handle_oFFs(png_ptr, info_ptr, length);
  186290. #endif
  186291. #if defined(PNG_READ_pCAL_SUPPORTED)
  186292. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  186293. png_handle_pCAL(png_ptr, info_ptr, length);
  186294. #endif
  186295. #if defined(PNG_READ_sCAL_SUPPORTED)
  186296. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  186297. png_handle_sCAL(png_ptr, info_ptr, length);
  186298. #endif
  186299. #if defined(PNG_READ_pHYs_SUPPORTED)
  186300. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  186301. png_handle_pHYs(png_ptr, info_ptr, length);
  186302. #endif
  186303. #if defined(PNG_READ_sBIT_SUPPORTED)
  186304. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  186305. png_handle_sBIT(png_ptr, info_ptr, length);
  186306. #endif
  186307. #if defined(PNG_READ_sRGB_SUPPORTED)
  186308. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  186309. png_handle_sRGB(png_ptr, info_ptr, length);
  186310. #endif
  186311. #if defined(PNG_READ_iCCP_SUPPORTED)
  186312. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  186313. png_handle_iCCP(png_ptr, info_ptr, length);
  186314. #endif
  186315. #if defined(PNG_READ_sPLT_SUPPORTED)
  186316. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  186317. png_handle_sPLT(png_ptr, info_ptr, length);
  186318. #endif
  186319. #if defined(PNG_READ_tEXt_SUPPORTED)
  186320. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  186321. png_handle_tEXt(png_ptr, info_ptr, length);
  186322. #endif
  186323. #if defined(PNG_READ_tIME_SUPPORTED)
  186324. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  186325. png_handle_tIME(png_ptr, info_ptr, length);
  186326. #endif
  186327. #if defined(PNG_READ_tRNS_SUPPORTED)
  186328. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  186329. png_handle_tRNS(png_ptr, info_ptr, length);
  186330. #endif
  186331. #if defined(PNG_READ_zTXt_SUPPORTED)
  186332. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  186333. png_handle_zTXt(png_ptr, info_ptr, length);
  186334. #endif
  186335. #if defined(PNG_READ_iTXt_SUPPORTED)
  186336. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  186337. png_handle_iTXt(png_ptr, info_ptr, length);
  186338. #endif
  186339. else
  186340. png_handle_unknown(png_ptr, info_ptr, length);
  186341. }
  186342. }
  186343. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186344. /* optional call to update the users info_ptr structure */
  186345. void PNGAPI
  186346. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  186347. {
  186348. png_debug(1, "in png_read_update_info\n");
  186349. if(png_ptr == NULL) return;
  186350. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186351. png_read_start_row(png_ptr);
  186352. else
  186353. png_warning(png_ptr,
  186354. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  186355. png_read_transform_info(png_ptr, info_ptr);
  186356. }
  186357. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186358. /* Initialize palette, background, etc, after transformations
  186359. * are set, but before any reading takes place. This allows
  186360. * the user to obtain a gamma-corrected palette, for example.
  186361. * If the user doesn't call this, we will do it ourselves.
  186362. */
  186363. void PNGAPI
  186364. png_start_read_image(png_structp png_ptr)
  186365. {
  186366. png_debug(1, "in png_start_read_image\n");
  186367. if(png_ptr == NULL) return;
  186368. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186369. png_read_start_row(png_ptr);
  186370. }
  186371. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186372. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186373. void PNGAPI
  186374. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  186375. {
  186376. #ifdef PNG_USE_LOCAL_ARRAYS
  186377. PNG_CONST PNG_IDAT;
  186378. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  186379. 0xff};
  186380. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  186381. #endif
  186382. int ret;
  186383. if(png_ptr == NULL) return;
  186384. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  186385. png_ptr->row_number, png_ptr->pass);
  186386. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186387. png_read_start_row(png_ptr);
  186388. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  186389. {
  186390. /* check for transforms that have been set but were defined out */
  186391. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  186392. if (png_ptr->transformations & PNG_INVERT_MONO)
  186393. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  186394. #endif
  186395. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  186396. if (png_ptr->transformations & PNG_FILLER)
  186397. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  186398. #endif
  186399. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  186400. if (png_ptr->transformations & PNG_PACKSWAP)
  186401. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  186402. #endif
  186403. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  186404. if (png_ptr->transformations & PNG_PACK)
  186405. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  186406. #endif
  186407. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  186408. if (png_ptr->transformations & PNG_SHIFT)
  186409. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  186410. #endif
  186411. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  186412. if (png_ptr->transformations & PNG_BGR)
  186413. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  186414. #endif
  186415. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  186416. if (png_ptr->transformations & PNG_SWAP_BYTES)
  186417. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  186418. #endif
  186419. }
  186420. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186421. /* if interlaced and we do not need a new row, combine row and return */
  186422. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  186423. {
  186424. switch (png_ptr->pass)
  186425. {
  186426. case 0:
  186427. if (png_ptr->row_number & 0x07)
  186428. {
  186429. if (dsp_row != NULL)
  186430. png_combine_row(png_ptr, dsp_row,
  186431. png_pass_dsp_mask[png_ptr->pass]);
  186432. png_read_finish_row(png_ptr);
  186433. return;
  186434. }
  186435. break;
  186436. case 1:
  186437. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  186438. {
  186439. if (dsp_row != NULL)
  186440. png_combine_row(png_ptr, dsp_row,
  186441. png_pass_dsp_mask[png_ptr->pass]);
  186442. png_read_finish_row(png_ptr);
  186443. return;
  186444. }
  186445. break;
  186446. case 2:
  186447. if ((png_ptr->row_number & 0x07) != 4)
  186448. {
  186449. if (dsp_row != NULL && (png_ptr->row_number & 4))
  186450. png_combine_row(png_ptr, dsp_row,
  186451. png_pass_dsp_mask[png_ptr->pass]);
  186452. png_read_finish_row(png_ptr);
  186453. return;
  186454. }
  186455. break;
  186456. case 3:
  186457. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  186458. {
  186459. if (dsp_row != NULL)
  186460. png_combine_row(png_ptr, dsp_row,
  186461. png_pass_dsp_mask[png_ptr->pass]);
  186462. png_read_finish_row(png_ptr);
  186463. return;
  186464. }
  186465. break;
  186466. case 4:
  186467. if ((png_ptr->row_number & 3) != 2)
  186468. {
  186469. if (dsp_row != NULL && (png_ptr->row_number & 2))
  186470. png_combine_row(png_ptr, dsp_row,
  186471. png_pass_dsp_mask[png_ptr->pass]);
  186472. png_read_finish_row(png_ptr);
  186473. return;
  186474. }
  186475. break;
  186476. case 5:
  186477. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  186478. {
  186479. if (dsp_row != NULL)
  186480. png_combine_row(png_ptr, dsp_row,
  186481. png_pass_dsp_mask[png_ptr->pass]);
  186482. png_read_finish_row(png_ptr);
  186483. return;
  186484. }
  186485. break;
  186486. case 6:
  186487. if (!(png_ptr->row_number & 1))
  186488. {
  186489. png_read_finish_row(png_ptr);
  186490. return;
  186491. }
  186492. break;
  186493. }
  186494. }
  186495. #endif
  186496. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  186497. png_error(png_ptr, "Invalid attempt to read row data");
  186498. png_ptr->zstream.next_out = png_ptr->row_buf;
  186499. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  186500. do
  186501. {
  186502. if (!(png_ptr->zstream.avail_in))
  186503. {
  186504. while (!png_ptr->idat_size)
  186505. {
  186506. png_byte chunk_length[4];
  186507. png_crc_finish(png_ptr, 0);
  186508. png_read_data(png_ptr, chunk_length, 4);
  186509. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  186510. png_reset_crc(png_ptr);
  186511. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186512. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186513. png_error(png_ptr, "Not enough image data");
  186514. }
  186515. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  186516. png_ptr->zstream.next_in = png_ptr->zbuf;
  186517. if (png_ptr->zbuf_size > png_ptr->idat_size)
  186518. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  186519. png_crc_read(png_ptr, png_ptr->zbuf,
  186520. (png_size_t)png_ptr->zstream.avail_in);
  186521. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  186522. }
  186523. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  186524. if (ret == Z_STREAM_END)
  186525. {
  186526. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  186527. png_ptr->idat_size)
  186528. png_error(png_ptr, "Extra compressed data");
  186529. png_ptr->mode |= PNG_AFTER_IDAT;
  186530. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  186531. break;
  186532. }
  186533. if (ret != Z_OK)
  186534. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  186535. "Decompression error");
  186536. } while (png_ptr->zstream.avail_out);
  186537. png_ptr->row_info.color_type = png_ptr->color_type;
  186538. png_ptr->row_info.width = png_ptr->iwidth;
  186539. png_ptr->row_info.channels = png_ptr->channels;
  186540. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  186541. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  186542. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186543. png_ptr->row_info.width);
  186544. if(png_ptr->row_buf[0])
  186545. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  186546. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  186547. (int)(png_ptr->row_buf[0]));
  186548. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  186549. png_ptr->rowbytes + 1);
  186550. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  186551. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  186552. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  186553. {
  186554. /* Intrapixel differencing */
  186555. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186556. }
  186557. #endif
  186558. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  186559. png_do_read_transformations(png_ptr);
  186560. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186561. /* blow up interlaced rows to full size */
  186562. if (png_ptr->interlaced &&
  186563. (png_ptr->transformations & PNG_INTERLACE))
  186564. {
  186565. if (png_ptr->pass < 6)
  186566. /* old interface (pre-1.0.9):
  186567. png_do_read_interlace(&(png_ptr->row_info),
  186568. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  186569. */
  186570. png_do_read_interlace(png_ptr);
  186571. if (dsp_row != NULL)
  186572. png_combine_row(png_ptr, dsp_row,
  186573. png_pass_dsp_mask[png_ptr->pass]);
  186574. if (row != NULL)
  186575. png_combine_row(png_ptr, row,
  186576. png_pass_mask[png_ptr->pass]);
  186577. }
  186578. else
  186579. #endif
  186580. {
  186581. if (row != NULL)
  186582. png_combine_row(png_ptr, row, 0xff);
  186583. if (dsp_row != NULL)
  186584. png_combine_row(png_ptr, dsp_row, 0xff);
  186585. }
  186586. png_read_finish_row(png_ptr);
  186587. if (png_ptr->read_row_fn != NULL)
  186588. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  186589. }
  186590. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186591. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186592. /* Read one or more rows of image data. If the image is interlaced,
  186593. * and png_set_interlace_handling() has been called, the rows need to
  186594. * contain the contents of the rows from the previous pass. If the
  186595. * image has alpha or transparency, and png_handle_alpha()[*] has been
  186596. * called, the rows contents must be initialized to the contents of the
  186597. * screen.
  186598. *
  186599. * "row" holds the actual image, and pixels are placed in it
  186600. * as they arrive. If the image is displayed after each pass, it will
  186601. * appear to "sparkle" in. "display_row" can be used to display a
  186602. * "chunky" progressive image, with finer detail added as it becomes
  186603. * available. If you do not want this "chunky" display, you may pass
  186604. * NULL for display_row. If you do not want the sparkle display, and
  186605. * you have not called png_handle_alpha(), you may pass NULL for rows.
  186606. * If you have called png_handle_alpha(), and the image has either an
  186607. * alpha channel or a transparency chunk, you must provide a buffer for
  186608. * rows. In this case, you do not have to provide a display_row buffer
  186609. * also, but you may. If the image is not interlaced, or if you have
  186610. * not called png_set_interlace_handling(), the display_row buffer will
  186611. * be ignored, so pass NULL to it.
  186612. *
  186613. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  186614. */
  186615. void PNGAPI
  186616. png_read_rows(png_structp png_ptr, png_bytepp row,
  186617. png_bytepp display_row, png_uint_32 num_rows)
  186618. {
  186619. png_uint_32 i;
  186620. png_bytepp rp;
  186621. png_bytepp dp;
  186622. png_debug(1, "in png_read_rows\n");
  186623. if(png_ptr == NULL) return;
  186624. rp = row;
  186625. dp = display_row;
  186626. if (rp != NULL && dp != NULL)
  186627. for (i = 0; i < num_rows; i++)
  186628. {
  186629. png_bytep rptr = *rp++;
  186630. png_bytep dptr = *dp++;
  186631. png_read_row(png_ptr, rptr, dptr);
  186632. }
  186633. else if(rp != NULL)
  186634. for (i = 0; i < num_rows; i++)
  186635. {
  186636. png_bytep rptr = *rp;
  186637. png_read_row(png_ptr, rptr, png_bytep_NULL);
  186638. rp++;
  186639. }
  186640. else if(dp != NULL)
  186641. for (i = 0; i < num_rows; i++)
  186642. {
  186643. png_bytep dptr = *dp;
  186644. png_read_row(png_ptr, png_bytep_NULL, dptr);
  186645. dp++;
  186646. }
  186647. }
  186648. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186649. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186650. /* Read the entire image. If the image has an alpha channel or a tRNS
  186651. * chunk, and you have called png_handle_alpha()[*], you will need to
  186652. * initialize the image to the current image that PNG will be overlaying.
  186653. * We set the num_rows again here, in case it was incorrectly set in
  186654. * png_read_start_row() by a call to png_read_update_info() or
  186655. * png_start_read_image() if png_set_interlace_handling() wasn't called
  186656. * prior to either of these functions like it should have been. You can
  186657. * only call this function once. If you desire to have an image for
  186658. * each pass of a interlaced image, use png_read_rows() instead.
  186659. *
  186660. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  186661. */
  186662. void PNGAPI
  186663. png_read_image(png_structp png_ptr, png_bytepp image)
  186664. {
  186665. png_uint_32 i,image_height;
  186666. int pass, j;
  186667. png_bytepp rp;
  186668. png_debug(1, "in png_read_image\n");
  186669. if(png_ptr == NULL) return;
  186670. #ifdef PNG_READ_INTERLACING_SUPPORTED
  186671. pass = png_set_interlace_handling(png_ptr);
  186672. #else
  186673. if (png_ptr->interlaced)
  186674. png_error(png_ptr,
  186675. "Cannot read interlaced image -- interlace handler disabled.");
  186676. pass = 1;
  186677. #endif
  186678. image_height=png_ptr->height;
  186679. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  186680. for (j = 0; j < pass; j++)
  186681. {
  186682. rp = image;
  186683. for (i = 0; i < image_height; i++)
  186684. {
  186685. png_read_row(png_ptr, *rp, png_bytep_NULL);
  186686. rp++;
  186687. }
  186688. }
  186689. }
  186690. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186691. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186692. /* Read the end of the PNG file. Will not read past the end of the
  186693. * file, will verify the end is accurate, and will read any comments
  186694. * or time information at the end of the file, if info is not NULL.
  186695. */
  186696. void PNGAPI
  186697. png_read_end(png_structp png_ptr, png_infop info_ptr)
  186698. {
  186699. png_byte chunk_length[4];
  186700. png_uint_32 length;
  186701. png_debug(1, "in png_read_end\n");
  186702. if(png_ptr == NULL) return;
  186703. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  186704. do
  186705. {
  186706. #ifdef PNG_USE_LOCAL_ARRAYS
  186707. PNG_CONST PNG_IHDR;
  186708. PNG_CONST PNG_IDAT;
  186709. PNG_CONST PNG_IEND;
  186710. PNG_CONST PNG_PLTE;
  186711. #if defined(PNG_READ_bKGD_SUPPORTED)
  186712. PNG_CONST PNG_bKGD;
  186713. #endif
  186714. #if defined(PNG_READ_cHRM_SUPPORTED)
  186715. PNG_CONST PNG_cHRM;
  186716. #endif
  186717. #if defined(PNG_READ_gAMA_SUPPORTED)
  186718. PNG_CONST PNG_gAMA;
  186719. #endif
  186720. #if defined(PNG_READ_hIST_SUPPORTED)
  186721. PNG_CONST PNG_hIST;
  186722. #endif
  186723. #if defined(PNG_READ_iCCP_SUPPORTED)
  186724. PNG_CONST PNG_iCCP;
  186725. #endif
  186726. #if defined(PNG_READ_iTXt_SUPPORTED)
  186727. PNG_CONST PNG_iTXt;
  186728. #endif
  186729. #if defined(PNG_READ_oFFs_SUPPORTED)
  186730. PNG_CONST PNG_oFFs;
  186731. #endif
  186732. #if defined(PNG_READ_pCAL_SUPPORTED)
  186733. PNG_CONST PNG_pCAL;
  186734. #endif
  186735. #if defined(PNG_READ_pHYs_SUPPORTED)
  186736. PNG_CONST PNG_pHYs;
  186737. #endif
  186738. #if defined(PNG_READ_sBIT_SUPPORTED)
  186739. PNG_CONST PNG_sBIT;
  186740. #endif
  186741. #if defined(PNG_READ_sCAL_SUPPORTED)
  186742. PNG_CONST PNG_sCAL;
  186743. #endif
  186744. #if defined(PNG_READ_sPLT_SUPPORTED)
  186745. PNG_CONST PNG_sPLT;
  186746. #endif
  186747. #if defined(PNG_READ_sRGB_SUPPORTED)
  186748. PNG_CONST PNG_sRGB;
  186749. #endif
  186750. #if defined(PNG_READ_tEXt_SUPPORTED)
  186751. PNG_CONST PNG_tEXt;
  186752. #endif
  186753. #if defined(PNG_READ_tIME_SUPPORTED)
  186754. PNG_CONST PNG_tIME;
  186755. #endif
  186756. #if defined(PNG_READ_tRNS_SUPPORTED)
  186757. PNG_CONST PNG_tRNS;
  186758. #endif
  186759. #if defined(PNG_READ_zTXt_SUPPORTED)
  186760. PNG_CONST PNG_zTXt;
  186761. #endif
  186762. #endif /* PNG_USE_LOCAL_ARRAYS */
  186763. png_read_data(png_ptr, chunk_length, 4);
  186764. length = png_get_uint_31(png_ptr,chunk_length);
  186765. png_reset_crc(png_ptr);
  186766. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186767. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  186768. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  186769. png_handle_IHDR(png_ptr, info_ptr, length);
  186770. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  186771. png_handle_IEND(png_ptr, info_ptr, length);
  186772. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186773. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  186774. {
  186775. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186776. {
  186777. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  186778. png_error(png_ptr, "Too many IDAT's found");
  186779. }
  186780. png_handle_unknown(png_ptr, info_ptr, length);
  186781. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186782. png_ptr->mode |= PNG_HAVE_PLTE;
  186783. }
  186784. #endif
  186785. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186786. {
  186787. /* Zero length IDATs are legal after the last IDAT has been
  186788. * read, but not after other chunks have been read.
  186789. */
  186790. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  186791. png_error(png_ptr, "Too many IDAT's found");
  186792. png_crc_finish(png_ptr, length);
  186793. }
  186794. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186795. png_handle_PLTE(png_ptr, info_ptr, length);
  186796. #if defined(PNG_READ_bKGD_SUPPORTED)
  186797. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  186798. png_handle_bKGD(png_ptr, info_ptr, length);
  186799. #endif
  186800. #if defined(PNG_READ_cHRM_SUPPORTED)
  186801. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  186802. png_handle_cHRM(png_ptr, info_ptr, length);
  186803. #endif
  186804. #if defined(PNG_READ_gAMA_SUPPORTED)
  186805. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  186806. png_handle_gAMA(png_ptr, info_ptr, length);
  186807. #endif
  186808. #if defined(PNG_READ_hIST_SUPPORTED)
  186809. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  186810. png_handle_hIST(png_ptr, info_ptr, length);
  186811. #endif
  186812. #if defined(PNG_READ_oFFs_SUPPORTED)
  186813. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  186814. png_handle_oFFs(png_ptr, info_ptr, length);
  186815. #endif
  186816. #if defined(PNG_READ_pCAL_SUPPORTED)
  186817. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  186818. png_handle_pCAL(png_ptr, info_ptr, length);
  186819. #endif
  186820. #if defined(PNG_READ_sCAL_SUPPORTED)
  186821. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  186822. png_handle_sCAL(png_ptr, info_ptr, length);
  186823. #endif
  186824. #if defined(PNG_READ_pHYs_SUPPORTED)
  186825. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  186826. png_handle_pHYs(png_ptr, info_ptr, length);
  186827. #endif
  186828. #if defined(PNG_READ_sBIT_SUPPORTED)
  186829. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  186830. png_handle_sBIT(png_ptr, info_ptr, length);
  186831. #endif
  186832. #if defined(PNG_READ_sRGB_SUPPORTED)
  186833. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  186834. png_handle_sRGB(png_ptr, info_ptr, length);
  186835. #endif
  186836. #if defined(PNG_READ_iCCP_SUPPORTED)
  186837. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  186838. png_handle_iCCP(png_ptr, info_ptr, length);
  186839. #endif
  186840. #if defined(PNG_READ_sPLT_SUPPORTED)
  186841. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  186842. png_handle_sPLT(png_ptr, info_ptr, length);
  186843. #endif
  186844. #if defined(PNG_READ_tEXt_SUPPORTED)
  186845. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  186846. png_handle_tEXt(png_ptr, info_ptr, length);
  186847. #endif
  186848. #if defined(PNG_READ_tIME_SUPPORTED)
  186849. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  186850. png_handle_tIME(png_ptr, info_ptr, length);
  186851. #endif
  186852. #if defined(PNG_READ_tRNS_SUPPORTED)
  186853. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  186854. png_handle_tRNS(png_ptr, info_ptr, length);
  186855. #endif
  186856. #if defined(PNG_READ_zTXt_SUPPORTED)
  186857. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  186858. png_handle_zTXt(png_ptr, info_ptr, length);
  186859. #endif
  186860. #if defined(PNG_READ_iTXt_SUPPORTED)
  186861. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  186862. png_handle_iTXt(png_ptr, info_ptr, length);
  186863. #endif
  186864. else
  186865. png_handle_unknown(png_ptr, info_ptr, length);
  186866. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  186867. }
  186868. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186869. /* free all memory used by the read */
  186870. void PNGAPI
  186871. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  186872. png_infopp end_info_ptr_ptr)
  186873. {
  186874. png_structp png_ptr = NULL;
  186875. png_infop info_ptr = NULL, end_info_ptr = NULL;
  186876. #ifdef PNG_USER_MEM_SUPPORTED
  186877. png_free_ptr free_fn;
  186878. png_voidp mem_ptr;
  186879. #endif
  186880. png_debug(1, "in png_destroy_read_struct\n");
  186881. if (png_ptr_ptr != NULL)
  186882. png_ptr = *png_ptr_ptr;
  186883. if (info_ptr_ptr != NULL)
  186884. info_ptr = *info_ptr_ptr;
  186885. if (end_info_ptr_ptr != NULL)
  186886. end_info_ptr = *end_info_ptr_ptr;
  186887. #ifdef PNG_USER_MEM_SUPPORTED
  186888. free_fn = png_ptr->free_fn;
  186889. mem_ptr = png_ptr->mem_ptr;
  186890. #endif
  186891. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  186892. if (info_ptr != NULL)
  186893. {
  186894. #if defined(PNG_TEXT_SUPPORTED)
  186895. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  186896. #endif
  186897. #ifdef PNG_USER_MEM_SUPPORTED
  186898. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  186899. (png_voidp)mem_ptr);
  186900. #else
  186901. png_destroy_struct((png_voidp)info_ptr);
  186902. #endif
  186903. *info_ptr_ptr = NULL;
  186904. }
  186905. if (end_info_ptr != NULL)
  186906. {
  186907. #if defined(PNG_READ_TEXT_SUPPORTED)
  186908. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  186909. #endif
  186910. #ifdef PNG_USER_MEM_SUPPORTED
  186911. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  186912. (png_voidp)mem_ptr);
  186913. #else
  186914. png_destroy_struct((png_voidp)end_info_ptr);
  186915. #endif
  186916. *end_info_ptr_ptr = NULL;
  186917. }
  186918. if (png_ptr != NULL)
  186919. {
  186920. #ifdef PNG_USER_MEM_SUPPORTED
  186921. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  186922. (png_voidp)mem_ptr);
  186923. #else
  186924. png_destroy_struct((png_voidp)png_ptr);
  186925. #endif
  186926. *png_ptr_ptr = NULL;
  186927. }
  186928. }
  186929. /* free all memory used by the read (old method) */
  186930. void /* PRIVATE */
  186931. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  186932. {
  186933. #ifdef PNG_SETJMP_SUPPORTED
  186934. jmp_buf tmp_jmp;
  186935. #endif
  186936. png_error_ptr error_fn;
  186937. png_error_ptr warning_fn;
  186938. png_voidp error_ptr;
  186939. #ifdef PNG_USER_MEM_SUPPORTED
  186940. png_free_ptr free_fn;
  186941. #endif
  186942. png_debug(1, "in png_read_destroy\n");
  186943. if (info_ptr != NULL)
  186944. png_info_destroy(png_ptr, info_ptr);
  186945. if (end_info_ptr != NULL)
  186946. png_info_destroy(png_ptr, end_info_ptr);
  186947. png_free(png_ptr, png_ptr->zbuf);
  186948. png_free(png_ptr, png_ptr->big_row_buf);
  186949. png_free(png_ptr, png_ptr->prev_row);
  186950. #if defined(PNG_READ_DITHER_SUPPORTED)
  186951. png_free(png_ptr, png_ptr->palette_lookup);
  186952. png_free(png_ptr, png_ptr->dither_index);
  186953. #endif
  186954. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186955. png_free(png_ptr, png_ptr->gamma_table);
  186956. #endif
  186957. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186958. png_free(png_ptr, png_ptr->gamma_from_1);
  186959. png_free(png_ptr, png_ptr->gamma_to_1);
  186960. #endif
  186961. #ifdef PNG_FREE_ME_SUPPORTED
  186962. if (png_ptr->free_me & PNG_FREE_PLTE)
  186963. png_zfree(png_ptr, png_ptr->palette);
  186964. png_ptr->free_me &= ~PNG_FREE_PLTE;
  186965. #else
  186966. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  186967. png_zfree(png_ptr, png_ptr->palette);
  186968. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  186969. #endif
  186970. #if defined(PNG_tRNS_SUPPORTED) || \
  186971. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186972. #ifdef PNG_FREE_ME_SUPPORTED
  186973. if (png_ptr->free_me & PNG_FREE_TRNS)
  186974. png_free(png_ptr, png_ptr->trans);
  186975. png_ptr->free_me &= ~PNG_FREE_TRNS;
  186976. #else
  186977. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  186978. png_free(png_ptr, png_ptr->trans);
  186979. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  186980. #endif
  186981. #endif
  186982. #if defined(PNG_READ_hIST_SUPPORTED)
  186983. #ifdef PNG_FREE_ME_SUPPORTED
  186984. if (png_ptr->free_me & PNG_FREE_HIST)
  186985. png_free(png_ptr, png_ptr->hist);
  186986. png_ptr->free_me &= ~PNG_FREE_HIST;
  186987. #else
  186988. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  186989. png_free(png_ptr, png_ptr->hist);
  186990. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  186991. #endif
  186992. #endif
  186993. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186994. if (png_ptr->gamma_16_table != NULL)
  186995. {
  186996. int i;
  186997. int istop = (1 << (8 - png_ptr->gamma_shift));
  186998. for (i = 0; i < istop; i++)
  186999. {
  187000. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187001. }
  187002. png_free(png_ptr, png_ptr->gamma_16_table);
  187003. }
  187004. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187005. if (png_ptr->gamma_16_from_1 != NULL)
  187006. {
  187007. int i;
  187008. int istop = (1 << (8 - png_ptr->gamma_shift));
  187009. for (i = 0; i < istop; i++)
  187010. {
  187011. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187012. }
  187013. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187014. }
  187015. if (png_ptr->gamma_16_to_1 != NULL)
  187016. {
  187017. int i;
  187018. int istop = (1 << (8 - png_ptr->gamma_shift));
  187019. for (i = 0; i < istop; i++)
  187020. {
  187021. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187022. }
  187023. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187024. }
  187025. #endif
  187026. #endif
  187027. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187028. png_free(png_ptr, png_ptr->time_buffer);
  187029. #endif
  187030. inflateEnd(&png_ptr->zstream);
  187031. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187032. png_free(png_ptr, png_ptr->save_buffer);
  187033. #endif
  187034. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187035. #ifdef PNG_TEXT_SUPPORTED
  187036. png_free(png_ptr, png_ptr->current_text);
  187037. #endif /* PNG_TEXT_SUPPORTED */
  187038. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187039. /* Save the important info out of the png_struct, in case it is
  187040. * being used again.
  187041. */
  187042. #ifdef PNG_SETJMP_SUPPORTED
  187043. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187044. #endif
  187045. error_fn = png_ptr->error_fn;
  187046. warning_fn = png_ptr->warning_fn;
  187047. error_ptr = png_ptr->error_ptr;
  187048. #ifdef PNG_USER_MEM_SUPPORTED
  187049. free_fn = png_ptr->free_fn;
  187050. #endif
  187051. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187052. png_ptr->error_fn = error_fn;
  187053. png_ptr->warning_fn = warning_fn;
  187054. png_ptr->error_ptr = error_ptr;
  187055. #ifdef PNG_USER_MEM_SUPPORTED
  187056. png_ptr->free_fn = free_fn;
  187057. #endif
  187058. #ifdef PNG_SETJMP_SUPPORTED
  187059. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187060. #endif
  187061. }
  187062. void PNGAPI
  187063. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187064. {
  187065. if(png_ptr == NULL) return;
  187066. png_ptr->read_row_fn = read_row_fn;
  187067. }
  187068. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187069. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187070. void PNGAPI
  187071. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187072. int transforms,
  187073. voidp params)
  187074. {
  187075. int row;
  187076. if(png_ptr == NULL) return;
  187077. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187078. /* invert the alpha channel from opacity to transparency
  187079. */
  187080. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187081. png_set_invert_alpha(png_ptr);
  187082. #endif
  187083. /* png_read_info() gives us all of the information from the
  187084. * PNG file before the first IDAT (image data chunk).
  187085. */
  187086. png_read_info(png_ptr, info_ptr);
  187087. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187088. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187089. /* -------------- image transformations start here ------------------- */
  187090. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187091. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187092. */
  187093. if (transforms & PNG_TRANSFORM_STRIP_16)
  187094. png_set_strip_16(png_ptr);
  187095. #endif
  187096. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187097. /* Strip alpha bytes from the input data without combining with
  187098. * the background (not recommended).
  187099. */
  187100. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187101. png_set_strip_alpha(png_ptr);
  187102. #endif
  187103. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187104. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187105. * byte into separate bytes (useful for paletted and grayscale images).
  187106. */
  187107. if (transforms & PNG_TRANSFORM_PACKING)
  187108. png_set_packing(png_ptr);
  187109. #endif
  187110. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187111. /* Change the order of packed pixels to least significant bit first
  187112. * (not useful if you are using png_set_packing).
  187113. */
  187114. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187115. png_set_packswap(png_ptr);
  187116. #endif
  187117. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187118. /* Expand paletted colors into true RGB triplets
  187119. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187120. * Expand paletted or RGB images with transparency to full alpha
  187121. * channels so the data will be available as RGBA quartets.
  187122. */
  187123. if (transforms & PNG_TRANSFORM_EXPAND)
  187124. if ((png_ptr->bit_depth < 8) ||
  187125. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187126. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  187127. png_set_expand(png_ptr);
  187128. #endif
  187129. /* We don't handle background color or gamma transformation or dithering.
  187130. */
  187131. #if defined(PNG_READ_INVERT_SUPPORTED)
  187132. /* invert monochrome files to have 0 as white and 1 as black
  187133. */
  187134. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  187135. png_set_invert_mono(png_ptr);
  187136. #endif
  187137. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187138. /* If you want to shift the pixel values from the range [0,255] or
  187139. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  187140. * colors were originally in:
  187141. */
  187142. if ((transforms & PNG_TRANSFORM_SHIFT)
  187143. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  187144. {
  187145. png_color_8p sig_bit;
  187146. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  187147. png_set_shift(png_ptr, sig_bit);
  187148. }
  187149. #endif
  187150. #if defined(PNG_READ_BGR_SUPPORTED)
  187151. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  187152. */
  187153. if (transforms & PNG_TRANSFORM_BGR)
  187154. png_set_bgr(png_ptr);
  187155. #endif
  187156. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187157. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  187158. */
  187159. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  187160. png_set_swap_alpha(png_ptr);
  187161. #endif
  187162. #if defined(PNG_READ_SWAP_SUPPORTED)
  187163. /* swap bytes of 16 bit files to least significant byte first
  187164. */
  187165. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  187166. png_set_swap(png_ptr);
  187167. #endif
  187168. /* We don't handle adding filler bytes */
  187169. /* Optional call to gamma correct and add the background to the palette
  187170. * and update info structure. REQUIRED if you are expecting libpng to
  187171. * update the palette for you (i.e., you selected such a transform above).
  187172. */
  187173. png_read_update_info(png_ptr, info_ptr);
  187174. /* -------------- image transformations end here ------------------- */
  187175. #ifdef PNG_FREE_ME_SUPPORTED
  187176. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  187177. #endif
  187178. if(info_ptr->row_pointers == NULL)
  187179. {
  187180. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  187181. info_ptr->height * png_sizeof(png_bytep));
  187182. #ifdef PNG_FREE_ME_SUPPORTED
  187183. info_ptr->free_me |= PNG_FREE_ROWS;
  187184. #endif
  187185. for (row = 0; row < (int)info_ptr->height; row++)
  187186. {
  187187. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  187188. png_get_rowbytes(png_ptr, info_ptr));
  187189. }
  187190. }
  187191. png_read_image(png_ptr, info_ptr->row_pointers);
  187192. info_ptr->valid |= PNG_INFO_IDAT;
  187193. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  187194. png_read_end(png_ptr, info_ptr);
  187195. transforms = transforms; /* quiet compiler warnings */
  187196. params = params;
  187197. }
  187198. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  187199. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187200. #endif /* PNG_READ_SUPPORTED */
  187201. /*** End of inlined file: pngread.c ***/
  187202. /*** Start of inlined file: pngpread.c ***/
  187203. /* pngpread.c - read a png file in push mode
  187204. *
  187205. * Last changed in libpng 1.2.21 October 4, 2007
  187206. * For conditions of distribution and use, see copyright notice in png.h
  187207. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187208. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187209. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187210. */
  187211. #define PNG_INTERNAL
  187212. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187213. /* push model modes */
  187214. #define PNG_READ_SIG_MODE 0
  187215. #define PNG_READ_CHUNK_MODE 1
  187216. #define PNG_READ_IDAT_MODE 2
  187217. #define PNG_SKIP_MODE 3
  187218. #define PNG_READ_tEXt_MODE 4
  187219. #define PNG_READ_zTXt_MODE 5
  187220. #define PNG_READ_DONE_MODE 6
  187221. #define PNG_READ_iTXt_MODE 7
  187222. #define PNG_ERROR_MODE 8
  187223. void PNGAPI
  187224. png_process_data(png_structp png_ptr, png_infop info_ptr,
  187225. png_bytep buffer, png_size_t buffer_size)
  187226. {
  187227. if(png_ptr == NULL) return;
  187228. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  187229. while (png_ptr->buffer_size)
  187230. {
  187231. png_process_some_data(png_ptr, info_ptr);
  187232. }
  187233. }
  187234. /* What we do with the incoming data depends on what we were previously
  187235. * doing before we ran out of data...
  187236. */
  187237. void /* PRIVATE */
  187238. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  187239. {
  187240. if(png_ptr == NULL) return;
  187241. switch (png_ptr->process_mode)
  187242. {
  187243. case PNG_READ_SIG_MODE:
  187244. {
  187245. png_push_read_sig(png_ptr, info_ptr);
  187246. break;
  187247. }
  187248. case PNG_READ_CHUNK_MODE:
  187249. {
  187250. png_push_read_chunk(png_ptr, info_ptr);
  187251. break;
  187252. }
  187253. case PNG_READ_IDAT_MODE:
  187254. {
  187255. png_push_read_IDAT(png_ptr);
  187256. break;
  187257. }
  187258. #if defined(PNG_READ_tEXt_SUPPORTED)
  187259. case PNG_READ_tEXt_MODE:
  187260. {
  187261. png_push_read_tEXt(png_ptr, info_ptr);
  187262. break;
  187263. }
  187264. #endif
  187265. #if defined(PNG_READ_zTXt_SUPPORTED)
  187266. case PNG_READ_zTXt_MODE:
  187267. {
  187268. png_push_read_zTXt(png_ptr, info_ptr);
  187269. break;
  187270. }
  187271. #endif
  187272. #if defined(PNG_READ_iTXt_SUPPORTED)
  187273. case PNG_READ_iTXt_MODE:
  187274. {
  187275. png_push_read_iTXt(png_ptr, info_ptr);
  187276. break;
  187277. }
  187278. #endif
  187279. case PNG_SKIP_MODE:
  187280. {
  187281. png_push_crc_finish(png_ptr);
  187282. break;
  187283. }
  187284. default:
  187285. {
  187286. png_ptr->buffer_size = 0;
  187287. break;
  187288. }
  187289. }
  187290. }
  187291. /* Read any remaining signature bytes from the stream and compare them with
  187292. * the correct PNG signature. It is possible that this routine is called
  187293. * with bytes already read from the signature, either because they have been
  187294. * checked by the calling application, or because of multiple calls to this
  187295. * routine.
  187296. */
  187297. void /* PRIVATE */
  187298. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  187299. {
  187300. png_size_t num_checked = png_ptr->sig_bytes,
  187301. num_to_check = 8 - num_checked;
  187302. if (png_ptr->buffer_size < num_to_check)
  187303. {
  187304. num_to_check = png_ptr->buffer_size;
  187305. }
  187306. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  187307. num_to_check);
  187308. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  187309. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187310. {
  187311. if (num_checked < 4 &&
  187312. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187313. png_error(png_ptr, "Not a PNG file");
  187314. else
  187315. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187316. }
  187317. else
  187318. {
  187319. if (png_ptr->sig_bytes >= 8)
  187320. {
  187321. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187322. }
  187323. }
  187324. }
  187325. void /* PRIVATE */
  187326. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  187327. {
  187328. #ifdef PNG_USE_LOCAL_ARRAYS
  187329. PNG_CONST PNG_IHDR;
  187330. PNG_CONST PNG_IDAT;
  187331. PNG_CONST PNG_IEND;
  187332. PNG_CONST PNG_PLTE;
  187333. #if defined(PNG_READ_bKGD_SUPPORTED)
  187334. PNG_CONST PNG_bKGD;
  187335. #endif
  187336. #if defined(PNG_READ_cHRM_SUPPORTED)
  187337. PNG_CONST PNG_cHRM;
  187338. #endif
  187339. #if defined(PNG_READ_gAMA_SUPPORTED)
  187340. PNG_CONST PNG_gAMA;
  187341. #endif
  187342. #if defined(PNG_READ_hIST_SUPPORTED)
  187343. PNG_CONST PNG_hIST;
  187344. #endif
  187345. #if defined(PNG_READ_iCCP_SUPPORTED)
  187346. PNG_CONST PNG_iCCP;
  187347. #endif
  187348. #if defined(PNG_READ_iTXt_SUPPORTED)
  187349. PNG_CONST PNG_iTXt;
  187350. #endif
  187351. #if defined(PNG_READ_oFFs_SUPPORTED)
  187352. PNG_CONST PNG_oFFs;
  187353. #endif
  187354. #if defined(PNG_READ_pCAL_SUPPORTED)
  187355. PNG_CONST PNG_pCAL;
  187356. #endif
  187357. #if defined(PNG_READ_pHYs_SUPPORTED)
  187358. PNG_CONST PNG_pHYs;
  187359. #endif
  187360. #if defined(PNG_READ_sBIT_SUPPORTED)
  187361. PNG_CONST PNG_sBIT;
  187362. #endif
  187363. #if defined(PNG_READ_sCAL_SUPPORTED)
  187364. PNG_CONST PNG_sCAL;
  187365. #endif
  187366. #if defined(PNG_READ_sRGB_SUPPORTED)
  187367. PNG_CONST PNG_sRGB;
  187368. #endif
  187369. #if defined(PNG_READ_sPLT_SUPPORTED)
  187370. PNG_CONST PNG_sPLT;
  187371. #endif
  187372. #if defined(PNG_READ_tEXt_SUPPORTED)
  187373. PNG_CONST PNG_tEXt;
  187374. #endif
  187375. #if defined(PNG_READ_tIME_SUPPORTED)
  187376. PNG_CONST PNG_tIME;
  187377. #endif
  187378. #if defined(PNG_READ_tRNS_SUPPORTED)
  187379. PNG_CONST PNG_tRNS;
  187380. #endif
  187381. #if defined(PNG_READ_zTXt_SUPPORTED)
  187382. PNG_CONST PNG_zTXt;
  187383. #endif
  187384. #endif /* PNG_USE_LOCAL_ARRAYS */
  187385. /* First we make sure we have enough data for the 4 byte chunk name
  187386. * and the 4 byte chunk length before proceeding with decoding the
  187387. * chunk data. To fully decode each of these chunks, we also make
  187388. * sure we have enough data in the buffer for the 4 byte CRC at the
  187389. * end of every chunk (except IDAT, which is handled separately).
  187390. */
  187391. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  187392. {
  187393. png_byte chunk_length[4];
  187394. if (png_ptr->buffer_size < 8)
  187395. {
  187396. png_push_save_buffer(png_ptr);
  187397. return;
  187398. }
  187399. png_push_fill_buffer(png_ptr, chunk_length, 4);
  187400. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  187401. png_reset_crc(png_ptr);
  187402. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187403. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  187404. }
  187405. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187406. if(png_ptr->mode & PNG_AFTER_IDAT)
  187407. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187408. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187409. {
  187410. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187411. {
  187412. png_push_save_buffer(png_ptr);
  187413. return;
  187414. }
  187415. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  187416. }
  187417. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187418. {
  187419. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187420. {
  187421. png_push_save_buffer(png_ptr);
  187422. return;
  187423. }
  187424. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  187425. png_ptr->process_mode = PNG_READ_DONE_MODE;
  187426. png_push_have_end(png_ptr, info_ptr);
  187427. }
  187428. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187429. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187430. {
  187431. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187432. {
  187433. png_push_save_buffer(png_ptr);
  187434. return;
  187435. }
  187436. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187437. png_ptr->mode |= PNG_HAVE_IDAT;
  187438. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  187439. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187440. png_ptr->mode |= PNG_HAVE_PLTE;
  187441. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187442. {
  187443. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187444. png_error(png_ptr, "Missing IHDR before IDAT");
  187445. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187446. !(png_ptr->mode & PNG_HAVE_PLTE))
  187447. png_error(png_ptr, "Missing PLTE before IDAT");
  187448. }
  187449. }
  187450. #endif
  187451. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187452. {
  187453. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187454. {
  187455. png_push_save_buffer(png_ptr);
  187456. return;
  187457. }
  187458. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  187459. }
  187460. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187461. {
  187462. /* If we reach an IDAT chunk, this means we have read all of the
  187463. * header chunks, and we can start reading the image (or if this
  187464. * is called after the image has been read - we have an error).
  187465. */
  187466. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187467. png_error(png_ptr, "Missing IHDR before IDAT");
  187468. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187469. !(png_ptr->mode & PNG_HAVE_PLTE))
  187470. png_error(png_ptr, "Missing PLTE before IDAT");
  187471. if (png_ptr->mode & PNG_HAVE_IDAT)
  187472. {
  187473. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187474. if (png_ptr->push_length == 0)
  187475. return;
  187476. if (png_ptr->mode & PNG_AFTER_IDAT)
  187477. png_error(png_ptr, "Too many IDAT's found");
  187478. }
  187479. png_ptr->idat_size = png_ptr->push_length;
  187480. png_ptr->mode |= PNG_HAVE_IDAT;
  187481. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  187482. png_push_have_info(png_ptr, info_ptr);
  187483. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187484. png_ptr->zstream.next_out = png_ptr->row_buf;
  187485. return;
  187486. }
  187487. #if defined(PNG_READ_gAMA_SUPPORTED)
  187488. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187489. {
  187490. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187491. {
  187492. png_push_save_buffer(png_ptr);
  187493. return;
  187494. }
  187495. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  187496. }
  187497. #endif
  187498. #if defined(PNG_READ_sBIT_SUPPORTED)
  187499. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187500. {
  187501. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187502. {
  187503. png_push_save_buffer(png_ptr);
  187504. return;
  187505. }
  187506. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  187507. }
  187508. #endif
  187509. #if defined(PNG_READ_cHRM_SUPPORTED)
  187510. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187511. {
  187512. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187513. {
  187514. png_push_save_buffer(png_ptr);
  187515. return;
  187516. }
  187517. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  187518. }
  187519. #endif
  187520. #if defined(PNG_READ_sRGB_SUPPORTED)
  187521. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187522. {
  187523. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187524. {
  187525. png_push_save_buffer(png_ptr);
  187526. return;
  187527. }
  187528. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  187529. }
  187530. #endif
  187531. #if defined(PNG_READ_iCCP_SUPPORTED)
  187532. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187533. {
  187534. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187535. {
  187536. png_push_save_buffer(png_ptr);
  187537. return;
  187538. }
  187539. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  187540. }
  187541. #endif
  187542. #if defined(PNG_READ_sPLT_SUPPORTED)
  187543. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187544. {
  187545. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187546. {
  187547. png_push_save_buffer(png_ptr);
  187548. return;
  187549. }
  187550. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  187551. }
  187552. #endif
  187553. #if defined(PNG_READ_tRNS_SUPPORTED)
  187554. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187555. {
  187556. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187557. {
  187558. png_push_save_buffer(png_ptr);
  187559. return;
  187560. }
  187561. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  187562. }
  187563. #endif
  187564. #if defined(PNG_READ_bKGD_SUPPORTED)
  187565. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187566. {
  187567. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187568. {
  187569. png_push_save_buffer(png_ptr);
  187570. return;
  187571. }
  187572. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  187573. }
  187574. #endif
  187575. #if defined(PNG_READ_hIST_SUPPORTED)
  187576. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187577. {
  187578. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187579. {
  187580. png_push_save_buffer(png_ptr);
  187581. return;
  187582. }
  187583. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  187584. }
  187585. #endif
  187586. #if defined(PNG_READ_pHYs_SUPPORTED)
  187587. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187588. {
  187589. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187590. {
  187591. png_push_save_buffer(png_ptr);
  187592. return;
  187593. }
  187594. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  187595. }
  187596. #endif
  187597. #if defined(PNG_READ_oFFs_SUPPORTED)
  187598. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187599. {
  187600. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187601. {
  187602. png_push_save_buffer(png_ptr);
  187603. return;
  187604. }
  187605. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  187606. }
  187607. #endif
  187608. #if defined(PNG_READ_pCAL_SUPPORTED)
  187609. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187610. {
  187611. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187612. {
  187613. png_push_save_buffer(png_ptr);
  187614. return;
  187615. }
  187616. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  187617. }
  187618. #endif
  187619. #if defined(PNG_READ_sCAL_SUPPORTED)
  187620. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187621. {
  187622. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187623. {
  187624. png_push_save_buffer(png_ptr);
  187625. return;
  187626. }
  187627. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  187628. }
  187629. #endif
  187630. #if defined(PNG_READ_tIME_SUPPORTED)
  187631. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187632. {
  187633. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187634. {
  187635. png_push_save_buffer(png_ptr);
  187636. return;
  187637. }
  187638. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  187639. }
  187640. #endif
  187641. #if defined(PNG_READ_tEXt_SUPPORTED)
  187642. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187643. {
  187644. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187645. {
  187646. png_push_save_buffer(png_ptr);
  187647. return;
  187648. }
  187649. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  187650. }
  187651. #endif
  187652. #if defined(PNG_READ_zTXt_SUPPORTED)
  187653. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187654. {
  187655. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187656. {
  187657. png_push_save_buffer(png_ptr);
  187658. return;
  187659. }
  187660. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  187661. }
  187662. #endif
  187663. #if defined(PNG_READ_iTXt_SUPPORTED)
  187664. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187665. {
  187666. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187667. {
  187668. png_push_save_buffer(png_ptr);
  187669. return;
  187670. }
  187671. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  187672. }
  187673. #endif
  187674. else
  187675. {
  187676. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187677. {
  187678. png_push_save_buffer(png_ptr);
  187679. return;
  187680. }
  187681. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  187682. }
  187683. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  187684. }
  187685. void /* PRIVATE */
  187686. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  187687. {
  187688. png_ptr->process_mode = PNG_SKIP_MODE;
  187689. png_ptr->skip_length = skip;
  187690. }
  187691. void /* PRIVATE */
  187692. png_push_crc_finish(png_structp png_ptr)
  187693. {
  187694. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  187695. {
  187696. png_size_t save_size;
  187697. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  187698. save_size = (png_size_t)png_ptr->skip_length;
  187699. else
  187700. save_size = png_ptr->save_buffer_size;
  187701. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  187702. png_ptr->skip_length -= save_size;
  187703. png_ptr->buffer_size -= save_size;
  187704. png_ptr->save_buffer_size -= save_size;
  187705. png_ptr->save_buffer_ptr += save_size;
  187706. }
  187707. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  187708. {
  187709. png_size_t save_size;
  187710. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  187711. save_size = (png_size_t)png_ptr->skip_length;
  187712. else
  187713. save_size = png_ptr->current_buffer_size;
  187714. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  187715. png_ptr->skip_length -= save_size;
  187716. png_ptr->buffer_size -= save_size;
  187717. png_ptr->current_buffer_size -= save_size;
  187718. png_ptr->current_buffer_ptr += save_size;
  187719. }
  187720. if (!png_ptr->skip_length)
  187721. {
  187722. if (png_ptr->buffer_size < 4)
  187723. {
  187724. png_push_save_buffer(png_ptr);
  187725. return;
  187726. }
  187727. png_crc_finish(png_ptr, 0);
  187728. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187729. }
  187730. }
  187731. void PNGAPI
  187732. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  187733. {
  187734. png_bytep ptr;
  187735. if(png_ptr == NULL) return;
  187736. ptr = buffer;
  187737. if (png_ptr->save_buffer_size)
  187738. {
  187739. png_size_t save_size;
  187740. if (length < png_ptr->save_buffer_size)
  187741. save_size = length;
  187742. else
  187743. save_size = png_ptr->save_buffer_size;
  187744. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  187745. length -= save_size;
  187746. ptr += save_size;
  187747. png_ptr->buffer_size -= save_size;
  187748. png_ptr->save_buffer_size -= save_size;
  187749. png_ptr->save_buffer_ptr += save_size;
  187750. }
  187751. if (length && png_ptr->current_buffer_size)
  187752. {
  187753. png_size_t save_size;
  187754. if (length < png_ptr->current_buffer_size)
  187755. save_size = length;
  187756. else
  187757. save_size = png_ptr->current_buffer_size;
  187758. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  187759. png_ptr->buffer_size -= save_size;
  187760. png_ptr->current_buffer_size -= save_size;
  187761. png_ptr->current_buffer_ptr += save_size;
  187762. }
  187763. }
  187764. void /* PRIVATE */
  187765. png_push_save_buffer(png_structp png_ptr)
  187766. {
  187767. if (png_ptr->save_buffer_size)
  187768. {
  187769. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  187770. {
  187771. png_size_t i,istop;
  187772. png_bytep sp;
  187773. png_bytep dp;
  187774. istop = png_ptr->save_buffer_size;
  187775. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  187776. i < istop; i++, sp++, dp++)
  187777. {
  187778. *dp = *sp;
  187779. }
  187780. }
  187781. }
  187782. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  187783. png_ptr->save_buffer_max)
  187784. {
  187785. png_size_t new_max;
  187786. png_bytep old_buffer;
  187787. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  187788. (png_ptr->current_buffer_size + 256))
  187789. {
  187790. png_error(png_ptr, "Potential overflow of save_buffer");
  187791. }
  187792. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  187793. old_buffer = png_ptr->save_buffer;
  187794. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  187795. (png_uint_32)new_max);
  187796. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  187797. png_free(png_ptr, old_buffer);
  187798. png_ptr->save_buffer_max = new_max;
  187799. }
  187800. if (png_ptr->current_buffer_size)
  187801. {
  187802. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  187803. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  187804. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  187805. png_ptr->current_buffer_size = 0;
  187806. }
  187807. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  187808. png_ptr->buffer_size = 0;
  187809. }
  187810. void /* PRIVATE */
  187811. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  187812. png_size_t buffer_length)
  187813. {
  187814. png_ptr->current_buffer = buffer;
  187815. png_ptr->current_buffer_size = buffer_length;
  187816. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  187817. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  187818. }
  187819. void /* PRIVATE */
  187820. png_push_read_IDAT(png_structp png_ptr)
  187821. {
  187822. #ifdef PNG_USE_LOCAL_ARRAYS
  187823. PNG_CONST PNG_IDAT;
  187824. #endif
  187825. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  187826. {
  187827. png_byte chunk_length[4];
  187828. if (png_ptr->buffer_size < 8)
  187829. {
  187830. png_push_save_buffer(png_ptr);
  187831. return;
  187832. }
  187833. png_push_fill_buffer(png_ptr, chunk_length, 4);
  187834. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  187835. png_reset_crc(png_ptr);
  187836. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187837. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  187838. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187839. {
  187840. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187841. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  187842. png_error(png_ptr, "Not enough compressed data");
  187843. return;
  187844. }
  187845. png_ptr->idat_size = png_ptr->push_length;
  187846. }
  187847. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  187848. {
  187849. png_size_t save_size;
  187850. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  187851. {
  187852. save_size = (png_size_t)png_ptr->idat_size;
  187853. /* check for overflow */
  187854. if((png_uint_32)save_size != png_ptr->idat_size)
  187855. png_error(png_ptr, "save_size overflowed in pngpread");
  187856. }
  187857. else
  187858. save_size = png_ptr->save_buffer_size;
  187859. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  187860. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  187861. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  187862. png_ptr->idat_size -= save_size;
  187863. png_ptr->buffer_size -= save_size;
  187864. png_ptr->save_buffer_size -= save_size;
  187865. png_ptr->save_buffer_ptr += save_size;
  187866. }
  187867. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  187868. {
  187869. png_size_t save_size;
  187870. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  187871. {
  187872. save_size = (png_size_t)png_ptr->idat_size;
  187873. /* check for overflow */
  187874. if((png_uint_32)save_size != png_ptr->idat_size)
  187875. png_error(png_ptr, "save_size overflowed in pngpread");
  187876. }
  187877. else
  187878. save_size = png_ptr->current_buffer_size;
  187879. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  187880. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  187881. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  187882. png_ptr->idat_size -= save_size;
  187883. png_ptr->buffer_size -= save_size;
  187884. png_ptr->current_buffer_size -= save_size;
  187885. png_ptr->current_buffer_ptr += save_size;
  187886. }
  187887. if (!png_ptr->idat_size)
  187888. {
  187889. if (png_ptr->buffer_size < 4)
  187890. {
  187891. png_push_save_buffer(png_ptr);
  187892. return;
  187893. }
  187894. png_crc_finish(png_ptr, 0);
  187895. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  187896. png_ptr->mode |= PNG_AFTER_IDAT;
  187897. }
  187898. }
  187899. void /* PRIVATE */
  187900. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  187901. png_size_t buffer_length)
  187902. {
  187903. int ret;
  187904. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  187905. png_error(png_ptr, "Extra compression data");
  187906. png_ptr->zstream.next_in = buffer;
  187907. png_ptr->zstream.avail_in = (uInt)buffer_length;
  187908. for(;;)
  187909. {
  187910. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187911. if (ret != Z_OK)
  187912. {
  187913. if (ret == Z_STREAM_END)
  187914. {
  187915. if (png_ptr->zstream.avail_in)
  187916. png_error(png_ptr, "Extra compressed data");
  187917. if (!(png_ptr->zstream.avail_out))
  187918. {
  187919. png_push_process_row(png_ptr);
  187920. }
  187921. png_ptr->mode |= PNG_AFTER_IDAT;
  187922. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187923. break;
  187924. }
  187925. else if (ret == Z_BUF_ERROR)
  187926. break;
  187927. else
  187928. png_error(png_ptr, "Decompression Error");
  187929. }
  187930. if (!(png_ptr->zstream.avail_out))
  187931. {
  187932. if ((
  187933. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187934. png_ptr->interlaced && png_ptr->pass > 6) ||
  187935. (!png_ptr->interlaced &&
  187936. #endif
  187937. png_ptr->row_number == png_ptr->num_rows))
  187938. {
  187939. if (png_ptr->zstream.avail_in)
  187940. {
  187941. png_warning(png_ptr, "Too much data in IDAT chunks");
  187942. }
  187943. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187944. break;
  187945. }
  187946. png_push_process_row(png_ptr);
  187947. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187948. png_ptr->zstream.next_out = png_ptr->row_buf;
  187949. }
  187950. else
  187951. break;
  187952. }
  187953. }
  187954. void /* PRIVATE */
  187955. png_push_process_row(png_structp png_ptr)
  187956. {
  187957. png_ptr->row_info.color_type = png_ptr->color_type;
  187958. png_ptr->row_info.width = png_ptr->iwidth;
  187959. png_ptr->row_info.channels = png_ptr->channels;
  187960. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187961. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187962. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187963. png_ptr->row_info.width);
  187964. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187965. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187966. (int)(png_ptr->row_buf[0]));
  187967. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187968. png_ptr->rowbytes + 1);
  187969. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187970. png_do_read_transformations(png_ptr);
  187971. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187972. /* blow up interlaced rows to full size */
  187973. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187974. {
  187975. if (png_ptr->pass < 6)
  187976. /* old interface (pre-1.0.9):
  187977. png_do_read_interlace(&(png_ptr->row_info),
  187978. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187979. */
  187980. png_do_read_interlace(png_ptr);
  187981. switch (png_ptr->pass)
  187982. {
  187983. case 0:
  187984. {
  187985. int i;
  187986. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  187987. {
  187988. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  187989. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  187990. }
  187991. if (png_ptr->pass == 2) /* pass 1 might be empty */
  187992. {
  187993. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  187994. {
  187995. png_push_have_row(png_ptr, png_bytep_NULL);
  187996. png_read_push_finish_row(png_ptr);
  187997. }
  187998. }
  187999. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188000. {
  188001. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188002. {
  188003. png_push_have_row(png_ptr, png_bytep_NULL);
  188004. png_read_push_finish_row(png_ptr);
  188005. }
  188006. }
  188007. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188008. {
  188009. png_push_have_row(png_ptr, png_bytep_NULL);
  188010. png_read_push_finish_row(png_ptr);
  188011. }
  188012. break;
  188013. }
  188014. case 1:
  188015. {
  188016. int i;
  188017. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188018. {
  188019. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188020. png_read_push_finish_row(png_ptr);
  188021. }
  188022. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188023. {
  188024. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188025. {
  188026. png_push_have_row(png_ptr, png_bytep_NULL);
  188027. png_read_push_finish_row(png_ptr);
  188028. }
  188029. }
  188030. break;
  188031. }
  188032. case 2:
  188033. {
  188034. int i;
  188035. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188036. {
  188037. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188038. png_read_push_finish_row(png_ptr);
  188039. }
  188040. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188041. {
  188042. png_push_have_row(png_ptr, png_bytep_NULL);
  188043. png_read_push_finish_row(png_ptr);
  188044. }
  188045. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188046. {
  188047. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188048. {
  188049. png_push_have_row(png_ptr, png_bytep_NULL);
  188050. png_read_push_finish_row(png_ptr);
  188051. }
  188052. }
  188053. break;
  188054. }
  188055. case 3:
  188056. {
  188057. int i;
  188058. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188059. {
  188060. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188061. png_read_push_finish_row(png_ptr);
  188062. }
  188063. if (png_ptr->pass == 4) /* skip top two generated rows */
  188064. {
  188065. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188066. {
  188067. png_push_have_row(png_ptr, png_bytep_NULL);
  188068. png_read_push_finish_row(png_ptr);
  188069. }
  188070. }
  188071. break;
  188072. }
  188073. case 4:
  188074. {
  188075. int i;
  188076. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188077. {
  188078. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188079. png_read_push_finish_row(png_ptr);
  188080. }
  188081. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188082. {
  188083. png_push_have_row(png_ptr, png_bytep_NULL);
  188084. png_read_push_finish_row(png_ptr);
  188085. }
  188086. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188087. {
  188088. png_push_have_row(png_ptr, png_bytep_NULL);
  188089. png_read_push_finish_row(png_ptr);
  188090. }
  188091. break;
  188092. }
  188093. case 5:
  188094. {
  188095. int i;
  188096. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188097. {
  188098. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188099. png_read_push_finish_row(png_ptr);
  188100. }
  188101. if (png_ptr->pass == 6) /* skip top generated row */
  188102. {
  188103. png_push_have_row(png_ptr, png_bytep_NULL);
  188104. png_read_push_finish_row(png_ptr);
  188105. }
  188106. break;
  188107. }
  188108. case 6:
  188109. {
  188110. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188111. png_read_push_finish_row(png_ptr);
  188112. if (png_ptr->pass != 6)
  188113. break;
  188114. png_push_have_row(png_ptr, png_bytep_NULL);
  188115. png_read_push_finish_row(png_ptr);
  188116. }
  188117. }
  188118. }
  188119. else
  188120. #endif
  188121. {
  188122. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188123. png_read_push_finish_row(png_ptr);
  188124. }
  188125. }
  188126. void /* PRIVATE */
  188127. png_read_push_finish_row(png_structp png_ptr)
  188128. {
  188129. #ifdef PNG_USE_LOCAL_ARRAYS
  188130. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  188131. /* start of interlace block */
  188132. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  188133. /* offset to next interlace block */
  188134. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  188135. /* start of interlace block in the y direction */
  188136. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  188137. /* offset to next interlace block in the y direction */
  188138. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  188139. /* Height of interlace block. This is not currently used - if you need
  188140. * it, uncomment it here and in png.h
  188141. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  188142. */
  188143. #endif
  188144. png_ptr->row_number++;
  188145. if (png_ptr->row_number < png_ptr->num_rows)
  188146. return;
  188147. if (png_ptr->interlaced)
  188148. {
  188149. png_ptr->row_number = 0;
  188150. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  188151. png_ptr->rowbytes + 1);
  188152. do
  188153. {
  188154. png_ptr->pass++;
  188155. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  188156. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  188157. (png_ptr->pass == 5 && png_ptr->width < 2))
  188158. png_ptr->pass++;
  188159. if (png_ptr->pass > 7)
  188160. png_ptr->pass--;
  188161. if (png_ptr->pass >= 7)
  188162. break;
  188163. png_ptr->iwidth = (png_ptr->width +
  188164. png_pass_inc[png_ptr->pass] - 1 -
  188165. png_pass_start[png_ptr->pass]) /
  188166. png_pass_inc[png_ptr->pass];
  188167. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  188168. png_ptr->iwidth) + 1;
  188169. if (png_ptr->transformations & PNG_INTERLACE)
  188170. break;
  188171. png_ptr->num_rows = (png_ptr->height +
  188172. png_pass_yinc[png_ptr->pass] - 1 -
  188173. png_pass_ystart[png_ptr->pass]) /
  188174. png_pass_yinc[png_ptr->pass];
  188175. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  188176. }
  188177. }
  188178. #if defined(PNG_READ_tEXt_SUPPORTED)
  188179. void /* PRIVATE */
  188180. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188181. length)
  188182. {
  188183. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188184. {
  188185. png_error(png_ptr, "Out of place tEXt");
  188186. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188187. }
  188188. #ifdef PNG_MAX_MALLOC_64K
  188189. png_ptr->skip_length = 0; /* This may not be necessary */
  188190. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188191. {
  188192. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188193. png_ptr->skip_length = length - (png_uint_32)65535L;
  188194. length = (png_uint_32)65535L;
  188195. }
  188196. #endif
  188197. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188198. (png_uint_32)(length+1));
  188199. png_ptr->current_text[length] = '\0';
  188200. png_ptr->current_text_ptr = png_ptr->current_text;
  188201. png_ptr->current_text_size = (png_size_t)length;
  188202. png_ptr->current_text_left = (png_size_t)length;
  188203. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  188204. }
  188205. void /* PRIVATE */
  188206. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  188207. {
  188208. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188209. {
  188210. png_size_t text_size;
  188211. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188212. text_size = png_ptr->buffer_size;
  188213. else
  188214. text_size = png_ptr->current_text_left;
  188215. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188216. png_ptr->current_text_left -= text_size;
  188217. png_ptr->current_text_ptr += text_size;
  188218. }
  188219. if (!(png_ptr->current_text_left))
  188220. {
  188221. png_textp text_ptr;
  188222. png_charp text;
  188223. png_charp key;
  188224. int ret;
  188225. if (png_ptr->buffer_size < 4)
  188226. {
  188227. png_push_save_buffer(png_ptr);
  188228. return;
  188229. }
  188230. png_push_crc_finish(png_ptr);
  188231. #if defined(PNG_MAX_MALLOC_64K)
  188232. if (png_ptr->skip_length)
  188233. return;
  188234. #endif
  188235. key = png_ptr->current_text;
  188236. for (text = key; *text; text++)
  188237. /* empty loop */ ;
  188238. if (text < key + png_ptr->current_text_size)
  188239. text++;
  188240. text_ptr = (png_textp)png_malloc(png_ptr,
  188241. (png_uint_32)png_sizeof(png_text));
  188242. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  188243. text_ptr->key = key;
  188244. #ifdef PNG_iTXt_SUPPORTED
  188245. text_ptr->lang = NULL;
  188246. text_ptr->lang_key = NULL;
  188247. #endif
  188248. text_ptr->text = text;
  188249. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188250. png_free(png_ptr, key);
  188251. png_free(png_ptr, text_ptr);
  188252. png_ptr->current_text = NULL;
  188253. if (ret)
  188254. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188255. }
  188256. }
  188257. #endif
  188258. #if defined(PNG_READ_zTXt_SUPPORTED)
  188259. void /* PRIVATE */
  188260. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188261. length)
  188262. {
  188263. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188264. {
  188265. png_error(png_ptr, "Out of place zTXt");
  188266. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188267. }
  188268. #ifdef PNG_MAX_MALLOC_64K
  188269. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  188270. * to be able to store the uncompressed data. Actually, the threshold
  188271. * is probably around 32K, but it isn't as definite as 64K is.
  188272. */
  188273. if (length > (png_uint_32)65535L)
  188274. {
  188275. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  188276. png_push_crc_skip(png_ptr, length);
  188277. return;
  188278. }
  188279. #endif
  188280. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188281. (png_uint_32)(length+1));
  188282. png_ptr->current_text[length] = '\0';
  188283. png_ptr->current_text_ptr = png_ptr->current_text;
  188284. png_ptr->current_text_size = (png_size_t)length;
  188285. png_ptr->current_text_left = (png_size_t)length;
  188286. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  188287. }
  188288. void /* PRIVATE */
  188289. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  188290. {
  188291. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188292. {
  188293. png_size_t text_size;
  188294. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  188295. text_size = png_ptr->buffer_size;
  188296. else
  188297. text_size = png_ptr->current_text_left;
  188298. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188299. png_ptr->current_text_left -= text_size;
  188300. png_ptr->current_text_ptr += text_size;
  188301. }
  188302. if (!(png_ptr->current_text_left))
  188303. {
  188304. png_textp text_ptr;
  188305. png_charp text;
  188306. png_charp key;
  188307. int ret;
  188308. png_size_t text_size, key_size;
  188309. if (png_ptr->buffer_size < 4)
  188310. {
  188311. png_push_save_buffer(png_ptr);
  188312. return;
  188313. }
  188314. png_push_crc_finish(png_ptr);
  188315. key = png_ptr->current_text;
  188316. for (text = key; *text; text++)
  188317. /* empty loop */ ;
  188318. /* zTXt can't have zero text */
  188319. if (text >= key + png_ptr->current_text_size)
  188320. {
  188321. png_ptr->current_text = NULL;
  188322. png_free(png_ptr, key);
  188323. return;
  188324. }
  188325. text++;
  188326. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  188327. {
  188328. png_ptr->current_text = NULL;
  188329. png_free(png_ptr, key);
  188330. return;
  188331. }
  188332. text++;
  188333. png_ptr->zstream.next_in = (png_bytep )text;
  188334. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  188335. (text - key));
  188336. png_ptr->zstream.next_out = png_ptr->zbuf;
  188337. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188338. key_size = text - key;
  188339. text_size = 0;
  188340. text = NULL;
  188341. ret = Z_STREAM_END;
  188342. while (png_ptr->zstream.avail_in)
  188343. {
  188344. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188345. if (ret != Z_OK && ret != Z_STREAM_END)
  188346. {
  188347. inflateReset(&png_ptr->zstream);
  188348. png_ptr->zstream.avail_in = 0;
  188349. png_ptr->current_text = NULL;
  188350. png_free(png_ptr, key);
  188351. png_free(png_ptr, text);
  188352. return;
  188353. }
  188354. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  188355. {
  188356. if (text == NULL)
  188357. {
  188358. text = (png_charp)png_malloc(png_ptr,
  188359. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188360. + key_size + 1));
  188361. png_memcpy(text + key_size, png_ptr->zbuf,
  188362. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188363. png_memcpy(text, key, key_size);
  188364. text_size = key_size + png_ptr->zbuf_size -
  188365. png_ptr->zstream.avail_out;
  188366. *(text + text_size) = '\0';
  188367. }
  188368. else
  188369. {
  188370. png_charp tmp;
  188371. tmp = text;
  188372. text = (png_charp)png_malloc(png_ptr, text_size +
  188373. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188374. + 1));
  188375. png_memcpy(text, tmp, text_size);
  188376. png_free(png_ptr, tmp);
  188377. png_memcpy(text + text_size, png_ptr->zbuf,
  188378. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188379. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188380. *(text + text_size) = '\0';
  188381. }
  188382. if (ret != Z_STREAM_END)
  188383. {
  188384. png_ptr->zstream.next_out = png_ptr->zbuf;
  188385. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188386. }
  188387. }
  188388. else
  188389. {
  188390. break;
  188391. }
  188392. if (ret == Z_STREAM_END)
  188393. break;
  188394. }
  188395. inflateReset(&png_ptr->zstream);
  188396. png_ptr->zstream.avail_in = 0;
  188397. if (ret != Z_STREAM_END)
  188398. {
  188399. png_ptr->current_text = NULL;
  188400. png_free(png_ptr, key);
  188401. png_free(png_ptr, text);
  188402. return;
  188403. }
  188404. png_ptr->current_text = NULL;
  188405. png_free(png_ptr, key);
  188406. key = text;
  188407. text += key_size;
  188408. text_ptr = (png_textp)png_malloc(png_ptr,
  188409. (png_uint_32)png_sizeof(png_text));
  188410. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  188411. text_ptr->key = key;
  188412. #ifdef PNG_iTXt_SUPPORTED
  188413. text_ptr->lang = NULL;
  188414. text_ptr->lang_key = NULL;
  188415. #endif
  188416. text_ptr->text = text;
  188417. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188418. png_free(png_ptr, key);
  188419. png_free(png_ptr, text_ptr);
  188420. if (ret)
  188421. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188422. }
  188423. }
  188424. #endif
  188425. #if defined(PNG_READ_iTXt_SUPPORTED)
  188426. void /* PRIVATE */
  188427. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188428. length)
  188429. {
  188430. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188431. {
  188432. png_error(png_ptr, "Out of place iTXt");
  188433. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188434. }
  188435. #ifdef PNG_MAX_MALLOC_64K
  188436. png_ptr->skip_length = 0; /* This may not be necessary */
  188437. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188438. {
  188439. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  188440. png_ptr->skip_length = length - (png_uint_32)65535L;
  188441. length = (png_uint_32)65535L;
  188442. }
  188443. #endif
  188444. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188445. (png_uint_32)(length+1));
  188446. png_ptr->current_text[length] = '\0';
  188447. png_ptr->current_text_ptr = png_ptr->current_text;
  188448. png_ptr->current_text_size = (png_size_t)length;
  188449. png_ptr->current_text_left = (png_size_t)length;
  188450. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  188451. }
  188452. void /* PRIVATE */
  188453. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  188454. {
  188455. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188456. {
  188457. png_size_t text_size;
  188458. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188459. text_size = png_ptr->buffer_size;
  188460. else
  188461. text_size = png_ptr->current_text_left;
  188462. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188463. png_ptr->current_text_left -= text_size;
  188464. png_ptr->current_text_ptr += text_size;
  188465. }
  188466. if (!(png_ptr->current_text_left))
  188467. {
  188468. png_textp text_ptr;
  188469. png_charp key;
  188470. int comp_flag;
  188471. png_charp lang;
  188472. png_charp lang_key;
  188473. png_charp text;
  188474. int ret;
  188475. if (png_ptr->buffer_size < 4)
  188476. {
  188477. png_push_save_buffer(png_ptr);
  188478. return;
  188479. }
  188480. png_push_crc_finish(png_ptr);
  188481. #if defined(PNG_MAX_MALLOC_64K)
  188482. if (png_ptr->skip_length)
  188483. return;
  188484. #endif
  188485. key = png_ptr->current_text;
  188486. for (lang = key; *lang; lang++)
  188487. /* empty loop */ ;
  188488. if (lang < key + png_ptr->current_text_size - 3)
  188489. lang++;
  188490. comp_flag = *lang++;
  188491. lang++; /* skip comp_type, always zero */
  188492. for (lang_key = lang; *lang_key; lang_key++)
  188493. /* empty loop */ ;
  188494. lang_key++; /* skip NUL separator */
  188495. text=lang_key;
  188496. if (lang_key < key + png_ptr->current_text_size - 1)
  188497. {
  188498. for (; *text; text++)
  188499. /* empty loop */ ;
  188500. }
  188501. if (text < key + png_ptr->current_text_size)
  188502. text++;
  188503. text_ptr = (png_textp)png_malloc(png_ptr,
  188504. (png_uint_32)png_sizeof(png_text));
  188505. text_ptr->compression = comp_flag + 2;
  188506. text_ptr->key = key;
  188507. text_ptr->lang = lang;
  188508. text_ptr->lang_key = lang_key;
  188509. text_ptr->text = text;
  188510. text_ptr->text_length = 0;
  188511. text_ptr->itxt_length = png_strlen(text);
  188512. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188513. png_ptr->current_text = NULL;
  188514. png_free(png_ptr, text_ptr);
  188515. if (ret)
  188516. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  188517. }
  188518. }
  188519. #endif
  188520. /* This function is called when we haven't found a handler for this
  188521. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  188522. * name or a critical chunk), the chunk is (currently) silently ignored.
  188523. */
  188524. void /* PRIVATE */
  188525. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188526. length)
  188527. {
  188528. png_uint_32 skip=0;
  188529. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  188530. if (!(png_ptr->chunk_name[0] & 0x20))
  188531. {
  188532. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  188533. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  188534. PNG_HANDLE_CHUNK_ALWAYS
  188535. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  188536. && png_ptr->read_user_chunk_fn == NULL
  188537. #endif
  188538. )
  188539. #endif
  188540. png_chunk_error(png_ptr, "unknown critical chunk");
  188541. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188542. }
  188543. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  188544. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  188545. {
  188546. #ifdef PNG_MAX_MALLOC_64K
  188547. if (length > (png_uint_32)65535L)
  188548. {
  188549. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  188550. skip = length - (png_uint_32)65535L;
  188551. length = (png_uint_32)65535L;
  188552. }
  188553. #endif
  188554. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  188555. (png_charp)png_ptr->chunk_name, 5);
  188556. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  188557. png_ptr->unknown_chunk.size = (png_size_t)length;
  188558. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  188559. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  188560. if(png_ptr->read_user_chunk_fn != NULL)
  188561. {
  188562. /* callback to user unknown chunk handler */
  188563. int ret;
  188564. ret = (*(png_ptr->read_user_chunk_fn))
  188565. (png_ptr, &png_ptr->unknown_chunk);
  188566. if (ret < 0)
  188567. png_chunk_error(png_ptr, "error in user chunk");
  188568. if (ret == 0)
  188569. {
  188570. if (!(png_ptr->chunk_name[0] & 0x20))
  188571. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  188572. PNG_HANDLE_CHUNK_ALWAYS)
  188573. png_chunk_error(png_ptr, "unknown critical chunk");
  188574. png_set_unknown_chunks(png_ptr, info_ptr,
  188575. &png_ptr->unknown_chunk, 1);
  188576. }
  188577. }
  188578. #else
  188579. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  188580. #endif
  188581. png_free(png_ptr, png_ptr->unknown_chunk.data);
  188582. png_ptr->unknown_chunk.data = NULL;
  188583. }
  188584. else
  188585. #endif
  188586. skip=length;
  188587. png_push_crc_skip(png_ptr, skip);
  188588. }
  188589. void /* PRIVATE */
  188590. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  188591. {
  188592. if (png_ptr->info_fn != NULL)
  188593. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  188594. }
  188595. void /* PRIVATE */
  188596. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  188597. {
  188598. if (png_ptr->end_fn != NULL)
  188599. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  188600. }
  188601. void /* PRIVATE */
  188602. png_push_have_row(png_structp png_ptr, png_bytep row)
  188603. {
  188604. if (png_ptr->row_fn != NULL)
  188605. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  188606. (int)png_ptr->pass);
  188607. }
  188608. void PNGAPI
  188609. png_progressive_combine_row (png_structp png_ptr,
  188610. png_bytep old_row, png_bytep new_row)
  188611. {
  188612. #ifdef PNG_USE_LOCAL_ARRAYS
  188613. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  188614. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  188615. #endif
  188616. if(png_ptr == NULL) return;
  188617. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  188618. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  188619. }
  188620. void PNGAPI
  188621. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  188622. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  188623. png_progressive_end_ptr end_fn)
  188624. {
  188625. if(png_ptr == NULL) return;
  188626. png_ptr->info_fn = info_fn;
  188627. png_ptr->row_fn = row_fn;
  188628. png_ptr->end_fn = end_fn;
  188629. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  188630. }
  188631. png_voidp PNGAPI
  188632. png_get_progressive_ptr(png_structp png_ptr)
  188633. {
  188634. if(png_ptr == NULL) return (NULL);
  188635. return png_ptr->io_ptr;
  188636. }
  188637. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188638. /*** End of inlined file: pngpread.c ***/
  188639. /*** Start of inlined file: pngrio.c ***/
  188640. /* pngrio.c - functions for data input
  188641. *
  188642. * Last changed in libpng 1.2.13 November 13, 2006
  188643. * For conditions of distribution and use, see copyright notice in png.h
  188644. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  188645. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188646. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188647. *
  188648. * This file provides a location for all input. Users who need
  188649. * special handling are expected to write a function that has the same
  188650. * arguments as this and performs a similar function, but that possibly
  188651. * has a different input method. Note that you shouldn't change this
  188652. * function, but rather write a replacement function and then make
  188653. * libpng use it at run time with png_set_read_fn(...).
  188654. */
  188655. #define PNG_INTERNAL
  188656. #if defined(PNG_READ_SUPPORTED)
  188657. /* Read the data from whatever input you are using. The default routine
  188658. reads from a file pointer. Note that this routine sometimes gets called
  188659. with very small lengths, so you should implement some kind of simple
  188660. buffering if you are using unbuffered reads. This should never be asked
  188661. to read more then 64K on a 16 bit machine. */
  188662. void /* PRIVATE */
  188663. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  188664. {
  188665. png_debug1(4,"reading %d bytes\n", (int)length);
  188666. if (png_ptr->read_data_fn != NULL)
  188667. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  188668. else
  188669. png_error(png_ptr, "Call to NULL read function");
  188670. }
  188671. #if !defined(PNG_NO_STDIO)
  188672. /* This is the function that does the actual reading of data. If you are
  188673. not reading from a standard C stream, you should create a replacement
  188674. read_data function and use it at run time with png_set_read_fn(), rather
  188675. than changing the library. */
  188676. #ifndef USE_FAR_KEYWORD
  188677. void PNGAPI
  188678. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  188679. {
  188680. png_size_t check;
  188681. if(png_ptr == NULL) return;
  188682. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  188683. * instead of an int, which is what fread() actually returns.
  188684. */
  188685. #if defined(_WIN32_WCE)
  188686. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  188687. check = 0;
  188688. #else
  188689. check = (png_size_t)fread(data, (png_size_t)1, length,
  188690. (png_FILE_p)png_ptr->io_ptr);
  188691. #endif
  188692. if (check != length)
  188693. png_error(png_ptr, "Read Error");
  188694. }
  188695. #else
  188696. /* this is the model-independent version. Since the standard I/O library
  188697. can't handle far buffers in the medium and small models, we have to copy
  188698. the data.
  188699. */
  188700. #define NEAR_BUF_SIZE 1024
  188701. #define MIN(a,b) (a <= b ? a : b)
  188702. static void PNGAPI
  188703. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  188704. {
  188705. int check;
  188706. png_byte *n_data;
  188707. png_FILE_p io_ptr;
  188708. if(png_ptr == NULL) return;
  188709. /* Check if data really is near. If so, use usual code. */
  188710. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  188711. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  188712. if ((png_bytep)n_data == data)
  188713. {
  188714. #if defined(_WIN32_WCE)
  188715. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  188716. check = 0;
  188717. #else
  188718. check = fread(n_data, 1, length, io_ptr);
  188719. #endif
  188720. }
  188721. else
  188722. {
  188723. png_byte buf[NEAR_BUF_SIZE];
  188724. png_size_t read, remaining, err;
  188725. check = 0;
  188726. remaining = length;
  188727. do
  188728. {
  188729. read = MIN(NEAR_BUF_SIZE, remaining);
  188730. #if defined(_WIN32_WCE)
  188731. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  188732. err = 0;
  188733. #else
  188734. err = fread(buf, (png_size_t)1, read, io_ptr);
  188735. #endif
  188736. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  188737. if(err != read)
  188738. break;
  188739. else
  188740. check += err;
  188741. data += read;
  188742. remaining -= read;
  188743. }
  188744. while (remaining != 0);
  188745. }
  188746. if ((png_uint_32)check != (png_uint_32)length)
  188747. png_error(png_ptr, "read Error");
  188748. }
  188749. #endif
  188750. #endif
  188751. /* This function allows the application to supply a new input function
  188752. for libpng if standard C streams aren't being used.
  188753. This function takes as its arguments:
  188754. png_ptr - pointer to a png input data structure
  188755. io_ptr - pointer to user supplied structure containing info about
  188756. the input functions. May be NULL.
  188757. read_data_fn - pointer to a new input function that takes as its
  188758. arguments a pointer to a png_struct, a pointer to
  188759. a location where input data can be stored, and a 32-bit
  188760. unsigned int that is the number of bytes to be read.
  188761. To exit and output any fatal error messages the new write
  188762. function should call png_error(png_ptr, "Error msg"). */
  188763. void PNGAPI
  188764. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  188765. png_rw_ptr read_data_fn)
  188766. {
  188767. if(png_ptr == NULL) return;
  188768. png_ptr->io_ptr = io_ptr;
  188769. #if !defined(PNG_NO_STDIO)
  188770. if (read_data_fn != NULL)
  188771. png_ptr->read_data_fn = read_data_fn;
  188772. else
  188773. png_ptr->read_data_fn = png_default_read_data;
  188774. #else
  188775. png_ptr->read_data_fn = read_data_fn;
  188776. #endif
  188777. /* It is an error to write to a read device */
  188778. if (png_ptr->write_data_fn != NULL)
  188779. {
  188780. png_ptr->write_data_fn = NULL;
  188781. png_warning(png_ptr,
  188782. "It's an error to set both read_data_fn and write_data_fn in the ");
  188783. png_warning(png_ptr,
  188784. "same structure. Resetting write_data_fn to NULL.");
  188785. }
  188786. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  188787. png_ptr->output_flush_fn = NULL;
  188788. #endif
  188789. }
  188790. #endif /* PNG_READ_SUPPORTED */
  188791. /*** End of inlined file: pngrio.c ***/
  188792. /*** Start of inlined file: pngrtran.c ***/
  188793. /* pngrtran.c - transforms the data in a row for PNG readers
  188794. *
  188795. * Last changed in libpng 1.2.21 [October 4, 2007]
  188796. * For conditions of distribution and use, see copyright notice in png.h
  188797. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188798. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188799. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188800. *
  188801. * This file contains functions optionally called by an application
  188802. * in order to tell libpng how to handle data when reading a PNG.
  188803. * Transformations that are used in both reading and writing are
  188804. * in pngtrans.c.
  188805. */
  188806. #define PNG_INTERNAL
  188807. #if defined(PNG_READ_SUPPORTED)
  188808. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  188809. void PNGAPI
  188810. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  188811. {
  188812. png_debug(1, "in png_set_crc_action\n");
  188813. /* Tell libpng how we react to CRC errors in critical chunks */
  188814. if(png_ptr == NULL) return;
  188815. switch (crit_action)
  188816. {
  188817. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  188818. break;
  188819. case PNG_CRC_WARN_USE: /* warn/use data */
  188820. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  188821. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  188822. break;
  188823. case PNG_CRC_QUIET_USE: /* quiet/use data */
  188824. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  188825. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  188826. PNG_FLAG_CRC_CRITICAL_IGNORE;
  188827. break;
  188828. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  188829. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  188830. case PNG_CRC_ERROR_QUIT: /* error/quit */
  188831. case PNG_CRC_DEFAULT:
  188832. default:
  188833. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  188834. break;
  188835. }
  188836. switch (ancil_action)
  188837. {
  188838. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  188839. break;
  188840. case PNG_CRC_WARN_USE: /* warn/use data */
  188841. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  188842. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  188843. break;
  188844. case PNG_CRC_QUIET_USE: /* quiet/use data */
  188845. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  188846. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  188847. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  188848. break;
  188849. case PNG_CRC_ERROR_QUIT: /* error/quit */
  188850. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  188851. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  188852. break;
  188853. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  188854. case PNG_CRC_DEFAULT:
  188855. default:
  188856. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  188857. break;
  188858. }
  188859. }
  188860. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  188861. defined(PNG_FLOATING_POINT_SUPPORTED)
  188862. /* handle alpha and tRNS via a background color */
  188863. void PNGAPI
  188864. png_set_background(png_structp png_ptr,
  188865. png_color_16p background_color, int background_gamma_code,
  188866. int need_expand, double background_gamma)
  188867. {
  188868. png_debug(1, "in png_set_background\n");
  188869. if(png_ptr == NULL) return;
  188870. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  188871. {
  188872. png_warning(png_ptr, "Application must supply a known background gamma");
  188873. return;
  188874. }
  188875. png_ptr->transformations |= PNG_BACKGROUND;
  188876. png_memcpy(&(png_ptr->background), background_color,
  188877. png_sizeof(png_color_16));
  188878. png_ptr->background_gamma = (float)background_gamma;
  188879. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  188880. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  188881. }
  188882. #endif
  188883. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188884. /* strip 16 bit depth files to 8 bit depth */
  188885. void PNGAPI
  188886. png_set_strip_16(png_structp png_ptr)
  188887. {
  188888. png_debug(1, "in png_set_strip_16\n");
  188889. if(png_ptr == NULL) return;
  188890. png_ptr->transformations |= PNG_16_TO_8;
  188891. }
  188892. #endif
  188893. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188894. void PNGAPI
  188895. png_set_strip_alpha(png_structp png_ptr)
  188896. {
  188897. png_debug(1, "in png_set_strip_alpha\n");
  188898. if(png_ptr == NULL) return;
  188899. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  188900. }
  188901. #endif
  188902. #if defined(PNG_READ_DITHER_SUPPORTED)
  188903. /* Dither file to 8 bit. Supply a palette, the current number
  188904. * of elements in the palette, the maximum number of elements
  188905. * allowed, and a histogram if possible. If the current number
  188906. * of colors is greater then the maximum number, the palette will be
  188907. * modified to fit in the maximum number. "full_dither" indicates
  188908. * whether we need a dithering cube set up for RGB images, or if we
  188909. * simply are reducing the number of colors in a paletted image.
  188910. */
  188911. typedef struct png_dsort_struct
  188912. {
  188913. struct png_dsort_struct FAR * next;
  188914. png_byte left;
  188915. png_byte right;
  188916. } png_dsort;
  188917. typedef png_dsort FAR * png_dsortp;
  188918. typedef png_dsort FAR * FAR * png_dsortpp;
  188919. void PNGAPI
  188920. png_set_dither(png_structp png_ptr, png_colorp palette,
  188921. int num_palette, int maximum_colors, png_uint_16p histogram,
  188922. int full_dither)
  188923. {
  188924. png_debug(1, "in png_set_dither\n");
  188925. if(png_ptr == NULL) return;
  188926. png_ptr->transformations |= PNG_DITHER;
  188927. if (!full_dither)
  188928. {
  188929. int i;
  188930. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  188931. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  188932. for (i = 0; i < num_palette; i++)
  188933. png_ptr->dither_index[i] = (png_byte)i;
  188934. }
  188935. if (num_palette > maximum_colors)
  188936. {
  188937. if (histogram != NULL)
  188938. {
  188939. /* This is easy enough, just throw out the least used colors.
  188940. Perhaps not the best solution, but good enough. */
  188941. int i;
  188942. /* initialize an array to sort colors */
  188943. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  188944. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  188945. /* initialize the dither_sort array */
  188946. for (i = 0; i < num_palette; i++)
  188947. png_ptr->dither_sort[i] = (png_byte)i;
  188948. /* Find the least used palette entries by starting a
  188949. bubble sort, and running it until we have sorted
  188950. out enough colors. Note that we don't care about
  188951. sorting all the colors, just finding which are
  188952. least used. */
  188953. for (i = num_palette - 1; i >= maximum_colors; i--)
  188954. {
  188955. int done; /* to stop early if the list is pre-sorted */
  188956. int j;
  188957. done = 1;
  188958. for (j = 0; j < i; j++)
  188959. {
  188960. if (histogram[png_ptr->dither_sort[j]]
  188961. < histogram[png_ptr->dither_sort[j + 1]])
  188962. {
  188963. png_byte t;
  188964. t = png_ptr->dither_sort[j];
  188965. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  188966. png_ptr->dither_sort[j + 1] = t;
  188967. done = 0;
  188968. }
  188969. }
  188970. if (done)
  188971. break;
  188972. }
  188973. /* swap the palette around, and set up a table, if necessary */
  188974. if (full_dither)
  188975. {
  188976. int j = num_palette;
  188977. /* put all the useful colors within the max, but don't
  188978. move the others */
  188979. for (i = 0; i < maximum_colors; i++)
  188980. {
  188981. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  188982. {
  188983. do
  188984. j--;
  188985. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  188986. palette[i] = palette[j];
  188987. }
  188988. }
  188989. }
  188990. else
  188991. {
  188992. int j = num_palette;
  188993. /* move all the used colors inside the max limit, and
  188994. develop a translation table */
  188995. for (i = 0; i < maximum_colors; i++)
  188996. {
  188997. /* only move the colors we need to */
  188998. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  188999. {
  189000. png_color tmp_color;
  189001. do
  189002. j--;
  189003. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189004. tmp_color = palette[j];
  189005. palette[j] = palette[i];
  189006. palette[i] = tmp_color;
  189007. /* indicate where the color went */
  189008. png_ptr->dither_index[j] = (png_byte)i;
  189009. png_ptr->dither_index[i] = (png_byte)j;
  189010. }
  189011. }
  189012. /* find closest color for those colors we are not using */
  189013. for (i = 0; i < num_palette; i++)
  189014. {
  189015. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189016. {
  189017. int min_d, k, min_k, d_index;
  189018. /* find the closest color to one we threw out */
  189019. d_index = png_ptr->dither_index[i];
  189020. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189021. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189022. {
  189023. int d;
  189024. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189025. if (d < min_d)
  189026. {
  189027. min_d = d;
  189028. min_k = k;
  189029. }
  189030. }
  189031. /* point to closest color */
  189032. png_ptr->dither_index[i] = (png_byte)min_k;
  189033. }
  189034. }
  189035. }
  189036. png_free(png_ptr, png_ptr->dither_sort);
  189037. png_ptr->dither_sort=NULL;
  189038. }
  189039. else
  189040. {
  189041. /* This is much harder to do simply (and quickly). Perhaps
  189042. we need to go through a median cut routine, but those
  189043. don't always behave themselves with only a few colors
  189044. as input. So we will just find the closest two colors,
  189045. and throw out one of them (chosen somewhat randomly).
  189046. [We don't understand this at all, so if someone wants to
  189047. work on improving it, be our guest - AED, GRP]
  189048. */
  189049. int i;
  189050. int max_d;
  189051. int num_new_palette;
  189052. png_dsortp t;
  189053. png_dsortpp hash;
  189054. t=NULL;
  189055. /* initialize palette index arrays */
  189056. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189057. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189058. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189059. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189060. /* initialize the sort array */
  189061. for (i = 0; i < num_palette; i++)
  189062. {
  189063. png_ptr->index_to_palette[i] = (png_byte)i;
  189064. png_ptr->palette_to_index[i] = (png_byte)i;
  189065. }
  189066. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189067. png_sizeof (png_dsortp)));
  189068. for (i = 0; i < 769; i++)
  189069. hash[i] = NULL;
  189070. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189071. num_new_palette = num_palette;
  189072. /* initial wild guess at how far apart the farthest pixel
  189073. pair we will be eliminating will be. Larger
  189074. numbers mean more areas will be allocated, Smaller
  189075. numbers run the risk of not saving enough data, and
  189076. having to do this all over again.
  189077. I have not done extensive checking on this number.
  189078. */
  189079. max_d = 96;
  189080. while (num_new_palette > maximum_colors)
  189081. {
  189082. for (i = 0; i < num_new_palette - 1; i++)
  189083. {
  189084. int j;
  189085. for (j = i + 1; j < num_new_palette; j++)
  189086. {
  189087. int d;
  189088. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189089. if (d <= max_d)
  189090. {
  189091. t = (png_dsortp)png_malloc_warn(png_ptr,
  189092. (png_uint_32)(png_sizeof(png_dsort)));
  189093. if (t == NULL)
  189094. break;
  189095. t->next = hash[d];
  189096. t->left = (png_byte)i;
  189097. t->right = (png_byte)j;
  189098. hash[d] = t;
  189099. }
  189100. }
  189101. if (t == NULL)
  189102. break;
  189103. }
  189104. if (t != NULL)
  189105. for (i = 0; i <= max_d; i++)
  189106. {
  189107. if (hash[i] != NULL)
  189108. {
  189109. png_dsortp p;
  189110. for (p = hash[i]; p; p = p->next)
  189111. {
  189112. if ((int)png_ptr->index_to_palette[p->left]
  189113. < num_new_palette &&
  189114. (int)png_ptr->index_to_palette[p->right]
  189115. < num_new_palette)
  189116. {
  189117. int j, next_j;
  189118. if (num_new_palette & 0x01)
  189119. {
  189120. j = p->left;
  189121. next_j = p->right;
  189122. }
  189123. else
  189124. {
  189125. j = p->right;
  189126. next_j = p->left;
  189127. }
  189128. num_new_palette--;
  189129. palette[png_ptr->index_to_palette[j]]
  189130. = palette[num_new_palette];
  189131. if (!full_dither)
  189132. {
  189133. int k;
  189134. for (k = 0; k < num_palette; k++)
  189135. {
  189136. if (png_ptr->dither_index[k] ==
  189137. png_ptr->index_to_palette[j])
  189138. png_ptr->dither_index[k] =
  189139. png_ptr->index_to_palette[next_j];
  189140. if ((int)png_ptr->dither_index[k] ==
  189141. num_new_palette)
  189142. png_ptr->dither_index[k] =
  189143. png_ptr->index_to_palette[j];
  189144. }
  189145. }
  189146. png_ptr->index_to_palette[png_ptr->palette_to_index
  189147. [num_new_palette]] = png_ptr->index_to_palette[j];
  189148. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  189149. = png_ptr->palette_to_index[num_new_palette];
  189150. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  189151. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  189152. }
  189153. if (num_new_palette <= maximum_colors)
  189154. break;
  189155. }
  189156. if (num_new_palette <= maximum_colors)
  189157. break;
  189158. }
  189159. }
  189160. for (i = 0; i < 769; i++)
  189161. {
  189162. if (hash[i] != NULL)
  189163. {
  189164. png_dsortp p = hash[i];
  189165. while (p)
  189166. {
  189167. t = p->next;
  189168. png_free(png_ptr, p);
  189169. p = t;
  189170. }
  189171. }
  189172. hash[i] = 0;
  189173. }
  189174. max_d += 96;
  189175. }
  189176. png_free(png_ptr, hash);
  189177. png_free(png_ptr, png_ptr->palette_to_index);
  189178. png_free(png_ptr, png_ptr->index_to_palette);
  189179. png_ptr->palette_to_index=NULL;
  189180. png_ptr->index_to_palette=NULL;
  189181. }
  189182. num_palette = maximum_colors;
  189183. }
  189184. if (png_ptr->palette == NULL)
  189185. {
  189186. png_ptr->palette = palette;
  189187. }
  189188. png_ptr->num_palette = (png_uint_16)num_palette;
  189189. if (full_dither)
  189190. {
  189191. int i;
  189192. png_bytep distance;
  189193. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  189194. PNG_DITHER_BLUE_BITS;
  189195. int num_red = (1 << PNG_DITHER_RED_BITS);
  189196. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  189197. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  189198. png_size_t num_entries = ((png_size_t)1 << total_bits);
  189199. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  189200. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  189201. png_memset(png_ptr->palette_lookup, 0, num_entries *
  189202. png_sizeof (png_byte));
  189203. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  189204. png_sizeof(png_byte)));
  189205. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  189206. for (i = 0; i < num_palette; i++)
  189207. {
  189208. int ir, ig, ib;
  189209. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  189210. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  189211. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  189212. for (ir = 0; ir < num_red; ir++)
  189213. {
  189214. /* int dr = abs(ir - r); */
  189215. int dr = ((ir > r) ? ir - r : r - ir);
  189216. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  189217. for (ig = 0; ig < num_green; ig++)
  189218. {
  189219. /* int dg = abs(ig - g); */
  189220. int dg = ((ig > g) ? ig - g : g - ig);
  189221. int dt = dr + dg;
  189222. int dm = ((dr > dg) ? dr : dg);
  189223. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  189224. for (ib = 0; ib < num_blue; ib++)
  189225. {
  189226. int d_index = index_g | ib;
  189227. /* int db = abs(ib - b); */
  189228. int db = ((ib > b) ? ib - b : b - ib);
  189229. int dmax = ((dm > db) ? dm : db);
  189230. int d = dmax + dt + db;
  189231. if (d < (int)distance[d_index])
  189232. {
  189233. distance[d_index] = (png_byte)d;
  189234. png_ptr->palette_lookup[d_index] = (png_byte)i;
  189235. }
  189236. }
  189237. }
  189238. }
  189239. }
  189240. png_free(png_ptr, distance);
  189241. }
  189242. }
  189243. #endif
  189244. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189245. /* Transform the image from the file_gamma to the screen_gamma. We
  189246. * only do transformations on images where the file_gamma and screen_gamma
  189247. * are not close reciprocals, otherwise it slows things down slightly, and
  189248. * also needlessly introduces small errors.
  189249. *
  189250. * We will turn off gamma transformation later if no semitransparent entries
  189251. * are present in the tRNS array for palette images. We can't do it here
  189252. * because we don't necessarily have the tRNS chunk yet.
  189253. */
  189254. void PNGAPI
  189255. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  189256. {
  189257. png_debug(1, "in png_set_gamma\n");
  189258. if(png_ptr == NULL) return;
  189259. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  189260. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  189261. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  189262. png_ptr->transformations |= PNG_GAMMA;
  189263. png_ptr->gamma = (float)file_gamma;
  189264. png_ptr->screen_gamma = (float)scrn_gamma;
  189265. }
  189266. #endif
  189267. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189268. /* Expand paletted images to RGB, expand grayscale images of
  189269. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  189270. * to alpha channels.
  189271. */
  189272. void PNGAPI
  189273. png_set_expand(png_structp png_ptr)
  189274. {
  189275. png_debug(1, "in png_set_expand\n");
  189276. if(png_ptr == NULL) return;
  189277. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189278. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189279. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189280. #endif
  189281. }
  189282. /* GRR 19990627: the following three functions currently are identical
  189283. * to png_set_expand(). However, it is entirely reasonable that someone
  189284. * might wish to expand an indexed image to RGB but *not* expand a single,
  189285. * fully transparent palette entry to a full alpha channel--perhaps instead
  189286. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  189287. * the transparent color with a particular RGB value, or drop tRNS entirely.
  189288. * IOW, a future version of the library may make the transformations flag
  189289. * a bit more fine-grained, with separate bits for each of these three
  189290. * functions.
  189291. *
  189292. * More to the point, these functions make it obvious what libpng will be
  189293. * doing, whereas "expand" can (and does) mean any number of things.
  189294. *
  189295. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  189296. * to expand only the sample depth but not to expand the tRNS to alpha.
  189297. */
  189298. /* Expand paletted images to RGB. */
  189299. void PNGAPI
  189300. png_set_palette_to_rgb(png_structp png_ptr)
  189301. {
  189302. png_debug(1, "in png_set_palette_to_rgb\n");
  189303. if(png_ptr == NULL) return;
  189304. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189305. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189306. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  189307. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189308. #endif
  189309. }
  189310. #if !defined(PNG_1_0_X)
  189311. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189312. void PNGAPI
  189313. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  189314. {
  189315. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  189316. if(png_ptr == NULL) return;
  189317. png_ptr->transformations |= PNG_EXPAND;
  189318. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189319. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189320. #endif
  189321. }
  189322. #endif
  189323. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  189324. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189325. /* Deprecated as of libpng-1.2.9 */
  189326. void PNGAPI
  189327. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  189328. {
  189329. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  189330. if(png_ptr == NULL) return;
  189331. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189332. }
  189333. #endif
  189334. /* Expand tRNS chunks to alpha channels. */
  189335. void PNGAPI
  189336. png_set_tRNS_to_alpha(png_structp png_ptr)
  189337. {
  189338. png_debug(1, "in png_set_tRNS_to_alpha\n");
  189339. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189340. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189341. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189342. #endif
  189343. }
  189344. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  189345. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189346. void PNGAPI
  189347. png_set_gray_to_rgb(png_structp png_ptr)
  189348. {
  189349. png_debug(1, "in png_set_gray_to_rgb\n");
  189350. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  189351. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189352. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189353. #endif
  189354. }
  189355. #endif
  189356. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189357. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  189358. /* Convert a RGB image to a grayscale of the same width. This allows us,
  189359. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  189360. */
  189361. void PNGAPI
  189362. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  189363. double green)
  189364. {
  189365. int red_fixed = (int)((float)red*100000.0 + 0.5);
  189366. int green_fixed = (int)((float)green*100000.0 + 0.5);
  189367. if(png_ptr == NULL) return;
  189368. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  189369. }
  189370. #endif
  189371. void PNGAPI
  189372. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  189373. png_fixed_point red, png_fixed_point green)
  189374. {
  189375. png_debug(1, "in png_set_rgb_to_gray\n");
  189376. if(png_ptr == NULL) return;
  189377. switch(error_action)
  189378. {
  189379. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  189380. break;
  189381. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  189382. break;
  189383. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  189384. }
  189385. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189386. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189387. png_ptr->transformations |= PNG_EXPAND;
  189388. #else
  189389. {
  189390. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  189391. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  189392. }
  189393. #endif
  189394. {
  189395. png_uint_16 red_int, green_int;
  189396. if(red < 0 || green < 0)
  189397. {
  189398. red_int = 6968; /* .212671 * 32768 + .5 */
  189399. green_int = 23434; /* .715160 * 32768 + .5 */
  189400. }
  189401. else if(red + green < 100000L)
  189402. {
  189403. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  189404. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  189405. }
  189406. else
  189407. {
  189408. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  189409. red_int = 6968;
  189410. green_int = 23434;
  189411. }
  189412. png_ptr->rgb_to_gray_red_coeff = red_int;
  189413. png_ptr->rgb_to_gray_green_coeff = green_int;
  189414. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  189415. }
  189416. }
  189417. #endif
  189418. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  189419. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  189420. defined(PNG_LEGACY_SUPPORTED)
  189421. void PNGAPI
  189422. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  189423. read_user_transform_fn)
  189424. {
  189425. png_debug(1, "in png_set_read_user_transform_fn\n");
  189426. if(png_ptr == NULL) return;
  189427. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  189428. png_ptr->transformations |= PNG_USER_TRANSFORM;
  189429. png_ptr->read_user_transform_fn = read_user_transform_fn;
  189430. #endif
  189431. #ifdef PNG_LEGACY_SUPPORTED
  189432. if(read_user_transform_fn)
  189433. png_warning(png_ptr,
  189434. "This version of libpng does not support user transforms");
  189435. #endif
  189436. }
  189437. #endif
  189438. /* Initialize everything needed for the read. This includes modifying
  189439. * the palette.
  189440. */
  189441. void /* PRIVATE */
  189442. png_init_read_transformations(png_structp png_ptr)
  189443. {
  189444. png_debug(1, "in png_init_read_transformations\n");
  189445. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189446. if(png_ptr != NULL)
  189447. #endif
  189448. {
  189449. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  189450. || defined(PNG_READ_GAMMA_SUPPORTED)
  189451. int color_type = png_ptr->color_type;
  189452. #endif
  189453. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  189454. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189455. /* Detect gray background and attempt to enable optimization
  189456. * for gray --> RGB case */
  189457. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  189458. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  189459. * background color might actually be gray yet not be flagged as such.
  189460. * This is not a problem for the current code, which uses
  189461. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  189462. * png_do_gray_to_rgb() transformation.
  189463. */
  189464. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189465. !(color_type & PNG_COLOR_MASK_COLOR))
  189466. {
  189467. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  189468. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  189469. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189470. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  189471. png_ptr->background.red == png_ptr->background.green &&
  189472. png_ptr->background.red == png_ptr->background.blue)
  189473. {
  189474. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  189475. png_ptr->background.gray = png_ptr->background.red;
  189476. }
  189477. #endif
  189478. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189479. (png_ptr->transformations & PNG_EXPAND))
  189480. {
  189481. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  189482. {
  189483. /* expand background and tRNS chunks */
  189484. switch (png_ptr->bit_depth)
  189485. {
  189486. case 1:
  189487. png_ptr->background.gray *= (png_uint_16)0xff;
  189488. png_ptr->background.red = png_ptr->background.green
  189489. = png_ptr->background.blue = png_ptr->background.gray;
  189490. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189491. {
  189492. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  189493. png_ptr->trans_values.red = png_ptr->trans_values.green
  189494. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189495. }
  189496. break;
  189497. case 2:
  189498. png_ptr->background.gray *= (png_uint_16)0x55;
  189499. png_ptr->background.red = png_ptr->background.green
  189500. = png_ptr->background.blue = png_ptr->background.gray;
  189501. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189502. {
  189503. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  189504. png_ptr->trans_values.red = png_ptr->trans_values.green
  189505. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189506. }
  189507. break;
  189508. case 4:
  189509. png_ptr->background.gray *= (png_uint_16)0x11;
  189510. png_ptr->background.red = png_ptr->background.green
  189511. = png_ptr->background.blue = png_ptr->background.gray;
  189512. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189513. {
  189514. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  189515. png_ptr->trans_values.red = png_ptr->trans_values.green
  189516. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189517. }
  189518. break;
  189519. case 8:
  189520. case 16:
  189521. png_ptr->background.red = png_ptr->background.green
  189522. = png_ptr->background.blue = png_ptr->background.gray;
  189523. break;
  189524. }
  189525. }
  189526. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  189527. {
  189528. png_ptr->background.red =
  189529. png_ptr->palette[png_ptr->background.index].red;
  189530. png_ptr->background.green =
  189531. png_ptr->palette[png_ptr->background.index].green;
  189532. png_ptr->background.blue =
  189533. png_ptr->palette[png_ptr->background.index].blue;
  189534. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  189535. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  189536. {
  189537. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189538. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189539. #endif
  189540. {
  189541. /* invert the alpha channel (in tRNS) unless the pixels are
  189542. going to be expanded, in which case leave it for later */
  189543. int i,istop;
  189544. istop=(int)png_ptr->num_trans;
  189545. for (i=0; i<istop; i++)
  189546. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  189547. }
  189548. }
  189549. #endif
  189550. }
  189551. }
  189552. #endif
  189553. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  189554. png_ptr->background_1 = png_ptr->background;
  189555. #endif
  189556. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189557. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  189558. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  189559. < PNG_GAMMA_THRESHOLD))
  189560. {
  189561. int i,k;
  189562. k=0;
  189563. for (i=0; i<png_ptr->num_trans; i++)
  189564. {
  189565. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  189566. k=1; /* partial transparency is present */
  189567. }
  189568. if (k == 0)
  189569. png_ptr->transformations &= (~PNG_GAMMA);
  189570. }
  189571. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  189572. png_ptr->gamma != 0.0)
  189573. {
  189574. png_build_gamma_table(png_ptr);
  189575. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189576. if (png_ptr->transformations & PNG_BACKGROUND)
  189577. {
  189578. if (color_type == PNG_COLOR_TYPE_PALETTE)
  189579. {
  189580. /* could skip if no transparency and
  189581. */
  189582. png_color back, back_1;
  189583. png_colorp palette = png_ptr->palette;
  189584. int num_palette = png_ptr->num_palette;
  189585. int i;
  189586. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  189587. {
  189588. back.red = png_ptr->gamma_table[png_ptr->background.red];
  189589. back.green = png_ptr->gamma_table[png_ptr->background.green];
  189590. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  189591. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  189592. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  189593. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  189594. }
  189595. else
  189596. {
  189597. double g, gs;
  189598. switch (png_ptr->background_gamma_type)
  189599. {
  189600. case PNG_BACKGROUND_GAMMA_SCREEN:
  189601. g = (png_ptr->screen_gamma);
  189602. gs = 1.0;
  189603. break;
  189604. case PNG_BACKGROUND_GAMMA_FILE:
  189605. g = 1.0 / (png_ptr->gamma);
  189606. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189607. break;
  189608. case PNG_BACKGROUND_GAMMA_UNIQUE:
  189609. g = 1.0 / (png_ptr->background_gamma);
  189610. gs = 1.0 / (png_ptr->background_gamma *
  189611. png_ptr->screen_gamma);
  189612. break;
  189613. default:
  189614. g = 1.0; /* back_1 */
  189615. gs = 1.0; /* back */
  189616. }
  189617. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  189618. {
  189619. back.red = (png_byte)png_ptr->background.red;
  189620. back.green = (png_byte)png_ptr->background.green;
  189621. back.blue = (png_byte)png_ptr->background.blue;
  189622. }
  189623. else
  189624. {
  189625. back.red = (png_byte)(pow(
  189626. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  189627. back.green = (png_byte)(pow(
  189628. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  189629. back.blue = (png_byte)(pow(
  189630. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  189631. }
  189632. back_1.red = (png_byte)(pow(
  189633. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  189634. back_1.green = (png_byte)(pow(
  189635. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  189636. back_1.blue = (png_byte)(pow(
  189637. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  189638. }
  189639. for (i = 0; i < num_palette; i++)
  189640. {
  189641. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  189642. {
  189643. if (png_ptr->trans[i] == 0)
  189644. {
  189645. palette[i] = back;
  189646. }
  189647. else /* if (png_ptr->trans[i] != 0xff) */
  189648. {
  189649. png_byte v, w;
  189650. v = png_ptr->gamma_to_1[palette[i].red];
  189651. png_composite(w, v, png_ptr->trans[i], back_1.red);
  189652. palette[i].red = png_ptr->gamma_from_1[w];
  189653. v = png_ptr->gamma_to_1[palette[i].green];
  189654. png_composite(w, v, png_ptr->trans[i], back_1.green);
  189655. palette[i].green = png_ptr->gamma_from_1[w];
  189656. v = png_ptr->gamma_to_1[palette[i].blue];
  189657. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  189658. palette[i].blue = png_ptr->gamma_from_1[w];
  189659. }
  189660. }
  189661. else
  189662. {
  189663. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189664. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189665. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189666. }
  189667. }
  189668. }
  189669. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  189670. else
  189671. /* color_type != PNG_COLOR_TYPE_PALETTE */
  189672. {
  189673. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  189674. double g = 1.0;
  189675. double gs = 1.0;
  189676. switch (png_ptr->background_gamma_type)
  189677. {
  189678. case PNG_BACKGROUND_GAMMA_SCREEN:
  189679. g = (png_ptr->screen_gamma);
  189680. gs = 1.0;
  189681. break;
  189682. case PNG_BACKGROUND_GAMMA_FILE:
  189683. g = 1.0 / (png_ptr->gamma);
  189684. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189685. break;
  189686. case PNG_BACKGROUND_GAMMA_UNIQUE:
  189687. g = 1.0 / (png_ptr->background_gamma);
  189688. gs = 1.0 / (png_ptr->background_gamma *
  189689. png_ptr->screen_gamma);
  189690. break;
  189691. }
  189692. png_ptr->background_1.gray = (png_uint_16)(pow(
  189693. (double)png_ptr->background.gray / m, g) * m + .5);
  189694. png_ptr->background.gray = (png_uint_16)(pow(
  189695. (double)png_ptr->background.gray / m, gs) * m + .5);
  189696. if ((png_ptr->background.red != png_ptr->background.green) ||
  189697. (png_ptr->background.red != png_ptr->background.blue) ||
  189698. (png_ptr->background.red != png_ptr->background.gray))
  189699. {
  189700. /* RGB or RGBA with color background */
  189701. png_ptr->background_1.red = (png_uint_16)(pow(
  189702. (double)png_ptr->background.red / m, g) * m + .5);
  189703. png_ptr->background_1.green = (png_uint_16)(pow(
  189704. (double)png_ptr->background.green / m, g) * m + .5);
  189705. png_ptr->background_1.blue = (png_uint_16)(pow(
  189706. (double)png_ptr->background.blue / m, g) * m + .5);
  189707. png_ptr->background.red = (png_uint_16)(pow(
  189708. (double)png_ptr->background.red / m, gs) * m + .5);
  189709. png_ptr->background.green = (png_uint_16)(pow(
  189710. (double)png_ptr->background.green / m, gs) * m + .5);
  189711. png_ptr->background.blue = (png_uint_16)(pow(
  189712. (double)png_ptr->background.blue / m, gs) * m + .5);
  189713. }
  189714. else
  189715. {
  189716. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  189717. png_ptr->background_1.red = png_ptr->background_1.green
  189718. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  189719. png_ptr->background.red = png_ptr->background.green
  189720. = png_ptr->background.blue = png_ptr->background.gray;
  189721. }
  189722. }
  189723. }
  189724. else
  189725. /* transformation does not include PNG_BACKGROUND */
  189726. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  189727. if (color_type == PNG_COLOR_TYPE_PALETTE)
  189728. {
  189729. png_colorp palette = png_ptr->palette;
  189730. int num_palette = png_ptr->num_palette;
  189731. int i;
  189732. for (i = 0; i < num_palette; i++)
  189733. {
  189734. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189735. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189736. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189737. }
  189738. }
  189739. }
  189740. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189741. else
  189742. #endif
  189743. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  189744. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189745. /* No GAMMA transformation */
  189746. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  189747. (color_type == PNG_COLOR_TYPE_PALETTE))
  189748. {
  189749. int i;
  189750. int istop = (int)png_ptr->num_trans;
  189751. png_color back;
  189752. png_colorp palette = png_ptr->palette;
  189753. back.red = (png_byte)png_ptr->background.red;
  189754. back.green = (png_byte)png_ptr->background.green;
  189755. back.blue = (png_byte)png_ptr->background.blue;
  189756. for (i = 0; i < istop; i++)
  189757. {
  189758. if (png_ptr->trans[i] == 0)
  189759. {
  189760. palette[i] = back;
  189761. }
  189762. else if (png_ptr->trans[i] != 0xff)
  189763. {
  189764. /* The png_composite() macro is defined in png.h */
  189765. png_composite(palette[i].red, palette[i].red,
  189766. png_ptr->trans[i], back.red);
  189767. png_composite(palette[i].green, palette[i].green,
  189768. png_ptr->trans[i], back.green);
  189769. png_composite(palette[i].blue, palette[i].blue,
  189770. png_ptr->trans[i], back.blue);
  189771. }
  189772. }
  189773. }
  189774. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  189775. #if defined(PNG_READ_SHIFT_SUPPORTED)
  189776. if ((png_ptr->transformations & PNG_SHIFT) &&
  189777. (color_type == PNG_COLOR_TYPE_PALETTE))
  189778. {
  189779. png_uint_16 i;
  189780. png_uint_16 istop = png_ptr->num_palette;
  189781. int sr = 8 - png_ptr->sig_bit.red;
  189782. int sg = 8 - png_ptr->sig_bit.green;
  189783. int sb = 8 - png_ptr->sig_bit.blue;
  189784. if (sr < 0 || sr > 8)
  189785. sr = 0;
  189786. if (sg < 0 || sg > 8)
  189787. sg = 0;
  189788. if (sb < 0 || sb > 8)
  189789. sb = 0;
  189790. for (i = 0; i < istop; i++)
  189791. {
  189792. png_ptr->palette[i].red >>= sr;
  189793. png_ptr->palette[i].green >>= sg;
  189794. png_ptr->palette[i].blue >>= sb;
  189795. }
  189796. }
  189797. #endif /* PNG_READ_SHIFT_SUPPORTED */
  189798. }
  189799. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  189800. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  189801. if(png_ptr)
  189802. return;
  189803. #endif
  189804. }
  189805. /* Modify the info structure to reflect the transformations. The
  189806. * info should be updated so a PNG file could be written with it,
  189807. * assuming the transformations result in valid PNG data.
  189808. */
  189809. void /* PRIVATE */
  189810. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  189811. {
  189812. png_debug(1, "in png_read_transform_info\n");
  189813. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189814. if (png_ptr->transformations & PNG_EXPAND)
  189815. {
  189816. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189817. {
  189818. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  189819. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  189820. else
  189821. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  189822. info_ptr->bit_depth = 8;
  189823. info_ptr->num_trans = 0;
  189824. }
  189825. else
  189826. {
  189827. if (png_ptr->num_trans)
  189828. {
  189829. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  189830. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  189831. else
  189832. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  189833. }
  189834. if (info_ptr->bit_depth < 8)
  189835. info_ptr->bit_depth = 8;
  189836. info_ptr->num_trans = 0;
  189837. }
  189838. }
  189839. #endif
  189840. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189841. if (png_ptr->transformations & PNG_BACKGROUND)
  189842. {
  189843. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  189844. info_ptr->num_trans = 0;
  189845. info_ptr->background = png_ptr->background;
  189846. }
  189847. #endif
  189848. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189849. if (png_ptr->transformations & PNG_GAMMA)
  189850. {
  189851. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189852. info_ptr->gamma = png_ptr->gamma;
  189853. #endif
  189854. #ifdef PNG_FIXED_POINT_SUPPORTED
  189855. info_ptr->int_gamma = png_ptr->int_gamma;
  189856. #endif
  189857. }
  189858. #endif
  189859. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189860. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  189861. info_ptr->bit_depth = 8;
  189862. #endif
  189863. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189864. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  189865. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  189866. #endif
  189867. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189868. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  189869. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  189870. #endif
  189871. #if defined(PNG_READ_DITHER_SUPPORTED)
  189872. if (png_ptr->transformations & PNG_DITHER)
  189873. {
  189874. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  189875. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  189876. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  189877. {
  189878. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  189879. }
  189880. }
  189881. #endif
  189882. #if defined(PNG_READ_PACK_SUPPORTED)
  189883. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  189884. info_ptr->bit_depth = 8;
  189885. #endif
  189886. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189887. info_ptr->channels = 1;
  189888. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  189889. info_ptr->channels = 3;
  189890. else
  189891. info_ptr->channels = 1;
  189892. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189893. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  189894. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  189895. #endif
  189896. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  189897. info_ptr->channels++;
  189898. #if defined(PNG_READ_FILLER_SUPPORTED)
  189899. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  189900. if ((png_ptr->transformations & PNG_FILLER) &&
  189901. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  189902. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  189903. {
  189904. info_ptr->channels++;
  189905. /* if adding a true alpha channel not just filler */
  189906. #if !defined(PNG_1_0_X)
  189907. if (png_ptr->transformations & PNG_ADD_ALPHA)
  189908. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  189909. #endif
  189910. }
  189911. #endif
  189912. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  189913. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  189914. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  189915. {
  189916. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  189917. info_ptr->bit_depth = png_ptr->user_transform_depth;
  189918. if(info_ptr->channels < png_ptr->user_transform_channels)
  189919. info_ptr->channels = png_ptr->user_transform_channels;
  189920. }
  189921. #endif
  189922. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  189923. info_ptr->bit_depth);
  189924. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  189925. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  189926. if(png_ptr)
  189927. return;
  189928. #endif
  189929. }
  189930. /* Transform the row. The order of transformations is significant,
  189931. * and is very touchy. If you add a transformation, take care to
  189932. * decide how it fits in with the other transformations here.
  189933. */
  189934. void /* PRIVATE */
  189935. png_do_read_transformations(png_structp png_ptr)
  189936. {
  189937. png_debug(1, "in png_do_read_transformations\n");
  189938. if (png_ptr->row_buf == NULL)
  189939. {
  189940. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189941. char msg[50];
  189942. png_snprintf2(msg, 50,
  189943. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  189944. png_ptr->pass);
  189945. png_error(png_ptr, msg);
  189946. #else
  189947. png_error(png_ptr, "NULL row buffer");
  189948. #endif
  189949. }
  189950. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189951. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  189952. /* Application has failed to call either png_read_start_image()
  189953. * or png_read_update_info() after setting transforms that expand
  189954. * pixels. This check added to libpng-1.2.19 */
  189955. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  189956. png_error(png_ptr, "Uninitialized row");
  189957. #else
  189958. png_warning(png_ptr, "Uninitialized row");
  189959. #endif
  189960. #endif
  189961. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189962. if (png_ptr->transformations & PNG_EXPAND)
  189963. {
  189964. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  189965. {
  189966. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  189967. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  189968. }
  189969. else
  189970. {
  189971. if (png_ptr->num_trans &&
  189972. (png_ptr->transformations & PNG_EXPAND_tRNS))
  189973. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  189974. &(png_ptr->trans_values));
  189975. else
  189976. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  189977. NULL);
  189978. }
  189979. }
  189980. #endif
  189981. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189982. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  189983. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  189984. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  189985. #endif
  189986. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189987. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  189988. {
  189989. int rgb_error =
  189990. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  189991. if(rgb_error)
  189992. {
  189993. png_ptr->rgb_to_gray_status=1;
  189994. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  189995. PNG_RGB_TO_GRAY_WARN)
  189996. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  189997. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  189998. PNG_RGB_TO_GRAY_ERR)
  189999. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190000. }
  190001. }
  190002. #endif
  190003. /*
  190004. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190005. In most cases, the "simple transparency" should be done prior to doing
  190006. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190007. pixel is transparent. You would also need to make sure that the
  190008. transparency information is upgraded to RGB.
  190009. To summarize, the current flow is:
  190010. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190011. with background "in place" if transparent,
  190012. convert to RGB if necessary
  190013. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190014. convert to RGB if necessary
  190015. To support RGB backgrounds for gray images we need:
  190016. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190017. 3 or 6 bytes and composite with background
  190018. "in place" if transparent (3x compare/pixel
  190019. compared to doing composite with gray bkgrnd)
  190020. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190021. remove alpha bytes (3x float operations/pixel
  190022. compared with composite on gray background)
  190023. Greg's change will do this. The reason it wasn't done before is for
  190024. performance, as this increases the per-pixel operations. If we would check
  190025. in advance if the background was gray or RGB, and position the gray-to-RGB
  190026. transform appropriately, then it would save a lot of work/time.
  190027. */
  190028. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190029. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190030. * for performance reasons */
  190031. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190032. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190033. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190034. #endif
  190035. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190036. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190037. ((png_ptr->num_trans != 0 ) ||
  190038. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190039. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190040. &(png_ptr->trans_values), &(png_ptr->background)
  190041. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190042. , &(png_ptr->background_1),
  190043. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190044. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190045. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190046. png_ptr->gamma_shift
  190047. #endif
  190048. );
  190049. #endif
  190050. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190051. if ((png_ptr->transformations & PNG_GAMMA) &&
  190052. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190053. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190054. ((png_ptr->num_trans != 0) ||
  190055. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190056. #endif
  190057. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190058. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190059. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190060. png_ptr->gamma_shift);
  190061. #endif
  190062. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190063. if (png_ptr->transformations & PNG_16_TO_8)
  190064. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190065. #endif
  190066. #if defined(PNG_READ_DITHER_SUPPORTED)
  190067. if (png_ptr->transformations & PNG_DITHER)
  190068. {
  190069. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190070. png_ptr->palette_lookup, png_ptr->dither_index);
  190071. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190072. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190073. }
  190074. #endif
  190075. #if defined(PNG_READ_INVERT_SUPPORTED)
  190076. if (png_ptr->transformations & PNG_INVERT_MONO)
  190077. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190078. #endif
  190079. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190080. if (png_ptr->transformations & PNG_SHIFT)
  190081. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190082. &(png_ptr->shift));
  190083. #endif
  190084. #if defined(PNG_READ_PACK_SUPPORTED)
  190085. if (png_ptr->transformations & PNG_PACK)
  190086. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190087. #endif
  190088. #if defined(PNG_READ_BGR_SUPPORTED)
  190089. if (png_ptr->transformations & PNG_BGR)
  190090. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190091. #endif
  190092. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190093. if (png_ptr->transformations & PNG_PACKSWAP)
  190094. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190095. #endif
  190096. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190097. /* if gray -> RGB, do so now only if we did not do so above */
  190098. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190099. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190100. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190101. #endif
  190102. #if defined(PNG_READ_FILLER_SUPPORTED)
  190103. if (png_ptr->transformations & PNG_FILLER)
  190104. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190105. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190106. #endif
  190107. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190108. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190109. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190110. #endif
  190111. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190112. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190113. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190114. #endif
  190115. #if defined(PNG_READ_SWAP_SUPPORTED)
  190116. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190117. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190118. #endif
  190119. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190120. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190121. {
  190122. if(png_ptr->read_user_transform_fn != NULL)
  190123. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190124. (png_ptr, /* png_ptr */
  190125. &(png_ptr->row_info), /* row_info: */
  190126. /* png_uint_32 width; width of row */
  190127. /* png_uint_32 rowbytes; number of bytes in row */
  190128. /* png_byte color_type; color type of pixels */
  190129. /* png_byte bit_depth; bit depth of samples */
  190130. /* png_byte channels; number of channels (1-4) */
  190131. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  190132. png_ptr->row_buf + 1); /* start of pixel data for row */
  190133. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190134. if(png_ptr->user_transform_depth)
  190135. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  190136. if(png_ptr->user_transform_channels)
  190137. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  190138. #endif
  190139. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  190140. png_ptr->row_info.channels);
  190141. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  190142. png_ptr->row_info.width);
  190143. }
  190144. #endif
  190145. }
  190146. #if defined(PNG_READ_PACK_SUPPORTED)
  190147. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  190148. * without changing the actual values. Thus, if you had a row with
  190149. * a bit depth of 1, you would end up with bytes that only contained
  190150. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  190151. * png_do_shift() after this.
  190152. */
  190153. void /* PRIVATE */
  190154. png_do_unpack(png_row_infop row_info, png_bytep row)
  190155. {
  190156. png_debug(1, "in png_do_unpack\n");
  190157. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190158. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  190159. #else
  190160. if (row_info->bit_depth < 8)
  190161. #endif
  190162. {
  190163. png_uint_32 i;
  190164. png_uint_32 row_width=row_info->width;
  190165. switch (row_info->bit_depth)
  190166. {
  190167. case 1:
  190168. {
  190169. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  190170. png_bytep dp = row + (png_size_t)row_width - 1;
  190171. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  190172. for (i = 0; i < row_width; i++)
  190173. {
  190174. *dp = (png_byte)((*sp >> shift) & 0x01);
  190175. if (shift == 7)
  190176. {
  190177. shift = 0;
  190178. sp--;
  190179. }
  190180. else
  190181. shift++;
  190182. dp--;
  190183. }
  190184. break;
  190185. }
  190186. case 2:
  190187. {
  190188. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  190189. png_bytep dp = row + (png_size_t)row_width - 1;
  190190. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190191. for (i = 0; i < row_width; i++)
  190192. {
  190193. *dp = (png_byte)((*sp >> shift) & 0x03);
  190194. if (shift == 6)
  190195. {
  190196. shift = 0;
  190197. sp--;
  190198. }
  190199. else
  190200. shift += 2;
  190201. dp--;
  190202. }
  190203. break;
  190204. }
  190205. case 4:
  190206. {
  190207. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  190208. png_bytep dp = row + (png_size_t)row_width - 1;
  190209. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  190210. for (i = 0; i < row_width; i++)
  190211. {
  190212. *dp = (png_byte)((*sp >> shift) & 0x0f);
  190213. if (shift == 4)
  190214. {
  190215. shift = 0;
  190216. sp--;
  190217. }
  190218. else
  190219. shift = 4;
  190220. dp--;
  190221. }
  190222. break;
  190223. }
  190224. }
  190225. row_info->bit_depth = 8;
  190226. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190227. row_info->rowbytes = row_width * row_info->channels;
  190228. }
  190229. }
  190230. #endif
  190231. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190232. /* Reverse the effects of png_do_shift. This routine merely shifts the
  190233. * pixels back to their significant bits values. Thus, if you have
  190234. * a row of bit depth 8, but only 5 are significant, this will shift
  190235. * the values back to 0 through 31.
  190236. */
  190237. void /* PRIVATE */
  190238. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  190239. {
  190240. png_debug(1, "in png_do_unshift\n");
  190241. if (
  190242. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190243. row != NULL && row_info != NULL && sig_bits != NULL &&
  190244. #endif
  190245. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  190246. {
  190247. int shift[4];
  190248. int channels = 0;
  190249. int c;
  190250. png_uint_16 value = 0;
  190251. png_uint_32 row_width = row_info->width;
  190252. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  190253. {
  190254. shift[channels++] = row_info->bit_depth - sig_bits->red;
  190255. shift[channels++] = row_info->bit_depth - sig_bits->green;
  190256. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  190257. }
  190258. else
  190259. {
  190260. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  190261. }
  190262. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  190263. {
  190264. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  190265. }
  190266. for (c = 0; c < channels; c++)
  190267. {
  190268. if (shift[c] <= 0)
  190269. shift[c] = 0;
  190270. else
  190271. value = 1;
  190272. }
  190273. if (!value)
  190274. return;
  190275. switch (row_info->bit_depth)
  190276. {
  190277. case 2:
  190278. {
  190279. png_bytep bp;
  190280. png_uint_32 i;
  190281. png_uint_32 istop = row_info->rowbytes;
  190282. for (bp = row, i = 0; i < istop; i++)
  190283. {
  190284. *bp >>= 1;
  190285. *bp++ &= 0x55;
  190286. }
  190287. break;
  190288. }
  190289. case 4:
  190290. {
  190291. png_bytep bp = row;
  190292. png_uint_32 i;
  190293. png_uint_32 istop = row_info->rowbytes;
  190294. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  190295. (png_byte)((int)0xf >> shift[0]));
  190296. for (i = 0; i < istop; i++)
  190297. {
  190298. *bp >>= shift[0];
  190299. *bp++ &= mask;
  190300. }
  190301. break;
  190302. }
  190303. case 8:
  190304. {
  190305. png_bytep bp = row;
  190306. png_uint_32 i;
  190307. png_uint_32 istop = row_width * channels;
  190308. for (i = 0; i < istop; i++)
  190309. {
  190310. *bp++ >>= shift[i%channels];
  190311. }
  190312. break;
  190313. }
  190314. case 16:
  190315. {
  190316. png_bytep bp = row;
  190317. png_uint_32 i;
  190318. png_uint_32 istop = channels * row_width;
  190319. for (i = 0; i < istop; i++)
  190320. {
  190321. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  190322. value >>= shift[i%channels];
  190323. *bp++ = (png_byte)(value >> 8);
  190324. *bp++ = (png_byte)(value & 0xff);
  190325. }
  190326. break;
  190327. }
  190328. }
  190329. }
  190330. }
  190331. #endif
  190332. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190333. /* chop rows of bit depth 16 down to 8 */
  190334. void /* PRIVATE */
  190335. png_do_chop(png_row_infop row_info, png_bytep row)
  190336. {
  190337. png_debug(1, "in png_do_chop\n");
  190338. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190339. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  190340. #else
  190341. if (row_info->bit_depth == 16)
  190342. #endif
  190343. {
  190344. png_bytep sp = row;
  190345. png_bytep dp = row;
  190346. png_uint_32 i;
  190347. png_uint_32 istop = row_info->width * row_info->channels;
  190348. for (i = 0; i<istop; i++, sp += 2, dp++)
  190349. {
  190350. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  190351. /* This does a more accurate scaling of the 16-bit color
  190352. * value, rather than a simple low-byte truncation.
  190353. *
  190354. * What the ideal calculation should be:
  190355. * *dp = (((((png_uint_32)(*sp) << 8) |
  190356. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  190357. *
  190358. * GRR: no, I think this is what it really should be:
  190359. * *dp = (((((png_uint_32)(*sp) << 8) |
  190360. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  190361. *
  190362. * GRR: here's the exact calculation with shifts:
  190363. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  190364. * *dp = (temp - (temp >> 8)) >> 8;
  190365. *
  190366. * Approximate calculation with shift/add instead of multiply/divide:
  190367. * *dp = ((((png_uint_32)(*sp) << 8) |
  190368. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  190369. *
  190370. * What we actually do to avoid extra shifting and conversion:
  190371. */
  190372. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  190373. #else
  190374. /* Simply discard the low order byte */
  190375. *dp = *sp;
  190376. #endif
  190377. }
  190378. row_info->bit_depth = 8;
  190379. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190380. row_info->rowbytes = row_info->width * row_info->channels;
  190381. }
  190382. }
  190383. #endif
  190384. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190385. void /* PRIVATE */
  190386. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  190387. {
  190388. png_debug(1, "in png_do_read_swap_alpha\n");
  190389. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190390. if (row != NULL && row_info != NULL)
  190391. #endif
  190392. {
  190393. png_uint_32 row_width = row_info->width;
  190394. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190395. {
  190396. /* This converts from RGBA to ARGB */
  190397. if (row_info->bit_depth == 8)
  190398. {
  190399. png_bytep sp = row + row_info->rowbytes;
  190400. png_bytep dp = sp;
  190401. png_byte save;
  190402. png_uint_32 i;
  190403. for (i = 0; i < row_width; i++)
  190404. {
  190405. save = *(--sp);
  190406. *(--dp) = *(--sp);
  190407. *(--dp) = *(--sp);
  190408. *(--dp) = *(--sp);
  190409. *(--dp) = save;
  190410. }
  190411. }
  190412. /* This converts from RRGGBBAA to AARRGGBB */
  190413. else
  190414. {
  190415. png_bytep sp = row + row_info->rowbytes;
  190416. png_bytep dp = sp;
  190417. png_byte save[2];
  190418. png_uint_32 i;
  190419. for (i = 0; i < row_width; i++)
  190420. {
  190421. save[0] = *(--sp);
  190422. save[1] = *(--sp);
  190423. *(--dp) = *(--sp);
  190424. *(--dp) = *(--sp);
  190425. *(--dp) = *(--sp);
  190426. *(--dp) = *(--sp);
  190427. *(--dp) = *(--sp);
  190428. *(--dp) = *(--sp);
  190429. *(--dp) = save[0];
  190430. *(--dp) = save[1];
  190431. }
  190432. }
  190433. }
  190434. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190435. {
  190436. /* This converts from GA to AG */
  190437. if (row_info->bit_depth == 8)
  190438. {
  190439. png_bytep sp = row + row_info->rowbytes;
  190440. png_bytep dp = sp;
  190441. png_byte save;
  190442. png_uint_32 i;
  190443. for (i = 0; i < row_width; i++)
  190444. {
  190445. save = *(--sp);
  190446. *(--dp) = *(--sp);
  190447. *(--dp) = save;
  190448. }
  190449. }
  190450. /* This converts from GGAA to AAGG */
  190451. else
  190452. {
  190453. png_bytep sp = row + row_info->rowbytes;
  190454. png_bytep dp = sp;
  190455. png_byte save[2];
  190456. png_uint_32 i;
  190457. for (i = 0; i < row_width; i++)
  190458. {
  190459. save[0] = *(--sp);
  190460. save[1] = *(--sp);
  190461. *(--dp) = *(--sp);
  190462. *(--dp) = *(--sp);
  190463. *(--dp) = save[0];
  190464. *(--dp) = save[1];
  190465. }
  190466. }
  190467. }
  190468. }
  190469. }
  190470. #endif
  190471. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190472. void /* PRIVATE */
  190473. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  190474. {
  190475. png_debug(1, "in png_do_read_invert_alpha\n");
  190476. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190477. if (row != NULL && row_info != NULL)
  190478. #endif
  190479. {
  190480. png_uint_32 row_width = row_info->width;
  190481. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190482. {
  190483. /* This inverts the alpha channel in RGBA */
  190484. if (row_info->bit_depth == 8)
  190485. {
  190486. png_bytep sp = row + row_info->rowbytes;
  190487. png_bytep dp = sp;
  190488. png_uint_32 i;
  190489. for (i = 0; i < row_width; i++)
  190490. {
  190491. *(--dp) = (png_byte)(255 - *(--sp));
  190492. /* This does nothing:
  190493. *(--dp) = *(--sp);
  190494. *(--dp) = *(--sp);
  190495. *(--dp) = *(--sp);
  190496. We can replace it with:
  190497. */
  190498. sp-=3;
  190499. dp=sp;
  190500. }
  190501. }
  190502. /* This inverts the alpha channel in RRGGBBAA */
  190503. else
  190504. {
  190505. png_bytep sp = row + row_info->rowbytes;
  190506. png_bytep dp = sp;
  190507. png_uint_32 i;
  190508. for (i = 0; i < row_width; i++)
  190509. {
  190510. *(--dp) = (png_byte)(255 - *(--sp));
  190511. *(--dp) = (png_byte)(255 - *(--sp));
  190512. /* This does nothing:
  190513. *(--dp) = *(--sp);
  190514. *(--dp) = *(--sp);
  190515. *(--dp) = *(--sp);
  190516. *(--dp) = *(--sp);
  190517. *(--dp) = *(--sp);
  190518. *(--dp) = *(--sp);
  190519. We can replace it with:
  190520. */
  190521. sp-=6;
  190522. dp=sp;
  190523. }
  190524. }
  190525. }
  190526. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190527. {
  190528. /* This inverts the alpha channel in GA */
  190529. if (row_info->bit_depth == 8)
  190530. {
  190531. png_bytep sp = row + row_info->rowbytes;
  190532. png_bytep dp = sp;
  190533. png_uint_32 i;
  190534. for (i = 0; i < row_width; i++)
  190535. {
  190536. *(--dp) = (png_byte)(255 - *(--sp));
  190537. *(--dp) = *(--sp);
  190538. }
  190539. }
  190540. /* This inverts the alpha channel in GGAA */
  190541. else
  190542. {
  190543. png_bytep sp = row + row_info->rowbytes;
  190544. png_bytep dp = sp;
  190545. png_uint_32 i;
  190546. for (i = 0; i < row_width; i++)
  190547. {
  190548. *(--dp) = (png_byte)(255 - *(--sp));
  190549. *(--dp) = (png_byte)(255 - *(--sp));
  190550. /*
  190551. *(--dp) = *(--sp);
  190552. *(--dp) = *(--sp);
  190553. */
  190554. sp-=2;
  190555. dp=sp;
  190556. }
  190557. }
  190558. }
  190559. }
  190560. }
  190561. #endif
  190562. #if defined(PNG_READ_FILLER_SUPPORTED)
  190563. /* Add filler channel if we have RGB color */
  190564. void /* PRIVATE */
  190565. png_do_read_filler(png_row_infop row_info, png_bytep row,
  190566. png_uint_32 filler, png_uint_32 flags)
  190567. {
  190568. png_uint_32 i;
  190569. png_uint_32 row_width = row_info->width;
  190570. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  190571. png_byte lo_filler = (png_byte)(filler & 0xff);
  190572. png_debug(1, "in png_do_read_filler\n");
  190573. if (
  190574. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190575. row != NULL && row_info != NULL &&
  190576. #endif
  190577. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  190578. {
  190579. if(row_info->bit_depth == 8)
  190580. {
  190581. /* This changes the data from G to GX */
  190582. if (flags & PNG_FLAG_FILLER_AFTER)
  190583. {
  190584. png_bytep sp = row + (png_size_t)row_width;
  190585. png_bytep dp = sp + (png_size_t)row_width;
  190586. for (i = 1; i < row_width; i++)
  190587. {
  190588. *(--dp) = lo_filler;
  190589. *(--dp) = *(--sp);
  190590. }
  190591. *(--dp) = lo_filler;
  190592. row_info->channels = 2;
  190593. row_info->pixel_depth = 16;
  190594. row_info->rowbytes = row_width * 2;
  190595. }
  190596. /* This changes the data from G to XG */
  190597. else
  190598. {
  190599. png_bytep sp = row + (png_size_t)row_width;
  190600. png_bytep dp = sp + (png_size_t)row_width;
  190601. for (i = 0; i < row_width; i++)
  190602. {
  190603. *(--dp) = *(--sp);
  190604. *(--dp) = lo_filler;
  190605. }
  190606. row_info->channels = 2;
  190607. row_info->pixel_depth = 16;
  190608. row_info->rowbytes = row_width * 2;
  190609. }
  190610. }
  190611. else if(row_info->bit_depth == 16)
  190612. {
  190613. /* This changes the data from GG to GGXX */
  190614. if (flags & PNG_FLAG_FILLER_AFTER)
  190615. {
  190616. png_bytep sp = row + (png_size_t)row_width * 2;
  190617. png_bytep dp = sp + (png_size_t)row_width * 2;
  190618. for (i = 1; i < row_width; i++)
  190619. {
  190620. *(--dp) = hi_filler;
  190621. *(--dp) = lo_filler;
  190622. *(--dp) = *(--sp);
  190623. *(--dp) = *(--sp);
  190624. }
  190625. *(--dp) = hi_filler;
  190626. *(--dp) = lo_filler;
  190627. row_info->channels = 2;
  190628. row_info->pixel_depth = 32;
  190629. row_info->rowbytes = row_width * 4;
  190630. }
  190631. /* This changes the data from GG to XXGG */
  190632. else
  190633. {
  190634. png_bytep sp = row + (png_size_t)row_width * 2;
  190635. png_bytep dp = sp + (png_size_t)row_width * 2;
  190636. for (i = 0; i < row_width; i++)
  190637. {
  190638. *(--dp) = *(--sp);
  190639. *(--dp) = *(--sp);
  190640. *(--dp) = hi_filler;
  190641. *(--dp) = lo_filler;
  190642. }
  190643. row_info->channels = 2;
  190644. row_info->pixel_depth = 32;
  190645. row_info->rowbytes = row_width * 4;
  190646. }
  190647. }
  190648. } /* COLOR_TYPE == GRAY */
  190649. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190650. {
  190651. if(row_info->bit_depth == 8)
  190652. {
  190653. /* This changes the data from RGB to RGBX */
  190654. if (flags & PNG_FLAG_FILLER_AFTER)
  190655. {
  190656. png_bytep sp = row + (png_size_t)row_width * 3;
  190657. png_bytep dp = sp + (png_size_t)row_width;
  190658. for (i = 1; i < row_width; i++)
  190659. {
  190660. *(--dp) = lo_filler;
  190661. *(--dp) = *(--sp);
  190662. *(--dp) = *(--sp);
  190663. *(--dp) = *(--sp);
  190664. }
  190665. *(--dp) = lo_filler;
  190666. row_info->channels = 4;
  190667. row_info->pixel_depth = 32;
  190668. row_info->rowbytes = row_width * 4;
  190669. }
  190670. /* This changes the data from RGB to XRGB */
  190671. else
  190672. {
  190673. png_bytep sp = row + (png_size_t)row_width * 3;
  190674. png_bytep dp = sp + (png_size_t)row_width;
  190675. for (i = 0; i < row_width; i++)
  190676. {
  190677. *(--dp) = *(--sp);
  190678. *(--dp) = *(--sp);
  190679. *(--dp) = *(--sp);
  190680. *(--dp) = lo_filler;
  190681. }
  190682. row_info->channels = 4;
  190683. row_info->pixel_depth = 32;
  190684. row_info->rowbytes = row_width * 4;
  190685. }
  190686. }
  190687. else if(row_info->bit_depth == 16)
  190688. {
  190689. /* This changes the data from RRGGBB to RRGGBBXX */
  190690. if (flags & PNG_FLAG_FILLER_AFTER)
  190691. {
  190692. png_bytep sp = row + (png_size_t)row_width * 6;
  190693. png_bytep dp = sp + (png_size_t)row_width * 2;
  190694. for (i = 1; i < row_width; i++)
  190695. {
  190696. *(--dp) = hi_filler;
  190697. *(--dp) = lo_filler;
  190698. *(--dp) = *(--sp);
  190699. *(--dp) = *(--sp);
  190700. *(--dp) = *(--sp);
  190701. *(--dp) = *(--sp);
  190702. *(--dp) = *(--sp);
  190703. *(--dp) = *(--sp);
  190704. }
  190705. *(--dp) = hi_filler;
  190706. *(--dp) = lo_filler;
  190707. row_info->channels = 4;
  190708. row_info->pixel_depth = 64;
  190709. row_info->rowbytes = row_width * 8;
  190710. }
  190711. /* This changes the data from RRGGBB to XXRRGGBB */
  190712. else
  190713. {
  190714. png_bytep sp = row + (png_size_t)row_width * 6;
  190715. png_bytep dp = sp + (png_size_t)row_width * 2;
  190716. for (i = 0; i < row_width; i++)
  190717. {
  190718. *(--dp) = *(--sp);
  190719. *(--dp) = *(--sp);
  190720. *(--dp) = *(--sp);
  190721. *(--dp) = *(--sp);
  190722. *(--dp) = *(--sp);
  190723. *(--dp) = *(--sp);
  190724. *(--dp) = hi_filler;
  190725. *(--dp) = lo_filler;
  190726. }
  190727. row_info->channels = 4;
  190728. row_info->pixel_depth = 64;
  190729. row_info->rowbytes = row_width * 8;
  190730. }
  190731. }
  190732. } /* COLOR_TYPE == RGB */
  190733. }
  190734. #endif
  190735. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190736. /* expand grayscale files to RGB, with or without alpha */
  190737. void /* PRIVATE */
  190738. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  190739. {
  190740. png_uint_32 i;
  190741. png_uint_32 row_width = row_info->width;
  190742. png_debug(1, "in png_do_gray_to_rgb\n");
  190743. if (row_info->bit_depth >= 8 &&
  190744. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190745. row != NULL && row_info != NULL &&
  190746. #endif
  190747. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  190748. {
  190749. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  190750. {
  190751. if (row_info->bit_depth == 8)
  190752. {
  190753. png_bytep sp = row + (png_size_t)row_width - 1;
  190754. png_bytep dp = sp + (png_size_t)row_width * 2;
  190755. for (i = 0; i < row_width; i++)
  190756. {
  190757. *(dp--) = *sp;
  190758. *(dp--) = *sp;
  190759. *(dp--) = *(sp--);
  190760. }
  190761. }
  190762. else
  190763. {
  190764. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  190765. png_bytep dp = sp + (png_size_t)row_width * 4;
  190766. for (i = 0; i < row_width; i++)
  190767. {
  190768. *(dp--) = *sp;
  190769. *(dp--) = *(sp - 1);
  190770. *(dp--) = *sp;
  190771. *(dp--) = *(sp - 1);
  190772. *(dp--) = *(sp--);
  190773. *(dp--) = *(sp--);
  190774. }
  190775. }
  190776. }
  190777. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190778. {
  190779. if (row_info->bit_depth == 8)
  190780. {
  190781. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  190782. png_bytep dp = sp + (png_size_t)row_width * 2;
  190783. for (i = 0; i < row_width; i++)
  190784. {
  190785. *(dp--) = *(sp--);
  190786. *(dp--) = *sp;
  190787. *(dp--) = *sp;
  190788. *(dp--) = *(sp--);
  190789. }
  190790. }
  190791. else
  190792. {
  190793. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  190794. png_bytep dp = sp + (png_size_t)row_width * 4;
  190795. for (i = 0; i < row_width; i++)
  190796. {
  190797. *(dp--) = *(sp--);
  190798. *(dp--) = *(sp--);
  190799. *(dp--) = *sp;
  190800. *(dp--) = *(sp - 1);
  190801. *(dp--) = *sp;
  190802. *(dp--) = *(sp - 1);
  190803. *(dp--) = *(sp--);
  190804. *(dp--) = *(sp--);
  190805. }
  190806. }
  190807. }
  190808. row_info->channels += (png_byte)2;
  190809. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  190810. row_info->pixel_depth = (png_byte)(row_info->channels *
  190811. row_info->bit_depth);
  190812. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190813. }
  190814. }
  190815. #endif
  190816. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190817. /* reduce RGB files to grayscale, with or without alpha
  190818. * using the equation given in Poynton's ColorFAQ at
  190819. * <http://www.inforamp.net/~poynton/>
  190820. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  190821. *
  190822. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  190823. *
  190824. * We approximate this with
  190825. *
  190826. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  190827. *
  190828. * which can be expressed with integers as
  190829. *
  190830. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  190831. *
  190832. * The calculation is to be done in a linear colorspace.
  190833. *
  190834. * Other integer coefficents can be used via png_set_rgb_to_gray().
  190835. */
  190836. int /* PRIVATE */
  190837. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  190838. {
  190839. png_uint_32 i;
  190840. png_uint_32 row_width = row_info->width;
  190841. int rgb_error = 0;
  190842. png_debug(1, "in png_do_rgb_to_gray\n");
  190843. if (
  190844. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190845. row != NULL && row_info != NULL &&
  190846. #endif
  190847. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  190848. {
  190849. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  190850. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  190851. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  190852. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190853. {
  190854. if (row_info->bit_depth == 8)
  190855. {
  190856. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  190857. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  190858. {
  190859. png_bytep sp = row;
  190860. png_bytep dp = row;
  190861. for (i = 0; i < row_width; i++)
  190862. {
  190863. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  190864. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  190865. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  190866. if(red != green || red != blue)
  190867. {
  190868. rgb_error |= 1;
  190869. *(dp++) = png_ptr->gamma_from_1[
  190870. (rc*red+gc*green+bc*blue)>>15];
  190871. }
  190872. else
  190873. *(dp++) = *(sp-1);
  190874. }
  190875. }
  190876. else
  190877. #endif
  190878. {
  190879. png_bytep sp = row;
  190880. png_bytep dp = row;
  190881. for (i = 0; i < row_width; i++)
  190882. {
  190883. png_byte red = *(sp++);
  190884. png_byte green = *(sp++);
  190885. png_byte blue = *(sp++);
  190886. if(red != green || red != blue)
  190887. {
  190888. rgb_error |= 1;
  190889. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  190890. }
  190891. else
  190892. *(dp++) = *(sp-1);
  190893. }
  190894. }
  190895. }
  190896. else /* RGB bit_depth == 16 */
  190897. {
  190898. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  190899. if (png_ptr->gamma_16_to_1 != NULL &&
  190900. png_ptr->gamma_16_from_1 != NULL)
  190901. {
  190902. png_bytep sp = row;
  190903. png_bytep dp = row;
  190904. for (i = 0; i < row_width; i++)
  190905. {
  190906. png_uint_16 red, green, blue, w;
  190907. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  190908. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  190909. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  190910. if(red == green && red == blue)
  190911. w = red;
  190912. else
  190913. {
  190914. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  190915. png_ptr->gamma_shift][red>>8];
  190916. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  190917. png_ptr->gamma_shift][green>>8];
  190918. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  190919. png_ptr->gamma_shift][blue>>8];
  190920. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  190921. + bc*blue_1)>>15);
  190922. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  190923. png_ptr->gamma_shift][gray16 >> 8];
  190924. rgb_error |= 1;
  190925. }
  190926. *(dp++) = (png_byte)((w>>8) & 0xff);
  190927. *(dp++) = (png_byte)(w & 0xff);
  190928. }
  190929. }
  190930. else
  190931. #endif
  190932. {
  190933. png_bytep sp = row;
  190934. png_bytep dp = row;
  190935. for (i = 0; i < row_width; i++)
  190936. {
  190937. png_uint_16 red, green, blue, gray16;
  190938. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  190939. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  190940. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  190941. if(red != green || red != blue)
  190942. rgb_error |= 1;
  190943. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  190944. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  190945. *(dp++) = (png_byte)(gray16 & 0xff);
  190946. }
  190947. }
  190948. }
  190949. }
  190950. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190951. {
  190952. if (row_info->bit_depth == 8)
  190953. {
  190954. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  190955. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  190956. {
  190957. png_bytep sp = row;
  190958. png_bytep dp = row;
  190959. for (i = 0; i < row_width; i++)
  190960. {
  190961. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  190962. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  190963. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  190964. if(red != green || red != blue)
  190965. rgb_error |= 1;
  190966. *(dp++) = png_ptr->gamma_from_1
  190967. [(rc*red + gc*green + bc*blue)>>15];
  190968. *(dp++) = *(sp++); /* alpha */
  190969. }
  190970. }
  190971. else
  190972. #endif
  190973. {
  190974. png_bytep sp = row;
  190975. png_bytep dp = row;
  190976. for (i = 0; i < row_width; i++)
  190977. {
  190978. png_byte red = *(sp++);
  190979. png_byte green = *(sp++);
  190980. png_byte blue = *(sp++);
  190981. if(red != green || red != blue)
  190982. rgb_error |= 1;
  190983. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  190984. *(dp++) = *(sp++); /* alpha */
  190985. }
  190986. }
  190987. }
  190988. else /* RGBA bit_depth == 16 */
  190989. {
  190990. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  190991. if (png_ptr->gamma_16_to_1 != NULL &&
  190992. png_ptr->gamma_16_from_1 != NULL)
  190993. {
  190994. png_bytep sp = row;
  190995. png_bytep dp = row;
  190996. for (i = 0; i < row_width; i++)
  190997. {
  190998. png_uint_16 red, green, blue, w;
  190999. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191000. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191001. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191002. if(red == green && red == blue)
  191003. w = red;
  191004. else
  191005. {
  191006. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191007. png_ptr->gamma_shift][red>>8];
  191008. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191009. png_ptr->gamma_shift][green>>8];
  191010. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191011. png_ptr->gamma_shift][blue>>8];
  191012. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191013. + gc * green_1 + bc * blue_1)>>15);
  191014. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191015. png_ptr->gamma_shift][gray16 >> 8];
  191016. rgb_error |= 1;
  191017. }
  191018. *(dp++) = (png_byte)((w>>8) & 0xff);
  191019. *(dp++) = (png_byte)(w & 0xff);
  191020. *(dp++) = *(sp++); /* alpha */
  191021. *(dp++) = *(sp++);
  191022. }
  191023. }
  191024. else
  191025. #endif
  191026. {
  191027. png_bytep sp = row;
  191028. png_bytep dp = row;
  191029. for (i = 0; i < row_width; i++)
  191030. {
  191031. png_uint_16 red, green, blue, gray16;
  191032. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191033. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191034. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191035. if(red != green || red != blue)
  191036. rgb_error |= 1;
  191037. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191038. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191039. *(dp++) = (png_byte)(gray16 & 0xff);
  191040. *(dp++) = *(sp++); /* alpha */
  191041. *(dp++) = *(sp++);
  191042. }
  191043. }
  191044. }
  191045. }
  191046. row_info->channels -= (png_byte)2;
  191047. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191048. row_info->pixel_depth = (png_byte)(row_info->channels *
  191049. row_info->bit_depth);
  191050. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191051. }
  191052. return rgb_error;
  191053. }
  191054. #endif
  191055. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191056. * large of png_color. This lets grayscale images be treated as
  191057. * paletted. Most useful for gamma correction and simplification
  191058. * of code.
  191059. */
  191060. void PNGAPI
  191061. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191062. {
  191063. int num_palette;
  191064. int color_inc;
  191065. int i;
  191066. int v;
  191067. png_debug(1, "in png_do_build_grayscale_palette\n");
  191068. if (palette == NULL)
  191069. return;
  191070. switch (bit_depth)
  191071. {
  191072. case 1:
  191073. num_palette = 2;
  191074. color_inc = 0xff;
  191075. break;
  191076. case 2:
  191077. num_palette = 4;
  191078. color_inc = 0x55;
  191079. break;
  191080. case 4:
  191081. num_palette = 16;
  191082. color_inc = 0x11;
  191083. break;
  191084. case 8:
  191085. num_palette = 256;
  191086. color_inc = 1;
  191087. break;
  191088. default:
  191089. num_palette = 0;
  191090. color_inc = 0;
  191091. break;
  191092. }
  191093. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191094. {
  191095. palette[i].red = (png_byte)v;
  191096. palette[i].green = (png_byte)v;
  191097. palette[i].blue = (png_byte)v;
  191098. }
  191099. }
  191100. /* This function is currently unused. Do we really need it? */
  191101. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191102. void /* PRIVATE */
  191103. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191104. int num_palette)
  191105. {
  191106. png_debug(1, "in png_correct_palette\n");
  191107. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191108. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191109. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191110. {
  191111. png_color back, back_1;
  191112. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191113. {
  191114. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191115. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191116. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191117. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191118. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191119. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191120. }
  191121. else
  191122. {
  191123. double g;
  191124. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191125. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191126. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  191127. {
  191128. back.red = png_ptr->background.red;
  191129. back.green = png_ptr->background.green;
  191130. back.blue = png_ptr->background.blue;
  191131. }
  191132. else
  191133. {
  191134. back.red =
  191135. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191136. 255.0 + 0.5);
  191137. back.green =
  191138. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191139. 255.0 + 0.5);
  191140. back.blue =
  191141. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191142. 255.0 + 0.5);
  191143. }
  191144. g = 1.0 / png_ptr->background_gamma;
  191145. back_1.red =
  191146. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191147. 255.0 + 0.5);
  191148. back_1.green =
  191149. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191150. 255.0 + 0.5);
  191151. back_1.blue =
  191152. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191153. 255.0 + 0.5);
  191154. }
  191155. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191156. {
  191157. png_uint_32 i;
  191158. for (i = 0; i < (png_uint_32)num_palette; i++)
  191159. {
  191160. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  191161. {
  191162. palette[i] = back;
  191163. }
  191164. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191165. {
  191166. png_byte v, w;
  191167. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  191168. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191169. palette[i].red = png_ptr->gamma_from_1[w];
  191170. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  191171. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191172. palette[i].green = png_ptr->gamma_from_1[w];
  191173. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  191174. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191175. palette[i].blue = png_ptr->gamma_from_1[w];
  191176. }
  191177. else
  191178. {
  191179. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191180. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191181. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191182. }
  191183. }
  191184. }
  191185. else
  191186. {
  191187. int i;
  191188. for (i = 0; i < num_palette; i++)
  191189. {
  191190. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  191191. {
  191192. palette[i] = back;
  191193. }
  191194. else
  191195. {
  191196. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191197. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191198. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191199. }
  191200. }
  191201. }
  191202. }
  191203. else
  191204. #endif
  191205. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191206. if (png_ptr->transformations & PNG_GAMMA)
  191207. {
  191208. int i;
  191209. for (i = 0; i < num_palette; i++)
  191210. {
  191211. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191212. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191213. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191214. }
  191215. }
  191216. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191217. else
  191218. #endif
  191219. #endif
  191220. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191221. if (png_ptr->transformations & PNG_BACKGROUND)
  191222. {
  191223. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191224. {
  191225. png_color back;
  191226. back.red = (png_byte)png_ptr->background.red;
  191227. back.green = (png_byte)png_ptr->background.green;
  191228. back.blue = (png_byte)png_ptr->background.blue;
  191229. for (i = 0; i < (int)png_ptr->num_trans; i++)
  191230. {
  191231. if (png_ptr->trans[i] == 0)
  191232. {
  191233. palette[i].red = back.red;
  191234. palette[i].green = back.green;
  191235. palette[i].blue = back.blue;
  191236. }
  191237. else if (png_ptr->trans[i] != 0xff)
  191238. {
  191239. png_composite(palette[i].red, png_ptr->palette[i].red,
  191240. png_ptr->trans[i], back.red);
  191241. png_composite(palette[i].green, png_ptr->palette[i].green,
  191242. png_ptr->trans[i], back.green);
  191243. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  191244. png_ptr->trans[i], back.blue);
  191245. }
  191246. }
  191247. }
  191248. else /* assume grayscale palette (what else could it be?) */
  191249. {
  191250. int i;
  191251. for (i = 0; i < num_palette; i++)
  191252. {
  191253. if (i == (png_byte)png_ptr->trans_values.gray)
  191254. {
  191255. palette[i].red = (png_byte)png_ptr->background.red;
  191256. palette[i].green = (png_byte)png_ptr->background.green;
  191257. palette[i].blue = (png_byte)png_ptr->background.blue;
  191258. }
  191259. }
  191260. }
  191261. }
  191262. #endif
  191263. }
  191264. #endif
  191265. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191266. /* Replace any alpha or transparency with the supplied background color.
  191267. * "background" is already in the screen gamma, while "background_1" is
  191268. * at a gamma of 1.0. Paletted files have already been taken care of.
  191269. */
  191270. void /* PRIVATE */
  191271. png_do_background(png_row_infop row_info, png_bytep row,
  191272. png_color_16p trans_values, png_color_16p background
  191273. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191274. , png_color_16p background_1,
  191275. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  191276. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  191277. png_uint_16pp gamma_16_to_1, int gamma_shift
  191278. #endif
  191279. )
  191280. {
  191281. png_bytep sp, dp;
  191282. png_uint_32 i;
  191283. png_uint_32 row_width=row_info->width;
  191284. int shift;
  191285. png_debug(1, "in png_do_background\n");
  191286. if (background != NULL &&
  191287. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191288. row != NULL && row_info != NULL &&
  191289. #endif
  191290. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  191291. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  191292. {
  191293. switch (row_info->color_type)
  191294. {
  191295. case PNG_COLOR_TYPE_GRAY:
  191296. {
  191297. switch (row_info->bit_depth)
  191298. {
  191299. case 1:
  191300. {
  191301. sp = row;
  191302. shift = 7;
  191303. for (i = 0; i < row_width; i++)
  191304. {
  191305. if ((png_uint_16)((*sp >> shift) & 0x01)
  191306. == trans_values->gray)
  191307. {
  191308. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191309. *sp |= (png_byte)(background->gray << shift);
  191310. }
  191311. if (!shift)
  191312. {
  191313. shift = 7;
  191314. sp++;
  191315. }
  191316. else
  191317. shift--;
  191318. }
  191319. break;
  191320. }
  191321. case 2:
  191322. {
  191323. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191324. if (gamma_table != NULL)
  191325. {
  191326. sp = row;
  191327. shift = 6;
  191328. for (i = 0; i < row_width; i++)
  191329. {
  191330. if ((png_uint_16)((*sp >> shift) & 0x03)
  191331. == trans_values->gray)
  191332. {
  191333. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191334. *sp |= (png_byte)(background->gray << shift);
  191335. }
  191336. else
  191337. {
  191338. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  191339. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  191340. (p << 4) | (p << 6)] >> 6) & 0x03);
  191341. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191342. *sp |= (png_byte)(g << shift);
  191343. }
  191344. if (!shift)
  191345. {
  191346. shift = 6;
  191347. sp++;
  191348. }
  191349. else
  191350. shift -= 2;
  191351. }
  191352. }
  191353. else
  191354. #endif
  191355. {
  191356. sp = row;
  191357. shift = 6;
  191358. for (i = 0; i < row_width; i++)
  191359. {
  191360. if ((png_uint_16)((*sp >> shift) & 0x03)
  191361. == trans_values->gray)
  191362. {
  191363. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191364. *sp |= (png_byte)(background->gray << shift);
  191365. }
  191366. if (!shift)
  191367. {
  191368. shift = 6;
  191369. sp++;
  191370. }
  191371. else
  191372. shift -= 2;
  191373. }
  191374. }
  191375. break;
  191376. }
  191377. case 4:
  191378. {
  191379. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191380. if (gamma_table != NULL)
  191381. {
  191382. sp = row;
  191383. shift = 4;
  191384. for (i = 0; i < row_width; i++)
  191385. {
  191386. if ((png_uint_16)((*sp >> shift) & 0x0f)
  191387. == trans_values->gray)
  191388. {
  191389. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191390. *sp |= (png_byte)(background->gray << shift);
  191391. }
  191392. else
  191393. {
  191394. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  191395. png_byte g = (png_byte)((gamma_table[p |
  191396. (p << 4)] >> 4) & 0x0f);
  191397. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191398. *sp |= (png_byte)(g << shift);
  191399. }
  191400. if (!shift)
  191401. {
  191402. shift = 4;
  191403. sp++;
  191404. }
  191405. else
  191406. shift -= 4;
  191407. }
  191408. }
  191409. else
  191410. #endif
  191411. {
  191412. sp = row;
  191413. shift = 4;
  191414. for (i = 0; i < row_width; i++)
  191415. {
  191416. if ((png_uint_16)((*sp >> shift) & 0x0f)
  191417. == trans_values->gray)
  191418. {
  191419. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191420. *sp |= (png_byte)(background->gray << shift);
  191421. }
  191422. if (!shift)
  191423. {
  191424. shift = 4;
  191425. sp++;
  191426. }
  191427. else
  191428. shift -= 4;
  191429. }
  191430. }
  191431. break;
  191432. }
  191433. case 8:
  191434. {
  191435. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191436. if (gamma_table != NULL)
  191437. {
  191438. sp = row;
  191439. for (i = 0; i < row_width; i++, sp++)
  191440. {
  191441. if (*sp == trans_values->gray)
  191442. {
  191443. *sp = (png_byte)background->gray;
  191444. }
  191445. else
  191446. {
  191447. *sp = gamma_table[*sp];
  191448. }
  191449. }
  191450. }
  191451. else
  191452. #endif
  191453. {
  191454. sp = row;
  191455. for (i = 0; i < row_width; i++, sp++)
  191456. {
  191457. if (*sp == trans_values->gray)
  191458. {
  191459. *sp = (png_byte)background->gray;
  191460. }
  191461. }
  191462. }
  191463. break;
  191464. }
  191465. case 16:
  191466. {
  191467. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191468. if (gamma_16 != NULL)
  191469. {
  191470. sp = row;
  191471. for (i = 0; i < row_width; i++, sp += 2)
  191472. {
  191473. png_uint_16 v;
  191474. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191475. if (v == trans_values->gray)
  191476. {
  191477. /* background is already in screen gamma */
  191478. *sp = (png_byte)((background->gray >> 8) & 0xff);
  191479. *(sp + 1) = (png_byte)(background->gray & 0xff);
  191480. }
  191481. else
  191482. {
  191483. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191484. *sp = (png_byte)((v >> 8) & 0xff);
  191485. *(sp + 1) = (png_byte)(v & 0xff);
  191486. }
  191487. }
  191488. }
  191489. else
  191490. #endif
  191491. {
  191492. sp = row;
  191493. for (i = 0; i < row_width; i++, sp += 2)
  191494. {
  191495. png_uint_16 v;
  191496. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191497. if (v == trans_values->gray)
  191498. {
  191499. *sp = (png_byte)((background->gray >> 8) & 0xff);
  191500. *(sp + 1) = (png_byte)(background->gray & 0xff);
  191501. }
  191502. }
  191503. }
  191504. break;
  191505. }
  191506. }
  191507. break;
  191508. }
  191509. case PNG_COLOR_TYPE_RGB:
  191510. {
  191511. if (row_info->bit_depth == 8)
  191512. {
  191513. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191514. if (gamma_table != NULL)
  191515. {
  191516. sp = row;
  191517. for (i = 0; i < row_width; i++, sp += 3)
  191518. {
  191519. if (*sp == trans_values->red &&
  191520. *(sp + 1) == trans_values->green &&
  191521. *(sp + 2) == trans_values->blue)
  191522. {
  191523. *sp = (png_byte)background->red;
  191524. *(sp + 1) = (png_byte)background->green;
  191525. *(sp + 2) = (png_byte)background->blue;
  191526. }
  191527. else
  191528. {
  191529. *sp = gamma_table[*sp];
  191530. *(sp + 1) = gamma_table[*(sp + 1)];
  191531. *(sp + 2) = gamma_table[*(sp + 2)];
  191532. }
  191533. }
  191534. }
  191535. else
  191536. #endif
  191537. {
  191538. sp = row;
  191539. for (i = 0; i < row_width; i++, sp += 3)
  191540. {
  191541. if (*sp == trans_values->red &&
  191542. *(sp + 1) == trans_values->green &&
  191543. *(sp + 2) == trans_values->blue)
  191544. {
  191545. *sp = (png_byte)background->red;
  191546. *(sp + 1) = (png_byte)background->green;
  191547. *(sp + 2) = (png_byte)background->blue;
  191548. }
  191549. }
  191550. }
  191551. }
  191552. else /* if (row_info->bit_depth == 16) */
  191553. {
  191554. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191555. if (gamma_16 != NULL)
  191556. {
  191557. sp = row;
  191558. for (i = 0; i < row_width; i++, sp += 6)
  191559. {
  191560. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191561. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191562. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  191563. if (r == trans_values->red && g == trans_values->green &&
  191564. b == trans_values->blue)
  191565. {
  191566. /* background is already in screen gamma */
  191567. *sp = (png_byte)((background->red >> 8) & 0xff);
  191568. *(sp + 1) = (png_byte)(background->red & 0xff);
  191569. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191570. *(sp + 3) = (png_byte)(background->green & 0xff);
  191571. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191572. *(sp + 5) = (png_byte)(background->blue & 0xff);
  191573. }
  191574. else
  191575. {
  191576. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191577. *sp = (png_byte)((v >> 8) & 0xff);
  191578. *(sp + 1) = (png_byte)(v & 0xff);
  191579. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  191580. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  191581. *(sp + 3) = (png_byte)(v & 0xff);
  191582. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  191583. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  191584. *(sp + 5) = (png_byte)(v & 0xff);
  191585. }
  191586. }
  191587. }
  191588. else
  191589. #endif
  191590. {
  191591. sp = row;
  191592. for (i = 0; i < row_width; i++, sp += 6)
  191593. {
  191594. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  191595. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191596. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  191597. if (r == trans_values->red && g == trans_values->green &&
  191598. b == trans_values->blue)
  191599. {
  191600. *sp = (png_byte)((background->red >> 8) & 0xff);
  191601. *(sp + 1) = (png_byte)(background->red & 0xff);
  191602. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191603. *(sp + 3) = (png_byte)(background->green & 0xff);
  191604. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191605. *(sp + 5) = (png_byte)(background->blue & 0xff);
  191606. }
  191607. }
  191608. }
  191609. }
  191610. break;
  191611. }
  191612. case PNG_COLOR_TYPE_GRAY_ALPHA:
  191613. {
  191614. if (row_info->bit_depth == 8)
  191615. {
  191616. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191617. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  191618. gamma_table != NULL)
  191619. {
  191620. sp = row;
  191621. dp = row;
  191622. for (i = 0; i < row_width; i++, sp += 2, dp++)
  191623. {
  191624. png_uint_16 a = *(sp + 1);
  191625. if (a == 0xff)
  191626. {
  191627. *dp = gamma_table[*sp];
  191628. }
  191629. else if (a == 0)
  191630. {
  191631. /* background is already in screen gamma */
  191632. *dp = (png_byte)background->gray;
  191633. }
  191634. else
  191635. {
  191636. png_byte v, w;
  191637. v = gamma_to_1[*sp];
  191638. png_composite(w, v, a, background_1->gray);
  191639. *dp = gamma_from_1[w];
  191640. }
  191641. }
  191642. }
  191643. else
  191644. #endif
  191645. {
  191646. sp = row;
  191647. dp = row;
  191648. for (i = 0; i < row_width; i++, sp += 2, dp++)
  191649. {
  191650. png_byte a = *(sp + 1);
  191651. if (a == 0xff)
  191652. {
  191653. *dp = *sp;
  191654. }
  191655. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191656. else if (a == 0)
  191657. {
  191658. *dp = (png_byte)background->gray;
  191659. }
  191660. else
  191661. {
  191662. png_composite(*dp, *sp, a, background_1->gray);
  191663. }
  191664. #else
  191665. *dp = (png_byte)background->gray;
  191666. #endif
  191667. }
  191668. }
  191669. }
  191670. else /* if (png_ptr->bit_depth == 16) */
  191671. {
  191672. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191673. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  191674. gamma_16_to_1 != NULL)
  191675. {
  191676. sp = row;
  191677. dp = row;
  191678. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  191679. {
  191680. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191681. if (a == (png_uint_16)0xffff)
  191682. {
  191683. png_uint_16 v;
  191684. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191685. *dp = (png_byte)((v >> 8) & 0xff);
  191686. *(dp + 1) = (png_byte)(v & 0xff);
  191687. }
  191688. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191689. else if (a == 0)
  191690. #else
  191691. else
  191692. #endif
  191693. {
  191694. /* background is already in screen gamma */
  191695. *dp = (png_byte)((background->gray >> 8) & 0xff);
  191696. *(dp + 1) = (png_byte)(background->gray & 0xff);
  191697. }
  191698. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191699. else
  191700. {
  191701. png_uint_16 g, v, w;
  191702. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  191703. png_composite_16(v, g, a, background_1->gray);
  191704. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  191705. *dp = (png_byte)((w >> 8) & 0xff);
  191706. *(dp + 1) = (png_byte)(w & 0xff);
  191707. }
  191708. #endif
  191709. }
  191710. }
  191711. else
  191712. #endif
  191713. {
  191714. sp = row;
  191715. dp = row;
  191716. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  191717. {
  191718. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191719. if (a == (png_uint_16)0xffff)
  191720. {
  191721. png_memcpy(dp, sp, 2);
  191722. }
  191723. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191724. else if (a == 0)
  191725. #else
  191726. else
  191727. #endif
  191728. {
  191729. *dp = (png_byte)((background->gray >> 8) & 0xff);
  191730. *(dp + 1) = (png_byte)(background->gray & 0xff);
  191731. }
  191732. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191733. else
  191734. {
  191735. png_uint_16 g, v;
  191736. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191737. png_composite_16(v, g, a, background_1->gray);
  191738. *dp = (png_byte)((v >> 8) & 0xff);
  191739. *(dp + 1) = (png_byte)(v & 0xff);
  191740. }
  191741. #endif
  191742. }
  191743. }
  191744. }
  191745. break;
  191746. }
  191747. case PNG_COLOR_TYPE_RGB_ALPHA:
  191748. {
  191749. if (row_info->bit_depth == 8)
  191750. {
  191751. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191752. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  191753. gamma_table != NULL)
  191754. {
  191755. sp = row;
  191756. dp = row;
  191757. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  191758. {
  191759. png_byte a = *(sp + 3);
  191760. if (a == 0xff)
  191761. {
  191762. *dp = gamma_table[*sp];
  191763. *(dp + 1) = gamma_table[*(sp + 1)];
  191764. *(dp + 2) = gamma_table[*(sp + 2)];
  191765. }
  191766. else if (a == 0)
  191767. {
  191768. /* background is already in screen gamma */
  191769. *dp = (png_byte)background->red;
  191770. *(dp + 1) = (png_byte)background->green;
  191771. *(dp + 2) = (png_byte)background->blue;
  191772. }
  191773. else
  191774. {
  191775. png_byte v, w;
  191776. v = gamma_to_1[*sp];
  191777. png_composite(w, v, a, background_1->red);
  191778. *dp = gamma_from_1[w];
  191779. v = gamma_to_1[*(sp + 1)];
  191780. png_composite(w, v, a, background_1->green);
  191781. *(dp + 1) = gamma_from_1[w];
  191782. v = gamma_to_1[*(sp + 2)];
  191783. png_composite(w, v, a, background_1->blue);
  191784. *(dp + 2) = gamma_from_1[w];
  191785. }
  191786. }
  191787. }
  191788. else
  191789. #endif
  191790. {
  191791. sp = row;
  191792. dp = row;
  191793. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  191794. {
  191795. png_byte a = *(sp + 3);
  191796. if (a == 0xff)
  191797. {
  191798. *dp = *sp;
  191799. *(dp + 1) = *(sp + 1);
  191800. *(dp + 2) = *(sp + 2);
  191801. }
  191802. else if (a == 0)
  191803. {
  191804. *dp = (png_byte)background->red;
  191805. *(dp + 1) = (png_byte)background->green;
  191806. *(dp + 2) = (png_byte)background->blue;
  191807. }
  191808. else
  191809. {
  191810. png_composite(*dp, *sp, a, background->red);
  191811. png_composite(*(dp + 1), *(sp + 1), a,
  191812. background->green);
  191813. png_composite(*(dp + 2), *(sp + 2), a,
  191814. background->blue);
  191815. }
  191816. }
  191817. }
  191818. }
  191819. else /* if (row_info->bit_depth == 16) */
  191820. {
  191821. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191822. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  191823. gamma_16_to_1 != NULL)
  191824. {
  191825. sp = row;
  191826. dp = row;
  191827. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  191828. {
  191829. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  191830. << 8) + (png_uint_16)(*(sp + 7)));
  191831. if (a == (png_uint_16)0xffff)
  191832. {
  191833. png_uint_16 v;
  191834. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191835. *dp = (png_byte)((v >> 8) & 0xff);
  191836. *(dp + 1) = (png_byte)(v & 0xff);
  191837. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  191838. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  191839. *(dp + 3) = (png_byte)(v & 0xff);
  191840. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  191841. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  191842. *(dp + 5) = (png_byte)(v & 0xff);
  191843. }
  191844. else if (a == 0)
  191845. {
  191846. /* background is already in screen gamma */
  191847. *dp = (png_byte)((background->red >> 8) & 0xff);
  191848. *(dp + 1) = (png_byte)(background->red & 0xff);
  191849. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191850. *(dp + 3) = (png_byte)(background->green & 0xff);
  191851. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191852. *(dp + 5) = (png_byte)(background->blue & 0xff);
  191853. }
  191854. else
  191855. {
  191856. png_uint_16 v, w, x;
  191857. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  191858. png_composite_16(w, v, a, background_1->red);
  191859. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  191860. *dp = (png_byte)((x >> 8) & 0xff);
  191861. *(dp + 1) = (png_byte)(x & 0xff);
  191862. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  191863. png_composite_16(w, v, a, background_1->green);
  191864. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  191865. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  191866. *(dp + 3) = (png_byte)(x & 0xff);
  191867. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  191868. png_composite_16(w, v, a, background_1->blue);
  191869. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  191870. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  191871. *(dp + 5) = (png_byte)(x & 0xff);
  191872. }
  191873. }
  191874. }
  191875. else
  191876. #endif
  191877. {
  191878. sp = row;
  191879. dp = row;
  191880. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  191881. {
  191882. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  191883. << 8) + (png_uint_16)(*(sp + 7)));
  191884. if (a == (png_uint_16)0xffff)
  191885. {
  191886. png_memcpy(dp, sp, 6);
  191887. }
  191888. else if (a == 0)
  191889. {
  191890. *dp = (png_byte)((background->red >> 8) & 0xff);
  191891. *(dp + 1) = (png_byte)(background->red & 0xff);
  191892. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191893. *(dp + 3) = (png_byte)(background->green & 0xff);
  191894. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191895. *(dp + 5) = (png_byte)(background->blue & 0xff);
  191896. }
  191897. else
  191898. {
  191899. png_uint_16 v;
  191900. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191901. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  191902. + *(sp + 3));
  191903. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  191904. + *(sp + 5));
  191905. png_composite_16(v, r, a, background->red);
  191906. *dp = (png_byte)((v >> 8) & 0xff);
  191907. *(dp + 1) = (png_byte)(v & 0xff);
  191908. png_composite_16(v, g, a, background->green);
  191909. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  191910. *(dp + 3) = (png_byte)(v & 0xff);
  191911. png_composite_16(v, b, a, background->blue);
  191912. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  191913. *(dp + 5) = (png_byte)(v & 0xff);
  191914. }
  191915. }
  191916. }
  191917. }
  191918. break;
  191919. }
  191920. }
  191921. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191922. {
  191923. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191924. row_info->channels--;
  191925. row_info->pixel_depth = (png_byte)(row_info->channels *
  191926. row_info->bit_depth);
  191927. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191928. }
  191929. }
  191930. }
  191931. #endif
  191932. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191933. /* Gamma correct the image, avoiding the alpha channel. Make sure
  191934. * you do this after you deal with the transparency issue on grayscale
  191935. * or RGB images. If your bit depth is 8, use gamma_table, if it
  191936. * is 16, use gamma_16_table and gamma_shift. Build these with
  191937. * build_gamma_table().
  191938. */
  191939. void /* PRIVATE */
  191940. png_do_gamma(png_row_infop row_info, png_bytep row,
  191941. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  191942. int gamma_shift)
  191943. {
  191944. png_bytep sp;
  191945. png_uint_32 i;
  191946. png_uint_32 row_width=row_info->width;
  191947. png_debug(1, "in png_do_gamma\n");
  191948. if (
  191949. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191950. row != NULL && row_info != NULL &&
  191951. #endif
  191952. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  191953. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  191954. {
  191955. switch (row_info->color_type)
  191956. {
  191957. case PNG_COLOR_TYPE_RGB:
  191958. {
  191959. if (row_info->bit_depth == 8)
  191960. {
  191961. sp = row;
  191962. for (i = 0; i < row_width; i++)
  191963. {
  191964. *sp = gamma_table[*sp];
  191965. sp++;
  191966. *sp = gamma_table[*sp];
  191967. sp++;
  191968. *sp = gamma_table[*sp];
  191969. sp++;
  191970. }
  191971. }
  191972. else /* if (row_info->bit_depth == 16) */
  191973. {
  191974. sp = row;
  191975. for (i = 0; i < row_width; i++)
  191976. {
  191977. png_uint_16 v;
  191978. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  191979. *sp = (png_byte)((v >> 8) & 0xff);
  191980. *(sp + 1) = (png_byte)(v & 0xff);
  191981. sp += 2;
  191982. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  191983. *sp = (png_byte)((v >> 8) & 0xff);
  191984. *(sp + 1) = (png_byte)(v & 0xff);
  191985. sp += 2;
  191986. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  191987. *sp = (png_byte)((v >> 8) & 0xff);
  191988. *(sp + 1) = (png_byte)(v & 0xff);
  191989. sp += 2;
  191990. }
  191991. }
  191992. break;
  191993. }
  191994. case PNG_COLOR_TYPE_RGB_ALPHA:
  191995. {
  191996. if (row_info->bit_depth == 8)
  191997. {
  191998. sp = row;
  191999. for (i = 0; i < row_width; i++)
  192000. {
  192001. *sp = gamma_table[*sp];
  192002. sp++;
  192003. *sp = gamma_table[*sp];
  192004. sp++;
  192005. *sp = gamma_table[*sp];
  192006. sp++;
  192007. sp++;
  192008. }
  192009. }
  192010. else /* if (row_info->bit_depth == 16) */
  192011. {
  192012. sp = row;
  192013. for (i = 0; i < row_width; i++)
  192014. {
  192015. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192016. *sp = (png_byte)((v >> 8) & 0xff);
  192017. *(sp + 1) = (png_byte)(v & 0xff);
  192018. sp += 2;
  192019. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192020. *sp = (png_byte)((v >> 8) & 0xff);
  192021. *(sp + 1) = (png_byte)(v & 0xff);
  192022. sp += 2;
  192023. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192024. *sp = (png_byte)((v >> 8) & 0xff);
  192025. *(sp + 1) = (png_byte)(v & 0xff);
  192026. sp += 4;
  192027. }
  192028. }
  192029. break;
  192030. }
  192031. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192032. {
  192033. if (row_info->bit_depth == 8)
  192034. {
  192035. sp = row;
  192036. for (i = 0; i < row_width; i++)
  192037. {
  192038. *sp = gamma_table[*sp];
  192039. sp += 2;
  192040. }
  192041. }
  192042. else /* if (row_info->bit_depth == 16) */
  192043. {
  192044. sp = row;
  192045. for (i = 0; i < row_width; i++)
  192046. {
  192047. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192048. *sp = (png_byte)((v >> 8) & 0xff);
  192049. *(sp + 1) = (png_byte)(v & 0xff);
  192050. sp += 4;
  192051. }
  192052. }
  192053. break;
  192054. }
  192055. case PNG_COLOR_TYPE_GRAY:
  192056. {
  192057. if (row_info->bit_depth == 2)
  192058. {
  192059. sp = row;
  192060. for (i = 0; i < row_width; i += 4)
  192061. {
  192062. int a = *sp & 0xc0;
  192063. int b = *sp & 0x30;
  192064. int c = *sp & 0x0c;
  192065. int d = *sp & 0x03;
  192066. *sp = (png_byte)(
  192067. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192068. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192069. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192070. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192071. sp++;
  192072. }
  192073. }
  192074. if (row_info->bit_depth == 4)
  192075. {
  192076. sp = row;
  192077. for (i = 0; i < row_width; i += 2)
  192078. {
  192079. int msb = *sp & 0xf0;
  192080. int lsb = *sp & 0x0f;
  192081. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192082. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192083. sp++;
  192084. }
  192085. }
  192086. else if (row_info->bit_depth == 8)
  192087. {
  192088. sp = row;
  192089. for (i = 0; i < row_width; i++)
  192090. {
  192091. *sp = gamma_table[*sp];
  192092. sp++;
  192093. }
  192094. }
  192095. else if (row_info->bit_depth == 16)
  192096. {
  192097. sp = row;
  192098. for (i = 0; i < row_width; i++)
  192099. {
  192100. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192101. *sp = (png_byte)((v >> 8) & 0xff);
  192102. *(sp + 1) = (png_byte)(v & 0xff);
  192103. sp += 2;
  192104. }
  192105. }
  192106. break;
  192107. }
  192108. }
  192109. }
  192110. }
  192111. #endif
  192112. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192113. /* Expands a palette row to an RGB or RGBA row depending
  192114. * upon whether you supply trans and num_trans.
  192115. */
  192116. void /* PRIVATE */
  192117. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192118. png_colorp palette, png_bytep trans, int num_trans)
  192119. {
  192120. int shift, value;
  192121. png_bytep sp, dp;
  192122. png_uint_32 i;
  192123. png_uint_32 row_width=row_info->width;
  192124. png_debug(1, "in png_do_expand_palette\n");
  192125. if (
  192126. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192127. row != NULL && row_info != NULL &&
  192128. #endif
  192129. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  192130. {
  192131. if (row_info->bit_depth < 8)
  192132. {
  192133. switch (row_info->bit_depth)
  192134. {
  192135. case 1:
  192136. {
  192137. sp = row + (png_size_t)((row_width - 1) >> 3);
  192138. dp = row + (png_size_t)row_width - 1;
  192139. shift = 7 - (int)((row_width + 7) & 0x07);
  192140. for (i = 0; i < row_width; i++)
  192141. {
  192142. if ((*sp >> shift) & 0x01)
  192143. *dp = 1;
  192144. else
  192145. *dp = 0;
  192146. if (shift == 7)
  192147. {
  192148. shift = 0;
  192149. sp--;
  192150. }
  192151. else
  192152. shift++;
  192153. dp--;
  192154. }
  192155. break;
  192156. }
  192157. case 2:
  192158. {
  192159. sp = row + (png_size_t)((row_width - 1) >> 2);
  192160. dp = row + (png_size_t)row_width - 1;
  192161. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192162. for (i = 0; i < row_width; i++)
  192163. {
  192164. value = (*sp >> shift) & 0x03;
  192165. *dp = (png_byte)value;
  192166. if (shift == 6)
  192167. {
  192168. shift = 0;
  192169. sp--;
  192170. }
  192171. else
  192172. shift += 2;
  192173. dp--;
  192174. }
  192175. break;
  192176. }
  192177. case 4:
  192178. {
  192179. sp = row + (png_size_t)((row_width - 1) >> 1);
  192180. dp = row + (png_size_t)row_width - 1;
  192181. shift = (int)((row_width & 0x01) << 2);
  192182. for (i = 0; i < row_width; i++)
  192183. {
  192184. value = (*sp >> shift) & 0x0f;
  192185. *dp = (png_byte)value;
  192186. if (shift == 4)
  192187. {
  192188. shift = 0;
  192189. sp--;
  192190. }
  192191. else
  192192. shift += 4;
  192193. dp--;
  192194. }
  192195. break;
  192196. }
  192197. }
  192198. row_info->bit_depth = 8;
  192199. row_info->pixel_depth = 8;
  192200. row_info->rowbytes = row_width;
  192201. }
  192202. switch (row_info->bit_depth)
  192203. {
  192204. case 8:
  192205. {
  192206. if (trans != NULL)
  192207. {
  192208. sp = row + (png_size_t)row_width - 1;
  192209. dp = row + (png_size_t)(row_width << 2) - 1;
  192210. for (i = 0; i < row_width; i++)
  192211. {
  192212. if ((int)(*sp) >= num_trans)
  192213. *dp-- = 0xff;
  192214. else
  192215. *dp-- = trans[*sp];
  192216. *dp-- = palette[*sp].blue;
  192217. *dp-- = palette[*sp].green;
  192218. *dp-- = palette[*sp].red;
  192219. sp--;
  192220. }
  192221. row_info->bit_depth = 8;
  192222. row_info->pixel_depth = 32;
  192223. row_info->rowbytes = row_width * 4;
  192224. row_info->color_type = 6;
  192225. row_info->channels = 4;
  192226. }
  192227. else
  192228. {
  192229. sp = row + (png_size_t)row_width - 1;
  192230. dp = row + (png_size_t)(row_width * 3) - 1;
  192231. for (i = 0; i < row_width; i++)
  192232. {
  192233. *dp-- = palette[*sp].blue;
  192234. *dp-- = palette[*sp].green;
  192235. *dp-- = palette[*sp].red;
  192236. sp--;
  192237. }
  192238. row_info->bit_depth = 8;
  192239. row_info->pixel_depth = 24;
  192240. row_info->rowbytes = row_width * 3;
  192241. row_info->color_type = 2;
  192242. row_info->channels = 3;
  192243. }
  192244. break;
  192245. }
  192246. }
  192247. }
  192248. }
  192249. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  192250. * expanded transparency value is supplied, an alpha channel is built.
  192251. */
  192252. void /* PRIVATE */
  192253. png_do_expand(png_row_infop row_info, png_bytep row,
  192254. png_color_16p trans_value)
  192255. {
  192256. int shift, value;
  192257. png_bytep sp, dp;
  192258. png_uint_32 i;
  192259. png_uint_32 row_width=row_info->width;
  192260. png_debug(1, "in png_do_expand\n");
  192261. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192262. if (row != NULL && row_info != NULL)
  192263. #endif
  192264. {
  192265. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192266. {
  192267. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  192268. if (row_info->bit_depth < 8)
  192269. {
  192270. switch (row_info->bit_depth)
  192271. {
  192272. case 1:
  192273. {
  192274. gray = (png_uint_16)((gray&0x01)*0xff);
  192275. sp = row + (png_size_t)((row_width - 1) >> 3);
  192276. dp = row + (png_size_t)row_width - 1;
  192277. shift = 7 - (int)((row_width + 7) & 0x07);
  192278. for (i = 0; i < row_width; i++)
  192279. {
  192280. if ((*sp >> shift) & 0x01)
  192281. *dp = 0xff;
  192282. else
  192283. *dp = 0;
  192284. if (shift == 7)
  192285. {
  192286. shift = 0;
  192287. sp--;
  192288. }
  192289. else
  192290. shift++;
  192291. dp--;
  192292. }
  192293. break;
  192294. }
  192295. case 2:
  192296. {
  192297. gray = (png_uint_16)((gray&0x03)*0x55);
  192298. sp = row + (png_size_t)((row_width - 1) >> 2);
  192299. dp = row + (png_size_t)row_width - 1;
  192300. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192301. for (i = 0; i < row_width; i++)
  192302. {
  192303. value = (*sp >> shift) & 0x03;
  192304. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  192305. (value << 6));
  192306. if (shift == 6)
  192307. {
  192308. shift = 0;
  192309. sp--;
  192310. }
  192311. else
  192312. shift += 2;
  192313. dp--;
  192314. }
  192315. break;
  192316. }
  192317. case 4:
  192318. {
  192319. gray = (png_uint_16)((gray&0x0f)*0x11);
  192320. sp = row + (png_size_t)((row_width - 1) >> 1);
  192321. dp = row + (png_size_t)row_width - 1;
  192322. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  192323. for (i = 0; i < row_width; i++)
  192324. {
  192325. value = (*sp >> shift) & 0x0f;
  192326. *dp = (png_byte)(value | (value << 4));
  192327. if (shift == 4)
  192328. {
  192329. shift = 0;
  192330. sp--;
  192331. }
  192332. else
  192333. shift = 4;
  192334. dp--;
  192335. }
  192336. break;
  192337. }
  192338. }
  192339. row_info->bit_depth = 8;
  192340. row_info->pixel_depth = 8;
  192341. row_info->rowbytes = row_width;
  192342. }
  192343. if (trans_value != NULL)
  192344. {
  192345. if (row_info->bit_depth == 8)
  192346. {
  192347. gray = gray & 0xff;
  192348. sp = row + (png_size_t)row_width - 1;
  192349. dp = row + (png_size_t)(row_width << 1) - 1;
  192350. for (i = 0; i < row_width; i++)
  192351. {
  192352. if (*sp == gray)
  192353. *dp-- = 0;
  192354. else
  192355. *dp-- = 0xff;
  192356. *dp-- = *sp--;
  192357. }
  192358. }
  192359. else if (row_info->bit_depth == 16)
  192360. {
  192361. png_byte gray_high = (gray >> 8) & 0xff;
  192362. png_byte gray_low = gray & 0xff;
  192363. sp = row + row_info->rowbytes - 1;
  192364. dp = row + (row_info->rowbytes << 1) - 1;
  192365. for (i = 0; i < row_width; i++)
  192366. {
  192367. if (*(sp-1) == gray_high && *(sp) == gray_low)
  192368. {
  192369. *dp-- = 0;
  192370. *dp-- = 0;
  192371. }
  192372. else
  192373. {
  192374. *dp-- = 0xff;
  192375. *dp-- = 0xff;
  192376. }
  192377. *dp-- = *sp--;
  192378. *dp-- = *sp--;
  192379. }
  192380. }
  192381. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  192382. row_info->channels = 2;
  192383. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  192384. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  192385. row_width);
  192386. }
  192387. }
  192388. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  192389. {
  192390. if (row_info->bit_depth == 8)
  192391. {
  192392. png_byte red = trans_value->red & 0xff;
  192393. png_byte green = trans_value->green & 0xff;
  192394. png_byte blue = trans_value->blue & 0xff;
  192395. sp = row + (png_size_t)row_info->rowbytes - 1;
  192396. dp = row + (png_size_t)(row_width << 2) - 1;
  192397. for (i = 0; i < row_width; i++)
  192398. {
  192399. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  192400. *dp-- = 0;
  192401. else
  192402. *dp-- = 0xff;
  192403. *dp-- = *sp--;
  192404. *dp-- = *sp--;
  192405. *dp-- = *sp--;
  192406. }
  192407. }
  192408. else if (row_info->bit_depth == 16)
  192409. {
  192410. png_byte red_high = (trans_value->red >> 8) & 0xff;
  192411. png_byte green_high = (trans_value->green >> 8) & 0xff;
  192412. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  192413. png_byte red_low = trans_value->red & 0xff;
  192414. png_byte green_low = trans_value->green & 0xff;
  192415. png_byte blue_low = trans_value->blue & 0xff;
  192416. sp = row + row_info->rowbytes - 1;
  192417. dp = row + (png_size_t)(row_width << 3) - 1;
  192418. for (i = 0; i < row_width; i++)
  192419. {
  192420. if (*(sp - 5) == red_high &&
  192421. *(sp - 4) == red_low &&
  192422. *(sp - 3) == green_high &&
  192423. *(sp - 2) == green_low &&
  192424. *(sp - 1) == blue_high &&
  192425. *(sp ) == blue_low)
  192426. {
  192427. *dp-- = 0;
  192428. *dp-- = 0;
  192429. }
  192430. else
  192431. {
  192432. *dp-- = 0xff;
  192433. *dp-- = 0xff;
  192434. }
  192435. *dp-- = *sp--;
  192436. *dp-- = *sp--;
  192437. *dp-- = *sp--;
  192438. *dp-- = *sp--;
  192439. *dp-- = *sp--;
  192440. *dp-- = *sp--;
  192441. }
  192442. }
  192443. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  192444. row_info->channels = 4;
  192445. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  192446. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192447. }
  192448. }
  192449. }
  192450. #endif
  192451. #if defined(PNG_READ_DITHER_SUPPORTED)
  192452. void /* PRIVATE */
  192453. png_do_dither(png_row_infop row_info, png_bytep row,
  192454. png_bytep palette_lookup, png_bytep dither_lookup)
  192455. {
  192456. png_bytep sp, dp;
  192457. png_uint_32 i;
  192458. png_uint_32 row_width=row_info->width;
  192459. png_debug(1, "in png_do_dither\n");
  192460. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192461. if (row != NULL && row_info != NULL)
  192462. #endif
  192463. {
  192464. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  192465. palette_lookup && row_info->bit_depth == 8)
  192466. {
  192467. int r, g, b, p;
  192468. sp = row;
  192469. dp = row;
  192470. for (i = 0; i < row_width; i++)
  192471. {
  192472. r = *sp++;
  192473. g = *sp++;
  192474. b = *sp++;
  192475. /* this looks real messy, but the compiler will reduce
  192476. it down to a reasonable formula. For example, with
  192477. 5 bits per color, we get:
  192478. p = (((r >> 3) & 0x1f) << 10) |
  192479. (((g >> 3) & 0x1f) << 5) |
  192480. ((b >> 3) & 0x1f);
  192481. */
  192482. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  192483. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  192484. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  192485. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  192486. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  192487. (PNG_DITHER_BLUE_BITS)) |
  192488. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  192489. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  192490. *dp++ = palette_lookup[p];
  192491. }
  192492. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  192493. row_info->channels = 1;
  192494. row_info->pixel_depth = row_info->bit_depth;
  192495. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192496. }
  192497. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  192498. palette_lookup != NULL && row_info->bit_depth == 8)
  192499. {
  192500. int r, g, b, p;
  192501. sp = row;
  192502. dp = row;
  192503. for (i = 0; i < row_width; i++)
  192504. {
  192505. r = *sp++;
  192506. g = *sp++;
  192507. b = *sp++;
  192508. sp++;
  192509. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  192510. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  192511. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  192512. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  192513. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  192514. (PNG_DITHER_BLUE_BITS)) |
  192515. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  192516. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  192517. *dp++ = palette_lookup[p];
  192518. }
  192519. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  192520. row_info->channels = 1;
  192521. row_info->pixel_depth = row_info->bit_depth;
  192522. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192523. }
  192524. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  192525. dither_lookup && row_info->bit_depth == 8)
  192526. {
  192527. sp = row;
  192528. for (i = 0; i < row_width; i++, sp++)
  192529. {
  192530. *sp = dither_lookup[*sp];
  192531. }
  192532. }
  192533. }
  192534. }
  192535. #endif
  192536. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192537. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192538. static PNG_CONST int png_gamma_shift[] =
  192539. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  192540. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  192541. * tables, we don't make a full table if we are reducing to 8-bit in
  192542. * the future. Note also how the gamma_16 tables are segmented so that
  192543. * we don't need to allocate > 64K chunks for a full 16-bit table.
  192544. */
  192545. void /* PRIVATE */
  192546. png_build_gamma_table(png_structp png_ptr)
  192547. {
  192548. png_debug(1, "in png_build_gamma_table\n");
  192549. if (png_ptr->bit_depth <= 8)
  192550. {
  192551. int i;
  192552. double g;
  192553. if (png_ptr->screen_gamma > .000001)
  192554. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  192555. else
  192556. g = 1.0;
  192557. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  192558. (png_uint_32)256);
  192559. for (i = 0; i < 256; i++)
  192560. {
  192561. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  192562. g) * 255.0 + .5);
  192563. }
  192564. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  192565. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192566. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  192567. {
  192568. g = 1.0 / (png_ptr->gamma);
  192569. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  192570. (png_uint_32)256);
  192571. for (i = 0; i < 256; i++)
  192572. {
  192573. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  192574. g) * 255.0 + .5);
  192575. }
  192576. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  192577. (png_uint_32)256);
  192578. if(png_ptr->screen_gamma > 0.000001)
  192579. g = 1.0 / png_ptr->screen_gamma;
  192580. else
  192581. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  192582. for (i = 0; i < 256; i++)
  192583. {
  192584. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  192585. g) * 255.0 + .5);
  192586. }
  192587. }
  192588. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  192589. }
  192590. else
  192591. {
  192592. double g;
  192593. int i, j, shift, num;
  192594. int sig_bit;
  192595. png_uint_32 ig;
  192596. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192597. {
  192598. sig_bit = (int)png_ptr->sig_bit.red;
  192599. if ((int)png_ptr->sig_bit.green > sig_bit)
  192600. sig_bit = png_ptr->sig_bit.green;
  192601. if ((int)png_ptr->sig_bit.blue > sig_bit)
  192602. sig_bit = png_ptr->sig_bit.blue;
  192603. }
  192604. else
  192605. {
  192606. sig_bit = (int)png_ptr->sig_bit.gray;
  192607. }
  192608. if (sig_bit > 0)
  192609. shift = 16 - sig_bit;
  192610. else
  192611. shift = 0;
  192612. if (png_ptr->transformations & PNG_16_TO_8)
  192613. {
  192614. if (shift < (16 - PNG_MAX_GAMMA_8))
  192615. shift = (16 - PNG_MAX_GAMMA_8);
  192616. }
  192617. if (shift > 8)
  192618. shift = 8;
  192619. if (shift < 0)
  192620. shift = 0;
  192621. png_ptr->gamma_shift = (png_byte)shift;
  192622. num = (1 << (8 - shift));
  192623. if (png_ptr->screen_gamma > .000001)
  192624. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  192625. else
  192626. g = 1.0;
  192627. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  192628. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  192629. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  192630. {
  192631. double fin, fout;
  192632. png_uint_32 last, max;
  192633. for (i = 0; i < num; i++)
  192634. {
  192635. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  192636. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192637. }
  192638. g = 1.0 / g;
  192639. last = 0;
  192640. for (i = 0; i < 256; i++)
  192641. {
  192642. fout = ((double)i + 0.5) / 256.0;
  192643. fin = pow(fout, g);
  192644. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  192645. while (last <= max)
  192646. {
  192647. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  192648. [(int)(last >> (8 - shift))] = (png_uint_16)(
  192649. (png_uint_16)i | ((png_uint_16)i << 8));
  192650. last++;
  192651. }
  192652. }
  192653. while (last < ((png_uint_32)num << 8))
  192654. {
  192655. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  192656. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  192657. last++;
  192658. }
  192659. }
  192660. else
  192661. {
  192662. for (i = 0; i < num; i++)
  192663. {
  192664. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  192665. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192666. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  192667. for (j = 0; j < 256; j++)
  192668. {
  192669. png_ptr->gamma_16_table[i][j] =
  192670. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  192671. 65535.0, g) * 65535.0 + .5);
  192672. }
  192673. }
  192674. }
  192675. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  192676. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192677. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  192678. {
  192679. g = 1.0 / (png_ptr->gamma);
  192680. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  192681. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  192682. for (i = 0; i < num; i++)
  192683. {
  192684. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  192685. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192686. ig = (((png_uint_32)i *
  192687. (png_uint_32)png_gamma_shift[shift]) >> 4);
  192688. for (j = 0; j < 256; j++)
  192689. {
  192690. png_ptr->gamma_16_to_1[i][j] =
  192691. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  192692. 65535.0, g) * 65535.0 + .5);
  192693. }
  192694. }
  192695. if(png_ptr->screen_gamma > 0.000001)
  192696. g = 1.0 / png_ptr->screen_gamma;
  192697. else
  192698. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  192699. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  192700. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  192701. for (i = 0; i < num; i++)
  192702. {
  192703. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  192704. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192705. ig = (((png_uint_32)i *
  192706. (png_uint_32)png_gamma_shift[shift]) >> 4);
  192707. for (j = 0; j < 256; j++)
  192708. {
  192709. png_ptr->gamma_16_from_1[i][j] =
  192710. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  192711. 65535.0, g) * 65535.0 + .5);
  192712. }
  192713. }
  192714. }
  192715. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  192716. }
  192717. }
  192718. #endif
  192719. /* To do: install integer version of png_build_gamma_table here */
  192720. #endif
  192721. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192722. /* undoes intrapixel differencing */
  192723. void /* PRIVATE */
  192724. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  192725. {
  192726. png_debug(1, "in png_do_read_intrapixel\n");
  192727. if (
  192728. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192729. row != NULL && row_info != NULL &&
  192730. #endif
  192731. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192732. {
  192733. int bytes_per_pixel;
  192734. png_uint_32 row_width = row_info->width;
  192735. if (row_info->bit_depth == 8)
  192736. {
  192737. png_bytep rp;
  192738. png_uint_32 i;
  192739. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192740. bytes_per_pixel = 3;
  192741. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192742. bytes_per_pixel = 4;
  192743. else
  192744. return;
  192745. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  192746. {
  192747. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  192748. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  192749. }
  192750. }
  192751. else if (row_info->bit_depth == 16)
  192752. {
  192753. png_bytep rp;
  192754. png_uint_32 i;
  192755. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192756. bytes_per_pixel = 6;
  192757. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192758. bytes_per_pixel = 8;
  192759. else
  192760. return;
  192761. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  192762. {
  192763. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  192764. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  192765. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  192766. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  192767. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  192768. *(rp ) = (png_byte)((red >> 8) & 0xff);
  192769. *(rp+1) = (png_byte)(red & 0xff);
  192770. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  192771. *(rp+5) = (png_byte)(blue & 0xff);
  192772. }
  192773. }
  192774. }
  192775. }
  192776. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  192777. #endif /* PNG_READ_SUPPORTED */
  192778. /*** End of inlined file: pngrtran.c ***/
  192779. /*** Start of inlined file: pngrutil.c ***/
  192780. /* pngrutil.c - utilities to read a PNG file
  192781. *
  192782. * Last changed in libpng 1.2.21 [October 4, 2007]
  192783. * For conditions of distribution and use, see copyright notice in png.h
  192784. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192785. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192786. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192787. *
  192788. * This file contains routines that are only called from within
  192789. * libpng itself during the course of reading an image.
  192790. */
  192791. #define PNG_INTERNAL
  192792. #if defined(PNG_READ_SUPPORTED)
  192793. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  192794. # define WIN32_WCE_OLD
  192795. #endif
  192796. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192797. # if defined(WIN32_WCE_OLD)
  192798. /* strtod() function is not supported on WindowsCE */
  192799. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  192800. {
  192801. double result = 0;
  192802. int len;
  192803. wchar_t *str, *end;
  192804. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  192805. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  192806. if ( NULL != str )
  192807. {
  192808. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  192809. result = wcstod(str, &end);
  192810. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  192811. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  192812. png_free(png_ptr, str);
  192813. }
  192814. return result;
  192815. }
  192816. # else
  192817. # define png_strtod(p,a,b) strtod(a,b)
  192818. # endif
  192819. #endif
  192820. png_uint_32 PNGAPI
  192821. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  192822. {
  192823. png_uint_32 i = png_get_uint_32(buf);
  192824. if (i > PNG_UINT_31_MAX)
  192825. png_error(png_ptr, "PNG unsigned integer out of range.");
  192826. return (i);
  192827. }
  192828. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  192829. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  192830. png_uint_32 PNGAPI
  192831. png_get_uint_32(png_bytep buf)
  192832. {
  192833. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  192834. ((png_uint_32)(*(buf + 1)) << 16) +
  192835. ((png_uint_32)(*(buf + 2)) << 8) +
  192836. (png_uint_32)(*(buf + 3));
  192837. return (i);
  192838. }
  192839. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  192840. * data is stored in the PNG file in two's complement format, and it is
  192841. * assumed that the machine format for signed integers is the same. */
  192842. png_int_32 PNGAPI
  192843. png_get_int_32(png_bytep buf)
  192844. {
  192845. png_int_32 i = ((png_int_32)(*buf) << 24) +
  192846. ((png_int_32)(*(buf + 1)) << 16) +
  192847. ((png_int_32)(*(buf + 2)) << 8) +
  192848. (png_int_32)(*(buf + 3));
  192849. return (i);
  192850. }
  192851. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  192852. png_uint_16 PNGAPI
  192853. png_get_uint_16(png_bytep buf)
  192854. {
  192855. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  192856. (png_uint_16)(*(buf + 1)));
  192857. return (i);
  192858. }
  192859. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  192860. /* Read data, and (optionally) run it through the CRC. */
  192861. void /* PRIVATE */
  192862. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  192863. {
  192864. if(png_ptr == NULL) return;
  192865. png_read_data(png_ptr, buf, length);
  192866. png_calculate_crc(png_ptr, buf, length);
  192867. }
  192868. /* Optionally skip data and then check the CRC. Depending on whether we
  192869. are reading a ancillary or critical chunk, and how the program has set
  192870. things up, we may calculate the CRC on the data and print a message.
  192871. Returns '1' if there was a CRC error, '0' otherwise. */
  192872. int /* PRIVATE */
  192873. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  192874. {
  192875. png_size_t i;
  192876. png_size_t istop = png_ptr->zbuf_size;
  192877. for (i = (png_size_t)skip; i > istop; i -= istop)
  192878. {
  192879. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  192880. }
  192881. if (i)
  192882. {
  192883. png_crc_read(png_ptr, png_ptr->zbuf, i);
  192884. }
  192885. if (png_crc_error(png_ptr))
  192886. {
  192887. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  192888. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  192889. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  192890. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  192891. {
  192892. png_chunk_warning(png_ptr, "CRC error");
  192893. }
  192894. else
  192895. {
  192896. png_chunk_error(png_ptr, "CRC error");
  192897. }
  192898. return (1);
  192899. }
  192900. return (0);
  192901. }
  192902. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  192903. the data it has read thus far. */
  192904. int /* PRIVATE */
  192905. png_crc_error(png_structp png_ptr)
  192906. {
  192907. png_byte crc_bytes[4];
  192908. png_uint_32 crc;
  192909. int need_crc = 1;
  192910. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  192911. {
  192912. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  192913. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  192914. need_crc = 0;
  192915. }
  192916. else /* critical */
  192917. {
  192918. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  192919. need_crc = 0;
  192920. }
  192921. png_read_data(png_ptr, crc_bytes, 4);
  192922. if (need_crc)
  192923. {
  192924. crc = png_get_uint_32(crc_bytes);
  192925. return ((int)(crc != png_ptr->crc));
  192926. }
  192927. else
  192928. return (0);
  192929. }
  192930. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  192931. defined(PNG_READ_iCCP_SUPPORTED)
  192932. /*
  192933. * Decompress trailing data in a chunk. The assumption is that chunkdata
  192934. * points at an allocated area holding the contents of a chunk with a
  192935. * trailing compressed part. What we get back is an allocated area
  192936. * holding the original prefix part and an uncompressed version of the
  192937. * trailing part (the malloc area passed in is freed).
  192938. */
  192939. png_charp /* PRIVATE */
  192940. png_decompress_chunk(png_structp png_ptr, int comp_type,
  192941. png_charp chunkdata, png_size_t chunklength,
  192942. png_size_t prefix_size, png_size_t *newlength)
  192943. {
  192944. static PNG_CONST char msg[] = "Error decoding compressed text";
  192945. png_charp text;
  192946. png_size_t text_size;
  192947. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  192948. {
  192949. int ret = Z_OK;
  192950. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  192951. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  192952. png_ptr->zstream.next_out = png_ptr->zbuf;
  192953. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  192954. text_size = 0;
  192955. text = NULL;
  192956. while (png_ptr->zstream.avail_in)
  192957. {
  192958. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  192959. if (ret != Z_OK && ret != Z_STREAM_END)
  192960. {
  192961. if (png_ptr->zstream.msg != NULL)
  192962. png_warning(png_ptr, png_ptr->zstream.msg);
  192963. else
  192964. png_warning(png_ptr, msg);
  192965. inflateReset(&png_ptr->zstream);
  192966. png_ptr->zstream.avail_in = 0;
  192967. if (text == NULL)
  192968. {
  192969. text_size = prefix_size + png_sizeof(msg) + 1;
  192970. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  192971. if (text == NULL)
  192972. {
  192973. png_free(png_ptr,chunkdata);
  192974. png_error(png_ptr,"Not enough memory to decompress chunk");
  192975. }
  192976. png_memcpy(text, chunkdata, prefix_size);
  192977. }
  192978. text[text_size - 1] = 0x00;
  192979. /* Copy what we can of the error message into the text chunk */
  192980. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  192981. text_size = png_sizeof(msg) > text_size ? text_size :
  192982. png_sizeof(msg);
  192983. png_memcpy(text + prefix_size, msg, text_size + 1);
  192984. break;
  192985. }
  192986. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  192987. {
  192988. if (text == NULL)
  192989. {
  192990. text_size = prefix_size +
  192991. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  192992. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  192993. if (text == NULL)
  192994. {
  192995. png_free(png_ptr,chunkdata);
  192996. png_error(png_ptr,"Not enough memory to decompress chunk.");
  192997. }
  192998. png_memcpy(text + prefix_size, png_ptr->zbuf,
  192999. text_size - prefix_size);
  193000. png_memcpy(text, chunkdata, prefix_size);
  193001. *(text + text_size) = 0x00;
  193002. }
  193003. else
  193004. {
  193005. png_charp tmp;
  193006. tmp = text;
  193007. text = (png_charp)png_malloc_warn(png_ptr,
  193008. (png_uint_32)(text_size +
  193009. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193010. if (text == NULL)
  193011. {
  193012. png_free(png_ptr, tmp);
  193013. png_free(png_ptr, chunkdata);
  193014. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193015. }
  193016. png_memcpy(text, tmp, text_size);
  193017. png_free(png_ptr, tmp);
  193018. png_memcpy(text + text_size, png_ptr->zbuf,
  193019. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193020. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193021. *(text + text_size) = 0x00;
  193022. }
  193023. if (ret == Z_STREAM_END)
  193024. break;
  193025. else
  193026. {
  193027. png_ptr->zstream.next_out = png_ptr->zbuf;
  193028. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193029. }
  193030. }
  193031. }
  193032. if (ret != Z_STREAM_END)
  193033. {
  193034. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193035. char umsg[52];
  193036. if (ret == Z_BUF_ERROR)
  193037. png_snprintf(umsg, 52,
  193038. "Buffer error in compressed datastream in %s chunk",
  193039. png_ptr->chunk_name);
  193040. else if (ret == Z_DATA_ERROR)
  193041. png_snprintf(umsg, 52,
  193042. "Data error in compressed datastream in %s chunk",
  193043. png_ptr->chunk_name);
  193044. else
  193045. png_snprintf(umsg, 52,
  193046. "Incomplete compressed datastream in %s chunk",
  193047. png_ptr->chunk_name);
  193048. png_warning(png_ptr, umsg);
  193049. #else
  193050. png_warning(png_ptr,
  193051. "Incomplete compressed datastream in chunk other than IDAT");
  193052. #endif
  193053. text_size=prefix_size;
  193054. if (text == NULL)
  193055. {
  193056. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193057. if (text == NULL)
  193058. {
  193059. png_free(png_ptr, chunkdata);
  193060. png_error(png_ptr,"Not enough memory for text.");
  193061. }
  193062. png_memcpy(text, chunkdata, prefix_size);
  193063. }
  193064. *(text + text_size) = 0x00;
  193065. }
  193066. inflateReset(&png_ptr->zstream);
  193067. png_ptr->zstream.avail_in = 0;
  193068. png_free(png_ptr, chunkdata);
  193069. chunkdata = text;
  193070. *newlength=text_size;
  193071. }
  193072. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193073. {
  193074. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193075. char umsg[50];
  193076. png_snprintf(umsg, 50,
  193077. "Unknown zTXt compression type %d", comp_type);
  193078. png_warning(png_ptr, umsg);
  193079. #else
  193080. png_warning(png_ptr, "Unknown zTXt compression type");
  193081. #endif
  193082. *(chunkdata + prefix_size) = 0x00;
  193083. *newlength=prefix_size;
  193084. }
  193085. return chunkdata;
  193086. }
  193087. #endif
  193088. /* read and check the IDHR chunk */
  193089. void /* PRIVATE */
  193090. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193091. {
  193092. png_byte buf[13];
  193093. png_uint_32 width, height;
  193094. int bit_depth, color_type, compression_type, filter_type;
  193095. int interlace_type;
  193096. png_debug(1, "in png_handle_IHDR\n");
  193097. if (png_ptr->mode & PNG_HAVE_IHDR)
  193098. png_error(png_ptr, "Out of place IHDR");
  193099. /* check the length */
  193100. if (length != 13)
  193101. png_error(png_ptr, "Invalid IHDR chunk");
  193102. png_ptr->mode |= PNG_HAVE_IHDR;
  193103. png_crc_read(png_ptr, buf, 13);
  193104. png_crc_finish(png_ptr, 0);
  193105. width = png_get_uint_31(png_ptr, buf);
  193106. height = png_get_uint_31(png_ptr, buf + 4);
  193107. bit_depth = buf[8];
  193108. color_type = buf[9];
  193109. compression_type = buf[10];
  193110. filter_type = buf[11];
  193111. interlace_type = buf[12];
  193112. /* set internal variables */
  193113. png_ptr->width = width;
  193114. png_ptr->height = height;
  193115. png_ptr->bit_depth = (png_byte)bit_depth;
  193116. png_ptr->interlaced = (png_byte)interlace_type;
  193117. png_ptr->color_type = (png_byte)color_type;
  193118. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193119. png_ptr->filter_type = (png_byte)filter_type;
  193120. #endif
  193121. png_ptr->compression_type = (png_byte)compression_type;
  193122. /* find number of channels */
  193123. switch (png_ptr->color_type)
  193124. {
  193125. case PNG_COLOR_TYPE_GRAY:
  193126. case PNG_COLOR_TYPE_PALETTE:
  193127. png_ptr->channels = 1;
  193128. break;
  193129. case PNG_COLOR_TYPE_RGB:
  193130. png_ptr->channels = 3;
  193131. break;
  193132. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193133. png_ptr->channels = 2;
  193134. break;
  193135. case PNG_COLOR_TYPE_RGB_ALPHA:
  193136. png_ptr->channels = 4;
  193137. break;
  193138. }
  193139. /* set up other useful info */
  193140. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  193141. png_ptr->channels);
  193142. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  193143. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  193144. png_debug1(3,"channels = %d\n", png_ptr->channels);
  193145. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  193146. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  193147. color_type, interlace_type, compression_type, filter_type);
  193148. }
  193149. /* read and check the palette */
  193150. void /* PRIVATE */
  193151. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193152. {
  193153. png_color palette[PNG_MAX_PALETTE_LENGTH];
  193154. int num, i;
  193155. #ifndef PNG_NO_POINTER_INDEXING
  193156. png_colorp pal_ptr;
  193157. #endif
  193158. png_debug(1, "in png_handle_PLTE\n");
  193159. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193160. png_error(png_ptr, "Missing IHDR before PLTE");
  193161. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193162. {
  193163. png_warning(png_ptr, "Invalid PLTE after IDAT");
  193164. png_crc_finish(png_ptr, length);
  193165. return;
  193166. }
  193167. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193168. png_error(png_ptr, "Duplicate PLTE chunk");
  193169. png_ptr->mode |= PNG_HAVE_PLTE;
  193170. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  193171. {
  193172. png_warning(png_ptr,
  193173. "Ignoring PLTE chunk in grayscale PNG");
  193174. png_crc_finish(png_ptr, length);
  193175. return;
  193176. }
  193177. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193178. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193179. {
  193180. png_crc_finish(png_ptr, length);
  193181. return;
  193182. }
  193183. #endif
  193184. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  193185. {
  193186. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193187. {
  193188. png_warning(png_ptr, "Invalid palette chunk");
  193189. png_crc_finish(png_ptr, length);
  193190. return;
  193191. }
  193192. else
  193193. {
  193194. png_error(png_ptr, "Invalid palette chunk");
  193195. }
  193196. }
  193197. num = (int)length / 3;
  193198. #ifndef PNG_NO_POINTER_INDEXING
  193199. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  193200. {
  193201. png_byte buf[3];
  193202. png_crc_read(png_ptr, buf, 3);
  193203. pal_ptr->red = buf[0];
  193204. pal_ptr->green = buf[1];
  193205. pal_ptr->blue = buf[2];
  193206. }
  193207. #else
  193208. for (i = 0; i < num; i++)
  193209. {
  193210. png_byte buf[3];
  193211. png_crc_read(png_ptr, buf, 3);
  193212. /* don't depend upon png_color being any order */
  193213. palette[i].red = buf[0];
  193214. palette[i].green = buf[1];
  193215. palette[i].blue = buf[2];
  193216. }
  193217. #endif
  193218. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  193219. whatever the normal CRC configuration tells us. However, if we
  193220. have an RGB image, the PLTE can be considered ancillary, so
  193221. we will act as though it is. */
  193222. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193223. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193224. #endif
  193225. {
  193226. png_crc_finish(png_ptr, 0);
  193227. }
  193228. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193229. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  193230. {
  193231. /* If we don't want to use the data from an ancillary chunk,
  193232. we have two options: an error abort, or a warning and we
  193233. ignore the data in this chunk (which should be OK, since
  193234. it's considered ancillary for a RGB or RGBA image). */
  193235. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  193236. {
  193237. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  193238. {
  193239. png_chunk_error(png_ptr, "CRC error");
  193240. }
  193241. else
  193242. {
  193243. png_chunk_warning(png_ptr, "CRC error");
  193244. return;
  193245. }
  193246. }
  193247. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  193248. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193249. {
  193250. png_chunk_warning(png_ptr, "CRC error");
  193251. }
  193252. }
  193253. #endif
  193254. png_set_PLTE(png_ptr, info_ptr, palette, num);
  193255. #if defined(PNG_READ_tRNS_SUPPORTED)
  193256. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193257. {
  193258. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  193259. {
  193260. if (png_ptr->num_trans > (png_uint_16)num)
  193261. {
  193262. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  193263. png_ptr->num_trans = (png_uint_16)num;
  193264. }
  193265. if (info_ptr->num_trans > (png_uint_16)num)
  193266. {
  193267. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  193268. info_ptr->num_trans = (png_uint_16)num;
  193269. }
  193270. }
  193271. }
  193272. #endif
  193273. }
  193274. void /* PRIVATE */
  193275. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193276. {
  193277. png_debug(1, "in png_handle_IEND\n");
  193278. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  193279. {
  193280. png_error(png_ptr, "No image in file");
  193281. }
  193282. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  193283. if (length != 0)
  193284. {
  193285. png_warning(png_ptr, "Incorrect IEND chunk length");
  193286. }
  193287. png_crc_finish(png_ptr, length);
  193288. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  193289. }
  193290. #if defined(PNG_READ_gAMA_SUPPORTED)
  193291. void /* PRIVATE */
  193292. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193293. {
  193294. png_fixed_point igamma;
  193295. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193296. float file_gamma;
  193297. #endif
  193298. png_byte buf[4];
  193299. png_debug(1, "in png_handle_gAMA\n");
  193300. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193301. png_error(png_ptr, "Missing IHDR before gAMA");
  193302. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193303. {
  193304. png_warning(png_ptr, "Invalid gAMA after IDAT");
  193305. png_crc_finish(png_ptr, length);
  193306. return;
  193307. }
  193308. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193309. /* Should be an error, but we can cope with it */
  193310. png_warning(png_ptr, "Out of place gAMA chunk");
  193311. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  193312. #if defined(PNG_READ_sRGB_SUPPORTED)
  193313. && !(info_ptr->valid & PNG_INFO_sRGB)
  193314. #endif
  193315. )
  193316. {
  193317. png_warning(png_ptr, "Duplicate gAMA chunk");
  193318. png_crc_finish(png_ptr, length);
  193319. return;
  193320. }
  193321. if (length != 4)
  193322. {
  193323. png_warning(png_ptr, "Incorrect gAMA chunk length");
  193324. png_crc_finish(png_ptr, length);
  193325. return;
  193326. }
  193327. png_crc_read(png_ptr, buf, 4);
  193328. if (png_crc_finish(png_ptr, 0))
  193329. return;
  193330. igamma = (png_fixed_point)png_get_uint_32(buf);
  193331. /* check for zero gamma */
  193332. if (igamma == 0)
  193333. {
  193334. png_warning(png_ptr,
  193335. "Ignoring gAMA chunk with gamma=0");
  193336. return;
  193337. }
  193338. #if defined(PNG_READ_sRGB_SUPPORTED)
  193339. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193340. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193341. {
  193342. png_warning(png_ptr,
  193343. "Ignoring incorrect gAMA value when sRGB is also present");
  193344. #ifndef PNG_NO_CONSOLE_IO
  193345. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  193346. #endif
  193347. return;
  193348. }
  193349. #endif /* PNG_READ_sRGB_SUPPORTED */
  193350. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193351. file_gamma = (float)igamma / (float)100000.0;
  193352. # ifdef PNG_READ_GAMMA_SUPPORTED
  193353. png_ptr->gamma = file_gamma;
  193354. # endif
  193355. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  193356. #endif
  193357. #ifdef PNG_FIXED_POINT_SUPPORTED
  193358. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  193359. #endif
  193360. }
  193361. #endif
  193362. #if defined(PNG_READ_sBIT_SUPPORTED)
  193363. void /* PRIVATE */
  193364. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193365. {
  193366. png_size_t truelen;
  193367. png_byte buf[4];
  193368. png_debug(1, "in png_handle_sBIT\n");
  193369. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  193370. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193371. png_error(png_ptr, "Missing IHDR before sBIT");
  193372. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193373. {
  193374. png_warning(png_ptr, "Invalid sBIT after IDAT");
  193375. png_crc_finish(png_ptr, length);
  193376. return;
  193377. }
  193378. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193379. {
  193380. /* Should be an error, but we can cope with it */
  193381. png_warning(png_ptr, "Out of place sBIT chunk");
  193382. }
  193383. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  193384. {
  193385. png_warning(png_ptr, "Duplicate sBIT chunk");
  193386. png_crc_finish(png_ptr, length);
  193387. return;
  193388. }
  193389. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193390. truelen = 3;
  193391. else
  193392. truelen = (png_size_t)png_ptr->channels;
  193393. if (length != truelen || length > 4)
  193394. {
  193395. png_warning(png_ptr, "Incorrect sBIT chunk length");
  193396. png_crc_finish(png_ptr, length);
  193397. return;
  193398. }
  193399. png_crc_read(png_ptr, buf, truelen);
  193400. if (png_crc_finish(png_ptr, 0))
  193401. return;
  193402. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193403. {
  193404. png_ptr->sig_bit.red = buf[0];
  193405. png_ptr->sig_bit.green = buf[1];
  193406. png_ptr->sig_bit.blue = buf[2];
  193407. png_ptr->sig_bit.alpha = buf[3];
  193408. }
  193409. else
  193410. {
  193411. png_ptr->sig_bit.gray = buf[0];
  193412. png_ptr->sig_bit.red = buf[0];
  193413. png_ptr->sig_bit.green = buf[0];
  193414. png_ptr->sig_bit.blue = buf[0];
  193415. png_ptr->sig_bit.alpha = buf[1];
  193416. }
  193417. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  193418. }
  193419. #endif
  193420. #if defined(PNG_READ_cHRM_SUPPORTED)
  193421. void /* PRIVATE */
  193422. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193423. {
  193424. png_byte buf[4];
  193425. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193426. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  193427. #endif
  193428. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  193429. int_y_green, int_x_blue, int_y_blue;
  193430. png_uint_32 uint_x, uint_y;
  193431. png_debug(1, "in png_handle_cHRM\n");
  193432. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193433. png_error(png_ptr, "Missing IHDR before cHRM");
  193434. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193435. {
  193436. png_warning(png_ptr, "Invalid cHRM after IDAT");
  193437. png_crc_finish(png_ptr, length);
  193438. return;
  193439. }
  193440. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193441. /* Should be an error, but we can cope with it */
  193442. png_warning(png_ptr, "Missing PLTE before cHRM");
  193443. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  193444. #if defined(PNG_READ_sRGB_SUPPORTED)
  193445. && !(info_ptr->valid & PNG_INFO_sRGB)
  193446. #endif
  193447. )
  193448. {
  193449. png_warning(png_ptr, "Duplicate cHRM chunk");
  193450. png_crc_finish(png_ptr, length);
  193451. return;
  193452. }
  193453. if (length != 32)
  193454. {
  193455. png_warning(png_ptr, "Incorrect cHRM chunk length");
  193456. png_crc_finish(png_ptr, length);
  193457. return;
  193458. }
  193459. png_crc_read(png_ptr, buf, 4);
  193460. uint_x = png_get_uint_32(buf);
  193461. png_crc_read(png_ptr, buf, 4);
  193462. uint_y = png_get_uint_32(buf);
  193463. if (uint_x > 80000L || uint_y > 80000L ||
  193464. uint_x + uint_y > 100000L)
  193465. {
  193466. png_warning(png_ptr, "Invalid cHRM white point");
  193467. png_crc_finish(png_ptr, 24);
  193468. return;
  193469. }
  193470. int_x_white = (png_fixed_point)uint_x;
  193471. int_y_white = (png_fixed_point)uint_y;
  193472. png_crc_read(png_ptr, buf, 4);
  193473. uint_x = png_get_uint_32(buf);
  193474. png_crc_read(png_ptr, buf, 4);
  193475. uint_y = png_get_uint_32(buf);
  193476. if (uint_x + uint_y > 100000L)
  193477. {
  193478. png_warning(png_ptr, "Invalid cHRM red point");
  193479. png_crc_finish(png_ptr, 16);
  193480. return;
  193481. }
  193482. int_x_red = (png_fixed_point)uint_x;
  193483. int_y_red = (png_fixed_point)uint_y;
  193484. png_crc_read(png_ptr, buf, 4);
  193485. uint_x = png_get_uint_32(buf);
  193486. png_crc_read(png_ptr, buf, 4);
  193487. uint_y = png_get_uint_32(buf);
  193488. if (uint_x + uint_y > 100000L)
  193489. {
  193490. png_warning(png_ptr, "Invalid cHRM green point");
  193491. png_crc_finish(png_ptr, 8);
  193492. return;
  193493. }
  193494. int_x_green = (png_fixed_point)uint_x;
  193495. int_y_green = (png_fixed_point)uint_y;
  193496. png_crc_read(png_ptr, buf, 4);
  193497. uint_x = png_get_uint_32(buf);
  193498. png_crc_read(png_ptr, buf, 4);
  193499. uint_y = png_get_uint_32(buf);
  193500. if (uint_x + uint_y > 100000L)
  193501. {
  193502. png_warning(png_ptr, "Invalid cHRM blue point");
  193503. png_crc_finish(png_ptr, 0);
  193504. return;
  193505. }
  193506. int_x_blue = (png_fixed_point)uint_x;
  193507. int_y_blue = (png_fixed_point)uint_y;
  193508. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193509. white_x = (float)int_x_white / (float)100000.0;
  193510. white_y = (float)int_y_white / (float)100000.0;
  193511. red_x = (float)int_x_red / (float)100000.0;
  193512. red_y = (float)int_y_red / (float)100000.0;
  193513. green_x = (float)int_x_green / (float)100000.0;
  193514. green_y = (float)int_y_green / (float)100000.0;
  193515. blue_x = (float)int_x_blue / (float)100000.0;
  193516. blue_y = (float)int_y_blue / (float)100000.0;
  193517. #endif
  193518. #if defined(PNG_READ_sRGB_SUPPORTED)
  193519. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  193520. {
  193521. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  193522. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  193523. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  193524. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  193525. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  193526. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  193527. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  193528. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  193529. {
  193530. png_warning(png_ptr,
  193531. "Ignoring incorrect cHRM value when sRGB is also present");
  193532. #ifndef PNG_NO_CONSOLE_IO
  193533. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193534. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  193535. white_x, white_y, red_x, red_y);
  193536. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  193537. green_x, green_y, blue_x, blue_y);
  193538. #else
  193539. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  193540. int_x_white, int_y_white, int_x_red, int_y_red);
  193541. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  193542. int_x_green, int_y_green, int_x_blue, int_y_blue);
  193543. #endif
  193544. #endif /* PNG_NO_CONSOLE_IO */
  193545. }
  193546. png_crc_finish(png_ptr, 0);
  193547. return;
  193548. }
  193549. #endif /* PNG_READ_sRGB_SUPPORTED */
  193550. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193551. png_set_cHRM(png_ptr, info_ptr,
  193552. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  193553. #endif
  193554. #ifdef PNG_FIXED_POINT_SUPPORTED
  193555. png_set_cHRM_fixed(png_ptr, info_ptr,
  193556. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  193557. int_y_green, int_x_blue, int_y_blue);
  193558. #endif
  193559. if (png_crc_finish(png_ptr, 0))
  193560. return;
  193561. }
  193562. #endif
  193563. #if defined(PNG_READ_sRGB_SUPPORTED)
  193564. void /* PRIVATE */
  193565. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193566. {
  193567. int intent;
  193568. png_byte buf[1];
  193569. png_debug(1, "in png_handle_sRGB\n");
  193570. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193571. png_error(png_ptr, "Missing IHDR before sRGB");
  193572. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193573. {
  193574. png_warning(png_ptr, "Invalid sRGB after IDAT");
  193575. png_crc_finish(png_ptr, length);
  193576. return;
  193577. }
  193578. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193579. /* Should be an error, but we can cope with it */
  193580. png_warning(png_ptr, "Out of place sRGB chunk");
  193581. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193582. {
  193583. png_warning(png_ptr, "Duplicate sRGB chunk");
  193584. png_crc_finish(png_ptr, length);
  193585. return;
  193586. }
  193587. if (length != 1)
  193588. {
  193589. png_warning(png_ptr, "Incorrect sRGB chunk length");
  193590. png_crc_finish(png_ptr, length);
  193591. return;
  193592. }
  193593. png_crc_read(png_ptr, buf, 1);
  193594. if (png_crc_finish(png_ptr, 0))
  193595. return;
  193596. intent = buf[0];
  193597. /* check for bad intent */
  193598. if (intent >= PNG_sRGB_INTENT_LAST)
  193599. {
  193600. png_warning(png_ptr, "Unknown sRGB intent");
  193601. return;
  193602. }
  193603. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  193604. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  193605. {
  193606. png_fixed_point igamma;
  193607. #ifdef PNG_FIXED_POINT_SUPPORTED
  193608. igamma=info_ptr->int_gamma;
  193609. #else
  193610. # ifdef PNG_FLOATING_POINT_SUPPORTED
  193611. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  193612. # endif
  193613. #endif
  193614. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193615. {
  193616. png_warning(png_ptr,
  193617. "Ignoring incorrect gAMA value when sRGB is also present");
  193618. #ifndef PNG_NO_CONSOLE_IO
  193619. # ifdef PNG_FIXED_POINT_SUPPORTED
  193620. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  193621. # else
  193622. # ifdef PNG_FLOATING_POINT_SUPPORTED
  193623. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  193624. # endif
  193625. # endif
  193626. #endif
  193627. }
  193628. }
  193629. #endif /* PNG_READ_gAMA_SUPPORTED */
  193630. #ifdef PNG_READ_cHRM_SUPPORTED
  193631. #ifdef PNG_FIXED_POINT_SUPPORTED
  193632. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  193633. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  193634. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  193635. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  193636. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  193637. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  193638. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  193639. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  193640. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  193641. {
  193642. png_warning(png_ptr,
  193643. "Ignoring incorrect cHRM value when sRGB is also present");
  193644. }
  193645. #endif /* PNG_FIXED_POINT_SUPPORTED */
  193646. #endif /* PNG_READ_cHRM_SUPPORTED */
  193647. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  193648. }
  193649. #endif /* PNG_READ_sRGB_SUPPORTED */
  193650. #if defined(PNG_READ_iCCP_SUPPORTED)
  193651. void /* PRIVATE */
  193652. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193653. /* Note: this does not properly handle chunks that are > 64K under DOS */
  193654. {
  193655. png_charp chunkdata;
  193656. png_byte compression_type;
  193657. png_bytep pC;
  193658. png_charp profile;
  193659. png_uint_32 skip = 0;
  193660. png_uint_32 profile_size, profile_length;
  193661. png_size_t slength, prefix_length, data_length;
  193662. png_debug(1, "in png_handle_iCCP\n");
  193663. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193664. png_error(png_ptr, "Missing IHDR before iCCP");
  193665. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193666. {
  193667. png_warning(png_ptr, "Invalid iCCP after IDAT");
  193668. png_crc_finish(png_ptr, length);
  193669. return;
  193670. }
  193671. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193672. /* Should be an error, but we can cope with it */
  193673. png_warning(png_ptr, "Out of place iCCP chunk");
  193674. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  193675. {
  193676. png_warning(png_ptr, "Duplicate iCCP chunk");
  193677. png_crc_finish(png_ptr, length);
  193678. return;
  193679. }
  193680. #ifdef PNG_MAX_MALLOC_64K
  193681. if (length > (png_uint_32)65535L)
  193682. {
  193683. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  193684. skip = length - (png_uint_32)65535L;
  193685. length = (png_uint_32)65535L;
  193686. }
  193687. #endif
  193688. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  193689. slength = (png_size_t)length;
  193690. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  193691. if (png_crc_finish(png_ptr, skip))
  193692. {
  193693. png_free(png_ptr, chunkdata);
  193694. return;
  193695. }
  193696. chunkdata[slength] = 0x00;
  193697. for (profile = chunkdata; *profile; profile++)
  193698. /* empty loop to find end of name */ ;
  193699. ++profile;
  193700. /* there should be at least one zero (the compression type byte)
  193701. following the separator, and we should be on it */
  193702. if ( profile >= chunkdata + slength - 1)
  193703. {
  193704. png_free(png_ptr, chunkdata);
  193705. png_warning(png_ptr, "Malformed iCCP chunk");
  193706. return;
  193707. }
  193708. /* compression_type should always be zero */
  193709. compression_type = *profile++;
  193710. if (compression_type)
  193711. {
  193712. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  193713. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  193714. wrote nonzero) */
  193715. }
  193716. prefix_length = profile - chunkdata;
  193717. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  193718. slength, prefix_length, &data_length);
  193719. profile_length = data_length - prefix_length;
  193720. if ( prefix_length > data_length || profile_length < 4)
  193721. {
  193722. png_free(png_ptr, chunkdata);
  193723. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  193724. return;
  193725. }
  193726. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  193727. pC = (png_bytep)(chunkdata+prefix_length);
  193728. profile_size = ((*(pC ))<<24) |
  193729. ((*(pC+1))<<16) |
  193730. ((*(pC+2))<< 8) |
  193731. ((*(pC+3)) );
  193732. if(profile_size < profile_length)
  193733. profile_length = profile_size;
  193734. if(profile_size > profile_length)
  193735. {
  193736. png_free(png_ptr, chunkdata);
  193737. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  193738. return;
  193739. }
  193740. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  193741. chunkdata + prefix_length, profile_length);
  193742. png_free(png_ptr, chunkdata);
  193743. }
  193744. #endif /* PNG_READ_iCCP_SUPPORTED */
  193745. #if defined(PNG_READ_sPLT_SUPPORTED)
  193746. void /* PRIVATE */
  193747. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193748. /* Note: this does not properly handle chunks that are > 64K under DOS */
  193749. {
  193750. png_bytep chunkdata;
  193751. png_bytep entry_start;
  193752. png_sPLT_t new_palette;
  193753. #ifdef PNG_NO_POINTER_INDEXING
  193754. png_sPLT_entryp pp;
  193755. #endif
  193756. int data_length, entry_size, i;
  193757. png_uint_32 skip = 0;
  193758. png_size_t slength;
  193759. png_debug(1, "in png_handle_sPLT\n");
  193760. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193761. png_error(png_ptr, "Missing IHDR before sPLT");
  193762. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193763. {
  193764. png_warning(png_ptr, "Invalid sPLT after IDAT");
  193765. png_crc_finish(png_ptr, length);
  193766. return;
  193767. }
  193768. #ifdef PNG_MAX_MALLOC_64K
  193769. if (length > (png_uint_32)65535L)
  193770. {
  193771. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  193772. skip = length - (png_uint_32)65535L;
  193773. length = (png_uint_32)65535L;
  193774. }
  193775. #endif
  193776. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  193777. slength = (png_size_t)length;
  193778. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  193779. if (png_crc_finish(png_ptr, skip))
  193780. {
  193781. png_free(png_ptr, chunkdata);
  193782. return;
  193783. }
  193784. chunkdata[slength] = 0x00;
  193785. for (entry_start = chunkdata; *entry_start; entry_start++)
  193786. /* empty loop to find end of name */ ;
  193787. ++entry_start;
  193788. /* a sample depth should follow the separator, and we should be on it */
  193789. if (entry_start > chunkdata + slength - 2)
  193790. {
  193791. png_free(png_ptr, chunkdata);
  193792. png_warning(png_ptr, "malformed sPLT chunk");
  193793. return;
  193794. }
  193795. new_palette.depth = *entry_start++;
  193796. entry_size = (new_palette.depth == 8 ? 6 : 10);
  193797. data_length = (slength - (entry_start - chunkdata));
  193798. /* integrity-check the data length */
  193799. if (data_length % entry_size)
  193800. {
  193801. png_free(png_ptr, chunkdata);
  193802. png_warning(png_ptr, "sPLT chunk has bad length");
  193803. return;
  193804. }
  193805. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  193806. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  193807. png_sizeof(png_sPLT_entry)))
  193808. {
  193809. png_warning(png_ptr, "sPLT chunk too long");
  193810. return;
  193811. }
  193812. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  193813. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  193814. if (new_palette.entries == NULL)
  193815. {
  193816. png_warning(png_ptr, "sPLT chunk requires too much memory");
  193817. return;
  193818. }
  193819. #ifndef PNG_NO_POINTER_INDEXING
  193820. for (i = 0; i < new_palette.nentries; i++)
  193821. {
  193822. png_sPLT_entryp pp = new_palette.entries + i;
  193823. if (new_palette.depth == 8)
  193824. {
  193825. pp->red = *entry_start++;
  193826. pp->green = *entry_start++;
  193827. pp->blue = *entry_start++;
  193828. pp->alpha = *entry_start++;
  193829. }
  193830. else
  193831. {
  193832. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  193833. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  193834. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  193835. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  193836. }
  193837. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  193838. }
  193839. #else
  193840. pp = new_palette.entries;
  193841. for (i = 0; i < new_palette.nentries; i++)
  193842. {
  193843. if (new_palette.depth == 8)
  193844. {
  193845. pp[i].red = *entry_start++;
  193846. pp[i].green = *entry_start++;
  193847. pp[i].blue = *entry_start++;
  193848. pp[i].alpha = *entry_start++;
  193849. }
  193850. else
  193851. {
  193852. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  193853. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  193854. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  193855. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  193856. }
  193857. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  193858. }
  193859. #endif
  193860. /* discard all chunk data except the name and stash that */
  193861. new_palette.name = (png_charp)chunkdata;
  193862. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  193863. png_free(png_ptr, chunkdata);
  193864. png_free(png_ptr, new_palette.entries);
  193865. }
  193866. #endif /* PNG_READ_sPLT_SUPPORTED */
  193867. #if defined(PNG_READ_tRNS_SUPPORTED)
  193868. void /* PRIVATE */
  193869. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193870. {
  193871. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  193872. int bit_mask;
  193873. png_debug(1, "in png_handle_tRNS\n");
  193874. /* For non-indexed color, mask off any bits in the tRNS value that
  193875. * exceed the bit depth. Some creators were writing extra bits there.
  193876. * This is not needed for indexed color. */
  193877. bit_mask = (1 << png_ptr->bit_depth) - 1;
  193878. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193879. png_error(png_ptr, "Missing IHDR before tRNS");
  193880. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193881. {
  193882. png_warning(png_ptr, "Invalid tRNS after IDAT");
  193883. png_crc_finish(png_ptr, length);
  193884. return;
  193885. }
  193886. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  193887. {
  193888. png_warning(png_ptr, "Duplicate tRNS chunk");
  193889. png_crc_finish(png_ptr, length);
  193890. return;
  193891. }
  193892. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  193893. {
  193894. png_byte buf[2];
  193895. if (length != 2)
  193896. {
  193897. png_warning(png_ptr, "Incorrect tRNS chunk length");
  193898. png_crc_finish(png_ptr, length);
  193899. return;
  193900. }
  193901. png_crc_read(png_ptr, buf, 2);
  193902. png_ptr->num_trans = 1;
  193903. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  193904. }
  193905. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193906. {
  193907. png_byte buf[6];
  193908. if (length != 6)
  193909. {
  193910. png_warning(png_ptr, "Incorrect tRNS chunk length");
  193911. png_crc_finish(png_ptr, length);
  193912. return;
  193913. }
  193914. png_crc_read(png_ptr, buf, (png_size_t)length);
  193915. png_ptr->num_trans = 1;
  193916. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  193917. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  193918. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  193919. }
  193920. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193921. {
  193922. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  193923. {
  193924. /* Should be an error, but we can cope with it. */
  193925. png_warning(png_ptr, "Missing PLTE before tRNS");
  193926. }
  193927. if (length > (png_uint_32)png_ptr->num_palette ||
  193928. length > PNG_MAX_PALETTE_LENGTH)
  193929. {
  193930. png_warning(png_ptr, "Incorrect tRNS chunk length");
  193931. png_crc_finish(png_ptr, length);
  193932. return;
  193933. }
  193934. if (length == 0)
  193935. {
  193936. png_warning(png_ptr, "Zero length tRNS chunk");
  193937. png_crc_finish(png_ptr, length);
  193938. return;
  193939. }
  193940. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  193941. png_ptr->num_trans = (png_uint_16)length;
  193942. }
  193943. else
  193944. {
  193945. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  193946. png_crc_finish(png_ptr, length);
  193947. return;
  193948. }
  193949. if (png_crc_finish(png_ptr, 0))
  193950. {
  193951. png_ptr->num_trans = 0;
  193952. return;
  193953. }
  193954. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  193955. &(png_ptr->trans_values));
  193956. }
  193957. #endif
  193958. #if defined(PNG_READ_bKGD_SUPPORTED)
  193959. void /* PRIVATE */
  193960. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193961. {
  193962. png_size_t truelen;
  193963. png_byte buf[6];
  193964. png_debug(1, "in png_handle_bKGD\n");
  193965. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193966. png_error(png_ptr, "Missing IHDR before bKGD");
  193967. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193968. {
  193969. png_warning(png_ptr, "Invalid bKGD after IDAT");
  193970. png_crc_finish(png_ptr, length);
  193971. return;
  193972. }
  193973. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  193974. !(png_ptr->mode & PNG_HAVE_PLTE))
  193975. {
  193976. png_warning(png_ptr, "Missing PLTE before bKGD");
  193977. png_crc_finish(png_ptr, length);
  193978. return;
  193979. }
  193980. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  193981. {
  193982. png_warning(png_ptr, "Duplicate bKGD chunk");
  193983. png_crc_finish(png_ptr, length);
  193984. return;
  193985. }
  193986. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193987. truelen = 1;
  193988. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193989. truelen = 6;
  193990. else
  193991. truelen = 2;
  193992. if (length != truelen)
  193993. {
  193994. png_warning(png_ptr, "Incorrect bKGD chunk length");
  193995. png_crc_finish(png_ptr, length);
  193996. return;
  193997. }
  193998. png_crc_read(png_ptr, buf, truelen);
  193999. if (png_crc_finish(png_ptr, 0))
  194000. return;
  194001. /* We convert the index value into RGB components so that we can allow
  194002. * arbitrary RGB values for background when we have transparency, and
  194003. * so it is easy to determine the RGB values of the background color
  194004. * from the info_ptr struct. */
  194005. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194006. {
  194007. png_ptr->background.index = buf[0];
  194008. if(info_ptr->num_palette)
  194009. {
  194010. if(buf[0] > info_ptr->num_palette)
  194011. {
  194012. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194013. return;
  194014. }
  194015. png_ptr->background.red =
  194016. (png_uint_16)png_ptr->palette[buf[0]].red;
  194017. png_ptr->background.green =
  194018. (png_uint_16)png_ptr->palette[buf[0]].green;
  194019. png_ptr->background.blue =
  194020. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194021. }
  194022. }
  194023. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194024. {
  194025. png_ptr->background.red =
  194026. png_ptr->background.green =
  194027. png_ptr->background.blue =
  194028. png_ptr->background.gray = png_get_uint_16(buf);
  194029. }
  194030. else
  194031. {
  194032. png_ptr->background.red = png_get_uint_16(buf);
  194033. png_ptr->background.green = png_get_uint_16(buf + 2);
  194034. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194035. }
  194036. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194037. }
  194038. #endif
  194039. #if defined(PNG_READ_hIST_SUPPORTED)
  194040. void /* PRIVATE */
  194041. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194042. {
  194043. unsigned int num, i;
  194044. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194045. png_debug(1, "in png_handle_hIST\n");
  194046. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194047. png_error(png_ptr, "Missing IHDR before hIST");
  194048. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194049. {
  194050. png_warning(png_ptr, "Invalid hIST after IDAT");
  194051. png_crc_finish(png_ptr, length);
  194052. return;
  194053. }
  194054. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194055. {
  194056. png_warning(png_ptr, "Missing PLTE before hIST");
  194057. png_crc_finish(png_ptr, length);
  194058. return;
  194059. }
  194060. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194061. {
  194062. png_warning(png_ptr, "Duplicate hIST chunk");
  194063. png_crc_finish(png_ptr, length);
  194064. return;
  194065. }
  194066. num = length / 2 ;
  194067. if (num != (unsigned int) png_ptr->num_palette || num >
  194068. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194069. {
  194070. png_warning(png_ptr, "Incorrect hIST chunk length");
  194071. png_crc_finish(png_ptr, length);
  194072. return;
  194073. }
  194074. for (i = 0; i < num; i++)
  194075. {
  194076. png_byte buf[2];
  194077. png_crc_read(png_ptr, buf, 2);
  194078. readbuf[i] = png_get_uint_16(buf);
  194079. }
  194080. if (png_crc_finish(png_ptr, 0))
  194081. return;
  194082. png_set_hIST(png_ptr, info_ptr, readbuf);
  194083. }
  194084. #endif
  194085. #if defined(PNG_READ_pHYs_SUPPORTED)
  194086. void /* PRIVATE */
  194087. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194088. {
  194089. png_byte buf[9];
  194090. png_uint_32 res_x, res_y;
  194091. int unit_type;
  194092. png_debug(1, "in png_handle_pHYs\n");
  194093. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194094. png_error(png_ptr, "Missing IHDR before pHYs");
  194095. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194096. {
  194097. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194098. png_crc_finish(png_ptr, length);
  194099. return;
  194100. }
  194101. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194102. {
  194103. png_warning(png_ptr, "Duplicate pHYs chunk");
  194104. png_crc_finish(png_ptr, length);
  194105. return;
  194106. }
  194107. if (length != 9)
  194108. {
  194109. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194110. png_crc_finish(png_ptr, length);
  194111. return;
  194112. }
  194113. png_crc_read(png_ptr, buf, 9);
  194114. if (png_crc_finish(png_ptr, 0))
  194115. return;
  194116. res_x = png_get_uint_32(buf);
  194117. res_y = png_get_uint_32(buf + 4);
  194118. unit_type = buf[8];
  194119. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194120. }
  194121. #endif
  194122. #if defined(PNG_READ_oFFs_SUPPORTED)
  194123. void /* PRIVATE */
  194124. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194125. {
  194126. png_byte buf[9];
  194127. png_int_32 offset_x, offset_y;
  194128. int unit_type;
  194129. png_debug(1, "in png_handle_oFFs\n");
  194130. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194131. png_error(png_ptr, "Missing IHDR before oFFs");
  194132. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194133. {
  194134. png_warning(png_ptr, "Invalid oFFs after IDAT");
  194135. png_crc_finish(png_ptr, length);
  194136. return;
  194137. }
  194138. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  194139. {
  194140. png_warning(png_ptr, "Duplicate oFFs chunk");
  194141. png_crc_finish(png_ptr, length);
  194142. return;
  194143. }
  194144. if (length != 9)
  194145. {
  194146. png_warning(png_ptr, "Incorrect oFFs chunk length");
  194147. png_crc_finish(png_ptr, length);
  194148. return;
  194149. }
  194150. png_crc_read(png_ptr, buf, 9);
  194151. if (png_crc_finish(png_ptr, 0))
  194152. return;
  194153. offset_x = png_get_int_32(buf);
  194154. offset_y = png_get_int_32(buf + 4);
  194155. unit_type = buf[8];
  194156. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  194157. }
  194158. #endif
  194159. #if defined(PNG_READ_pCAL_SUPPORTED)
  194160. /* read the pCAL chunk (described in the PNG Extensions document) */
  194161. void /* PRIVATE */
  194162. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194163. {
  194164. png_charp purpose;
  194165. png_int_32 X0, X1;
  194166. png_byte type, nparams;
  194167. png_charp buf, units, endptr;
  194168. png_charpp params;
  194169. png_size_t slength;
  194170. int i;
  194171. png_debug(1, "in png_handle_pCAL\n");
  194172. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194173. png_error(png_ptr, "Missing IHDR before pCAL");
  194174. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194175. {
  194176. png_warning(png_ptr, "Invalid pCAL after IDAT");
  194177. png_crc_finish(png_ptr, length);
  194178. return;
  194179. }
  194180. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  194181. {
  194182. png_warning(png_ptr, "Duplicate pCAL chunk");
  194183. png_crc_finish(png_ptr, length);
  194184. return;
  194185. }
  194186. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  194187. length + 1);
  194188. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194189. if (purpose == NULL)
  194190. {
  194191. png_warning(png_ptr, "No memory for pCAL purpose.");
  194192. return;
  194193. }
  194194. slength = (png_size_t)length;
  194195. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  194196. if (png_crc_finish(png_ptr, 0))
  194197. {
  194198. png_free(png_ptr, purpose);
  194199. return;
  194200. }
  194201. purpose[slength] = 0x00; /* null terminate the last string */
  194202. png_debug(3, "Finding end of pCAL purpose string\n");
  194203. for (buf = purpose; *buf; buf++)
  194204. /* empty loop */ ;
  194205. endptr = purpose + slength;
  194206. /* We need to have at least 12 bytes after the purpose string
  194207. in order to get the parameter information. */
  194208. if (endptr <= buf + 12)
  194209. {
  194210. png_warning(png_ptr, "Invalid pCAL data");
  194211. png_free(png_ptr, purpose);
  194212. return;
  194213. }
  194214. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  194215. X0 = png_get_int_32((png_bytep)buf+1);
  194216. X1 = png_get_int_32((png_bytep)buf+5);
  194217. type = buf[9];
  194218. nparams = buf[10];
  194219. units = buf + 11;
  194220. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  194221. /* Check that we have the right number of parameters for known
  194222. equation types. */
  194223. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  194224. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  194225. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  194226. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  194227. {
  194228. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  194229. png_free(png_ptr, purpose);
  194230. return;
  194231. }
  194232. else if (type >= PNG_EQUATION_LAST)
  194233. {
  194234. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  194235. }
  194236. for (buf = units; *buf; buf++)
  194237. /* Empty loop to move past the units string. */ ;
  194238. png_debug(3, "Allocating pCAL parameters array\n");
  194239. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  194240. *png_sizeof(png_charp))) ;
  194241. if (params == NULL)
  194242. {
  194243. png_free(png_ptr, purpose);
  194244. png_warning(png_ptr, "No memory for pCAL params.");
  194245. return;
  194246. }
  194247. /* Get pointers to the start of each parameter string. */
  194248. for (i = 0; i < (int)nparams; i++)
  194249. {
  194250. buf++; /* Skip the null string terminator from previous parameter. */
  194251. png_debug1(3, "Reading pCAL parameter %d\n", i);
  194252. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  194253. /* Empty loop to move past each parameter string */ ;
  194254. /* Make sure we haven't run out of data yet */
  194255. if (buf > endptr)
  194256. {
  194257. png_warning(png_ptr, "Invalid pCAL data");
  194258. png_free(png_ptr, purpose);
  194259. png_free(png_ptr, params);
  194260. return;
  194261. }
  194262. }
  194263. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  194264. units, params);
  194265. png_free(png_ptr, purpose);
  194266. png_free(png_ptr, params);
  194267. }
  194268. #endif
  194269. #if defined(PNG_READ_sCAL_SUPPORTED)
  194270. /* read the sCAL chunk */
  194271. void /* PRIVATE */
  194272. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194273. {
  194274. png_charp buffer, ep;
  194275. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194276. double width, height;
  194277. png_charp vp;
  194278. #else
  194279. #ifdef PNG_FIXED_POINT_SUPPORTED
  194280. png_charp swidth, sheight;
  194281. #endif
  194282. #endif
  194283. png_size_t slength;
  194284. png_debug(1, "in png_handle_sCAL\n");
  194285. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194286. png_error(png_ptr, "Missing IHDR before sCAL");
  194287. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194288. {
  194289. png_warning(png_ptr, "Invalid sCAL after IDAT");
  194290. png_crc_finish(png_ptr, length);
  194291. return;
  194292. }
  194293. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  194294. {
  194295. png_warning(png_ptr, "Duplicate sCAL chunk");
  194296. png_crc_finish(png_ptr, length);
  194297. return;
  194298. }
  194299. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  194300. length + 1);
  194301. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194302. if (buffer == NULL)
  194303. {
  194304. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  194305. return;
  194306. }
  194307. slength = (png_size_t)length;
  194308. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  194309. if (png_crc_finish(png_ptr, 0))
  194310. {
  194311. png_free(png_ptr, buffer);
  194312. return;
  194313. }
  194314. buffer[slength] = 0x00; /* null terminate the last string */
  194315. ep = buffer + 1; /* skip unit byte */
  194316. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194317. width = png_strtod(png_ptr, ep, &vp);
  194318. if (*vp)
  194319. {
  194320. png_warning(png_ptr, "malformed width string in sCAL chunk");
  194321. return;
  194322. }
  194323. #else
  194324. #ifdef PNG_FIXED_POINT_SUPPORTED
  194325. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194326. if (swidth == NULL)
  194327. {
  194328. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  194329. return;
  194330. }
  194331. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  194332. #endif
  194333. #endif
  194334. for (ep = buffer; *ep; ep++)
  194335. /* empty loop */ ;
  194336. ep++;
  194337. if (buffer + slength < ep)
  194338. {
  194339. png_warning(png_ptr, "Truncated sCAL chunk");
  194340. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  194341. !defined(PNG_FLOATING_POINT_SUPPORTED)
  194342. png_free(png_ptr, swidth);
  194343. #endif
  194344. png_free(png_ptr, buffer);
  194345. return;
  194346. }
  194347. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194348. height = png_strtod(png_ptr, ep, &vp);
  194349. if (*vp)
  194350. {
  194351. png_warning(png_ptr, "malformed height string in sCAL chunk");
  194352. return;
  194353. }
  194354. #else
  194355. #ifdef PNG_FIXED_POINT_SUPPORTED
  194356. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194357. if (swidth == NULL)
  194358. {
  194359. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  194360. return;
  194361. }
  194362. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  194363. #endif
  194364. #endif
  194365. if (buffer + slength < ep
  194366. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194367. || width <= 0. || height <= 0.
  194368. #endif
  194369. )
  194370. {
  194371. png_warning(png_ptr, "Invalid sCAL data");
  194372. png_free(png_ptr, buffer);
  194373. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194374. png_free(png_ptr, swidth);
  194375. png_free(png_ptr, sheight);
  194376. #endif
  194377. return;
  194378. }
  194379. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194380. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  194381. #else
  194382. #ifdef PNG_FIXED_POINT_SUPPORTED
  194383. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  194384. #endif
  194385. #endif
  194386. png_free(png_ptr, buffer);
  194387. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194388. png_free(png_ptr, swidth);
  194389. png_free(png_ptr, sheight);
  194390. #endif
  194391. }
  194392. #endif
  194393. #if defined(PNG_READ_tIME_SUPPORTED)
  194394. void /* PRIVATE */
  194395. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194396. {
  194397. png_byte buf[7];
  194398. png_time mod_time;
  194399. png_debug(1, "in png_handle_tIME\n");
  194400. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194401. png_error(png_ptr, "Out of place tIME chunk");
  194402. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  194403. {
  194404. png_warning(png_ptr, "Duplicate tIME chunk");
  194405. png_crc_finish(png_ptr, length);
  194406. return;
  194407. }
  194408. if (png_ptr->mode & PNG_HAVE_IDAT)
  194409. png_ptr->mode |= PNG_AFTER_IDAT;
  194410. if (length != 7)
  194411. {
  194412. png_warning(png_ptr, "Incorrect tIME chunk length");
  194413. png_crc_finish(png_ptr, length);
  194414. return;
  194415. }
  194416. png_crc_read(png_ptr, buf, 7);
  194417. if (png_crc_finish(png_ptr, 0))
  194418. return;
  194419. mod_time.second = buf[6];
  194420. mod_time.minute = buf[5];
  194421. mod_time.hour = buf[4];
  194422. mod_time.day = buf[3];
  194423. mod_time.month = buf[2];
  194424. mod_time.year = png_get_uint_16(buf);
  194425. png_set_tIME(png_ptr, info_ptr, &mod_time);
  194426. }
  194427. #endif
  194428. #if defined(PNG_READ_tEXt_SUPPORTED)
  194429. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194430. void /* PRIVATE */
  194431. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194432. {
  194433. png_textp text_ptr;
  194434. png_charp key;
  194435. png_charp text;
  194436. png_uint_32 skip = 0;
  194437. png_size_t slength;
  194438. int ret;
  194439. png_debug(1, "in png_handle_tEXt\n");
  194440. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194441. png_error(png_ptr, "Missing IHDR before tEXt");
  194442. if (png_ptr->mode & PNG_HAVE_IDAT)
  194443. png_ptr->mode |= PNG_AFTER_IDAT;
  194444. #ifdef PNG_MAX_MALLOC_64K
  194445. if (length > (png_uint_32)65535L)
  194446. {
  194447. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  194448. skip = length - (png_uint_32)65535L;
  194449. length = (png_uint_32)65535L;
  194450. }
  194451. #endif
  194452. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194453. if (key == NULL)
  194454. {
  194455. png_warning(png_ptr, "No memory to process text chunk.");
  194456. return;
  194457. }
  194458. slength = (png_size_t)length;
  194459. png_crc_read(png_ptr, (png_bytep)key, slength);
  194460. if (png_crc_finish(png_ptr, skip))
  194461. {
  194462. png_free(png_ptr, key);
  194463. return;
  194464. }
  194465. key[slength] = 0x00;
  194466. for (text = key; *text; text++)
  194467. /* empty loop to find end of key */ ;
  194468. if (text != key + slength)
  194469. text++;
  194470. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194471. (png_uint_32)png_sizeof(png_text));
  194472. if (text_ptr == NULL)
  194473. {
  194474. png_warning(png_ptr, "Not enough memory to process text chunk.");
  194475. png_free(png_ptr, key);
  194476. return;
  194477. }
  194478. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  194479. text_ptr->key = key;
  194480. #ifdef PNG_iTXt_SUPPORTED
  194481. text_ptr->lang = NULL;
  194482. text_ptr->lang_key = NULL;
  194483. text_ptr->itxt_length = 0;
  194484. #endif
  194485. text_ptr->text = text;
  194486. text_ptr->text_length = png_strlen(text);
  194487. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194488. png_free(png_ptr, key);
  194489. png_free(png_ptr, text_ptr);
  194490. if (ret)
  194491. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  194492. }
  194493. #endif
  194494. #if defined(PNG_READ_zTXt_SUPPORTED)
  194495. /* note: this does not correctly handle chunks that are > 64K under DOS */
  194496. void /* PRIVATE */
  194497. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194498. {
  194499. png_textp text_ptr;
  194500. png_charp chunkdata;
  194501. png_charp text;
  194502. int comp_type;
  194503. int ret;
  194504. png_size_t slength, prefix_len, data_len;
  194505. png_debug(1, "in png_handle_zTXt\n");
  194506. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194507. png_error(png_ptr, "Missing IHDR before zTXt");
  194508. if (png_ptr->mode & PNG_HAVE_IDAT)
  194509. png_ptr->mode |= PNG_AFTER_IDAT;
  194510. #ifdef PNG_MAX_MALLOC_64K
  194511. /* We will no doubt have problems with chunks even half this size, but
  194512. there is no hard and fast rule to tell us where to stop. */
  194513. if (length > (png_uint_32)65535L)
  194514. {
  194515. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  194516. png_crc_finish(png_ptr, length);
  194517. return;
  194518. }
  194519. #endif
  194520. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194521. if (chunkdata == NULL)
  194522. {
  194523. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  194524. return;
  194525. }
  194526. slength = (png_size_t)length;
  194527. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194528. if (png_crc_finish(png_ptr, 0))
  194529. {
  194530. png_free(png_ptr, chunkdata);
  194531. return;
  194532. }
  194533. chunkdata[slength] = 0x00;
  194534. for (text = chunkdata; *text; text++)
  194535. /* empty loop */ ;
  194536. /* zTXt must have some text after the chunkdataword */
  194537. if (text >= chunkdata + slength - 2)
  194538. {
  194539. png_warning(png_ptr, "Truncated zTXt chunk");
  194540. png_free(png_ptr, chunkdata);
  194541. return;
  194542. }
  194543. else
  194544. {
  194545. comp_type = *(++text);
  194546. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  194547. {
  194548. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  194549. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  194550. }
  194551. text++; /* skip the compression_method byte */
  194552. }
  194553. prefix_len = text - chunkdata;
  194554. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  194555. (png_size_t)length, prefix_len, &data_len);
  194556. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194557. (png_uint_32)png_sizeof(png_text));
  194558. if (text_ptr == NULL)
  194559. {
  194560. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  194561. png_free(png_ptr, chunkdata);
  194562. return;
  194563. }
  194564. text_ptr->compression = comp_type;
  194565. text_ptr->key = chunkdata;
  194566. #ifdef PNG_iTXt_SUPPORTED
  194567. text_ptr->lang = NULL;
  194568. text_ptr->lang_key = NULL;
  194569. text_ptr->itxt_length = 0;
  194570. #endif
  194571. text_ptr->text = chunkdata + prefix_len;
  194572. text_ptr->text_length = data_len;
  194573. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194574. png_free(png_ptr, text_ptr);
  194575. png_free(png_ptr, chunkdata);
  194576. if (ret)
  194577. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  194578. }
  194579. #endif
  194580. #if defined(PNG_READ_iTXt_SUPPORTED)
  194581. /* note: this does not correctly handle chunks that are > 64K under DOS */
  194582. void /* PRIVATE */
  194583. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194584. {
  194585. png_textp text_ptr;
  194586. png_charp chunkdata;
  194587. png_charp key, lang, text, lang_key;
  194588. int comp_flag;
  194589. int comp_type = 0;
  194590. int ret;
  194591. png_size_t slength, prefix_len, data_len;
  194592. png_debug(1, "in png_handle_iTXt\n");
  194593. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194594. png_error(png_ptr, "Missing IHDR before iTXt");
  194595. if (png_ptr->mode & PNG_HAVE_IDAT)
  194596. png_ptr->mode |= PNG_AFTER_IDAT;
  194597. #ifdef PNG_MAX_MALLOC_64K
  194598. /* We will no doubt have problems with chunks even half this size, but
  194599. there is no hard and fast rule to tell us where to stop. */
  194600. if (length > (png_uint_32)65535L)
  194601. {
  194602. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  194603. png_crc_finish(png_ptr, length);
  194604. return;
  194605. }
  194606. #endif
  194607. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194608. if (chunkdata == NULL)
  194609. {
  194610. png_warning(png_ptr, "No memory to process iTXt chunk.");
  194611. return;
  194612. }
  194613. slength = (png_size_t)length;
  194614. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194615. if (png_crc_finish(png_ptr, 0))
  194616. {
  194617. png_free(png_ptr, chunkdata);
  194618. return;
  194619. }
  194620. chunkdata[slength] = 0x00;
  194621. for (lang = chunkdata; *lang; lang++)
  194622. /* empty loop */ ;
  194623. lang++; /* skip NUL separator */
  194624. /* iTXt must have a language tag (possibly empty), two compression bytes,
  194625. translated keyword (possibly empty), and possibly some text after the
  194626. keyword */
  194627. if (lang >= chunkdata + slength - 3)
  194628. {
  194629. png_warning(png_ptr, "Truncated iTXt chunk");
  194630. png_free(png_ptr, chunkdata);
  194631. return;
  194632. }
  194633. else
  194634. {
  194635. comp_flag = *lang++;
  194636. comp_type = *lang++;
  194637. }
  194638. for (lang_key = lang; *lang_key; lang_key++)
  194639. /* empty loop */ ;
  194640. lang_key++; /* skip NUL separator */
  194641. if (lang_key >= chunkdata + slength)
  194642. {
  194643. png_warning(png_ptr, "Truncated iTXt chunk");
  194644. png_free(png_ptr, chunkdata);
  194645. return;
  194646. }
  194647. for (text = lang_key; *text; text++)
  194648. /* empty loop */ ;
  194649. text++; /* skip NUL separator */
  194650. if (text >= chunkdata + slength)
  194651. {
  194652. png_warning(png_ptr, "Malformed iTXt chunk");
  194653. png_free(png_ptr, chunkdata);
  194654. return;
  194655. }
  194656. prefix_len = text - chunkdata;
  194657. key=chunkdata;
  194658. if (comp_flag)
  194659. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  194660. (size_t)length, prefix_len, &data_len);
  194661. else
  194662. data_len=png_strlen(chunkdata + prefix_len);
  194663. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194664. (png_uint_32)png_sizeof(png_text));
  194665. if (text_ptr == NULL)
  194666. {
  194667. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  194668. png_free(png_ptr, chunkdata);
  194669. return;
  194670. }
  194671. text_ptr->compression = (int)comp_flag + 1;
  194672. text_ptr->lang_key = chunkdata+(lang_key-key);
  194673. text_ptr->lang = chunkdata+(lang-key);
  194674. text_ptr->itxt_length = data_len;
  194675. text_ptr->text_length = 0;
  194676. text_ptr->key = chunkdata;
  194677. text_ptr->text = chunkdata + prefix_len;
  194678. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194679. png_free(png_ptr, text_ptr);
  194680. png_free(png_ptr, chunkdata);
  194681. if (ret)
  194682. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  194683. }
  194684. #endif
  194685. /* This function is called when we haven't found a handler for a
  194686. chunk. If there isn't a problem with the chunk itself (ie bad
  194687. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  194688. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  194689. case it will be saved away to be written out later. */
  194690. void /* PRIVATE */
  194691. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194692. {
  194693. png_uint_32 skip = 0;
  194694. png_debug(1, "in png_handle_unknown\n");
  194695. if (png_ptr->mode & PNG_HAVE_IDAT)
  194696. {
  194697. #ifdef PNG_USE_LOCAL_ARRAYS
  194698. PNG_CONST PNG_IDAT;
  194699. #endif
  194700. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  194701. png_ptr->mode |= PNG_AFTER_IDAT;
  194702. }
  194703. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  194704. if (!(png_ptr->chunk_name[0] & 0x20))
  194705. {
  194706. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  194707. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  194708. PNG_HANDLE_CHUNK_ALWAYS
  194709. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  194710. && png_ptr->read_user_chunk_fn == NULL
  194711. #endif
  194712. )
  194713. #endif
  194714. png_chunk_error(png_ptr, "unknown critical chunk");
  194715. }
  194716. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  194717. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  194718. (png_ptr->read_user_chunk_fn != NULL))
  194719. {
  194720. #ifdef PNG_MAX_MALLOC_64K
  194721. if (length > (png_uint_32)65535L)
  194722. {
  194723. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  194724. skip = length - (png_uint_32)65535L;
  194725. length = (png_uint_32)65535L;
  194726. }
  194727. #endif
  194728. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  194729. (png_charp)png_ptr->chunk_name, 5);
  194730. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  194731. png_ptr->unknown_chunk.size = (png_size_t)length;
  194732. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  194733. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  194734. if(png_ptr->read_user_chunk_fn != NULL)
  194735. {
  194736. /* callback to user unknown chunk handler */
  194737. int ret;
  194738. ret = (*(png_ptr->read_user_chunk_fn))
  194739. (png_ptr, &png_ptr->unknown_chunk);
  194740. if (ret < 0)
  194741. png_chunk_error(png_ptr, "error in user chunk");
  194742. if (ret == 0)
  194743. {
  194744. if (!(png_ptr->chunk_name[0] & 0x20))
  194745. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  194746. PNG_HANDLE_CHUNK_ALWAYS)
  194747. png_chunk_error(png_ptr, "unknown critical chunk");
  194748. png_set_unknown_chunks(png_ptr, info_ptr,
  194749. &png_ptr->unknown_chunk, 1);
  194750. }
  194751. }
  194752. #else
  194753. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  194754. #endif
  194755. png_free(png_ptr, png_ptr->unknown_chunk.data);
  194756. png_ptr->unknown_chunk.data = NULL;
  194757. }
  194758. else
  194759. #endif
  194760. skip = length;
  194761. png_crc_finish(png_ptr, skip);
  194762. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  194763. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  194764. #endif
  194765. }
  194766. /* This function is called to verify that a chunk name is valid.
  194767. This function can't have the "critical chunk check" incorporated
  194768. into it, since in the future we will need to be able to call user
  194769. functions to handle unknown critical chunks after we check that
  194770. the chunk name itself is valid. */
  194771. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  194772. void /* PRIVATE */
  194773. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  194774. {
  194775. png_debug(1, "in png_check_chunk_name\n");
  194776. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  194777. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  194778. {
  194779. png_chunk_error(png_ptr, "invalid chunk type");
  194780. }
  194781. }
  194782. /* Combines the row recently read in with the existing pixels in the
  194783. row. This routine takes care of alpha and transparency if requested.
  194784. This routine also handles the two methods of progressive display
  194785. of interlaced images, depending on the mask value.
  194786. The mask value describes which pixels are to be combined with
  194787. the row. The pattern always repeats every 8 pixels, so just 8
  194788. bits are needed. A one indicates the pixel is to be combined,
  194789. a zero indicates the pixel is to be skipped. This is in addition
  194790. to any alpha or transparency value associated with the pixel. If
  194791. you want all pixels to be combined, pass 0xff (255) in mask. */
  194792. void /* PRIVATE */
  194793. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  194794. {
  194795. png_debug(1,"in png_combine_row\n");
  194796. if (mask == 0xff)
  194797. {
  194798. png_memcpy(row, png_ptr->row_buf + 1,
  194799. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  194800. }
  194801. else
  194802. {
  194803. switch (png_ptr->row_info.pixel_depth)
  194804. {
  194805. case 1:
  194806. {
  194807. png_bytep sp = png_ptr->row_buf + 1;
  194808. png_bytep dp = row;
  194809. int s_inc, s_start, s_end;
  194810. int m = 0x80;
  194811. int shift;
  194812. png_uint_32 i;
  194813. png_uint_32 row_width = png_ptr->width;
  194814. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  194815. if (png_ptr->transformations & PNG_PACKSWAP)
  194816. {
  194817. s_start = 0;
  194818. s_end = 7;
  194819. s_inc = 1;
  194820. }
  194821. else
  194822. #endif
  194823. {
  194824. s_start = 7;
  194825. s_end = 0;
  194826. s_inc = -1;
  194827. }
  194828. shift = s_start;
  194829. for (i = 0; i < row_width; i++)
  194830. {
  194831. if (m & mask)
  194832. {
  194833. int value;
  194834. value = (*sp >> shift) & 0x01;
  194835. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  194836. *dp |= (png_byte)(value << shift);
  194837. }
  194838. if (shift == s_end)
  194839. {
  194840. shift = s_start;
  194841. sp++;
  194842. dp++;
  194843. }
  194844. else
  194845. shift += s_inc;
  194846. if (m == 1)
  194847. m = 0x80;
  194848. else
  194849. m >>= 1;
  194850. }
  194851. break;
  194852. }
  194853. case 2:
  194854. {
  194855. png_bytep sp = png_ptr->row_buf + 1;
  194856. png_bytep dp = row;
  194857. int s_start, s_end, s_inc;
  194858. int m = 0x80;
  194859. int shift;
  194860. png_uint_32 i;
  194861. png_uint_32 row_width = png_ptr->width;
  194862. int value;
  194863. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  194864. if (png_ptr->transformations & PNG_PACKSWAP)
  194865. {
  194866. s_start = 0;
  194867. s_end = 6;
  194868. s_inc = 2;
  194869. }
  194870. else
  194871. #endif
  194872. {
  194873. s_start = 6;
  194874. s_end = 0;
  194875. s_inc = -2;
  194876. }
  194877. shift = s_start;
  194878. for (i = 0; i < row_width; i++)
  194879. {
  194880. if (m & mask)
  194881. {
  194882. value = (*sp >> shift) & 0x03;
  194883. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  194884. *dp |= (png_byte)(value << shift);
  194885. }
  194886. if (shift == s_end)
  194887. {
  194888. shift = s_start;
  194889. sp++;
  194890. dp++;
  194891. }
  194892. else
  194893. shift += s_inc;
  194894. if (m == 1)
  194895. m = 0x80;
  194896. else
  194897. m >>= 1;
  194898. }
  194899. break;
  194900. }
  194901. case 4:
  194902. {
  194903. png_bytep sp = png_ptr->row_buf + 1;
  194904. png_bytep dp = row;
  194905. int s_start, s_end, s_inc;
  194906. int m = 0x80;
  194907. int shift;
  194908. png_uint_32 i;
  194909. png_uint_32 row_width = png_ptr->width;
  194910. int value;
  194911. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  194912. if (png_ptr->transformations & PNG_PACKSWAP)
  194913. {
  194914. s_start = 0;
  194915. s_end = 4;
  194916. s_inc = 4;
  194917. }
  194918. else
  194919. #endif
  194920. {
  194921. s_start = 4;
  194922. s_end = 0;
  194923. s_inc = -4;
  194924. }
  194925. shift = s_start;
  194926. for (i = 0; i < row_width; i++)
  194927. {
  194928. if (m & mask)
  194929. {
  194930. value = (*sp >> shift) & 0xf;
  194931. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  194932. *dp |= (png_byte)(value << shift);
  194933. }
  194934. if (shift == s_end)
  194935. {
  194936. shift = s_start;
  194937. sp++;
  194938. dp++;
  194939. }
  194940. else
  194941. shift += s_inc;
  194942. if (m == 1)
  194943. m = 0x80;
  194944. else
  194945. m >>= 1;
  194946. }
  194947. break;
  194948. }
  194949. default:
  194950. {
  194951. png_bytep sp = png_ptr->row_buf + 1;
  194952. png_bytep dp = row;
  194953. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  194954. png_uint_32 i;
  194955. png_uint_32 row_width = png_ptr->width;
  194956. png_byte m = 0x80;
  194957. for (i = 0; i < row_width; i++)
  194958. {
  194959. if (m & mask)
  194960. {
  194961. png_memcpy(dp, sp, pixel_bytes);
  194962. }
  194963. sp += pixel_bytes;
  194964. dp += pixel_bytes;
  194965. if (m == 1)
  194966. m = 0x80;
  194967. else
  194968. m >>= 1;
  194969. }
  194970. break;
  194971. }
  194972. }
  194973. }
  194974. }
  194975. #ifdef PNG_READ_INTERLACING_SUPPORTED
  194976. /* OLD pre-1.0.9 interface:
  194977. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  194978. png_uint_32 transformations)
  194979. */
  194980. void /* PRIVATE */
  194981. png_do_read_interlace(png_structp png_ptr)
  194982. {
  194983. png_row_infop row_info = &(png_ptr->row_info);
  194984. png_bytep row = png_ptr->row_buf + 1;
  194985. int pass = png_ptr->pass;
  194986. png_uint_32 transformations = png_ptr->transformations;
  194987. #ifdef PNG_USE_LOCAL_ARRAYS
  194988. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  194989. /* offset to next interlace block */
  194990. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  194991. #endif
  194992. png_debug(1,"in png_do_read_interlace\n");
  194993. if (row != NULL && row_info != NULL)
  194994. {
  194995. png_uint_32 final_width;
  194996. final_width = row_info->width * png_pass_inc[pass];
  194997. switch (row_info->pixel_depth)
  194998. {
  194999. case 1:
  195000. {
  195001. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195002. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195003. int sshift, dshift;
  195004. int s_start, s_end, s_inc;
  195005. int jstop = png_pass_inc[pass];
  195006. png_byte v;
  195007. png_uint_32 i;
  195008. int j;
  195009. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195010. if (transformations & PNG_PACKSWAP)
  195011. {
  195012. sshift = (int)((row_info->width + 7) & 0x07);
  195013. dshift = (int)((final_width + 7) & 0x07);
  195014. s_start = 7;
  195015. s_end = 0;
  195016. s_inc = -1;
  195017. }
  195018. else
  195019. #endif
  195020. {
  195021. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195022. dshift = 7 - (int)((final_width + 7) & 0x07);
  195023. s_start = 0;
  195024. s_end = 7;
  195025. s_inc = 1;
  195026. }
  195027. for (i = 0; i < row_info->width; i++)
  195028. {
  195029. v = (png_byte)((*sp >> sshift) & 0x01);
  195030. for (j = 0; j < jstop; j++)
  195031. {
  195032. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195033. *dp |= (png_byte)(v << dshift);
  195034. if (dshift == s_end)
  195035. {
  195036. dshift = s_start;
  195037. dp--;
  195038. }
  195039. else
  195040. dshift += s_inc;
  195041. }
  195042. if (sshift == s_end)
  195043. {
  195044. sshift = s_start;
  195045. sp--;
  195046. }
  195047. else
  195048. sshift += s_inc;
  195049. }
  195050. break;
  195051. }
  195052. case 2:
  195053. {
  195054. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195055. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195056. int sshift, dshift;
  195057. int s_start, s_end, s_inc;
  195058. int jstop = png_pass_inc[pass];
  195059. png_uint_32 i;
  195060. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195061. if (transformations & PNG_PACKSWAP)
  195062. {
  195063. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195064. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195065. s_start = 6;
  195066. s_end = 0;
  195067. s_inc = -2;
  195068. }
  195069. else
  195070. #endif
  195071. {
  195072. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195073. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195074. s_start = 0;
  195075. s_end = 6;
  195076. s_inc = 2;
  195077. }
  195078. for (i = 0; i < row_info->width; i++)
  195079. {
  195080. png_byte v;
  195081. int j;
  195082. v = (png_byte)((*sp >> sshift) & 0x03);
  195083. for (j = 0; j < jstop; j++)
  195084. {
  195085. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195086. *dp |= (png_byte)(v << dshift);
  195087. if (dshift == s_end)
  195088. {
  195089. dshift = s_start;
  195090. dp--;
  195091. }
  195092. else
  195093. dshift += s_inc;
  195094. }
  195095. if (sshift == s_end)
  195096. {
  195097. sshift = s_start;
  195098. sp--;
  195099. }
  195100. else
  195101. sshift += s_inc;
  195102. }
  195103. break;
  195104. }
  195105. case 4:
  195106. {
  195107. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195108. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195109. int sshift, dshift;
  195110. int s_start, s_end, s_inc;
  195111. png_uint_32 i;
  195112. int jstop = png_pass_inc[pass];
  195113. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195114. if (transformations & PNG_PACKSWAP)
  195115. {
  195116. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195117. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195118. s_start = 4;
  195119. s_end = 0;
  195120. s_inc = -4;
  195121. }
  195122. else
  195123. #endif
  195124. {
  195125. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195126. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  195127. s_start = 0;
  195128. s_end = 4;
  195129. s_inc = 4;
  195130. }
  195131. for (i = 0; i < row_info->width; i++)
  195132. {
  195133. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  195134. int j;
  195135. for (j = 0; j < jstop; j++)
  195136. {
  195137. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  195138. *dp |= (png_byte)(v << dshift);
  195139. if (dshift == s_end)
  195140. {
  195141. dshift = s_start;
  195142. dp--;
  195143. }
  195144. else
  195145. dshift += s_inc;
  195146. }
  195147. if (sshift == s_end)
  195148. {
  195149. sshift = s_start;
  195150. sp--;
  195151. }
  195152. else
  195153. sshift += s_inc;
  195154. }
  195155. break;
  195156. }
  195157. default:
  195158. {
  195159. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  195160. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  195161. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  195162. int jstop = png_pass_inc[pass];
  195163. png_uint_32 i;
  195164. for (i = 0; i < row_info->width; i++)
  195165. {
  195166. png_byte v[8];
  195167. int j;
  195168. png_memcpy(v, sp, pixel_bytes);
  195169. for (j = 0; j < jstop; j++)
  195170. {
  195171. png_memcpy(dp, v, pixel_bytes);
  195172. dp -= pixel_bytes;
  195173. }
  195174. sp -= pixel_bytes;
  195175. }
  195176. break;
  195177. }
  195178. }
  195179. row_info->width = final_width;
  195180. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  195181. }
  195182. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  195183. transformations = transformations; /* silence compiler warning */
  195184. #endif
  195185. }
  195186. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  195187. void /* PRIVATE */
  195188. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  195189. png_bytep prev_row, int filter)
  195190. {
  195191. png_debug(1, "in png_read_filter_row\n");
  195192. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  195193. switch (filter)
  195194. {
  195195. case PNG_FILTER_VALUE_NONE:
  195196. break;
  195197. case PNG_FILTER_VALUE_SUB:
  195198. {
  195199. png_uint_32 i;
  195200. png_uint_32 istop = row_info->rowbytes;
  195201. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195202. png_bytep rp = row + bpp;
  195203. png_bytep lp = row;
  195204. for (i = bpp; i < istop; i++)
  195205. {
  195206. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  195207. rp++;
  195208. }
  195209. break;
  195210. }
  195211. case PNG_FILTER_VALUE_UP:
  195212. {
  195213. png_uint_32 i;
  195214. png_uint_32 istop = row_info->rowbytes;
  195215. png_bytep rp = row;
  195216. png_bytep pp = prev_row;
  195217. for (i = 0; i < istop; i++)
  195218. {
  195219. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195220. rp++;
  195221. }
  195222. break;
  195223. }
  195224. case PNG_FILTER_VALUE_AVG:
  195225. {
  195226. png_uint_32 i;
  195227. png_bytep rp = row;
  195228. png_bytep pp = prev_row;
  195229. png_bytep lp = row;
  195230. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195231. png_uint_32 istop = row_info->rowbytes - bpp;
  195232. for (i = 0; i < bpp; i++)
  195233. {
  195234. *rp = (png_byte)(((int)(*rp) +
  195235. ((int)(*pp++) / 2 )) & 0xff);
  195236. rp++;
  195237. }
  195238. for (i = 0; i < istop; i++)
  195239. {
  195240. *rp = (png_byte)(((int)(*rp) +
  195241. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  195242. rp++;
  195243. }
  195244. break;
  195245. }
  195246. case PNG_FILTER_VALUE_PAETH:
  195247. {
  195248. png_uint_32 i;
  195249. png_bytep rp = row;
  195250. png_bytep pp = prev_row;
  195251. png_bytep lp = row;
  195252. png_bytep cp = prev_row;
  195253. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195254. png_uint_32 istop=row_info->rowbytes - bpp;
  195255. for (i = 0; i < bpp; i++)
  195256. {
  195257. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195258. rp++;
  195259. }
  195260. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  195261. {
  195262. int a, b, c, pa, pb, pc, p;
  195263. a = *lp++;
  195264. b = *pp++;
  195265. c = *cp++;
  195266. p = b - c;
  195267. pc = a - c;
  195268. #ifdef PNG_USE_ABS
  195269. pa = abs(p);
  195270. pb = abs(pc);
  195271. pc = abs(p + pc);
  195272. #else
  195273. pa = p < 0 ? -p : p;
  195274. pb = pc < 0 ? -pc : pc;
  195275. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  195276. #endif
  195277. /*
  195278. if (pa <= pb && pa <= pc)
  195279. p = a;
  195280. else if (pb <= pc)
  195281. p = b;
  195282. else
  195283. p = c;
  195284. */
  195285. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  195286. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  195287. rp++;
  195288. }
  195289. break;
  195290. }
  195291. default:
  195292. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  195293. *row=0;
  195294. break;
  195295. }
  195296. }
  195297. void /* PRIVATE */
  195298. png_read_finish_row(png_structp png_ptr)
  195299. {
  195300. #ifdef PNG_USE_LOCAL_ARRAYS
  195301. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195302. /* start of interlace block */
  195303. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195304. /* offset to next interlace block */
  195305. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195306. /* start of interlace block in the y direction */
  195307. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195308. /* offset to next interlace block in the y direction */
  195309. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195310. #endif
  195311. png_debug(1, "in png_read_finish_row\n");
  195312. png_ptr->row_number++;
  195313. if (png_ptr->row_number < png_ptr->num_rows)
  195314. return;
  195315. if (png_ptr->interlaced)
  195316. {
  195317. png_ptr->row_number = 0;
  195318. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  195319. png_ptr->rowbytes + 1);
  195320. do
  195321. {
  195322. png_ptr->pass++;
  195323. if (png_ptr->pass >= 7)
  195324. break;
  195325. png_ptr->iwidth = (png_ptr->width +
  195326. png_pass_inc[png_ptr->pass] - 1 -
  195327. png_pass_start[png_ptr->pass]) /
  195328. png_pass_inc[png_ptr->pass];
  195329. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  195330. png_ptr->iwidth) + 1;
  195331. if (!(png_ptr->transformations & PNG_INTERLACE))
  195332. {
  195333. png_ptr->num_rows = (png_ptr->height +
  195334. png_pass_yinc[png_ptr->pass] - 1 -
  195335. png_pass_ystart[png_ptr->pass]) /
  195336. png_pass_yinc[png_ptr->pass];
  195337. if (!(png_ptr->num_rows))
  195338. continue;
  195339. }
  195340. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  195341. break;
  195342. } while (png_ptr->iwidth == 0);
  195343. if (png_ptr->pass < 7)
  195344. return;
  195345. }
  195346. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  195347. {
  195348. #ifdef PNG_USE_LOCAL_ARRAYS
  195349. PNG_CONST PNG_IDAT;
  195350. #endif
  195351. char extra;
  195352. int ret;
  195353. png_ptr->zstream.next_out = (Bytef *)&extra;
  195354. png_ptr->zstream.avail_out = (uInt)1;
  195355. for(;;)
  195356. {
  195357. if (!(png_ptr->zstream.avail_in))
  195358. {
  195359. while (!png_ptr->idat_size)
  195360. {
  195361. png_byte chunk_length[4];
  195362. png_crc_finish(png_ptr, 0);
  195363. png_read_data(png_ptr, chunk_length, 4);
  195364. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  195365. png_reset_crc(png_ptr);
  195366. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  195367. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  195368. png_error(png_ptr, "Not enough image data");
  195369. }
  195370. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  195371. png_ptr->zstream.next_in = png_ptr->zbuf;
  195372. if (png_ptr->zbuf_size > png_ptr->idat_size)
  195373. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  195374. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  195375. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  195376. }
  195377. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  195378. if (ret == Z_STREAM_END)
  195379. {
  195380. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  195381. png_ptr->idat_size)
  195382. png_warning(png_ptr, "Extra compressed data");
  195383. png_ptr->mode |= PNG_AFTER_IDAT;
  195384. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  195385. break;
  195386. }
  195387. if (ret != Z_OK)
  195388. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  195389. "Decompression Error");
  195390. if (!(png_ptr->zstream.avail_out))
  195391. {
  195392. png_warning(png_ptr, "Extra compressed data.");
  195393. png_ptr->mode |= PNG_AFTER_IDAT;
  195394. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  195395. break;
  195396. }
  195397. }
  195398. png_ptr->zstream.avail_out = 0;
  195399. }
  195400. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  195401. png_warning(png_ptr, "Extra compression data");
  195402. inflateReset(&png_ptr->zstream);
  195403. png_ptr->mode |= PNG_AFTER_IDAT;
  195404. }
  195405. void /* PRIVATE */
  195406. png_read_start_row(png_structp png_ptr)
  195407. {
  195408. #ifdef PNG_USE_LOCAL_ARRAYS
  195409. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195410. /* start of interlace block */
  195411. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195412. /* offset to next interlace block */
  195413. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195414. /* start of interlace block in the y direction */
  195415. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195416. /* offset to next interlace block in the y direction */
  195417. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195418. #endif
  195419. int max_pixel_depth;
  195420. png_uint_32 row_bytes;
  195421. png_debug(1, "in png_read_start_row\n");
  195422. png_ptr->zstream.avail_in = 0;
  195423. png_init_read_transformations(png_ptr);
  195424. if (png_ptr->interlaced)
  195425. {
  195426. if (!(png_ptr->transformations & PNG_INTERLACE))
  195427. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  195428. png_pass_ystart[0]) / png_pass_yinc[0];
  195429. else
  195430. png_ptr->num_rows = png_ptr->height;
  195431. png_ptr->iwidth = (png_ptr->width +
  195432. png_pass_inc[png_ptr->pass] - 1 -
  195433. png_pass_start[png_ptr->pass]) /
  195434. png_pass_inc[png_ptr->pass];
  195435. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  195436. png_ptr->irowbytes = (png_size_t)row_bytes;
  195437. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  195438. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  195439. }
  195440. else
  195441. {
  195442. png_ptr->num_rows = png_ptr->height;
  195443. png_ptr->iwidth = png_ptr->width;
  195444. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  195445. }
  195446. max_pixel_depth = png_ptr->pixel_depth;
  195447. #if defined(PNG_READ_PACK_SUPPORTED)
  195448. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  195449. max_pixel_depth = 8;
  195450. #endif
  195451. #if defined(PNG_READ_EXPAND_SUPPORTED)
  195452. if (png_ptr->transformations & PNG_EXPAND)
  195453. {
  195454. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195455. {
  195456. if (png_ptr->num_trans)
  195457. max_pixel_depth = 32;
  195458. else
  195459. max_pixel_depth = 24;
  195460. }
  195461. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195462. {
  195463. if (max_pixel_depth < 8)
  195464. max_pixel_depth = 8;
  195465. if (png_ptr->num_trans)
  195466. max_pixel_depth *= 2;
  195467. }
  195468. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195469. {
  195470. if (png_ptr->num_trans)
  195471. {
  195472. max_pixel_depth *= 4;
  195473. max_pixel_depth /= 3;
  195474. }
  195475. }
  195476. }
  195477. #endif
  195478. #if defined(PNG_READ_FILLER_SUPPORTED)
  195479. if (png_ptr->transformations & (PNG_FILLER))
  195480. {
  195481. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195482. max_pixel_depth = 32;
  195483. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195484. {
  195485. if (max_pixel_depth <= 8)
  195486. max_pixel_depth = 16;
  195487. else
  195488. max_pixel_depth = 32;
  195489. }
  195490. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195491. {
  195492. if (max_pixel_depth <= 32)
  195493. max_pixel_depth = 32;
  195494. else
  195495. max_pixel_depth = 64;
  195496. }
  195497. }
  195498. #endif
  195499. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  195500. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  195501. {
  195502. if (
  195503. #if defined(PNG_READ_EXPAND_SUPPORTED)
  195504. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  195505. #endif
  195506. #if defined(PNG_READ_FILLER_SUPPORTED)
  195507. (png_ptr->transformations & (PNG_FILLER)) ||
  195508. #endif
  195509. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195510. {
  195511. if (max_pixel_depth <= 16)
  195512. max_pixel_depth = 32;
  195513. else
  195514. max_pixel_depth = 64;
  195515. }
  195516. else
  195517. {
  195518. if (max_pixel_depth <= 8)
  195519. {
  195520. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195521. max_pixel_depth = 32;
  195522. else
  195523. max_pixel_depth = 24;
  195524. }
  195525. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195526. max_pixel_depth = 64;
  195527. else
  195528. max_pixel_depth = 48;
  195529. }
  195530. }
  195531. #endif
  195532. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  195533. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  195534. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  195535. {
  195536. int user_pixel_depth=png_ptr->user_transform_depth*
  195537. png_ptr->user_transform_channels;
  195538. if(user_pixel_depth > max_pixel_depth)
  195539. max_pixel_depth=user_pixel_depth;
  195540. }
  195541. #endif
  195542. /* align the width on the next larger 8 pixels. Mainly used
  195543. for interlacing */
  195544. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  195545. /* calculate the maximum bytes needed, adding a byte and a pixel
  195546. for safety's sake */
  195547. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  195548. 1 + ((max_pixel_depth + 7) >> 3);
  195549. #ifdef PNG_MAX_MALLOC_64K
  195550. if (row_bytes > (png_uint_32)65536L)
  195551. png_error(png_ptr, "This image requires a row greater than 64KB");
  195552. #endif
  195553. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  195554. png_ptr->row_buf = png_ptr->big_row_buf+32;
  195555. #ifdef PNG_MAX_MALLOC_64K
  195556. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  195557. png_error(png_ptr, "This image requires a row greater than 64KB");
  195558. #endif
  195559. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  195560. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  195561. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  195562. png_ptr->rowbytes + 1));
  195563. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  195564. png_debug1(3, "width = %lu,\n", png_ptr->width);
  195565. png_debug1(3, "height = %lu,\n", png_ptr->height);
  195566. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  195567. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  195568. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  195569. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  195570. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  195571. }
  195572. #endif /* PNG_READ_SUPPORTED */
  195573. /*** End of inlined file: pngrutil.c ***/
  195574. /*** Start of inlined file: pngset.c ***/
  195575. /* pngset.c - storage of image information into info struct
  195576. *
  195577. * Last changed in libpng 1.2.21 [October 4, 2007]
  195578. * For conditions of distribution and use, see copyright notice in png.h
  195579. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195580. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195581. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195582. *
  195583. * The functions here are used during reads to store data from the file
  195584. * into the info struct, and during writes to store application data
  195585. * into the info struct for writing into the file. This abstracts the
  195586. * info struct and allows us to change the structure in the future.
  195587. */
  195588. #define PNG_INTERNAL
  195589. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  195590. #if defined(PNG_bKGD_SUPPORTED)
  195591. void PNGAPI
  195592. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  195593. {
  195594. png_debug1(1, "in %s storage function\n", "bKGD");
  195595. if (png_ptr == NULL || info_ptr == NULL)
  195596. return;
  195597. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  195598. info_ptr->valid |= PNG_INFO_bKGD;
  195599. }
  195600. #endif
  195601. #if defined(PNG_cHRM_SUPPORTED)
  195602. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195603. void PNGAPI
  195604. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  195605. double white_x, double white_y, double red_x, double red_y,
  195606. double green_x, double green_y, double blue_x, double blue_y)
  195607. {
  195608. png_debug1(1, "in %s storage function\n", "cHRM");
  195609. if (png_ptr == NULL || info_ptr == NULL)
  195610. return;
  195611. if (white_x < 0.0 || white_y < 0.0 ||
  195612. red_x < 0.0 || red_y < 0.0 ||
  195613. green_x < 0.0 || green_y < 0.0 ||
  195614. blue_x < 0.0 || blue_y < 0.0)
  195615. {
  195616. png_warning(png_ptr,
  195617. "Ignoring attempt to set negative chromaticity value");
  195618. return;
  195619. }
  195620. if (white_x > 21474.83 || white_y > 21474.83 ||
  195621. red_x > 21474.83 || red_y > 21474.83 ||
  195622. green_x > 21474.83 || green_y > 21474.83 ||
  195623. blue_x > 21474.83 || blue_y > 21474.83)
  195624. {
  195625. png_warning(png_ptr,
  195626. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  195627. return;
  195628. }
  195629. info_ptr->x_white = (float)white_x;
  195630. info_ptr->y_white = (float)white_y;
  195631. info_ptr->x_red = (float)red_x;
  195632. info_ptr->y_red = (float)red_y;
  195633. info_ptr->x_green = (float)green_x;
  195634. info_ptr->y_green = (float)green_y;
  195635. info_ptr->x_blue = (float)blue_x;
  195636. info_ptr->y_blue = (float)blue_y;
  195637. #ifdef PNG_FIXED_POINT_SUPPORTED
  195638. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  195639. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  195640. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  195641. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  195642. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  195643. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  195644. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  195645. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  195646. #endif
  195647. info_ptr->valid |= PNG_INFO_cHRM;
  195648. }
  195649. #endif
  195650. #ifdef PNG_FIXED_POINT_SUPPORTED
  195651. void PNGAPI
  195652. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  195653. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  195654. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  195655. png_fixed_point blue_x, png_fixed_point blue_y)
  195656. {
  195657. png_debug1(1, "in %s storage function\n", "cHRM");
  195658. if (png_ptr == NULL || info_ptr == NULL)
  195659. return;
  195660. if (white_x < 0 || white_y < 0 ||
  195661. red_x < 0 || red_y < 0 ||
  195662. green_x < 0 || green_y < 0 ||
  195663. blue_x < 0 || blue_y < 0)
  195664. {
  195665. png_warning(png_ptr,
  195666. "Ignoring attempt to set negative chromaticity value");
  195667. return;
  195668. }
  195669. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195670. if (white_x > (double) PNG_UINT_31_MAX ||
  195671. white_y > (double) PNG_UINT_31_MAX ||
  195672. red_x > (double) PNG_UINT_31_MAX ||
  195673. red_y > (double) PNG_UINT_31_MAX ||
  195674. green_x > (double) PNG_UINT_31_MAX ||
  195675. green_y > (double) PNG_UINT_31_MAX ||
  195676. blue_x > (double) PNG_UINT_31_MAX ||
  195677. blue_y > (double) PNG_UINT_31_MAX)
  195678. #else
  195679. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195680. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195681. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195682. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195683. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195684. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195685. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195686. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  195687. #endif
  195688. {
  195689. png_warning(png_ptr,
  195690. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  195691. return;
  195692. }
  195693. info_ptr->int_x_white = white_x;
  195694. info_ptr->int_y_white = white_y;
  195695. info_ptr->int_x_red = red_x;
  195696. info_ptr->int_y_red = red_y;
  195697. info_ptr->int_x_green = green_x;
  195698. info_ptr->int_y_green = green_y;
  195699. info_ptr->int_x_blue = blue_x;
  195700. info_ptr->int_y_blue = blue_y;
  195701. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195702. info_ptr->x_white = (float)(white_x/100000.);
  195703. info_ptr->y_white = (float)(white_y/100000.);
  195704. info_ptr->x_red = (float)( red_x/100000.);
  195705. info_ptr->y_red = (float)( red_y/100000.);
  195706. info_ptr->x_green = (float)(green_x/100000.);
  195707. info_ptr->y_green = (float)(green_y/100000.);
  195708. info_ptr->x_blue = (float)( blue_x/100000.);
  195709. info_ptr->y_blue = (float)( blue_y/100000.);
  195710. #endif
  195711. info_ptr->valid |= PNG_INFO_cHRM;
  195712. }
  195713. #endif
  195714. #endif
  195715. #if defined(PNG_gAMA_SUPPORTED)
  195716. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195717. void PNGAPI
  195718. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  195719. {
  195720. double gamma;
  195721. png_debug1(1, "in %s storage function\n", "gAMA");
  195722. if (png_ptr == NULL || info_ptr == NULL)
  195723. return;
  195724. /* Check for overflow */
  195725. if (file_gamma > 21474.83)
  195726. {
  195727. png_warning(png_ptr, "Limiting gamma to 21474.83");
  195728. gamma=21474.83;
  195729. }
  195730. else
  195731. gamma=file_gamma;
  195732. info_ptr->gamma = (float)gamma;
  195733. #ifdef PNG_FIXED_POINT_SUPPORTED
  195734. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  195735. #endif
  195736. info_ptr->valid |= PNG_INFO_gAMA;
  195737. if(gamma == 0.0)
  195738. png_warning(png_ptr, "Setting gamma=0");
  195739. }
  195740. #endif
  195741. void PNGAPI
  195742. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  195743. int_gamma)
  195744. {
  195745. png_fixed_point gamma;
  195746. png_debug1(1, "in %s storage function\n", "gAMA");
  195747. if (png_ptr == NULL || info_ptr == NULL)
  195748. return;
  195749. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  195750. {
  195751. png_warning(png_ptr, "Limiting gamma to 21474.83");
  195752. gamma=PNG_UINT_31_MAX;
  195753. }
  195754. else
  195755. {
  195756. if (int_gamma < 0)
  195757. {
  195758. png_warning(png_ptr, "Setting negative gamma to zero");
  195759. gamma=0;
  195760. }
  195761. else
  195762. gamma=int_gamma;
  195763. }
  195764. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195765. info_ptr->gamma = (float)(gamma/100000.);
  195766. #endif
  195767. #ifdef PNG_FIXED_POINT_SUPPORTED
  195768. info_ptr->int_gamma = gamma;
  195769. #endif
  195770. info_ptr->valid |= PNG_INFO_gAMA;
  195771. if(gamma == 0)
  195772. png_warning(png_ptr, "Setting gamma=0");
  195773. }
  195774. #endif
  195775. #if defined(PNG_hIST_SUPPORTED)
  195776. void PNGAPI
  195777. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  195778. {
  195779. int i;
  195780. png_debug1(1, "in %s storage function\n", "hIST");
  195781. if (png_ptr == NULL || info_ptr == NULL)
  195782. return;
  195783. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  195784. > PNG_MAX_PALETTE_LENGTH)
  195785. {
  195786. png_warning(png_ptr,
  195787. "Invalid palette size, hIST allocation skipped.");
  195788. return;
  195789. }
  195790. #ifdef PNG_FREE_ME_SUPPORTED
  195791. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  195792. #endif
  195793. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  195794. 1.2.1 */
  195795. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  195796. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  195797. if (png_ptr->hist == NULL)
  195798. {
  195799. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  195800. return;
  195801. }
  195802. for (i = 0; i < info_ptr->num_palette; i++)
  195803. png_ptr->hist[i] = hist[i];
  195804. info_ptr->hist = png_ptr->hist;
  195805. info_ptr->valid |= PNG_INFO_hIST;
  195806. #ifdef PNG_FREE_ME_SUPPORTED
  195807. info_ptr->free_me |= PNG_FREE_HIST;
  195808. #else
  195809. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  195810. #endif
  195811. }
  195812. #endif
  195813. void PNGAPI
  195814. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  195815. png_uint_32 width, png_uint_32 height, int bit_depth,
  195816. int color_type, int interlace_type, int compression_type,
  195817. int filter_type)
  195818. {
  195819. png_debug1(1, "in %s storage function\n", "IHDR");
  195820. if (png_ptr == NULL || info_ptr == NULL)
  195821. return;
  195822. /* check for width and height valid values */
  195823. if (width == 0 || height == 0)
  195824. png_error(png_ptr, "Image width or height is zero in IHDR");
  195825. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  195826. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  195827. png_error(png_ptr, "image size exceeds user limits in IHDR");
  195828. #else
  195829. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  195830. png_error(png_ptr, "image size exceeds user limits in IHDR");
  195831. #endif
  195832. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  195833. png_error(png_ptr, "Invalid image size in IHDR");
  195834. if ( width > (PNG_UINT_32_MAX
  195835. >> 3) /* 8-byte RGBA pixels */
  195836. - 64 /* bigrowbuf hack */
  195837. - 1 /* filter byte */
  195838. - 7*8 /* rounding of width to multiple of 8 pixels */
  195839. - 8) /* extra max_pixel_depth pad */
  195840. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  195841. /* check other values */
  195842. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  195843. bit_depth != 8 && bit_depth != 16)
  195844. png_error(png_ptr, "Invalid bit depth in IHDR");
  195845. if (color_type < 0 || color_type == 1 ||
  195846. color_type == 5 || color_type > 6)
  195847. png_error(png_ptr, "Invalid color type in IHDR");
  195848. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  195849. ((color_type == PNG_COLOR_TYPE_RGB ||
  195850. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  195851. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  195852. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  195853. if (interlace_type >= PNG_INTERLACE_LAST)
  195854. png_error(png_ptr, "Unknown interlace method in IHDR");
  195855. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  195856. png_error(png_ptr, "Unknown compression method in IHDR");
  195857. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195858. /* Accept filter_method 64 (intrapixel differencing) only if
  195859. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  195860. * 2. Libpng did not read a PNG signature (this filter_method is only
  195861. * used in PNG datastreams that are embedded in MNG datastreams) and
  195862. * 3. The application called png_permit_mng_features with a mask that
  195863. * included PNG_FLAG_MNG_FILTER_64 and
  195864. * 4. The filter_method is 64 and
  195865. * 5. The color_type is RGB or RGBA
  195866. */
  195867. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  195868. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  195869. if(filter_type != PNG_FILTER_TYPE_BASE)
  195870. {
  195871. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195872. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  195873. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  195874. (color_type == PNG_COLOR_TYPE_RGB ||
  195875. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  195876. png_error(png_ptr, "Unknown filter method in IHDR");
  195877. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  195878. png_warning(png_ptr, "Invalid filter method in IHDR");
  195879. }
  195880. #else
  195881. if(filter_type != PNG_FILTER_TYPE_BASE)
  195882. png_error(png_ptr, "Unknown filter method in IHDR");
  195883. #endif
  195884. info_ptr->width = width;
  195885. info_ptr->height = height;
  195886. info_ptr->bit_depth = (png_byte)bit_depth;
  195887. info_ptr->color_type =(png_byte) color_type;
  195888. info_ptr->compression_type = (png_byte)compression_type;
  195889. info_ptr->filter_type = (png_byte)filter_type;
  195890. info_ptr->interlace_type = (png_byte)interlace_type;
  195891. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195892. info_ptr->channels = 1;
  195893. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195894. info_ptr->channels = 3;
  195895. else
  195896. info_ptr->channels = 1;
  195897. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  195898. info_ptr->channels++;
  195899. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  195900. /* check for potential overflow */
  195901. if (width > (PNG_UINT_32_MAX
  195902. >> 3) /* 8-byte RGBA pixels */
  195903. - 64 /* bigrowbuf hack */
  195904. - 1 /* filter byte */
  195905. - 7*8 /* rounding of width to multiple of 8 pixels */
  195906. - 8) /* extra max_pixel_depth pad */
  195907. info_ptr->rowbytes = (png_size_t)0;
  195908. else
  195909. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  195910. }
  195911. #if defined(PNG_oFFs_SUPPORTED)
  195912. void PNGAPI
  195913. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  195914. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  195915. {
  195916. png_debug1(1, "in %s storage function\n", "oFFs");
  195917. if (png_ptr == NULL || info_ptr == NULL)
  195918. return;
  195919. info_ptr->x_offset = offset_x;
  195920. info_ptr->y_offset = offset_y;
  195921. info_ptr->offset_unit_type = (png_byte)unit_type;
  195922. info_ptr->valid |= PNG_INFO_oFFs;
  195923. }
  195924. #endif
  195925. #if defined(PNG_pCAL_SUPPORTED)
  195926. void PNGAPI
  195927. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  195928. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  195929. png_charp units, png_charpp params)
  195930. {
  195931. png_uint_32 length;
  195932. int i;
  195933. png_debug1(1, "in %s storage function\n", "pCAL");
  195934. if (png_ptr == NULL || info_ptr == NULL)
  195935. return;
  195936. length = png_strlen(purpose) + 1;
  195937. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  195938. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  195939. if (info_ptr->pcal_purpose == NULL)
  195940. {
  195941. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  195942. return;
  195943. }
  195944. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  195945. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  195946. info_ptr->pcal_X0 = X0;
  195947. info_ptr->pcal_X1 = X1;
  195948. info_ptr->pcal_type = (png_byte)type;
  195949. info_ptr->pcal_nparams = (png_byte)nparams;
  195950. length = png_strlen(units) + 1;
  195951. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  195952. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  195953. if (info_ptr->pcal_units == NULL)
  195954. {
  195955. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  195956. return;
  195957. }
  195958. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  195959. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  195960. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  195961. if (info_ptr->pcal_params == NULL)
  195962. {
  195963. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  195964. return;
  195965. }
  195966. info_ptr->pcal_params[nparams] = NULL;
  195967. for (i = 0; i < nparams; i++)
  195968. {
  195969. length = png_strlen(params[i]) + 1;
  195970. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  195971. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  195972. if (info_ptr->pcal_params[i] == NULL)
  195973. {
  195974. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  195975. return;
  195976. }
  195977. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  195978. }
  195979. info_ptr->valid |= PNG_INFO_pCAL;
  195980. #ifdef PNG_FREE_ME_SUPPORTED
  195981. info_ptr->free_me |= PNG_FREE_PCAL;
  195982. #endif
  195983. }
  195984. #endif
  195985. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  195986. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195987. void PNGAPI
  195988. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  195989. int unit, double width, double height)
  195990. {
  195991. png_debug1(1, "in %s storage function\n", "sCAL");
  195992. if (png_ptr == NULL || info_ptr == NULL)
  195993. return;
  195994. info_ptr->scal_unit = (png_byte)unit;
  195995. info_ptr->scal_pixel_width = width;
  195996. info_ptr->scal_pixel_height = height;
  195997. info_ptr->valid |= PNG_INFO_sCAL;
  195998. }
  195999. #else
  196000. #ifdef PNG_FIXED_POINT_SUPPORTED
  196001. void PNGAPI
  196002. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196003. int unit, png_charp swidth, png_charp sheight)
  196004. {
  196005. png_uint_32 length;
  196006. png_debug1(1, "in %s storage function\n", "sCAL");
  196007. if (png_ptr == NULL || info_ptr == NULL)
  196008. return;
  196009. info_ptr->scal_unit = (png_byte)unit;
  196010. length = png_strlen(swidth) + 1;
  196011. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196012. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196013. if (info_ptr->scal_s_width == NULL)
  196014. {
  196015. png_warning(png_ptr,
  196016. "Memory allocation failed while processing sCAL.");
  196017. }
  196018. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196019. length = png_strlen(sheight) + 1;
  196020. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196021. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196022. if (info_ptr->scal_s_height == NULL)
  196023. {
  196024. png_free (png_ptr, info_ptr->scal_s_width);
  196025. png_warning(png_ptr,
  196026. "Memory allocation failed while processing sCAL.");
  196027. }
  196028. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196029. info_ptr->valid |= PNG_INFO_sCAL;
  196030. #ifdef PNG_FREE_ME_SUPPORTED
  196031. info_ptr->free_me |= PNG_FREE_SCAL;
  196032. #endif
  196033. }
  196034. #endif
  196035. #endif
  196036. #endif
  196037. #if defined(PNG_pHYs_SUPPORTED)
  196038. void PNGAPI
  196039. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196040. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196041. {
  196042. png_debug1(1, "in %s storage function\n", "pHYs");
  196043. if (png_ptr == NULL || info_ptr == NULL)
  196044. return;
  196045. info_ptr->x_pixels_per_unit = res_x;
  196046. info_ptr->y_pixels_per_unit = res_y;
  196047. info_ptr->phys_unit_type = (png_byte)unit_type;
  196048. info_ptr->valid |= PNG_INFO_pHYs;
  196049. }
  196050. #endif
  196051. void PNGAPI
  196052. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196053. png_colorp palette, int num_palette)
  196054. {
  196055. png_debug1(1, "in %s storage function\n", "PLTE");
  196056. if (png_ptr == NULL || info_ptr == NULL)
  196057. return;
  196058. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196059. {
  196060. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196061. png_error(png_ptr, "Invalid palette length");
  196062. else
  196063. {
  196064. png_warning(png_ptr, "Invalid palette length");
  196065. return;
  196066. }
  196067. }
  196068. /*
  196069. * It may not actually be necessary to set png_ptr->palette here;
  196070. * we do it for backward compatibility with the way the png_handle_tRNS
  196071. * function used to do the allocation.
  196072. */
  196073. #ifdef PNG_FREE_ME_SUPPORTED
  196074. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196075. #endif
  196076. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196077. of num_palette entries,
  196078. in case of an invalid PNG file that has too-large sample values. */
  196079. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196080. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196081. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196082. png_sizeof(png_color));
  196083. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196084. info_ptr->palette = png_ptr->palette;
  196085. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196086. #ifdef PNG_FREE_ME_SUPPORTED
  196087. info_ptr->free_me |= PNG_FREE_PLTE;
  196088. #else
  196089. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196090. #endif
  196091. info_ptr->valid |= PNG_INFO_PLTE;
  196092. }
  196093. #if defined(PNG_sBIT_SUPPORTED)
  196094. void PNGAPI
  196095. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196096. png_color_8p sig_bit)
  196097. {
  196098. png_debug1(1, "in %s storage function\n", "sBIT");
  196099. if (png_ptr == NULL || info_ptr == NULL)
  196100. return;
  196101. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196102. info_ptr->valid |= PNG_INFO_sBIT;
  196103. }
  196104. #endif
  196105. #if defined(PNG_sRGB_SUPPORTED)
  196106. void PNGAPI
  196107. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196108. {
  196109. png_debug1(1, "in %s storage function\n", "sRGB");
  196110. if (png_ptr == NULL || info_ptr == NULL)
  196111. return;
  196112. info_ptr->srgb_intent = (png_byte)intent;
  196113. info_ptr->valid |= PNG_INFO_sRGB;
  196114. }
  196115. void PNGAPI
  196116. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196117. int intent)
  196118. {
  196119. #if defined(PNG_gAMA_SUPPORTED)
  196120. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196121. float file_gamma;
  196122. #endif
  196123. #ifdef PNG_FIXED_POINT_SUPPORTED
  196124. png_fixed_point int_file_gamma;
  196125. #endif
  196126. #endif
  196127. #if defined(PNG_cHRM_SUPPORTED)
  196128. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196129. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  196130. #endif
  196131. #ifdef PNG_FIXED_POINT_SUPPORTED
  196132. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  196133. int_green_y, int_blue_x, int_blue_y;
  196134. #endif
  196135. #endif
  196136. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  196137. if (png_ptr == NULL || info_ptr == NULL)
  196138. return;
  196139. png_set_sRGB(png_ptr, info_ptr, intent);
  196140. #if defined(PNG_gAMA_SUPPORTED)
  196141. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196142. file_gamma = (float).45455;
  196143. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  196144. #endif
  196145. #ifdef PNG_FIXED_POINT_SUPPORTED
  196146. int_file_gamma = 45455L;
  196147. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  196148. #endif
  196149. #endif
  196150. #if defined(PNG_cHRM_SUPPORTED)
  196151. #ifdef PNG_FIXED_POINT_SUPPORTED
  196152. int_white_x = 31270L;
  196153. int_white_y = 32900L;
  196154. int_red_x = 64000L;
  196155. int_red_y = 33000L;
  196156. int_green_x = 30000L;
  196157. int_green_y = 60000L;
  196158. int_blue_x = 15000L;
  196159. int_blue_y = 6000L;
  196160. png_set_cHRM_fixed(png_ptr, info_ptr,
  196161. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  196162. int_blue_x, int_blue_y);
  196163. #endif
  196164. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196165. white_x = (float).3127;
  196166. white_y = (float).3290;
  196167. red_x = (float).64;
  196168. red_y = (float).33;
  196169. green_x = (float).30;
  196170. green_y = (float).60;
  196171. blue_x = (float).15;
  196172. blue_y = (float).06;
  196173. png_set_cHRM(png_ptr, info_ptr,
  196174. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  196175. #endif
  196176. #endif
  196177. }
  196178. #endif
  196179. #if defined(PNG_iCCP_SUPPORTED)
  196180. void PNGAPI
  196181. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  196182. png_charp name, int compression_type,
  196183. png_charp profile, png_uint_32 proflen)
  196184. {
  196185. png_charp new_iccp_name;
  196186. png_charp new_iccp_profile;
  196187. png_debug1(1, "in %s storage function\n", "iCCP");
  196188. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  196189. return;
  196190. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  196191. if (new_iccp_name == NULL)
  196192. {
  196193. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  196194. return;
  196195. }
  196196. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  196197. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  196198. if (new_iccp_profile == NULL)
  196199. {
  196200. png_free (png_ptr, new_iccp_name);
  196201. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  196202. return;
  196203. }
  196204. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  196205. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  196206. info_ptr->iccp_proflen = proflen;
  196207. info_ptr->iccp_name = new_iccp_name;
  196208. info_ptr->iccp_profile = new_iccp_profile;
  196209. /* Compression is always zero but is here so the API and info structure
  196210. * does not have to change if we introduce multiple compression types */
  196211. info_ptr->iccp_compression = (png_byte)compression_type;
  196212. #ifdef PNG_FREE_ME_SUPPORTED
  196213. info_ptr->free_me |= PNG_FREE_ICCP;
  196214. #endif
  196215. info_ptr->valid |= PNG_INFO_iCCP;
  196216. }
  196217. #endif
  196218. #if defined(PNG_TEXT_SUPPORTED)
  196219. void PNGAPI
  196220. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196221. int num_text)
  196222. {
  196223. int ret;
  196224. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  196225. if (ret)
  196226. png_error(png_ptr, "Insufficient memory to store text");
  196227. }
  196228. int /* PRIVATE */
  196229. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196230. int num_text)
  196231. {
  196232. int i;
  196233. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  196234. "text" : (png_const_charp)png_ptr->chunk_name));
  196235. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  196236. return(0);
  196237. /* Make sure we have enough space in the "text" array in info_struct
  196238. * to hold all of the incoming text_ptr objects.
  196239. */
  196240. if (info_ptr->num_text + num_text > info_ptr->max_text)
  196241. {
  196242. if (info_ptr->text != NULL)
  196243. {
  196244. png_textp old_text;
  196245. int old_max;
  196246. old_max = info_ptr->max_text;
  196247. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  196248. old_text = info_ptr->text;
  196249. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196250. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196251. if (info_ptr->text == NULL)
  196252. {
  196253. png_free(png_ptr, old_text);
  196254. return(1);
  196255. }
  196256. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  196257. png_sizeof(png_text)));
  196258. png_free(png_ptr, old_text);
  196259. }
  196260. else
  196261. {
  196262. info_ptr->max_text = num_text + 8;
  196263. info_ptr->num_text = 0;
  196264. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196265. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196266. if (info_ptr->text == NULL)
  196267. return(1);
  196268. #ifdef PNG_FREE_ME_SUPPORTED
  196269. info_ptr->free_me |= PNG_FREE_TEXT;
  196270. #endif
  196271. }
  196272. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  196273. info_ptr->max_text);
  196274. }
  196275. for (i = 0; i < num_text; i++)
  196276. {
  196277. png_size_t text_length,key_len;
  196278. png_size_t lang_len,lang_key_len;
  196279. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  196280. if (text_ptr[i].key == NULL)
  196281. continue;
  196282. key_len = png_strlen(text_ptr[i].key);
  196283. if(text_ptr[i].compression <= 0)
  196284. {
  196285. lang_len = 0;
  196286. lang_key_len = 0;
  196287. }
  196288. else
  196289. #ifdef PNG_iTXt_SUPPORTED
  196290. {
  196291. /* set iTXt data */
  196292. if (text_ptr[i].lang != NULL)
  196293. lang_len = png_strlen(text_ptr[i].lang);
  196294. else
  196295. lang_len = 0;
  196296. if (text_ptr[i].lang_key != NULL)
  196297. lang_key_len = png_strlen(text_ptr[i].lang_key);
  196298. else
  196299. lang_key_len = 0;
  196300. }
  196301. #else
  196302. {
  196303. png_warning(png_ptr, "iTXt chunk not supported.");
  196304. continue;
  196305. }
  196306. #endif
  196307. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  196308. {
  196309. text_length = 0;
  196310. #ifdef PNG_iTXt_SUPPORTED
  196311. if(text_ptr[i].compression > 0)
  196312. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  196313. else
  196314. #endif
  196315. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  196316. }
  196317. else
  196318. {
  196319. text_length = png_strlen(text_ptr[i].text);
  196320. textp->compression = text_ptr[i].compression;
  196321. }
  196322. textp->key = (png_charp)png_malloc_warn(png_ptr,
  196323. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  196324. if (textp->key == NULL)
  196325. return(1);
  196326. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  196327. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  196328. (int)textp->key);
  196329. png_memcpy(textp->key, text_ptr[i].key,
  196330. (png_size_t)(key_len));
  196331. *(textp->key+key_len) = '\0';
  196332. #ifdef PNG_iTXt_SUPPORTED
  196333. if (text_ptr[i].compression > 0)
  196334. {
  196335. textp->lang=textp->key + key_len + 1;
  196336. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  196337. *(textp->lang+lang_len) = '\0';
  196338. textp->lang_key=textp->lang + lang_len + 1;
  196339. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  196340. *(textp->lang_key+lang_key_len) = '\0';
  196341. textp->text=textp->lang_key + lang_key_len + 1;
  196342. }
  196343. else
  196344. #endif
  196345. {
  196346. #ifdef PNG_iTXt_SUPPORTED
  196347. textp->lang=NULL;
  196348. textp->lang_key=NULL;
  196349. #endif
  196350. textp->text=textp->key + key_len + 1;
  196351. }
  196352. if(text_length)
  196353. png_memcpy(textp->text, text_ptr[i].text,
  196354. (png_size_t)(text_length));
  196355. *(textp->text+text_length) = '\0';
  196356. #ifdef PNG_iTXt_SUPPORTED
  196357. if(textp->compression > 0)
  196358. {
  196359. textp->text_length = 0;
  196360. textp->itxt_length = text_length;
  196361. }
  196362. else
  196363. #endif
  196364. {
  196365. textp->text_length = text_length;
  196366. #ifdef PNG_iTXt_SUPPORTED
  196367. textp->itxt_length = 0;
  196368. #endif
  196369. }
  196370. info_ptr->num_text++;
  196371. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  196372. }
  196373. return(0);
  196374. }
  196375. #endif
  196376. #if defined(PNG_tIME_SUPPORTED)
  196377. void PNGAPI
  196378. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  196379. {
  196380. png_debug1(1, "in %s storage function\n", "tIME");
  196381. if (png_ptr == NULL || info_ptr == NULL ||
  196382. (png_ptr->mode & PNG_WROTE_tIME))
  196383. return;
  196384. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  196385. info_ptr->valid |= PNG_INFO_tIME;
  196386. }
  196387. #endif
  196388. #if defined(PNG_tRNS_SUPPORTED)
  196389. void PNGAPI
  196390. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  196391. png_bytep trans, int num_trans, png_color_16p trans_values)
  196392. {
  196393. png_debug1(1, "in %s storage function\n", "tRNS");
  196394. if (png_ptr == NULL || info_ptr == NULL)
  196395. return;
  196396. if (trans != NULL)
  196397. {
  196398. /*
  196399. * It may not actually be necessary to set png_ptr->trans here;
  196400. * we do it for backward compatibility with the way the png_handle_tRNS
  196401. * function used to do the allocation.
  196402. */
  196403. #ifdef PNG_FREE_ME_SUPPORTED
  196404. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  196405. #endif
  196406. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  196407. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  196408. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  196409. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  196410. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  196411. #ifdef PNG_FREE_ME_SUPPORTED
  196412. info_ptr->free_me |= PNG_FREE_TRNS;
  196413. #else
  196414. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  196415. #endif
  196416. }
  196417. if (trans_values != NULL)
  196418. {
  196419. png_memcpy(&(info_ptr->trans_values), trans_values,
  196420. png_sizeof(png_color_16));
  196421. if (num_trans == 0)
  196422. num_trans = 1;
  196423. }
  196424. info_ptr->num_trans = (png_uint_16)num_trans;
  196425. info_ptr->valid |= PNG_INFO_tRNS;
  196426. }
  196427. #endif
  196428. #if defined(PNG_sPLT_SUPPORTED)
  196429. void PNGAPI
  196430. png_set_sPLT(png_structp png_ptr,
  196431. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  196432. {
  196433. png_sPLT_tp np;
  196434. int i;
  196435. if (png_ptr == NULL || info_ptr == NULL)
  196436. return;
  196437. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  196438. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  196439. if (np == NULL)
  196440. {
  196441. png_warning(png_ptr, "No memory for sPLT palettes.");
  196442. return;
  196443. }
  196444. png_memcpy(np, info_ptr->splt_palettes,
  196445. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  196446. png_free(png_ptr, info_ptr->splt_palettes);
  196447. info_ptr->splt_palettes=NULL;
  196448. for (i = 0; i < nentries; i++)
  196449. {
  196450. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  196451. png_sPLT_tp from = entries + i;
  196452. to->name = (png_charp)png_malloc_warn(png_ptr,
  196453. png_strlen(from->name) + 1);
  196454. if (to->name == NULL)
  196455. {
  196456. png_warning(png_ptr,
  196457. "Out of memory while processing sPLT chunk");
  196458. }
  196459. /* TODO: use png_malloc_warn */
  196460. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  196461. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  196462. from->nentries * png_sizeof(png_sPLT_entry));
  196463. /* TODO: use png_malloc_warn */
  196464. png_memcpy(to->entries, from->entries,
  196465. from->nentries * png_sizeof(png_sPLT_entry));
  196466. if (to->entries == NULL)
  196467. {
  196468. png_warning(png_ptr,
  196469. "Out of memory while processing sPLT chunk");
  196470. png_free(png_ptr,to->name);
  196471. to->name = NULL;
  196472. }
  196473. to->nentries = from->nentries;
  196474. to->depth = from->depth;
  196475. }
  196476. info_ptr->splt_palettes = np;
  196477. info_ptr->splt_palettes_num += nentries;
  196478. info_ptr->valid |= PNG_INFO_sPLT;
  196479. #ifdef PNG_FREE_ME_SUPPORTED
  196480. info_ptr->free_me |= PNG_FREE_SPLT;
  196481. #endif
  196482. }
  196483. #endif /* PNG_sPLT_SUPPORTED */
  196484. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196485. void PNGAPI
  196486. png_set_unknown_chunks(png_structp png_ptr,
  196487. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  196488. {
  196489. png_unknown_chunkp np;
  196490. int i;
  196491. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  196492. return;
  196493. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  196494. (info_ptr->unknown_chunks_num + num_unknowns) *
  196495. png_sizeof(png_unknown_chunk));
  196496. if (np == NULL)
  196497. {
  196498. png_warning(png_ptr,
  196499. "Out of memory while processing unknown chunk.");
  196500. return;
  196501. }
  196502. png_memcpy(np, info_ptr->unknown_chunks,
  196503. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  196504. png_free(png_ptr, info_ptr->unknown_chunks);
  196505. info_ptr->unknown_chunks=NULL;
  196506. for (i = 0; i < num_unknowns; i++)
  196507. {
  196508. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  196509. png_unknown_chunkp from = unknowns + i;
  196510. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  196511. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  196512. if (to->data == NULL)
  196513. {
  196514. png_warning(png_ptr,
  196515. "Out of memory while processing unknown chunk.");
  196516. }
  196517. else
  196518. {
  196519. png_memcpy(to->data, from->data, from->size);
  196520. to->size = from->size;
  196521. /* note our location in the read or write sequence */
  196522. to->location = (png_byte)(png_ptr->mode & 0xff);
  196523. }
  196524. }
  196525. info_ptr->unknown_chunks = np;
  196526. info_ptr->unknown_chunks_num += num_unknowns;
  196527. #ifdef PNG_FREE_ME_SUPPORTED
  196528. info_ptr->free_me |= PNG_FREE_UNKN;
  196529. #endif
  196530. }
  196531. void PNGAPI
  196532. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  196533. int chunk, int location)
  196534. {
  196535. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  196536. (int)info_ptr->unknown_chunks_num)
  196537. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  196538. }
  196539. #endif
  196540. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  196541. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  196542. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  196543. void PNGAPI
  196544. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  196545. {
  196546. /* This function is deprecated in favor of png_permit_mng_features()
  196547. and will be removed from libpng-1.3.0 */
  196548. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  196549. if (png_ptr == NULL)
  196550. return;
  196551. png_ptr->mng_features_permitted = (png_byte)
  196552. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  196553. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  196554. }
  196555. #endif
  196556. #endif
  196557. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196558. png_uint_32 PNGAPI
  196559. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  196560. {
  196561. png_debug(1, "in png_permit_mng_features\n");
  196562. if (png_ptr == NULL)
  196563. return (png_uint_32)0;
  196564. png_ptr->mng_features_permitted =
  196565. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  196566. return (png_uint_32)png_ptr->mng_features_permitted;
  196567. }
  196568. #endif
  196569. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196570. void PNGAPI
  196571. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  196572. chunk_list, int num_chunks)
  196573. {
  196574. png_bytep new_list, p;
  196575. int i, old_num_chunks;
  196576. if (png_ptr == NULL)
  196577. return;
  196578. if (num_chunks == 0)
  196579. {
  196580. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  196581. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  196582. else
  196583. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  196584. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  196585. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  196586. else
  196587. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  196588. return;
  196589. }
  196590. if (chunk_list == NULL)
  196591. return;
  196592. old_num_chunks=png_ptr->num_chunk_list;
  196593. new_list=(png_bytep)png_malloc(png_ptr,
  196594. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  196595. if(png_ptr->chunk_list != NULL)
  196596. {
  196597. png_memcpy(new_list, png_ptr->chunk_list,
  196598. (png_size_t)(5*old_num_chunks));
  196599. png_free(png_ptr, png_ptr->chunk_list);
  196600. png_ptr->chunk_list=NULL;
  196601. }
  196602. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  196603. (png_size_t)(5*num_chunks));
  196604. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  196605. *p=(png_byte)keep;
  196606. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  196607. png_ptr->chunk_list=new_list;
  196608. #ifdef PNG_FREE_ME_SUPPORTED
  196609. png_ptr->free_me |= PNG_FREE_LIST;
  196610. #endif
  196611. }
  196612. #endif
  196613. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196614. void PNGAPI
  196615. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  196616. png_user_chunk_ptr read_user_chunk_fn)
  196617. {
  196618. png_debug(1, "in png_set_read_user_chunk_fn\n");
  196619. if (png_ptr == NULL)
  196620. return;
  196621. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  196622. png_ptr->user_chunk_ptr = user_chunk_ptr;
  196623. }
  196624. #endif
  196625. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  196626. void PNGAPI
  196627. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  196628. {
  196629. png_debug1(1, "in %s storage function\n", "rows");
  196630. if (png_ptr == NULL || info_ptr == NULL)
  196631. return;
  196632. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  196633. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  196634. info_ptr->row_pointers = row_pointers;
  196635. if(row_pointers)
  196636. info_ptr->valid |= PNG_INFO_IDAT;
  196637. }
  196638. #endif
  196639. #ifdef PNG_WRITE_SUPPORTED
  196640. void PNGAPI
  196641. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  196642. {
  196643. if (png_ptr == NULL)
  196644. return;
  196645. if(png_ptr->zbuf)
  196646. png_free(png_ptr, png_ptr->zbuf);
  196647. png_ptr->zbuf_size = (png_size_t)size;
  196648. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  196649. png_ptr->zstream.next_out = png_ptr->zbuf;
  196650. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196651. }
  196652. #endif
  196653. void PNGAPI
  196654. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  196655. {
  196656. if (png_ptr && info_ptr)
  196657. info_ptr->valid &= ~(mask);
  196658. }
  196659. #ifndef PNG_1_0_X
  196660. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  196661. /* function was added to libpng 1.2.0 and should always exist by default */
  196662. void PNGAPI
  196663. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  196664. {
  196665. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  196666. if (png_ptr != NULL)
  196667. png_ptr->asm_flags = 0;
  196668. }
  196669. /* this function was added to libpng 1.2.0 */
  196670. void PNGAPI
  196671. png_set_mmx_thresholds (png_structp png_ptr,
  196672. png_byte,
  196673. png_uint_32)
  196674. {
  196675. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  196676. if (png_ptr == NULL)
  196677. return;
  196678. }
  196679. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  196680. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196681. /* this function was added to libpng 1.2.6 */
  196682. void PNGAPI
  196683. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  196684. png_uint_32 user_height_max)
  196685. {
  196686. /* Images with dimensions larger than these limits will be
  196687. * rejected by png_set_IHDR(). To accept any PNG datastream
  196688. * regardless of dimensions, set both limits to 0x7ffffffL.
  196689. */
  196690. if(png_ptr == NULL) return;
  196691. png_ptr->user_width_max = user_width_max;
  196692. png_ptr->user_height_max = user_height_max;
  196693. }
  196694. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  196695. #endif /* ?PNG_1_0_X */
  196696. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  196697. /*** End of inlined file: pngset.c ***/
  196698. /*** Start of inlined file: pngtrans.c ***/
  196699. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  196700. *
  196701. * Last changed in libpng 1.2.17 May 15, 2007
  196702. * For conditions of distribution and use, see copyright notice in png.h
  196703. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196704. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196705. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196706. */
  196707. #define PNG_INTERNAL
  196708. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196709. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  196710. /* turn on BGR-to-RGB mapping */
  196711. void PNGAPI
  196712. png_set_bgr(png_structp png_ptr)
  196713. {
  196714. png_debug(1, "in png_set_bgr\n");
  196715. if(png_ptr == NULL) return;
  196716. png_ptr->transformations |= PNG_BGR;
  196717. }
  196718. #endif
  196719. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  196720. /* turn on 16 bit byte swapping */
  196721. void PNGAPI
  196722. png_set_swap(png_structp png_ptr)
  196723. {
  196724. png_debug(1, "in png_set_swap\n");
  196725. if(png_ptr == NULL) return;
  196726. if (png_ptr->bit_depth == 16)
  196727. png_ptr->transformations |= PNG_SWAP_BYTES;
  196728. }
  196729. #endif
  196730. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  196731. /* turn on pixel packing */
  196732. void PNGAPI
  196733. png_set_packing(png_structp png_ptr)
  196734. {
  196735. png_debug(1, "in png_set_packing\n");
  196736. if(png_ptr == NULL) return;
  196737. if (png_ptr->bit_depth < 8)
  196738. {
  196739. png_ptr->transformations |= PNG_PACK;
  196740. png_ptr->usr_bit_depth = 8;
  196741. }
  196742. }
  196743. #endif
  196744. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  196745. /* turn on packed pixel swapping */
  196746. void PNGAPI
  196747. png_set_packswap(png_structp png_ptr)
  196748. {
  196749. png_debug(1, "in png_set_packswap\n");
  196750. if(png_ptr == NULL) return;
  196751. if (png_ptr->bit_depth < 8)
  196752. png_ptr->transformations |= PNG_PACKSWAP;
  196753. }
  196754. #endif
  196755. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  196756. void PNGAPI
  196757. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  196758. {
  196759. png_debug(1, "in png_set_shift\n");
  196760. if(png_ptr == NULL) return;
  196761. png_ptr->transformations |= PNG_SHIFT;
  196762. png_ptr->shift = *true_bits;
  196763. }
  196764. #endif
  196765. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  196766. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196767. int PNGAPI
  196768. png_set_interlace_handling(png_structp png_ptr)
  196769. {
  196770. png_debug(1, "in png_set_interlace handling\n");
  196771. if (png_ptr && png_ptr->interlaced)
  196772. {
  196773. png_ptr->transformations |= PNG_INTERLACE;
  196774. return (7);
  196775. }
  196776. return (1);
  196777. }
  196778. #endif
  196779. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  196780. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  196781. * The filler type has changed in v0.95 to allow future 2-byte fillers
  196782. * for 48-bit input data, as well as to avoid problems with some compilers
  196783. * that don't like bytes as parameters.
  196784. */
  196785. void PNGAPI
  196786. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  196787. {
  196788. png_debug(1, "in png_set_filler\n");
  196789. if(png_ptr == NULL) return;
  196790. png_ptr->transformations |= PNG_FILLER;
  196791. png_ptr->filler = (png_byte)filler;
  196792. if (filler_loc == PNG_FILLER_AFTER)
  196793. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  196794. else
  196795. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  196796. /* This should probably go in the "do_read_filler" routine.
  196797. * I attempted to do that in libpng-1.0.1a but that caused problems
  196798. * so I restored it in libpng-1.0.2a
  196799. */
  196800. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196801. {
  196802. png_ptr->usr_channels = 4;
  196803. }
  196804. /* Also I added this in libpng-1.0.2a (what happens when we expand
  196805. * a less-than-8-bit grayscale to GA? */
  196806. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  196807. {
  196808. png_ptr->usr_channels = 2;
  196809. }
  196810. }
  196811. #if !defined(PNG_1_0_X)
  196812. /* Added to libpng-1.2.7 */
  196813. void PNGAPI
  196814. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  196815. {
  196816. png_debug(1, "in png_set_add_alpha\n");
  196817. if(png_ptr == NULL) return;
  196818. png_set_filler(png_ptr, filler, filler_loc);
  196819. png_ptr->transformations |= PNG_ADD_ALPHA;
  196820. }
  196821. #endif
  196822. #endif
  196823. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  196824. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  196825. void PNGAPI
  196826. png_set_swap_alpha(png_structp png_ptr)
  196827. {
  196828. png_debug(1, "in png_set_swap_alpha\n");
  196829. if(png_ptr == NULL) return;
  196830. png_ptr->transformations |= PNG_SWAP_ALPHA;
  196831. }
  196832. #endif
  196833. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  196834. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196835. void PNGAPI
  196836. png_set_invert_alpha(png_structp png_ptr)
  196837. {
  196838. png_debug(1, "in png_set_invert_alpha\n");
  196839. if(png_ptr == NULL) return;
  196840. png_ptr->transformations |= PNG_INVERT_ALPHA;
  196841. }
  196842. #endif
  196843. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  196844. void PNGAPI
  196845. png_set_invert_mono(png_structp png_ptr)
  196846. {
  196847. png_debug(1, "in png_set_invert_mono\n");
  196848. if(png_ptr == NULL) return;
  196849. png_ptr->transformations |= PNG_INVERT_MONO;
  196850. }
  196851. /* invert monochrome grayscale data */
  196852. void /* PRIVATE */
  196853. png_do_invert(png_row_infop row_info, png_bytep row)
  196854. {
  196855. png_debug(1, "in png_do_invert\n");
  196856. /* This test removed from libpng version 1.0.13 and 1.2.0:
  196857. * if (row_info->bit_depth == 1 &&
  196858. */
  196859. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196860. if (row == NULL || row_info == NULL)
  196861. return;
  196862. #endif
  196863. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  196864. {
  196865. png_bytep rp = row;
  196866. png_uint_32 i;
  196867. png_uint_32 istop = row_info->rowbytes;
  196868. for (i = 0; i < istop; i++)
  196869. {
  196870. *rp = (png_byte)(~(*rp));
  196871. rp++;
  196872. }
  196873. }
  196874. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  196875. row_info->bit_depth == 8)
  196876. {
  196877. png_bytep rp = row;
  196878. png_uint_32 i;
  196879. png_uint_32 istop = row_info->rowbytes;
  196880. for (i = 0; i < istop; i+=2)
  196881. {
  196882. *rp = (png_byte)(~(*rp));
  196883. rp+=2;
  196884. }
  196885. }
  196886. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  196887. row_info->bit_depth == 16)
  196888. {
  196889. png_bytep rp = row;
  196890. png_uint_32 i;
  196891. png_uint_32 istop = row_info->rowbytes;
  196892. for (i = 0; i < istop; i+=4)
  196893. {
  196894. *rp = (png_byte)(~(*rp));
  196895. *(rp+1) = (png_byte)(~(*(rp+1)));
  196896. rp+=4;
  196897. }
  196898. }
  196899. }
  196900. #endif
  196901. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  196902. /* swaps byte order on 16 bit depth images */
  196903. void /* PRIVATE */
  196904. png_do_swap(png_row_infop row_info, png_bytep row)
  196905. {
  196906. png_debug(1, "in png_do_swap\n");
  196907. if (
  196908. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196909. row != NULL && row_info != NULL &&
  196910. #endif
  196911. row_info->bit_depth == 16)
  196912. {
  196913. png_bytep rp = row;
  196914. png_uint_32 i;
  196915. png_uint_32 istop= row_info->width * row_info->channels;
  196916. for (i = 0; i < istop; i++, rp += 2)
  196917. {
  196918. png_byte t = *rp;
  196919. *rp = *(rp + 1);
  196920. *(rp + 1) = t;
  196921. }
  196922. }
  196923. }
  196924. #endif
  196925. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  196926. static PNG_CONST png_byte onebppswaptable[256] = {
  196927. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  196928. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  196929. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  196930. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  196931. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  196932. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  196933. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  196934. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  196935. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  196936. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  196937. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  196938. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  196939. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  196940. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  196941. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  196942. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  196943. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  196944. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  196945. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  196946. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  196947. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  196948. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  196949. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  196950. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  196951. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  196952. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  196953. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  196954. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  196955. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  196956. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  196957. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  196958. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  196959. };
  196960. static PNG_CONST png_byte twobppswaptable[256] = {
  196961. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  196962. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  196963. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  196964. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  196965. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  196966. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  196967. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  196968. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  196969. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  196970. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  196971. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  196972. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  196973. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  196974. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  196975. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  196976. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  196977. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  196978. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  196979. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  196980. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  196981. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  196982. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  196983. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  196984. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  196985. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  196986. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  196987. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  196988. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  196989. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  196990. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  196991. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  196992. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  196993. };
  196994. static PNG_CONST png_byte fourbppswaptable[256] = {
  196995. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  196996. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  196997. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  196998. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  196999. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197000. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197001. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197002. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197003. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197004. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197005. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197006. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197007. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197008. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197009. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197010. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197011. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197012. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197013. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197014. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197015. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197016. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197017. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197018. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197019. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197020. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197021. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197022. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197023. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197024. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197025. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197026. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197027. };
  197028. /* swaps pixel packing order within bytes */
  197029. void /* PRIVATE */
  197030. png_do_packswap(png_row_infop row_info, png_bytep row)
  197031. {
  197032. png_debug(1, "in png_do_packswap\n");
  197033. if (
  197034. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197035. row != NULL && row_info != NULL &&
  197036. #endif
  197037. row_info->bit_depth < 8)
  197038. {
  197039. png_bytep rp, end, table;
  197040. end = row + row_info->rowbytes;
  197041. if (row_info->bit_depth == 1)
  197042. table = (png_bytep)onebppswaptable;
  197043. else if (row_info->bit_depth == 2)
  197044. table = (png_bytep)twobppswaptable;
  197045. else if (row_info->bit_depth == 4)
  197046. table = (png_bytep)fourbppswaptable;
  197047. else
  197048. return;
  197049. for (rp = row; rp < end; rp++)
  197050. *rp = table[*rp];
  197051. }
  197052. }
  197053. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197054. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197055. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197056. /* remove filler or alpha byte(s) */
  197057. void /* PRIVATE */
  197058. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197059. {
  197060. png_debug(1, "in png_do_strip_filler\n");
  197061. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197062. if (row != NULL && row_info != NULL)
  197063. #endif
  197064. {
  197065. png_bytep sp=row;
  197066. png_bytep dp=row;
  197067. png_uint_32 row_width=row_info->width;
  197068. png_uint_32 i;
  197069. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197070. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197071. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197072. row_info->channels == 4)
  197073. {
  197074. if (row_info->bit_depth == 8)
  197075. {
  197076. /* This converts from RGBX or RGBA to RGB */
  197077. if (flags & PNG_FLAG_FILLER_AFTER)
  197078. {
  197079. dp+=3; sp+=4;
  197080. for (i = 1; i < row_width; i++)
  197081. {
  197082. *dp++ = *sp++;
  197083. *dp++ = *sp++;
  197084. *dp++ = *sp++;
  197085. sp++;
  197086. }
  197087. }
  197088. /* This converts from XRGB or ARGB to RGB */
  197089. else
  197090. {
  197091. for (i = 0; i < row_width; i++)
  197092. {
  197093. sp++;
  197094. *dp++ = *sp++;
  197095. *dp++ = *sp++;
  197096. *dp++ = *sp++;
  197097. }
  197098. }
  197099. row_info->pixel_depth = 24;
  197100. row_info->rowbytes = row_width * 3;
  197101. }
  197102. else /* if (row_info->bit_depth == 16) */
  197103. {
  197104. if (flags & PNG_FLAG_FILLER_AFTER)
  197105. {
  197106. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197107. sp += 8; dp += 6;
  197108. for (i = 1; i < row_width; i++)
  197109. {
  197110. /* This could be (although png_memcpy is probably slower):
  197111. png_memcpy(dp, sp, 6);
  197112. sp += 8;
  197113. dp += 6;
  197114. */
  197115. *dp++ = *sp++;
  197116. *dp++ = *sp++;
  197117. *dp++ = *sp++;
  197118. *dp++ = *sp++;
  197119. *dp++ = *sp++;
  197120. *dp++ = *sp++;
  197121. sp += 2;
  197122. }
  197123. }
  197124. else
  197125. {
  197126. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  197127. for (i = 0; i < row_width; i++)
  197128. {
  197129. /* This could be (although png_memcpy is probably slower):
  197130. png_memcpy(dp, sp, 6);
  197131. sp += 8;
  197132. dp += 6;
  197133. */
  197134. sp+=2;
  197135. *dp++ = *sp++;
  197136. *dp++ = *sp++;
  197137. *dp++ = *sp++;
  197138. *dp++ = *sp++;
  197139. *dp++ = *sp++;
  197140. *dp++ = *sp++;
  197141. }
  197142. }
  197143. row_info->pixel_depth = 48;
  197144. row_info->rowbytes = row_width * 6;
  197145. }
  197146. row_info->channels = 3;
  197147. }
  197148. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  197149. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197150. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197151. row_info->channels == 2)
  197152. {
  197153. if (row_info->bit_depth == 8)
  197154. {
  197155. /* This converts from GX or GA to G */
  197156. if (flags & PNG_FLAG_FILLER_AFTER)
  197157. {
  197158. for (i = 0; i < row_width; i++)
  197159. {
  197160. *dp++ = *sp++;
  197161. sp++;
  197162. }
  197163. }
  197164. /* This converts from XG or AG to G */
  197165. else
  197166. {
  197167. for (i = 0; i < row_width; i++)
  197168. {
  197169. sp++;
  197170. *dp++ = *sp++;
  197171. }
  197172. }
  197173. row_info->pixel_depth = 8;
  197174. row_info->rowbytes = row_width;
  197175. }
  197176. else /* if (row_info->bit_depth == 16) */
  197177. {
  197178. if (flags & PNG_FLAG_FILLER_AFTER)
  197179. {
  197180. /* This converts from GGXX or GGAA to GG */
  197181. sp += 4; dp += 2;
  197182. for (i = 1; i < row_width; i++)
  197183. {
  197184. *dp++ = *sp++;
  197185. *dp++ = *sp++;
  197186. sp += 2;
  197187. }
  197188. }
  197189. else
  197190. {
  197191. /* This converts from XXGG or AAGG to GG */
  197192. for (i = 0; i < row_width; i++)
  197193. {
  197194. sp += 2;
  197195. *dp++ = *sp++;
  197196. *dp++ = *sp++;
  197197. }
  197198. }
  197199. row_info->pixel_depth = 16;
  197200. row_info->rowbytes = row_width * 2;
  197201. }
  197202. row_info->channels = 1;
  197203. }
  197204. if (flags & PNG_FLAG_STRIP_ALPHA)
  197205. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  197206. }
  197207. }
  197208. #endif
  197209. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197210. /* swaps red and blue bytes within a pixel */
  197211. void /* PRIVATE */
  197212. png_do_bgr(png_row_infop row_info, png_bytep row)
  197213. {
  197214. png_debug(1, "in png_do_bgr\n");
  197215. if (
  197216. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197217. row != NULL && row_info != NULL &&
  197218. #endif
  197219. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197220. {
  197221. png_uint_32 row_width = row_info->width;
  197222. if (row_info->bit_depth == 8)
  197223. {
  197224. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197225. {
  197226. png_bytep rp;
  197227. png_uint_32 i;
  197228. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  197229. {
  197230. png_byte save = *rp;
  197231. *rp = *(rp + 2);
  197232. *(rp + 2) = save;
  197233. }
  197234. }
  197235. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197236. {
  197237. png_bytep rp;
  197238. png_uint_32 i;
  197239. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  197240. {
  197241. png_byte save = *rp;
  197242. *rp = *(rp + 2);
  197243. *(rp + 2) = save;
  197244. }
  197245. }
  197246. }
  197247. else if (row_info->bit_depth == 16)
  197248. {
  197249. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197250. {
  197251. png_bytep rp;
  197252. png_uint_32 i;
  197253. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  197254. {
  197255. png_byte save = *rp;
  197256. *rp = *(rp + 4);
  197257. *(rp + 4) = save;
  197258. save = *(rp + 1);
  197259. *(rp + 1) = *(rp + 5);
  197260. *(rp + 5) = save;
  197261. }
  197262. }
  197263. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197264. {
  197265. png_bytep rp;
  197266. png_uint_32 i;
  197267. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  197268. {
  197269. png_byte save = *rp;
  197270. *rp = *(rp + 4);
  197271. *(rp + 4) = save;
  197272. save = *(rp + 1);
  197273. *(rp + 1) = *(rp + 5);
  197274. *(rp + 5) = save;
  197275. }
  197276. }
  197277. }
  197278. }
  197279. }
  197280. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  197281. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  197282. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  197283. defined(PNG_LEGACY_SUPPORTED)
  197284. void PNGAPI
  197285. png_set_user_transform_info(png_structp png_ptr, png_voidp
  197286. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  197287. {
  197288. png_debug(1, "in png_set_user_transform_info\n");
  197289. if(png_ptr == NULL) return;
  197290. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197291. png_ptr->user_transform_ptr = user_transform_ptr;
  197292. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  197293. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  197294. #else
  197295. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  197296. png_warning(png_ptr,
  197297. "This version of libpng does not support user transform info");
  197298. #endif
  197299. }
  197300. #endif
  197301. /* This function returns a pointer to the user_transform_ptr associated with
  197302. * the user transform functions. The application should free any memory
  197303. * associated with this pointer before png_write_destroy and png_read_destroy
  197304. * are called.
  197305. */
  197306. png_voidp PNGAPI
  197307. png_get_user_transform_ptr(png_structp png_ptr)
  197308. {
  197309. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197310. if (png_ptr == NULL) return (NULL);
  197311. return ((png_voidp)png_ptr->user_transform_ptr);
  197312. #else
  197313. return (NULL);
  197314. #endif
  197315. }
  197316. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197317. /*** End of inlined file: pngtrans.c ***/
  197318. /*** Start of inlined file: pngwio.c ***/
  197319. /* pngwio.c - functions for data output
  197320. *
  197321. * Last changed in libpng 1.2.13 November 13, 2006
  197322. * For conditions of distribution and use, see copyright notice in png.h
  197323. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  197324. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197325. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197326. *
  197327. * This file provides a location for all output. Users who need
  197328. * special handling are expected to write functions that have the same
  197329. * arguments as these and perform similar functions, but that possibly
  197330. * use different output methods. Note that you shouldn't change these
  197331. * functions, but rather write replacement functions and then change
  197332. * them at run time with png_set_write_fn(...).
  197333. */
  197334. #define PNG_INTERNAL
  197335. #ifdef PNG_WRITE_SUPPORTED
  197336. /* Write the data to whatever output you are using. The default routine
  197337. writes to a file pointer. Note that this routine sometimes gets called
  197338. with very small lengths, so you should implement some kind of simple
  197339. buffering if you are using unbuffered writes. This should never be asked
  197340. to write more than 64K on a 16 bit machine. */
  197341. void /* PRIVATE */
  197342. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197343. {
  197344. if (png_ptr->write_data_fn != NULL )
  197345. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  197346. else
  197347. png_error(png_ptr, "Call to NULL write function");
  197348. }
  197349. #if !defined(PNG_NO_STDIO)
  197350. /* This is the function that does the actual writing of data. If you are
  197351. not writing to a standard C stream, you should create a replacement
  197352. write_data function and use it at run time with png_set_write_fn(), rather
  197353. than changing the library. */
  197354. #ifndef USE_FAR_KEYWORD
  197355. void PNGAPI
  197356. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197357. {
  197358. png_uint_32 check;
  197359. if(png_ptr == NULL) return;
  197360. #if defined(_WIN32_WCE)
  197361. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  197362. check = 0;
  197363. #else
  197364. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  197365. #endif
  197366. if (check != length)
  197367. png_error(png_ptr, "Write Error");
  197368. }
  197369. #else
  197370. /* this is the model-independent version. Since the standard I/O library
  197371. can't handle far buffers in the medium and small models, we have to copy
  197372. the data.
  197373. */
  197374. #define NEAR_BUF_SIZE 1024
  197375. #define MIN(a,b) (a <= b ? a : b)
  197376. void PNGAPI
  197377. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197378. {
  197379. png_uint_32 check;
  197380. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  197381. png_FILE_p io_ptr;
  197382. if(png_ptr == NULL) return;
  197383. /* Check if data really is near. If so, use usual code. */
  197384. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  197385. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  197386. if ((png_bytep)near_data == data)
  197387. {
  197388. #if defined(_WIN32_WCE)
  197389. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  197390. check = 0;
  197391. #else
  197392. check = fwrite(near_data, 1, length, io_ptr);
  197393. #endif
  197394. }
  197395. else
  197396. {
  197397. png_byte buf[NEAR_BUF_SIZE];
  197398. png_size_t written, remaining, err;
  197399. check = 0;
  197400. remaining = length;
  197401. do
  197402. {
  197403. written = MIN(NEAR_BUF_SIZE, remaining);
  197404. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  197405. #if defined(_WIN32_WCE)
  197406. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  197407. err = 0;
  197408. #else
  197409. err = fwrite(buf, 1, written, io_ptr);
  197410. #endif
  197411. if (err != written)
  197412. break;
  197413. else
  197414. check += err;
  197415. data += written;
  197416. remaining -= written;
  197417. }
  197418. while (remaining != 0);
  197419. }
  197420. if (check != length)
  197421. png_error(png_ptr, "Write Error");
  197422. }
  197423. #endif
  197424. #endif
  197425. /* This function is called to output any data pending writing (normally
  197426. to disk). After png_flush is called, there should be no data pending
  197427. writing in any buffers. */
  197428. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197429. void /* PRIVATE */
  197430. png_flush(png_structp png_ptr)
  197431. {
  197432. if (png_ptr->output_flush_fn != NULL)
  197433. (*(png_ptr->output_flush_fn))(png_ptr);
  197434. }
  197435. #if !defined(PNG_NO_STDIO)
  197436. void PNGAPI
  197437. png_default_flush(png_structp png_ptr)
  197438. {
  197439. #if !defined(_WIN32_WCE)
  197440. png_FILE_p io_ptr;
  197441. #endif
  197442. if(png_ptr == NULL) return;
  197443. #if !defined(_WIN32_WCE)
  197444. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  197445. if (io_ptr != NULL)
  197446. fflush(io_ptr);
  197447. #endif
  197448. }
  197449. #endif
  197450. #endif
  197451. /* This function allows the application to supply new output functions for
  197452. libpng if standard C streams aren't being used.
  197453. This function takes as its arguments:
  197454. png_ptr - pointer to a png output data structure
  197455. io_ptr - pointer to user supplied structure containing info about
  197456. the output functions. May be NULL.
  197457. write_data_fn - pointer to a new output function that takes as its
  197458. arguments a pointer to a png_struct, a pointer to
  197459. data to be written, and a 32-bit unsigned int that is
  197460. the number of bytes to be written. The new write
  197461. function should call png_error(png_ptr, "Error msg")
  197462. to exit and output any fatal error messages.
  197463. flush_data_fn - pointer to a new flush function that takes as its
  197464. arguments a pointer to a png_struct. After a call to
  197465. the flush function, there should be no data in any buffers
  197466. or pending transmission. If the output method doesn't do
  197467. any buffering of ouput, a function prototype must still be
  197468. supplied although it doesn't have to do anything. If
  197469. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  197470. time, output_flush_fn will be ignored, although it must be
  197471. supplied for compatibility. */
  197472. void PNGAPI
  197473. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  197474. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  197475. {
  197476. if(png_ptr == NULL) return;
  197477. png_ptr->io_ptr = io_ptr;
  197478. #if !defined(PNG_NO_STDIO)
  197479. if (write_data_fn != NULL)
  197480. png_ptr->write_data_fn = write_data_fn;
  197481. else
  197482. png_ptr->write_data_fn = png_default_write_data;
  197483. #else
  197484. png_ptr->write_data_fn = write_data_fn;
  197485. #endif
  197486. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197487. #if !defined(PNG_NO_STDIO)
  197488. if (output_flush_fn != NULL)
  197489. png_ptr->output_flush_fn = output_flush_fn;
  197490. else
  197491. png_ptr->output_flush_fn = png_default_flush;
  197492. #else
  197493. png_ptr->output_flush_fn = output_flush_fn;
  197494. #endif
  197495. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  197496. /* It is an error to read while writing a png file */
  197497. if (png_ptr->read_data_fn != NULL)
  197498. {
  197499. png_ptr->read_data_fn = NULL;
  197500. png_warning(png_ptr,
  197501. "Attempted to set both read_data_fn and write_data_fn in");
  197502. png_warning(png_ptr,
  197503. "the same structure. Resetting read_data_fn to NULL.");
  197504. }
  197505. }
  197506. #if defined(USE_FAR_KEYWORD)
  197507. #if defined(_MSC_VER)
  197508. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  197509. {
  197510. void *near_ptr;
  197511. void FAR *far_ptr;
  197512. FP_OFF(near_ptr) = FP_OFF(ptr);
  197513. far_ptr = (void FAR *)near_ptr;
  197514. if(check != 0)
  197515. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  197516. png_error(png_ptr,"segment lost in conversion");
  197517. return(near_ptr);
  197518. }
  197519. # else
  197520. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  197521. {
  197522. void *near_ptr;
  197523. void FAR *far_ptr;
  197524. near_ptr = (void FAR *)ptr;
  197525. far_ptr = (void FAR *)near_ptr;
  197526. if(check != 0)
  197527. if(far_ptr != ptr)
  197528. png_error(png_ptr,"segment lost in conversion");
  197529. return(near_ptr);
  197530. }
  197531. # endif
  197532. # endif
  197533. #endif /* PNG_WRITE_SUPPORTED */
  197534. /*** End of inlined file: pngwio.c ***/
  197535. /*** Start of inlined file: pngwrite.c ***/
  197536. /* pngwrite.c - general routines to write a PNG file
  197537. *
  197538. * Last changed in libpng 1.2.15 January 5, 2007
  197539. * For conditions of distribution and use, see copyright notice in png.h
  197540. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197541. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197542. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197543. */
  197544. /* get internal access to png.h */
  197545. #define PNG_INTERNAL
  197546. #ifdef PNG_WRITE_SUPPORTED
  197547. /* Writes all the PNG information. This is the suggested way to use the
  197548. * library. If you have a new chunk to add, make a function to write it,
  197549. * and put it in the correct location here. If you want the chunk written
  197550. * after the image data, put it in png_write_end(). I strongly encourage
  197551. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  197552. * the chunk, as that will keep the code from breaking if you want to just
  197553. * write a plain PNG file. If you have long comments, I suggest writing
  197554. * them in png_write_end(), and compressing them.
  197555. */
  197556. void PNGAPI
  197557. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  197558. {
  197559. png_debug(1, "in png_write_info_before_PLTE\n");
  197560. if (png_ptr == NULL || info_ptr == NULL)
  197561. return;
  197562. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  197563. {
  197564. png_write_sig(png_ptr); /* write PNG signature */
  197565. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197566. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  197567. {
  197568. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197569. png_ptr->mng_features_permitted=0;
  197570. }
  197571. #endif
  197572. /* write IHDR information. */
  197573. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  197574. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  197575. info_ptr->filter_type,
  197576. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197577. info_ptr->interlace_type);
  197578. #else
  197579. 0);
  197580. #endif
  197581. /* the rest of these check to see if the valid field has the appropriate
  197582. flag set, and if it does, writes the chunk. */
  197583. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  197584. if (info_ptr->valid & PNG_INFO_gAMA)
  197585. {
  197586. # ifdef PNG_FLOATING_POINT_SUPPORTED
  197587. png_write_gAMA(png_ptr, info_ptr->gamma);
  197588. #else
  197589. #ifdef PNG_FIXED_POINT_SUPPORTED
  197590. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  197591. # endif
  197592. #endif
  197593. }
  197594. #endif
  197595. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  197596. if (info_ptr->valid & PNG_INFO_sRGB)
  197597. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  197598. #endif
  197599. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  197600. if (info_ptr->valid & PNG_INFO_iCCP)
  197601. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  197602. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  197603. #endif
  197604. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  197605. if (info_ptr->valid & PNG_INFO_sBIT)
  197606. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  197607. #endif
  197608. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  197609. if (info_ptr->valid & PNG_INFO_cHRM)
  197610. {
  197611. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197612. png_write_cHRM(png_ptr,
  197613. info_ptr->x_white, info_ptr->y_white,
  197614. info_ptr->x_red, info_ptr->y_red,
  197615. info_ptr->x_green, info_ptr->y_green,
  197616. info_ptr->x_blue, info_ptr->y_blue);
  197617. #else
  197618. # ifdef PNG_FIXED_POINT_SUPPORTED
  197619. png_write_cHRM_fixed(png_ptr,
  197620. info_ptr->int_x_white, info_ptr->int_y_white,
  197621. info_ptr->int_x_red, info_ptr->int_y_red,
  197622. info_ptr->int_x_green, info_ptr->int_y_green,
  197623. info_ptr->int_x_blue, info_ptr->int_y_blue);
  197624. # endif
  197625. #endif
  197626. }
  197627. #endif
  197628. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  197629. if (info_ptr->unknown_chunks_num)
  197630. {
  197631. png_unknown_chunk *up;
  197632. png_debug(5, "writing extra chunks\n");
  197633. for (up = info_ptr->unknown_chunks;
  197634. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  197635. up++)
  197636. {
  197637. int keep=png_handle_as_unknown(png_ptr, up->name);
  197638. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  197639. up->location && !(up->location & PNG_HAVE_PLTE) &&
  197640. !(up->location & PNG_HAVE_IDAT) &&
  197641. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  197642. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  197643. {
  197644. png_write_chunk(png_ptr, up->name, up->data, up->size);
  197645. }
  197646. }
  197647. }
  197648. #endif
  197649. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  197650. }
  197651. }
  197652. void PNGAPI
  197653. png_write_info(png_structp png_ptr, png_infop info_ptr)
  197654. {
  197655. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  197656. int i;
  197657. #endif
  197658. png_debug(1, "in png_write_info\n");
  197659. if (png_ptr == NULL || info_ptr == NULL)
  197660. return;
  197661. png_write_info_before_PLTE(png_ptr, info_ptr);
  197662. if (info_ptr->valid & PNG_INFO_PLTE)
  197663. png_write_PLTE(png_ptr, info_ptr->palette,
  197664. (png_uint_32)info_ptr->num_palette);
  197665. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197666. png_error(png_ptr, "Valid palette required for paletted images");
  197667. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  197668. if (info_ptr->valid & PNG_INFO_tRNS)
  197669. {
  197670. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197671. /* invert the alpha channel (in tRNS) */
  197672. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  197673. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197674. {
  197675. int j;
  197676. for (j=0; j<(int)info_ptr->num_trans; j++)
  197677. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  197678. }
  197679. #endif
  197680. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  197681. info_ptr->num_trans, info_ptr->color_type);
  197682. }
  197683. #endif
  197684. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  197685. if (info_ptr->valid & PNG_INFO_bKGD)
  197686. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  197687. #endif
  197688. #if defined(PNG_WRITE_hIST_SUPPORTED)
  197689. if (info_ptr->valid & PNG_INFO_hIST)
  197690. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  197691. #endif
  197692. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  197693. if (info_ptr->valid & PNG_INFO_oFFs)
  197694. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  197695. info_ptr->offset_unit_type);
  197696. #endif
  197697. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  197698. if (info_ptr->valid & PNG_INFO_pCAL)
  197699. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  197700. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  197701. info_ptr->pcal_units, info_ptr->pcal_params);
  197702. #endif
  197703. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  197704. if (info_ptr->valid & PNG_INFO_sCAL)
  197705. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  197706. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  197707. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  197708. #else
  197709. #ifdef PNG_FIXED_POINT_SUPPORTED
  197710. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  197711. info_ptr->scal_s_width, info_ptr->scal_s_height);
  197712. #else
  197713. png_warning(png_ptr,
  197714. "png_write_sCAL not supported; sCAL chunk not written.");
  197715. #endif
  197716. #endif
  197717. #endif
  197718. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  197719. if (info_ptr->valid & PNG_INFO_pHYs)
  197720. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  197721. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  197722. #endif
  197723. #if defined(PNG_WRITE_tIME_SUPPORTED)
  197724. if (info_ptr->valid & PNG_INFO_tIME)
  197725. {
  197726. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  197727. png_ptr->mode |= PNG_WROTE_tIME;
  197728. }
  197729. #endif
  197730. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  197731. if (info_ptr->valid & PNG_INFO_sPLT)
  197732. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  197733. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  197734. #endif
  197735. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  197736. /* Check to see if we need to write text chunks */
  197737. for (i = 0; i < info_ptr->num_text; i++)
  197738. {
  197739. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  197740. info_ptr->text[i].compression);
  197741. /* an internationalized chunk? */
  197742. if (info_ptr->text[i].compression > 0)
  197743. {
  197744. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  197745. /* write international chunk */
  197746. png_write_iTXt(png_ptr,
  197747. info_ptr->text[i].compression,
  197748. info_ptr->text[i].key,
  197749. info_ptr->text[i].lang,
  197750. info_ptr->text[i].lang_key,
  197751. info_ptr->text[i].text);
  197752. #else
  197753. png_warning(png_ptr, "Unable to write international text");
  197754. #endif
  197755. /* Mark this chunk as written */
  197756. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  197757. }
  197758. /* If we want a compressed text chunk */
  197759. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  197760. {
  197761. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  197762. /* write compressed chunk */
  197763. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  197764. info_ptr->text[i].text, 0,
  197765. info_ptr->text[i].compression);
  197766. #else
  197767. png_warning(png_ptr, "Unable to write compressed text");
  197768. #endif
  197769. /* Mark this chunk as written */
  197770. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  197771. }
  197772. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  197773. {
  197774. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  197775. /* write uncompressed chunk */
  197776. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  197777. info_ptr->text[i].text,
  197778. 0);
  197779. #else
  197780. png_warning(png_ptr, "Unable to write uncompressed text");
  197781. #endif
  197782. /* Mark this chunk as written */
  197783. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  197784. }
  197785. }
  197786. #endif
  197787. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  197788. if (info_ptr->unknown_chunks_num)
  197789. {
  197790. png_unknown_chunk *up;
  197791. png_debug(5, "writing extra chunks\n");
  197792. for (up = info_ptr->unknown_chunks;
  197793. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  197794. up++)
  197795. {
  197796. int keep=png_handle_as_unknown(png_ptr, up->name);
  197797. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  197798. up->location && (up->location & PNG_HAVE_PLTE) &&
  197799. !(up->location & PNG_HAVE_IDAT) &&
  197800. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  197801. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  197802. {
  197803. png_write_chunk(png_ptr, up->name, up->data, up->size);
  197804. }
  197805. }
  197806. }
  197807. #endif
  197808. }
  197809. /* Writes the end of the PNG file. If you don't want to write comments or
  197810. * time information, you can pass NULL for info. If you already wrote these
  197811. * in png_write_info(), do not write them again here. If you have long
  197812. * comments, I suggest writing them here, and compressing them.
  197813. */
  197814. void PNGAPI
  197815. png_write_end(png_structp png_ptr, png_infop info_ptr)
  197816. {
  197817. png_debug(1, "in png_write_end\n");
  197818. if (png_ptr == NULL)
  197819. return;
  197820. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  197821. png_error(png_ptr, "No IDATs written into file");
  197822. /* see if user wants us to write information chunks */
  197823. if (info_ptr != NULL)
  197824. {
  197825. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  197826. int i; /* local index variable */
  197827. #endif
  197828. #if defined(PNG_WRITE_tIME_SUPPORTED)
  197829. /* check to see if user has supplied a time chunk */
  197830. if ((info_ptr->valid & PNG_INFO_tIME) &&
  197831. !(png_ptr->mode & PNG_WROTE_tIME))
  197832. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  197833. #endif
  197834. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  197835. /* loop through comment chunks */
  197836. for (i = 0; i < info_ptr->num_text; i++)
  197837. {
  197838. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  197839. info_ptr->text[i].compression);
  197840. /* an internationalized chunk? */
  197841. if (info_ptr->text[i].compression > 0)
  197842. {
  197843. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  197844. /* write international chunk */
  197845. png_write_iTXt(png_ptr,
  197846. info_ptr->text[i].compression,
  197847. info_ptr->text[i].key,
  197848. info_ptr->text[i].lang,
  197849. info_ptr->text[i].lang_key,
  197850. info_ptr->text[i].text);
  197851. #else
  197852. png_warning(png_ptr, "Unable to write international text");
  197853. #endif
  197854. /* Mark this chunk as written */
  197855. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  197856. }
  197857. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  197858. {
  197859. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  197860. /* write compressed chunk */
  197861. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  197862. info_ptr->text[i].text, 0,
  197863. info_ptr->text[i].compression);
  197864. #else
  197865. png_warning(png_ptr, "Unable to write compressed text");
  197866. #endif
  197867. /* Mark this chunk as written */
  197868. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  197869. }
  197870. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  197871. {
  197872. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  197873. /* write uncompressed chunk */
  197874. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  197875. info_ptr->text[i].text, 0);
  197876. #else
  197877. png_warning(png_ptr, "Unable to write uncompressed text");
  197878. #endif
  197879. /* Mark this chunk as written */
  197880. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  197881. }
  197882. }
  197883. #endif
  197884. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  197885. if (info_ptr->unknown_chunks_num)
  197886. {
  197887. png_unknown_chunk *up;
  197888. png_debug(5, "writing extra chunks\n");
  197889. for (up = info_ptr->unknown_chunks;
  197890. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  197891. up++)
  197892. {
  197893. int keep=png_handle_as_unknown(png_ptr, up->name);
  197894. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  197895. up->location && (up->location & PNG_AFTER_IDAT) &&
  197896. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  197897. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  197898. {
  197899. png_write_chunk(png_ptr, up->name, up->data, up->size);
  197900. }
  197901. }
  197902. }
  197903. #endif
  197904. }
  197905. png_ptr->mode |= PNG_AFTER_IDAT;
  197906. /* write end of PNG file */
  197907. png_write_IEND(png_ptr);
  197908. }
  197909. #if defined(PNG_WRITE_tIME_SUPPORTED)
  197910. #if !defined(_WIN32_WCE)
  197911. /* "time.h" functions are not supported on WindowsCE */
  197912. void PNGAPI
  197913. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  197914. {
  197915. png_debug(1, "in png_convert_from_struct_tm\n");
  197916. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  197917. ptime->month = (png_byte)(ttime->tm_mon + 1);
  197918. ptime->day = (png_byte)ttime->tm_mday;
  197919. ptime->hour = (png_byte)ttime->tm_hour;
  197920. ptime->minute = (png_byte)ttime->tm_min;
  197921. ptime->second = (png_byte)ttime->tm_sec;
  197922. }
  197923. void PNGAPI
  197924. png_convert_from_time_t(png_timep ptime, time_t ttime)
  197925. {
  197926. struct tm *tbuf;
  197927. png_debug(1, "in png_convert_from_time_t\n");
  197928. tbuf = gmtime(&ttime);
  197929. png_convert_from_struct_tm(ptime, tbuf);
  197930. }
  197931. #endif
  197932. #endif
  197933. /* Initialize png_ptr structure, and allocate any memory needed */
  197934. png_structp PNGAPI
  197935. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  197936. png_error_ptr error_fn, png_error_ptr warn_fn)
  197937. {
  197938. #ifdef PNG_USER_MEM_SUPPORTED
  197939. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  197940. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  197941. }
  197942. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  197943. png_structp PNGAPI
  197944. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  197945. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  197946. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  197947. {
  197948. #endif /* PNG_USER_MEM_SUPPORTED */
  197949. png_structp png_ptr;
  197950. #ifdef PNG_SETJMP_SUPPORTED
  197951. #ifdef USE_FAR_KEYWORD
  197952. jmp_buf jmpbuf;
  197953. #endif
  197954. #endif
  197955. int i;
  197956. png_debug(1, "in png_create_write_struct\n");
  197957. #ifdef PNG_USER_MEM_SUPPORTED
  197958. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  197959. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  197960. #else
  197961. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  197962. #endif /* PNG_USER_MEM_SUPPORTED */
  197963. if (png_ptr == NULL)
  197964. return (NULL);
  197965. /* added at libpng-1.2.6 */
  197966. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197967. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  197968. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  197969. #endif
  197970. #ifdef PNG_SETJMP_SUPPORTED
  197971. #ifdef USE_FAR_KEYWORD
  197972. if (setjmp(jmpbuf))
  197973. #else
  197974. if (setjmp(png_ptr->jmpbuf))
  197975. #endif
  197976. {
  197977. png_free(png_ptr, png_ptr->zbuf);
  197978. png_ptr->zbuf=NULL;
  197979. png_destroy_struct(png_ptr);
  197980. return (NULL);
  197981. }
  197982. #ifdef USE_FAR_KEYWORD
  197983. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  197984. #endif
  197985. #endif
  197986. #ifdef PNG_USER_MEM_SUPPORTED
  197987. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  197988. #endif /* PNG_USER_MEM_SUPPORTED */
  197989. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  197990. i=0;
  197991. do
  197992. {
  197993. if(user_png_ver[i] != png_libpng_ver[i])
  197994. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  197995. } while (png_libpng_ver[i++]);
  197996. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  197997. {
  197998. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  197999. * we must recompile any applications that use any older library version.
  198000. * For versions after libpng 1.0, we will be compatible, so we need
  198001. * only check the first digit.
  198002. */
  198003. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198004. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198005. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198006. {
  198007. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198008. char msg[80];
  198009. if (user_png_ver)
  198010. {
  198011. png_snprintf(msg, 80,
  198012. "Application was compiled with png.h from libpng-%.20s",
  198013. user_png_ver);
  198014. png_warning(png_ptr, msg);
  198015. }
  198016. png_snprintf(msg, 80,
  198017. "Application is running with png.c from libpng-%.20s",
  198018. png_libpng_ver);
  198019. png_warning(png_ptr, msg);
  198020. #endif
  198021. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198022. png_ptr->flags=0;
  198023. #endif
  198024. png_error(png_ptr,
  198025. "Incompatible libpng version in application and library");
  198026. }
  198027. }
  198028. /* initialize zbuf - compression buffer */
  198029. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198030. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198031. (png_uint_32)png_ptr->zbuf_size);
  198032. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198033. png_flush_ptr_NULL);
  198034. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198035. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198036. 1, png_doublep_NULL, png_doublep_NULL);
  198037. #endif
  198038. #ifdef PNG_SETJMP_SUPPORTED
  198039. /* Applications that neglect to set up their own setjmp() and then encounter
  198040. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198041. abort instead of returning. */
  198042. #ifdef USE_FAR_KEYWORD
  198043. if (setjmp(jmpbuf))
  198044. PNG_ABORT();
  198045. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198046. #else
  198047. if (setjmp(png_ptr->jmpbuf))
  198048. PNG_ABORT();
  198049. #endif
  198050. #endif
  198051. return (png_ptr);
  198052. }
  198053. /* Initialize png_ptr structure, and allocate any memory needed */
  198054. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198055. /* Deprecated. */
  198056. #undef png_write_init
  198057. void PNGAPI
  198058. png_write_init(png_structp png_ptr)
  198059. {
  198060. /* We only come here via pre-1.0.7-compiled applications */
  198061. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198062. }
  198063. void PNGAPI
  198064. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198065. png_size_t png_struct_size, png_size_t png_info_size)
  198066. {
  198067. /* We only come here via pre-1.0.12-compiled applications */
  198068. if(png_ptr == NULL) return;
  198069. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198070. if(png_sizeof(png_struct) > png_struct_size ||
  198071. png_sizeof(png_info) > png_info_size)
  198072. {
  198073. char msg[80];
  198074. png_ptr->warning_fn=NULL;
  198075. if (user_png_ver)
  198076. {
  198077. png_snprintf(msg, 80,
  198078. "Application was compiled with png.h from libpng-%.20s",
  198079. user_png_ver);
  198080. png_warning(png_ptr, msg);
  198081. }
  198082. png_snprintf(msg, 80,
  198083. "Application is running with png.c from libpng-%.20s",
  198084. png_libpng_ver);
  198085. png_warning(png_ptr, msg);
  198086. }
  198087. #endif
  198088. if(png_sizeof(png_struct) > png_struct_size)
  198089. {
  198090. png_ptr->error_fn=NULL;
  198091. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198092. png_ptr->flags=0;
  198093. #endif
  198094. png_error(png_ptr,
  198095. "The png struct allocated by the application for writing is too small.");
  198096. }
  198097. if(png_sizeof(png_info) > png_info_size)
  198098. {
  198099. png_ptr->error_fn=NULL;
  198100. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198101. png_ptr->flags=0;
  198102. #endif
  198103. png_error(png_ptr,
  198104. "The info struct allocated by the application for writing is too small.");
  198105. }
  198106. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198107. }
  198108. #endif /* PNG_1_0_X || PNG_1_2_X */
  198109. void PNGAPI
  198110. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198111. png_size_t png_struct_size)
  198112. {
  198113. png_structp png_ptr=*ptr_ptr;
  198114. #ifdef PNG_SETJMP_SUPPORTED
  198115. jmp_buf tmp_jmp; /* to save current jump buffer */
  198116. #endif
  198117. int i = 0;
  198118. if (png_ptr == NULL)
  198119. return;
  198120. do
  198121. {
  198122. if (user_png_ver[i] != png_libpng_ver[i])
  198123. {
  198124. #ifdef PNG_LEGACY_SUPPORTED
  198125. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198126. #else
  198127. png_ptr->warning_fn=NULL;
  198128. png_warning(png_ptr,
  198129. "Application uses deprecated png_write_init() and should be recompiled.");
  198130. break;
  198131. #endif
  198132. }
  198133. } while (png_libpng_ver[i++]);
  198134. png_debug(1, "in png_write_init_3\n");
  198135. #ifdef PNG_SETJMP_SUPPORTED
  198136. /* save jump buffer and error functions */
  198137. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198138. #endif
  198139. if (png_sizeof(png_struct) > png_struct_size)
  198140. {
  198141. png_destroy_struct(png_ptr);
  198142. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198143. *ptr_ptr = png_ptr;
  198144. }
  198145. /* reset all variables to 0 */
  198146. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198147. /* added at libpng-1.2.6 */
  198148. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198149. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198150. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198151. #endif
  198152. #ifdef PNG_SETJMP_SUPPORTED
  198153. /* restore jump buffer */
  198154. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198155. #endif
  198156. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198157. png_flush_ptr_NULL);
  198158. /* initialize zbuf - compression buffer */
  198159. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198160. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198161. (png_uint_32)png_ptr->zbuf_size);
  198162. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198163. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198164. 1, png_doublep_NULL, png_doublep_NULL);
  198165. #endif
  198166. }
  198167. /* Write a few rows of image data. If the image is interlaced,
  198168. * either you will have to write the 7 sub images, or, if you
  198169. * have called png_set_interlace_handling(), you will have to
  198170. * "write" the image seven times.
  198171. */
  198172. void PNGAPI
  198173. png_write_rows(png_structp png_ptr, png_bytepp row,
  198174. png_uint_32 num_rows)
  198175. {
  198176. png_uint_32 i; /* row counter */
  198177. png_bytepp rp; /* row pointer */
  198178. png_debug(1, "in png_write_rows\n");
  198179. if (png_ptr == NULL)
  198180. return;
  198181. /* loop through the rows */
  198182. for (i = 0, rp = row; i < num_rows; i++, rp++)
  198183. {
  198184. png_write_row(png_ptr, *rp);
  198185. }
  198186. }
  198187. /* Write the image. You only need to call this function once, even
  198188. * if you are writing an interlaced image.
  198189. */
  198190. void PNGAPI
  198191. png_write_image(png_structp png_ptr, png_bytepp image)
  198192. {
  198193. png_uint_32 i; /* row index */
  198194. int pass, num_pass; /* pass variables */
  198195. png_bytepp rp; /* points to current row */
  198196. if (png_ptr == NULL)
  198197. return;
  198198. png_debug(1, "in png_write_image\n");
  198199. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198200. /* intialize interlace handling. If image is not interlaced,
  198201. this will set pass to 1 */
  198202. num_pass = png_set_interlace_handling(png_ptr);
  198203. #else
  198204. num_pass = 1;
  198205. #endif
  198206. /* loop through passes */
  198207. for (pass = 0; pass < num_pass; pass++)
  198208. {
  198209. /* loop through image */
  198210. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  198211. {
  198212. png_write_row(png_ptr, *rp);
  198213. }
  198214. }
  198215. }
  198216. /* called by user to write a row of image data */
  198217. void PNGAPI
  198218. png_write_row(png_structp png_ptr, png_bytep row)
  198219. {
  198220. if (png_ptr == NULL)
  198221. return;
  198222. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  198223. png_ptr->row_number, png_ptr->pass);
  198224. /* initialize transformations and other stuff if first time */
  198225. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  198226. {
  198227. /* make sure we wrote the header info */
  198228. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198229. png_error(png_ptr,
  198230. "png_write_info was never called before png_write_row.");
  198231. /* check for transforms that have been set but were defined out */
  198232. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  198233. if (png_ptr->transformations & PNG_INVERT_MONO)
  198234. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  198235. #endif
  198236. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  198237. if (png_ptr->transformations & PNG_FILLER)
  198238. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  198239. #endif
  198240. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  198241. if (png_ptr->transformations & PNG_PACKSWAP)
  198242. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  198243. #endif
  198244. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  198245. if (png_ptr->transformations & PNG_PACK)
  198246. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  198247. #endif
  198248. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  198249. if (png_ptr->transformations & PNG_SHIFT)
  198250. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  198251. #endif
  198252. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  198253. if (png_ptr->transformations & PNG_BGR)
  198254. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  198255. #endif
  198256. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  198257. if (png_ptr->transformations & PNG_SWAP_BYTES)
  198258. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  198259. #endif
  198260. png_write_start_row(png_ptr);
  198261. }
  198262. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198263. /* if interlaced and not interested in row, return */
  198264. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  198265. {
  198266. switch (png_ptr->pass)
  198267. {
  198268. case 0:
  198269. if (png_ptr->row_number & 0x07)
  198270. {
  198271. png_write_finish_row(png_ptr);
  198272. return;
  198273. }
  198274. break;
  198275. case 1:
  198276. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  198277. {
  198278. png_write_finish_row(png_ptr);
  198279. return;
  198280. }
  198281. break;
  198282. case 2:
  198283. if ((png_ptr->row_number & 0x07) != 4)
  198284. {
  198285. png_write_finish_row(png_ptr);
  198286. return;
  198287. }
  198288. break;
  198289. case 3:
  198290. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  198291. {
  198292. png_write_finish_row(png_ptr);
  198293. return;
  198294. }
  198295. break;
  198296. case 4:
  198297. if ((png_ptr->row_number & 0x03) != 2)
  198298. {
  198299. png_write_finish_row(png_ptr);
  198300. return;
  198301. }
  198302. break;
  198303. case 5:
  198304. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  198305. {
  198306. png_write_finish_row(png_ptr);
  198307. return;
  198308. }
  198309. break;
  198310. case 6:
  198311. if (!(png_ptr->row_number & 0x01))
  198312. {
  198313. png_write_finish_row(png_ptr);
  198314. return;
  198315. }
  198316. break;
  198317. }
  198318. }
  198319. #endif
  198320. /* set up row info for transformations */
  198321. png_ptr->row_info.color_type = png_ptr->color_type;
  198322. png_ptr->row_info.width = png_ptr->usr_width;
  198323. png_ptr->row_info.channels = png_ptr->usr_channels;
  198324. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  198325. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  198326. png_ptr->row_info.channels);
  198327. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  198328. png_ptr->row_info.width);
  198329. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  198330. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  198331. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  198332. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  198333. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  198334. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  198335. /* Copy user's row into buffer, leaving room for filter byte. */
  198336. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  198337. png_ptr->row_info.rowbytes);
  198338. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198339. /* handle interlacing */
  198340. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  198341. (png_ptr->transformations & PNG_INTERLACE))
  198342. {
  198343. png_do_write_interlace(&(png_ptr->row_info),
  198344. png_ptr->row_buf + 1, png_ptr->pass);
  198345. /* this should always get caught above, but still ... */
  198346. if (!(png_ptr->row_info.width))
  198347. {
  198348. png_write_finish_row(png_ptr);
  198349. return;
  198350. }
  198351. }
  198352. #endif
  198353. /* handle other transformations */
  198354. if (png_ptr->transformations)
  198355. png_do_write_transformations(png_ptr);
  198356. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198357. /* Write filter_method 64 (intrapixel differencing) only if
  198358. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  198359. * 2. Libpng did not write a PNG signature (this filter_method is only
  198360. * used in PNG datastreams that are embedded in MNG datastreams) and
  198361. * 3. The application called png_permit_mng_features with a mask that
  198362. * included PNG_FLAG_MNG_FILTER_64 and
  198363. * 4. The filter_method is 64 and
  198364. * 5. The color_type is RGB or RGBA
  198365. */
  198366. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198367. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  198368. {
  198369. /* Intrapixel differencing */
  198370. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198371. }
  198372. #endif
  198373. /* Find a filter if necessary, filter the row and write it out. */
  198374. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  198375. if (png_ptr->write_row_fn != NULL)
  198376. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  198377. }
  198378. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198379. /* Set the automatic flush interval or 0 to turn flushing off */
  198380. void PNGAPI
  198381. png_set_flush(png_structp png_ptr, int nrows)
  198382. {
  198383. png_debug(1, "in png_set_flush\n");
  198384. if (png_ptr == NULL)
  198385. return;
  198386. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  198387. }
  198388. /* flush the current output buffers now */
  198389. void PNGAPI
  198390. png_write_flush(png_structp png_ptr)
  198391. {
  198392. int wrote_IDAT;
  198393. png_debug(1, "in png_write_flush\n");
  198394. if (png_ptr == NULL)
  198395. return;
  198396. /* We have already written out all of the data */
  198397. if (png_ptr->row_number >= png_ptr->num_rows)
  198398. return;
  198399. do
  198400. {
  198401. int ret;
  198402. /* compress the data */
  198403. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  198404. wrote_IDAT = 0;
  198405. /* check for compression errors */
  198406. if (ret != Z_OK)
  198407. {
  198408. if (png_ptr->zstream.msg != NULL)
  198409. png_error(png_ptr, png_ptr->zstream.msg);
  198410. else
  198411. png_error(png_ptr, "zlib error");
  198412. }
  198413. if (!(png_ptr->zstream.avail_out))
  198414. {
  198415. /* write the IDAT and reset the zlib output buffer */
  198416. png_write_IDAT(png_ptr, png_ptr->zbuf,
  198417. png_ptr->zbuf_size);
  198418. png_ptr->zstream.next_out = png_ptr->zbuf;
  198419. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198420. wrote_IDAT = 1;
  198421. }
  198422. } while(wrote_IDAT == 1);
  198423. /* If there is any data left to be output, write it into a new IDAT */
  198424. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  198425. {
  198426. /* write the IDAT and reset the zlib output buffer */
  198427. png_write_IDAT(png_ptr, png_ptr->zbuf,
  198428. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  198429. png_ptr->zstream.next_out = png_ptr->zbuf;
  198430. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198431. }
  198432. png_ptr->flush_rows = 0;
  198433. png_flush(png_ptr);
  198434. }
  198435. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198436. /* free all memory used by the write */
  198437. void PNGAPI
  198438. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  198439. {
  198440. png_structp png_ptr = NULL;
  198441. png_infop info_ptr = NULL;
  198442. #ifdef PNG_USER_MEM_SUPPORTED
  198443. png_free_ptr free_fn = NULL;
  198444. png_voidp mem_ptr = NULL;
  198445. #endif
  198446. png_debug(1, "in png_destroy_write_struct\n");
  198447. if (png_ptr_ptr != NULL)
  198448. {
  198449. png_ptr = *png_ptr_ptr;
  198450. #ifdef PNG_USER_MEM_SUPPORTED
  198451. free_fn = png_ptr->free_fn;
  198452. mem_ptr = png_ptr->mem_ptr;
  198453. #endif
  198454. }
  198455. if (info_ptr_ptr != NULL)
  198456. info_ptr = *info_ptr_ptr;
  198457. if (info_ptr != NULL)
  198458. {
  198459. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  198460. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  198461. if (png_ptr->num_chunk_list)
  198462. {
  198463. png_free(png_ptr, png_ptr->chunk_list);
  198464. png_ptr->chunk_list=NULL;
  198465. png_ptr->num_chunk_list=0;
  198466. }
  198467. #endif
  198468. #ifdef PNG_USER_MEM_SUPPORTED
  198469. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  198470. (png_voidp)mem_ptr);
  198471. #else
  198472. png_destroy_struct((png_voidp)info_ptr);
  198473. #endif
  198474. *info_ptr_ptr = NULL;
  198475. }
  198476. if (png_ptr != NULL)
  198477. {
  198478. png_write_destroy(png_ptr);
  198479. #ifdef PNG_USER_MEM_SUPPORTED
  198480. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  198481. (png_voidp)mem_ptr);
  198482. #else
  198483. png_destroy_struct((png_voidp)png_ptr);
  198484. #endif
  198485. *png_ptr_ptr = NULL;
  198486. }
  198487. }
  198488. /* Free any memory used in png_ptr struct (old method) */
  198489. void /* PRIVATE */
  198490. png_write_destroy(png_structp png_ptr)
  198491. {
  198492. #ifdef PNG_SETJMP_SUPPORTED
  198493. jmp_buf tmp_jmp; /* save jump buffer */
  198494. #endif
  198495. png_error_ptr error_fn;
  198496. png_error_ptr warning_fn;
  198497. png_voidp error_ptr;
  198498. #ifdef PNG_USER_MEM_SUPPORTED
  198499. png_free_ptr free_fn;
  198500. #endif
  198501. png_debug(1, "in png_write_destroy\n");
  198502. /* free any memory zlib uses */
  198503. deflateEnd(&png_ptr->zstream);
  198504. /* free our memory. png_free checks NULL for us. */
  198505. png_free(png_ptr, png_ptr->zbuf);
  198506. png_free(png_ptr, png_ptr->row_buf);
  198507. png_free(png_ptr, png_ptr->prev_row);
  198508. png_free(png_ptr, png_ptr->sub_row);
  198509. png_free(png_ptr, png_ptr->up_row);
  198510. png_free(png_ptr, png_ptr->avg_row);
  198511. png_free(png_ptr, png_ptr->paeth_row);
  198512. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  198513. png_free(png_ptr, png_ptr->time_buffer);
  198514. #endif
  198515. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198516. png_free(png_ptr, png_ptr->prev_filters);
  198517. png_free(png_ptr, png_ptr->filter_weights);
  198518. png_free(png_ptr, png_ptr->inv_filter_weights);
  198519. png_free(png_ptr, png_ptr->filter_costs);
  198520. png_free(png_ptr, png_ptr->inv_filter_costs);
  198521. #endif
  198522. #ifdef PNG_SETJMP_SUPPORTED
  198523. /* reset structure */
  198524. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198525. #endif
  198526. error_fn = png_ptr->error_fn;
  198527. warning_fn = png_ptr->warning_fn;
  198528. error_ptr = png_ptr->error_ptr;
  198529. #ifdef PNG_USER_MEM_SUPPORTED
  198530. free_fn = png_ptr->free_fn;
  198531. #endif
  198532. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198533. png_ptr->error_fn = error_fn;
  198534. png_ptr->warning_fn = warning_fn;
  198535. png_ptr->error_ptr = error_ptr;
  198536. #ifdef PNG_USER_MEM_SUPPORTED
  198537. png_ptr->free_fn = free_fn;
  198538. #endif
  198539. #ifdef PNG_SETJMP_SUPPORTED
  198540. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198541. #endif
  198542. }
  198543. /* Allow the application to select one or more row filters to use. */
  198544. void PNGAPI
  198545. png_set_filter(png_structp png_ptr, int method, int filters)
  198546. {
  198547. png_debug(1, "in png_set_filter\n");
  198548. if (png_ptr == NULL)
  198549. return;
  198550. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198551. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198552. (method == PNG_INTRAPIXEL_DIFFERENCING))
  198553. method = PNG_FILTER_TYPE_BASE;
  198554. #endif
  198555. if (method == PNG_FILTER_TYPE_BASE)
  198556. {
  198557. switch (filters & (PNG_ALL_FILTERS | 0x07))
  198558. {
  198559. #ifndef PNG_NO_WRITE_FILTER
  198560. case 5:
  198561. case 6:
  198562. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  198563. #endif /* PNG_NO_WRITE_FILTER */
  198564. case PNG_FILTER_VALUE_NONE:
  198565. png_ptr->do_filter=PNG_FILTER_NONE; break;
  198566. #ifndef PNG_NO_WRITE_FILTER
  198567. case PNG_FILTER_VALUE_SUB:
  198568. png_ptr->do_filter=PNG_FILTER_SUB; break;
  198569. case PNG_FILTER_VALUE_UP:
  198570. png_ptr->do_filter=PNG_FILTER_UP; break;
  198571. case PNG_FILTER_VALUE_AVG:
  198572. png_ptr->do_filter=PNG_FILTER_AVG; break;
  198573. case PNG_FILTER_VALUE_PAETH:
  198574. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  198575. default: png_ptr->do_filter = (png_byte)filters; break;
  198576. #else
  198577. default: png_warning(png_ptr, "Unknown row filter for method 0");
  198578. #endif /* PNG_NO_WRITE_FILTER */
  198579. }
  198580. /* If we have allocated the row_buf, this means we have already started
  198581. * with the image and we should have allocated all of the filter buffers
  198582. * that have been selected. If prev_row isn't already allocated, then
  198583. * it is too late to start using the filters that need it, since we
  198584. * will be missing the data in the previous row. If an application
  198585. * wants to start and stop using particular filters during compression,
  198586. * it should start out with all of the filters, and then add and
  198587. * remove them after the start of compression.
  198588. */
  198589. if (png_ptr->row_buf != NULL)
  198590. {
  198591. #ifndef PNG_NO_WRITE_FILTER
  198592. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  198593. {
  198594. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  198595. (png_ptr->rowbytes + 1));
  198596. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  198597. }
  198598. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  198599. {
  198600. if (png_ptr->prev_row == NULL)
  198601. {
  198602. png_warning(png_ptr, "Can't add Up filter after starting");
  198603. png_ptr->do_filter &= ~PNG_FILTER_UP;
  198604. }
  198605. else
  198606. {
  198607. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  198608. (png_ptr->rowbytes + 1));
  198609. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  198610. }
  198611. }
  198612. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  198613. {
  198614. if (png_ptr->prev_row == NULL)
  198615. {
  198616. png_warning(png_ptr, "Can't add Average filter after starting");
  198617. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  198618. }
  198619. else
  198620. {
  198621. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  198622. (png_ptr->rowbytes + 1));
  198623. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  198624. }
  198625. }
  198626. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  198627. png_ptr->paeth_row == NULL)
  198628. {
  198629. if (png_ptr->prev_row == NULL)
  198630. {
  198631. png_warning(png_ptr, "Can't add Paeth filter after starting");
  198632. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  198633. }
  198634. else
  198635. {
  198636. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  198637. (png_ptr->rowbytes + 1));
  198638. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  198639. }
  198640. }
  198641. if (png_ptr->do_filter == PNG_NO_FILTERS)
  198642. #endif /* PNG_NO_WRITE_FILTER */
  198643. png_ptr->do_filter = PNG_FILTER_NONE;
  198644. }
  198645. }
  198646. else
  198647. png_error(png_ptr, "Unknown custom filter method");
  198648. }
  198649. /* This allows us to influence the way in which libpng chooses the "best"
  198650. * filter for the current scanline. While the "minimum-sum-of-absolute-
  198651. * differences metric is relatively fast and effective, there is some
  198652. * question as to whether it can be improved upon by trying to keep the
  198653. * filtered data going to zlib more consistent, hopefully resulting in
  198654. * better compression.
  198655. */
  198656. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  198657. void PNGAPI
  198658. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  198659. int num_weights, png_doublep filter_weights,
  198660. png_doublep filter_costs)
  198661. {
  198662. int i;
  198663. png_debug(1, "in png_set_filter_heuristics\n");
  198664. if (png_ptr == NULL)
  198665. return;
  198666. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  198667. {
  198668. png_warning(png_ptr, "Unknown filter heuristic method");
  198669. return;
  198670. }
  198671. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  198672. {
  198673. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  198674. }
  198675. if (num_weights < 0 || filter_weights == NULL ||
  198676. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  198677. {
  198678. num_weights = 0;
  198679. }
  198680. png_ptr->num_prev_filters = (png_byte)num_weights;
  198681. png_ptr->heuristic_method = (png_byte)heuristic_method;
  198682. if (num_weights > 0)
  198683. {
  198684. if (png_ptr->prev_filters == NULL)
  198685. {
  198686. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  198687. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  198688. /* To make sure that the weighting starts out fairly */
  198689. for (i = 0; i < num_weights; i++)
  198690. {
  198691. png_ptr->prev_filters[i] = 255;
  198692. }
  198693. }
  198694. if (png_ptr->filter_weights == NULL)
  198695. {
  198696. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  198697. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  198698. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  198699. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  198700. for (i = 0; i < num_weights; i++)
  198701. {
  198702. png_ptr->inv_filter_weights[i] =
  198703. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  198704. }
  198705. }
  198706. for (i = 0; i < num_weights; i++)
  198707. {
  198708. if (filter_weights[i] < 0.0)
  198709. {
  198710. png_ptr->inv_filter_weights[i] =
  198711. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  198712. }
  198713. else
  198714. {
  198715. png_ptr->inv_filter_weights[i] =
  198716. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  198717. png_ptr->filter_weights[i] =
  198718. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  198719. }
  198720. }
  198721. }
  198722. /* If, in the future, there are other filter methods, this would
  198723. * need to be based on png_ptr->filter.
  198724. */
  198725. if (png_ptr->filter_costs == NULL)
  198726. {
  198727. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  198728. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  198729. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  198730. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  198731. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  198732. {
  198733. png_ptr->inv_filter_costs[i] =
  198734. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  198735. }
  198736. }
  198737. /* Here is where we set the relative costs of the different filters. We
  198738. * should take the desired compression level into account when setting
  198739. * the costs, so that Paeth, for instance, has a high relative cost at low
  198740. * compression levels, while it has a lower relative cost at higher
  198741. * compression settings. The filter types are in order of increasing
  198742. * relative cost, so it would be possible to do this with an algorithm.
  198743. */
  198744. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  198745. {
  198746. if (filter_costs == NULL || filter_costs[i] < 0.0)
  198747. {
  198748. png_ptr->inv_filter_costs[i] =
  198749. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  198750. }
  198751. else if (filter_costs[i] >= 1.0)
  198752. {
  198753. png_ptr->inv_filter_costs[i] =
  198754. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  198755. png_ptr->filter_costs[i] =
  198756. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  198757. }
  198758. }
  198759. }
  198760. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  198761. void PNGAPI
  198762. png_set_compression_level(png_structp png_ptr, int level)
  198763. {
  198764. png_debug(1, "in png_set_compression_level\n");
  198765. if (png_ptr == NULL)
  198766. return;
  198767. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  198768. png_ptr->zlib_level = level;
  198769. }
  198770. void PNGAPI
  198771. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  198772. {
  198773. png_debug(1, "in png_set_compression_mem_level\n");
  198774. if (png_ptr == NULL)
  198775. return;
  198776. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  198777. png_ptr->zlib_mem_level = mem_level;
  198778. }
  198779. void PNGAPI
  198780. png_set_compression_strategy(png_structp png_ptr, int strategy)
  198781. {
  198782. png_debug(1, "in png_set_compression_strategy\n");
  198783. if (png_ptr == NULL)
  198784. return;
  198785. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  198786. png_ptr->zlib_strategy = strategy;
  198787. }
  198788. void PNGAPI
  198789. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  198790. {
  198791. if (png_ptr == NULL)
  198792. return;
  198793. if (window_bits > 15)
  198794. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  198795. else if (window_bits < 8)
  198796. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  198797. #ifndef WBITS_8_OK
  198798. /* avoid libpng bug with 256-byte windows */
  198799. if (window_bits == 8)
  198800. {
  198801. png_warning(png_ptr, "Compression window is being reset to 512");
  198802. window_bits=9;
  198803. }
  198804. #endif
  198805. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  198806. png_ptr->zlib_window_bits = window_bits;
  198807. }
  198808. void PNGAPI
  198809. png_set_compression_method(png_structp png_ptr, int method)
  198810. {
  198811. png_debug(1, "in png_set_compression_method\n");
  198812. if (png_ptr == NULL)
  198813. return;
  198814. if (method != 8)
  198815. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  198816. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  198817. png_ptr->zlib_method = method;
  198818. }
  198819. void PNGAPI
  198820. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  198821. {
  198822. if (png_ptr == NULL)
  198823. return;
  198824. png_ptr->write_row_fn = write_row_fn;
  198825. }
  198826. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  198827. void PNGAPI
  198828. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  198829. write_user_transform_fn)
  198830. {
  198831. png_debug(1, "in png_set_write_user_transform_fn\n");
  198832. if (png_ptr == NULL)
  198833. return;
  198834. png_ptr->transformations |= PNG_USER_TRANSFORM;
  198835. png_ptr->write_user_transform_fn = write_user_transform_fn;
  198836. }
  198837. #endif
  198838. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  198839. void PNGAPI
  198840. png_write_png(png_structp png_ptr, png_infop info_ptr,
  198841. int transforms, voidp params)
  198842. {
  198843. if (png_ptr == NULL || info_ptr == NULL)
  198844. return;
  198845. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198846. /* invert the alpha channel from opacity to transparency */
  198847. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  198848. png_set_invert_alpha(png_ptr);
  198849. #endif
  198850. /* Write the file header information. */
  198851. png_write_info(png_ptr, info_ptr);
  198852. /* ------ these transformations don't touch the info structure ------- */
  198853. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  198854. /* invert monochrome pixels */
  198855. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  198856. png_set_invert_mono(png_ptr);
  198857. #endif
  198858. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  198859. /* Shift the pixels up to a legal bit depth and fill in
  198860. * as appropriate to correctly scale the image.
  198861. */
  198862. if ((transforms & PNG_TRANSFORM_SHIFT)
  198863. && (info_ptr->valid & PNG_INFO_sBIT))
  198864. png_set_shift(png_ptr, &info_ptr->sig_bit);
  198865. #endif
  198866. #if defined(PNG_WRITE_PACK_SUPPORTED)
  198867. /* pack pixels into bytes */
  198868. if (transforms & PNG_TRANSFORM_PACKING)
  198869. png_set_packing(png_ptr);
  198870. #endif
  198871. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198872. /* swap location of alpha bytes from ARGB to RGBA */
  198873. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  198874. png_set_swap_alpha(png_ptr);
  198875. #endif
  198876. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  198877. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  198878. * RGB (4 channels -> 3 channels). The second parameter is not used.
  198879. */
  198880. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  198881. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  198882. #endif
  198883. #if defined(PNG_WRITE_BGR_SUPPORTED)
  198884. /* flip BGR pixels to RGB */
  198885. if (transforms & PNG_TRANSFORM_BGR)
  198886. png_set_bgr(png_ptr);
  198887. #endif
  198888. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  198889. /* swap bytes of 16-bit files to most significant byte first */
  198890. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  198891. png_set_swap(png_ptr);
  198892. #endif
  198893. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198894. /* swap bits of 1, 2, 4 bit packed pixel formats */
  198895. if (transforms & PNG_TRANSFORM_PACKSWAP)
  198896. png_set_packswap(png_ptr);
  198897. #endif
  198898. /* ----------------------- end of transformations ------------------- */
  198899. /* write the bits */
  198900. if (info_ptr->valid & PNG_INFO_IDAT)
  198901. png_write_image(png_ptr, info_ptr->row_pointers);
  198902. /* It is REQUIRED to call this to finish writing the rest of the file */
  198903. png_write_end(png_ptr, info_ptr);
  198904. transforms = transforms; /* quiet compiler warnings */
  198905. params = params;
  198906. }
  198907. #endif
  198908. #endif /* PNG_WRITE_SUPPORTED */
  198909. /*** End of inlined file: pngwrite.c ***/
  198910. /*** Start of inlined file: pngwtran.c ***/
  198911. /* pngwtran.c - transforms the data in a row for PNG writers
  198912. *
  198913. * Last changed in libpng 1.2.9 April 14, 2006
  198914. * For conditions of distribution and use, see copyright notice in png.h
  198915. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198916. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198917. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198918. */
  198919. #define PNG_INTERNAL
  198920. #ifdef PNG_WRITE_SUPPORTED
  198921. /* Transform the data according to the user's wishes. The order of
  198922. * transformations is significant.
  198923. */
  198924. void /* PRIVATE */
  198925. png_do_write_transformations(png_structp png_ptr)
  198926. {
  198927. png_debug(1, "in png_do_write_transformations\n");
  198928. if (png_ptr == NULL)
  198929. return;
  198930. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  198931. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  198932. if(png_ptr->write_user_transform_fn != NULL)
  198933. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  198934. (png_ptr, /* png_ptr */
  198935. &(png_ptr->row_info), /* row_info: */
  198936. /* png_uint_32 width; width of row */
  198937. /* png_uint_32 rowbytes; number of bytes in row */
  198938. /* png_byte color_type; color type of pixels */
  198939. /* png_byte bit_depth; bit depth of samples */
  198940. /* png_byte channels; number of channels (1-4) */
  198941. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  198942. png_ptr->row_buf + 1); /* start of pixel data for row */
  198943. #endif
  198944. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  198945. if (png_ptr->transformations & PNG_FILLER)
  198946. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  198947. png_ptr->flags);
  198948. #endif
  198949. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198950. if (png_ptr->transformations & PNG_PACKSWAP)
  198951. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198952. #endif
  198953. #if defined(PNG_WRITE_PACK_SUPPORTED)
  198954. if (png_ptr->transformations & PNG_PACK)
  198955. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  198956. (png_uint_32)png_ptr->bit_depth);
  198957. #endif
  198958. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  198959. if (png_ptr->transformations & PNG_SWAP_BYTES)
  198960. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198961. #endif
  198962. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  198963. if (png_ptr->transformations & PNG_SHIFT)
  198964. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  198965. &(png_ptr->shift));
  198966. #endif
  198967. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198968. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  198969. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198970. #endif
  198971. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198972. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  198973. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198974. #endif
  198975. #if defined(PNG_WRITE_BGR_SUPPORTED)
  198976. if (png_ptr->transformations & PNG_BGR)
  198977. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198978. #endif
  198979. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  198980. if (png_ptr->transformations & PNG_INVERT_MONO)
  198981. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198982. #endif
  198983. }
  198984. #if defined(PNG_WRITE_PACK_SUPPORTED)
  198985. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  198986. * row_info bit depth should be 8 (one pixel per byte). The channels
  198987. * should be 1 (this only happens on grayscale and paletted images).
  198988. */
  198989. void /* PRIVATE */
  198990. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  198991. {
  198992. png_debug(1, "in png_do_pack\n");
  198993. if (row_info->bit_depth == 8 &&
  198994. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198995. row != NULL && row_info != NULL &&
  198996. #endif
  198997. row_info->channels == 1)
  198998. {
  198999. switch ((int)bit_depth)
  199000. {
  199001. case 1:
  199002. {
  199003. png_bytep sp, dp;
  199004. int mask, v;
  199005. png_uint_32 i;
  199006. png_uint_32 row_width = row_info->width;
  199007. sp = row;
  199008. dp = row;
  199009. mask = 0x80;
  199010. v = 0;
  199011. for (i = 0; i < row_width; i++)
  199012. {
  199013. if (*sp != 0)
  199014. v |= mask;
  199015. sp++;
  199016. if (mask > 1)
  199017. mask >>= 1;
  199018. else
  199019. {
  199020. mask = 0x80;
  199021. *dp = (png_byte)v;
  199022. dp++;
  199023. v = 0;
  199024. }
  199025. }
  199026. if (mask != 0x80)
  199027. *dp = (png_byte)v;
  199028. break;
  199029. }
  199030. case 2:
  199031. {
  199032. png_bytep sp, dp;
  199033. int shift, v;
  199034. png_uint_32 i;
  199035. png_uint_32 row_width = row_info->width;
  199036. sp = row;
  199037. dp = row;
  199038. shift = 6;
  199039. v = 0;
  199040. for (i = 0; i < row_width; i++)
  199041. {
  199042. png_byte value;
  199043. value = (png_byte)(*sp & 0x03);
  199044. v |= (value << shift);
  199045. if (shift == 0)
  199046. {
  199047. shift = 6;
  199048. *dp = (png_byte)v;
  199049. dp++;
  199050. v = 0;
  199051. }
  199052. else
  199053. shift -= 2;
  199054. sp++;
  199055. }
  199056. if (shift != 6)
  199057. *dp = (png_byte)v;
  199058. break;
  199059. }
  199060. case 4:
  199061. {
  199062. png_bytep sp, dp;
  199063. int shift, v;
  199064. png_uint_32 i;
  199065. png_uint_32 row_width = row_info->width;
  199066. sp = row;
  199067. dp = row;
  199068. shift = 4;
  199069. v = 0;
  199070. for (i = 0; i < row_width; i++)
  199071. {
  199072. png_byte value;
  199073. value = (png_byte)(*sp & 0x0f);
  199074. v |= (value << shift);
  199075. if (shift == 0)
  199076. {
  199077. shift = 4;
  199078. *dp = (png_byte)v;
  199079. dp++;
  199080. v = 0;
  199081. }
  199082. else
  199083. shift -= 4;
  199084. sp++;
  199085. }
  199086. if (shift != 4)
  199087. *dp = (png_byte)v;
  199088. break;
  199089. }
  199090. }
  199091. row_info->bit_depth = (png_byte)bit_depth;
  199092. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199093. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199094. row_info->width);
  199095. }
  199096. }
  199097. #endif
  199098. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199099. /* Shift pixel values to take advantage of whole range. Pass the
  199100. * true number of bits in bit_depth. The row should be packed
  199101. * according to row_info->bit_depth. Thus, if you had a row of
  199102. * bit depth 4, but the pixels only had values from 0 to 7, you
  199103. * would pass 3 as bit_depth, and this routine would translate the
  199104. * data to 0 to 15.
  199105. */
  199106. void /* PRIVATE */
  199107. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199108. {
  199109. png_debug(1, "in png_do_shift\n");
  199110. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199111. if (row != NULL && row_info != NULL &&
  199112. #else
  199113. if (
  199114. #endif
  199115. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199116. {
  199117. int shift_start[4], shift_dec[4];
  199118. int channels = 0;
  199119. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199120. {
  199121. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199122. shift_dec[channels] = bit_depth->red;
  199123. channels++;
  199124. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199125. shift_dec[channels] = bit_depth->green;
  199126. channels++;
  199127. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  199128. shift_dec[channels] = bit_depth->blue;
  199129. channels++;
  199130. }
  199131. else
  199132. {
  199133. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  199134. shift_dec[channels] = bit_depth->gray;
  199135. channels++;
  199136. }
  199137. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  199138. {
  199139. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  199140. shift_dec[channels] = bit_depth->alpha;
  199141. channels++;
  199142. }
  199143. /* with low row depths, could only be grayscale, so one channel */
  199144. if (row_info->bit_depth < 8)
  199145. {
  199146. png_bytep bp = row;
  199147. png_uint_32 i;
  199148. png_byte mask;
  199149. png_uint_32 row_bytes = row_info->rowbytes;
  199150. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  199151. mask = 0x55;
  199152. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  199153. mask = 0x11;
  199154. else
  199155. mask = 0xff;
  199156. for (i = 0; i < row_bytes; i++, bp++)
  199157. {
  199158. png_uint_16 v;
  199159. int j;
  199160. v = *bp;
  199161. *bp = 0;
  199162. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  199163. {
  199164. if (j > 0)
  199165. *bp |= (png_byte)((v << j) & 0xff);
  199166. else
  199167. *bp |= (png_byte)((v >> (-j)) & mask);
  199168. }
  199169. }
  199170. }
  199171. else if (row_info->bit_depth == 8)
  199172. {
  199173. png_bytep bp = row;
  199174. png_uint_32 i;
  199175. png_uint_32 istop = channels * row_info->width;
  199176. for (i = 0; i < istop; i++, bp++)
  199177. {
  199178. png_uint_16 v;
  199179. int j;
  199180. int c = (int)(i%channels);
  199181. v = *bp;
  199182. *bp = 0;
  199183. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199184. {
  199185. if (j > 0)
  199186. *bp |= (png_byte)((v << j) & 0xff);
  199187. else
  199188. *bp |= (png_byte)((v >> (-j)) & 0xff);
  199189. }
  199190. }
  199191. }
  199192. else
  199193. {
  199194. png_bytep bp;
  199195. png_uint_32 i;
  199196. png_uint_32 istop = channels * row_info->width;
  199197. for (bp = row, i = 0; i < istop; i++)
  199198. {
  199199. int c = (int)(i%channels);
  199200. png_uint_16 value, v;
  199201. int j;
  199202. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  199203. value = 0;
  199204. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199205. {
  199206. if (j > 0)
  199207. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  199208. else
  199209. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  199210. }
  199211. *bp++ = (png_byte)(value >> 8);
  199212. *bp++ = (png_byte)(value & 0xff);
  199213. }
  199214. }
  199215. }
  199216. }
  199217. #endif
  199218. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199219. void /* PRIVATE */
  199220. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  199221. {
  199222. png_debug(1, "in png_do_write_swap_alpha\n");
  199223. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199224. if (row != NULL && row_info != NULL)
  199225. #endif
  199226. {
  199227. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199228. {
  199229. /* This converts from ARGB to RGBA */
  199230. if (row_info->bit_depth == 8)
  199231. {
  199232. png_bytep sp, dp;
  199233. png_uint_32 i;
  199234. png_uint_32 row_width = row_info->width;
  199235. for (i = 0, sp = dp = row; i < row_width; i++)
  199236. {
  199237. png_byte save = *(sp++);
  199238. *(dp++) = *(sp++);
  199239. *(dp++) = *(sp++);
  199240. *(dp++) = *(sp++);
  199241. *(dp++) = save;
  199242. }
  199243. }
  199244. /* This converts from AARRGGBB to RRGGBBAA */
  199245. else
  199246. {
  199247. png_bytep sp, dp;
  199248. png_uint_32 i;
  199249. png_uint_32 row_width = row_info->width;
  199250. for (i = 0, sp = dp = row; i < row_width; i++)
  199251. {
  199252. png_byte save[2];
  199253. save[0] = *(sp++);
  199254. save[1] = *(sp++);
  199255. *(dp++) = *(sp++);
  199256. *(dp++) = *(sp++);
  199257. *(dp++) = *(sp++);
  199258. *(dp++) = *(sp++);
  199259. *(dp++) = *(sp++);
  199260. *(dp++) = *(sp++);
  199261. *(dp++) = save[0];
  199262. *(dp++) = save[1];
  199263. }
  199264. }
  199265. }
  199266. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199267. {
  199268. /* This converts from AG to GA */
  199269. if (row_info->bit_depth == 8)
  199270. {
  199271. png_bytep sp, dp;
  199272. png_uint_32 i;
  199273. png_uint_32 row_width = row_info->width;
  199274. for (i = 0, sp = dp = row; i < row_width; i++)
  199275. {
  199276. png_byte save = *(sp++);
  199277. *(dp++) = *(sp++);
  199278. *(dp++) = save;
  199279. }
  199280. }
  199281. /* This converts from AAGG to GGAA */
  199282. else
  199283. {
  199284. png_bytep sp, dp;
  199285. png_uint_32 i;
  199286. png_uint_32 row_width = row_info->width;
  199287. for (i = 0, sp = dp = row; i < row_width; i++)
  199288. {
  199289. png_byte save[2];
  199290. save[0] = *(sp++);
  199291. save[1] = *(sp++);
  199292. *(dp++) = *(sp++);
  199293. *(dp++) = *(sp++);
  199294. *(dp++) = save[0];
  199295. *(dp++) = save[1];
  199296. }
  199297. }
  199298. }
  199299. }
  199300. }
  199301. #endif
  199302. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199303. void /* PRIVATE */
  199304. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  199305. {
  199306. png_debug(1, "in png_do_write_invert_alpha\n");
  199307. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199308. if (row != NULL && row_info != NULL)
  199309. #endif
  199310. {
  199311. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199312. {
  199313. /* This inverts the alpha channel in RGBA */
  199314. if (row_info->bit_depth == 8)
  199315. {
  199316. png_bytep sp, dp;
  199317. png_uint_32 i;
  199318. png_uint_32 row_width = row_info->width;
  199319. for (i = 0, sp = dp = row; i < row_width; i++)
  199320. {
  199321. /* does nothing
  199322. *(dp++) = *(sp++);
  199323. *(dp++) = *(sp++);
  199324. *(dp++) = *(sp++);
  199325. */
  199326. sp+=3; dp = sp;
  199327. *(dp++) = (png_byte)(255 - *(sp++));
  199328. }
  199329. }
  199330. /* This inverts the alpha channel in RRGGBBAA */
  199331. else
  199332. {
  199333. png_bytep sp, dp;
  199334. png_uint_32 i;
  199335. png_uint_32 row_width = row_info->width;
  199336. for (i = 0, sp = dp = row; i < row_width; i++)
  199337. {
  199338. /* does nothing
  199339. *(dp++) = *(sp++);
  199340. *(dp++) = *(sp++);
  199341. *(dp++) = *(sp++);
  199342. *(dp++) = *(sp++);
  199343. *(dp++) = *(sp++);
  199344. *(dp++) = *(sp++);
  199345. */
  199346. sp+=6; dp = sp;
  199347. *(dp++) = (png_byte)(255 - *(sp++));
  199348. *(dp++) = (png_byte)(255 - *(sp++));
  199349. }
  199350. }
  199351. }
  199352. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199353. {
  199354. /* This inverts the alpha channel in GA */
  199355. if (row_info->bit_depth == 8)
  199356. {
  199357. png_bytep sp, dp;
  199358. png_uint_32 i;
  199359. png_uint_32 row_width = row_info->width;
  199360. for (i = 0, sp = dp = row; i < row_width; i++)
  199361. {
  199362. *(dp++) = *(sp++);
  199363. *(dp++) = (png_byte)(255 - *(sp++));
  199364. }
  199365. }
  199366. /* This inverts the alpha channel in GGAA */
  199367. else
  199368. {
  199369. png_bytep sp, dp;
  199370. png_uint_32 i;
  199371. png_uint_32 row_width = row_info->width;
  199372. for (i = 0, sp = dp = row; i < row_width; i++)
  199373. {
  199374. /* does nothing
  199375. *(dp++) = *(sp++);
  199376. *(dp++) = *(sp++);
  199377. */
  199378. sp+=2; dp = sp;
  199379. *(dp++) = (png_byte)(255 - *(sp++));
  199380. *(dp++) = (png_byte)(255 - *(sp++));
  199381. }
  199382. }
  199383. }
  199384. }
  199385. }
  199386. #endif
  199387. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199388. /* undoes intrapixel differencing */
  199389. void /* PRIVATE */
  199390. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  199391. {
  199392. png_debug(1, "in png_do_write_intrapixel\n");
  199393. if (
  199394. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199395. row != NULL && row_info != NULL &&
  199396. #endif
  199397. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  199398. {
  199399. int bytes_per_pixel;
  199400. png_uint_32 row_width = row_info->width;
  199401. if (row_info->bit_depth == 8)
  199402. {
  199403. png_bytep rp;
  199404. png_uint_32 i;
  199405. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199406. bytes_per_pixel = 3;
  199407. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199408. bytes_per_pixel = 4;
  199409. else
  199410. return;
  199411. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  199412. {
  199413. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  199414. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  199415. }
  199416. }
  199417. else if (row_info->bit_depth == 16)
  199418. {
  199419. png_bytep rp;
  199420. png_uint_32 i;
  199421. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199422. bytes_per_pixel = 6;
  199423. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199424. bytes_per_pixel = 8;
  199425. else
  199426. return;
  199427. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  199428. {
  199429. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  199430. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  199431. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  199432. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  199433. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  199434. *(rp ) = (png_byte)((red >> 8) & 0xff);
  199435. *(rp+1) = (png_byte)(red & 0xff);
  199436. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  199437. *(rp+5) = (png_byte)(blue & 0xff);
  199438. }
  199439. }
  199440. }
  199441. }
  199442. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  199443. #endif /* PNG_WRITE_SUPPORTED */
  199444. /*** End of inlined file: pngwtran.c ***/
  199445. /*** Start of inlined file: pngwutil.c ***/
  199446. /* pngwutil.c - utilities to write a PNG file
  199447. *
  199448. * Last changed in libpng 1.2.20 Septhember 3, 2007
  199449. * For conditions of distribution and use, see copyright notice in png.h
  199450. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  199451. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199452. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199453. */
  199454. #define PNG_INTERNAL
  199455. #ifdef PNG_WRITE_SUPPORTED
  199456. /* Place a 32-bit number into a buffer in PNG byte order. We work
  199457. * with unsigned numbers for convenience, although one supported
  199458. * ancillary chunk uses signed (two's complement) numbers.
  199459. */
  199460. void PNGAPI
  199461. png_save_uint_32(png_bytep buf, png_uint_32 i)
  199462. {
  199463. buf[0] = (png_byte)((i >> 24) & 0xff);
  199464. buf[1] = (png_byte)((i >> 16) & 0xff);
  199465. buf[2] = (png_byte)((i >> 8) & 0xff);
  199466. buf[3] = (png_byte)(i & 0xff);
  199467. }
  199468. /* The png_save_int_32 function assumes integers are stored in two's
  199469. * complement format. If this isn't the case, then this routine needs to
  199470. * be modified to write data in two's complement format.
  199471. */
  199472. void PNGAPI
  199473. png_save_int_32(png_bytep buf, png_int_32 i)
  199474. {
  199475. buf[0] = (png_byte)((i >> 24) & 0xff);
  199476. buf[1] = (png_byte)((i >> 16) & 0xff);
  199477. buf[2] = (png_byte)((i >> 8) & 0xff);
  199478. buf[3] = (png_byte)(i & 0xff);
  199479. }
  199480. /* Place a 16-bit number into a buffer in PNG byte order.
  199481. * The parameter is declared unsigned int, not png_uint_16,
  199482. * just to avoid potential problems on pre-ANSI C compilers.
  199483. */
  199484. void PNGAPI
  199485. png_save_uint_16(png_bytep buf, unsigned int i)
  199486. {
  199487. buf[0] = (png_byte)((i >> 8) & 0xff);
  199488. buf[1] = (png_byte)(i & 0xff);
  199489. }
  199490. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  199491. * representing the chunk name. The array must be at least 4 bytes in
  199492. * length, and does not need to be null terminated. To be safe, pass the
  199493. * pre-defined chunk names here, and if you need a new one, define it
  199494. * where the others are defined. The length is the length of the data.
  199495. * All the data must be present. If that is not possible, use the
  199496. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  199497. * functions instead.
  199498. */
  199499. void PNGAPI
  199500. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  199501. png_bytep data, png_size_t length)
  199502. {
  199503. if(png_ptr == NULL) return;
  199504. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  199505. png_write_chunk_data(png_ptr, data, length);
  199506. png_write_chunk_end(png_ptr);
  199507. }
  199508. /* Write the start of a PNG chunk. The type is the chunk type.
  199509. * The total_length is the sum of the lengths of all the data you will be
  199510. * passing in png_write_chunk_data().
  199511. */
  199512. void PNGAPI
  199513. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  199514. png_uint_32 length)
  199515. {
  199516. png_byte buf[4];
  199517. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  199518. if(png_ptr == NULL) return;
  199519. /* write the length */
  199520. png_save_uint_32(buf, length);
  199521. png_write_data(png_ptr, buf, (png_size_t)4);
  199522. /* write the chunk name */
  199523. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  199524. /* reset the crc and run it over the chunk name */
  199525. png_reset_crc(png_ptr);
  199526. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  199527. }
  199528. /* Write the data of a PNG chunk started with png_write_chunk_start().
  199529. * Note that multiple calls to this function are allowed, and that the
  199530. * sum of the lengths from these calls *must* add up to the total_length
  199531. * given to png_write_chunk_start().
  199532. */
  199533. void PNGAPI
  199534. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  199535. {
  199536. /* write the data, and run the CRC over it */
  199537. if(png_ptr == NULL) return;
  199538. if (data != NULL && length > 0)
  199539. {
  199540. png_calculate_crc(png_ptr, data, length);
  199541. png_write_data(png_ptr, data, length);
  199542. }
  199543. }
  199544. /* Finish a chunk started with png_write_chunk_start(). */
  199545. void PNGAPI
  199546. png_write_chunk_end(png_structp png_ptr)
  199547. {
  199548. png_byte buf[4];
  199549. if(png_ptr == NULL) return;
  199550. /* write the crc */
  199551. png_save_uint_32(buf, png_ptr->crc);
  199552. png_write_data(png_ptr, buf, (png_size_t)4);
  199553. }
  199554. /* Simple function to write the signature. If we have already written
  199555. * the magic bytes of the signature, or more likely, the PNG stream is
  199556. * being embedded into another stream and doesn't need its own signature,
  199557. * we should call png_set_sig_bytes() to tell libpng how many of the
  199558. * bytes have already been written.
  199559. */
  199560. void /* PRIVATE */
  199561. png_write_sig(png_structp png_ptr)
  199562. {
  199563. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  199564. /* write the rest of the 8 byte signature */
  199565. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  199566. (png_size_t)8 - png_ptr->sig_bytes);
  199567. if(png_ptr->sig_bytes < 3)
  199568. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  199569. }
  199570. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  199571. /*
  199572. * This pair of functions encapsulates the operation of (a) compressing a
  199573. * text string, and (b) issuing it later as a series of chunk data writes.
  199574. * The compression_state structure is shared context for these functions
  199575. * set up by the caller in order to make the whole mess thread-safe.
  199576. */
  199577. typedef struct
  199578. {
  199579. char *input; /* the uncompressed input data */
  199580. int input_len; /* its length */
  199581. int num_output_ptr; /* number of output pointers used */
  199582. int max_output_ptr; /* size of output_ptr */
  199583. png_charpp output_ptr; /* array of pointers to output */
  199584. } compression_state;
  199585. /* compress given text into storage in the png_ptr structure */
  199586. static int /* PRIVATE */
  199587. png_text_compress(png_structp png_ptr,
  199588. png_charp text, png_size_t text_len, int compression,
  199589. compression_state *comp)
  199590. {
  199591. int ret;
  199592. comp->num_output_ptr = 0;
  199593. comp->max_output_ptr = 0;
  199594. comp->output_ptr = NULL;
  199595. comp->input = NULL;
  199596. comp->input_len = 0;
  199597. /* we may just want to pass the text right through */
  199598. if (compression == PNG_TEXT_COMPRESSION_NONE)
  199599. {
  199600. comp->input = text;
  199601. comp->input_len = text_len;
  199602. return((int)text_len);
  199603. }
  199604. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  199605. {
  199606. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199607. char msg[50];
  199608. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  199609. png_warning(png_ptr, msg);
  199610. #else
  199611. png_warning(png_ptr, "Unknown compression type");
  199612. #endif
  199613. }
  199614. /* We can't write the chunk until we find out how much data we have,
  199615. * which means we need to run the compressor first and save the
  199616. * output. This shouldn't be a problem, as the vast majority of
  199617. * comments should be reasonable, but we will set up an array of
  199618. * malloc'd pointers to be sure.
  199619. *
  199620. * If we knew the application was well behaved, we could simplify this
  199621. * greatly by assuming we can always malloc an output buffer large
  199622. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  199623. * and malloc this directly. The only time this would be a bad idea is
  199624. * if we can't malloc more than 64K and we have 64K of random input
  199625. * data, or if the input string is incredibly large (although this
  199626. * wouldn't cause a failure, just a slowdown due to swapping).
  199627. */
  199628. /* set up the compression buffers */
  199629. png_ptr->zstream.avail_in = (uInt)text_len;
  199630. png_ptr->zstream.next_in = (Bytef *)text;
  199631. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199632. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  199633. /* this is the same compression loop as in png_write_row() */
  199634. do
  199635. {
  199636. /* compress the data */
  199637. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  199638. if (ret != Z_OK)
  199639. {
  199640. /* error */
  199641. if (png_ptr->zstream.msg != NULL)
  199642. png_error(png_ptr, png_ptr->zstream.msg);
  199643. else
  199644. png_error(png_ptr, "zlib error");
  199645. }
  199646. /* check to see if we need more room */
  199647. if (!(png_ptr->zstream.avail_out))
  199648. {
  199649. /* make sure the output array has room */
  199650. if (comp->num_output_ptr >= comp->max_output_ptr)
  199651. {
  199652. int old_max;
  199653. old_max = comp->max_output_ptr;
  199654. comp->max_output_ptr = comp->num_output_ptr + 4;
  199655. if (comp->output_ptr != NULL)
  199656. {
  199657. png_charpp old_ptr;
  199658. old_ptr = comp->output_ptr;
  199659. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199660. (png_uint_32)(comp->max_output_ptr *
  199661. png_sizeof (png_charpp)));
  199662. png_memcpy(comp->output_ptr, old_ptr, old_max
  199663. * png_sizeof (png_charp));
  199664. png_free(png_ptr, old_ptr);
  199665. }
  199666. else
  199667. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199668. (png_uint_32)(comp->max_output_ptr *
  199669. png_sizeof (png_charp)));
  199670. }
  199671. /* save the data */
  199672. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  199673. (png_uint_32)png_ptr->zbuf_size);
  199674. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  199675. png_ptr->zbuf_size);
  199676. comp->num_output_ptr++;
  199677. /* and reset the buffer */
  199678. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199679. png_ptr->zstream.next_out = png_ptr->zbuf;
  199680. }
  199681. /* continue until we don't have any more to compress */
  199682. } while (png_ptr->zstream.avail_in);
  199683. /* finish the compression */
  199684. do
  199685. {
  199686. /* tell zlib we are finished */
  199687. ret = deflate(&png_ptr->zstream, Z_FINISH);
  199688. if (ret == Z_OK)
  199689. {
  199690. /* check to see if we need more room */
  199691. if (!(png_ptr->zstream.avail_out))
  199692. {
  199693. /* check to make sure our output array has room */
  199694. if (comp->num_output_ptr >= comp->max_output_ptr)
  199695. {
  199696. int old_max;
  199697. old_max = comp->max_output_ptr;
  199698. comp->max_output_ptr = comp->num_output_ptr + 4;
  199699. if (comp->output_ptr != NULL)
  199700. {
  199701. png_charpp old_ptr;
  199702. old_ptr = comp->output_ptr;
  199703. /* This could be optimized to realloc() */
  199704. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199705. (png_uint_32)(comp->max_output_ptr *
  199706. png_sizeof (png_charpp)));
  199707. png_memcpy(comp->output_ptr, old_ptr,
  199708. old_max * png_sizeof (png_charp));
  199709. png_free(png_ptr, old_ptr);
  199710. }
  199711. else
  199712. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199713. (png_uint_32)(comp->max_output_ptr *
  199714. png_sizeof (png_charp)));
  199715. }
  199716. /* save off the data */
  199717. comp->output_ptr[comp->num_output_ptr] =
  199718. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  199719. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  199720. png_ptr->zbuf_size);
  199721. comp->num_output_ptr++;
  199722. /* and reset the buffer pointers */
  199723. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199724. png_ptr->zstream.next_out = png_ptr->zbuf;
  199725. }
  199726. }
  199727. else if (ret != Z_STREAM_END)
  199728. {
  199729. /* we got an error */
  199730. if (png_ptr->zstream.msg != NULL)
  199731. png_error(png_ptr, png_ptr->zstream.msg);
  199732. else
  199733. png_error(png_ptr, "zlib error");
  199734. }
  199735. } while (ret != Z_STREAM_END);
  199736. /* text length is number of buffers plus last buffer */
  199737. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  199738. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  199739. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  199740. return((int)text_len);
  199741. }
  199742. /* ship the compressed text out via chunk writes */
  199743. static void /* PRIVATE */
  199744. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  199745. {
  199746. int i;
  199747. /* handle the no-compression case */
  199748. if (comp->input)
  199749. {
  199750. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  199751. (png_size_t)comp->input_len);
  199752. return;
  199753. }
  199754. /* write saved output buffers, if any */
  199755. for (i = 0; i < comp->num_output_ptr; i++)
  199756. {
  199757. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  199758. png_ptr->zbuf_size);
  199759. png_free(png_ptr, comp->output_ptr[i]);
  199760. comp->output_ptr[i]=NULL;
  199761. }
  199762. if (comp->max_output_ptr != 0)
  199763. png_free(png_ptr, comp->output_ptr);
  199764. comp->output_ptr=NULL;
  199765. /* write anything left in zbuf */
  199766. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  199767. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  199768. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199769. /* reset zlib for another zTXt/iTXt or image data */
  199770. deflateReset(&png_ptr->zstream);
  199771. png_ptr->zstream.data_type = Z_BINARY;
  199772. }
  199773. #endif
  199774. /* Write the IHDR chunk, and update the png_struct with the necessary
  199775. * information. Note that the rest of this code depends upon this
  199776. * information being correct.
  199777. */
  199778. void /* PRIVATE */
  199779. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  199780. int bit_depth, int color_type, int compression_type, int filter_type,
  199781. int interlace_type)
  199782. {
  199783. #ifdef PNG_USE_LOCAL_ARRAYS
  199784. PNG_IHDR;
  199785. #endif
  199786. png_byte buf[13]; /* buffer to store the IHDR info */
  199787. png_debug(1, "in png_write_IHDR\n");
  199788. /* Check that we have valid input data from the application info */
  199789. switch (color_type)
  199790. {
  199791. case PNG_COLOR_TYPE_GRAY:
  199792. switch (bit_depth)
  199793. {
  199794. case 1:
  199795. case 2:
  199796. case 4:
  199797. case 8:
  199798. case 16: png_ptr->channels = 1; break;
  199799. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  199800. }
  199801. break;
  199802. case PNG_COLOR_TYPE_RGB:
  199803. if (bit_depth != 8 && bit_depth != 16)
  199804. png_error(png_ptr, "Invalid bit depth for RGB image");
  199805. png_ptr->channels = 3;
  199806. break;
  199807. case PNG_COLOR_TYPE_PALETTE:
  199808. switch (bit_depth)
  199809. {
  199810. case 1:
  199811. case 2:
  199812. case 4:
  199813. case 8: png_ptr->channels = 1; break;
  199814. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  199815. }
  199816. break;
  199817. case PNG_COLOR_TYPE_GRAY_ALPHA:
  199818. if (bit_depth != 8 && bit_depth != 16)
  199819. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  199820. png_ptr->channels = 2;
  199821. break;
  199822. case PNG_COLOR_TYPE_RGB_ALPHA:
  199823. if (bit_depth != 8 && bit_depth != 16)
  199824. png_error(png_ptr, "Invalid bit depth for RGBA image");
  199825. png_ptr->channels = 4;
  199826. break;
  199827. default:
  199828. png_error(png_ptr, "Invalid image color type specified");
  199829. }
  199830. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  199831. {
  199832. png_warning(png_ptr, "Invalid compression type specified");
  199833. compression_type = PNG_COMPRESSION_TYPE_BASE;
  199834. }
  199835. /* Write filter_method 64 (intrapixel differencing) only if
  199836. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199837. * 2. Libpng did not write a PNG signature (this filter_method is only
  199838. * used in PNG datastreams that are embedded in MNG datastreams) and
  199839. * 3. The application called png_permit_mng_features with a mask that
  199840. * included PNG_FLAG_MNG_FILTER_64 and
  199841. * 4. The filter_method is 64 and
  199842. * 5. The color_type is RGB or RGBA
  199843. */
  199844. if (
  199845. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199846. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199847. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  199848. (color_type == PNG_COLOR_TYPE_RGB ||
  199849. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  199850. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  199851. #endif
  199852. filter_type != PNG_FILTER_TYPE_BASE)
  199853. {
  199854. png_warning(png_ptr, "Invalid filter type specified");
  199855. filter_type = PNG_FILTER_TYPE_BASE;
  199856. }
  199857. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  199858. if (interlace_type != PNG_INTERLACE_NONE &&
  199859. interlace_type != PNG_INTERLACE_ADAM7)
  199860. {
  199861. png_warning(png_ptr, "Invalid interlace type specified");
  199862. interlace_type = PNG_INTERLACE_ADAM7;
  199863. }
  199864. #else
  199865. interlace_type=PNG_INTERLACE_NONE;
  199866. #endif
  199867. /* save off the relevent information */
  199868. png_ptr->bit_depth = (png_byte)bit_depth;
  199869. png_ptr->color_type = (png_byte)color_type;
  199870. png_ptr->interlaced = (png_byte)interlace_type;
  199871. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199872. png_ptr->filter_type = (png_byte)filter_type;
  199873. #endif
  199874. png_ptr->compression_type = (png_byte)compression_type;
  199875. png_ptr->width = width;
  199876. png_ptr->height = height;
  199877. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  199878. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  199879. /* set the usr info, so any transformations can modify it */
  199880. png_ptr->usr_width = png_ptr->width;
  199881. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  199882. png_ptr->usr_channels = png_ptr->channels;
  199883. /* pack the header information into the buffer */
  199884. png_save_uint_32(buf, width);
  199885. png_save_uint_32(buf + 4, height);
  199886. buf[8] = (png_byte)bit_depth;
  199887. buf[9] = (png_byte)color_type;
  199888. buf[10] = (png_byte)compression_type;
  199889. buf[11] = (png_byte)filter_type;
  199890. buf[12] = (png_byte)interlace_type;
  199891. /* write the chunk */
  199892. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  199893. /* initialize zlib with PNG info */
  199894. png_ptr->zstream.zalloc = png_zalloc;
  199895. png_ptr->zstream.zfree = png_zfree;
  199896. png_ptr->zstream.opaque = (voidpf)png_ptr;
  199897. if (!(png_ptr->do_filter))
  199898. {
  199899. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  199900. png_ptr->bit_depth < 8)
  199901. png_ptr->do_filter = PNG_FILTER_NONE;
  199902. else
  199903. png_ptr->do_filter = PNG_ALL_FILTERS;
  199904. }
  199905. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  199906. {
  199907. if (png_ptr->do_filter != PNG_FILTER_NONE)
  199908. png_ptr->zlib_strategy = Z_FILTERED;
  199909. else
  199910. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  199911. }
  199912. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  199913. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  199914. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  199915. png_ptr->zlib_mem_level = 8;
  199916. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  199917. png_ptr->zlib_window_bits = 15;
  199918. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  199919. png_ptr->zlib_method = 8;
  199920. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  199921. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  199922. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  199923. png_error(png_ptr, "zlib failed to initialize compressor");
  199924. png_ptr->zstream.next_out = png_ptr->zbuf;
  199925. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199926. /* libpng is not interested in zstream.data_type */
  199927. /* set it to a predefined value, to avoid its evaluation inside zlib */
  199928. png_ptr->zstream.data_type = Z_BINARY;
  199929. png_ptr->mode = PNG_HAVE_IHDR;
  199930. }
  199931. /* write the palette. We are careful not to trust png_color to be in the
  199932. * correct order for PNG, so people can redefine it to any convenient
  199933. * structure.
  199934. */
  199935. void /* PRIVATE */
  199936. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  199937. {
  199938. #ifdef PNG_USE_LOCAL_ARRAYS
  199939. PNG_PLTE;
  199940. #endif
  199941. png_uint_32 i;
  199942. png_colorp pal_ptr;
  199943. png_byte buf[3];
  199944. png_debug(1, "in png_write_PLTE\n");
  199945. if ((
  199946. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199947. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  199948. #endif
  199949. num_pal == 0) || num_pal > 256)
  199950. {
  199951. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199952. {
  199953. png_error(png_ptr, "Invalid number of colors in palette");
  199954. }
  199955. else
  199956. {
  199957. png_warning(png_ptr, "Invalid number of colors in palette");
  199958. return;
  199959. }
  199960. }
  199961. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  199962. {
  199963. png_warning(png_ptr,
  199964. "Ignoring request to write a PLTE chunk in grayscale PNG");
  199965. return;
  199966. }
  199967. png_ptr->num_palette = (png_uint_16)num_pal;
  199968. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  199969. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  199970. #ifndef PNG_NO_POINTER_INDEXING
  199971. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  199972. {
  199973. buf[0] = pal_ptr->red;
  199974. buf[1] = pal_ptr->green;
  199975. buf[2] = pal_ptr->blue;
  199976. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  199977. }
  199978. #else
  199979. /* This is a little slower but some buggy compilers need to do this instead */
  199980. pal_ptr=palette;
  199981. for (i = 0; i < num_pal; i++)
  199982. {
  199983. buf[0] = pal_ptr[i].red;
  199984. buf[1] = pal_ptr[i].green;
  199985. buf[2] = pal_ptr[i].blue;
  199986. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  199987. }
  199988. #endif
  199989. png_write_chunk_end(png_ptr);
  199990. png_ptr->mode |= PNG_HAVE_PLTE;
  199991. }
  199992. /* write an IDAT chunk */
  199993. void /* PRIVATE */
  199994. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  199995. {
  199996. #ifdef PNG_USE_LOCAL_ARRAYS
  199997. PNG_IDAT;
  199998. #endif
  199999. png_debug(1, "in png_write_IDAT\n");
  200000. /* Optimize the CMF field in the zlib stream. */
  200001. /* This hack of the zlib stream is compliant to the stream specification. */
  200002. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200003. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200004. {
  200005. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200006. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200007. {
  200008. /* Avoid memory underflows and multiplication overflows. */
  200009. /* The conditions below are practically always satisfied;
  200010. however, they still must be checked. */
  200011. if (length >= 2 &&
  200012. png_ptr->height < 16384 && png_ptr->width < 16384)
  200013. {
  200014. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200015. ((png_ptr->width *
  200016. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200017. unsigned int z_cinfo = z_cmf >> 4;
  200018. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200019. while (uncompressed_idat_size <= half_z_window_size &&
  200020. half_z_window_size >= 256)
  200021. {
  200022. z_cinfo--;
  200023. half_z_window_size >>= 1;
  200024. }
  200025. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200026. if (data[0] != (png_byte)z_cmf)
  200027. {
  200028. data[0] = (png_byte)z_cmf;
  200029. data[1] &= 0xe0;
  200030. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200031. }
  200032. }
  200033. }
  200034. else
  200035. png_error(png_ptr,
  200036. "Invalid zlib compression method or flags in IDAT");
  200037. }
  200038. png_write_chunk(png_ptr, png_IDAT, data, length);
  200039. png_ptr->mode |= PNG_HAVE_IDAT;
  200040. }
  200041. /* write an IEND chunk */
  200042. void /* PRIVATE */
  200043. png_write_IEND(png_structp png_ptr)
  200044. {
  200045. #ifdef PNG_USE_LOCAL_ARRAYS
  200046. PNG_IEND;
  200047. #endif
  200048. png_debug(1, "in png_write_IEND\n");
  200049. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200050. (png_size_t)0);
  200051. png_ptr->mode |= PNG_HAVE_IEND;
  200052. }
  200053. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200054. /* write a gAMA chunk */
  200055. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200056. void /* PRIVATE */
  200057. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200058. {
  200059. #ifdef PNG_USE_LOCAL_ARRAYS
  200060. PNG_gAMA;
  200061. #endif
  200062. png_uint_32 igamma;
  200063. png_byte buf[4];
  200064. png_debug(1, "in png_write_gAMA\n");
  200065. /* file_gamma is saved in 1/100,000ths */
  200066. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200067. png_save_uint_32(buf, igamma);
  200068. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200069. }
  200070. #endif
  200071. #ifdef PNG_FIXED_POINT_SUPPORTED
  200072. void /* PRIVATE */
  200073. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200074. {
  200075. #ifdef PNG_USE_LOCAL_ARRAYS
  200076. PNG_gAMA;
  200077. #endif
  200078. png_byte buf[4];
  200079. png_debug(1, "in png_write_gAMA\n");
  200080. /* file_gamma is saved in 1/100,000ths */
  200081. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200082. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200083. }
  200084. #endif
  200085. #endif
  200086. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200087. /* write a sRGB chunk */
  200088. void /* PRIVATE */
  200089. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200090. {
  200091. #ifdef PNG_USE_LOCAL_ARRAYS
  200092. PNG_sRGB;
  200093. #endif
  200094. png_byte buf[1];
  200095. png_debug(1, "in png_write_sRGB\n");
  200096. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200097. png_warning(png_ptr,
  200098. "Invalid sRGB rendering intent specified");
  200099. buf[0]=(png_byte)srgb_intent;
  200100. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200101. }
  200102. #endif
  200103. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200104. /* write an iCCP chunk */
  200105. void /* PRIVATE */
  200106. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200107. png_charp profile, int profile_len)
  200108. {
  200109. #ifdef PNG_USE_LOCAL_ARRAYS
  200110. PNG_iCCP;
  200111. #endif
  200112. png_size_t name_len;
  200113. png_charp new_name;
  200114. compression_state comp;
  200115. int embedded_profile_len = 0;
  200116. png_debug(1, "in png_write_iCCP\n");
  200117. comp.num_output_ptr = 0;
  200118. comp.max_output_ptr = 0;
  200119. comp.output_ptr = NULL;
  200120. comp.input = NULL;
  200121. comp.input_len = 0;
  200122. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200123. &new_name)) == 0)
  200124. {
  200125. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200126. return;
  200127. }
  200128. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200129. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  200130. if (profile == NULL)
  200131. profile_len = 0;
  200132. if (profile_len > 3)
  200133. embedded_profile_len =
  200134. ((*( (png_bytep)profile ))<<24) |
  200135. ((*( (png_bytep)profile+1))<<16) |
  200136. ((*( (png_bytep)profile+2))<< 8) |
  200137. ((*( (png_bytep)profile+3)) );
  200138. if (profile_len < embedded_profile_len)
  200139. {
  200140. png_warning(png_ptr,
  200141. "Embedded profile length too large in iCCP chunk");
  200142. return;
  200143. }
  200144. if (profile_len > embedded_profile_len)
  200145. {
  200146. png_warning(png_ptr,
  200147. "Truncating profile to actual length in iCCP chunk");
  200148. profile_len = embedded_profile_len;
  200149. }
  200150. if (profile_len)
  200151. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  200152. PNG_COMPRESSION_TYPE_BASE, &comp);
  200153. /* make sure we include the NULL after the name and the compression type */
  200154. png_write_chunk_start(png_ptr, png_iCCP,
  200155. (png_uint_32)name_len+profile_len+2);
  200156. new_name[name_len+1]=0x00;
  200157. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  200158. if (profile_len)
  200159. png_write_compressed_data_out(png_ptr, &comp);
  200160. png_write_chunk_end(png_ptr);
  200161. png_free(png_ptr, new_name);
  200162. }
  200163. #endif
  200164. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  200165. /* write a sPLT chunk */
  200166. void /* PRIVATE */
  200167. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  200168. {
  200169. #ifdef PNG_USE_LOCAL_ARRAYS
  200170. PNG_sPLT;
  200171. #endif
  200172. png_size_t name_len;
  200173. png_charp new_name;
  200174. png_byte entrybuf[10];
  200175. int entry_size = (spalette->depth == 8 ? 6 : 10);
  200176. int palette_size = entry_size * spalette->nentries;
  200177. png_sPLT_entryp ep;
  200178. #ifdef PNG_NO_POINTER_INDEXING
  200179. int i;
  200180. #endif
  200181. png_debug(1, "in png_write_sPLT\n");
  200182. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  200183. spalette->name, &new_name))==0)
  200184. {
  200185. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  200186. return;
  200187. }
  200188. /* make sure we include the NULL after the name */
  200189. png_write_chunk_start(png_ptr, png_sPLT,
  200190. (png_uint_32)(name_len + 2 + palette_size));
  200191. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  200192. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  200193. /* loop through each palette entry, writing appropriately */
  200194. #ifndef PNG_NO_POINTER_INDEXING
  200195. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  200196. {
  200197. if (spalette->depth == 8)
  200198. {
  200199. entrybuf[0] = (png_byte)ep->red;
  200200. entrybuf[1] = (png_byte)ep->green;
  200201. entrybuf[2] = (png_byte)ep->blue;
  200202. entrybuf[3] = (png_byte)ep->alpha;
  200203. png_save_uint_16(entrybuf + 4, ep->frequency);
  200204. }
  200205. else
  200206. {
  200207. png_save_uint_16(entrybuf + 0, ep->red);
  200208. png_save_uint_16(entrybuf + 2, ep->green);
  200209. png_save_uint_16(entrybuf + 4, ep->blue);
  200210. png_save_uint_16(entrybuf + 6, ep->alpha);
  200211. png_save_uint_16(entrybuf + 8, ep->frequency);
  200212. }
  200213. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  200214. }
  200215. #else
  200216. ep=spalette->entries;
  200217. for (i=0; i>spalette->nentries; i++)
  200218. {
  200219. if (spalette->depth == 8)
  200220. {
  200221. entrybuf[0] = (png_byte)ep[i].red;
  200222. entrybuf[1] = (png_byte)ep[i].green;
  200223. entrybuf[2] = (png_byte)ep[i].blue;
  200224. entrybuf[3] = (png_byte)ep[i].alpha;
  200225. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  200226. }
  200227. else
  200228. {
  200229. png_save_uint_16(entrybuf + 0, ep[i].red);
  200230. png_save_uint_16(entrybuf + 2, ep[i].green);
  200231. png_save_uint_16(entrybuf + 4, ep[i].blue);
  200232. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  200233. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  200234. }
  200235. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  200236. }
  200237. #endif
  200238. png_write_chunk_end(png_ptr);
  200239. png_free(png_ptr, new_name);
  200240. }
  200241. #endif
  200242. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  200243. /* write the sBIT chunk */
  200244. void /* PRIVATE */
  200245. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  200246. {
  200247. #ifdef PNG_USE_LOCAL_ARRAYS
  200248. PNG_sBIT;
  200249. #endif
  200250. png_byte buf[4];
  200251. png_size_t size;
  200252. png_debug(1, "in png_write_sBIT\n");
  200253. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  200254. if (color_type & PNG_COLOR_MASK_COLOR)
  200255. {
  200256. png_byte maxbits;
  200257. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  200258. png_ptr->usr_bit_depth);
  200259. if (sbit->red == 0 || sbit->red > maxbits ||
  200260. sbit->green == 0 || sbit->green > maxbits ||
  200261. sbit->blue == 0 || sbit->blue > maxbits)
  200262. {
  200263. png_warning(png_ptr, "Invalid sBIT depth specified");
  200264. return;
  200265. }
  200266. buf[0] = sbit->red;
  200267. buf[1] = sbit->green;
  200268. buf[2] = sbit->blue;
  200269. size = 3;
  200270. }
  200271. else
  200272. {
  200273. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  200274. {
  200275. png_warning(png_ptr, "Invalid sBIT depth specified");
  200276. return;
  200277. }
  200278. buf[0] = sbit->gray;
  200279. size = 1;
  200280. }
  200281. if (color_type & PNG_COLOR_MASK_ALPHA)
  200282. {
  200283. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  200284. {
  200285. png_warning(png_ptr, "Invalid sBIT depth specified");
  200286. return;
  200287. }
  200288. buf[size++] = sbit->alpha;
  200289. }
  200290. png_write_chunk(png_ptr, png_sBIT, buf, size);
  200291. }
  200292. #endif
  200293. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  200294. /* write the cHRM chunk */
  200295. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200296. void /* PRIVATE */
  200297. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  200298. double red_x, double red_y, double green_x, double green_y,
  200299. double blue_x, double blue_y)
  200300. {
  200301. #ifdef PNG_USE_LOCAL_ARRAYS
  200302. PNG_cHRM;
  200303. #endif
  200304. png_byte buf[32];
  200305. png_uint_32 itemp;
  200306. png_debug(1, "in png_write_cHRM\n");
  200307. /* each value is saved in 1/100,000ths */
  200308. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  200309. white_x + white_y > 1.0)
  200310. {
  200311. png_warning(png_ptr, "Invalid cHRM white point specified");
  200312. #if !defined(PNG_NO_CONSOLE_IO)
  200313. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  200314. #endif
  200315. return;
  200316. }
  200317. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  200318. png_save_uint_32(buf, itemp);
  200319. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  200320. png_save_uint_32(buf + 4, itemp);
  200321. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  200322. {
  200323. png_warning(png_ptr, "Invalid cHRM red point specified");
  200324. return;
  200325. }
  200326. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  200327. png_save_uint_32(buf + 8, itemp);
  200328. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  200329. png_save_uint_32(buf + 12, itemp);
  200330. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  200331. {
  200332. png_warning(png_ptr, "Invalid cHRM green point specified");
  200333. return;
  200334. }
  200335. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  200336. png_save_uint_32(buf + 16, itemp);
  200337. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  200338. png_save_uint_32(buf + 20, itemp);
  200339. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  200340. {
  200341. png_warning(png_ptr, "Invalid cHRM blue point specified");
  200342. return;
  200343. }
  200344. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  200345. png_save_uint_32(buf + 24, itemp);
  200346. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  200347. png_save_uint_32(buf + 28, itemp);
  200348. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200349. }
  200350. #endif
  200351. #ifdef PNG_FIXED_POINT_SUPPORTED
  200352. void /* PRIVATE */
  200353. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  200354. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  200355. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  200356. png_fixed_point blue_y)
  200357. {
  200358. #ifdef PNG_USE_LOCAL_ARRAYS
  200359. PNG_cHRM;
  200360. #endif
  200361. png_byte buf[32];
  200362. png_debug(1, "in png_write_cHRM\n");
  200363. /* each value is saved in 1/100,000ths */
  200364. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  200365. {
  200366. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  200367. #if !defined(PNG_NO_CONSOLE_IO)
  200368. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  200369. #endif
  200370. return;
  200371. }
  200372. png_save_uint_32(buf, (png_uint_32)white_x);
  200373. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  200374. if (red_x + red_y > 100000L)
  200375. {
  200376. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  200377. return;
  200378. }
  200379. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  200380. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  200381. if (green_x + green_y > 100000L)
  200382. {
  200383. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  200384. return;
  200385. }
  200386. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  200387. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  200388. if (blue_x + blue_y > 100000L)
  200389. {
  200390. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  200391. return;
  200392. }
  200393. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  200394. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  200395. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200396. }
  200397. #endif
  200398. #endif
  200399. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  200400. /* write the tRNS chunk */
  200401. void /* PRIVATE */
  200402. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  200403. int num_trans, int color_type)
  200404. {
  200405. #ifdef PNG_USE_LOCAL_ARRAYS
  200406. PNG_tRNS;
  200407. #endif
  200408. png_byte buf[6];
  200409. png_debug(1, "in png_write_tRNS\n");
  200410. if (color_type == PNG_COLOR_TYPE_PALETTE)
  200411. {
  200412. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  200413. {
  200414. png_warning(png_ptr,"Invalid number of transparent colors specified");
  200415. return;
  200416. }
  200417. /* write the chunk out as it is */
  200418. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  200419. }
  200420. else if (color_type == PNG_COLOR_TYPE_GRAY)
  200421. {
  200422. /* one 16 bit value */
  200423. if(tran->gray >= (1 << png_ptr->bit_depth))
  200424. {
  200425. png_warning(png_ptr,
  200426. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  200427. return;
  200428. }
  200429. png_save_uint_16(buf, tran->gray);
  200430. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  200431. }
  200432. else if (color_type == PNG_COLOR_TYPE_RGB)
  200433. {
  200434. /* three 16 bit values */
  200435. png_save_uint_16(buf, tran->red);
  200436. png_save_uint_16(buf + 2, tran->green);
  200437. png_save_uint_16(buf + 4, tran->blue);
  200438. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  200439. {
  200440. png_warning(png_ptr,
  200441. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  200442. return;
  200443. }
  200444. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  200445. }
  200446. else
  200447. {
  200448. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  200449. }
  200450. }
  200451. #endif
  200452. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  200453. /* write the background chunk */
  200454. void /* PRIVATE */
  200455. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  200456. {
  200457. #ifdef PNG_USE_LOCAL_ARRAYS
  200458. PNG_bKGD;
  200459. #endif
  200460. png_byte buf[6];
  200461. png_debug(1, "in png_write_bKGD\n");
  200462. if (color_type == PNG_COLOR_TYPE_PALETTE)
  200463. {
  200464. if (
  200465. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200466. (png_ptr->num_palette ||
  200467. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  200468. #endif
  200469. back->index > png_ptr->num_palette)
  200470. {
  200471. png_warning(png_ptr, "Invalid background palette index");
  200472. return;
  200473. }
  200474. buf[0] = back->index;
  200475. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  200476. }
  200477. else if (color_type & PNG_COLOR_MASK_COLOR)
  200478. {
  200479. png_save_uint_16(buf, back->red);
  200480. png_save_uint_16(buf + 2, back->green);
  200481. png_save_uint_16(buf + 4, back->blue);
  200482. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  200483. {
  200484. png_warning(png_ptr,
  200485. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  200486. return;
  200487. }
  200488. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  200489. }
  200490. else
  200491. {
  200492. if(back->gray >= (1 << png_ptr->bit_depth))
  200493. {
  200494. png_warning(png_ptr,
  200495. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  200496. return;
  200497. }
  200498. png_save_uint_16(buf, back->gray);
  200499. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  200500. }
  200501. }
  200502. #endif
  200503. #if defined(PNG_WRITE_hIST_SUPPORTED)
  200504. /* write the histogram */
  200505. void /* PRIVATE */
  200506. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  200507. {
  200508. #ifdef PNG_USE_LOCAL_ARRAYS
  200509. PNG_hIST;
  200510. #endif
  200511. int i;
  200512. png_byte buf[3];
  200513. png_debug(1, "in png_write_hIST\n");
  200514. if (num_hist > (int)png_ptr->num_palette)
  200515. {
  200516. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  200517. png_ptr->num_palette);
  200518. png_warning(png_ptr, "Invalid number of histogram entries specified");
  200519. return;
  200520. }
  200521. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  200522. for (i = 0; i < num_hist; i++)
  200523. {
  200524. png_save_uint_16(buf, hist[i]);
  200525. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  200526. }
  200527. png_write_chunk_end(png_ptr);
  200528. }
  200529. #endif
  200530. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  200531. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  200532. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  200533. * and if invalid, correct the keyword rather than discarding the entire
  200534. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  200535. * length, forbids leading or trailing whitespace, multiple internal spaces,
  200536. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  200537. *
  200538. * The new_key is allocated to hold the corrected keyword and must be freed
  200539. * by the calling routine. This avoids problems with trying to write to
  200540. * static keywords without having to have duplicate copies of the strings.
  200541. */
  200542. png_size_t /* PRIVATE */
  200543. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  200544. {
  200545. png_size_t key_len;
  200546. png_charp kp, dp;
  200547. int kflag;
  200548. int kwarn=0;
  200549. png_debug(1, "in png_check_keyword\n");
  200550. *new_key = NULL;
  200551. if (key == NULL || (key_len = png_strlen(key)) == 0)
  200552. {
  200553. png_warning(png_ptr, "zero length keyword");
  200554. return ((png_size_t)0);
  200555. }
  200556. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  200557. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  200558. if (*new_key == NULL)
  200559. {
  200560. png_warning(png_ptr, "Out of memory while procesing keyword");
  200561. return ((png_size_t)0);
  200562. }
  200563. /* Replace non-printing characters with a blank and print a warning */
  200564. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  200565. {
  200566. if ((png_byte)*kp < 0x20 ||
  200567. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  200568. {
  200569. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200570. char msg[40];
  200571. png_snprintf(msg, 40,
  200572. "invalid keyword character 0x%02X", (png_byte)*kp);
  200573. png_warning(png_ptr, msg);
  200574. #else
  200575. png_warning(png_ptr, "invalid character in keyword");
  200576. #endif
  200577. *dp = ' ';
  200578. }
  200579. else
  200580. {
  200581. *dp = *kp;
  200582. }
  200583. }
  200584. *dp = '\0';
  200585. /* Remove any trailing white space. */
  200586. kp = *new_key + key_len - 1;
  200587. if (*kp == ' ')
  200588. {
  200589. png_warning(png_ptr, "trailing spaces removed from keyword");
  200590. while (*kp == ' ')
  200591. {
  200592. *(kp--) = '\0';
  200593. key_len--;
  200594. }
  200595. }
  200596. /* Remove any leading white space. */
  200597. kp = *new_key;
  200598. if (*kp == ' ')
  200599. {
  200600. png_warning(png_ptr, "leading spaces removed from keyword");
  200601. while (*kp == ' ')
  200602. {
  200603. kp++;
  200604. key_len--;
  200605. }
  200606. }
  200607. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  200608. /* Remove multiple internal spaces. */
  200609. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  200610. {
  200611. if (*kp == ' ' && kflag == 0)
  200612. {
  200613. *(dp++) = *kp;
  200614. kflag = 1;
  200615. }
  200616. else if (*kp == ' ')
  200617. {
  200618. key_len--;
  200619. kwarn=1;
  200620. }
  200621. else
  200622. {
  200623. *(dp++) = *kp;
  200624. kflag = 0;
  200625. }
  200626. }
  200627. *dp = '\0';
  200628. if(kwarn)
  200629. png_warning(png_ptr, "extra interior spaces removed from keyword");
  200630. if (key_len == 0)
  200631. {
  200632. png_free(png_ptr, *new_key);
  200633. *new_key=NULL;
  200634. png_warning(png_ptr, "Zero length keyword");
  200635. }
  200636. if (key_len > 79)
  200637. {
  200638. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  200639. new_key[79] = '\0';
  200640. key_len = 79;
  200641. }
  200642. return (key_len);
  200643. }
  200644. #endif
  200645. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  200646. /* write a tEXt chunk */
  200647. void /* PRIVATE */
  200648. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  200649. png_size_t text_len)
  200650. {
  200651. #ifdef PNG_USE_LOCAL_ARRAYS
  200652. PNG_tEXt;
  200653. #endif
  200654. png_size_t key_len;
  200655. png_charp new_key;
  200656. png_debug(1, "in png_write_tEXt\n");
  200657. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  200658. {
  200659. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  200660. return;
  200661. }
  200662. if (text == NULL || *text == '\0')
  200663. text_len = 0;
  200664. else
  200665. text_len = png_strlen(text);
  200666. /* make sure we include the 0 after the key */
  200667. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  200668. /*
  200669. * We leave it to the application to meet PNG-1.0 requirements on the
  200670. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  200671. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  200672. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  200673. */
  200674. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  200675. if (text_len)
  200676. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  200677. png_write_chunk_end(png_ptr);
  200678. png_free(png_ptr, new_key);
  200679. }
  200680. #endif
  200681. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  200682. /* write a compressed text chunk */
  200683. void /* PRIVATE */
  200684. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  200685. png_size_t text_len, int compression)
  200686. {
  200687. #ifdef PNG_USE_LOCAL_ARRAYS
  200688. PNG_zTXt;
  200689. #endif
  200690. png_size_t key_len;
  200691. char buf[1];
  200692. png_charp new_key;
  200693. compression_state comp;
  200694. png_debug(1, "in png_write_zTXt\n");
  200695. comp.num_output_ptr = 0;
  200696. comp.max_output_ptr = 0;
  200697. comp.output_ptr = NULL;
  200698. comp.input = NULL;
  200699. comp.input_len = 0;
  200700. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  200701. {
  200702. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  200703. return;
  200704. }
  200705. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  200706. {
  200707. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  200708. png_free(png_ptr, new_key);
  200709. return;
  200710. }
  200711. text_len = png_strlen(text);
  200712. /* compute the compressed data; do it now for the length */
  200713. text_len = png_text_compress(png_ptr, text, text_len, compression,
  200714. &comp);
  200715. /* write start of chunk */
  200716. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  200717. (key_len+text_len+2));
  200718. /* write key */
  200719. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  200720. png_free(png_ptr, new_key);
  200721. buf[0] = (png_byte)compression;
  200722. /* write compression */
  200723. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  200724. /* write the compressed data */
  200725. png_write_compressed_data_out(png_ptr, &comp);
  200726. /* close the chunk */
  200727. png_write_chunk_end(png_ptr);
  200728. }
  200729. #endif
  200730. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  200731. /* write an iTXt chunk */
  200732. void /* PRIVATE */
  200733. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  200734. png_charp lang, png_charp lang_key, png_charp text)
  200735. {
  200736. #ifdef PNG_USE_LOCAL_ARRAYS
  200737. PNG_iTXt;
  200738. #endif
  200739. png_size_t lang_len, key_len, lang_key_len, text_len;
  200740. png_charp new_lang, new_key;
  200741. png_byte cbuf[2];
  200742. compression_state comp;
  200743. png_debug(1, "in png_write_iTXt\n");
  200744. comp.num_output_ptr = 0;
  200745. comp.max_output_ptr = 0;
  200746. comp.output_ptr = NULL;
  200747. comp.input = NULL;
  200748. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  200749. {
  200750. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  200751. return;
  200752. }
  200753. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  200754. {
  200755. png_warning(png_ptr, "Empty language field in iTXt chunk");
  200756. new_lang = NULL;
  200757. lang_len = 0;
  200758. }
  200759. if (lang_key == NULL)
  200760. lang_key_len = 0;
  200761. else
  200762. lang_key_len = png_strlen(lang_key);
  200763. if (text == NULL)
  200764. text_len = 0;
  200765. else
  200766. text_len = png_strlen(text);
  200767. /* compute the compressed data; do it now for the length */
  200768. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  200769. &comp);
  200770. /* make sure we include the compression flag, the compression byte,
  200771. * and the NULs after the key, lang, and lang_key parts */
  200772. png_write_chunk_start(png_ptr, png_iTXt,
  200773. (png_uint_32)(
  200774. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  200775. + key_len
  200776. + lang_len
  200777. + lang_key_len
  200778. + text_len));
  200779. /*
  200780. * We leave it to the application to meet PNG-1.0 requirements on the
  200781. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  200782. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  200783. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  200784. */
  200785. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  200786. /* set the compression flag */
  200787. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  200788. compression == PNG_TEXT_COMPRESSION_NONE)
  200789. cbuf[0] = 0;
  200790. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  200791. cbuf[0] = 1;
  200792. /* set the compression method */
  200793. cbuf[1] = 0;
  200794. png_write_chunk_data(png_ptr, cbuf, 2);
  200795. cbuf[0] = 0;
  200796. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  200797. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  200798. png_write_compressed_data_out(png_ptr, &comp);
  200799. png_write_chunk_end(png_ptr);
  200800. png_free(png_ptr, new_key);
  200801. if (new_lang)
  200802. png_free(png_ptr, new_lang);
  200803. }
  200804. #endif
  200805. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  200806. /* write the oFFs chunk */
  200807. void /* PRIVATE */
  200808. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  200809. int unit_type)
  200810. {
  200811. #ifdef PNG_USE_LOCAL_ARRAYS
  200812. PNG_oFFs;
  200813. #endif
  200814. png_byte buf[9];
  200815. png_debug(1, "in png_write_oFFs\n");
  200816. if (unit_type >= PNG_OFFSET_LAST)
  200817. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  200818. png_save_int_32(buf, x_offset);
  200819. png_save_int_32(buf + 4, y_offset);
  200820. buf[8] = (png_byte)unit_type;
  200821. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  200822. }
  200823. #endif
  200824. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  200825. /* write the pCAL chunk (described in the PNG extensions document) */
  200826. void /* PRIVATE */
  200827. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  200828. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  200829. {
  200830. #ifdef PNG_USE_LOCAL_ARRAYS
  200831. PNG_pCAL;
  200832. #endif
  200833. png_size_t purpose_len, units_len, total_len;
  200834. png_uint_32p params_len;
  200835. png_byte buf[10];
  200836. png_charp new_purpose;
  200837. int i;
  200838. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  200839. if (type >= PNG_EQUATION_LAST)
  200840. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  200841. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  200842. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  200843. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  200844. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  200845. total_len = purpose_len + units_len + 10;
  200846. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  200847. *png_sizeof(png_uint_32)));
  200848. /* Find the length of each parameter, making sure we don't count the
  200849. null terminator for the last parameter. */
  200850. for (i = 0; i < nparams; i++)
  200851. {
  200852. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  200853. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  200854. total_len += (png_size_t)params_len[i];
  200855. }
  200856. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  200857. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  200858. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  200859. png_save_int_32(buf, X0);
  200860. png_save_int_32(buf + 4, X1);
  200861. buf[8] = (png_byte)type;
  200862. buf[9] = (png_byte)nparams;
  200863. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  200864. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  200865. png_free(png_ptr, new_purpose);
  200866. for (i = 0; i < nparams; i++)
  200867. {
  200868. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  200869. (png_size_t)params_len[i]);
  200870. }
  200871. png_free(png_ptr, params_len);
  200872. png_write_chunk_end(png_ptr);
  200873. }
  200874. #endif
  200875. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  200876. /* write the sCAL chunk */
  200877. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  200878. void /* PRIVATE */
  200879. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  200880. {
  200881. #ifdef PNG_USE_LOCAL_ARRAYS
  200882. PNG_sCAL;
  200883. #endif
  200884. char buf[64];
  200885. png_size_t total_len;
  200886. png_debug(1, "in png_write_sCAL\n");
  200887. buf[0] = (char)unit;
  200888. #if defined(_WIN32_WCE)
  200889. /* sprintf() function is not supported on WindowsCE */
  200890. {
  200891. wchar_t wc_buf[32];
  200892. size_t wc_len;
  200893. swprintf(wc_buf, TEXT("%12.12e"), width);
  200894. wc_len = wcslen(wc_buf);
  200895. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  200896. total_len = wc_len + 2;
  200897. swprintf(wc_buf, TEXT("%12.12e"), height);
  200898. wc_len = wcslen(wc_buf);
  200899. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  200900. NULL, NULL);
  200901. total_len += wc_len;
  200902. }
  200903. #else
  200904. png_snprintf(buf + 1, 63, "%12.12e", width);
  200905. total_len = 1 + png_strlen(buf + 1) + 1;
  200906. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  200907. total_len += png_strlen(buf + total_len);
  200908. #endif
  200909. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  200910. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  200911. }
  200912. #else
  200913. #ifdef PNG_FIXED_POINT_SUPPORTED
  200914. void /* PRIVATE */
  200915. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  200916. png_charp height)
  200917. {
  200918. #ifdef PNG_USE_LOCAL_ARRAYS
  200919. PNG_sCAL;
  200920. #endif
  200921. png_byte buf[64];
  200922. png_size_t wlen, hlen, total_len;
  200923. png_debug(1, "in png_write_sCAL_s\n");
  200924. wlen = png_strlen(width);
  200925. hlen = png_strlen(height);
  200926. total_len = wlen + hlen + 2;
  200927. if (total_len > 64)
  200928. {
  200929. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  200930. return;
  200931. }
  200932. buf[0] = (png_byte)unit;
  200933. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  200934. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  200935. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  200936. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  200937. }
  200938. #endif
  200939. #endif
  200940. #endif
  200941. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  200942. /* write the pHYs chunk */
  200943. void /* PRIVATE */
  200944. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  200945. png_uint_32 y_pixels_per_unit,
  200946. int unit_type)
  200947. {
  200948. #ifdef PNG_USE_LOCAL_ARRAYS
  200949. PNG_pHYs;
  200950. #endif
  200951. png_byte buf[9];
  200952. png_debug(1, "in png_write_pHYs\n");
  200953. if (unit_type >= PNG_RESOLUTION_LAST)
  200954. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  200955. png_save_uint_32(buf, x_pixels_per_unit);
  200956. png_save_uint_32(buf + 4, y_pixels_per_unit);
  200957. buf[8] = (png_byte)unit_type;
  200958. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  200959. }
  200960. #endif
  200961. #if defined(PNG_WRITE_tIME_SUPPORTED)
  200962. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  200963. * or png_convert_from_time_t(), or fill in the structure yourself.
  200964. */
  200965. void /* PRIVATE */
  200966. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  200967. {
  200968. #ifdef PNG_USE_LOCAL_ARRAYS
  200969. PNG_tIME;
  200970. #endif
  200971. png_byte buf[7];
  200972. png_debug(1, "in png_write_tIME\n");
  200973. if (mod_time->month > 12 || mod_time->month < 1 ||
  200974. mod_time->day > 31 || mod_time->day < 1 ||
  200975. mod_time->hour > 23 || mod_time->second > 60)
  200976. {
  200977. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  200978. return;
  200979. }
  200980. png_save_uint_16(buf, mod_time->year);
  200981. buf[2] = mod_time->month;
  200982. buf[3] = mod_time->day;
  200983. buf[4] = mod_time->hour;
  200984. buf[5] = mod_time->minute;
  200985. buf[6] = mod_time->second;
  200986. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  200987. }
  200988. #endif
  200989. /* initializes the row writing capability of libpng */
  200990. void /* PRIVATE */
  200991. png_write_start_row(png_structp png_ptr)
  200992. {
  200993. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200994. #ifdef PNG_USE_LOCAL_ARRAYS
  200995. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  200996. /* start of interlace block */
  200997. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  200998. /* offset to next interlace block */
  200999. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201000. /* start of interlace block in the y direction */
  201001. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201002. /* offset to next interlace block in the y direction */
  201003. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201004. #endif
  201005. #endif
  201006. png_size_t buf_size;
  201007. png_debug(1, "in png_write_start_row\n");
  201008. buf_size = (png_size_t)(PNG_ROWBYTES(
  201009. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201010. /* set up row buffer */
  201011. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201012. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201013. #ifndef PNG_NO_WRITE_FILTERING
  201014. /* set up filtering buffer, if using this filter */
  201015. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201016. {
  201017. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201018. (png_ptr->rowbytes + 1));
  201019. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201020. }
  201021. /* We only need to keep the previous row if we are using one of these. */
  201022. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201023. {
  201024. /* set up previous row buffer */
  201025. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201026. png_memset(png_ptr->prev_row, 0, buf_size);
  201027. if (png_ptr->do_filter & PNG_FILTER_UP)
  201028. {
  201029. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201030. (png_ptr->rowbytes + 1));
  201031. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201032. }
  201033. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201034. {
  201035. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201036. (png_ptr->rowbytes + 1));
  201037. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201038. }
  201039. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201040. {
  201041. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201042. (png_ptr->rowbytes + 1));
  201043. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201044. }
  201045. #endif /* PNG_NO_WRITE_FILTERING */
  201046. }
  201047. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201048. /* if interlaced, we need to set up width and height of pass */
  201049. if (png_ptr->interlaced)
  201050. {
  201051. if (!(png_ptr->transformations & PNG_INTERLACE))
  201052. {
  201053. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201054. png_pass_ystart[0]) / png_pass_yinc[0];
  201055. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201056. png_pass_start[0]) / png_pass_inc[0];
  201057. }
  201058. else
  201059. {
  201060. png_ptr->num_rows = png_ptr->height;
  201061. png_ptr->usr_width = png_ptr->width;
  201062. }
  201063. }
  201064. else
  201065. #endif
  201066. {
  201067. png_ptr->num_rows = png_ptr->height;
  201068. png_ptr->usr_width = png_ptr->width;
  201069. }
  201070. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201071. png_ptr->zstream.next_out = png_ptr->zbuf;
  201072. }
  201073. /* Internal use only. Called when finished processing a row of data. */
  201074. void /* PRIVATE */
  201075. png_write_finish_row(png_structp png_ptr)
  201076. {
  201077. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201078. #ifdef PNG_USE_LOCAL_ARRAYS
  201079. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201080. /* start of interlace block */
  201081. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201082. /* offset to next interlace block */
  201083. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201084. /* start of interlace block in the y direction */
  201085. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201086. /* offset to next interlace block in the y direction */
  201087. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201088. #endif
  201089. #endif
  201090. int ret;
  201091. png_debug(1, "in png_write_finish_row\n");
  201092. /* next row */
  201093. png_ptr->row_number++;
  201094. /* see if we are done */
  201095. if (png_ptr->row_number < png_ptr->num_rows)
  201096. return;
  201097. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201098. /* if interlaced, go to next pass */
  201099. if (png_ptr->interlaced)
  201100. {
  201101. png_ptr->row_number = 0;
  201102. if (png_ptr->transformations & PNG_INTERLACE)
  201103. {
  201104. png_ptr->pass++;
  201105. }
  201106. else
  201107. {
  201108. /* loop until we find a non-zero width or height pass */
  201109. do
  201110. {
  201111. png_ptr->pass++;
  201112. if (png_ptr->pass >= 7)
  201113. break;
  201114. png_ptr->usr_width = (png_ptr->width +
  201115. png_pass_inc[png_ptr->pass] - 1 -
  201116. png_pass_start[png_ptr->pass]) /
  201117. png_pass_inc[png_ptr->pass];
  201118. png_ptr->num_rows = (png_ptr->height +
  201119. png_pass_yinc[png_ptr->pass] - 1 -
  201120. png_pass_ystart[png_ptr->pass]) /
  201121. png_pass_yinc[png_ptr->pass];
  201122. if (png_ptr->transformations & PNG_INTERLACE)
  201123. break;
  201124. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201125. }
  201126. /* reset the row above the image for the next pass */
  201127. if (png_ptr->pass < 7)
  201128. {
  201129. if (png_ptr->prev_row != NULL)
  201130. png_memset(png_ptr->prev_row, 0,
  201131. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  201132. png_ptr->usr_bit_depth,png_ptr->width))+1);
  201133. return;
  201134. }
  201135. }
  201136. #endif
  201137. /* if we get here, we've just written the last row, so we need
  201138. to flush the compressor */
  201139. do
  201140. {
  201141. /* tell the compressor we are done */
  201142. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201143. /* check for an error */
  201144. if (ret == Z_OK)
  201145. {
  201146. /* check to see if we need more room */
  201147. if (!(png_ptr->zstream.avail_out))
  201148. {
  201149. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  201150. png_ptr->zstream.next_out = png_ptr->zbuf;
  201151. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201152. }
  201153. }
  201154. else if (ret != Z_STREAM_END)
  201155. {
  201156. if (png_ptr->zstream.msg != NULL)
  201157. png_error(png_ptr, png_ptr->zstream.msg);
  201158. else
  201159. png_error(png_ptr, "zlib error");
  201160. }
  201161. } while (ret != Z_STREAM_END);
  201162. /* write any extra space */
  201163. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201164. {
  201165. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  201166. png_ptr->zstream.avail_out);
  201167. }
  201168. deflateReset(&png_ptr->zstream);
  201169. png_ptr->zstream.data_type = Z_BINARY;
  201170. }
  201171. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  201172. /* Pick out the correct pixels for the interlace pass.
  201173. * The basic idea here is to go through the row with a source
  201174. * pointer and a destination pointer (sp and dp), and copy the
  201175. * correct pixels for the pass. As the row gets compacted,
  201176. * sp will always be >= dp, so we should never overwrite anything.
  201177. * See the default: case for the easiest code to understand.
  201178. */
  201179. void /* PRIVATE */
  201180. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  201181. {
  201182. #ifdef PNG_USE_LOCAL_ARRAYS
  201183. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201184. /* start of interlace block */
  201185. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201186. /* offset to next interlace block */
  201187. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201188. #endif
  201189. png_debug(1, "in png_do_write_interlace\n");
  201190. /* we don't have to do anything on the last pass (6) */
  201191. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201192. if (row != NULL && row_info != NULL && pass < 6)
  201193. #else
  201194. if (pass < 6)
  201195. #endif
  201196. {
  201197. /* each pixel depth is handled separately */
  201198. switch (row_info->pixel_depth)
  201199. {
  201200. case 1:
  201201. {
  201202. png_bytep sp;
  201203. png_bytep dp;
  201204. int shift;
  201205. int d;
  201206. int value;
  201207. png_uint_32 i;
  201208. png_uint_32 row_width = row_info->width;
  201209. dp = row;
  201210. d = 0;
  201211. shift = 7;
  201212. for (i = png_pass_start[pass]; i < row_width;
  201213. i += png_pass_inc[pass])
  201214. {
  201215. sp = row + (png_size_t)(i >> 3);
  201216. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  201217. d |= (value << shift);
  201218. if (shift == 0)
  201219. {
  201220. shift = 7;
  201221. *dp++ = (png_byte)d;
  201222. d = 0;
  201223. }
  201224. else
  201225. shift--;
  201226. }
  201227. if (shift != 7)
  201228. *dp = (png_byte)d;
  201229. break;
  201230. }
  201231. case 2:
  201232. {
  201233. png_bytep sp;
  201234. png_bytep dp;
  201235. int shift;
  201236. int d;
  201237. int value;
  201238. png_uint_32 i;
  201239. png_uint_32 row_width = row_info->width;
  201240. dp = row;
  201241. shift = 6;
  201242. d = 0;
  201243. for (i = png_pass_start[pass]; i < row_width;
  201244. i += png_pass_inc[pass])
  201245. {
  201246. sp = row + (png_size_t)(i >> 2);
  201247. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  201248. d |= (value << shift);
  201249. if (shift == 0)
  201250. {
  201251. shift = 6;
  201252. *dp++ = (png_byte)d;
  201253. d = 0;
  201254. }
  201255. else
  201256. shift -= 2;
  201257. }
  201258. if (shift != 6)
  201259. *dp = (png_byte)d;
  201260. break;
  201261. }
  201262. case 4:
  201263. {
  201264. png_bytep sp;
  201265. png_bytep dp;
  201266. int shift;
  201267. int d;
  201268. int value;
  201269. png_uint_32 i;
  201270. png_uint_32 row_width = row_info->width;
  201271. dp = row;
  201272. shift = 4;
  201273. d = 0;
  201274. for (i = png_pass_start[pass]; i < row_width;
  201275. i += png_pass_inc[pass])
  201276. {
  201277. sp = row + (png_size_t)(i >> 1);
  201278. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  201279. d |= (value << shift);
  201280. if (shift == 0)
  201281. {
  201282. shift = 4;
  201283. *dp++ = (png_byte)d;
  201284. d = 0;
  201285. }
  201286. else
  201287. shift -= 4;
  201288. }
  201289. if (shift != 4)
  201290. *dp = (png_byte)d;
  201291. break;
  201292. }
  201293. default:
  201294. {
  201295. png_bytep sp;
  201296. png_bytep dp;
  201297. png_uint_32 i;
  201298. png_uint_32 row_width = row_info->width;
  201299. png_size_t pixel_bytes;
  201300. /* start at the beginning */
  201301. dp = row;
  201302. /* find out how many bytes each pixel takes up */
  201303. pixel_bytes = (row_info->pixel_depth >> 3);
  201304. /* loop through the row, only looking at the pixels that
  201305. matter */
  201306. for (i = png_pass_start[pass]; i < row_width;
  201307. i += png_pass_inc[pass])
  201308. {
  201309. /* find out where the original pixel is */
  201310. sp = row + (png_size_t)i * pixel_bytes;
  201311. /* move the pixel */
  201312. if (dp != sp)
  201313. png_memcpy(dp, sp, pixel_bytes);
  201314. /* next pixel */
  201315. dp += pixel_bytes;
  201316. }
  201317. break;
  201318. }
  201319. }
  201320. /* set new row width */
  201321. row_info->width = (row_info->width +
  201322. png_pass_inc[pass] - 1 -
  201323. png_pass_start[pass]) /
  201324. png_pass_inc[pass];
  201325. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  201326. row_info->width);
  201327. }
  201328. }
  201329. #endif
  201330. /* This filters the row, chooses which filter to use, if it has not already
  201331. * been specified by the application, and then writes the row out with the
  201332. * chosen filter.
  201333. */
  201334. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  201335. #define PNG_HISHIFT 10
  201336. #define PNG_LOMASK ((png_uint_32)0xffffL)
  201337. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  201338. void /* PRIVATE */
  201339. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  201340. {
  201341. png_bytep best_row;
  201342. #ifndef PNG_NO_WRITE_FILTER
  201343. png_bytep prev_row, row_buf;
  201344. png_uint_32 mins, bpp;
  201345. png_byte filter_to_do = png_ptr->do_filter;
  201346. png_uint_32 row_bytes = row_info->rowbytes;
  201347. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201348. int num_p_filters = (int)png_ptr->num_prev_filters;
  201349. #endif
  201350. png_debug(1, "in png_write_find_filter\n");
  201351. /* find out how many bytes offset each pixel is */
  201352. bpp = (row_info->pixel_depth + 7) >> 3;
  201353. prev_row = png_ptr->prev_row;
  201354. #endif
  201355. best_row = png_ptr->row_buf;
  201356. #ifndef PNG_NO_WRITE_FILTER
  201357. row_buf = best_row;
  201358. mins = PNG_MAXSUM;
  201359. /* The prediction method we use is to find which method provides the
  201360. * smallest value when summing the absolute values of the distances
  201361. * from zero, using anything >= 128 as negative numbers. This is known
  201362. * as the "minimum sum of absolute differences" heuristic. Other
  201363. * heuristics are the "weighted minimum sum of absolute differences"
  201364. * (experimental and can in theory improve compression), and the "zlib
  201365. * predictive" method (not implemented yet), which does test compressions
  201366. * of lines using different filter methods, and then chooses the
  201367. * (series of) filter(s) that give minimum compressed data size (VERY
  201368. * computationally expensive).
  201369. *
  201370. * GRR 980525: consider also
  201371. * (1) minimum sum of absolute differences from running average (i.e.,
  201372. * keep running sum of non-absolute differences & count of bytes)
  201373. * [track dispersion, too? restart average if dispersion too large?]
  201374. * (1b) minimum sum of absolute differences from sliding average, probably
  201375. * with window size <= deflate window (usually 32K)
  201376. * (2) minimum sum of squared differences from zero or running average
  201377. * (i.e., ~ root-mean-square approach)
  201378. */
  201379. /* We don't need to test the 'no filter' case if this is the only filter
  201380. * that has been chosen, as it doesn't actually do anything to the data.
  201381. */
  201382. if ((filter_to_do & PNG_FILTER_NONE) &&
  201383. filter_to_do != PNG_FILTER_NONE)
  201384. {
  201385. png_bytep rp;
  201386. png_uint_32 sum = 0;
  201387. png_uint_32 i;
  201388. int v;
  201389. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  201390. {
  201391. v = *rp;
  201392. sum += (v < 128) ? v : 256 - v;
  201393. }
  201394. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201395. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201396. {
  201397. png_uint_32 sumhi, sumlo;
  201398. int j;
  201399. sumlo = sum & PNG_LOMASK;
  201400. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  201401. /* Reduce the sum if we match any of the previous rows */
  201402. for (j = 0; j < num_p_filters; j++)
  201403. {
  201404. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  201405. {
  201406. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201407. PNG_WEIGHT_SHIFT;
  201408. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201409. PNG_WEIGHT_SHIFT;
  201410. }
  201411. }
  201412. /* Factor in the cost of this filter (this is here for completeness,
  201413. * but it makes no sense to have a "cost" for the NONE filter, as
  201414. * it has the minimum possible computational cost - none).
  201415. */
  201416. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  201417. PNG_COST_SHIFT;
  201418. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  201419. PNG_COST_SHIFT;
  201420. if (sumhi > PNG_HIMASK)
  201421. sum = PNG_MAXSUM;
  201422. else
  201423. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201424. }
  201425. #endif
  201426. mins = sum;
  201427. }
  201428. /* sub filter */
  201429. if (filter_to_do == PNG_FILTER_SUB)
  201430. /* it's the only filter so no testing is needed */
  201431. {
  201432. png_bytep rp, lp, dp;
  201433. png_uint_32 i;
  201434. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  201435. i++, rp++, dp++)
  201436. {
  201437. *dp = *rp;
  201438. }
  201439. for (lp = row_buf + 1; i < row_bytes;
  201440. i++, rp++, lp++, dp++)
  201441. {
  201442. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  201443. }
  201444. best_row = png_ptr->sub_row;
  201445. }
  201446. else if (filter_to_do & PNG_FILTER_SUB)
  201447. {
  201448. png_bytep rp, dp, lp;
  201449. png_uint_32 sum = 0, lmins = mins;
  201450. png_uint_32 i;
  201451. int v;
  201452. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201453. /* We temporarily increase the "minimum sum" by the factor we
  201454. * would reduce the sum of this filter, so that we can do the
  201455. * early exit comparison without scaling the sum each time.
  201456. */
  201457. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201458. {
  201459. int j;
  201460. png_uint_32 lmhi, lmlo;
  201461. lmlo = lmins & PNG_LOMASK;
  201462. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201463. for (j = 0; j < num_p_filters; j++)
  201464. {
  201465. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  201466. {
  201467. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201468. PNG_WEIGHT_SHIFT;
  201469. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201470. PNG_WEIGHT_SHIFT;
  201471. }
  201472. }
  201473. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201474. PNG_COST_SHIFT;
  201475. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201476. PNG_COST_SHIFT;
  201477. if (lmhi > PNG_HIMASK)
  201478. lmins = PNG_MAXSUM;
  201479. else
  201480. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201481. }
  201482. #endif
  201483. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  201484. i++, rp++, dp++)
  201485. {
  201486. v = *dp = *rp;
  201487. sum += (v < 128) ? v : 256 - v;
  201488. }
  201489. for (lp = row_buf + 1; i < row_bytes;
  201490. i++, rp++, lp++, dp++)
  201491. {
  201492. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  201493. sum += (v < 128) ? v : 256 - v;
  201494. if (sum > lmins) /* We are already worse, don't continue. */
  201495. break;
  201496. }
  201497. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201498. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201499. {
  201500. int j;
  201501. png_uint_32 sumhi, sumlo;
  201502. sumlo = sum & PNG_LOMASK;
  201503. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201504. for (j = 0; j < num_p_filters; j++)
  201505. {
  201506. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  201507. {
  201508. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  201509. PNG_WEIGHT_SHIFT;
  201510. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  201511. PNG_WEIGHT_SHIFT;
  201512. }
  201513. }
  201514. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201515. PNG_COST_SHIFT;
  201516. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201517. PNG_COST_SHIFT;
  201518. if (sumhi > PNG_HIMASK)
  201519. sum = PNG_MAXSUM;
  201520. else
  201521. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201522. }
  201523. #endif
  201524. if (sum < mins)
  201525. {
  201526. mins = sum;
  201527. best_row = png_ptr->sub_row;
  201528. }
  201529. }
  201530. /* up filter */
  201531. if (filter_to_do == PNG_FILTER_UP)
  201532. {
  201533. png_bytep rp, dp, pp;
  201534. png_uint_32 i;
  201535. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  201536. pp = prev_row + 1; i < row_bytes;
  201537. i++, rp++, pp++, dp++)
  201538. {
  201539. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  201540. }
  201541. best_row = png_ptr->up_row;
  201542. }
  201543. else if (filter_to_do & PNG_FILTER_UP)
  201544. {
  201545. png_bytep rp, dp, pp;
  201546. png_uint_32 sum = 0, lmins = mins;
  201547. png_uint_32 i;
  201548. int v;
  201549. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201550. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201551. {
  201552. int j;
  201553. png_uint_32 lmhi, lmlo;
  201554. lmlo = lmins & PNG_LOMASK;
  201555. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201556. for (j = 0; j < num_p_filters; j++)
  201557. {
  201558. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  201559. {
  201560. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201561. PNG_WEIGHT_SHIFT;
  201562. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201563. PNG_WEIGHT_SHIFT;
  201564. }
  201565. }
  201566. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  201567. PNG_COST_SHIFT;
  201568. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  201569. PNG_COST_SHIFT;
  201570. if (lmhi > PNG_HIMASK)
  201571. lmins = PNG_MAXSUM;
  201572. else
  201573. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201574. }
  201575. #endif
  201576. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  201577. pp = prev_row + 1; i < row_bytes; i++)
  201578. {
  201579. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  201580. sum += (v < 128) ? v : 256 - v;
  201581. if (sum > lmins) /* We are already worse, don't continue. */
  201582. break;
  201583. }
  201584. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201585. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201586. {
  201587. int j;
  201588. png_uint_32 sumhi, sumlo;
  201589. sumlo = sum & PNG_LOMASK;
  201590. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201591. for (j = 0; j < num_p_filters; j++)
  201592. {
  201593. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  201594. {
  201595. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201596. PNG_WEIGHT_SHIFT;
  201597. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201598. PNG_WEIGHT_SHIFT;
  201599. }
  201600. }
  201601. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  201602. PNG_COST_SHIFT;
  201603. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  201604. PNG_COST_SHIFT;
  201605. if (sumhi > PNG_HIMASK)
  201606. sum = PNG_MAXSUM;
  201607. else
  201608. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201609. }
  201610. #endif
  201611. if (sum < mins)
  201612. {
  201613. mins = sum;
  201614. best_row = png_ptr->up_row;
  201615. }
  201616. }
  201617. /* avg filter */
  201618. if (filter_to_do == PNG_FILTER_AVG)
  201619. {
  201620. png_bytep rp, dp, pp, lp;
  201621. png_uint_32 i;
  201622. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  201623. pp = prev_row + 1; i < bpp; i++)
  201624. {
  201625. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  201626. }
  201627. for (lp = row_buf + 1; i < row_bytes; i++)
  201628. {
  201629. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  201630. & 0xff);
  201631. }
  201632. best_row = png_ptr->avg_row;
  201633. }
  201634. else if (filter_to_do & PNG_FILTER_AVG)
  201635. {
  201636. png_bytep rp, dp, pp, lp;
  201637. png_uint_32 sum = 0, lmins = mins;
  201638. png_uint_32 i;
  201639. int v;
  201640. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201641. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201642. {
  201643. int j;
  201644. png_uint_32 lmhi, lmlo;
  201645. lmlo = lmins & PNG_LOMASK;
  201646. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201647. for (j = 0; j < num_p_filters; j++)
  201648. {
  201649. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  201650. {
  201651. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201652. PNG_WEIGHT_SHIFT;
  201653. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201654. PNG_WEIGHT_SHIFT;
  201655. }
  201656. }
  201657. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201658. PNG_COST_SHIFT;
  201659. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201660. PNG_COST_SHIFT;
  201661. if (lmhi > PNG_HIMASK)
  201662. lmins = PNG_MAXSUM;
  201663. else
  201664. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201665. }
  201666. #endif
  201667. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  201668. pp = prev_row + 1; i < bpp; i++)
  201669. {
  201670. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  201671. sum += (v < 128) ? v : 256 - v;
  201672. }
  201673. for (lp = row_buf + 1; i < row_bytes; i++)
  201674. {
  201675. v = *dp++ =
  201676. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  201677. sum += (v < 128) ? v : 256 - v;
  201678. if (sum > lmins) /* We are already worse, don't continue. */
  201679. break;
  201680. }
  201681. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201682. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201683. {
  201684. int j;
  201685. png_uint_32 sumhi, sumlo;
  201686. sumlo = sum & PNG_LOMASK;
  201687. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201688. for (j = 0; j < num_p_filters; j++)
  201689. {
  201690. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  201691. {
  201692. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201693. PNG_WEIGHT_SHIFT;
  201694. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201695. PNG_WEIGHT_SHIFT;
  201696. }
  201697. }
  201698. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201699. PNG_COST_SHIFT;
  201700. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201701. PNG_COST_SHIFT;
  201702. if (sumhi > PNG_HIMASK)
  201703. sum = PNG_MAXSUM;
  201704. else
  201705. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201706. }
  201707. #endif
  201708. if (sum < mins)
  201709. {
  201710. mins = sum;
  201711. best_row = png_ptr->avg_row;
  201712. }
  201713. }
  201714. /* Paeth filter */
  201715. if (filter_to_do == PNG_FILTER_PAETH)
  201716. {
  201717. png_bytep rp, dp, pp, cp, lp;
  201718. png_uint_32 i;
  201719. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  201720. pp = prev_row + 1; i < bpp; i++)
  201721. {
  201722. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  201723. }
  201724. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  201725. {
  201726. int a, b, c, pa, pb, pc, p;
  201727. b = *pp++;
  201728. c = *cp++;
  201729. a = *lp++;
  201730. p = b - c;
  201731. pc = a - c;
  201732. #ifdef PNG_USE_ABS
  201733. pa = abs(p);
  201734. pb = abs(pc);
  201735. pc = abs(p + pc);
  201736. #else
  201737. pa = p < 0 ? -p : p;
  201738. pb = pc < 0 ? -pc : pc;
  201739. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  201740. #endif
  201741. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  201742. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  201743. }
  201744. best_row = png_ptr->paeth_row;
  201745. }
  201746. else if (filter_to_do & PNG_FILTER_PAETH)
  201747. {
  201748. png_bytep rp, dp, pp, cp, lp;
  201749. png_uint_32 sum = 0, lmins = mins;
  201750. png_uint_32 i;
  201751. int v;
  201752. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201753. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201754. {
  201755. int j;
  201756. png_uint_32 lmhi, lmlo;
  201757. lmlo = lmins & PNG_LOMASK;
  201758. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201759. for (j = 0; j < num_p_filters; j++)
  201760. {
  201761. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  201762. {
  201763. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201764. PNG_WEIGHT_SHIFT;
  201765. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201766. PNG_WEIGHT_SHIFT;
  201767. }
  201768. }
  201769. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  201770. PNG_COST_SHIFT;
  201771. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  201772. PNG_COST_SHIFT;
  201773. if (lmhi > PNG_HIMASK)
  201774. lmins = PNG_MAXSUM;
  201775. else
  201776. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201777. }
  201778. #endif
  201779. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  201780. pp = prev_row + 1; i < bpp; i++)
  201781. {
  201782. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  201783. sum += (v < 128) ? v : 256 - v;
  201784. }
  201785. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  201786. {
  201787. int a, b, c, pa, pb, pc, p;
  201788. b = *pp++;
  201789. c = *cp++;
  201790. a = *lp++;
  201791. #ifndef PNG_SLOW_PAETH
  201792. p = b - c;
  201793. pc = a - c;
  201794. #ifdef PNG_USE_ABS
  201795. pa = abs(p);
  201796. pb = abs(pc);
  201797. pc = abs(p + pc);
  201798. #else
  201799. pa = p < 0 ? -p : p;
  201800. pb = pc < 0 ? -pc : pc;
  201801. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  201802. #endif
  201803. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  201804. #else /* PNG_SLOW_PAETH */
  201805. p = a + b - c;
  201806. pa = abs(p - a);
  201807. pb = abs(p - b);
  201808. pc = abs(p - c);
  201809. if (pa <= pb && pa <= pc)
  201810. p = a;
  201811. else if (pb <= pc)
  201812. p = b;
  201813. else
  201814. p = c;
  201815. #endif /* PNG_SLOW_PAETH */
  201816. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  201817. sum += (v < 128) ? v : 256 - v;
  201818. if (sum > lmins) /* We are already worse, don't continue. */
  201819. break;
  201820. }
  201821. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201822. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201823. {
  201824. int j;
  201825. png_uint_32 sumhi, sumlo;
  201826. sumlo = sum & PNG_LOMASK;
  201827. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201828. for (j = 0; j < num_p_filters; j++)
  201829. {
  201830. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  201831. {
  201832. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201833. PNG_WEIGHT_SHIFT;
  201834. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201835. PNG_WEIGHT_SHIFT;
  201836. }
  201837. }
  201838. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  201839. PNG_COST_SHIFT;
  201840. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  201841. PNG_COST_SHIFT;
  201842. if (sumhi > PNG_HIMASK)
  201843. sum = PNG_MAXSUM;
  201844. else
  201845. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201846. }
  201847. #endif
  201848. if (sum < mins)
  201849. {
  201850. best_row = png_ptr->paeth_row;
  201851. }
  201852. }
  201853. #endif /* PNG_NO_WRITE_FILTER */
  201854. /* Do the actual writing of the filtered row data from the chosen filter. */
  201855. png_write_filtered_row(png_ptr, best_row);
  201856. #ifndef PNG_NO_WRITE_FILTER
  201857. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201858. /* Save the type of filter we picked this time for future calculations */
  201859. if (png_ptr->num_prev_filters > 0)
  201860. {
  201861. int j;
  201862. for (j = 1; j < num_p_filters; j++)
  201863. {
  201864. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  201865. }
  201866. png_ptr->prev_filters[j] = best_row[0];
  201867. }
  201868. #endif
  201869. #endif /* PNG_NO_WRITE_FILTER */
  201870. }
  201871. /* Do the actual writing of a previously filtered row. */
  201872. void /* PRIVATE */
  201873. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  201874. {
  201875. png_debug(1, "in png_write_filtered_row\n");
  201876. png_debug1(2, "filter = %d\n", filtered_row[0]);
  201877. /* set up the zlib input buffer */
  201878. png_ptr->zstream.next_in = filtered_row;
  201879. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  201880. /* repeat until we have compressed all the data */
  201881. do
  201882. {
  201883. int ret; /* return of zlib */
  201884. /* compress the data */
  201885. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  201886. /* check for compression errors */
  201887. if (ret != Z_OK)
  201888. {
  201889. if (png_ptr->zstream.msg != NULL)
  201890. png_error(png_ptr, png_ptr->zstream.msg);
  201891. else
  201892. png_error(png_ptr, "zlib error");
  201893. }
  201894. /* see if it is time to write another IDAT */
  201895. if (!(png_ptr->zstream.avail_out))
  201896. {
  201897. /* write the IDAT and reset the zlib output buffer */
  201898. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  201899. png_ptr->zstream.next_out = png_ptr->zbuf;
  201900. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201901. }
  201902. /* repeat until all data has been compressed */
  201903. } while (png_ptr->zstream.avail_in);
  201904. /* swap the current and previous rows */
  201905. if (png_ptr->prev_row != NULL)
  201906. {
  201907. png_bytep tptr;
  201908. tptr = png_ptr->prev_row;
  201909. png_ptr->prev_row = png_ptr->row_buf;
  201910. png_ptr->row_buf = tptr;
  201911. }
  201912. /* finish row - updates counters and flushes zlib if last row */
  201913. png_write_finish_row(png_ptr);
  201914. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  201915. png_ptr->flush_rows++;
  201916. if (png_ptr->flush_dist > 0 &&
  201917. png_ptr->flush_rows >= png_ptr->flush_dist)
  201918. {
  201919. png_write_flush(png_ptr);
  201920. }
  201921. #endif
  201922. }
  201923. #endif /* PNG_WRITE_SUPPORTED */
  201924. /*** End of inlined file: pngwutil.c ***/
  201925. }
  201926. #else
  201927. extern "C"
  201928. {
  201929. #include <png.h>
  201930. #include <pngconf.h>
  201931. }
  201932. #endif
  201933. }
  201934. #undef max
  201935. #undef min
  201936. #if JUCE_MSVC
  201937. #pragma warning (pop)
  201938. #endif
  201939. BEGIN_JUCE_NAMESPACE
  201940. using ::calloc;
  201941. using ::malloc;
  201942. using ::free;
  201943. namespace PNGHelpers
  201944. {
  201945. using namespace pnglibNamespace;
  201946. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  201947. {
  201948. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  201949. }
  201950. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  201951. {
  201952. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  201953. }
  201954. struct PNGErrorStruct {};
  201955. static void errorCallback (png_structp, png_const_charp)
  201956. {
  201957. throw PNGErrorStruct();
  201958. }
  201959. }
  201960. PNGImageFormat::PNGImageFormat() {}
  201961. PNGImageFormat::~PNGImageFormat() {}
  201962. const String PNGImageFormat::getFormatName()
  201963. {
  201964. return "PNG";
  201965. }
  201966. bool PNGImageFormat::canUnderstand (InputStream& in)
  201967. {
  201968. const int bytesNeeded = 4;
  201969. char header [bytesNeeded];
  201970. return in.read (header, bytesNeeded) == bytesNeeded
  201971. && header[1] == 'P'
  201972. && header[2] == 'N'
  201973. && header[3] == 'G';
  201974. }
  201975. const Image PNGImageFormat::decodeImage (InputStream& in)
  201976. {
  201977. using namespace pnglibNamespace;
  201978. Image image;
  201979. png_structp pngReadStruct;
  201980. png_infop pngInfoStruct;
  201981. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  201982. if (pngReadStruct != 0)
  201983. {
  201984. pngInfoStruct = png_create_info_struct (pngReadStruct);
  201985. if (pngInfoStruct == 0)
  201986. {
  201987. png_destroy_read_struct (&pngReadStruct, 0, 0);
  201988. return Image();
  201989. }
  201990. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  201991. // read the header..
  201992. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  201993. png_uint_32 width, height;
  201994. int bitDepth, colorType, interlaceType;
  201995. png_read_info (pngReadStruct, pngInfoStruct);
  201996. png_get_IHDR (pngReadStruct, pngInfoStruct,
  201997. &width, &height,
  201998. &bitDepth, &colorType,
  201999. &interlaceType, 0, 0);
  202000. if (bitDepth == 16)
  202001. png_set_strip_16 (pngReadStruct);
  202002. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202003. png_set_expand (pngReadStruct);
  202004. if (bitDepth < 8)
  202005. png_set_expand (pngReadStruct);
  202006. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202007. png_set_expand (pngReadStruct);
  202008. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202009. png_set_gray_to_rgb (pngReadStruct);
  202010. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202011. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202012. || pngInfoStruct->num_trans > 0;
  202013. // Load the image into a temp buffer in the pnglib format..
  202014. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202015. {
  202016. HeapBlock <png_bytep> rows (height);
  202017. for (int y = (int) height; --y >= 0;)
  202018. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202019. png_read_image (pngReadStruct, rows);
  202020. png_read_end (pngReadStruct, pngInfoStruct);
  202021. }
  202022. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202023. // now convert the data to a juce image format..
  202024. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202025. (int) width, (int) height, hasAlphaChan);
  202026. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202027. const Image::BitmapData destData (image, 0, 0, (int) width, (int) height, true);
  202028. uint8* srcRow = tempBuffer;
  202029. uint8* destRow = destData.data;
  202030. for (int y = 0; y < (int) height; ++y)
  202031. {
  202032. const uint8* src = srcRow;
  202033. srcRow += (width << 2);
  202034. uint8* dest = destRow;
  202035. destRow += destData.lineStride;
  202036. if (hasAlphaChan)
  202037. {
  202038. for (int i = (int) width; --i >= 0;)
  202039. {
  202040. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202041. ((PixelARGB*) dest)->premultiply();
  202042. dest += destData.pixelStride;
  202043. src += 4;
  202044. }
  202045. }
  202046. else
  202047. {
  202048. for (int i = (int) width; --i >= 0;)
  202049. {
  202050. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202051. dest += destData.pixelStride;
  202052. src += 4;
  202053. }
  202054. }
  202055. }
  202056. }
  202057. return image;
  202058. }
  202059. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202060. {
  202061. using namespace pnglibNamespace;
  202062. const int width = image.getWidth();
  202063. const int height = image.getHeight();
  202064. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202065. if (pngWriteStruct == 0)
  202066. return false;
  202067. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202068. if (pngInfoStruct == 0)
  202069. {
  202070. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202071. return false;
  202072. }
  202073. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202074. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202075. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202076. : PNG_COLOR_TYPE_RGB,
  202077. PNG_INTERLACE_NONE,
  202078. PNG_COMPRESSION_TYPE_BASE,
  202079. PNG_FILTER_TYPE_BASE);
  202080. HeapBlock <uint8> rowData (width * 4);
  202081. png_color_8 sig_bit;
  202082. sig_bit.red = 8;
  202083. sig_bit.green = 8;
  202084. sig_bit.blue = 8;
  202085. sig_bit.alpha = 8;
  202086. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202087. png_write_info (pngWriteStruct, pngInfoStruct);
  202088. png_set_shift (pngWriteStruct, &sig_bit);
  202089. png_set_packing (pngWriteStruct);
  202090. const Image::BitmapData srcData (image, 0, 0, width, height);
  202091. for (int y = 0; y < height; ++y)
  202092. {
  202093. uint8* dst = rowData;
  202094. const uint8* src = srcData.getLinePointer (y);
  202095. if (image.hasAlphaChannel())
  202096. {
  202097. for (int i = width; --i >= 0;)
  202098. {
  202099. PixelARGB p (*(const PixelARGB*) src);
  202100. p.unpremultiply();
  202101. *dst++ = p.getRed();
  202102. *dst++ = p.getGreen();
  202103. *dst++ = p.getBlue();
  202104. *dst++ = p.getAlpha();
  202105. src += srcData.pixelStride;
  202106. }
  202107. }
  202108. else
  202109. {
  202110. for (int i = width; --i >= 0;)
  202111. {
  202112. *dst++ = ((const PixelRGB*) src)->getRed();
  202113. *dst++ = ((const PixelRGB*) src)->getGreen();
  202114. *dst++ = ((const PixelRGB*) src)->getBlue();
  202115. src += srcData.pixelStride;
  202116. }
  202117. }
  202118. png_write_rows (pngWriteStruct, &rowData, 1);
  202119. }
  202120. png_write_end (pngWriteStruct, pngInfoStruct);
  202121. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  202122. out.flush();
  202123. return true;
  202124. }
  202125. END_JUCE_NAMESPACE
  202126. /*** End of inlined file: juce_PNGLoader.cpp ***/
  202127. #endif
  202128. //==============================================================================
  202129. #if JUCE_BUILD_NATIVE
  202130. #if JUCE_WINDOWS
  202131. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  202132. /*
  202133. This file wraps together all the win32-specific code, so that
  202134. we can include all the native headers just once, and compile all our
  202135. platform-specific stuff in one big lump, keeping it out of the way of
  202136. the rest of the codebase.
  202137. */
  202138. #if JUCE_WINDOWS
  202139. BEGIN_JUCE_NAMESPACE
  202140. #define JUCE_INCLUDED_FILE 1
  202141. // Now include the actual code files..
  202142. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202143. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202144. // compiled on its own).
  202145. #if JUCE_INCLUDED_FILE
  202146. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202147. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202148. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202149. #ifndef DOXYGEN
  202150. // use with DynamicLibraryLoader to simplify importing functions
  202151. //
  202152. // functionName: function to import
  202153. // localFunctionName: name you want to use to actually call it (must be different)
  202154. // returnType: the return type
  202155. // object: the DynamicLibraryLoader to use
  202156. // params: list of params (bracketed)
  202157. //
  202158. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  202159. typedef returnType (WINAPI *type##localFunctionName) params; \
  202160. type##localFunctionName localFunctionName \
  202161. = (type##localFunctionName)object.findProcAddress (#functionName);
  202162. // loads and unloads a DLL automatically
  202163. class JUCE_API DynamicLibraryLoader
  202164. {
  202165. public:
  202166. DynamicLibraryLoader (const String& name);
  202167. ~DynamicLibraryLoader();
  202168. void* findProcAddress (const String& functionName);
  202169. private:
  202170. void* libHandle;
  202171. };
  202172. #endif
  202173. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202174. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202175. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  202176. {
  202177. libHandle = LoadLibrary (name);
  202178. }
  202179. DynamicLibraryLoader::~DynamicLibraryLoader()
  202180. {
  202181. FreeLibrary ((HMODULE) libHandle);
  202182. }
  202183. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  202184. {
  202185. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  202186. }
  202187. #endif
  202188. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202189. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  202190. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202191. // compiled on its own).
  202192. #if JUCE_INCLUDED_FILE
  202193. extern void juce_initialiseThreadEvents();
  202194. void Logger::outputDebugString (const String& text)
  202195. {
  202196. OutputDebugString (text + "\n");
  202197. }
  202198. static int64 hiResTicksPerSecond;
  202199. static double hiResTicksScaleFactor;
  202200. #if JUCE_USE_INTRINSICS
  202201. // CPU info functions using intrinsics...
  202202. #pragma intrinsic (__cpuid)
  202203. #pragma intrinsic (__rdtsc)
  202204. const String SystemStats::getCpuVendor()
  202205. {
  202206. int info [4];
  202207. __cpuid (info, 0);
  202208. char v [12];
  202209. memcpy (v, info + 1, 4);
  202210. memcpy (v + 4, info + 3, 4);
  202211. memcpy (v + 8, info + 2, 4);
  202212. return String (v, 12);
  202213. }
  202214. #else
  202215. // CPU info functions using old fashioned inline asm...
  202216. static void juce_getCpuVendor (char* const v)
  202217. {
  202218. int vendor[4];
  202219. zeromem (vendor, 16);
  202220. #ifdef JUCE_64BIT
  202221. #else
  202222. #ifndef __MINGW32__
  202223. __try
  202224. #endif
  202225. {
  202226. #if JUCE_GCC
  202227. unsigned int dummy = 0;
  202228. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  202229. #else
  202230. __asm
  202231. {
  202232. mov eax, 0
  202233. cpuid
  202234. mov [vendor], ebx
  202235. mov [vendor + 4], edx
  202236. mov [vendor + 8], ecx
  202237. }
  202238. #endif
  202239. }
  202240. #ifndef __MINGW32__
  202241. __except (EXCEPTION_EXECUTE_HANDLER)
  202242. {
  202243. *v = 0;
  202244. }
  202245. #endif
  202246. #endif
  202247. memcpy (v, vendor, 16);
  202248. }
  202249. const String SystemStats::getCpuVendor()
  202250. {
  202251. char v [16];
  202252. juce_getCpuVendor (v);
  202253. return String (v, 16);
  202254. }
  202255. #endif
  202256. struct CPUFlags
  202257. {
  202258. bool hasMMX : 1;
  202259. bool hasSSE : 1;
  202260. bool hasSSE2 : 1;
  202261. bool has3DNow : 1;
  202262. };
  202263. static CPUFlags cpuFlags;
  202264. bool SystemStats::hasMMX()
  202265. {
  202266. return cpuFlags.hasMMX;
  202267. }
  202268. bool SystemStats::hasSSE()
  202269. {
  202270. return cpuFlags.hasSSE;
  202271. }
  202272. bool SystemStats::hasSSE2()
  202273. {
  202274. return cpuFlags.hasSSE2;
  202275. }
  202276. bool SystemStats::has3DNow()
  202277. {
  202278. return cpuFlags.has3DNow;
  202279. }
  202280. void SystemStats::initialiseStats()
  202281. {
  202282. juce_initialiseThreadEvents();
  202283. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  202284. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  202285. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  202286. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  202287. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  202288. #else
  202289. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  202290. #endif
  202291. LARGE_INTEGER f;
  202292. QueryPerformanceFrequency (&f);
  202293. hiResTicksPerSecond = f.QuadPart;
  202294. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  202295. String s (SystemStats::getJUCEVersion());
  202296. #if JUCE_DEBUG
  202297. const MMRESULT res = timeBeginPeriod (1);
  202298. jassert (res == TIMERR_NOERROR);
  202299. #else
  202300. timeBeginPeriod (1);
  202301. #endif
  202302. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202303. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  202304. #endif
  202305. }
  202306. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  202307. {
  202308. OSVERSIONINFO info;
  202309. info.dwOSVersionInfoSize = sizeof (info);
  202310. GetVersionEx (&info);
  202311. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  202312. {
  202313. switch (info.dwMajorVersion)
  202314. {
  202315. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  202316. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  202317. default: jassertfalse; break; // !! not a supported OS!
  202318. }
  202319. }
  202320. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  202321. {
  202322. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  202323. return Win98;
  202324. }
  202325. return UnknownOS;
  202326. }
  202327. const String SystemStats::getOperatingSystemName()
  202328. {
  202329. const char* name = "Unknown OS";
  202330. switch (getOperatingSystemType())
  202331. {
  202332. case Windows7: name = "Windows 7"; break;
  202333. case WinVista: name = "Windows Vista"; break;
  202334. case WinXP: name = "Windows XP"; break;
  202335. case Win2000: name = "Windows 2000"; break;
  202336. case Win98: name = "Windows 98"; break;
  202337. default: jassertfalse; break; // !! new type of OS?
  202338. }
  202339. return name;
  202340. }
  202341. bool SystemStats::isOperatingSystem64Bit()
  202342. {
  202343. #ifdef _WIN64
  202344. return true;
  202345. #else
  202346. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  202347. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  202348. BOOL isWow64 = FALSE;
  202349. return (fnIsWow64Process != 0)
  202350. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  202351. && (isWow64 != FALSE);
  202352. #endif
  202353. }
  202354. int SystemStats::getMemorySizeInMegabytes()
  202355. {
  202356. MEMORYSTATUSEX mem;
  202357. mem.dwLength = sizeof (mem);
  202358. GlobalMemoryStatusEx (&mem);
  202359. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  202360. }
  202361. int SystemStats::getNumCpus()
  202362. {
  202363. SYSTEM_INFO systemInfo;
  202364. GetSystemInfo (&systemInfo);
  202365. return systemInfo.dwNumberOfProcessors;
  202366. }
  202367. uint32 juce_millisecondsSinceStartup() throw()
  202368. {
  202369. return (uint32) GetTickCount();
  202370. }
  202371. int64 Time::getHighResolutionTicks() throw()
  202372. {
  202373. LARGE_INTEGER ticks;
  202374. QueryPerformanceCounter (&ticks);
  202375. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  202376. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  202377. // fix for a very obscure PCI hardware bug that can make the counter
  202378. // sometimes jump forwards by a few seconds..
  202379. static int64 hiResTicksOffset = 0;
  202380. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  202381. if (offsetDrift > (hiResTicksPerSecond >> 1))
  202382. hiResTicksOffset = newOffset;
  202383. return ticks.QuadPart + hiResTicksOffset;
  202384. }
  202385. double Time::getMillisecondCounterHiRes() throw()
  202386. {
  202387. return getHighResolutionTicks() * hiResTicksScaleFactor;
  202388. }
  202389. int64 Time::getHighResolutionTicksPerSecond() throw()
  202390. {
  202391. return hiResTicksPerSecond;
  202392. }
  202393. static int64 juce_getClockCycleCounter() throw()
  202394. {
  202395. #if JUCE_USE_INTRINSICS
  202396. // MS intrinsics version...
  202397. return __rdtsc();
  202398. #elif JUCE_GCC
  202399. // GNU inline asm version...
  202400. unsigned int hi = 0, lo = 0;
  202401. __asm__ __volatile__ (
  202402. "xor %%eax, %%eax \n\
  202403. xor %%edx, %%edx \n\
  202404. rdtsc \n\
  202405. movl %%eax, %[lo] \n\
  202406. movl %%edx, %[hi]"
  202407. :
  202408. : [hi] "m" (hi),
  202409. [lo] "m" (lo)
  202410. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  202411. return (int64) ((((uint64) hi) << 32) | lo);
  202412. #else
  202413. // MSVC inline asm version...
  202414. unsigned int hi = 0, lo = 0;
  202415. __asm
  202416. {
  202417. xor eax, eax
  202418. xor edx, edx
  202419. rdtsc
  202420. mov lo, eax
  202421. mov hi, edx
  202422. }
  202423. return (int64) ((((uint64) hi) << 32) | lo);
  202424. #endif
  202425. }
  202426. int SystemStats::getCpuSpeedInMegaherz()
  202427. {
  202428. const int64 cycles = juce_getClockCycleCounter();
  202429. const uint32 millis = Time::getMillisecondCounter();
  202430. int lastResult = 0;
  202431. for (;;)
  202432. {
  202433. int n = 1000000;
  202434. while (--n > 0) {}
  202435. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  202436. const int64 cyclesNow = juce_getClockCycleCounter();
  202437. if (millisElapsed > 80)
  202438. {
  202439. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  202440. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  202441. return newResult;
  202442. lastResult = newResult;
  202443. }
  202444. }
  202445. }
  202446. bool Time::setSystemTimeToThisTime() const
  202447. {
  202448. SYSTEMTIME st;
  202449. st.wDayOfWeek = 0;
  202450. st.wYear = (WORD) getYear();
  202451. st.wMonth = (WORD) (getMonth() + 1);
  202452. st.wDay = (WORD) getDayOfMonth();
  202453. st.wHour = (WORD) getHours();
  202454. st.wMinute = (WORD) getMinutes();
  202455. st.wSecond = (WORD) getSeconds();
  202456. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  202457. // do this twice because of daylight saving conversion problems - the
  202458. // first one sets it up, the second one kicks it in.
  202459. return SetLocalTime (&st) != 0
  202460. && SetLocalTime (&st) != 0;
  202461. }
  202462. int SystemStats::getPageSize()
  202463. {
  202464. SYSTEM_INFO systemInfo;
  202465. GetSystemInfo (&systemInfo);
  202466. return systemInfo.dwPageSize;
  202467. }
  202468. const String SystemStats::getLogonName()
  202469. {
  202470. TCHAR text [256];
  202471. DWORD len = numElementsInArray (text) - 2;
  202472. zerostruct (text);
  202473. GetUserName (text, &len);
  202474. return String (text, len);
  202475. }
  202476. const String SystemStats::getFullUserName()
  202477. {
  202478. return getLogonName();
  202479. }
  202480. #endif
  202481. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  202482. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  202483. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202484. // compiled on its own).
  202485. #if JUCE_INCLUDED_FILE
  202486. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202487. extern HWND juce_messageWindowHandle;
  202488. #endif
  202489. #if ! JUCE_USE_INTRINSICS
  202490. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  202491. // older ones we have to actually call the ops as win32 functions..
  202492. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  202493. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  202494. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  202495. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  202496. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  202497. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  202498. {
  202499. jassertfalse; // This operation isn't available in old MS compiler versions!
  202500. __int64 oldValue = *value;
  202501. if (oldValue == valueToCompare)
  202502. *value = newValue;
  202503. return oldValue;
  202504. }
  202505. #endif
  202506. CriticalSection::CriticalSection() throw()
  202507. {
  202508. // (just to check the MS haven't changed this structure and broken things...)
  202509. #if _MSC_VER >= 1400
  202510. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  202511. #else
  202512. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  202513. #endif
  202514. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  202515. }
  202516. CriticalSection::~CriticalSection() throw()
  202517. {
  202518. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  202519. }
  202520. void CriticalSection::enter() const throw()
  202521. {
  202522. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  202523. }
  202524. bool CriticalSection::tryEnter() const throw()
  202525. {
  202526. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  202527. }
  202528. void CriticalSection::exit() const throw()
  202529. {
  202530. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  202531. }
  202532. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  202533. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  202534. {
  202535. }
  202536. WaitableEvent::~WaitableEvent() throw()
  202537. {
  202538. CloseHandle (internal);
  202539. }
  202540. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  202541. {
  202542. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  202543. }
  202544. void WaitableEvent::signal() const throw()
  202545. {
  202546. SetEvent (internal);
  202547. }
  202548. void WaitableEvent::reset() const throw()
  202549. {
  202550. ResetEvent (internal);
  202551. }
  202552. void JUCE_API juce_threadEntryPoint (void*);
  202553. static unsigned int __stdcall threadEntryProc (void* userData)
  202554. {
  202555. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202556. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  202557. GetCurrentThreadId(), TRUE);
  202558. #endif
  202559. juce_threadEntryPoint (userData);
  202560. _endthreadex (0);
  202561. return 0;
  202562. }
  202563. void juce_CloseThreadHandle (void* handle)
  202564. {
  202565. CloseHandle ((HANDLE) handle);
  202566. }
  202567. void* juce_createThread (void* userData)
  202568. {
  202569. unsigned int threadId;
  202570. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  202571. }
  202572. void juce_killThread (void* handle)
  202573. {
  202574. if (handle != 0)
  202575. {
  202576. #if JUCE_DEBUG
  202577. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  202578. #endif
  202579. TerminateThread (handle, 0);
  202580. }
  202581. }
  202582. void juce_setCurrentThreadName (const String& name)
  202583. {
  202584. #if JUCE_DEBUG && JUCE_MSVC
  202585. struct
  202586. {
  202587. DWORD dwType;
  202588. LPCSTR szName;
  202589. DWORD dwThreadID;
  202590. DWORD dwFlags;
  202591. } info;
  202592. info.dwType = 0x1000;
  202593. info.szName = name.toCString();
  202594. info.dwThreadID = GetCurrentThreadId();
  202595. info.dwFlags = 0;
  202596. __try
  202597. {
  202598. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  202599. }
  202600. __except (EXCEPTION_CONTINUE_EXECUTION)
  202601. {}
  202602. #else
  202603. (void) name;
  202604. #endif
  202605. }
  202606. Thread::ThreadID Thread::getCurrentThreadId()
  202607. {
  202608. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  202609. }
  202610. // priority 1 to 10 where 5=normal, 1=low
  202611. bool juce_setThreadPriority (void* threadHandle, int priority)
  202612. {
  202613. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  202614. if (priority < 1)
  202615. pri = THREAD_PRIORITY_IDLE;
  202616. else if (priority < 2)
  202617. pri = THREAD_PRIORITY_LOWEST;
  202618. else if (priority < 5)
  202619. pri = THREAD_PRIORITY_BELOW_NORMAL;
  202620. else if (priority < 7)
  202621. pri = THREAD_PRIORITY_NORMAL;
  202622. else if (priority < 9)
  202623. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  202624. else if (priority < 10)
  202625. pri = THREAD_PRIORITY_HIGHEST;
  202626. if (threadHandle == 0)
  202627. threadHandle = GetCurrentThread();
  202628. return SetThreadPriority (threadHandle, pri) != FALSE;
  202629. }
  202630. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  202631. {
  202632. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  202633. }
  202634. static HANDLE sleepEvent = 0;
  202635. void juce_initialiseThreadEvents()
  202636. {
  202637. if (sleepEvent == 0)
  202638. #if JUCE_DEBUG
  202639. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  202640. #else
  202641. sleepEvent = CreateEvent (0, 0, 0, 0);
  202642. #endif
  202643. }
  202644. void Thread::yield()
  202645. {
  202646. Sleep (0);
  202647. }
  202648. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  202649. {
  202650. if (millisecs >= 10)
  202651. {
  202652. Sleep (millisecs);
  202653. }
  202654. else
  202655. {
  202656. jassert (sleepEvent != 0);
  202657. // unlike Sleep() this is guaranteed to return to the current thread after
  202658. // the time expires, so we'll use this for short waits, which are more likely
  202659. // to need to be accurate
  202660. WaitForSingleObject (sleepEvent, millisecs);
  202661. }
  202662. }
  202663. static int lastProcessPriority = -1;
  202664. // called by WindowDriver because Windows does wierd things to process priority
  202665. // when you swap apps, and this forces an update when the app is brought to the front.
  202666. void juce_repeatLastProcessPriority()
  202667. {
  202668. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  202669. {
  202670. DWORD p;
  202671. switch (lastProcessPriority)
  202672. {
  202673. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  202674. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  202675. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  202676. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  202677. default: jassertfalse; return; // bad priority value
  202678. }
  202679. SetPriorityClass (GetCurrentProcess(), p);
  202680. }
  202681. }
  202682. void Process::setPriority (ProcessPriority prior)
  202683. {
  202684. if (lastProcessPriority != (int) prior)
  202685. {
  202686. lastProcessPriority = (int) prior;
  202687. juce_repeatLastProcessPriority();
  202688. }
  202689. }
  202690. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  202691. {
  202692. return IsDebuggerPresent() != FALSE;
  202693. }
  202694. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  202695. {
  202696. return juce_isRunningUnderDebugger();
  202697. }
  202698. void Process::raisePrivilege()
  202699. {
  202700. jassertfalse; // xxx not implemented
  202701. }
  202702. void Process::lowerPrivilege()
  202703. {
  202704. jassertfalse; // xxx not implemented
  202705. }
  202706. void Process::terminate()
  202707. {
  202708. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202709. _CrtDumpMemoryLeaks();
  202710. #endif
  202711. // bullet in the head in case there's a problem shutting down..
  202712. ExitProcess (0);
  202713. }
  202714. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  202715. {
  202716. void* result = 0;
  202717. JUCE_TRY
  202718. {
  202719. result = LoadLibrary (name);
  202720. }
  202721. JUCE_CATCH_ALL
  202722. return result;
  202723. }
  202724. void PlatformUtilities::freeDynamicLibrary (void* h)
  202725. {
  202726. JUCE_TRY
  202727. {
  202728. if (h != 0)
  202729. FreeLibrary ((HMODULE) h);
  202730. }
  202731. JUCE_CATCH_ALL
  202732. }
  202733. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  202734. {
  202735. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  202736. }
  202737. class InterProcessLock::Pimpl
  202738. {
  202739. public:
  202740. Pimpl (const String& name, const int timeOutMillisecs)
  202741. : handle (0), refCount (1)
  202742. {
  202743. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  202744. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  202745. {
  202746. if (timeOutMillisecs == 0)
  202747. {
  202748. close();
  202749. return;
  202750. }
  202751. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  202752. {
  202753. case WAIT_OBJECT_0:
  202754. case WAIT_ABANDONED:
  202755. break;
  202756. case WAIT_TIMEOUT:
  202757. default:
  202758. close();
  202759. break;
  202760. }
  202761. }
  202762. }
  202763. ~Pimpl()
  202764. {
  202765. close();
  202766. }
  202767. void close()
  202768. {
  202769. if (handle != 0)
  202770. {
  202771. ReleaseMutex (handle);
  202772. CloseHandle (handle);
  202773. handle = 0;
  202774. }
  202775. }
  202776. HANDLE handle;
  202777. int refCount;
  202778. };
  202779. InterProcessLock::InterProcessLock (const String& name_)
  202780. : name (name_)
  202781. {
  202782. }
  202783. InterProcessLock::~InterProcessLock()
  202784. {
  202785. }
  202786. bool InterProcessLock::enter (const int timeOutMillisecs)
  202787. {
  202788. const ScopedLock sl (lock);
  202789. if (pimpl == 0)
  202790. {
  202791. pimpl = new Pimpl (name, timeOutMillisecs);
  202792. if (pimpl->handle == 0)
  202793. pimpl = 0;
  202794. }
  202795. else
  202796. {
  202797. pimpl->refCount++;
  202798. }
  202799. return pimpl != 0;
  202800. }
  202801. void InterProcessLock::exit()
  202802. {
  202803. const ScopedLock sl (lock);
  202804. // Trying to release the lock too many times!
  202805. jassert (pimpl != 0);
  202806. if (pimpl != 0 && --(pimpl->refCount) == 0)
  202807. pimpl = 0;
  202808. }
  202809. #endif
  202810. /*** End of inlined file: juce_win32_Threads.cpp ***/
  202811. /*** Start of inlined file: juce_win32_Files.cpp ***/
  202812. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202813. // compiled on its own).
  202814. #if JUCE_INCLUDED_FILE
  202815. #ifndef CSIDL_MYMUSIC
  202816. #define CSIDL_MYMUSIC 0x000d
  202817. #endif
  202818. #ifndef CSIDL_MYVIDEO
  202819. #define CSIDL_MYVIDEO 0x000e
  202820. #endif
  202821. #ifndef INVALID_FILE_ATTRIBUTES
  202822. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  202823. #endif
  202824. const juce_wchar File::separator = '\\';
  202825. const String File::separatorString ("\\");
  202826. bool File::exists() const
  202827. {
  202828. return fullPath.isNotEmpty()
  202829. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  202830. }
  202831. bool File::existsAsFile() const
  202832. {
  202833. return fullPath.isNotEmpty()
  202834. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  202835. }
  202836. bool File::isDirectory() const
  202837. {
  202838. const DWORD attr = GetFileAttributes (fullPath);
  202839. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  202840. }
  202841. bool File::hasWriteAccess() const
  202842. {
  202843. if (exists())
  202844. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  202845. // on windows, it seems that even read-only directories can still be written into,
  202846. // so checking the parent directory's permissions would return the wrong result..
  202847. return true;
  202848. }
  202849. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  202850. {
  202851. DWORD attr = GetFileAttributes (fullPath);
  202852. if (attr == INVALID_FILE_ATTRIBUTES)
  202853. return false;
  202854. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  202855. return true;
  202856. if (shouldBeReadOnly)
  202857. attr |= FILE_ATTRIBUTE_READONLY;
  202858. else
  202859. attr &= ~FILE_ATTRIBUTE_READONLY;
  202860. return SetFileAttributes (fullPath, attr) != FALSE;
  202861. }
  202862. bool File::isHidden() const
  202863. {
  202864. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  202865. }
  202866. bool File::deleteFile() const
  202867. {
  202868. if (! exists())
  202869. return true;
  202870. else if (isDirectory())
  202871. return RemoveDirectory (fullPath) != 0;
  202872. else
  202873. return DeleteFile (fullPath) != 0;
  202874. }
  202875. bool File::moveToTrash() const
  202876. {
  202877. if (! exists())
  202878. return true;
  202879. SHFILEOPSTRUCT fos;
  202880. zerostruct (fos);
  202881. // The string we pass in must be double null terminated..
  202882. String doubleNullTermPath (getFullPathName() + " ");
  202883. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  202884. p [getFullPathName().length()] = 0;
  202885. fos.wFunc = FO_DELETE;
  202886. fos.pFrom = p;
  202887. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  202888. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  202889. return SHFileOperation (&fos) == 0;
  202890. }
  202891. bool File::copyInternal (const File& dest) const
  202892. {
  202893. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  202894. }
  202895. bool File::moveInternal (const File& dest) const
  202896. {
  202897. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  202898. }
  202899. void File::createDirectoryInternal (const String& fileName) const
  202900. {
  202901. CreateDirectory (fileName, 0);
  202902. }
  202903. // return 0 if not possible
  202904. void* juce_fileOpen (const File& file, bool forWriting)
  202905. {
  202906. HANDLE h;
  202907. if (forWriting)
  202908. {
  202909. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  202910. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  202911. if (h != INVALID_HANDLE_VALUE)
  202912. SetFilePointer (h, 0, 0, FILE_END);
  202913. else
  202914. h = 0;
  202915. }
  202916. else
  202917. {
  202918. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  202919. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  202920. if (h == INVALID_HANDLE_VALUE)
  202921. h = 0;
  202922. }
  202923. return h;
  202924. }
  202925. void juce_fileClose (void* handle)
  202926. {
  202927. CloseHandle (handle);
  202928. }
  202929. int juce_fileRead (void* handle, void* buffer, int size)
  202930. {
  202931. DWORD num = 0;
  202932. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  202933. return (int) num;
  202934. }
  202935. int juce_fileWrite (void* handle, const void* buffer, int size)
  202936. {
  202937. DWORD num;
  202938. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  202939. return (int) num;
  202940. }
  202941. int64 juce_fileSetPosition (void* handle, int64 pos)
  202942. {
  202943. LARGE_INTEGER li;
  202944. li.QuadPart = pos;
  202945. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  202946. return li.QuadPart;
  202947. }
  202948. int64 FileOutputStream::getPositionInternal() const
  202949. {
  202950. if (fileHandle == 0)
  202951. return -1;
  202952. LARGE_INTEGER li;
  202953. li.QuadPart = 0;
  202954. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  202955. return jmax ((int64) 0, li.QuadPart);
  202956. }
  202957. void FileOutputStream::flushInternal()
  202958. {
  202959. if (fileHandle != 0)
  202960. FlushFileBuffers ((HANDLE) fileHandle);
  202961. }
  202962. int64 File::getSize() const
  202963. {
  202964. WIN32_FILE_ATTRIBUTE_DATA attributes;
  202965. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  202966. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  202967. return 0;
  202968. }
  202969. static int64 fileTimeToTime (const FILETIME* const ft)
  202970. {
  202971. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  202972. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  202973. }
  202974. static void timeToFileTime (const int64 time, FILETIME* const ft)
  202975. {
  202976. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  202977. }
  202978. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  202979. {
  202980. WIN32_FILE_ATTRIBUTE_DATA attributes;
  202981. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  202982. {
  202983. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  202984. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  202985. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  202986. }
  202987. else
  202988. {
  202989. creationTime = accessTime = modificationTime = 0;
  202990. }
  202991. }
  202992. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  202993. {
  202994. void* const h = juce_fileOpen (fullPath, true);
  202995. bool ok = false;
  202996. if (h != 0)
  202997. {
  202998. FILETIME m, a, c;
  202999. timeToFileTime (modificationTime, &m);
  203000. timeToFileTime (accessTime, &a);
  203001. timeToFileTime (creationTime, &c);
  203002. ok = SetFileTime ((HANDLE) h,
  203003. creationTime > 0 ? &c : 0,
  203004. accessTime > 0 ? &a : 0,
  203005. modificationTime > 0 ? &m : 0) != 0;
  203006. juce_fileClose (h);
  203007. }
  203008. return ok;
  203009. }
  203010. void File::findFileSystemRoots (Array<File>& destArray)
  203011. {
  203012. TCHAR buffer [2048];
  203013. buffer[0] = 0;
  203014. buffer[1] = 0;
  203015. GetLogicalDriveStrings (2048, buffer);
  203016. const TCHAR* n = buffer;
  203017. StringArray roots;
  203018. while (*n != 0)
  203019. {
  203020. roots.add (String (n));
  203021. while (*n++ != 0)
  203022. {}
  203023. }
  203024. roots.sort (true);
  203025. for (int i = 0; i < roots.size(); ++i)
  203026. destArray.add (roots [i]);
  203027. }
  203028. static const String getDriveFromPath (const String& path)
  203029. {
  203030. if (path.isNotEmpty() && path[1] == ':')
  203031. return path.substring (0, 2) + '\\';
  203032. return path;
  203033. }
  203034. const String File::getVolumeLabel() const
  203035. {
  203036. TCHAR dest[64];
  203037. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203038. numElementsInArray (dest), 0, 0, 0, 0, 0))
  203039. dest[0] = 0;
  203040. return dest;
  203041. }
  203042. int File::getVolumeSerialNumber() const
  203043. {
  203044. TCHAR dest[64];
  203045. DWORD serialNum;
  203046. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203047. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  203048. return 0;
  203049. return (int) serialNum;
  203050. }
  203051. static int64 getDiskSpaceInfo (const String& path, const bool total)
  203052. {
  203053. ULARGE_INTEGER spc, tot, totFree;
  203054. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  203055. return total ? (int64) tot.QuadPart
  203056. : (int64) spc.QuadPart;
  203057. return 0;
  203058. }
  203059. int64 File::getBytesFreeOnVolume() const
  203060. {
  203061. return getDiskSpaceInfo (getFullPathName(), false);
  203062. }
  203063. int64 File::getVolumeTotalSize() const
  203064. {
  203065. return getDiskSpaceInfo (getFullPathName(), true);
  203066. }
  203067. static unsigned int getWindowsDriveType (const String& path)
  203068. {
  203069. return GetDriveType (getDriveFromPath (path));
  203070. }
  203071. bool File::isOnCDRomDrive() const
  203072. {
  203073. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  203074. }
  203075. bool File::isOnHardDisk() const
  203076. {
  203077. if (fullPath.isEmpty())
  203078. return false;
  203079. const unsigned int n = getWindowsDriveType (getFullPathName());
  203080. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  203081. return n != DRIVE_REMOVABLE;
  203082. else
  203083. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  203084. }
  203085. bool File::isOnRemovableDrive() const
  203086. {
  203087. if (fullPath.isEmpty())
  203088. return false;
  203089. const unsigned int n = getWindowsDriveType (getFullPathName());
  203090. return n == DRIVE_CDROM
  203091. || n == DRIVE_REMOTE
  203092. || n == DRIVE_REMOVABLE
  203093. || n == DRIVE_RAMDISK;
  203094. }
  203095. static const File juce_getSpecialFolderPath (int type)
  203096. {
  203097. WCHAR path [MAX_PATH + 256];
  203098. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203099. return File (String (path));
  203100. return File::nonexistent;
  203101. }
  203102. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  203103. {
  203104. int csidlType = 0;
  203105. switch (type)
  203106. {
  203107. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  203108. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  203109. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  203110. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  203111. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  203112. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  203113. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  203114. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  203115. case tempDirectory:
  203116. {
  203117. WCHAR dest [2048];
  203118. dest[0] = 0;
  203119. GetTempPath (numElementsInArray (dest), dest);
  203120. return File (String (dest));
  203121. }
  203122. case invokedExecutableFile:
  203123. case currentExecutableFile:
  203124. case currentApplicationFile:
  203125. {
  203126. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  203127. WCHAR dest [MAX_PATH + 256];
  203128. dest[0] = 0;
  203129. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  203130. return File (String (dest));
  203131. }
  203132. break;
  203133. default:
  203134. jassertfalse; // unknown type?
  203135. return File::nonexistent;
  203136. }
  203137. return juce_getSpecialFolderPath (csidlType);
  203138. }
  203139. const File File::getCurrentWorkingDirectory()
  203140. {
  203141. WCHAR dest [MAX_PATH + 256];
  203142. dest[0] = 0;
  203143. GetCurrentDirectory (numElementsInArray (dest), dest);
  203144. return File (String (dest));
  203145. }
  203146. bool File::setAsCurrentWorkingDirectory() const
  203147. {
  203148. return SetCurrentDirectory (getFullPathName()) != FALSE;
  203149. }
  203150. const String File::getVersion() const
  203151. {
  203152. String result;
  203153. DWORD handle = 0;
  203154. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  203155. HeapBlock<char> buffer;
  203156. buffer.calloc (bufferSize);
  203157. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  203158. {
  203159. VS_FIXEDFILEINFO* vffi;
  203160. UINT len = 0;
  203161. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  203162. {
  203163. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  203164. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  203165. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  203166. << (int) LOWORD (vffi->dwFileVersionLS);
  203167. }
  203168. }
  203169. return result;
  203170. }
  203171. const File File::getLinkedTarget() const
  203172. {
  203173. File result (*this);
  203174. String p (getFullPathName());
  203175. if (! exists())
  203176. p += ".lnk";
  203177. else if (getFileExtension() != ".lnk")
  203178. return result;
  203179. ComSmartPtr <IShellLink> shellLink;
  203180. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  203181. {
  203182. ComSmartPtr <IPersistFile> persistFile;
  203183. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  203184. {
  203185. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  203186. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  203187. {
  203188. WIN32_FIND_DATA winFindData;
  203189. WCHAR resolvedPath [MAX_PATH];
  203190. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  203191. result = File (resolvedPath);
  203192. }
  203193. }
  203194. }
  203195. return result;
  203196. }
  203197. class DirectoryIterator::NativeIterator::Pimpl
  203198. {
  203199. public:
  203200. Pimpl (const File& directory, const String& wildCard)
  203201. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  203202. handle (INVALID_HANDLE_VALUE)
  203203. {
  203204. }
  203205. ~Pimpl()
  203206. {
  203207. if (handle != INVALID_HANDLE_VALUE)
  203208. FindClose (handle);
  203209. }
  203210. bool next (String& filenameFound,
  203211. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203212. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203213. {
  203214. WIN32_FIND_DATA findData;
  203215. if (handle == INVALID_HANDLE_VALUE)
  203216. {
  203217. handle = FindFirstFile (directoryWithWildCard, &findData);
  203218. if (handle == INVALID_HANDLE_VALUE)
  203219. return false;
  203220. }
  203221. else
  203222. {
  203223. if (FindNextFile (handle, &findData) == 0)
  203224. return false;
  203225. }
  203226. filenameFound = findData.cFileName;
  203227. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  203228. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  203229. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  203230. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  203231. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  203232. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  203233. return true;
  203234. }
  203235. juce_UseDebuggingNewOperator
  203236. private:
  203237. const String directoryWithWildCard;
  203238. HANDLE handle;
  203239. Pimpl (const Pimpl&);
  203240. Pimpl& operator= (const Pimpl&);
  203241. };
  203242. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  203243. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  203244. {
  203245. }
  203246. DirectoryIterator::NativeIterator::~NativeIterator()
  203247. {
  203248. }
  203249. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  203250. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203251. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203252. {
  203253. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  203254. }
  203255. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  203256. {
  203257. HINSTANCE hInstance = 0;
  203258. JUCE_TRY
  203259. {
  203260. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  203261. }
  203262. JUCE_CATCH_ALL
  203263. return hInstance > (HINSTANCE) 32;
  203264. }
  203265. void File::revealToUser() const
  203266. {
  203267. if (isDirectory())
  203268. startAsProcess();
  203269. else if (getParentDirectory().exists())
  203270. getParentDirectory().startAsProcess();
  203271. }
  203272. class NamedPipeInternal
  203273. {
  203274. public:
  203275. NamedPipeInternal (const String& file, const bool isPipe_)
  203276. : pipeH (0),
  203277. cancelEvent (0),
  203278. connected (false),
  203279. isPipe (isPipe_)
  203280. {
  203281. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  203282. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  203283. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  203284. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  203285. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  203286. }
  203287. ~NamedPipeInternal()
  203288. {
  203289. disconnectPipe();
  203290. if (pipeH != 0)
  203291. CloseHandle (pipeH);
  203292. CloseHandle (cancelEvent);
  203293. }
  203294. bool connect (const int timeOutMs)
  203295. {
  203296. if (! isPipe)
  203297. return true;
  203298. if (! connected)
  203299. {
  203300. OVERLAPPED over;
  203301. zerostruct (over);
  203302. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203303. if (ConnectNamedPipe (pipeH, &over))
  203304. {
  203305. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  203306. }
  203307. else
  203308. {
  203309. const int err = GetLastError();
  203310. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  203311. {
  203312. HANDLE handles[] = { over.hEvent, cancelEvent };
  203313. if (WaitForMultipleObjects (2, handles, FALSE,
  203314. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  203315. connected = true;
  203316. }
  203317. else if (err == ERROR_PIPE_CONNECTED)
  203318. {
  203319. connected = true;
  203320. }
  203321. }
  203322. CloseHandle (over.hEvent);
  203323. }
  203324. return connected;
  203325. }
  203326. void disconnectPipe()
  203327. {
  203328. if (connected)
  203329. {
  203330. DisconnectNamedPipe (pipeH);
  203331. connected = false;
  203332. }
  203333. }
  203334. HANDLE pipeH;
  203335. HANDLE cancelEvent;
  203336. bool connected, isPipe;
  203337. };
  203338. void NamedPipe::close()
  203339. {
  203340. cancelPendingReads();
  203341. const ScopedLock sl (lock);
  203342. delete static_cast<NamedPipeInternal*> (internal);
  203343. internal = 0;
  203344. }
  203345. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  203346. {
  203347. close();
  203348. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  203349. if (intern->pipeH != INVALID_HANDLE_VALUE)
  203350. {
  203351. internal = intern.release();
  203352. return true;
  203353. }
  203354. return false;
  203355. }
  203356. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  203357. {
  203358. const ScopedLock sl (lock);
  203359. int bytesRead = -1;
  203360. bool waitAgain = true;
  203361. while (waitAgain && internal != 0)
  203362. {
  203363. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203364. waitAgain = false;
  203365. if (! intern->connect (timeOutMilliseconds))
  203366. break;
  203367. if (maxBytesToRead <= 0)
  203368. return 0;
  203369. OVERLAPPED over;
  203370. zerostruct (over);
  203371. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203372. unsigned long numRead;
  203373. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  203374. {
  203375. bytesRead = (int) numRead;
  203376. }
  203377. else if (GetLastError() == ERROR_IO_PENDING)
  203378. {
  203379. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203380. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203381. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203382. : INFINITE);
  203383. if (waitResult != WAIT_OBJECT_0)
  203384. {
  203385. // if the operation timed out, let's cancel it...
  203386. CancelIo (intern->pipeH);
  203387. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  203388. }
  203389. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  203390. {
  203391. bytesRead = (int) numRead;
  203392. }
  203393. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203394. {
  203395. intern->disconnectPipe();
  203396. waitAgain = true;
  203397. }
  203398. }
  203399. else
  203400. {
  203401. waitAgain = internal != 0;
  203402. Sleep (5);
  203403. }
  203404. CloseHandle (over.hEvent);
  203405. }
  203406. return bytesRead;
  203407. }
  203408. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  203409. {
  203410. int bytesWritten = -1;
  203411. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203412. if (intern != 0 && intern->connect (timeOutMilliseconds))
  203413. {
  203414. if (numBytesToWrite <= 0)
  203415. return 0;
  203416. OVERLAPPED over;
  203417. zerostruct (over);
  203418. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203419. unsigned long numWritten;
  203420. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  203421. {
  203422. bytesWritten = (int) numWritten;
  203423. }
  203424. else if (GetLastError() == ERROR_IO_PENDING)
  203425. {
  203426. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203427. DWORD waitResult;
  203428. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203429. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203430. : INFINITE);
  203431. if (waitResult != WAIT_OBJECT_0)
  203432. {
  203433. CancelIo (intern->pipeH);
  203434. WaitForSingleObject (over.hEvent, INFINITE);
  203435. }
  203436. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  203437. {
  203438. bytesWritten = (int) numWritten;
  203439. }
  203440. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203441. {
  203442. intern->disconnectPipe();
  203443. }
  203444. }
  203445. CloseHandle (over.hEvent);
  203446. }
  203447. return bytesWritten;
  203448. }
  203449. void NamedPipe::cancelPendingReads()
  203450. {
  203451. if (internal != 0)
  203452. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  203453. }
  203454. #endif
  203455. /*** End of inlined file: juce_win32_Files.cpp ***/
  203456. /*** Start of inlined file: juce_win32_Network.cpp ***/
  203457. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203458. // compiled on its own).
  203459. #if JUCE_INCLUDED_FILE
  203460. #ifndef INTERNET_FLAG_NEED_FILE
  203461. #define INTERNET_FLAG_NEED_FILE 0x00000010
  203462. #endif
  203463. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  203464. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  203465. #endif
  203466. struct ConnectionAndRequestStruct
  203467. {
  203468. HINTERNET connection, request;
  203469. };
  203470. static HINTERNET sessionHandle = 0;
  203471. #ifndef WORKAROUND_TIMEOUT_BUG
  203472. //#define WORKAROUND_TIMEOUT_BUG 1
  203473. #endif
  203474. #if WORKAROUND_TIMEOUT_BUG
  203475. // Required because of a Microsoft bug in setting a timeout
  203476. class InternetConnectThread : public Thread
  203477. {
  203478. public:
  203479. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  203480. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  203481. {
  203482. startThread();
  203483. }
  203484. ~InternetConnectThread()
  203485. {
  203486. stopThread (60000);
  203487. }
  203488. void run()
  203489. {
  203490. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  203491. uc.nPort, _T(""), _T(""),
  203492. isFtp ? INTERNET_SERVICE_FTP
  203493. : INTERNET_SERVICE_HTTP,
  203494. 0, 0);
  203495. notify();
  203496. }
  203497. juce_UseDebuggingNewOperator
  203498. private:
  203499. URL_COMPONENTS& uc;
  203500. HINTERNET& connection;
  203501. const bool isFtp;
  203502. InternetConnectThread (const InternetConnectThread&);
  203503. InternetConnectThread& operator= (const InternetConnectThread&);
  203504. };
  203505. #endif
  203506. void* juce_openInternetFile (const String& url,
  203507. const String& headers,
  203508. const MemoryBlock& postData,
  203509. const bool isPost,
  203510. URL::OpenStreamProgressCallback* callback,
  203511. void* callbackContext,
  203512. int timeOutMs)
  203513. {
  203514. if (sessionHandle == 0)
  203515. sessionHandle = InternetOpen (_T("juce"),
  203516. INTERNET_OPEN_TYPE_PRECONFIG,
  203517. 0, 0, 0);
  203518. if (sessionHandle != 0)
  203519. {
  203520. // break up the url..
  203521. TCHAR file[1024], server[1024];
  203522. URL_COMPONENTS uc;
  203523. zerostruct (uc);
  203524. uc.dwStructSize = sizeof (uc);
  203525. uc.dwUrlPathLength = sizeof (file);
  203526. uc.dwHostNameLength = sizeof (server);
  203527. uc.lpszUrlPath = file;
  203528. uc.lpszHostName = server;
  203529. if (InternetCrackUrl (url, 0, 0, &uc))
  203530. {
  203531. int disable = 1;
  203532. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  203533. if (timeOutMs == 0)
  203534. timeOutMs = 30000;
  203535. else if (timeOutMs < 0)
  203536. timeOutMs = -1;
  203537. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  203538. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  203539. #if WORKAROUND_TIMEOUT_BUG
  203540. HINTERNET connection = 0;
  203541. {
  203542. InternetConnectThread connectThread (uc, connection, isFtp);
  203543. connectThread.wait (timeOutMs);
  203544. if (connection == 0)
  203545. {
  203546. InternetCloseHandle (sessionHandle);
  203547. sessionHandle = 0;
  203548. }
  203549. }
  203550. #else
  203551. HINTERNET connection = InternetConnect (sessionHandle,
  203552. uc.lpszHostName,
  203553. uc.nPort,
  203554. _T(""), _T(""),
  203555. isFtp ? INTERNET_SERVICE_FTP
  203556. : INTERNET_SERVICE_HTTP,
  203557. 0, 0);
  203558. #endif
  203559. if (connection != 0)
  203560. {
  203561. if (isFtp)
  203562. {
  203563. HINTERNET request = FtpOpenFile (connection,
  203564. uc.lpszUrlPath,
  203565. GENERIC_READ,
  203566. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  203567. 0);
  203568. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  203569. result->connection = connection;
  203570. result->request = request;
  203571. return result;
  203572. }
  203573. else
  203574. {
  203575. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  203576. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  203577. if (url.startsWithIgnoreCase ("https:"))
  203578. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  203579. // IE7 seems to automatically work out when it's https)
  203580. HINTERNET request = HttpOpenRequest (connection,
  203581. isPost ? _T("POST")
  203582. : _T("GET"),
  203583. uc.lpszUrlPath,
  203584. 0, 0, mimeTypes, flags, 0);
  203585. if (request != 0)
  203586. {
  203587. INTERNET_BUFFERS buffers;
  203588. zerostruct (buffers);
  203589. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  203590. buffers.lpcszHeader = (LPCTSTR) headers;
  203591. buffers.dwHeadersLength = headers.length();
  203592. buffers.dwBufferTotal = (DWORD) postData.getSize();
  203593. ConnectionAndRequestStruct* result = 0;
  203594. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  203595. {
  203596. int bytesSent = 0;
  203597. for (;;)
  203598. {
  203599. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  203600. DWORD bytesDone = 0;
  203601. if (bytesToDo > 0
  203602. && ! InternetWriteFile (request,
  203603. static_cast <const char*> (postData.getData()) + bytesSent,
  203604. bytesToDo, &bytesDone))
  203605. {
  203606. break;
  203607. }
  203608. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  203609. {
  203610. result = new ConnectionAndRequestStruct();
  203611. result->connection = connection;
  203612. result->request = request;
  203613. HttpEndRequest (request, 0, 0, 0);
  203614. return result;
  203615. }
  203616. bytesSent += bytesDone;
  203617. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  203618. break;
  203619. }
  203620. }
  203621. InternetCloseHandle (request);
  203622. }
  203623. InternetCloseHandle (connection);
  203624. }
  203625. }
  203626. }
  203627. }
  203628. return 0;
  203629. }
  203630. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  203631. {
  203632. DWORD bytesRead = 0;
  203633. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203634. if (crs != 0)
  203635. InternetReadFile (crs->request,
  203636. buffer, bytesToRead,
  203637. &bytesRead);
  203638. return bytesRead;
  203639. }
  203640. int juce_seekInInternetFile (void* handle, int newPosition)
  203641. {
  203642. if (handle != 0)
  203643. {
  203644. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203645. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  203646. }
  203647. return -1;
  203648. }
  203649. int64 juce_getInternetFileContentLength (void* handle)
  203650. {
  203651. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203652. if (crs != 0)
  203653. {
  203654. DWORD index = 0, result = 0, size = sizeof (result);
  203655. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  203656. return (int64) result;
  203657. }
  203658. return -1;
  203659. }
  203660. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  203661. {
  203662. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203663. if (crs != 0)
  203664. {
  203665. DWORD bufferSizeBytes = 4096;
  203666. for (;;)
  203667. {
  203668. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  203669. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  203670. {
  203671. StringArray headersArray;
  203672. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  203673. for (int i = 0; i < headersArray.size(); ++i)
  203674. {
  203675. const String& header = headersArray[i];
  203676. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  203677. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  203678. const String previousValue (headers [key]);
  203679. headers.set (key, previousValue.isEmpty() ? value : (previousValue + ";" + value));
  203680. }
  203681. break;
  203682. }
  203683. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  203684. break;
  203685. }
  203686. }
  203687. }
  203688. void juce_closeInternetFile (void* handle)
  203689. {
  203690. if (handle != 0)
  203691. {
  203692. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  203693. InternetCloseHandle (crs->request);
  203694. InternetCloseHandle (crs->connection);
  203695. }
  203696. }
  203697. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  203698. {
  203699. int numFound = 0;
  203700. DynamicLibraryLoader dll ("iphlpapi.dll");
  203701. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  203702. if (getAdaptersInfo != 0)
  203703. {
  203704. ULONG len = sizeof (IP_ADAPTER_INFO);
  203705. MemoryBlock mb;
  203706. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  203707. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  203708. {
  203709. mb.setSize (len);
  203710. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  203711. }
  203712. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  203713. {
  203714. PIP_ADAPTER_INFO adapter = adapterInfo;
  203715. while (adapter != 0)
  203716. {
  203717. int64 mac = 0;
  203718. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  203719. mac = (mac << 8) | adapter->Address[i];
  203720. if (littleEndian)
  203721. mac = (int64) ByteOrder::swap ((uint64) mac);
  203722. if (numFound < maxNum && mac != 0)
  203723. addresses [numFound++] = mac;
  203724. adapter = adapter->Next;
  203725. }
  203726. }
  203727. }
  203728. return numFound;
  203729. }
  203730. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  203731. {
  203732. int numFound = 0;
  203733. DynamicLibraryLoader dll ("netapi32.dll");
  203734. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  203735. if (NetbiosCall != 0)
  203736. {
  203737. NCB ncb;
  203738. zerostruct (ncb);
  203739. struct ASTAT
  203740. {
  203741. ADAPTER_STATUS adapt;
  203742. NAME_BUFFER NameBuff [30];
  203743. };
  203744. ASTAT astat;
  203745. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  203746. LANA_ENUM enums;
  203747. zerostruct (enums);
  203748. ncb.ncb_command = NCBENUM;
  203749. ncb.ncb_buffer = (unsigned char*) &enums;
  203750. ncb.ncb_length = sizeof (LANA_ENUM);
  203751. NetbiosCall (&ncb);
  203752. for (int i = 0; i < enums.length; ++i)
  203753. {
  203754. zerostruct (ncb);
  203755. ncb.ncb_command = NCBRESET;
  203756. ncb.ncb_lana_num = enums.lana[i];
  203757. if (NetbiosCall (&ncb) == 0)
  203758. {
  203759. zerostruct (ncb);
  203760. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  203761. ncb.ncb_command = NCBASTAT;
  203762. ncb.ncb_lana_num = enums.lana[i];
  203763. ncb.ncb_buffer = (unsigned char*) &astat;
  203764. ncb.ncb_length = sizeof (ASTAT);
  203765. if (NetbiosCall (&ncb) == 0)
  203766. {
  203767. if (astat.adapt.adapter_type == 0xfe)
  203768. {
  203769. uint64 mac = 0;
  203770. for (int i = 6; --i >= 0;)
  203771. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  203772. if (numFound < maxNum && mac != 0)
  203773. addresses [numFound++] = mac;
  203774. }
  203775. }
  203776. }
  203777. }
  203778. }
  203779. return numFound;
  203780. }
  203781. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  203782. {
  203783. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  203784. if (numFound == 0)
  203785. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  203786. return numFound;
  203787. }
  203788. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  203789. const String& emailSubject,
  203790. const String& bodyText,
  203791. const StringArray& filesToAttach)
  203792. {
  203793. HMODULE h = LoadLibraryA ("MAPI32.dll");
  203794. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  203795. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  203796. bool ok = false;
  203797. if (mapiSendMail != 0)
  203798. {
  203799. MapiMessage message;
  203800. zerostruct (message);
  203801. message.lpszSubject = (LPSTR) emailSubject.toCString();
  203802. message.lpszNoteText = (LPSTR) bodyText.toCString();
  203803. MapiRecipDesc recip;
  203804. zerostruct (recip);
  203805. recip.ulRecipClass = MAPI_TO;
  203806. String targetEmailAddress_ (targetEmailAddress);
  203807. if (targetEmailAddress_.isEmpty())
  203808. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  203809. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  203810. message.nRecipCount = 1;
  203811. message.lpRecips = &recip;
  203812. HeapBlock <MapiFileDesc> files;
  203813. files.calloc (filesToAttach.size());
  203814. message.nFileCount = filesToAttach.size();
  203815. message.lpFiles = files;
  203816. for (int i = 0; i < filesToAttach.size(); ++i)
  203817. {
  203818. files[i].nPosition = (ULONG) -1;
  203819. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  203820. }
  203821. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  203822. }
  203823. FreeLibrary (h);
  203824. return ok;
  203825. }
  203826. #endif
  203827. /*** End of inlined file: juce_win32_Network.cpp ***/
  203828. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  203829. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203830. // compiled on its own).
  203831. #if JUCE_INCLUDED_FILE
  203832. static HKEY findKeyForPath (String name,
  203833. const bool createForWriting,
  203834. String& valueName)
  203835. {
  203836. HKEY rootKey = 0;
  203837. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  203838. rootKey = HKEY_CURRENT_USER;
  203839. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  203840. rootKey = HKEY_LOCAL_MACHINE;
  203841. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  203842. rootKey = HKEY_CLASSES_ROOT;
  203843. if (rootKey != 0)
  203844. {
  203845. name = name.substring (name.indexOfChar ('\\') + 1);
  203846. const int lastSlash = name.lastIndexOfChar ('\\');
  203847. valueName = name.substring (lastSlash + 1);
  203848. name = name.substring (0, lastSlash);
  203849. HKEY key;
  203850. DWORD result;
  203851. if (createForWriting)
  203852. {
  203853. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  203854. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  203855. return key;
  203856. }
  203857. else
  203858. {
  203859. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  203860. return key;
  203861. }
  203862. }
  203863. return 0;
  203864. }
  203865. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  203866. const String& defaultValue)
  203867. {
  203868. String valueName, result (defaultValue);
  203869. HKEY k = findKeyForPath (regValuePath, false, valueName);
  203870. if (k != 0)
  203871. {
  203872. WCHAR buffer [2048];
  203873. unsigned long bufferSize = sizeof (buffer);
  203874. DWORD type = REG_SZ;
  203875. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  203876. {
  203877. if (type == REG_SZ)
  203878. result = buffer;
  203879. else if (type == REG_DWORD)
  203880. result = String ((int) *(DWORD*) buffer);
  203881. }
  203882. RegCloseKey (k);
  203883. }
  203884. return result;
  203885. }
  203886. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  203887. const String& value)
  203888. {
  203889. String valueName;
  203890. HKEY k = findKeyForPath (regValuePath, true, valueName);
  203891. if (k != 0)
  203892. {
  203893. RegSetValueEx (k, valueName, 0, REG_SZ,
  203894. (const BYTE*) (const WCHAR*) value,
  203895. sizeof (WCHAR) * (value.length() + 1));
  203896. RegCloseKey (k);
  203897. }
  203898. }
  203899. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  203900. {
  203901. bool exists = false;
  203902. String valueName;
  203903. HKEY k = findKeyForPath (regValuePath, false, valueName);
  203904. if (k != 0)
  203905. {
  203906. unsigned char buffer [2048];
  203907. unsigned long bufferSize = sizeof (buffer);
  203908. DWORD type = 0;
  203909. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  203910. exists = true;
  203911. RegCloseKey (k);
  203912. }
  203913. return exists;
  203914. }
  203915. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  203916. {
  203917. String valueName;
  203918. HKEY k = findKeyForPath (regValuePath, true, valueName);
  203919. if (k != 0)
  203920. {
  203921. RegDeleteValue (k, valueName);
  203922. RegCloseKey (k);
  203923. }
  203924. }
  203925. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  203926. {
  203927. String valueName;
  203928. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  203929. if (k != 0)
  203930. {
  203931. RegDeleteKey (k, valueName);
  203932. RegCloseKey (k);
  203933. }
  203934. }
  203935. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  203936. const String& symbolicDescription,
  203937. const String& fullDescription,
  203938. const File& targetExecutable,
  203939. int iconResourceNumber)
  203940. {
  203941. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  203942. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  203943. if (iconResourceNumber != 0)
  203944. setRegistryValue (key + "\\DefaultIcon\\",
  203945. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  203946. setRegistryValue (key + "\\", fullDescription);
  203947. setRegistryValue (key + "\\shell\\open\\command\\",
  203948. targetExecutable.getFullPathName() + " %1");
  203949. }
  203950. bool juce_IsRunningInWine()
  203951. {
  203952. HKEY key;
  203953. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  203954. {
  203955. RegCloseKey (key);
  203956. return true;
  203957. }
  203958. return false;
  203959. }
  203960. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  203961. {
  203962. String s (::GetCommandLineW());
  203963. StringArray tokens;
  203964. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  203965. return tokens.joinIntoString (" ", 1);
  203966. }
  203967. static void* currentModuleHandle = 0;
  203968. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  203969. {
  203970. if (currentModuleHandle == 0)
  203971. currentModuleHandle = GetModuleHandle (0);
  203972. return currentModuleHandle;
  203973. }
  203974. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  203975. {
  203976. currentModuleHandle = newHandle;
  203977. }
  203978. void PlatformUtilities::fpuReset()
  203979. {
  203980. #if JUCE_MSVC
  203981. _clearfp();
  203982. #endif
  203983. }
  203984. void PlatformUtilities::beep()
  203985. {
  203986. MessageBeep (MB_OK);
  203987. }
  203988. #endif
  203989. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  203990. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203991. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  203992. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203993. // compiled on its own).
  203994. #if JUCE_INCLUDED_FILE
  203995. static const unsigned int specialId = WM_APP + 0x4400;
  203996. static const unsigned int broadcastId = WM_APP + 0x4403;
  203997. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  203998. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  203999. HWND juce_messageWindowHandle = 0;
  204000. extern long improbableWindowNumber; // defined in windowing.cpp
  204001. #ifndef WM_APPCOMMAND
  204002. #define WM_APPCOMMAND 0x0319
  204003. #endif
  204004. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204005. const UINT message,
  204006. const WPARAM wParam,
  204007. const LPARAM lParam) throw()
  204008. {
  204009. JUCE_TRY
  204010. {
  204011. if (h == juce_messageWindowHandle)
  204012. {
  204013. if (message == specialCallbackId)
  204014. {
  204015. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204016. return (LRESULT) (*func) ((void*) lParam);
  204017. }
  204018. else if (message == specialId)
  204019. {
  204020. // these are trapped early in the dispatch call, but must also be checked
  204021. // here in case there are windows modal dialog boxes doing their own
  204022. // dispatch loop and not calling our version
  204023. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  204024. return 0;
  204025. }
  204026. else if (message == broadcastId)
  204027. {
  204028. const ScopedPointer <String> messageString ((String*) lParam);
  204029. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204030. return 0;
  204031. }
  204032. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204033. {
  204034. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204035. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204036. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204037. return 0;
  204038. }
  204039. }
  204040. }
  204041. JUCE_CATCH_EXCEPTION
  204042. return DefWindowProc (h, message, wParam, lParam);
  204043. }
  204044. static bool isEventBlockedByModalComps (MSG& m)
  204045. {
  204046. if (Component::getNumCurrentlyModalComponents() == 0
  204047. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  204048. return false;
  204049. switch (m.message)
  204050. {
  204051. case WM_MOUSEMOVE:
  204052. case WM_NCMOUSEMOVE:
  204053. case 0x020A: /* WM_MOUSEWHEEL */
  204054. case 0x020E: /* WM_MOUSEHWHEEL */
  204055. case WM_KEYUP:
  204056. case WM_SYSKEYUP:
  204057. case WM_CHAR:
  204058. case WM_APPCOMMAND:
  204059. case WM_LBUTTONUP:
  204060. case WM_MBUTTONUP:
  204061. case WM_RBUTTONUP:
  204062. case WM_MOUSEACTIVATE:
  204063. case WM_NCMOUSEHOVER:
  204064. case WM_MOUSEHOVER:
  204065. return true;
  204066. case WM_NCLBUTTONDOWN:
  204067. case WM_NCLBUTTONDBLCLK:
  204068. case WM_NCRBUTTONDOWN:
  204069. case WM_NCRBUTTONDBLCLK:
  204070. case WM_NCMBUTTONDOWN:
  204071. case WM_NCMBUTTONDBLCLK:
  204072. case WM_LBUTTONDOWN:
  204073. case WM_LBUTTONDBLCLK:
  204074. case WM_MBUTTONDOWN:
  204075. case WM_MBUTTONDBLCLK:
  204076. case WM_RBUTTONDOWN:
  204077. case WM_RBUTTONDBLCLK:
  204078. case WM_KEYDOWN:
  204079. case WM_SYSKEYDOWN:
  204080. {
  204081. Component* const modal = Component::getCurrentlyModalComponent (0);
  204082. if (modal != 0)
  204083. modal->inputAttemptWhenModal();
  204084. return true;
  204085. }
  204086. default:
  204087. break;
  204088. }
  204089. return false;
  204090. }
  204091. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204092. {
  204093. MSG m;
  204094. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204095. return false;
  204096. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  204097. {
  204098. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  204099. {
  204100. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  204101. }
  204102. else if (m.message == WM_QUIT)
  204103. {
  204104. if (JUCEApplication::getInstance())
  204105. JUCEApplication::getInstance()->systemRequestedQuit();
  204106. }
  204107. else if (! isEventBlockedByModalComps (m))
  204108. {
  204109. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  204110. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  204111. {
  204112. // if it's someone else's window being clicked on, and the focus is
  204113. // currently on a juce window, pass the kb focus over..
  204114. HWND currentFocus = GetFocus();
  204115. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204116. SetFocus (m.hwnd);
  204117. }
  204118. TranslateMessage (&m);
  204119. DispatchMessage (&m);
  204120. }
  204121. }
  204122. return true;
  204123. }
  204124. bool juce_postMessageToSystemQueue (void* message)
  204125. {
  204126. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204127. }
  204128. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204129. void* userData)
  204130. {
  204131. if (MessageManager::getInstance()->isThisTheMessageThread())
  204132. {
  204133. return (*callback) (userData);
  204134. }
  204135. else
  204136. {
  204137. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204138. // deadlock because the message manager is blocked from running, and can't
  204139. // call your function..
  204140. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204141. return (void*) SendMessage (juce_messageWindowHandle,
  204142. specialCallbackId,
  204143. (WPARAM) callback,
  204144. (LPARAM) userData);
  204145. }
  204146. }
  204147. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204148. {
  204149. if (hwnd != juce_messageWindowHandle)
  204150. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  204151. return TRUE;
  204152. }
  204153. void MessageManager::broadcastMessage (const String& value) throw()
  204154. {
  204155. Array<void*> windows;
  204156. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204157. const String localCopy (value);
  204158. COPYDATASTRUCT data;
  204159. data.dwData = broadcastId;
  204160. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204161. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  204162. for (int i = windows.size(); --i >= 0;)
  204163. {
  204164. HWND hwnd = (HWND) windows.getUnchecked(i);
  204165. TCHAR windowName [64]; // no need to read longer strings than this
  204166. GetWindowText (hwnd, windowName, 64);
  204167. windowName [63] = 0;
  204168. if (String (windowName) == messageWindowName)
  204169. {
  204170. DWORD_PTR result;
  204171. SendMessageTimeout (hwnd, WM_COPYDATA,
  204172. (WPARAM) juce_messageWindowHandle,
  204173. (LPARAM) &data,
  204174. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204175. 8000,
  204176. &result);
  204177. }
  204178. }
  204179. }
  204180. static const String getMessageWindowClassName()
  204181. {
  204182. // this name has to be different for each app/dll instance because otherwise
  204183. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204184. // window class).
  204185. static int number = 0;
  204186. if (number == 0)
  204187. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204188. return "JUCEcs_" + String (number);
  204189. }
  204190. void MessageManager::doPlatformSpecificInitialisation()
  204191. {
  204192. OleInitialize (0);
  204193. const String className (getMessageWindowClassName());
  204194. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204195. WNDCLASSEX wc;
  204196. zerostruct (wc);
  204197. wc.cbSize = sizeof (wc);
  204198. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204199. wc.cbWndExtra = 4;
  204200. wc.hInstance = hmod;
  204201. wc.lpszClassName = className;
  204202. RegisterClassEx (&wc);
  204203. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204204. messageWindowName,
  204205. 0, 0, 0, 0, 0, 0, 0,
  204206. hmod, 0);
  204207. }
  204208. void MessageManager::doPlatformSpecificShutdown()
  204209. {
  204210. DestroyWindow (juce_messageWindowHandle);
  204211. UnregisterClass (getMessageWindowClassName(), 0);
  204212. OleUninitialize();
  204213. }
  204214. #endif
  204215. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  204216. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  204217. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204218. // compiled on its own).
  204219. #if JUCE_INCLUDED_FILE
  204220. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  204221. // these are in the windows SDK, but need to be repeated here for GCC..
  204222. #ifndef GET_APPCOMMAND_LPARAM
  204223. #define FAPPCOMMAND_MASK 0xF000
  204224. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  204225. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  204226. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  204227. #define APPCOMMAND_MEDIA_STOP 13
  204228. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  204229. #define WM_APPCOMMAND 0x0319
  204230. #endif
  204231. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  204232. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  204233. extern bool juce_IsRunningInWine();
  204234. #ifndef ULW_ALPHA
  204235. #define ULW_ALPHA 0x00000002
  204236. #endif
  204237. #ifndef AC_SRC_ALPHA
  204238. #define AC_SRC_ALPHA 0x01
  204239. #endif
  204240. static HPALETTE palette = 0;
  204241. static bool createPaletteIfNeeded = true;
  204242. static bool shouldDeactivateTitleBar = true;
  204243. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  204244. #define WM_TRAYNOTIFY WM_USER + 100
  204245. using ::abs;
  204246. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  204247. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  204248. bool Desktop::canUseSemiTransparentWindows() throw()
  204249. {
  204250. if (updateLayeredWindow == 0)
  204251. {
  204252. if (! juce_IsRunningInWine())
  204253. {
  204254. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  204255. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  204256. }
  204257. }
  204258. return updateLayeredWindow != 0;
  204259. }
  204260. const int extendedKeyModifier = 0x10000;
  204261. const int KeyPress::spaceKey = VK_SPACE;
  204262. const int KeyPress::returnKey = VK_RETURN;
  204263. const int KeyPress::escapeKey = VK_ESCAPE;
  204264. const int KeyPress::backspaceKey = VK_BACK;
  204265. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  204266. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  204267. const int KeyPress::tabKey = VK_TAB;
  204268. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  204269. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  204270. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  204271. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  204272. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  204273. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  204274. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  204275. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  204276. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  204277. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  204278. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  204279. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  204280. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  204281. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  204282. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  204283. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  204284. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  204285. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  204286. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  204287. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  204288. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  204289. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  204290. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  204291. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  204292. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  204293. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  204294. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  204295. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  204296. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  204297. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  204298. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  204299. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  204300. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  204301. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  204302. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  204303. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  204304. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  204305. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  204306. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  204307. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  204308. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  204309. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  204310. const int KeyPress::playKey = 0x30000;
  204311. const int KeyPress::stopKey = 0x30001;
  204312. const int KeyPress::fastForwardKey = 0x30002;
  204313. const int KeyPress::rewindKey = 0x30003;
  204314. class WindowsBitmapImage : public Image::SharedImage
  204315. {
  204316. public:
  204317. HBITMAP hBitmap;
  204318. BITMAPV4HEADER bitmapInfo;
  204319. HDC hdc;
  204320. unsigned char* bitmapData;
  204321. WindowsBitmapImage (const Image::PixelFormat format_,
  204322. const int w, const int h, const bool clearImage)
  204323. : Image::SharedImage (format_, w, h)
  204324. {
  204325. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  204326. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  204327. zerostruct (bitmapInfo);
  204328. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  204329. bitmapInfo.bV4Width = w;
  204330. bitmapInfo.bV4Height = h;
  204331. bitmapInfo.bV4Planes = 1;
  204332. bitmapInfo.bV4CSType = 1;
  204333. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  204334. if (format_ == Image::ARGB)
  204335. {
  204336. bitmapInfo.bV4AlphaMask = 0xff000000;
  204337. bitmapInfo.bV4RedMask = 0xff0000;
  204338. bitmapInfo.bV4GreenMask = 0xff00;
  204339. bitmapInfo.bV4BlueMask = 0xff;
  204340. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  204341. }
  204342. else
  204343. {
  204344. bitmapInfo.bV4V4Compression = BI_RGB;
  204345. }
  204346. lineStride = -((w * pixelStride + 3) & ~3);
  204347. HDC dc = GetDC (0);
  204348. hdc = CreateCompatibleDC (dc);
  204349. ReleaseDC (0, dc);
  204350. SetMapMode (hdc, MM_TEXT);
  204351. hBitmap = CreateDIBSection (hdc,
  204352. (BITMAPINFO*) &(bitmapInfo),
  204353. DIB_RGB_COLORS,
  204354. (void**) &bitmapData,
  204355. 0, 0);
  204356. SelectObject (hdc, hBitmap);
  204357. if (format_ == Image::ARGB && clearImage)
  204358. zeromem (bitmapData, abs (h * lineStride));
  204359. imageData = bitmapData - (lineStride * (h - 1));
  204360. }
  204361. ~WindowsBitmapImage()
  204362. {
  204363. DeleteDC (hdc);
  204364. DeleteObject (hBitmap);
  204365. }
  204366. Image::ImageType getType() const { return Image::NativeImage; }
  204367. LowLevelGraphicsContext* createLowLevelContext()
  204368. {
  204369. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  204370. }
  204371. SharedImage* clone()
  204372. {
  204373. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  204374. for (int i = 0; i < height; ++i)
  204375. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  204376. return im;
  204377. }
  204378. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  204379. const int x, const int y,
  204380. const RectangleList& maskedRegion) throw()
  204381. {
  204382. static HDRAWDIB hdd = 0;
  204383. static bool needToCreateDrawDib = true;
  204384. if (needToCreateDrawDib)
  204385. {
  204386. needToCreateDrawDib = false;
  204387. HDC dc = GetDC (0);
  204388. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204389. ReleaseDC (0, dc);
  204390. // only open if we're not palettised
  204391. if (n > 8)
  204392. hdd = DrawDibOpen();
  204393. }
  204394. if (createPaletteIfNeeded)
  204395. {
  204396. HDC dc = GetDC (0);
  204397. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204398. ReleaseDC (0, dc);
  204399. if (n <= 8)
  204400. palette = CreateHalftonePalette (dc);
  204401. createPaletteIfNeeded = false;
  204402. }
  204403. if (palette != 0)
  204404. {
  204405. SelectPalette (dc, palette, FALSE);
  204406. RealizePalette (dc);
  204407. SetStretchBltMode (dc, HALFTONE);
  204408. }
  204409. SetMapMode (dc, MM_TEXT);
  204410. if (transparent)
  204411. {
  204412. POINT p, pos;
  204413. SIZE size;
  204414. RECT windowBounds;
  204415. GetWindowRect (hwnd, &windowBounds);
  204416. p.x = -x;
  204417. p.y = -y;
  204418. pos.x = windowBounds.left;
  204419. pos.y = windowBounds.top;
  204420. size.cx = windowBounds.right - windowBounds.left;
  204421. size.cy = windowBounds.bottom - windowBounds.top;
  204422. BLENDFUNCTION bf;
  204423. bf.AlphaFormat = AC_SRC_ALPHA;
  204424. bf.BlendFlags = 0;
  204425. bf.BlendOp = AC_SRC_OVER;
  204426. bf.SourceConstantAlpha = 0xff;
  204427. if (! maskedRegion.isEmpty())
  204428. {
  204429. for (RectangleList::Iterator i (maskedRegion); i.next();)
  204430. {
  204431. const Rectangle<int>& r = *i.getRectangle();
  204432. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  204433. }
  204434. }
  204435. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  204436. }
  204437. else
  204438. {
  204439. int savedDC = 0;
  204440. if (! maskedRegion.isEmpty())
  204441. {
  204442. savedDC = SaveDC (dc);
  204443. for (RectangleList::Iterator i (maskedRegion); i.next();)
  204444. {
  204445. const Rectangle<int>& r = *i.getRectangle();
  204446. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  204447. }
  204448. }
  204449. if (hdd == 0)
  204450. {
  204451. StretchDIBits (dc,
  204452. x, y, width, height,
  204453. 0, 0, width, height,
  204454. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  204455. DIB_RGB_COLORS, SRCCOPY);
  204456. }
  204457. else
  204458. {
  204459. DrawDibDraw (hdd, dc, x, y, -1, -1,
  204460. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  204461. 0, 0, width, height, 0);
  204462. }
  204463. if (! maskedRegion.isEmpty())
  204464. RestoreDC (dc, savedDC);
  204465. }
  204466. }
  204467. juce_UseDebuggingNewOperator
  204468. private:
  204469. WindowsBitmapImage (const WindowsBitmapImage&);
  204470. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  204471. };
  204472. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  204473. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  204474. {
  204475. SHORT k = (SHORT) keyCode;
  204476. if ((keyCode & extendedKeyModifier) == 0
  204477. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  204478. k += (SHORT) 'A' - (SHORT) 'a';
  204479. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  204480. (SHORT) '+', VK_OEM_PLUS,
  204481. (SHORT) '-', VK_OEM_MINUS,
  204482. (SHORT) '.', VK_OEM_PERIOD,
  204483. (SHORT) ';', VK_OEM_1,
  204484. (SHORT) ':', VK_OEM_1,
  204485. (SHORT) '/', VK_OEM_2,
  204486. (SHORT) '?', VK_OEM_2,
  204487. (SHORT) '[', VK_OEM_4,
  204488. (SHORT) ']', VK_OEM_6 };
  204489. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  204490. if (k == translatedValues [i])
  204491. k = translatedValues [i + 1];
  204492. return (GetKeyState (k) & 0x8000) != 0;
  204493. }
  204494. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  204495. {
  204496. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  204497. return callback (userData);
  204498. else
  204499. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  204500. }
  204501. class Win32ComponentPeer : public ComponentPeer
  204502. {
  204503. public:
  204504. Win32ComponentPeer (Component* const component,
  204505. const int windowStyleFlags)
  204506. : ComponentPeer (component, windowStyleFlags),
  204507. dontRepaint (false),
  204508. fullScreen (false),
  204509. isDragging (false),
  204510. isMouseOver (false),
  204511. hasCreatedCaret (false),
  204512. currentWindowIcon (0),
  204513. taskBarIcon (0),
  204514. dropTarget (0)
  204515. {
  204516. callFunctionIfNotLocked (&createWindowCallback, this);
  204517. setTitle (component->getName());
  204518. if ((windowStyleFlags & windowHasDropShadow) != 0
  204519. && Desktop::canUseSemiTransparentWindows())
  204520. {
  204521. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  204522. if (shadower != 0)
  204523. shadower->setOwner (component);
  204524. }
  204525. else
  204526. {
  204527. shadower = 0;
  204528. }
  204529. }
  204530. ~Win32ComponentPeer()
  204531. {
  204532. setTaskBarIcon (Image());
  204533. deleteAndZero (shadower);
  204534. // do this before the next bit to avoid messages arriving for this window
  204535. // before it's destroyed
  204536. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  204537. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  204538. if (currentWindowIcon != 0)
  204539. DestroyIcon (currentWindowIcon);
  204540. if (dropTarget != 0)
  204541. {
  204542. dropTarget->Release();
  204543. dropTarget = 0;
  204544. }
  204545. }
  204546. void* getNativeHandle() const
  204547. {
  204548. return hwnd;
  204549. }
  204550. void setVisible (bool shouldBeVisible)
  204551. {
  204552. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204553. if (shouldBeVisible)
  204554. InvalidateRect (hwnd, 0, 0);
  204555. else
  204556. lastPaintTime = 0;
  204557. }
  204558. void setTitle (const String& title)
  204559. {
  204560. SetWindowText (hwnd, title);
  204561. }
  204562. void setPosition (int x, int y)
  204563. {
  204564. offsetWithinParent (x, y);
  204565. SetWindowPos (hwnd, 0,
  204566. x - windowBorder.getLeft(),
  204567. y - windowBorder.getTop(),
  204568. 0, 0,
  204569. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204570. }
  204571. void repaintNowIfTransparent()
  204572. {
  204573. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  204574. handlePaintMessage();
  204575. }
  204576. void updateBorderSize()
  204577. {
  204578. WINDOWINFO info;
  204579. info.cbSize = sizeof (info);
  204580. if (GetWindowInfo (hwnd, &info))
  204581. {
  204582. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  204583. info.rcClient.left - info.rcWindow.left,
  204584. info.rcWindow.bottom - info.rcClient.bottom,
  204585. info.rcWindow.right - info.rcClient.right);
  204586. }
  204587. }
  204588. void setSize (int w, int h)
  204589. {
  204590. SetWindowPos (hwnd, 0, 0, 0,
  204591. w + windowBorder.getLeftAndRight(),
  204592. h + windowBorder.getTopAndBottom(),
  204593. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204594. updateBorderSize();
  204595. repaintNowIfTransparent();
  204596. }
  204597. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  204598. {
  204599. fullScreen = isNowFullScreen;
  204600. offsetWithinParent (x, y);
  204601. SetWindowPos (hwnd, 0,
  204602. x - windowBorder.getLeft(),
  204603. y - windowBorder.getTop(),
  204604. w + windowBorder.getLeftAndRight(),
  204605. h + windowBorder.getTopAndBottom(),
  204606. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204607. updateBorderSize();
  204608. repaintNowIfTransparent();
  204609. }
  204610. const Rectangle<int> getBounds() const
  204611. {
  204612. RECT r;
  204613. GetWindowRect (hwnd, &r);
  204614. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  204615. HWND parentH = GetParent (hwnd);
  204616. if (parentH != 0)
  204617. {
  204618. GetWindowRect (parentH, &r);
  204619. bounds.translate (-r.left, -r.top);
  204620. }
  204621. return windowBorder.subtractedFrom (bounds);
  204622. }
  204623. const Point<int> getScreenPosition() const
  204624. {
  204625. RECT r;
  204626. GetWindowRect (hwnd, &r);
  204627. return Point<int> (r.left + windowBorder.getLeft(),
  204628. r.top + windowBorder.getTop());
  204629. }
  204630. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  204631. {
  204632. return relativePosition + getScreenPosition();
  204633. }
  204634. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  204635. {
  204636. return screenPosition - getScreenPosition();
  204637. }
  204638. void setMinimised (bool shouldBeMinimised)
  204639. {
  204640. if (shouldBeMinimised != isMinimised())
  204641. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  204642. }
  204643. bool isMinimised() const
  204644. {
  204645. WINDOWPLACEMENT wp;
  204646. wp.length = sizeof (WINDOWPLACEMENT);
  204647. GetWindowPlacement (hwnd, &wp);
  204648. return wp.showCmd == SW_SHOWMINIMIZED;
  204649. }
  204650. void setFullScreen (bool shouldBeFullScreen)
  204651. {
  204652. setMinimised (false);
  204653. if (fullScreen != shouldBeFullScreen)
  204654. {
  204655. fullScreen = shouldBeFullScreen;
  204656. const Component::SafePointer<Component> deletionChecker (component);
  204657. if (! fullScreen)
  204658. {
  204659. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  204660. if (hasTitleBar())
  204661. ShowWindow (hwnd, SW_SHOWNORMAL);
  204662. if (! boundsCopy.isEmpty())
  204663. {
  204664. setBounds (boundsCopy.getX(),
  204665. boundsCopy.getY(),
  204666. boundsCopy.getWidth(),
  204667. boundsCopy.getHeight(),
  204668. false);
  204669. }
  204670. }
  204671. else
  204672. {
  204673. if (hasTitleBar())
  204674. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  204675. else
  204676. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  204677. }
  204678. if (deletionChecker != 0)
  204679. handleMovedOrResized();
  204680. }
  204681. }
  204682. bool isFullScreen() const
  204683. {
  204684. if (! hasTitleBar())
  204685. return fullScreen;
  204686. WINDOWPLACEMENT wp;
  204687. wp.length = sizeof (wp);
  204688. GetWindowPlacement (hwnd, &wp);
  204689. return wp.showCmd == SW_SHOWMAXIMIZED;
  204690. }
  204691. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  204692. {
  204693. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  204694. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  204695. return false;
  204696. RECT r;
  204697. GetWindowRect (hwnd, &r);
  204698. POINT p;
  204699. p.x = position.getX() + r.left + windowBorder.getLeft();
  204700. p.y = position.getY() + r.top + windowBorder.getTop();
  204701. HWND w = WindowFromPoint (p);
  204702. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  204703. }
  204704. const BorderSize getFrameSize() const
  204705. {
  204706. return windowBorder;
  204707. }
  204708. bool setAlwaysOnTop (bool alwaysOnTop)
  204709. {
  204710. const bool oldDeactivate = shouldDeactivateTitleBar;
  204711. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  204712. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  204713. 0, 0, 0, 0,
  204714. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  204715. shouldDeactivateTitleBar = oldDeactivate;
  204716. if (shadower != 0)
  204717. shadower->componentBroughtToFront (*component);
  204718. return true;
  204719. }
  204720. void toFront (bool makeActive)
  204721. {
  204722. setMinimised (false);
  204723. const bool oldDeactivate = shouldDeactivateTitleBar;
  204724. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  204725. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  204726. shouldDeactivateTitleBar = oldDeactivate;
  204727. if (! makeActive)
  204728. {
  204729. // in this case a broughttofront call won't have occured, so do it now..
  204730. handleBroughtToFront();
  204731. }
  204732. }
  204733. void toBehind (ComponentPeer* other)
  204734. {
  204735. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  204736. jassert (otherPeer != 0); // wrong type of window?
  204737. if (otherPeer != 0)
  204738. {
  204739. setMinimised (false);
  204740. // must be careful not to try to put a topmost window behind a normal one, or win32
  204741. // promotes the normal one to be topmost!
  204742. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  204743. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  204744. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  204745. else if (otherPeer->getComponent()->isAlwaysOnTop())
  204746. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  204747. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  204748. }
  204749. }
  204750. bool isFocused() const
  204751. {
  204752. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  204753. }
  204754. void grabFocus()
  204755. {
  204756. const bool oldDeactivate = shouldDeactivateTitleBar;
  204757. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  204758. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  204759. shouldDeactivateTitleBar = oldDeactivate;
  204760. }
  204761. void textInputRequired (const Point<int>&)
  204762. {
  204763. if (! hasCreatedCaret)
  204764. {
  204765. hasCreatedCaret = true;
  204766. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  204767. }
  204768. ShowCaret (hwnd);
  204769. SetCaretPos (0, 0);
  204770. }
  204771. void repaint (const Rectangle<int>& area)
  204772. {
  204773. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  204774. InvalidateRect (hwnd, &r, FALSE);
  204775. }
  204776. void performAnyPendingRepaintsNow()
  204777. {
  204778. MSG m;
  204779. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  204780. DispatchMessage (&m);
  204781. }
  204782. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  204783. {
  204784. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  204785. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  204786. return 0;
  204787. }
  204788. void setTaskBarIcon (const Image& image)
  204789. {
  204790. if (image.isValid())
  204791. {
  204792. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  204793. if (taskBarIcon == 0)
  204794. {
  204795. taskBarIcon = new NOTIFYICONDATA();
  204796. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  204797. taskBarIcon->hWnd = (HWND) hwnd;
  204798. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  204799. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  204800. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  204801. taskBarIcon->hIcon = hicon;
  204802. taskBarIcon->szTip[0] = 0;
  204803. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  204804. }
  204805. else
  204806. {
  204807. HICON oldIcon = taskBarIcon->hIcon;
  204808. taskBarIcon->hIcon = hicon;
  204809. taskBarIcon->uFlags = NIF_ICON;
  204810. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  204811. DestroyIcon (oldIcon);
  204812. }
  204813. DestroyIcon (hicon);
  204814. }
  204815. else if (taskBarIcon != 0)
  204816. {
  204817. taskBarIcon->uFlags = 0;
  204818. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  204819. DestroyIcon (taskBarIcon->hIcon);
  204820. deleteAndZero (taskBarIcon);
  204821. }
  204822. }
  204823. void setTaskBarIconToolTip (const String& toolTip) const
  204824. {
  204825. if (taskBarIcon != 0)
  204826. {
  204827. taskBarIcon->uFlags = NIF_TIP;
  204828. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  204829. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  204830. }
  204831. }
  204832. bool isInside (HWND h) const
  204833. {
  204834. return GetAncestor (hwnd, GA_ROOT) == h;
  204835. }
  204836. static void updateKeyModifiers() throw()
  204837. {
  204838. int keyMods = 0;
  204839. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  204840. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  204841. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  204842. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  204843. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  204844. }
  204845. static void updateModifiersFromWParam (const WPARAM wParam)
  204846. {
  204847. int mouseMods = 0;
  204848. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  204849. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  204850. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  204851. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  204852. updateKeyModifiers();
  204853. }
  204854. static int64 getMouseEventTime()
  204855. {
  204856. static int64 eventTimeOffset = 0;
  204857. static DWORD lastMessageTime = 0;
  204858. const DWORD thisMessageTime = GetMessageTime();
  204859. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  204860. {
  204861. lastMessageTime = thisMessageTime;
  204862. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  204863. }
  204864. return eventTimeOffset + thisMessageTime;
  204865. }
  204866. juce_UseDebuggingNewOperator
  204867. bool dontRepaint;
  204868. static ModifierKeys currentModifiers;
  204869. static ModifierKeys modifiersAtLastCallback;
  204870. private:
  204871. HWND hwnd;
  204872. DropShadower* shadower;
  204873. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  204874. BorderSize windowBorder;
  204875. HICON currentWindowIcon;
  204876. NOTIFYICONDATA* taskBarIcon;
  204877. IDropTarget* dropTarget;
  204878. class TemporaryImage : public Timer
  204879. {
  204880. public:
  204881. TemporaryImage() {}
  204882. ~TemporaryImage() {}
  204883. const Image& getImage (const bool transparent, const int w, const int h)
  204884. {
  204885. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  204886. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  204887. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  204888. startTimer (3000);
  204889. return image;
  204890. }
  204891. void timerCallback()
  204892. {
  204893. stopTimer();
  204894. image = Image();
  204895. }
  204896. private:
  204897. Image image;
  204898. TemporaryImage (const TemporaryImage&);
  204899. TemporaryImage& operator= (const TemporaryImage&);
  204900. };
  204901. TemporaryImage offscreenImageGenerator;
  204902. class WindowClassHolder : public DeletedAtShutdown
  204903. {
  204904. public:
  204905. WindowClassHolder()
  204906. : windowClassName ("JUCE_")
  204907. {
  204908. // this name has to be different for each app/dll instance because otherwise
  204909. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204910. // window class).
  204911. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  204912. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204913. TCHAR moduleFile [1024];
  204914. moduleFile[0] = 0;
  204915. GetModuleFileName (moduleHandle, moduleFile, 1024);
  204916. WORD iconNum = 0;
  204917. WNDCLASSEX wcex;
  204918. wcex.cbSize = sizeof (wcex);
  204919. wcex.style = CS_OWNDC;
  204920. wcex.lpfnWndProc = (WNDPROC) windowProc;
  204921. wcex.lpszClassName = windowClassName;
  204922. wcex.cbClsExtra = 0;
  204923. wcex.cbWndExtra = 32;
  204924. wcex.hInstance = moduleHandle;
  204925. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  204926. iconNum = 1;
  204927. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  204928. wcex.hCursor = 0;
  204929. wcex.hbrBackground = 0;
  204930. wcex.lpszMenuName = 0;
  204931. RegisterClassEx (&wcex);
  204932. }
  204933. ~WindowClassHolder()
  204934. {
  204935. if (ComponentPeer::getNumPeers() == 0)
  204936. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  204937. clearSingletonInstance();
  204938. }
  204939. String windowClassName;
  204940. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  204941. };
  204942. static void* createWindowCallback (void* userData)
  204943. {
  204944. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  204945. return 0;
  204946. }
  204947. void createWindow()
  204948. {
  204949. DWORD exstyle = WS_EX_ACCEPTFILES;
  204950. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  204951. if (hasTitleBar())
  204952. {
  204953. type |= WS_OVERLAPPED;
  204954. if ((styleFlags & windowHasCloseButton) != 0)
  204955. {
  204956. type |= WS_SYSMENU;
  204957. }
  204958. else
  204959. {
  204960. // annoyingly, windows won't let you have a min/max button without a close button
  204961. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  204962. }
  204963. if ((styleFlags & windowIsResizable) != 0)
  204964. type |= WS_THICKFRAME;
  204965. }
  204966. else
  204967. {
  204968. type |= WS_POPUP | WS_SYSMENU;
  204969. }
  204970. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  204971. exstyle |= WS_EX_TOOLWINDOW;
  204972. else
  204973. exstyle |= WS_EX_APPWINDOW;
  204974. if ((styleFlags & windowHasMinimiseButton) != 0)
  204975. type |= WS_MINIMIZEBOX;
  204976. if ((styleFlags & windowHasMaximiseButton) != 0)
  204977. type |= WS_MAXIMIZEBOX;
  204978. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  204979. exstyle |= WS_EX_TRANSPARENT;
  204980. if ((styleFlags & windowIsSemiTransparent) != 0
  204981. && Desktop::canUseSemiTransparentWindows())
  204982. exstyle |= WS_EX_LAYERED;
  204983. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  204984. if (hwnd != 0)
  204985. {
  204986. SetWindowLongPtr (hwnd, 0, 0);
  204987. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  204988. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  204989. if (dropTarget == 0)
  204990. dropTarget = new JuceDropTarget (this);
  204991. RegisterDragDrop (hwnd, dropTarget);
  204992. updateBorderSize();
  204993. // Calling this function here is (for some reason) necessary to make Windows
  204994. // correctly enable the menu items that we specify in the wm_initmenu message.
  204995. GetSystemMenu (hwnd, false);
  204996. }
  204997. else
  204998. {
  204999. jassertfalse;
  205000. }
  205001. }
  205002. static void* destroyWindowCallback (void* handle)
  205003. {
  205004. RevokeDragDrop ((HWND) handle);
  205005. DestroyWindow ((HWND) handle);
  205006. return 0;
  205007. }
  205008. static void* toFrontCallback1 (void* h)
  205009. {
  205010. SetForegroundWindow ((HWND) h);
  205011. return 0;
  205012. }
  205013. static void* toFrontCallback2 (void* h)
  205014. {
  205015. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205016. return 0;
  205017. }
  205018. static void* setFocusCallback (void* h)
  205019. {
  205020. SetFocus ((HWND) h);
  205021. return 0;
  205022. }
  205023. static void* getFocusCallback (void*)
  205024. {
  205025. return GetFocus();
  205026. }
  205027. void offsetWithinParent (int& x, int& y) const
  205028. {
  205029. if (isTransparent())
  205030. {
  205031. HWND parentHwnd = GetParent (hwnd);
  205032. if (parentHwnd != 0)
  205033. {
  205034. RECT parentRect;
  205035. GetWindowRect (parentHwnd, &parentRect);
  205036. x += parentRect.left;
  205037. y += parentRect.top;
  205038. }
  205039. }
  205040. }
  205041. bool isTransparent() const
  205042. {
  205043. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  205044. }
  205045. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  205046. void setIcon (const Image& newIcon)
  205047. {
  205048. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  205049. if (hicon != 0)
  205050. {
  205051. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  205052. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  205053. if (currentWindowIcon != 0)
  205054. DestroyIcon (currentWindowIcon);
  205055. currentWindowIcon = hicon;
  205056. }
  205057. }
  205058. void handlePaintMessage()
  205059. {
  205060. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  205061. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  205062. PAINTSTRUCT paintStruct;
  205063. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  205064. // message and become re-entrant, but that's OK
  205065. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  205066. // corrupt the image it's using to paint into, so do a check here.
  205067. static bool reentrant = false;
  205068. if (reentrant)
  205069. {
  205070. DeleteObject (rgn);
  205071. EndPaint (hwnd, &paintStruct);
  205072. return;
  205073. }
  205074. reentrant = true;
  205075. // this is the rectangle to update..
  205076. int x = paintStruct.rcPaint.left;
  205077. int y = paintStruct.rcPaint.top;
  205078. int w = paintStruct.rcPaint.right - x;
  205079. int h = paintStruct.rcPaint.bottom - y;
  205080. const bool transparent = isTransparent();
  205081. if (transparent)
  205082. {
  205083. // it's not possible to have a transparent window with a title bar at the moment!
  205084. jassert (! hasTitleBar());
  205085. RECT r;
  205086. GetWindowRect (hwnd, &r);
  205087. x = y = 0;
  205088. w = r.right - r.left;
  205089. h = r.bottom - r.top;
  205090. }
  205091. if (w > 0 && h > 0)
  205092. {
  205093. clearMaskedRegion();
  205094. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  205095. RectangleList contextClip;
  205096. const Rectangle<int> clipBounds (0, 0, w, h);
  205097. bool needToPaintAll = true;
  205098. if (regionType == COMPLEXREGION && ! transparent)
  205099. {
  205100. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  205101. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  205102. DeleteObject (clipRgn);
  205103. char rgnData [8192];
  205104. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  205105. if (res > 0 && res <= sizeof (rgnData))
  205106. {
  205107. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  205108. if (hdr->iType == RDH_RECTANGLES
  205109. && hdr->rcBound.right - hdr->rcBound.left >= w
  205110. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  205111. {
  205112. needToPaintAll = false;
  205113. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  205114. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  205115. while (--num >= 0)
  205116. {
  205117. if (rects->right <= x + w && rects->bottom <= y + h)
  205118. {
  205119. // (need to move this one pixel to the left because of a win32 bug)
  205120. const int cx = jmax (x, (int) rects->left - 1);
  205121. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  205122. .getIntersection (clipBounds));
  205123. }
  205124. else
  205125. {
  205126. needToPaintAll = true;
  205127. break;
  205128. }
  205129. ++rects;
  205130. }
  205131. }
  205132. }
  205133. }
  205134. if (needToPaintAll)
  205135. {
  205136. contextClip.clear();
  205137. contextClip.addWithoutMerging (Rectangle<int> (0, 0, w, h));
  205138. }
  205139. if (transparent)
  205140. {
  205141. RectangleList::Iterator i (contextClip);
  205142. while (i.next())
  205143. offscreenImage.clear (*i.getRectangle());
  205144. }
  205145. // if the component's not opaque, this won't draw properly unless the platform can support this
  205146. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  205147. updateCurrentModifiers();
  205148. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  205149. handlePaint (context);
  205150. if (! dontRepaint)
  205151. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  205152. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  205153. }
  205154. DeleteObject (rgn);
  205155. EndPaint (hwnd, &paintStruct);
  205156. reentrant = false;
  205157. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  205158. _fpreset(); // because some graphics cards can unmask FP exceptions
  205159. #endif
  205160. lastPaintTime = Time::getMillisecondCounter();
  205161. }
  205162. void doMouseEvent (const Point<int>& position)
  205163. {
  205164. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  205165. }
  205166. void doMouseMove (const Point<int>& position)
  205167. {
  205168. if (! isMouseOver)
  205169. {
  205170. isMouseOver = true;
  205171. updateKeyModifiers();
  205172. TRACKMOUSEEVENT tme;
  205173. tme.cbSize = sizeof (tme);
  205174. tme.dwFlags = TME_LEAVE;
  205175. tme.hwndTrack = hwnd;
  205176. tme.dwHoverTime = 0;
  205177. if (! TrackMouseEvent (&tme))
  205178. jassertfalse;
  205179. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  205180. }
  205181. else if (! isDragging)
  205182. {
  205183. if (! contains (position, false))
  205184. return;
  205185. }
  205186. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  205187. static uint32 lastMouseTime = 0;
  205188. const uint32 now = Time::getMillisecondCounter();
  205189. const int maxMouseMovesPerSecond = 60;
  205190. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205191. {
  205192. lastMouseTime = now;
  205193. doMouseEvent (position);
  205194. }
  205195. }
  205196. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  205197. {
  205198. if (GetCapture() != hwnd)
  205199. SetCapture (hwnd);
  205200. doMouseMove (position);
  205201. updateModifiersFromWParam (wParam);
  205202. isDragging = true;
  205203. doMouseEvent (position);
  205204. }
  205205. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  205206. {
  205207. updateModifiersFromWParam (wParam);
  205208. isDragging = false;
  205209. // release the mouse capture if the user has released all buttons
  205210. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  205211. ReleaseCapture();
  205212. doMouseEvent (position);
  205213. }
  205214. void doCaptureChanged()
  205215. {
  205216. if (isDragging)
  205217. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  205218. }
  205219. void doMouseExit()
  205220. {
  205221. isMouseOver = false;
  205222. doMouseEvent (getCurrentMousePos());
  205223. }
  205224. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  205225. {
  205226. updateKeyModifiers();
  205227. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  205228. handleMouseWheel (0, position, getMouseEventTime(),
  205229. isVertical ? 0.0f : amount,
  205230. isVertical ? amount : 0.0f);
  205231. }
  205232. void sendModifierKeyChangeIfNeeded()
  205233. {
  205234. if (modifiersAtLastCallback != currentModifiers)
  205235. {
  205236. modifiersAtLastCallback = currentModifiers;
  205237. handleModifierKeysChange();
  205238. }
  205239. }
  205240. bool doKeyUp (const WPARAM key)
  205241. {
  205242. updateKeyModifiers();
  205243. switch (key)
  205244. {
  205245. case VK_SHIFT:
  205246. case VK_CONTROL:
  205247. case VK_MENU:
  205248. case VK_CAPITAL:
  205249. case VK_LWIN:
  205250. case VK_RWIN:
  205251. case VK_APPS:
  205252. case VK_NUMLOCK:
  205253. case VK_SCROLL:
  205254. case VK_LSHIFT:
  205255. case VK_RSHIFT:
  205256. case VK_LCONTROL:
  205257. case VK_LMENU:
  205258. case VK_RCONTROL:
  205259. case VK_RMENU:
  205260. sendModifierKeyChangeIfNeeded();
  205261. }
  205262. return handleKeyUpOrDown (false)
  205263. || Component::getCurrentlyModalComponent() != 0;
  205264. }
  205265. bool doKeyDown (const WPARAM key)
  205266. {
  205267. updateKeyModifiers();
  205268. bool used = false;
  205269. switch (key)
  205270. {
  205271. case VK_SHIFT:
  205272. case VK_LSHIFT:
  205273. case VK_RSHIFT:
  205274. case VK_CONTROL:
  205275. case VK_LCONTROL:
  205276. case VK_RCONTROL:
  205277. case VK_MENU:
  205278. case VK_LMENU:
  205279. case VK_RMENU:
  205280. case VK_LWIN:
  205281. case VK_RWIN:
  205282. case VK_CAPITAL:
  205283. case VK_NUMLOCK:
  205284. case VK_SCROLL:
  205285. case VK_APPS:
  205286. sendModifierKeyChangeIfNeeded();
  205287. break;
  205288. case VK_LEFT:
  205289. case VK_RIGHT:
  205290. case VK_UP:
  205291. case VK_DOWN:
  205292. case VK_PRIOR:
  205293. case VK_NEXT:
  205294. case VK_HOME:
  205295. case VK_END:
  205296. case VK_DELETE:
  205297. case VK_INSERT:
  205298. case VK_F1:
  205299. case VK_F2:
  205300. case VK_F3:
  205301. case VK_F4:
  205302. case VK_F5:
  205303. case VK_F6:
  205304. case VK_F7:
  205305. case VK_F8:
  205306. case VK_F9:
  205307. case VK_F10:
  205308. case VK_F11:
  205309. case VK_F12:
  205310. case VK_F13:
  205311. case VK_F14:
  205312. case VK_F15:
  205313. case VK_F16:
  205314. used = handleKeyUpOrDown (true);
  205315. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  205316. break;
  205317. case VK_ADD:
  205318. case VK_SUBTRACT:
  205319. case VK_MULTIPLY:
  205320. case VK_DIVIDE:
  205321. case VK_SEPARATOR:
  205322. case VK_DECIMAL:
  205323. used = handleKeyUpOrDown (true);
  205324. break;
  205325. default:
  205326. used = handleKeyUpOrDown (true);
  205327. {
  205328. MSG msg;
  205329. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  205330. {
  205331. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  205332. // manually generate the key-press event that matches this key-down.
  205333. const UINT keyChar = MapVirtualKey (key, 2);
  205334. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  205335. }
  205336. }
  205337. break;
  205338. }
  205339. if (Component::getCurrentlyModalComponent() != 0)
  205340. used = true;
  205341. return used;
  205342. }
  205343. bool doKeyChar (int key, const LPARAM flags)
  205344. {
  205345. updateKeyModifiers();
  205346. juce_wchar textChar = (juce_wchar) key;
  205347. const int virtualScanCode = (flags >> 16) & 0xff;
  205348. if (key >= '0' && key <= '9')
  205349. {
  205350. switch (virtualScanCode) // check for a numeric keypad scan-code
  205351. {
  205352. case 0x52:
  205353. case 0x4f:
  205354. case 0x50:
  205355. case 0x51:
  205356. case 0x4b:
  205357. case 0x4c:
  205358. case 0x4d:
  205359. case 0x47:
  205360. case 0x48:
  205361. case 0x49:
  205362. key = (key - '0') + KeyPress::numberPad0;
  205363. break;
  205364. default:
  205365. break;
  205366. }
  205367. }
  205368. else
  205369. {
  205370. // convert the scan code to an unmodified character code..
  205371. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  205372. UINT keyChar = MapVirtualKey (virtualKey, 2);
  205373. keyChar = LOWORD (keyChar);
  205374. if (keyChar != 0)
  205375. key = (int) keyChar;
  205376. // avoid sending junk text characters for some control-key combinations
  205377. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  205378. textChar = 0;
  205379. }
  205380. return handleKeyPress (key, textChar);
  205381. }
  205382. bool doAppCommand (const LPARAM lParam)
  205383. {
  205384. int key = 0;
  205385. switch (GET_APPCOMMAND_LPARAM (lParam))
  205386. {
  205387. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  205388. key = KeyPress::playKey;
  205389. break;
  205390. case APPCOMMAND_MEDIA_STOP:
  205391. key = KeyPress::stopKey;
  205392. break;
  205393. case APPCOMMAND_MEDIA_NEXTTRACK:
  205394. key = KeyPress::fastForwardKey;
  205395. break;
  205396. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  205397. key = KeyPress::rewindKey;
  205398. break;
  205399. }
  205400. if (key != 0)
  205401. {
  205402. updateKeyModifiers();
  205403. if (hwnd == GetActiveWindow())
  205404. {
  205405. handleKeyPress (key, 0);
  205406. return true;
  205407. }
  205408. }
  205409. return false;
  205410. }
  205411. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  205412. {
  205413. public:
  205414. JuceDropTarget (Win32ComponentPeer* const owner_)
  205415. : owner (owner_)
  205416. {
  205417. }
  205418. ~JuceDropTarget() {}
  205419. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205420. {
  205421. updateFileList (pDataObject);
  205422. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205423. *pdwEffect = DROPEFFECT_COPY;
  205424. return S_OK;
  205425. }
  205426. HRESULT __stdcall DragLeave()
  205427. {
  205428. owner->handleFileDragExit (files);
  205429. return S_OK;
  205430. }
  205431. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205432. {
  205433. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205434. *pdwEffect = DROPEFFECT_COPY;
  205435. return S_OK;
  205436. }
  205437. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205438. {
  205439. updateFileList (pDataObject);
  205440. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205441. *pdwEffect = DROPEFFECT_COPY;
  205442. return S_OK;
  205443. }
  205444. private:
  205445. Win32ComponentPeer* const owner;
  205446. StringArray files;
  205447. void updateFileList (IDataObject* const pDataObject)
  205448. {
  205449. files.clear();
  205450. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  205451. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  205452. if (pDataObject->GetData (&format, &medium) == S_OK)
  205453. {
  205454. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  205455. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  205456. unsigned int i = 0;
  205457. if (pDropFiles->fWide)
  205458. {
  205459. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  205460. for (;;)
  205461. {
  205462. unsigned int len = 0;
  205463. while (i + len < totalLen && fname [i + len] != 0)
  205464. ++len;
  205465. if (len == 0)
  205466. break;
  205467. files.add (String (fname + i, len));
  205468. i += len + 1;
  205469. }
  205470. }
  205471. else
  205472. {
  205473. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  205474. for (;;)
  205475. {
  205476. unsigned int len = 0;
  205477. while (i + len < totalLen && fname [i + len] != 0)
  205478. ++len;
  205479. if (len == 0)
  205480. break;
  205481. files.add (String (fname + i, len));
  205482. i += len + 1;
  205483. }
  205484. }
  205485. GlobalUnlock (medium.hGlobal);
  205486. }
  205487. }
  205488. JuceDropTarget (const JuceDropTarget&);
  205489. JuceDropTarget& operator= (const JuceDropTarget&);
  205490. };
  205491. void doSettingChange()
  205492. {
  205493. Desktop::getInstance().refreshMonitorSizes();
  205494. if (fullScreen && ! isMinimised())
  205495. {
  205496. const Rectangle<int> r (component->getParentMonitorArea());
  205497. SetWindowPos (hwnd, 0,
  205498. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  205499. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  205500. }
  205501. }
  205502. public:
  205503. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  205504. {
  205505. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  205506. if (peer != 0)
  205507. return peer->peerWindowProc (h, message, wParam, lParam);
  205508. return DefWindowProcW (h, message, wParam, lParam);
  205509. }
  205510. private:
  205511. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  205512. {
  205513. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  205514. }
  205515. const Point<int> getCurrentMousePos() throw()
  205516. {
  205517. RECT wr;
  205518. GetWindowRect (hwnd, &wr);
  205519. const DWORD mp = GetMessagePos();
  205520. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  205521. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  205522. }
  205523. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  205524. {
  205525. if (isValidPeer (this))
  205526. {
  205527. switch (message)
  205528. {
  205529. case WM_NCHITTEST:
  205530. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205531. return HTTRANSPARENT;
  205532. if (hasTitleBar())
  205533. break;
  205534. return HTCLIENT;
  205535. case WM_PAINT:
  205536. handlePaintMessage();
  205537. return 0;
  205538. case WM_NCPAINT:
  205539. if (wParam != 1)
  205540. handlePaintMessage();
  205541. if (hasTitleBar())
  205542. break;
  205543. return 0;
  205544. case WM_ERASEBKGND:
  205545. case WM_NCCALCSIZE:
  205546. if (hasTitleBar())
  205547. break;
  205548. return 1;
  205549. case WM_MOUSEMOVE:
  205550. doMouseMove (getPointFromLParam (lParam));
  205551. return 0;
  205552. case WM_MOUSELEAVE:
  205553. doMouseExit();
  205554. return 0;
  205555. case WM_LBUTTONDOWN:
  205556. case WM_MBUTTONDOWN:
  205557. case WM_RBUTTONDOWN:
  205558. doMouseDown (getPointFromLParam (lParam), wParam);
  205559. return 0;
  205560. case WM_LBUTTONUP:
  205561. case WM_MBUTTONUP:
  205562. case WM_RBUTTONUP:
  205563. doMouseUp (getPointFromLParam (lParam), wParam);
  205564. return 0;
  205565. case WM_CAPTURECHANGED:
  205566. doCaptureChanged();
  205567. return 0;
  205568. case WM_NCMOUSEMOVE:
  205569. if (hasTitleBar())
  205570. break;
  205571. return 0;
  205572. case 0x020A: /* WM_MOUSEWHEEL */
  205573. doMouseWheel (getCurrentMousePos(), wParam, true);
  205574. return 0;
  205575. case 0x020E: /* WM_MOUSEHWHEEL */
  205576. doMouseWheel (getCurrentMousePos(), wParam, false);
  205577. return 0;
  205578. case WM_WINDOWPOSCHANGING:
  205579. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  205580. {
  205581. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  205582. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  205583. {
  205584. if (constrainer != 0)
  205585. {
  205586. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  205587. component->getY() - windowBorder.getTop(),
  205588. component->getWidth() + windowBorder.getLeftAndRight(),
  205589. component->getHeight() + windowBorder.getTopAndBottom());
  205590. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  205591. constrainer->checkBounds (pos, current,
  205592. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  205593. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  205594. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  205595. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  205596. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  205597. wp->x = pos.getX();
  205598. wp->y = pos.getY();
  205599. wp->cx = pos.getWidth();
  205600. wp->cy = pos.getHeight();
  205601. }
  205602. }
  205603. }
  205604. return 0;
  205605. case WM_WINDOWPOSCHANGED:
  205606. handleMovedOrResized();
  205607. if (dontRepaint)
  205608. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  205609. return 0;
  205610. case WM_KEYDOWN:
  205611. case WM_SYSKEYDOWN:
  205612. if (doKeyDown (wParam))
  205613. return 0;
  205614. break;
  205615. case WM_KEYUP:
  205616. case WM_SYSKEYUP:
  205617. if (doKeyUp (wParam))
  205618. return 0;
  205619. break;
  205620. case WM_CHAR:
  205621. if (doKeyChar ((int) wParam, lParam))
  205622. return 0;
  205623. break;
  205624. case WM_APPCOMMAND:
  205625. if (doAppCommand (lParam))
  205626. return TRUE;
  205627. break;
  205628. case WM_SETFOCUS:
  205629. updateKeyModifiers();
  205630. handleFocusGain();
  205631. break;
  205632. case WM_KILLFOCUS:
  205633. if (hasCreatedCaret)
  205634. {
  205635. hasCreatedCaret = false;
  205636. DestroyCaret();
  205637. }
  205638. handleFocusLoss();
  205639. break;
  205640. case WM_ACTIVATEAPP:
  205641. // Windows does weird things to process priority when you swap apps,
  205642. // so this forces an update when the app is brought to the front
  205643. if (wParam != FALSE)
  205644. juce_repeatLastProcessPriority();
  205645. else
  205646. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  205647. juce_CheckCurrentlyFocusedTopLevelWindow();
  205648. modifiersAtLastCallback = -1;
  205649. return 0;
  205650. case WM_ACTIVATE:
  205651. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  205652. {
  205653. modifiersAtLastCallback = -1;
  205654. updateKeyModifiers();
  205655. if (isMinimised())
  205656. {
  205657. component->repaint();
  205658. handleMovedOrResized();
  205659. if (! ComponentPeer::isValidPeer (this))
  205660. return 0;
  205661. }
  205662. if (LOWORD (wParam) == WA_CLICKACTIVE
  205663. && component->isCurrentlyBlockedByAnotherModalComponent())
  205664. {
  205665. const Point<int> mousePos (component->getMouseXYRelative());
  205666. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  205667. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  205668. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  205669. return 0;
  205670. }
  205671. handleBroughtToFront();
  205672. if (component->isCurrentlyBlockedByAnotherModalComponent())
  205673. Component::getCurrentlyModalComponent()->toFront (true);
  205674. return 0;
  205675. }
  205676. break;
  205677. case WM_NCACTIVATE:
  205678. // while a temporary window is being shown, prevent Windows from deactivating the
  205679. // title bars of our main windows.
  205680. if (wParam == 0 && ! shouldDeactivateTitleBar)
  205681. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  205682. break;
  205683. case WM_MOUSEACTIVATE:
  205684. if (! component->getMouseClickGrabsKeyboardFocus())
  205685. return MA_NOACTIVATE;
  205686. break;
  205687. case WM_SHOWWINDOW:
  205688. if (wParam != 0)
  205689. handleBroughtToFront();
  205690. break;
  205691. case WM_CLOSE:
  205692. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  205693. handleUserClosingWindow();
  205694. return 0;
  205695. case WM_QUERYENDSESSION:
  205696. if (JUCEApplication::getInstance() != 0)
  205697. {
  205698. JUCEApplication::getInstance()->systemRequestedQuit();
  205699. return MessageManager::getInstance()->hasStopMessageBeenSent();
  205700. }
  205701. return TRUE;
  205702. case WM_TRAYNOTIFY:
  205703. if (component->isCurrentlyBlockedByAnotherModalComponent())
  205704. {
  205705. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  205706. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  205707. {
  205708. Component* const current = Component::getCurrentlyModalComponent();
  205709. if (current != 0)
  205710. current->inputAttemptWhenModal();
  205711. }
  205712. }
  205713. else
  205714. {
  205715. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  205716. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  205717. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  205718. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  205719. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  205720. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  205721. eventMods = eventMods.withoutMouseButtons();
  205722. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  205723. Point<int>(), eventMods, component, component, getMouseEventTime(),
  205724. Point<int>(), getMouseEventTime(), 1, false);
  205725. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  205726. {
  205727. SetFocus (hwnd);
  205728. SetForegroundWindow (hwnd);
  205729. component->mouseDown (e);
  205730. }
  205731. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  205732. {
  205733. component->mouseUp (e);
  205734. }
  205735. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  205736. {
  205737. component->mouseDoubleClick (e);
  205738. }
  205739. else if (lParam == WM_MOUSEMOVE)
  205740. {
  205741. component->mouseMove (e);
  205742. }
  205743. }
  205744. break;
  205745. case WM_SYNCPAINT:
  205746. return 0;
  205747. case WM_PALETTECHANGED:
  205748. InvalidateRect (h, 0, 0);
  205749. break;
  205750. case WM_DISPLAYCHANGE:
  205751. InvalidateRect (h, 0, 0);
  205752. createPaletteIfNeeded = true;
  205753. // intentional fall-through...
  205754. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  205755. doSettingChange();
  205756. break;
  205757. case WM_INITMENU:
  205758. if (! hasTitleBar())
  205759. {
  205760. if (isFullScreen())
  205761. {
  205762. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  205763. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  205764. }
  205765. else if (! isMinimised())
  205766. {
  205767. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  205768. }
  205769. }
  205770. break;
  205771. case WM_SYSCOMMAND:
  205772. switch (wParam & 0xfff0)
  205773. {
  205774. case SC_CLOSE:
  205775. if (sendInputAttemptWhenModalMessage())
  205776. return 0;
  205777. if (hasTitleBar())
  205778. {
  205779. PostMessage (h, WM_CLOSE, 0, 0);
  205780. return 0;
  205781. }
  205782. break;
  205783. case SC_KEYMENU:
  205784. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  205785. // obscure situations that can arise if a modal loop is started from an alt-key
  205786. // keypress).
  205787. if (hasTitleBar() && h == GetCapture())
  205788. ReleaseCapture();
  205789. break;
  205790. case SC_MAXIMIZE:
  205791. if (sendInputAttemptWhenModalMessage())
  205792. return 0;
  205793. setFullScreen (true);
  205794. return 0;
  205795. case SC_MINIMIZE:
  205796. if (sendInputAttemptWhenModalMessage())
  205797. return 0;
  205798. if (! hasTitleBar())
  205799. {
  205800. setMinimised (true);
  205801. return 0;
  205802. }
  205803. break;
  205804. case SC_RESTORE:
  205805. if (sendInputAttemptWhenModalMessage())
  205806. return 0;
  205807. if (hasTitleBar())
  205808. {
  205809. if (isFullScreen())
  205810. {
  205811. setFullScreen (false);
  205812. return 0;
  205813. }
  205814. }
  205815. else
  205816. {
  205817. if (isMinimised())
  205818. setMinimised (false);
  205819. else if (isFullScreen())
  205820. setFullScreen (false);
  205821. return 0;
  205822. }
  205823. break;
  205824. }
  205825. break;
  205826. case WM_NCLBUTTONDOWN:
  205827. case WM_NCRBUTTONDOWN:
  205828. case WM_NCMBUTTONDOWN:
  205829. sendInputAttemptWhenModalMessage();
  205830. break;
  205831. //case WM_IME_STARTCOMPOSITION;
  205832. // return 0;
  205833. case WM_GETDLGCODE:
  205834. return DLGC_WANTALLKEYS;
  205835. default:
  205836. break;
  205837. }
  205838. }
  205839. return DefWindowProcW (h, message, wParam, lParam);
  205840. }
  205841. bool sendInputAttemptWhenModalMessage()
  205842. {
  205843. if (component->isCurrentlyBlockedByAnotherModalComponent())
  205844. {
  205845. Component* const current = Component::getCurrentlyModalComponent();
  205846. if (current != 0)
  205847. current->inputAttemptWhenModal();
  205848. return true;
  205849. }
  205850. return false;
  205851. }
  205852. Win32ComponentPeer (const Win32ComponentPeer&);
  205853. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  205854. };
  205855. ModifierKeys Win32ComponentPeer::currentModifiers;
  205856. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  205857. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  205858. {
  205859. return new Win32ComponentPeer (this, styleFlags);
  205860. }
  205861. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  205862. void ModifierKeys::updateCurrentModifiers() throw()
  205863. {
  205864. currentModifiers = Win32ComponentPeer::currentModifiers;
  205865. }
  205866. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  205867. {
  205868. Win32ComponentPeer::updateKeyModifiers();
  205869. int keyMods = 0;
  205870. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  205871. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  205872. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  205873. Win32ComponentPeer::currentModifiers
  205874. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  205875. return Win32ComponentPeer::currentModifiers;
  205876. }
  205877. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  205878. {
  205879. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  205880. if (wp != 0)
  205881. wp->setTaskBarIcon (newImage);
  205882. }
  205883. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  205884. {
  205885. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  205886. if (wp != 0)
  205887. wp->setTaskBarIconToolTip (tooltip);
  205888. }
  205889. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  205890. {
  205891. DWORD val = GetWindowLong (h, styleType);
  205892. if (bitIsSet)
  205893. val |= feature;
  205894. else
  205895. val &= ~feature;
  205896. SetWindowLongPtr (h, styleType, val);
  205897. SetWindowPos (h, 0, 0, 0, 0, 0,
  205898. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  205899. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  205900. }
  205901. bool Process::isForegroundProcess()
  205902. {
  205903. HWND fg = GetForegroundWindow();
  205904. if (fg == 0)
  205905. return true;
  205906. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  205907. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  205908. // have to see if any of our windows are children of the foreground window
  205909. fg = GetAncestor (fg, GA_ROOT);
  205910. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  205911. {
  205912. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  205913. if (wp != 0 && wp->isInside (fg))
  205914. return true;
  205915. }
  205916. return false;
  205917. }
  205918. bool AlertWindow::showNativeDialogBox (const String& title,
  205919. const String& bodyText,
  205920. bool isOkCancel)
  205921. {
  205922. return MessageBox (0, bodyText, title,
  205923. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  205924. : MB_OK)) == IDOK;
  205925. }
  205926. void Desktop::createMouseInputSources()
  205927. {
  205928. mouseSources.add (new MouseInputSource (0, true));
  205929. }
  205930. const Point<int> Desktop::getMousePosition()
  205931. {
  205932. POINT mousePos;
  205933. GetCursorPos (&mousePos);
  205934. return Point<int> (mousePos.x, mousePos.y);
  205935. }
  205936. void Desktop::setMousePosition (const Point<int>& newPosition)
  205937. {
  205938. SetCursorPos (newPosition.getX(), newPosition.getY());
  205939. }
  205940. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  205941. {
  205942. return createSoftwareImage (format, width, height, clearImage);
  205943. }
  205944. class ScreenSaverDefeater : public Timer,
  205945. public DeletedAtShutdown
  205946. {
  205947. public:
  205948. ScreenSaverDefeater()
  205949. {
  205950. startTimer (10000);
  205951. timerCallback();
  205952. }
  205953. ~ScreenSaverDefeater() {}
  205954. void timerCallback()
  205955. {
  205956. if (Process::isForegroundProcess())
  205957. {
  205958. // simulate a shift key getting pressed..
  205959. INPUT input[2];
  205960. input[0].type = INPUT_KEYBOARD;
  205961. input[0].ki.wVk = VK_SHIFT;
  205962. input[0].ki.dwFlags = 0;
  205963. input[0].ki.dwExtraInfo = 0;
  205964. input[1].type = INPUT_KEYBOARD;
  205965. input[1].ki.wVk = VK_SHIFT;
  205966. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  205967. input[1].ki.dwExtraInfo = 0;
  205968. SendInput (2, input, sizeof (INPUT));
  205969. }
  205970. }
  205971. };
  205972. static ScreenSaverDefeater* screenSaverDefeater = 0;
  205973. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  205974. {
  205975. if (isEnabled)
  205976. deleteAndZero (screenSaverDefeater);
  205977. else if (screenSaverDefeater == 0)
  205978. screenSaverDefeater = new ScreenSaverDefeater();
  205979. }
  205980. bool Desktop::isScreenSaverEnabled()
  205981. {
  205982. return screenSaverDefeater == 0;
  205983. }
  205984. /* (The code below is the "correct" way to disable the screen saver, but it
  205985. completely fails on winXP when the saver is password-protected...)
  205986. static bool juce_screenSaverEnabled = true;
  205987. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  205988. {
  205989. juce_screenSaverEnabled = isEnabled;
  205990. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  205991. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  205992. }
  205993. bool Desktop::isScreenSaverEnabled() throw()
  205994. {
  205995. return juce_screenSaverEnabled;
  205996. }
  205997. */
  205998. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  205999. {
  206000. if (enableOrDisable)
  206001. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  206002. }
  206003. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  206004. {
  206005. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  206006. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  206007. return TRUE;
  206008. }
  206009. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  206010. {
  206011. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  206012. // make sure the first in the list is the main monitor
  206013. for (int i = 1; i < monitorCoords.size(); ++i)
  206014. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  206015. monitorCoords.swap (i, 0);
  206016. if (monitorCoords.size() == 0)
  206017. {
  206018. RECT r;
  206019. GetWindowRect (GetDesktopWindow(), &r);
  206020. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  206021. }
  206022. if (clipToWorkArea)
  206023. {
  206024. // clip the main monitor to the active non-taskbar area
  206025. RECT r;
  206026. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  206027. Rectangle<int>& screen = monitorCoords.getReference (0);
  206028. screen.setPosition (jmax (screen.getX(), (int) r.left),
  206029. jmax (screen.getY(), (int) r.top));
  206030. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  206031. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  206032. }
  206033. }
  206034. static const Image createImageFromHBITMAP (HBITMAP bitmap) throw()
  206035. {
  206036. Image im;
  206037. if (bitmap != 0)
  206038. {
  206039. BITMAP bm;
  206040. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206041. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206042. {
  206043. HDC tempDC = GetDC (0);
  206044. HDC dc = CreateCompatibleDC (tempDC);
  206045. ReleaseDC (0, tempDC);
  206046. SelectObject (dc, bitmap);
  206047. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206048. Image::BitmapData imageData (im, 0, 0, bm.bmWidth, bm.bmHeight, true);
  206049. for (int y = bm.bmHeight; --y >= 0;)
  206050. {
  206051. for (int x = bm.bmWidth; --x >= 0;)
  206052. {
  206053. COLORREF col = GetPixel (dc, x, y);
  206054. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206055. (uint8) GetGValue (col),
  206056. (uint8) GetBValue (col)));
  206057. }
  206058. }
  206059. DeleteDC (dc);
  206060. }
  206061. }
  206062. return im;
  206063. }
  206064. static const Image createImageFromHICON (HICON icon) throw()
  206065. {
  206066. ICONINFO info;
  206067. if (GetIconInfo (icon, &info))
  206068. {
  206069. Image mask (createImageFromHBITMAP (info.hbmMask));
  206070. Image image (createImageFromHBITMAP (info.hbmColor));
  206071. if (mask.isValid() && image.isValid())
  206072. {
  206073. for (int y = image.getHeight(); --y >= 0;)
  206074. {
  206075. for (int x = image.getWidth(); --x >= 0;)
  206076. {
  206077. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206078. if (brightness > 0.0f)
  206079. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206080. }
  206081. }
  206082. return image;
  206083. }
  206084. }
  206085. return Image();
  206086. }
  206087. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  206088. {
  206089. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206090. Image bitmap (nativeBitmap);
  206091. {
  206092. Graphics g (bitmap);
  206093. g.drawImageAt (image, 0, 0);
  206094. }
  206095. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206096. ICONINFO info;
  206097. info.fIcon = isIcon;
  206098. info.xHotspot = hotspotX;
  206099. info.yHotspot = hotspotY;
  206100. info.hbmMask = mask;
  206101. info.hbmColor = nativeBitmap->hBitmap;
  206102. HICON hi = CreateIconIndirect (&info);
  206103. DeleteObject (mask);
  206104. return hi;
  206105. }
  206106. const Image juce_createIconForFile (const File& file)
  206107. {
  206108. Image image;
  206109. WCHAR filename [1024];
  206110. file.getFullPathName().copyToUnicode (filename, 1023);
  206111. WORD iconNum = 0;
  206112. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  206113. filename, &iconNum);
  206114. if (icon != 0)
  206115. {
  206116. image = createImageFromHICON (icon);
  206117. DestroyIcon (icon);
  206118. }
  206119. return image;
  206120. }
  206121. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  206122. {
  206123. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  206124. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  206125. Image im (image);
  206126. if (im.getWidth() > maxW || im.getHeight() > maxH)
  206127. {
  206128. im = im.rescaled (maxW, maxH);
  206129. hotspotX = (hotspotX * maxW) / image.getWidth();
  206130. hotspotY = (hotspotY * maxH) / image.getHeight();
  206131. }
  206132. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  206133. }
  206134. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  206135. {
  206136. if (cursorHandle != 0 && ! isStandard)
  206137. DestroyCursor ((HCURSOR) cursorHandle);
  206138. }
  206139. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  206140. {
  206141. LPCTSTR cursorName = IDC_ARROW;
  206142. switch (type)
  206143. {
  206144. case NormalCursor: break;
  206145. case NoCursor: return 0;
  206146. case WaitCursor: cursorName = IDC_WAIT; break;
  206147. case IBeamCursor: cursorName = IDC_IBEAM; break;
  206148. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  206149. case CrosshairCursor: cursorName = IDC_CROSS; break;
  206150. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  206151. case LeftRightResizeCursor:
  206152. case LeftEdgeResizeCursor:
  206153. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  206154. case UpDownResizeCursor:
  206155. case TopEdgeResizeCursor:
  206156. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  206157. case TopLeftCornerResizeCursor:
  206158. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  206159. case TopRightCornerResizeCursor:
  206160. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  206161. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  206162. case DraggingHandCursor:
  206163. {
  206164. static void* dragHandCursor = 0;
  206165. if (dragHandCursor == 0)
  206166. {
  206167. static const unsigned char dragHandData[] =
  206168. { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  206169. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39, 132,117,151,116,132,146,248,60,209,138,
  206170. 98,22,203,114,34,236,37,52,77,217,247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  206171. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  206172. }
  206173. return dragHandCursor;
  206174. }
  206175. default:
  206176. jassertfalse; break;
  206177. }
  206178. HCURSOR cursorH = LoadCursor (0, cursorName);
  206179. if (cursorH == 0)
  206180. cursorH = LoadCursor (0, IDC_ARROW);
  206181. return cursorH;
  206182. }
  206183. void MouseCursor::showInWindow (ComponentPeer*) const
  206184. {
  206185. SetCursor ((HCURSOR) getHandle());
  206186. }
  206187. void MouseCursor::showInAllWindows() const
  206188. {
  206189. showInWindow (0);
  206190. }
  206191. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  206192. {
  206193. public:
  206194. JuceDropSource() {}
  206195. ~JuceDropSource() {}
  206196. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  206197. {
  206198. if (escapePressed)
  206199. return DRAGDROP_S_CANCEL;
  206200. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  206201. return DRAGDROP_S_DROP;
  206202. return S_OK;
  206203. }
  206204. HRESULT __stdcall GiveFeedback (DWORD)
  206205. {
  206206. return DRAGDROP_S_USEDEFAULTCURSORS;
  206207. }
  206208. };
  206209. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  206210. {
  206211. public:
  206212. JuceEnumFormatEtc (const FORMATETC* const format_)
  206213. : format (format_),
  206214. index (0)
  206215. {
  206216. }
  206217. ~JuceEnumFormatEtc() {}
  206218. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  206219. {
  206220. if (result == 0)
  206221. return E_POINTER;
  206222. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  206223. newOne->index = index;
  206224. *result = newOne;
  206225. return S_OK;
  206226. }
  206227. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  206228. {
  206229. if (pceltFetched != 0)
  206230. *pceltFetched = 0;
  206231. else if (celt != 1)
  206232. return S_FALSE;
  206233. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  206234. {
  206235. copyFormatEtc (lpFormatEtc [0], *format);
  206236. ++index;
  206237. if (pceltFetched != 0)
  206238. *pceltFetched = 1;
  206239. return S_OK;
  206240. }
  206241. return S_FALSE;
  206242. }
  206243. HRESULT __stdcall Skip (ULONG celt)
  206244. {
  206245. if (index + (int) celt >= 1)
  206246. return S_FALSE;
  206247. index += celt;
  206248. return S_OK;
  206249. }
  206250. HRESULT __stdcall Reset()
  206251. {
  206252. index = 0;
  206253. return S_OK;
  206254. }
  206255. private:
  206256. const FORMATETC* const format;
  206257. int index;
  206258. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  206259. {
  206260. dest = source;
  206261. if (source.ptd != 0)
  206262. {
  206263. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  206264. *(dest.ptd) = *(source.ptd);
  206265. }
  206266. }
  206267. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  206268. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  206269. };
  206270. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  206271. {
  206272. JuceDropSource* const dropSource;
  206273. const FORMATETC* const format;
  206274. const STGMEDIUM* const medium;
  206275. JuceDataObject (const JuceDataObject&);
  206276. JuceDataObject& operator= (const JuceDataObject&);
  206277. public:
  206278. JuceDataObject (JuceDropSource* const dropSource_,
  206279. const FORMATETC* const format_,
  206280. const STGMEDIUM* const medium_)
  206281. : dropSource (dropSource_),
  206282. format (format_),
  206283. medium (medium_)
  206284. {
  206285. }
  206286. virtual ~JuceDataObject()
  206287. {
  206288. jassert (refCount == 0);
  206289. }
  206290. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  206291. {
  206292. if ((pFormatEtc->tymed & format->tymed) != 0
  206293. && pFormatEtc->cfFormat == format->cfFormat
  206294. && pFormatEtc->dwAspect == format->dwAspect)
  206295. {
  206296. pMedium->tymed = format->tymed;
  206297. pMedium->pUnkForRelease = 0;
  206298. if (format->tymed == TYMED_HGLOBAL)
  206299. {
  206300. const SIZE_T len = GlobalSize (medium->hGlobal);
  206301. void* const src = GlobalLock (medium->hGlobal);
  206302. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  206303. memcpy (dst, src, len);
  206304. GlobalUnlock (medium->hGlobal);
  206305. pMedium->hGlobal = dst;
  206306. return S_OK;
  206307. }
  206308. }
  206309. return DV_E_FORMATETC;
  206310. }
  206311. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  206312. {
  206313. if (f == 0)
  206314. return E_INVALIDARG;
  206315. if (f->tymed == format->tymed
  206316. && f->cfFormat == format->cfFormat
  206317. && f->dwAspect == format->dwAspect)
  206318. return S_OK;
  206319. return DV_E_FORMATETC;
  206320. }
  206321. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  206322. {
  206323. pFormatEtcOut->ptd = 0;
  206324. return E_NOTIMPL;
  206325. }
  206326. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  206327. {
  206328. if (result == 0)
  206329. return E_POINTER;
  206330. if (direction == DATADIR_GET)
  206331. {
  206332. *result = new JuceEnumFormatEtc (format);
  206333. return S_OK;
  206334. }
  206335. *result = 0;
  206336. return E_NOTIMPL;
  206337. }
  206338. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  206339. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  206340. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  206341. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  206342. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  206343. };
  206344. static HDROP createHDrop (const StringArray& fileNames) throw()
  206345. {
  206346. int totalChars = 0;
  206347. for (int i = fileNames.size(); --i >= 0;)
  206348. totalChars += fileNames[i].length() + 1;
  206349. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  206350. sizeof (DROPFILES)
  206351. + sizeof (WCHAR) * (totalChars + 2));
  206352. if (hDrop != 0)
  206353. {
  206354. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  206355. pDropFiles->pFiles = sizeof (DROPFILES);
  206356. pDropFiles->fWide = true;
  206357. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  206358. for (int i = 0; i < fileNames.size(); ++i)
  206359. {
  206360. fileNames[i].copyToUnicode (fname, 2048);
  206361. fname += fileNames[i].length() + 1;
  206362. }
  206363. *fname = 0;
  206364. GlobalUnlock (hDrop);
  206365. }
  206366. return hDrop;
  206367. }
  206368. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  206369. {
  206370. JuceDropSource* const source = new JuceDropSource();
  206371. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  206372. DWORD effect;
  206373. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  206374. data->Release();
  206375. source->Release();
  206376. return res == DRAGDROP_S_DROP;
  206377. }
  206378. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  206379. {
  206380. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206381. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206382. medium.hGlobal = createHDrop (files);
  206383. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  206384. : DROPEFFECT_COPY);
  206385. }
  206386. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  206387. {
  206388. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206389. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206390. const int numChars = text.length();
  206391. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  206392. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  206393. text.copyToUnicode (data, numChars + 1);
  206394. format.cfFormat = CF_UNICODETEXT;
  206395. GlobalUnlock (medium.hGlobal);
  206396. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  206397. }
  206398. #endif
  206399. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  206400. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  206401. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206402. // compiled on its own).
  206403. #if JUCE_INCLUDED_FILE
  206404. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  206405. NEWTEXTMETRICEXW*,
  206406. int type,
  206407. LPARAM lParam)
  206408. {
  206409. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206410. {
  206411. const String fontName (lpelfe->elfLogFont.lfFaceName);
  206412. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  206413. }
  206414. return 1;
  206415. }
  206416. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  206417. NEWTEXTMETRICEXW*,
  206418. int type,
  206419. LPARAM lParam)
  206420. {
  206421. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206422. {
  206423. LOGFONTW lf;
  206424. zerostruct (lf);
  206425. lf.lfWeight = FW_DONTCARE;
  206426. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206427. lf.lfQuality = DEFAULT_QUALITY;
  206428. lf.lfCharSet = DEFAULT_CHARSET;
  206429. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206430. lf.lfPitchAndFamily = FF_DONTCARE;
  206431. const String fontName (lpelfe->elfLogFont.lfFaceName);
  206432. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  206433. HDC dc = CreateCompatibleDC (0);
  206434. EnumFontFamiliesEx (dc, &lf,
  206435. (FONTENUMPROCW) &wfontEnum2,
  206436. lParam, 0);
  206437. DeleteDC (dc);
  206438. }
  206439. return 1;
  206440. }
  206441. const StringArray Font::findAllTypefaceNames()
  206442. {
  206443. StringArray results;
  206444. HDC dc = CreateCompatibleDC (0);
  206445. {
  206446. LOGFONTW lf;
  206447. zerostruct (lf);
  206448. lf.lfWeight = FW_DONTCARE;
  206449. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206450. lf.lfQuality = DEFAULT_QUALITY;
  206451. lf.lfCharSet = DEFAULT_CHARSET;
  206452. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206453. lf.lfPitchAndFamily = FF_DONTCARE;
  206454. lf.lfFaceName[0] = 0;
  206455. EnumFontFamiliesEx (dc, &lf,
  206456. (FONTENUMPROCW) &wfontEnum1,
  206457. (LPARAM) &results, 0);
  206458. }
  206459. DeleteDC (dc);
  206460. results.sort (true);
  206461. return results;
  206462. }
  206463. extern bool juce_IsRunningInWine();
  206464. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  206465. {
  206466. if (juce_IsRunningInWine())
  206467. {
  206468. // If we're running in Wine, then use fonts that might be available on Linux..
  206469. defaultSans = "Bitstream Vera Sans";
  206470. defaultSerif = "Bitstream Vera Serif";
  206471. defaultFixed = "Bitstream Vera Sans Mono";
  206472. }
  206473. else
  206474. {
  206475. defaultSans = "Verdana";
  206476. defaultSerif = "Times";
  206477. defaultFixed = "Lucida Console";
  206478. }
  206479. }
  206480. class FontDCHolder : private DeletedAtShutdown
  206481. {
  206482. public:
  206483. FontDCHolder()
  206484. : dc (0), numKPs (0), size (0),
  206485. bold (false), italic (false)
  206486. {
  206487. }
  206488. ~FontDCHolder()
  206489. {
  206490. if (dc != 0)
  206491. {
  206492. DeleteDC (dc);
  206493. DeleteObject (fontH);
  206494. }
  206495. clearSingletonInstance();
  206496. }
  206497. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  206498. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  206499. {
  206500. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  206501. {
  206502. fontName = fontName_;
  206503. bold = bold_;
  206504. italic = italic_;
  206505. size = size_;
  206506. if (dc != 0)
  206507. {
  206508. DeleteDC (dc);
  206509. DeleteObject (fontH);
  206510. kps.free();
  206511. }
  206512. fontH = 0;
  206513. dc = CreateCompatibleDC (0);
  206514. SetMapperFlags (dc, 0);
  206515. SetMapMode (dc, MM_TEXT);
  206516. LOGFONTW lfw;
  206517. zerostruct (lfw);
  206518. lfw.lfCharSet = DEFAULT_CHARSET;
  206519. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206520. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206521. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  206522. lfw.lfQuality = PROOF_QUALITY;
  206523. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  206524. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  206525. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  206526. lfw.lfHeight = size > 0 ? size : -256;
  206527. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  206528. if (standardSizedFont != 0)
  206529. {
  206530. if (SelectObject (dc, standardSizedFont) != 0)
  206531. {
  206532. fontH = standardSizedFont;
  206533. if (size == 0)
  206534. {
  206535. OUTLINETEXTMETRIC otm;
  206536. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  206537. {
  206538. lfw.lfHeight = -(int) otm.otmEMSquare;
  206539. fontH = CreateFontIndirect (&lfw);
  206540. SelectObject (dc, fontH);
  206541. DeleteObject (standardSizedFont);
  206542. }
  206543. }
  206544. }
  206545. else
  206546. {
  206547. jassertfalse;
  206548. }
  206549. }
  206550. else
  206551. {
  206552. jassertfalse;
  206553. }
  206554. }
  206555. return dc;
  206556. }
  206557. KERNINGPAIR* getKerningPairs (int& numKPs_)
  206558. {
  206559. if (kps == 0)
  206560. {
  206561. numKPs = GetKerningPairs (dc, 0, 0);
  206562. kps.calloc (numKPs);
  206563. GetKerningPairs (dc, numKPs, kps);
  206564. }
  206565. numKPs_ = numKPs;
  206566. return kps;
  206567. }
  206568. private:
  206569. HFONT fontH;
  206570. HDC dc;
  206571. String fontName;
  206572. HeapBlock <KERNINGPAIR> kps;
  206573. int numKPs, size;
  206574. bool bold, italic;
  206575. FontDCHolder (const FontDCHolder&);
  206576. FontDCHolder& operator= (const FontDCHolder&);
  206577. };
  206578. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  206579. class WindowsTypeface : public CustomTypeface
  206580. {
  206581. public:
  206582. WindowsTypeface (const Font& font)
  206583. {
  206584. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  206585. font.isBold(), font.isItalic(), 0);
  206586. TEXTMETRIC tm;
  206587. tm.tmAscent = tm.tmHeight = 1;
  206588. tm.tmDefaultChar = 0;
  206589. GetTextMetrics (dc, &tm);
  206590. setCharacteristics (font.getTypefaceName(),
  206591. tm.tmAscent / (float) tm.tmHeight,
  206592. font.isBold(), font.isItalic(),
  206593. tm.tmDefaultChar);
  206594. }
  206595. bool loadGlyphIfPossible (juce_wchar character)
  206596. {
  206597. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  206598. GLYPHMETRICS gm;
  206599. {
  206600. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  206601. WORD index = 0;
  206602. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  206603. && index == 0xffff)
  206604. {
  206605. return false;
  206606. }
  206607. }
  206608. Path glyphPath;
  206609. TEXTMETRIC tm;
  206610. if (! GetTextMetrics (dc, &tm))
  206611. {
  206612. addGlyph (character, glyphPath, 0);
  206613. return true;
  206614. }
  206615. const float height = (float) tm.tmHeight;
  206616. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  206617. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  206618. &gm, 0, 0, &identityMatrix);
  206619. if (bufSize > 0)
  206620. {
  206621. HeapBlock<char> data (bufSize);
  206622. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  206623. bufSize, data, &identityMatrix);
  206624. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  206625. const float scaleX = 1.0f / height;
  206626. const float scaleY = -1.0f / height;
  206627. while ((char*) pheader < data + bufSize)
  206628. {
  206629. float x = scaleX * pheader->pfxStart.x.value;
  206630. float y = scaleY * pheader->pfxStart.y.value;
  206631. glyphPath.startNewSubPath (x, y);
  206632. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  206633. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  206634. while ((const char*) curve < curveEnd)
  206635. {
  206636. if (curve->wType == TT_PRIM_LINE)
  206637. {
  206638. for (int i = 0; i < curve->cpfx; ++i)
  206639. {
  206640. x = scaleX * curve->apfx[i].x.value;
  206641. y = scaleY * curve->apfx[i].y.value;
  206642. glyphPath.lineTo (x, y);
  206643. }
  206644. }
  206645. else if (curve->wType == TT_PRIM_QSPLINE)
  206646. {
  206647. for (int i = 0; i < curve->cpfx - 1; ++i)
  206648. {
  206649. const float x2 = scaleX * curve->apfx[i].x.value;
  206650. const float y2 = scaleY * curve->apfx[i].y.value;
  206651. float x3, y3;
  206652. if (i < curve->cpfx - 2)
  206653. {
  206654. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  206655. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  206656. }
  206657. else
  206658. {
  206659. x3 = scaleX * curve->apfx[i + 1].x.value;
  206660. y3 = scaleY * curve->apfx[i + 1].y.value;
  206661. }
  206662. glyphPath.quadraticTo (x2, y2, x3, y3);
  206663. x = x3;
  206664. y = y3;
  206665. }
  206666. }
  206667. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  206668. }
  206669. pheader = (const TTPOLYGONHEADER*) curve;
  206670. glyphPath.closeSubPath();
  206671. }
  206672. }
  206673. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  206674. int numKPs;
  206675. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  206676. for (int i = 0; i < numKPs; ++i)
  206677. {
  206678. if (kps[i].wFirst == character)
  206679. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  206680. kps[i].iKernAmount / height);
  206681. }
  206682. return true;
  206683. }
  206684. juce_UseDebuggingNewOperator
  206685. };
  206686. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  206687. {
  206688. return new WindowsTypeface (font);
  206689. }
  206690. #endif
  206691. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  206692. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  206693. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206694. // compiled on its own).
  206695. #if JUCE_INCLUDED_FILE
  206696. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  206697. namespace FileChooserHelpers
  206698. {
  206699. static const void* defaultDirPath = 0;
  206700. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  206701. static Component* currentExtraFileWin = 0;
  206702. static bool areThereAnyAlwaysOnTopWindows()
  206703. {
  206704. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  206705. {
  206706. Component* c = Desktop::getInstance().getComponent (i);
  206707. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  206708. return true;
  206709. }
  206710. return false;
  206711. }
  206712. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  206713. {
  206714. if (msg == BFFM_INITIALIZED)
  206715. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  206716. else if (msg == BFFM_VALIDATEFAILEDW)
  206717. returnedString = (LPCWSTR) lParam;
  206718. else if (msg == BFFM_VALIDATEFAILEDA)
  206719. returnedString = (const char*) lParam;
  206720. return 0;
  206721. }
  206722. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  206723. {
  206724. if (currentExtraFileWin != 0)
  206725. {
  206726. if (uiMsg == WM_INITDIALOG)
  206727. {
  206728. HWND dialogH = GetParent (hdlg);
  206729. jassert (dialogH != 0);
  206730. if (dialogH == 0)
  206731. dialogH = hdlg;
  206732. RECT r, cr;
  206733. GetWindowRect (dialogH, &r);
  206734. GetClientRect (dialogH, &cr);
  206735. SetWindowPos (dialogH, 0,
  206736. r.left, r.top,
  206737. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  206738. jmax (150, (int) (r.bottom - r.top)),
  206739. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  206740. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  206741. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  206742. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  206743. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  206744. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  206745. }
  206746. else if (uiMsg == WM_NOTIFY)
  206747. {
  206748. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  206749. if (ofn->hdr.code == CDN_SELCHANGE)
  206750. {
  206751. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  206752. if (comp != 0)
  206753. {
  206754. TCHAR path [MAX_PATH * 2];
  206755. path[0] = 0;
  206756. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  206757. const String fn ((const WCHAR*) path);
  206758. comp->selectedFileChanged (File (fn));
  206759. }
  206760. }
  206761. }
  206762. }
  206763. return 0;
  206764. }
  206765. class FPComponentHolder : public Component
  206766. {
  206767. public:
  206768. FPComponentHolder()
  206769. {
  206770. setVisible (true);
  206771. setOpaque (true);
  206772. }
  206773. ~FPComponentHolder()
  206774. {
  206775. }
  206776. void paint (Graphics& g)
  206777. {
  206778. g.fillAll (Colours::lightgrey);
  206779. }
  206780. private:
  206781. FPComponentHolder (const FPComponentHolder&);
  206782. FPComponentHolder& operator= (const FPComponentHolder&);
  206783. };
  206784. }
  206785. void FileChooser::showPlatformDialog (Array<File>& results,
  206786. const String& title,
  206787. const File& currentFileOrDirectory,
  206788. const String& filter,
  206789. bool selectsDirectory,
  206790. bool /*selectsFiles*/,
  206791. bool isSaveDialogue,
  206792. bool warnAboutOverwritingExistingFiles,
  206793. bool selectMultipleFiles,
  206794. FilePreviewComponent* extraInfoComponent)
  206795. {
  206796. using namespace FileChooserHelpers;
  206797. const int numCharsAvailable = 32768;
  206798. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  206799. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  206800. int fnameIdx = 0;
  206801. JUCE_TRY
  206802. {
  206803. // use a modal window as the parent for this dialog box
  206804. // to block input from other app windows
  206805. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  206806. Component w (String::empty);
  206807. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  206808. mainMon.getY() + mainMon.getHeight() / 4,
  206809. 0, 0);
  206810. w.setOpaque (true);
  206811. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  206812. w.addToDesktop (0);
  206813. if (extraInfoComponent == 0)
  206814. w.enterModalState();
  206815. String initialDir;
  206816. if (currentFileOrDirectory.isDirectory())
  206817. {
  206818. initialDir = currentFileOrDirectory.getFullPathName();
  206819. }
  206820. else
  206821. {
  206822. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  206823. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  206824. }
  206825. if (currentExtraFileWin->isValidComponent())
  206826. {
  206827. jassertfalse;
  206828. return;
  206829. }
  206830. if (selectsDirectory)
  206831. {
  206832. LPITEMIDLIST list = 0;
  206833. filenameSpace.fillWith (0);
  206834. {
  206835. BROWSEINFO bi;
  206836. zerostruct (bi);
  206837. bi.hwndOwner = (HWND) w.getWindowHandle();
  206838. bi.pszDisplayName = fname;
  206839. bi.lpszTitle = title;
  206840. bi.lpfn = browseCallbackProc;
  206841. #ifdef BIF_USENEWUI
  206842. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  206843. #else
  206844. bi.ulFlags = 0x50;
  206845. #endif
  206846. defaultDirPath = (const WCHAR*) initialDir;
  206847. list = SHBrowseForFolder (&bi);
  206848. if (! SHGetPathFromIDListW (list, fname))
  206849. {
  206850. fname[0] = 0;
  206851. returnedString = String::empty;
  206852. }
  206853. }
  206854. LPMALLOC al;
  206855. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  206856. al->Free (list);
  206857. defaultDirPath = 0;
  206858. if (returnedString.isNotEmpty())
  206859. {
  206860. const String stringFName (fname);
  206861. results.add (File (stringFName).getSiblingFile (returnedString));
  206862. returnedString = String::empty;
  206863. return;
  206864. }
  206865. }
  206866. else
  206867. {
  206868. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  206869. if (warnAboutOverwritingExistingFiles)
  206870. flags |= OFN_OVERWRITEPROMPT;
  206871. if (selectMultipleFiles)
  206872. flags |= OFN_ALLOWMULTISELECT;
  206873. if (extraInfoComponent != 0)
  206874. {
  206875. flags |= OFN_ENABLEHOOK;
  206876. currentExtraFileWin = new FPComponentHolder();
  206877. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  206878. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  206879. extraInfoComponent->getHeight());
  206880. currentExtraFileWin->addToDesktop (0);
  206881. currentExtraFileWin->enterModalState();
  206882. }
  206883. {
  206884. WCHAR filters [1024];
  206885. zeromem (filters, sizeof (filters));
  206886. filter.copyToUnicode (filters, 1024);
  206887. filter.copyToUnicode (filters + filter.length() + 1,
  206888. 1022 - filter.length());
  206889. OPENFILENAMEW of;
  206890. zerostruct (of);
  206891. #ifdef OPENFILENAME_SIZE_VERSION_400W
  206892. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  206893. #else
  206894. of.lStructSize = sizeof (of);
  206895. #endif
  206896. of.hwndOwner = (HWND) w.getWindowHandle();
  206897. of.lpstrFilter = filters;
  206898. of.nFilterIndex = 1;
  206899. of.lpstrFile = fname;
  206900. of.nMaxFile = numCharsAvailable;
  206901. of.lpstrInitialDir = initialDir;
  206902. of.lpstrTitle = title;
  206903. of.Flags = flags;
  206904. if (extraInfoComponent != 0)
  206905. of.lpfnHook = &openCallback;
  206906. if (isSaveDialogue)
  206907. {
  206908. if (! GetSaveFileName (&of))
  206909. fname[0] = 0;
  206910. else
  206911. fnameIdx = of.nFileOffset;
  206912. }
  206913. else
  206914. {
  206915. if (! GetOpenFileName (&of))
  206916. fname[0] = 0;
  206917. else
  206918. fnameIdx = of.nFileOffset;
  206919. }
  206920. }
  206921. }
  206922. }
  206923. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  206924. catch (...)
  206925. {
  206926. fname[0] = 0;
  206927. }
  206928. #endif
  206929. deleteAndZero (currentExtraFileWin);
  206930. const WCHAR* const files = fname;
  206931. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  206932. {
  206933. const WCHAR* filename = files + fnameIdx;
  206934. while (*filename != 0)
  206935. {
  206936. const String filepath (String (files) + "\\" + String (filename));
  206937. results.add (File (filepath));
  206938. filename += CharacterFunctions::length (filename) + 1;
  206939. }
  206940. }
  206941. else if (files[0] != 0)
  206942. {
  206943. results.add (File (files));
  206944. }
  206945. }
  206946. #endif
  206947. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  206948. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  206949. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206950. // compiled on its own).
  206951. #if JUCE_INCLUDED_FILE
  206952. void SystemClipboard::copyTextToClipboard (const String& text)
  206953. {
  206954. if (OpenClipboard (0) != 0)
  206955. {
  206956. if (EmptyClipboard() != 0)
  206957. {
  206958. const int len = text.length();
  206959. if (len > 0)
  206960. {
  206961. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  206962. (len + 1) * sizeof (wchar_t));
  206963. if (bufH != 0)
  206964. {
  206965. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  206966. text.copyToUnicode (data, len);
  206967. GlobalUnlock (bufH);
  206968. SetClipboardData (CF_UNICODETEXT, bufH);
  206969. }
  206970. }
  206971. }
  206972. CloseClipboard();
  206973. }
  206974. }
  206975. const String SystemClipboard::getTextFromClipboard()
  206976. {
  206977. String result;
  206978. if (OpenClipboard (0) != 0)
  206979. {
  206980. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  206981. if (bufH != 0)
  206982. {
  206983. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  206984. if (data != 0)
  206985. {
  206986. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  206987. GlobalUnlock (bufH);
  206988. }
  206989. }
  206990. CloseClipboard();
  206991. }
  206992. return result;
  206993. }
  206994. #endif
  206995. /*** End of inlined file: juce_win32_Misc.cpp ***/
  206996. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  206997. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206998. // compiled on its own).
  206999. #if JUCE_INCLUDED_FILE
  207000. namespace ActiveXHelpers
  207001. {
  207002. class JuceIStorage : public ComBaseClassHelper <IStorage>
  207003. {
  207004. public:
  207005. JuceIStorage() {}
  207006. ~JuceIStorage() {}
  207007. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207008. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207009. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  207010. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  207011. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  207012. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  207013. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  207014. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  207015. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  207016. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  207017. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  207018. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  207019. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  207020. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  207021. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  207022. juce_UseDebuggingNewOperator
  207023. };
  207024. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  207025. {
  207026. HWND window;
  207027. public:
  207028. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  207029. ~JuceOleInPlaceFrame() {}
  207030. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207031. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207032. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  207033. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207034. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207035. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  207036. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  207037. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  207038. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  207039. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  207040. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  207041. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  207042. juce_UseDebuggingNewOperator
  207043. };
  207044. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  207045. {
  207046. HWND window;
  207047. JuceOleInPlaceFrame* frame;
  207048. public:
  207049. JuceIOleInPlaceSite (HWND window_)
  207050. : window (window_),
  207051. frame (new JuceOleInPlaceFrame (window))
  207052. {}
  207053. ~JuceIOleInPlaceSite()
  207054. {
  207055. frame->Release();
  207056. }
  207057. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207058. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207059. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  207060. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  207061. HRESULT __stdcall OnUIActivate() { return S_OK; }
  207062. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  207063. {
  207064. *lplpFrame = frame;
  207065. *lplpDoc = 0;
  207066. lpFrameInfo->fMDIApp = FALSE;
  207067. lpFrameInfo->hwndFrame = window;
  207068. lpFrameInfo->haccel = 0;
  207069. lpFrameInfo->cAccelEntries = 0;
  207070. return S_OK;
  207071. }
  207072. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  207073. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  207074. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  207075. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  207076. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  207077. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  207078. juce_UseDebuggingNewOperator
  207079. };
  207080. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  207081. {
  207082. JuceIOleInPlaceSite* inplaceSite;
  207083. public:
  207084. JuceIOleClientSite (HWND window)
  207085. : inplaceSite (new JuceIOleInPlaceSite (window))
  207086. {}
  207087. ~JuceIOleClientSite()
  207088. {
  207089. inplaceSite->Release();
  207090. }
  207091. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  207092. {
  207093. if (type == IID_IOleInPlaceSite)
  207094. {
  207095. inplaceSite->AddRef();
  207096. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  207097. return S_OK;
  207098. }
  207099. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  207100. }
  207101. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  207102. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  207103. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  207104. HRESULT __stdcall ShowObject() { return S_OK; }
  207105. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  207106. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  207107. juce_UseDebuggingNewOperator
  207108. };
  207109. static Array<ActiveXControlComponent*> activeXComps;
  207110. static HWND getHWND (const ActiveXControlComponent* const component)
  207111. {
  207112. HWND hwnd = 0;
  207113. const IID iid = IID_IOleWindow;
  207114. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  207115. if (window != 0)
  207116. {
  207117. window->GetWindow (&hwnd);
  207118. window->Release();
  207119. }
  207120. return hwnd;
  207121. }
  207122. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  207123. {
  207124. RECT activeXRect, peerRect;
  207125. GetWindowRect (hwnd, &activeXRect);
  207126. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  207127. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  207128. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  207129. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  207130. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  207131. switch (message)
  207132. {
  207133. case WM_MOUSEMOVE:
  207134. case WM_LBUTTONDOWN:
  207135. case WM_MBUTTONDOWN:
  207136. case WM_RBUTTONDOWN:
  207137. case WM_LBUTTONUP:
  207138. case WM_MBUTTONUP:
  207139. case WM_RBUTTONUP:
  207140. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  207141. break;
  207142. default:
  207143. break;
  207144. }
  207145. }
  207146. }
  207147. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  207148. {
  207149. ActiveXControlComponent* const owner;
  207150. bool wasShowing;
  207151. public:
  207152. HWND controlHWND;
  207153. IStorage* storage;
  207154. IOleClientSite* clientSite;
  207155. IOleObject* control;
  207156. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  207157. : ComponentMovementWatcher (owner_),
  207158. owner (owner_),
  207159. wasShowing (owner_ != 0 && owner_->isShowing()),
  207160. controlHWND (0),
  207161. storage (new ActiveXHelpers::JuceIStorage()),
  207162. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  207163. control (0)
  207164. {
  207165. }
  207166. ~Pimpl()
  207167. {
  207168. if (control != 0)
  207169. {
  207170. control->Close (OLECLOSE_NOSAVE);
  207171. control->Release();
  207172. }
  207173. clientSite->Release();
  207174. storage->Release();
  207175. }
  207176. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  207177. {
  207178. Component* const topComp = owner->getTopLevelComponent();
  207179. if (topComp->getPeer() != 0)
  207180. {
  207181. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  207182. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  207183. }
  207184. }
  207185. void componentPeerChanged()
  207186. {
  207187. const bool isShowingNow = owner->isShowing();
  207188. if (wasShowing != isShowingNow)
  207189. {
  207190. wasShowing = isShowingNow;
  207191. owner->setControlVisible (isShowingNow);
  207192. }
  207193. componentMovedOrResized (true, true);
  207194. }
  207195. void componentVisibilityChanged (Component&)
  207196. {
  207197. componentPeerChanged();
  207198. }
  207199. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  207200. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  207201. {
  207202. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  207203. {
  207204. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  207205. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  207206. {
  207207. switch (message)
  207208. {
  207209. case WM_MOUSEMOVE:
  207210. case WM_LBUTTONDOWN:
  207211. case WM_MBUTTONDOWN:
  207212. case WM_RBUTTONDOWN:
  207213. case WM_LBUTTONUP:
  207214. case WM_MBUTTONUP:
  207215. case WM_RBUTTONUP:
  207216. case WM_LBUTTONDBLCLK:
  207217. case WM_MBUTTONDBLCLK:
  207218. case WM_RBUTTONDBLCLK:
  207219. if (ax->isShowing())
  207220. {
  207221. ComponentPeer* const peer = ax->getPeer();
  207222. if (peer != 0)
  207223. {
  207224. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  207225. if (! ax->areMouseEventsAllowed())
  207226. return 0;
  207227. }
  207228. }
  207229. break;
  207230. default:
  207231. break;
  207232. }
  207233. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  207234. }
  207235. }
  207236. return DefWindowProc (hwnd, message, wParam, lParam);
  207237. }
  207238. };
  207239. ActiveXControlComponent::ActiveXControlComponent()
  207240. : originalWndProc (0),
  207241. mouseEventsAllowed (true)
  207242. {
  207243. ActiveXHelpers::activeXComps.add (this);
  207244. }
  207245. ActiveXControlComponent::~ActiveXControlComponent()
  207246. {
  207247. deleteControl();
  207248. ActiveXHelpers::activeXComps.removeValue (this);
  207249. }
  207250. void ActiveXControlComponent::paint (Graphics& g)
  207251. {
  207252. if (control == 0)
  207253. g.fillAll (Colours::lightgrey);
  207254. }
  207255. bool ActiveXControlComponent::createControl (const void* controlIID)
  207256. {
  207257. deleteControl();
  207258. ComponentPeer* const peer = getPeer();
  207259. // the component must have already been added to a real window when you call this!
  207260. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  207261. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  207262. {
  207263. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  207264. HWND hwnd = (HWND) peer->getNativeHandle();
  207265. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  207266. HRESULT hr;
  207267. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  207268. newControl->clientSite, newControl->storage,
  207269. (void**) &(newControl->control))) == S_OK)
  207270. {
  207271. newControl->control->SetHostNames (L"Juce", 0);
  207272. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  207273. {
  207274. RECT rect;
  207275. rect.left = pos.getX();
  207276. rect.top = pos.getY();
  207277. rect.right = pos.getX() + getWidth();
  207278. rect.bottom = pos.getY() + getHeight();
  207279. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  207280. {
  207281. control = newControl;
  207282. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  207283. control->controlHWND = ActiveXHelpers::getHWND (this);
  207284. if (control->controlHWND != 0)
  207285. {
  207286. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  207287. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  207288. }
  207289. return true;
  207290. }
  207291. }
  207292. }
  207293. }
  207294. return false;
  207295. }
  207296. void ActiveXControlComponent::deleteControl()
  207297. {
  207298. control = 0;
  207299. originalWndProc = 0;
  207300. }
  207301. void* ActiveXControlComponent::queryInterface (const void* iid) const
  207302. {
  207303. void* result = 0;
  207304. if (control != 0 && control->control != 0
  207305. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  207306. return result;
  207307. return 0;
  207308. }
  207309. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  207310. {
  207311. if (control->controlHWND != 0)
  207312. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  207313. }
  207314. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  207315. {
  207316. if (control->controlHWND != 0)
  207317. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207318. }
  207319. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  207320. {
  207321. mouseEventsAllowed = eventsCanReachControl;
  207322. }
  207323. #endif
  207324. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207325. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207326. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207327. // compiled on its own).
  207328. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  207329. using namespace QTOLibrary;
  207330. using namespace QTOControlLib;
  207331. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  207332. static bool isQTAvailable = false;
  207333. class QuickTimeMovieComponent::Pimpl
  207334. {
  207335. public:
  207336. Pimpl() : dataHandle (0)
  207337. {
  207338. }
  207339. ~Pimpl()
  207340. {
  207341. clearHandle();
  207342. }
  207343. void clearHandle()
  207344. {
  207345. if (dataHandle != 0)
  207346. {
  207347. DisposeHandle (dataHandle);
  207348. dataHandle = 0;
  207349. }
  207350. }
  207351. IQTControlPtr qtControl;
  207352. IQTMoviePtr qtMovie;
  207353. Handle dataHandle;
  207354. };
  207355. QuickTimeMovieComponent::QuickTimeMovieComponent()
  207356. : movieLoaded (false),
  207357. controllerVisible (true)
  207358. {
  207359. pimpl = new Pimpl();
  207360. setMouseEventsAllowed (false);
  207361. }
  207362. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  207363. {
  207364. closeMovie();
  207365. pimpl->qtControl = 0;
  207366. deleteControl();
  207367. pimpl = 0;
  207368. }
  207369. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  207370. {
  207371. if (! isQTAvailable)
  207372. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  207373. return isQTAvailable;
  207374. }
  207375. void QuickTimeMovieComponent::createControlIfNeeded()
  207376. {
  207377. if (isShowing() && ! isControlCreated())
  207378. {
  207379. const IID qtIID = __uuidof (QTControl);
  207380. if (createControl (&qtIID))
  207381. {
  207382. const IID qtInterfaceIID = __uuidof (IQTControl);
  207383. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  207384. if (pimpl->qtControl != 0)
  207385. {
  207386. pimpl->qtControl->Release(); // it has one ref too many at this point
  207387. pimpl->qtControl->QuickTimeInitialize();
  207388. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  207389. if (movieFile != File::nonexistent)
  207390. loadMovie (movieFile, controllerVisible);
  207391. }
  207392. }
  207393. }
  207394. }
  207395. bool QuickTimeMovieComponent::isControlCreated() const
  207396. {
  207397. return isControlOpen();
  207398. }
  207399. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  207400. const bool isControllerVisible)
  207401. {
  207402. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  207403. movieFile = File::nonexistent;
  207404. movieLoaded = false;
  207405. pimpl->qtMovie = 0;
  207406. controllerVisible = isControllerVisible;
  207407. createControlIfNeeded();
  207408. if (isControlCreated())
  207409. {
  207410. if (pimpl->qtControl != 0)
  207411. {
  207412. pimpl->qtControl->Put_MovieHandle (0);
  207413. pimpl->clearHandle();
  207414. Movie movie;
  207415. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  207416. {
  207417. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  207418. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  207419. if (pimpl->qtMovie != 0)
  207420. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  207421. : qtMovieControllerTypeNone);
  207422. }
  207423. if (movie == 0)
  207424. pimpl->clearHandle();
  207425. }
  207426. movieLoaded = (pimpl->qtMovie != 0);
  207427. }
  207428. else
  207429. {
  207430. // You're trying to open a movie when the control hasn't yet been created, probably because
  207431. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  207432. jassertfalse;
  207433. }
  207434. return movieLoaded;
  207435. }
  207436. void QuickTimeMovieComponent::closeMovie()
  207437. {
  207438. stop();
  207439. movieFile = File::nonexistent;
  207440. movieLoaded = false;
  207441. pimpl->qtMovie = 0;
  207442. if (pimpl->qtControl != 0)
  207443. pimpl->qtControl->Put_MovieHandle (0);
  207444. pimpl->clearHandle();
  207445. }
  207446. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  207447. {
  207448. return movieFile;
  207449. }
  207450. bool QuickTimeMovieComponent::isMovieOpen() const
  207451. {
  207452. return movieLoaded;
  207453. }
  207454. double QuickTimeMovieComponent::getMovieDuration() const
  207455. {
  207456. if (pimpl->qtMovie != 0)
  207457. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  207458. return 0.0;
  207459. }
  207460. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  207461. {
  207462. if (pimpl->qtMovie != 0)
  207463. {
  207464. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  207465. width = r.right - r.left;
  207466. height = r.bottom - r.top;
  207467. }
  207468. else
  207469. {
  207470. width = height = 0;
  207471. }
  207472. }
  207473. void QuickTimeMovieComponent::play()
  207474. {
  207475. if (pimpl->qtMovie != 0)
  207476. pimpl->qtMovie->Play();
  207477. }
  207478. void QuickTimeMovieComponent::stop()
  207479. {
  207480. if (pimpl->qtMovie != 0)
  207481. pimpl->qtMovie->Stop();
  207482. }
  207483. bool QuickTimeMovieComponent::isPlaying() const
  207484. {
  207485. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  207486. }
  207487. void QuickTimeMovieComponent::setPosition (const double seconds)
  207488. {
  207489. if (pimpl->qtMovie != 0)
  207490. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  207491. }
  207492. double QuickTimeMovieComponent::getPosition() const
  207493. {
  207494. if (pimpl->qtMovie != 0)
  207495. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  207496. return 0.0;
  207497. }
  207498. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  207499. {
  207500. if (pimpl->qtMovie != 0)
  207501. pimpl->qtMovie->PutRate (newSpeed);
  207502. }
  207503. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  207504. {
  207505. if (pimpl->qtMovie != 0)
  207506. {
  207507. pimpl->qtMovie->PutAudioVolume (newVolume);
  207508. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  207509. }
  207510. }
  207511. float QuickTimeMovieComponent::getMovieVolume() const
  207512. {
  207513. if (pimpl->qtMovie != 0)
  207514. return pimpl->qtMovie->GetAudioVolume();
  207515. return 0.0f;
  207516. }
  207517. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  207518. {
  207519. if (pimpl->qtMovie != 0)
  207520. pimpl->qtMovie->PutLoop (shouldLoop);
  207521. }
  207522. bool QuickTimeMovieComponent::isLooping() const
  207523. {
  207524. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  207525. }
  207526. bool QuickTimeMovieComponent::isControllerVisible() const
  207527. {
  207528. return controllerVisible;
  207529. }
  207530. void QuickTimeMovieComponent::parentHierarchyChanged()
  207531. {
  207532. createControlIfNeeded();
  207533. QTCompBaseClass::parentHierarchyChanged();
  207534. }
  207535. void QuickTimeMovieComponent::visibilityChanged()
  207536. {
  207537. createControlIfNeeded();
  207538. QTCompBaseClass::visibilityChanged();
  207539. }
  207540. void QuickTimeMovieComponent::paint (Graphics& g)
  207541. {
  207542. if (! isControlCreated())
  207543. g.fillAll (Colours::black);
  207544. }
  207545. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  207546. {
  207547. Handle dataRef = 0;
  207548. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  207549. if (err == noErr)
  207550. {
  207551. Str255 suffix;
  207552. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  207553. StringPtr name = suffix;
  207554. err = PtrAndHand (name, dataRef, name[0] + 1);
  207555. if (err == noErr)
  207556. {
  207557. long atoms[3];
  207558. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  207559. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  207560. atoms[2] = EndianU32_NtoB (MovieFileType);
  207561. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  207562. if (err == noErr)
  207563. return dataRef;
  207564. }
  207565. DisposeHandle (dataRef);
  207566. }
  207567. return 0;
  207568. }
  207569. static CFStringRef juceStringToCFString (const String& s)
  207570. {
  207571. const int len = s.length();
  207572. const juce_wchar* const t = s;
  207573. HeapBlock <UniChar> temp (len + 2);
  207574. for (int i = 0; i <= len; ++i)
  207575. temp[i] = t[i];
  207576. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  207577. }
  207578. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  207579. {
  207580. Boolean trueBool = true;
  207581. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  207582. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  207583. props[prop].propValueSize = sizeof (trueBool);
  207584. props[prop].propValueAddress = &trueBool;
  207585. ++prop;
  207586. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  207587. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  207588. props[prop].propValueSize = sizeof (trueBool);
  207589. props[prop].propValueAddress = &trueBool;
  207590. ++prop;
  207591. Boolean isActive = true;
  207592. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  207593. props[prop].propID = kQTNewMoviePropertyID_Active;
  207594. props[prop].propValueSize = sizeof (isActive);
  207595. props[prop].propValueAddress = &isActive;
  207596. ++prop;
  207597. MacSetPort (0);
  207598. jassert (prop <= 5);
  207599. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  207600. return err == noErr;
  207601. }
  207602. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  207603. {
  207604. if (input == 0)
  207605. return false;
  207606. dataHandle = 0;
  207607. bool ok = false;
  207608. QTNewMoviePropertyElement props[5];
  207609. zeromem (props, sizeof (props));
  207610. int prop = 0;
  207611. DataReferenceRecord dr;
  207612. props[prop].propClass = kQTPropertyClass_DataLocation;
  207613. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  207614. props[prop].propValueSize = sizeof (dr);
  207615. props[prop].propValueAddress = &dr;
  207616. ++prop;
  207617. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  207618. if (fin != 0)
  207619. {
  207620. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  207621. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  207622. &dr.dataRef, &dr.dataRefType);
  207623. ok = openMovie (props, prop, movie);
  207624. DisposeHandle (dr.dataRef);
  207625. CFRelease (filePath);
  207626. }
  207627. else
  207628. {
  207629. // sanity-check because this currently needs to load the whole stream into memory..
  207630. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  207631. dataHandle = NewHandle ((Size) input->getTotalLength());
  207632. HLock (dataHandle);
  207633. // read the entire stream into memory - this is a pain, but can't get it to work
  207634. // properly using a custom callback to supply the data.
  207635. input->read (*dataHandle, (int) input->getTotalLength());
  207636. HUnlock (dataHandle);
  207637. // different types to get QT to try. (We should really be a bit smarter here by
  207638. // working out in advance which one the stream contains, rather than just trying
  207639. // each one)
  207640. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  207641. "\04.avi", "\04.m4a" };
  207642. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  207643. {
  207644. /* // this fails for some bizarre reason - it can be bodged to work with
  207645. // movies, but can't seem to do it for other file types..
  207646. QTNewMovieUserProcRecord procInfo;
  207647. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  207648. procInfo.getMovieUserProcRefcon = this;
  207649. procInfo.defaultDataRef.dataRef = dataRef;
  207650. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  207651. props[prop].propClass = kQTPropertyClass_DataLocation;
  207652. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  207653. props[prop].propValueSize = sizeof (procInfo);
  207654. props[prop].propValueAddress = (void*) &procInfo;
  207655. ++prop; */
  207656. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  207657. dr.dataRefType = HandleDataHandlerSubType;
  207658. ok = openMovie (props, prop, movie);
  207659. DisposeHandle (dr.dataRef);
  207660. }
  207661. }
  207662. return ok;
  207663. }
  207664. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  207665. const bool isControllerVisible)
  207666. {
  207667. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  207668. movieFile = movieFile_;
  207669. return ok;
  207670. }
  207671. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  207672. const bool isControllerVisible)
  207673. {
  207674. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  207675. }
  207676. void QuickTimeMovieComponent::goToStart()
  207677. {
  207678. setPosition (0.0);
  207679. }
  207680. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  207681. const RectanglePlacement& placement)
  207682. {
  207683. int normalWidth, normalHeight;
  207684. getMovieNormalSize (normalWidth, normalHeight);
  207685. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  207686. {
  207687. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  207688. placement.applyTo (x, y, w, h,
  207689. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  207690. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  207691. if (w > 0 && h > 0)
  207692. {
  207693. setBounds (roundToInt (x), roundToInt (y),
  207694. roundToInt (w), roundToInt (h));
  207695. }
  207696. }
  207697. else
  207698. {
  207699. setBounds (spaceToFitWithin);
  207700. }
  207701. }
  207702. #endif
  207703. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207704. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  207705. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207706. // compiled on its own).
  207707. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  207708. class WebBrowserComponentInternal : public ActiveXControlComponent
  207709. {
  207710. public:
  207711. WebBrowserComponentInternal()
  207712. : browser (0),
  207713. connectionPoint (0),
  207714. adviseCookie (0)
  207715. {
  207716. }
  207717. ~WebBrowserComponentInternal()
  207718. {
  207719. if (connectionPoint != 0)
  207720. connectionPoint->Unadvise (adviseCookie);
  207721. if (browser != 0)
  207722. browser->Release();
  207723. }
  207724. void createBrowser()
  207725. {
  207726. createControl (&CLSID_WebBrowser);
  207727. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  207728. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  207729. if (connectionPointContainer != 0)
  207730. {
  207731. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  207732. &connectionPoint);
  207733. if (connectionPoint != 0)
  207734. {
  207735. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  207736. jassert (owner != 0);
  207737. EventHandler* handler = new EventHandler (owner);
  207738. connectionPoint->Advise (handler, &adviseCookie);
  207739. handler->Release();
  207740. }
  207741. }
  207742. }
  207743. void goToURL (const String& url,
  207744. const StringArray* headers,
  207745. const MemoryBlock* postData)
  207746. {
  207747. if (browser != 0)
  207748. {
  207749. LPSAFEARRAY sa = 0;
  207750. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  207751. VariantInit (&flags);
  207752. VariantInit (&frame);
  207753. VariantInit (&postDataVar);
  207754. VariantInit (&headersVar);
  207755. if (headers != 0)
  207756. {
  207757. V_VT (&headersVar) = VT_BSTR;
  207758. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  207759. }
  207760. if (postData != 0 && postData->getSize() > 0)
  207761. {
  207762. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  207763. if (sa != 0)
  207764. {
  207765. void* data = 0;
  207766. SafeArrayAccessData (sa, &data);
  207767. jassert (data != 0);
  207768. if (data != 0)
  207769. {
  207770. postData->copyTo (data, 0, postData->getSize());
  207771. SafeArrayUnaccessData (sa);
  207772. VARIANT postDataVar2;
  207773. VariantInit (&postDataVar2);
  207774. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  207775. V_ARRAY (&postDataVar2) = sa;
  207776. postDataVar = postDataVar2;
  207777. }
  207778. }
  207779. }
  207780. browser->Navigate ((BSTR) (const OLECHAR*) url,
  207781. &flags, &frame,
  207782. &postDataVar, &headersVar);
  207783. if (sa != 0)
  207784. SafeArrayDestroy (sa);
  207785. VariantClear (&flags);
  207786. VariantClear (&frame);
  207787. VariantClear (&postDataVar);
  207788. VariantClear (&headersVar);
  207789. }
  207790. }
  207791. IWebBrowser2* browser;
  207792. juce_UseDebuggingNewOperator
  207793. private:
  207794. IConnectionPoint* connectionPoint;
  207795. DWORD adviseCookie;
  207796. class EventHandler : public ComBaseClassHelper <IDispatch>,
  207797. public ComponentMovementWatcher
  207798. {
  207799. public:
  207800. EventHandler (WebBrowserComponent* owner_)
  207801. : ComponentMovementWatcher (owner_),
  207802. owner (owner_)
  207803. {
  207804. }
  207805. ~EventHandler()
  207806. {
  207807. }
  207808. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  207809. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  207810. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  207811. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  207812. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  207813. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  207814. UINT __RPC_FAR* /*puArgErr*/)
  207815. {
  207816. switch (dispIdMember)
  207817. {
  207818. case DISPID_BEFORENAVIGATE2:
  207819. {
  207820. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  207821. String url;
  207822. if ((vurl->vt & VT_BYREF) != 0)
  207823. url = *vurl->pbstrVal;
  207824. else
  207825. url = vurl->bstrVal;
  207826. *pDispParams->rgvarg->pboolVal
  207827. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  207828. : VARIANT_TRUE;
  207829. return S_OK;
  207830. }
  207831. default:
  207832. break;
  207833. }
  207834. return E_NOTIMPL;
  207835. }
  207836. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  207837. void componentPeerChanged() {}
  207838. void componentVisibilityChanged (Component&)
  207839. {
  207840. owner->visibilityChanged();
  207841. }
  207842. juce_UseDebuggingNewOperator
  207843. private:
  207844. WebBrowserComponent* const owner;
  207845. EventHandler (const EventHandler&);
  207846. EventHandler& operator= (const EventHandler&);
  207847. };
  207848. };
  207849. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  207850. : browser (0),
  207851. blankPageShown (false),
  207852. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  207853. {
  207854. setOpaque (true);
  207855. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  207856. }
  207857. WebBrowserComponent::~WebBrowserComponent()
  207858. {
  207859. delete browser;
  207860. }
  207861. void WebBrowserComponent::goToURL (const String& url,
  207862. const StringArray* headers,
  207863. const MemoryBlock* postData)
  207864. {
  207865. lastURL = url;
  207866. lastHeaders.clear();
  207867. if (headers != 0)
  207868. lastHeaders = *headers;
  207869. lastPostData.setSize (0);
  207870. if (postData != 0)
  207871. lastPostData = *postData;
  207872. blankPageShown = false;
  207873. browser->goToURL (url, headers, postData);
  207874. }
  207875. void WebBrowserComponent::stop()
  207876. {
  207877. if (browser->browser != 0)
  207878. browser->browser->Stop();
  207879. }
  207880. void WebBrowserComponent::goBack()
  207881. {
  207882. lastURL = String::empty;
  207883. blankPageShown = false;
  207884. if (browser->browser != 0)
  207885. browser->browser->GoBack();
  207886. }
  207887. void WebBrowserComponent::goForward()
  207888. {
  207889. lastURL = String::empty;
  207890. if (browser->browser != 0)
  207891. browser->browser->GoForward();
  207892. }
  207893. void WebBrowserComponent::refresh()
  207894. {
  207895. if (browser->browser != 0)
  207896. browser->browser->Refresh();
  207897. }
  207898. void WebBrowserComponent::paint (Graphics& g)
  207899. {
  207900. if (browser->browser == 0)
  207901. g.fillAll (Colours::white);
  207902. }
  207903. void WebBrowserComponent::checkWindowAssociation()
  207904. {
  207905. if (isShowing())
  207906. {
  207907. if (browser->browser == 0 && getPeer() != 0)
  207908. {
  207909. browser->createBrowser();
  207910. reloadLastURL();
  207911. }
  207912. else
  207913. {
  207914. if (blankPageShown)
  207915. goBack();
  207916. }
  207917. }
  207918. else
  207919. {
  207920. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  207921. {
  207922. // when the component becomes invisible, some stuff like flash
  207923. // carries on playing audio, so we need to force it onto a blank
  207924. // page to avoid this..
  207925. blankPageShown = true;
  207926. browser->goToURL ("about:blank", 0, 0);
  207927. }
  207928. }
  207929. }
  207930. void WebBrowserComponent::reloadLastURL()
  207931. {
  207932. if (lastURL.isNotEmpty())
  207933. {
  207934. goToURL (lastURL, &lastHeaders, &lastPostData);
  207935. lastURL = String::empty;
  207936. }
  207937. }
  207938. void WebBrowserComponent::parentHierarchyChanged()
  207939. {
  207940. checkWindowAssociation();
  207941. }
  207942. void WebBrowserComponent::resized()
  207943. {
  207944. browser->setSize (getWidth(), getHeight());
  207945. }
  207946. void WebBrowserComponent::visibilityChanged()
  207947. {
  207948. checkWindowAssociation();
  207949. }
  207950. bool WebBrowserComponent::pageAboutToLoad (const String&)
  207951. {
  207952. return true;
  207953. }
  207954. #endif
  207955. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  207956. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  207957. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207958. // compiled on its own).
  207959. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  207960. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  207961. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  207962. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  207963. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  207964. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  207965. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  207966. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  207967. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  207968. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  207969. #define WGL_ACCELERATION_ARB 0x2003
  207970. #define WGL_SWAP_METHOD_ARB 0x2007
  207971. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  207972. #define WGL_PIXEL_TYPE_ARB 0x2013
  207973. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  207974. #define WGL_COLOR_BITS_ARB 0x2014
  207975. #define WGL_RED_BITS_ARB 0x2015
  207976. #define WGL_GREEN_BITS_ARB 0x2017
  207977. #define WGL_BLUE_BITS_ARB 0x2019
  207978. #define WGL_ALPHA_BITS_ARB 0x201B
  207979. #define WGL_DEPTH_BITS_ARB 0x2022
  207980. #define WGL_STENCIL_BITS_ARB 0x2023
  207981. #define WGL_FULL_ACCELERATION_ARB 0x2027
  207982. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  207983. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  207984. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  207985. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  207986. #define WGL_STEREO_ARB 0x2012
  207987. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  207988. #define WGL_SAMPLES_ARB 0x2042
  207989. #define WGL_TYPE_RGBA_ARB 0x202B
  207990. static void getWglExtensions (HDC dc, StringArray& result) throw()
  207991. {
  207992. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  207993. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  207994. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  207995. else
  207996. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  207997. }
  207998. class WindowedGLContext : public OpenGLContext
  207999. {
  208000. public:
  208001. WindowedGLContext (Component* const component_,
  208002. HGLRC contextToShareWith,
  208003. const OpenGLPixelFormat& pixelFormat)
  208004. : renderContext (0),
  208005. nativeWindow (0),
  208006. dc (0),
  208007. component (component_)
  208008. {
  208009. jassert (component != 0);
  208010. createNativeWindow();
  208011. // Use a default pixel format that should be supported everywhere
  208012. PIXELFORMATDESCRIPTOR pfd;
  208013. zerostruct (pfd);
  208014. pfd.nSize = sizeof (pfd);
  208015. pfd.nVersion = 1;
  208016. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  208017. pfd.iPixelType = PFD_TYPE_RGBA;
  208018. pfd.cColorBits = 24;
  208019. pfd.cDepthBits = 16;
  208020. const int format = ChoosePixelFormat (dc, &pfd);
  208021. if (format != 0)
  208022. SetPixelFormat (dc, format, &pfd);
  208023. renderContext = wglCreateContext (dc);
  208024. makeActive();
  208025. setPixelFormat (pixelFormat);
  208026. if (contextToShareWith != 0 && renderContext != 0)
  208027. wglShareLists (contextToShareWith, renderContext);
  208028. }
  208029. ~WindowedGLContext()
  208030. {
  208031. makeInactive();
  208032. wglDeleteContext (renderContext);
  208033. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208034. delete nativeWindow;
  208035. }
  208036. bool makeActive() const throw()
  208037. {
  208038. jassert (renderContext != 0);
  208039. return wglMakeCurrent (dc, renderContext) != 0;
  208040. }
  208041. bool makeInactive() const throw()
  208042. {
  208043. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  208044. }
  208045. bool isActive() const throw()
  208046. {
  208047. return wglGetCurrentContext() == renderContext;
  208048. }
  208049. const OpenGLPixelFormat getPixelFormat() const
  208050. {
  208051. OpenGLPixelFormat pf;
  208052. makeActive();
  208053. StringArray availableExtensions;
  208054. getWglExtensions (dc, availableExtensions);
  208055. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  208056. return pf;
  208057. }
  208058. void* getRawContext() const throw()
  208059. {
  208060. return renderContext;
  208061. }
  208062. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  208063. {
  208064. makeActive();
  208065. PIXELFORMATDESCRIPTOR pfd;
  208066. zerostruct (pfd);
  208067. pfd.nSize = sizeof (pfd);
  208068. pfd.nVersion = 1;
  208069. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  208070. pfd.iPixelType = PFD_TYPE_RGBA;
  208071. pfd.iLayerType = PFD_MAIN_PLANE;
  208072. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  208073. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  208074. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  208075. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  208076. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  208077. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  208078. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  208079. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  208080. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  208081. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  208082. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  208083. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  208084. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  208085. int format = 0;
  208086. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  208087. StringArray availableExtensions;
  208088. getWglExtensions (dc, availableExtensions);
  208089. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208090. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  208091. {
  208092. int attributes[64];
  208093. int n = 0;
  208094. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  208095. attributes[n++] = GL_TRUE;
  208096. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  208097. attributes[n++] = GL_TRUE;
  208098. attributes[n++] = WGL_ACCELERATION_ARB;
  208099. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  208100. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  208101. attributes[n++] = GL_TRUE;
  208102. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  208103. attributes[n++] = WGL_TYPE_RGBA_ARB;
  208104. attributes[n++] = WGL_COLOR_BITS_ARB;
  208105. attributes[n++] = pfd.cColorBits;
  208106. attributes[n++] = WGL_RED_BITS_ARB;
  208107. attributes[n++] = pixelFormat.redBits;
  208108. attributes[n++] = WGL_GREEN_BITS_ARB;
  208109. attributes[n++] = pixelFormat.greenBits;
  208110. attributes[n++] = WGL_BLUE_BITS_ARB;
  208111. attributes[n++] = pixelFormat.blueBits;
  208112. attributes[n++] = WGL_ALPHA_BITS_ARB;
  208113. attributes[n++] = pixelFormat.alphaBits;
  208114. attributes[n++] = WGL_DEPTH_BITS_ARB;
  208115. attributes[n++] = pixelFormat.depthBufferBits;
  208116. if (pixelFormat.stencilBufferBits > 0)
  208117. {
  208118. attributes[n++] = WGL_STENCIL_BITS_ARB;
  208119. attributes[n++] = pixelFormat.stencilBufferBits;
  208120. }
  208121. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  208122. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  208123. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  208124. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  208125. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  208126. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  208127. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208128. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  208129. if (availableExtensions.contains ("WGL_ARB_multisample")
  208130. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  208131. {
  208132. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  208133. attributes[n++] = 1;
  208134. attributes[n++] = WGL_SAMPLES_ARB;
  208135. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  208136. }
  208137. attributes[n++] = 0;
  208138. UINT formatsCount;
  208139. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  208140. (void) ok;
  208141. jassert (ok);
  208142. }
  208143. else
  208144. {
  208145. format = ChoosePixelFormat (dc, &pfd);
  208146. }
  208147. if (format != 0)
  208148. {
  208149. makeInactive();
  208150. // win32 can't change the pixel format of a window, so need to delete the
  208151. // old one and create a new one..
  208152. jassert (nativeWindow != 0);
  208153. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208154. delete nativeWindow;
  208155. createNativeWindow();
  208156. if (SetPixelFormat (dc, format, &pfd))
  208157. {
  208158. wglDeleteContext (renderContext);
  208159. renderContext = wglCreateContext (dc);
  208160. jassert (renderContext != 0);
  208161. return renderContext != 0;
  208162. }
  208163. }
  208164. return false;
  208165. }
  208166. void updateWindowPosition (int x, int y, int w, int h, int)
  208167. {
  208168. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208169. x, y, w, h,
  208170. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208171. }
  208172. void repaint()
  208173. {
  208174. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  208175. }
  208176. void swapBuffers()
  208177. {
  208178. SwapBuffers (dc);
  208179. }
  208180. bool setSwapInterval (int numFramesPerSwap)
  208181. {
  208182. makeActive();
  208183. StringArray availableExtensions;
  208184. getWglExtensions (dc, availableExtensions);
  208185. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208186. return availableExtensions.contains ("WGL_EXT_swap_control")
  208187. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208188. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208189. }
  208190. int getSwapInterval() const
  208191. {
  208192. makeActive();
  208193. StringArray availableExtensions;
  208194. getWglExtensions (dc, availableExtensions);
  208195. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208196. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208197. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208198. return wglGetSwapIntervalEXT();
  208199. return 0;
  208200. }
  208201. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208202. {
  208203. jassert (isActive());
  208204. StringArray availableExtensions;
  208205. getWglExtensions (dc, availableExtensions);
  208206. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208207. int numTypes = 0;
  208208. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208209. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208210. {
  208211. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208212. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208213. jassertfalse;
  208214. }
  208215. else
  208216. {
  208217. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208218. }
  208219. OpenGLPixelFormat pf;
  208220. for (int i = 0; i < numTypes; ++i)
  208221. {
  208222. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208223. {
  208224. bool alreadyListed = false;
  208225. for (int j = results.size(); --j >= 0;)
  208226. if (pf == *results.getUnchecked(j))
  208227. alreadyListed = true;
  208228. if (! alreadyListed)
  208229. results.add (new OpenGLPixelFormat (pf));
  208230. }
  208231. }
  208232. }
  208233. void* getNativeWindowHandle() const
  208234. {
  208235. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  208236. }
  208237. juce_UseDebuggingNewOperator
  208238. HGLRC renderContext;
  208239. private:
  208240. Win32ComponentPeer* nativeWindow;
  208241. Component* const component;
  208242. HDC dc;
  208243. void createNativeWindow()
  208244. {
  208245. nativeWindow = new Win32ComponentPeer (component, 0);
  208246. nativeWindow->dontRepaint = true;
  208247. nativeWindow->setVisible (true);
  208248. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208249. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208250. if (peer != 0)
  208251. {
  208252. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208253. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208254. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208255. }
  208256. dc = GetDC (hwnd);
  208257. }
  208258. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208259. OpenGLPixelFormat& result,
  208260. const StringArray& availableExtensions) const throw()
  208261. {
  208262. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208263. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208264. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208265. {
  208266. int attributes[32];
  208267. int numAttributes = 0;
  208268. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208269. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208270. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208271. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208272. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208273. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208274. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208275. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208276. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208277. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208278. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208279. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208280. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208281. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208282. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208283. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208284. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208285. int values[32];
  208286. zeromem (values, sizeof (values));
  208287. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208288. {
  208289. int n = 0;
  208290. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208291. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208292. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208293. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208294. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208295. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208296. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208297. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208298. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208299. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208300. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208301. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208302. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208303. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208304. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208305. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  208306. return isValidFormat;
  208307. }
  208308. else
  208309. {
  208310. jassertfalse;
  208311. }
  208312. }
  208313. else
  208314. {
  208315. PIXELFORMATDESCRIPTOR pfd;
  208316. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208317. {
  208318. result.redBits = pfd.cRedBits;
  208319. result.greenBits = pfd.cGreenBits;
  208320. result.blueBits = pfd.cBlueBits;
  208321. result.alphaBits = pfd.cAlphaBits;
  208322. result.depthBufferBits = pfd.cDepthBits;
  208323. result.stencilBufferBits = pfd.cStencilBits;
  208324. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208325. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208326. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208327. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208328. result.fullSceneAntiAliasingNumSamples = 0;
  208329. return true;
  208330. }
  208331. else
  208332. {
  208333. jassertfalse;
  208334. }
  208335. }
  208336. return false;
  208337. }
  208338. WindowedGLContext (const WindowedGLContext&);
  208339. WindowedGLContext& operator= (const WindowedGLContext&);
  208340. };
  208341. OpenGLContext* OpenGLComponent::createContext()
  208342. {
  208343. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  208344. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  208345. preferredPixelFormat));
  208346. return (c->renderContext != 0) ? c.release() : 0;
  208347. }
  208348. void* OpenGLComponent::getNativeWindowHandle() const
  208349. {
  208350. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  208351. }
  208352. void juce_glViewport (const int w, const int h)
  208353. {
  208354. glViewport (0, 0, w, h);
  208355. }
  208356. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208357. OwnedArray <OpenGLPixelFormat>& results)
  208358. {
  208359. Component tempComp;
  208360. {
  208361. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208362. wc.makeActive();
  208363. wc.findAlternativeOpenGLPixelFormats (results);
  208364. }
  208365. }
  208366. #endif
  208367. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208368. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  208369. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208370. // compiled on its own).
  208371. #if JUCE_INCLUDED_FILE
  208372. #if JUCE_USE_CDREADER
  208373. namespace CDReaderHelpers
  208374. {
  208375. //***************************************************************************
  208376. // %%% TARGET STATUS VALUES %%%
  208377. //***************************************************************************
  208378. #define STATUS_GOOD 0x00 // Status Good
  208379. #define STATUS_CHKCOND 0x02 // Check Condition
  208380. #define STATUS_CONDMET 0x04 // Condition Met
  208381. #define STATUS_BUSY 0x08 // Busy
  208382. #define STATUS_INTERM 0x10 // Intermediate
  208383. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  208384. #define STATUS_RESCONF 0x18 // Reservation conflict
  208385. #define STATUS_COMTERM 0x22 // Command Terminated
  208386. #define STATUS_QFULL 0x28 // Queue full
  208387. //***************************************************************************
  208388. // %%% SCSI MISCELLANEOUS EQUATES %%%
  208389. //***************************************************************************
  208390. #define MAXLUN 7 // Maximum Logical Unit Id
  208391. #define MAXTARG 7 // Maximum Target Id
  208392. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  208393. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  208394. //***************************************************************************
  208395. // %%% Commands for all Device Types %%%
  208396. //***************************************************************************
  208397. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  208398. #define SCSI_COMPARE 0x39 // Compare (O)
  208399. #define SCSI_COPY 0x18 // Copy (O)
  208400. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  208401. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  208402. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  208403. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  208404. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  208405. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  208406. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  208407. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  208408. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  208409. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  208410. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  208411. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  208412. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  208413. //***************************************************************************
  208414. // %%% Commands Unique to Direct Access Devices %%%
  208415. //***************************************************************************
  208416. #define SCSI_COMPARE 0x39 // Compare (O)
  208417. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  208418. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  208419. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  208420. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  208421. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  208422. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  208423. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  208424. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  208425. #define SCSI_READ_LONG 0x3E // Read Long (O)
  208426. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  208427. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  208428. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  208429. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  208430. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  208431. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  208432. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  208433. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  208434. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  208435. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  208436. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  208437. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  208438. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  208439. #define SCSI_VERIFY 0x2F // Verify (O)
  208440. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  208441. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  208442. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  208443. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  208444. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  208445. //***************************************************************************
  208446. // %%% Commands Unique to Sequential Access Devices %%%
  208447. //***************************************************************************
  208448. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  208449. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  208450. #define SCSI_LOCATE 0x2B // Locate (O)
  208451. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  208452. #define SCSI_READ_POS 0x34 // Read Position (O)
  208453. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  208454. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  208455. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  208456. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  208457. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  208458. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  208459. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  208460. //***************************************************************************
  208461. // %%% Commands Unique to Printer Devices %%%
  208462. //***************************************************************************
  208463. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  208464. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  208465. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  208466. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  208467. //***************************************************************************
  208468. // %%% Commands Unique to Processor Devices %%%
  208469. //***************************************************************************
  208470. #define SCSI_RECEIVE 0x08 // Receive (O)
  208471. #define SCSI_SEND 0x0A // Send (O)
  208472. //***************************************************************************
  208473. // %%% Commands Unique to Write-Once Devices %%%
  208474. //***************************************************************************
  208475. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  208476. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  208477. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  208478. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  208479. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  208480. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  208481. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  208482. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  208483. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  208484. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  208485. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  208486. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  208487. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  208488. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  208489. //***************************************************************************
  208490. // %%% Commands Unique to CD-ROM Devices %%%
  208491. //***************************************************************************
  208492. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  208493. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  208494. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  208495. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  208496. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  208497. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  208498. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  208499. #define SCSI_READHEADER 0x44 // Read Header (O)
  208500. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  208501. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  208502. //***************************************************************************
  208503. // %%% Commands Unique to Scanner Devices %%%
  208504. //***************************************************************************
  208505. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  208506. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  208507. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  208508. #define SCSI_SCAN 0x1B // Scan (O)
  208509. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  208510. //***************************************************************************
  208511. // %%% Commands Unique to Optical Memory Devices %%%
  208512. //***************************************************************************
  208513. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  208514. //***************************************************************************
  208515. // %%% Commands Unique to Medium Changer Devices %%%
  208516. //***************************************************************************
  208517. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  208518. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  208519. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  208520. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  208521. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  208522. //***************************************************************************
  208523. // %%% Commands Unique to Communication Devices %%%
  208524. //***************************************************************************
  208525. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  208526. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  208527. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  208528. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  208529. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  208530. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  208531. //***************************************************************************
  208532. // %%% Request Sense Data Format %%%
  208533. //***************************************************************************
  208534. typedef struct {
  208535. BYTE ErrorCode; // Error Code (70H or 71H)
  208536. BYTE SegmentNum; // Number of current segment descriptor
  208537. BYTE SenseKey; // Sense Key(See bit definitions too)
  208538. BYTE InfoByte0; // Information MSB
  208539. BYTE InfoByte1; // Information MID
  208540. BYTE InfoByte2; // Information MID
  208541. BYTE InfoByte3; // Information LSB
  208542. BYTE AddSenLen; // Additional Sense Length
  208543. BYTE ComSpecInf0; // Command Specific Information MSB
  208544. BYTE ComSpecInf1; // Command Specific Information MID
  208545. BYTE ComSpecInf2; // Command Specific Information MID
  208546. BYTE ComSpecInf3; // Command Specific Information LSB
  208547. BYTE AddSenseCode; // Additional Sense Code
  208548. BYTE AddSenQual; // Additional Sense Code Qualifier
  208549. BYTE FieldRepUCode; // Field Replaceable Unit Code
  208550. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  208551. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  208552. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  208553. BYTE AddSenseBytes; // Additional Sense Bytes
  208554. } SENSE_DATA_FMT;
  208555. //***************************************************************************
  208556. // %%% REQUEST SENSE ERROR CODE %%%
  208557. //***************************************************************************
  208558. #define SERROR_CURRENT 0x70 // Current Errors
  208559. #define SERROR_DEFERED 0x71 // Deferred Errors
  208560. //***************************************************************************
  208561. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  208562. //***************************************************************************
  208563. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  208564. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  208565. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  208566. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  208567. //***************************************************************************
  208568. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  208569. //***************************************************************************
  208570. #define KEY_NOSENSE 0x00 // No Sense
  208571. #define KEY_RECERROR 0x01 // Recovered Error
  208572. #define KEY_NOTREADY 0x02 // Not Ready
  208573. #define KEY_MEDIUMERR 0x03 // Medium Error
  208574. #define KEY_HARDERROR 0x04 // Hardware Error
  208575. #define KEY_ILLGLREQ 0x05 // Illegal Request
  208576. #define KEY_UNITATT 0x06 // Unit Attention
  208577. #define KEY_DATAPROT 0x07 // Data Protect
  208578. #define KEY_BLANKCHK 0x08 // Blank Check
  208579. #define KEY_VENDSPEC 0x09 // Vendor Specific
  208580. #define KEY_COPYABORT 0x0A // Copy Abort
  208581. #define KEY_EQUAL 0x0C // Equal (Search)
  208582. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  208583. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  208584. #define KEY_RESERVED 0x0F // Reserved
  208585. //***************************************************************************
  208586. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  208587. //***************************************************************************
  208588. #define DTYPE_DASD 0x00 // Disk Device
  208589. #define DTYPE_SEQD 0x01 // Tape Device
  208590. #define DTYPE_PRNT 0x02 // Printer
  208591. #define DTYPE_PROC 0x03 // Processor
  208592. #define DTYPE_WORM 0x04 // Write-once read-multiple
  208593. #define DTYPE_CROM 0x05 // CD-ROM device
  208594. #define DTYPE_SCAN 0x06 // Scanner device
  208595. #define DTYPE_OPTI 0x07 // Optical memory device
  208596. #define DTYPE_JUKE 0x08 // Medium Changer device
  208597. #define DTYPE_COMM 0x09 // Communications device
  208598. #define DTYPE_RESL 0x0A // Reserved (low)
  208599. #define DTYPE_RESH 0x1E // Reserved (high)
  208600. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  208601. //***************************************************************************
  208602. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  208603. //***************************************************************************
  208604. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  208605. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  208606. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  208607. #define ANSI_RESLO 0x3 // Reserved (low)
  208608. #define ANSI_RESHI 0x7 // Reserved (high)
  208609. typedef struct
  208610. {
  208611. USHORT Length;
  208612. UCHAR ScsiStatus;
  208613. UCHAR PathId;
  208614. UCHAR TargetId;
  208615. UCHAR Lun;
  208616. UCHAR CdbLength;
  208617. UCHAR SenseInfoLength;
  208618. UCHAR DataIn;
  208619. ULONG DataTransferLength;
  208620. ULONG TimeOutValue;
  208621. ULONG DataBufferOffset;
  208622. ULONG SenseInfoOffset;
  208623. UCHAR Cdb[16];
  208624. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  208625. typedef struct
  208626. {
  208627. USHORT Length;
  208628. UCHAR ScsiStatus;
  208629. UCHAR PathId;
  208630. UCHAR TargetId;
  208631. UCHAR Lun;
  208632. UCHAR CdbLength;
  208633. UCHAR SenseInfoLength;
  208634. UCHAR DataIn;
  208635. ULONG DataTransferLength;
  208636. ULONG TimeOutValue;
  208637. PVOID DataBuffer;
  208638. ULONG SenseInfoOffset;
  208639. UCHAR Cdb[16];
  208640. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  208641. typedef struct
  208642. {
  208643. SCSI_PASS_THROUGH_DIRECT spt;
  208644. ULONG Filler;
  208645. UCHAR ucSenseBuf[32];
  208646. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  208647. typedef struct
  208648. {
  208649. ULONG Length;
  208650. UCHAR PortNumber;
  208651. UCHAR PathId;
  208652. UCHAR TargetId;
  208653. UCHAR Lun;
  208654. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  208655. #define METHOD_BUFFERED 0
  208656. #define METHOD_IN_DIRECT 1
  208657. #define METHOD_OUT_DIRECT 2
  208658. #define METHOD_NEITHER 3
  208659. #define FILE_ANY_ACCESS 0
  208660. #ifndef FILE_READ_ACCESS
  208661. #define FILE_READ_ACCESS (0x0001)
  208662. #endif
  208663. #ifndef FILE_WRITE_ACCESS
  208664. #define FILE_WRITE_ACCESS (0x0002)
  208665. #endif
  208666. #define IOCTL_SCSI_BASE 0x00000004
  208667. #define SCSI_IOCTL_DATA_OUT 0
  208668. #define SCSI_IOCTL_DATA_IN 1
  208669. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  208670. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  208671. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  208672. )
  208673. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  208674. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  208675. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  208676. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  208677. #define SENSE_LEN 14
  208678. #define SRB_DIR_SCSI 0x00
  208679. #define SRB_POSTING 0x01
  208680. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  208681. #define SRB_DIR_IN 0x08
  208682. #define SRB_DIR_OUT 0x10
  208683. #define SRB_EVENT_NOTIFY 0x40
  208684. #define RESIDUAL_COUNT_SUPPORTED 0x02
  208685. #define MAX_SRB_TIMEOUT 1080001u
  208686. #define DEFAULT_SRB_TIMEOUT 1080001u
  208687. #define SC_HA_INQUIRY 0x00
  208688. #define SC_GET_DEV_TYPE 0x01
  208689. #define SC_EXEC_SCSI_CMD 0x02
  208690. #define SC_ABORT_SRB 0x03
  208691. #define SC_RESET_DEV 0x04
  208692. #define SC_SET_HA_PARMS 0x05
  208693. #define SC_GET_DISK_INFO 0x06
  208694. #define SC_RESCAN_SCSI_BUS 0x07
  208695. #define SC_GETSET_TIMEOUTS 0x08
  208696. #define SS_PENDING 0x00
  208697. #define SS_COMP 0x01
  208698. #define SS_ABORTED 0x02
  208699. #define SS_ABORT_FAIL 0x03
  208700. #define SS_ERR 0x04
  208701. #define SS_INVALID_CMD 0x80
  208702. #define SS_INVALID_HA 0x81
  208703. #define SS_NO_DEVICE 0x82
  208704. #define SS_INVALID_SRB 0xE0
  208705. #define SS_OLD_MANAGER 0xE1
  208706. #define SS_BUFFER_ALIGN 0xE1
  208707. #define SS_ILLEGAL_MODE 0xE2
  208708. #define SS_NO_ASPI 0xE3
  208709. #define SS_FAILED_INIT 0xE4
  208710. #define SS_ASPI_IS_BUSY 0xE5
  208711. #define SS_BUFFER_TO_BIG 0xE6
  208712. #define SS_BUFFER_TOO_BIG 0xE6
  208713. #define SS_MISMATCHED_COMPONENTS 0xE7
  208714. #define SS_NO_ADAPTERS 0xE8
  208715. #define SS_INSUFFICIENT_RESOURCES 0xE9
  208716. #define SS_ASPI_IS_SHUTDOWN 0xEA
  208717. #define SS_BAD_INSTALL 0xEB
  208718. #define HASTAT_OK 0x00
  208719. #define HASTAT_SEL_TO 0x11
  208720. #define HASTAT_DO_DU 0x12
  208721. #define HASTAT_BUS_FREE 0x13
  208722. #define HASTAT_PHASE_ERR 0x14
  208723. #define HASTAT_TIMEOUT 0x09
  208724. #define HASTAT_COMMAND_TIMEOUT 0x0B
  208725. #define HASTAT_MESSAGE_REJECT 0x0D
  208726. #define HASTAT_BUS_RESET 0x0E
  208727. #define HASTAT_PARITY_ERROR 0x0F
  208728. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  208729. #define PACKED
  208730. #pragma pack(1)
  208731. typedef struct
  208732. {
  208733. BYTE SRB_Cmd;
  208734. BYTE SRB_Status;
  208735. BYTE SRB_HaID;
  208736. BYTE SRB_Flags;
  208737. DWORD SRB_Hdr_Rsvd;
  208738. BYTE HA_Count;
  208739. BYTE HA_SCSI_ID;
  208740. BYTE HA_ManagerId[16];
  208741. BYTE HA_Identifier[16];
  208742. BYTE HA_Unique[16];
  208743. WORD HA_Rsvd1;
  208744. BYTE pad[20];
  208745. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  208746. typedef struct
  208747. {
  208748. BYTE SRB_Cmd;
  208749. BYTE SRB_Status;
  208750. BYTE SRB_HaID;
  208751. BYTE SRB_Flags;
  208752. DWORD SRB_Hdr_Rsvd;
  208753. BYTE SRB_Target;
  208754. BYTE SRB_Lun;
  208755. BYTE SRB_DeviceType;
  208756. BYTE SRB_Rsvd1;
  208757. BYTE pad[68];
  208758. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  208759. typedef struct
  208760. {
  208761. BYTE SRB_Cmd;
  208762. BYTE SRB_Status;
  208763. BYTE SRB_HaID;
  208764. BYTE SRB_Flags;
  208765. DWORD SRB_Hdr_Rsvd;
  208766. BYTE SRB_Target;
  208767. BYTE SRB_Lun;
  208768. WORD SRB_Rsvd1;
  208769. DWORD SRB_BufLen;
  208770. BYTE FAR *SRB_BufPointer;
  208771. BYTE SRB_SenseLen;
  208772. BYTE SRB_CDBLen;
  208773. BYTE SRB_HaStat;
  208774. BYTE SRB_TargStat;
  208775. VOID FAR *SRB_PostProc;
  208776. BYTE SRB_Rsvd2[20];
  208777. BYTE CDBByte[16];
  208778. BYTE SenseArea[SENSE_LEN+2];
  208779. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  208780. typedef struct
  208781. {
  208782. BYTE SRB_Cmd;
  208783. BYTE SRB_Status;
  208784. BYTE SRB_HaId;
  208785. BYTE SRB_Flags;
  208786. DWORD SRB_Hdr_Rsvd;
  208787. } PACKED SRB, *PSRB, FAR *LPSRB;
  208788. #pragma pack()
  208789. struct CDDeviceInfo
  208790. {
  208791. char vendor[9];
  208792. char productId[17];
  208793. char rev[5];
  208794. char vendorSpec[21];
  208795. BYTE ha;
  208796. BYTE tgt;
  208797. BYTE lun;
  208798. char scsiDriveLetter; // will be 0 if not using scsi
  208799. };
  208800. class CDReadBuffer
  208801. {
  208802. public:
  208803. int startFrame;
  208804. int numFrames;
  208805. int dataStartOffset;
  208806. int dataLength;
  208807. int bufferSize;
  208808. HeapBlock<BYTE> buffer;
  208809. int index;
  208810. bool wantsIndex;
  208811. CDReadBuffer (const int numberOfFrames)
  208812. : startFrame (0),
  208813. numFrames (0),
  208814. dataStartOffset (0),
  208815. dataLength (0),
  208816. bufferSize (2352 * numberOfFrames),
  208817. buffer (bufferSize),
  208818. index (0),
  208819. wantsIndex (false)
  208820. {
  208821. }
  208822. bool isZero() const throw()
  208823. {
  208824. BYTE* p = buffer + dataStartOffset;
  208825. for (int i = dataLength; --i >= 0;)
  208826. if (*p++ != 0)
  208827. return false;
  208828. return true;
  208829. }
  208830. };
  208831. class CDDeviceHandle;
  208832. class CDController
  208833. {
  208834. public:
  208835. CDController();
  208836. virtual ~CDController();
  208837. virtual bool read (CDReadBuffer* t) = 0;
  208838. virtual void shutDown();
  208839. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  208840. int getLastIndex();
  208841. public:
  208842. bool initialised;
  208843. CDDeviceHandle* deviceInfo;
  208844. int framesToCheck, framesOverlap;
  208845. void prepare (SRB_ExecSCSICmd& s);
  208846. void perform (SRB_ExecSCSICmd& s);
  208847. void setPaused (bool paused);
  208848. };
  208849. #pragma pack(1)
  208850. struct TOCTRACK
  208851. {
  208852. BYTE rsvd;
  208853. BYTE ADR;
  208854. BYTE trackNumber;
  208855. BYTE rsvd2;
  208856. BYTE addr[4];
  208857. };
  208858. struct TOC
  208859. {
  208860. WORD tocLen;
  208861. BYTE firstTrack;
  208862. BYTE lastTrack;
  208863. TOCTRACK tracks[100];
  208864. };
  208865. #pragma pack()
  208866. enum
  208867. {
  208868. READTYPE_ANY = 0,
  208869. READTYPE_ATAPI1 = 1,
  208870. READTYPE_ATAPI2 = 2,
  208871. READTYPE_READ6 = 3,
  208872. READTYPE_READ10 = 4,
  208873. READTYPE_READ_D8 = 5,
  208874. READTYPE_READ_D4 = 6,
  208875. READTYPE_READ_D4_1 = 7,
  208876. READTYPE_READ10_2 = 8
  208877. };
  208878. class CDDeviceHandle
  208879. {
  208880. public:
  208881. CDDeviceHandle (const CDDeviceInfo* const device)
  208882. : scsiHandle (0),
  208883. readType (READTYPE_ANY),
  208884. controller (0)
  208885. {
  208886. memcpy (&info, device, sizeof (info));
  208887. }
  208888. ~CDDeviceHandle()
  208889. {
  208890. if (controller != 0)
  208891. {
  208892. controller->shutDown();
  208893. controller = 0;
  208894. }
  208895. if (scsiHandle != 0)
  208896. CloseHandle (scsiHandle);
  208897. }
  208898. bool readTOC (TOC* lpToc, bool useMSF);
  208899. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  208900. void openDrawer (bool shouldBeOpen);
  208901. CDDeviceInfo info;
  208902. HANDLE scsiHandle;
  208903. BYTE readType;
  208904. private:
  208905. ScopedPointer<CDController> controller;
  208906. bool testController (const int readType,
  208907. CDController* const newController,
  208908. CDReadBuffer* const bufferToUse);
  208909. };
  208910. DWORD (*fGetASPI32SupportInfo)(void);
  208911. DWORD (*fSendASPI32Command)(LPSRB);
  208912. static HINSTANCE winAspiLib = 0;
  208913. static bool usingScsi = false;
  208914. static bool initialised = false;
  208915. static bool InitialiseCDRipper()
  208916. {
  208917. if (! initialised)
  208918. {
  208919. initialised = true;
  208920. OSVERSIONINFO info;
  208921. info.dwOSVersionInfoSize = sizeof (info);
  208922. GetVersionEx (&info);
  208923. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  208924. if (! usingScsi)
  208925. {
  208926. fGetASPI32SupportInfo = 0;
  208927. fSendASPI32Command = 0;
  208928. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  208929. if (winAspiLib != 0)
  208930. {
  208931. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  208932. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  208933. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  208934. return false;
  208935. }
  208936. else
  208937. {
  208938. usingScsi = true;
  208939. }
  208940. }
  208941. }
  208942. return true;
  208943. }
  208944. static void DeinitialiseCDRipper()
  208945. {
  208946. if (winAspiLib != 0)
  208947. {
  208948. fGetASPI32SupportInfo = 0;
  208949. fSendASPI32Command = 0;
  208950. FreeLibrary (winAspiLib);
  208951. winAspiLib = 0;
  208952. }
  208953. initialised = false;
  208954. }
  208955. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  208956. {
  208957. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  208958. OSVERSIONINFO info;
  208959. info.dwOSVersionInfoSize = sizeof (info);
  208960. GetVersionEx (&info);
  208961. DWORD flags = GENERIC_READ;
  208962. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  208963. flags = GENERIC_READ | GENERIC_WRITE;
  208964. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  208965. if (h == INVALID_HANDLE_VALUE)
  208966. {
  208967. flags ^= GENERIC_WRITE;
  208968. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  208969. }
  208970. return h;
  208971. }
  208972. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  208973. const char driveLetter,
  208974. HANDLE& deviceHandle,
  208975. const bool retryOnFailure = true)
  208976. {
  208977. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  208978. zerostruct (s);
  208979. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  208980. s.spt.CdbLength = srb->SRB_CDBLen;
  208981. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  208982. ? SCSI_IOCTL_DATA_IN
  208983. : ((srb->SRB_Flags & SRB_DIR_OUT)
  208984. ? SCSI_IOCTL_DATA_OUT
  208985. : SCSI_IOCTL_DATA_UNSPECIFIED));
  208986. s.spt.DataTransferLength = srb->SRB_BufLen;
  208987. s.spt.TimeOutValue = 5;
  208988. s.spt.DataBuffer = srb->SRB_BufPointer;
  208989. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  208990. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  208991. srb->SRB_Status = SS_ERR;
  208992. srb->SRB_TargStat = 0x0004;
  208993. DWORD bytesReturned = 0;
  208994. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  208995. &s, sizeof (s),
  208996. &s, sizeof (s),
  208997. &bytesReturned, 0) != 0)
  208998. {
  208999. srb->SRB_Status = SS_COMP;
  209000. }
  209001. else if (retryOnFailure)
  209002. {
  209003. const DWORD error = GetLastError();
  209004. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  209005. {
  209006. if (error != ERROR_INVALID_HANDLE)
  209007. CloseHandle (deviceHandle);
  209008. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  209009. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  209010. }
  209011. }
  209012. return srb->SRB_Status;
  209013. }
  209014. // Controller types..
  209015. class ControllerType1 : public CDController
  209016. {
  209017. public:
  209018. ControllerType1() {}
  209019. ~ControllerType1() {}
  209020. bool read (CDReadBuffer* rb)
  209021. {
  209022. if (rb->numFrames * 2352 > rb->bufferSize)
  209023. return false;
  209024. SRB_ExecSCSICmd s;
  209025. prepare (s);
  209026. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209027. s.SRB_BufLen = rb->bufferSize;
  209028. s.SRB_BufPointer = rb->buffer;
  209029. s.SRB_CDBLen = 12;
  209030. s.CDBByte[0] = 0xBE;
  209031. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209032. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209033. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209034. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209035. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  209036. perform (s);
  209037. if (s.SRB_Status != SS_COMP)
  209038. return false;
  209039. rb->dataLength = rb->numFrames * 2352;
  209040. rb->dataStartOffset = 0;
  209041. return true;
  209042. }
  209043. };
  209044. class ControllerType2 : public CDController
  209045. {
  209046. public:
  209047. ControllerType2() {}
  209048. ~ControllerType2() {}
  209049. void shutDown()
  209050. {
  209051. if (initialised)
  209052. {
  209053. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  209054. SRB_ExecSCSICmd s;
  209055. prepare (s);
  209056. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  209057. s.SRB_BufLen = 0x0C;
  209058. s.SRB_BufPointer = bufPointer;
  209059. s.SRB_CDBLen = 6;
  209060. s.CDBByte[0] = 0x15;
  209061. s.CDBByte[4] = 0x0C;
  209062. perform (s);
  209063. }
  209064. }
  209065. bool init()
  209066. {
  209067. SRB_ExecSCSICmd s;
  209068. s.SRB_Status = SS_ERR;
  209069. if (deviceInfo->readType == READTYPE_READ10_2)
  209070. {
  209071. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  209072. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  209073. for (int i = 0; i < 2; ++i)
  209074. {
  209075. prepare (s);
  209076. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209077. s.SRB_BufLen = 0x14;
  209078. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  209079. s.SRB_CDBLen = 6;
  209080. s.CDBByte[0] = 0x15;
  209081. s.CDBByte[1] = 0x10;
  209082. s.CDBByte[4] = 0x14;
  209083. perform (s);
  209084. if (s.SRB_Status != SS_COMP)
  209085. return false;
  209086. }
  209087. }
  209088. else
  209089. {
  209090. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  209091. prepare (s);
  209092. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209093. s.SRB_BufLen = 0x0C;
  209094. s.SRB_BufPointer = bufPointer;
  209095. s.SRB_CDBLen = 6;
  209096. s.CDBByte[0] = 0x15;
  209097. s.CDBByte[4] = 0x0C;
  209098. perform (s);
  209099. }
  209100. return s.SRB_Status == SS_COMP;
  209101. }
  209102. bool read (CDReadBuffer* rb)
  209103. {
  209104. if (rb->numFrames * 2352 > rb->bufferSize)
  209105. return false;
  209106. if (!initialised)
  209107. {
  209108. initialised = init();
  209109. if (!initialised)
  209110. return false;
  209111. }
  209112. SRB_ExecSCSICmd s;
  209113. prepare (s);
  209114. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209115. s.SRB_BufLen = rb->bufferSize;
  209116. s.SRB_BufPointer = rb->buffer;
  209117. s.SRB_CDBLen = 10;
  209118. s.CDBByte[0] = 0x28;
  209119. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209120. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209121. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209122. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209123. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209124. perform (s);
  209125. if (s.SRB_Status != SS_COMP)
  209126. return false;
  209127. rb->dataLength = rb->numFrames * 2352;
  209128. rb->dataStartOffset = 0;
  209129. return true;
  209130. }
  209131. };
  209132. class ControllerType3 : public CDController
  209133. {
  209134. public:
  209135. ControllerType3() {}
  209136. ~ControllerType3() {}
  209137. bool read (CDReadBuffer* rb)
  209138. {
  209139. if (rb->numFrames * 2352 > rb->bufferSize)
  209140. return false;
  209141. if (!initialised)
  209142. {
  209143. setPaused (false);
  209144. initialised = true;
  209145. }
  209146. SRB_ExecSCSICmd s;
  209147. prepare (s);
  209148. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209149. s.SRB_BufLen = rb->numFrames * 2352;
  209150. s.SRB_BufPointer = rb->buffer;
  209151. s.SRB_CDBLen = 12;
  209152. s.CDBByte[0] = 0xD8;
  209153. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209154. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209155. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209156. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  209157. perform (s);
  209158. if (s.SRB_Status != SS_COMP)
  209159. return false;
  209160. rb->dataLength = rb->numFrames * 2352;
  209161. rb->dataStartOffset = 0;
  209162. return true;
  209163. }
  209164. };
  209165. class ControllerType4 : public CDController
  209166. {
  209167. public:
  209168. ControllerType4() {}
  209169. ~ControllerType4() {}
  209170. bool selectD4Mode()
  209171. {
  209172. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  209173. SRB_ExecSCSICmd s;
  209174. prepare (s);
  209175. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209176. s.SRB_CDBLen = 6;
  209177. s.SRB_BufLen = 12;
  209178. s.SRB_BufPointer = bufPointer;
  209179. s.CDBByte[0] = 0x15;
  209180. s.CDBByte[1] = 0x10;
  209181. s.CDBByte[4] = 0x08;
  209182. perform (s);
  209183. return s.SRB_Status == SS_COMP;
  209184. }
  209185. bool read (CDReadBuffer* rb)
  209186. {
  209187. if (rb->numFrames * 2352 > rb->bufferSize)
  209188. return false;
  209189. if (!initialised)
  209190. {
  209191. setPaused (true);
  209192. if (deviceInfo->readType == READTYPE_READ_D4_1)
  209193. selectD4Mode();
  209194. initialised = true;
  209195. }
  209196. SRB_ExecSCSICmd s;
  209197. prepare (s);
  209198. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209199. s.SRB_BufLen = rb->bufferSize;
  209200. s.SRB_BufPointer = rb->buffer;
  209201. s.SRB_CDBLen = 10;
  209202. s.CDBByte[0] = 0xD4;
  209203. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209204. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209205. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209206. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209207. perform (s);
  209208. if (s.SRB_Status != SS_COMP)
  209209. return false;
  209210. rb->dataLength = rb->numFrames * 2352;
  209211. rb->dataStartOffset = 0;
  209212. return true;
  209213. }
  209214. };
  209215. CDController::CDController() : initialised (false)
  209216. {
  209217. }
  209218. CDController::~CDController()
  209219. {
  209220. }
  209221. void CDController::prepare (SRB_ExecSCSICmd& s)
  209222. {
  209223. zerostruct (s);
  209224. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209225. s.SRB_HaID = deviceInfo->info.ha;
  209226. s.SRB_Target = deviceInfo->info.tgt;
  209227. s.SRB_Lun = deviceInfo->info.lun;
  209228. s.SRB_SenseLen = SENSE_LEN;
  209229. }
  209230. void CDController::perform (SRB_ExecSCSICmd& s)
  209231. {
  209232. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209233. s.SRB_PostProc = event;
  209234. ResetEvent (event);
  209235. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  209236. deviceInfo->info.scsiDriveLetter,
  209237. deviceInfo->scsiHandle)
  209238. : fSendASPI32Command ((LPSRB)&s);
  209239. if (status == SS_PENDING)
  209240. WaitForSingleObject (event, 4000);
  209241. CloseHandle (event);
  209242. }
  209243. void CDController::setPaused (bool paused)
  209244. {
  209245. SRB_ExecSCSICmd s;
  209246. prepare (s);
  209247. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209248. s.SRB_CDBLen = 10;
  209249. s.CDBByte[0] = 0x4B;
  209250. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  209251. perform (s);
  209252. }
  209253. void CDController::shutDown()
  209254. {
  209255. }
  209256. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  209257. {
  209258. if (overlapBuffer != 0)
  209259. {
  209260. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  209261. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  209262. if (doJitter
  209263. && overlapBuffer->startFrame > 0
  209264. && overlapBuffer->numFrames > 0
  209265. && overlapBuffer->dataLength > 0)
  209266. {
  209267. const int numFrames = rb->numFrames;
  209268. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  209269. {
  209270. rb->startFrame -= framesOverlap;
  209271. if (framesToCheck < framesOverlap
  209272. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  209273. rb->numFrames += framesOverlap;
  209274. }
  209275. else
  209276. {
  209277. overlapBuffer->dataLength = 0;
  209278. overlapBuffer->startFrame = 0;
  209279. overlapBuffer->numFrames = 0;
  209280. }
  209281. }
  209282. if (! read (rb))
  209283. return false;
  209284. if (doJitter)
  209285. {
  209286. const int checkLen = framesToCheck * 2352;
  209287. const int maxToCheck = rb->dataLength - checkLen;
  209288. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  209289. return true;
  209290. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  209291. bool found = false;
  209292. for (int i = 0; i < maxToCheck; ++i)
  209293. {
  209294. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  209295. {
  209296. i += checkLen;
  209297. rb->dataStartOffset = i;
  209298. rb->dataLength -= i;
  209299. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  209300. found = true;
  209301. break;
  209302. }
  209303. }
  209304. rb->numFrames = rb->dataLength / 2352;
  209305. rb->dataLength = 2352 * rb->numFrames;
  209306. if (!found)
  209307. return false;
  209308. }
  209309. if (canDoJitter)
  209310. {
  209311. memcpy (overlapBuffer->buffer,
  209312. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  209313. 2352 * framesToCheck);
  209314. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  209315. overlapBuffer->numFrames = framesToCheck;
  209316. overlapBuffer->dataLength = 2352 * framesToCheck;
  209317. overlapBuffer->dataStartOffset = 0;
  209318. }
  209319. else
  209320. {
  209321. overlapBuffer->startFrame = 0;
  209322. overlapBuffer->numFrames = 0;
  209323. overlapBuffer->dataLength = 0;
  209324. }
  209325. return true;
  209326. }
  209327. else
  209328. {
  209329. return read (rb);
  209330. }
  209331. }
  209332. int CDController::getLastIndex()
  209333. {
  209334. char qdata[100];
  209335. SRB_ExecSCSICmd s;
  209336. prepare (s);
  209337. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209338. s.SRB_BufLen = sizeof (qdata);
  209339. s.SRB_BufPointer = (BYTE*)qdata;
  209340. s.SRB_CDBLen = 12;
  209341. s.CDBByte[0] = 0x42;
  209342. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209343. s.CDBByte[2] = 64;
  209344. s.CDBByte[3] = 1; // get current position
  209345. s.CDBByte[7] = 0;
  209346. s.CDBByte[8] = (BYTE)sizeof (qdata);
  209347. perform (s);
  209348. if (s.SRB_Status == SS_COMP)
  209349. return qdata[7];
  209350. return 0;
  209351. }
  209352. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  209353. {
  209354. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209355. SRB_ExecSCSICmd s;
  209356. zerostruct (s);
  209357. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209358. s.SRB_HaID = info.ha;
  209359. s.SRB_Target = info.tgt;
  209360. s.SRB_Lun = info.lun;
  209361. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209362. s.SRB_BufLen = 0x324;
  209363. s.SRB_BufPointer = (BYTE*)lpToc;
  209364. s.SRB_SenseLen = 0x0E;
  209365. s.SRB_CDBLen = 0x0A;
  209366. s.SRB_PostProc = event;
  209367. s.CDBByte[0] = 0x43;
  209368. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  209369. s.CDBByte[7] = 0x03;
  209370. s.CDBByte[8] = 0x24;
  209371. ResetEvent (event);
  209372. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209373. : fSendASPI32Command ((LPSRB)&s);
  209374. if (status == SS_PENDING)
  209375. WaitForSingleObject (event, 4000);
  209376. CloseHandle (event);
  209377. return (s.SRB_Status == SS_COMP);
  209378. }
  209379. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  209380. CDReadBuffer* const overlapBuffer)
  209381. {
  209382. if (controller == 0)
  209383. {
  209384. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  209385. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  209386. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  209387. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  209388. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  209389. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  209390. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  209391. }
  209392. buffer->index = 0;
  209393. if ((controller != 0)
  209394. && controller->readAudio (buffer, overlapBuffer))
  209395. {
  209396. if (buffer->wantsIndex)
  209397. buffer->index = controller->getLastIndex();
  209398. return true;
  209399. }
  209400. return false;
  209401. }
  209402. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  209403. {
  209404. if (shouldBeOpen)
  209405. {
  209406. if (controller != 0)
  209407. {
  209408. controller->shutDown();
  209409. controller = 0;
  209410. }
  209411. if (scsiHandle != 0)
  209412. {
  209413. CloseHandle (scsiHandle);
  209414. scsiHandle = 0;
  209415. }
  209416. }
  209417. SRB_ExecSCSICmd s;
  209418. zerostruct (s);
  209419. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209420. s.SRB_HaID = info.ha;
  209421. s.SRB_Target = info.tgt;
  209422. s.SRB_Lun = info.lun;
  209423. s.SRB_SenseLen = SENSE_LEN;
  209424. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209425. s.SRB_BufLen = 0;
  209426. s.SRB_BufPointer = 0;
  209427. s.SRB_CDBLen = 12;
  209428. s.CDBByte[0] = 0x1b;
  209429. s.CDBByte[1] = (BYTE)(info.lun << 5);
  209430. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  209431. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209432. s.SRB_PostProc = event;
  209433. ResetEvent (event);
  209434. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209435. : fSendASPI32Command ((LPSRB)&s);
  209436. if (status == SS_PENDING)
  209437. WaitForSingleObject (event, 4000);
  209438. CloseHandle (event);
  209439. }
  209440. bool CDDeviceHandle::testController (const int type,
  209441. CDController* const newController,
  209442. CDReadBuffer* const rb)
  209443. {
  209444. controller = newController;
  209445. readType = (BYTE)type;
  209446. controller->deviceInfo = this;
  209447. controller->framesToCheck = 1;
  209448. controller->framesOverlap = 3;
  209449. bool passed = false;
  209450. memset (rb->buffer, 0xcd, rb->bufferSize);
  209451. if (controller->read (rb))
  209452. {
  209453. passed = true;
  209454. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  209455. int wrong = 0;
  209456. for (int i = rb->dataLength / 4; --i >= 0;)
  209457. {
  209458. if (*p++ == (int) 0xcdcdcdcd)
  209459. {
  209460. if (++wrong == 4)
  209461. {
  209462. passed = false;
  209463. break;
  209464. }
  209465. }
  209466. else
  209467. {
  209468. wrong = 0;
  209469. }
  209470. }
  209471. }
  209472. if (! passed)
  209473. {
  209474. controller->shutDown();
  209475. controller = 0;
  209476. }
  209477. return passed;
  209478. }
  209479. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  209480. {
  209481. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209482. const int bufSize = 128;
  209483. BYTE buffer[bufSize];
  209484. zeromem (buffer, bufSize);
  209485. SRB_ExecSCSICmd s;
  209486. zerostruct (s);
  209487. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209488. s.SRB_HaID = ha;
  209489. s.SRB_Target = tgt;
  209490. s.SRB_Lun = lun;
  209491. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209492. s.SRB_BufLen = bufSize;
  209493. s.SRB_BufPointer = buffer;
  209494. s.SRB_SenseLen = SENSE_LEN;
  209495. s.SRB_CDBLen = 6;
  209496. s.SRB_PostProc = event;
  209497. s.CDBByte[0] = SCSI_INQUIRY;
  209498. s.CDBByte[4] = 100;
  209499. ResetEvent (event);
  209500. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  209501. WaitForSingleObject (event, 4000);
  209502. CloseHandle (event);
  209503. if (s.SRB_Status == SS_COMP)
  209504. {
  209505. memcpy (dev->vendor, &buffer[8], 8);
  209506. memcpy (dev->productId, &buffer[16], 16);
  209507. memcpy (dev->rev, &buffer[32], 4);
  209508. memcpy (dev->vendorSpec, &buffer[36], 20);
  209509. }
  209510. }
  209511. static int FindCDDevices (CDDeviceInfo* const list,
  209512. int maxItems)
  209513. {
  209514. int count = 0;
  209515. if (usingScsi)
  209516. {
  209517. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  209518. {
  209519. TCHAR drivePath[8];
  209520. drivePath[0] = driveLetter;
  209521. drivePath[1] = ':';
  209522. drivePath[2] = '\\';
  209523. drivePath[3] = 0;
  209524. if (GetDriveType (drivePath) == DRIVE_CDROM)
  209525. {
  209526. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  209527. if (h != INVALID_HANDLE_VALUE)
  209528. {
  209529. BYTE buffer[100], passThroughStruct[1024];
  209530. zeromem (buffer, sizeof (buffer));
  209531. zeromem (passThroughStruct, sizeof (passThroughStruct));
  209532. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  209533. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  209534. p->spt.CdbLength = 6;
  209535. p->spt.SenseInfoLength = 24;
  209536. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  209537. p->spt.DataTransferLength = 100;
  209538. p->spt.TimeOutValue = 2;
  209539. p->spt.DataBuffer = buffer;
  209540. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209541. p->spt.Cdb[0] = 0x12;
  209542. p->spt.Cdb[4] = 100;
  209543. DWORD bytesReturned = 0;
  209544. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209545. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  209546. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  209547. &bytesReturned, 0) != 0)
  209548. {
  209549. zeromem (&list[count], sizeof (CDDeviceInfo));
  209550. list[count].scsiDriveLetter = driveLetter;
  209551. memcpy (list[count].vendor, &buffer[8], 8);
  209552. memcpy (list[count].productId, &buffer[16], 16);
  209553. memcpy (list[count].rev, &buffer[32], 4);
  209554. memcpy (list[count].vendorSpec, &buffer[36], 20);
  209555. zeromem (passThroughStruct, sizeof (passThroughStruct));
  209556. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  209557. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  209558. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  209559. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  209560. &bytesReturned, 0) != 0)
  209561. {
  209562. list[count].ha = scsiAddr->PortNumber;
  209563. list[count].tgt = scsiAddr->TargetId;
  209564. list[count].lun = scsiAddr->Lun;
  209565. ++count;
  209566. }
  209567. }
  209568. CloseHandle (h);
  209569. }
  209570. }
  209571. }
  209572. }
  209573. else
  209574. {
  209575. const DWORD d = fGetASPI32SupportInfo();
  209576. BYTE status = HIBYTE (LOWORD (d));
  209577. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  209578. return 0;
  209579. const int numAdapters = LOBYTE (LOWORD (d));
  209580. for (BYTE ha = 0; ha < numAdapters; ++ha)
  209581. {
  209582. SRB_HAInquiry s;
  209583. zerostruct (s);
  209584. s.SRB_Cmd = SC_HA_INQUIRY;
  209585. s.SRB_HaID = ha;
  209586. fSendASPI32Command ((LPSRB)&s);
  209587. if (s.SRB_Status == SS_COMP)
  209588. {
  209589. maxItems = (int)s.HA_Unique[3];
  209590. if (maxItems == 0)
  209591. maxItems = 8;
  209592. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  209593. {
  209594. for (BYTE lun = 0; lun < 8; ++lun)
  209595. {
  209596. SRB_GDEVBlock sb;
  209597. zerostruct (sb);
  209598. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  209599. sb.SRB_HaID = ha;
  209600. sb.SRB_Target = tgt;
  209601. sb.SRB_Lun = lun;
  209602. fSendASPI32Command ((LPSRB) &sb);
  209603. if (sb.SRB_Status == SS_COMP
  209604. && sb.SRB_DeviceType == DTYPE_CROM)
  209605. {
  209606. zeromem (&list[count], sizeof (CDDeviceInfo));
  209607. list[count].ha = ha;
  209608. list[count].tgt = tgt;
  209609. list[count].lun = lun;
  209610. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  209611. ++count;
  209612. }
  209613. }
  209614. }
  209615. }
  209616. }
  209617. }
  209618. return count;
  209619. }
  209620. static int ripperUsers = 0;
  209621. static bool initialisedOk = false;
  209622. class DeinitialiseTimer : private Timer,
  209623. private DeletedAtShutdown
  209624. {
  209625. DeinitialiseTimer (const DeinitialiseTimer&);
  209626. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  209627. public:
  209628. DeinitialiseTimer()
  209629. {
  209630. startTimer (4000);
  209631. }
  209632. ~DeinitialiseTimer()
  209633. {
  209634. if (--ripperUsers == 0)
  209635. DeinitialiseCDRipper();
  209636. }
  209637. void timerCallback()
  209638. {
  209639. delete this;
  209640. }
  209641. juce_UseDebuggingNewOperator
  209642. };
  209643. static void incUserCount()
  209644. {
  209645. if (ripperUsers++ == 0)
  209646. initialisedOk = InitialiseCDRipper();
  209647. }
  209648. static void decUserCount()
  209649. {
  209650. new DeinitialiseTimer();
  209651. }
  209652. struct CDDeviceWrapper
  209653. {
  209654. ScopedPointer<CDDeviceHandle> cdH;
  209655. ScopedPointer<CDReadBuffer> overlapBuffer;
  209656. bool jitter;
  209657. };
  209658. static int getAddressOf (const TOCTRACK* const t)
  209659. {
  209660. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  209661. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  209662. }
  209663. static int getMSFAddressOf (const TOCTRACK* const t)
  209664. {
  209665. return 60 * t->addr[1] + t->addr[2];
  209666. }
  209667. static const int samplesPerFrame = 44100 / 75;
  209668. static const int bytesPerFrame = samplesPerFrame * 4;
  209669. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  209670. {
  209671. SRB_GDEVBlock s;
  209672. zerostruct (s);
  209673. s.SRB_Cmd = SC_GET_DEV_TYPE;
  209674. s.SRB_HaID = device->ha;
  209675. s.SRB_Target = device->tgt;
  209676. s.SRB_Lun = device->lun;
  209677. if (usingScsi)
  209678. {
  209679. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  209680. if (h != INVALID_HANDLE_VALUE)
  209681. {
  209682. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  209683. cdh->scsiHandle = h;
  209684. return cdh;
  209685. }
  209686. }
  209687. else
  209688. {
  209689. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  209690. && s.SRB_DeviceType == DTYPE_CROM)
  209691. {
  209692. return new CDDeviceHandle (device);
  209693. }
  209694. }
  209695. return 0;
  209696. }
  209697. }
  209698. const StringArray AudioCDReader::getAvailableCDNames()
  209699. {
  209700. using namespace CDReaderHelpers;
  209701. StringArray results;
  209702. incUserCount();
  209703. if (initialisedOk)
  209704. {
  209705. CDDeviceInfo list[8];
  209706. const int num = FindCDDevices (list, 8);
  209707. decUserCount();
  209708. for (int i = 0; i < num; ++i)
  209709. {
  209710. String s;
  209711. if (list[i].scsiDriveLetter > 0)
  209712. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  209713. s << String (list[i].vendor).trim()
  209714. << ' ' << String (list[i].productId).trim()
  209715. << ' ' << String (list[i].rev).trim();
  209716. results.add (s);
  209717. }
  209718. }
  209719. return results;
  209720. }
  209721. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  209722. {
  209723. using namespace CDReaderHelpers;
  209724. incUserCount();
  209725. if (initialisedOk)
  209726. {
  209727. CDDeviceInfo list[8];
  209728. const int num = FindCDDevices (list, 8);
  209729. if (((unsigned int) deviceIndex) < (unsigned int) num)
  209730. {
  209731. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  209732. if (handle != 0)
  209733. {
  209734. CDDeviceWrapper* const d = new CDDeviceWrapper();
  209735. d->cdH = handle;
  209736. d->overlapBuffer = new CDReadBuffer(3);
  209737. return new AudioCDReader (d);
  209738. }
  209739. }
  209740. }
  209741. decUserCount();
  209742. return 0;
  209743. }
  209744. AudioCDReader::AudioCDReader (void* handle_)
  209745. : AudioFormatReader (0, "CD Audio"),
  209746. handle (handle_),
  209747. indexingEnabled (false),
  209748. lastIndex (0),
  209749. firstFrameInBuffer (0),
  209750. samplesInBuffer (0)
  209751. {
  209752. using namespace CDReaderHelpers;
  209753. jassert (handle_ != 0);
  209754. refreshTrackLengths();
  209755. sampleRate = 44100.0;
  209756. bitsPerSample = 16;
  209757. lengthInSamples = getPositionOfTrackStart (numTracks);
  209758. numChannels = 2;
  209759. usesFloatingPointData = false;
  209760. buffer.setSize (4 * bytesPerFrame, true);
  209761. }
  209762. AudioCDReader::~AudioCDReader()
  209763. {
  209764. using namespace CDReaderHelpers;
  209765. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  209766. delete device;
  209767. decUserCount();
  209768. }
  209769. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  209770. int64 startSampleInFile, int numSamples)
  209771. {
  209772. using namespace CDReaderHelpers;
  209773. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  209774. bool ok = true;
  209775. while (numSamples > 0)
  209776. {
  209777. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  209778. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  209779. if (startSampleInFile >= bufferStartSample
  209780. && startSampleInFile < bufferEndSample)
  209781. {
  209782. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  209783. int* const l = destSamples[0] + startOffsetInDestBuffer;
  209784. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  209785. const short* src = (const short*) buffer.getData();
  209786. src += 2 * (startSampleInFile - bufferStartSample);
  209787. for (int i = 0; i < toDo; ++i)
  209788. {
  209789. l[i] = src [i << 1] << 16;
  209790. if (r != 0)
  209791. r[i] = src [(i << 1) + 1] << 16;
  209792. }
  209793. startOffsetInDestBuffer += toDo;
  209794. startSampleInFile += toDo;
  209795. numSamples -= toDo;
  209796. }
  209797. else
  209798. {
  209799. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  209800. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  209801. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  209802. {
  209803. device->overlapBuffer->dataLength = 0;
  209804. device->overlapBuffer->startFrame = 0;
  209805. device->overlapBuffer->numFrames = 0;
  209806. device->jitter = false;
  209807. }
  209808. firstFrameInBuffer = frameNeeded;
  209809. lastIndex = 0;
  209810. CDReadBuffer readBuffer (framesInBuffer + 4);
  209811. readBuffer.wantsIndex = indexingEnabled;
  209812. int i;
  209813. for (i = 5; --i >= 0;)
  209814. {
  209815. readBuffer.startFrame = frameNeeded;
  209816. readBuffer.numFrames = framesInBuffer;
  209817. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  209818. break;
  209819. else
  209820. device->overlapBuffer->dataLength = 0;
  209821. }
  209822. if (i >= 0)
  209823. {
  209824. memcpy ((char*) buffer.getData(),
  209825. readBuffer.buffer + readBuffer.dataStartOffset,
  209826. readBuffer.dataLength);
  209827. samplesInBuffer = readBuffer.dataLength >> 2;
  209828. lastIndex = readBuffer.index;
  209829. }
  209830. else
  209831. {
  209832. int* l = destSamples[0] + startOffsetInDestBuffer;
  209833. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  209834. while (--numSamples >= 0)
  209835. {
  209836. *l++ = 0;
  209837. if (r != 0)
  209838. *r++ = 0;
  209839. }
  209840. // sometimes the read fails for just the very last couple of blocks, so
  209841. // we'll ignore and errors in the last half-second of the disk..
  209842. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  209843. break;
  209844. }
  209845. }
  209846. }
  209847. return ok;
  209848. }
  209849. bool AudioCDReader::isCDStillPresent() const
  209850. {
  209851. using namespace CDReaderHelpers;
  209852. TOC toc;
  209853. zerostruct (toc);
  209854. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  209855. }
  209856. int AudioCDReader::getNumTracks() const
  209857. {
  209858. return numTracks;
  209859. }
  209860. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  209861. {
  209862. using namespace CDReaderHelpers;
  209863. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  209864. : 0;
  209865. }
  209866. void AudioCDReader::refreshTrackLengths()
  209867. {
  209868. using namespace CDReaderHelpers;
  209869. zeromem (trackStarts, sizeof (trackStarts));
  209870. zeromem (audioTracks, sizeof (audioTracks));
  209871. TOC toc;
  209872. zerostruct (toc);
  209873. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  209874. {
  209875. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  209876. for (int i = 0; i <= numTracks; ++i)
  209877. {
  209878. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  209879. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  209880. }
  209881. }
  209882. else
  209883. {
  209884. numTracks = 0;
  209885. }
  209886. }
  209887. bool AudioCDReader::isTrackAudio (int trackNum) const
  209888. {
  209889. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  209890. : false;
  209891. }
  209892. void AudioCDReader::enableIndexScanning (bool b)
  209893. {
  209894. indexingEnabled = b;
  209895. }
  209896. int AudioCDReader::getLastIndex() const
  209897. {
  209898. return lastIndex;
  209899. }
  209900. const int framesPerIndexRead = 4;
  209901. int AudioCDReader::getIndexAt (int samplePos)
  209902. {
  209903. using namespace CDReaderHelpers;
  209904. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  209905. const int frameNeeded = samplePos / samplesPerFrame;
  209906. device->overlapBuffer->dataLength = 0;
  209907. device->overlapBuffer->startFrame = 0;
  209908. device->overlapBuffer->numFrames = 0;
  209909. device->jitter = false;
  209910. firstFrameInBuffer = 0;
  209911. lastIndex = 0;
  209912. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  209913. readBuffer.wantsIndex = true;
  209914. int i;
  209915. for (i = 5; --i >= 0;)
  209916. {
  209917. readBuffer.startFrame = frameNeeded;
  209918. readBuffer.numFrames = framesPerIndexRead;
  209919. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  209920. break;
  209921. }
  209922. if (i >= 0)
  209923. return readBuffer.index;
  209924. return -1;
  209925. }
  209926. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  209927. {
  209928. using namespace CDReaderHelpers;
  209929. Array <int> indexes;
  209930. const int trackStart = getPositionOfTrackStart (trackNumber);
  209931. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  209932. bool needToScan = true;
  209933. if (trackEnd - trackStart > 20 * 44100)
  209934. {
  209935. // check the end of the track for indexes before scanning the whole thing
  209936. needToScan = false;
  209937. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  209938. bool seenAnIndex = false;
  209939. while (pos <= trackEnd - samplesPerFrame)
  209940. {
  209941. const int index = getIndexAt (pos);
  209942. if (index == 0)
  209943. {
  209944. // lead-out, so skip back a bit if we've not found any indexes yet..
  209945. if (seenAnIndex)
  209946. break;
  209947. pos -= 44100 * 5;
  209948. if (pos < trackStart)
  209949. break;
  209950. }
  209951. else
  209952. {
  209953. if (index > 0)
  209954. seenAnIndex = true;
  209955. if (index > 1)
  209956. {
  209957. needToScan = true;
  209958. break;
  209959. }
  209960. pos += samplesPerFrame * framesPerIndexRead;
  209961. }
  209962. }
  209963. }
  209964. if (needToScan)
  209965. {
  209966. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  209967. int pos = trackStart;
  209968. int last = -1;
  209969. while (pos < trackEnd - samplesPerFrame * 10)
  209970. {
  209971. const int frameNeeded = pos / samplesPerFrame;
  209972. device->overlapBuffer->dataLength = 0;
  209973. device->overlapBuffer->startFrame = 0;
  209974. device->overlapBuffer->numFrames = 0;
  209975. device->jitter = false;
  209976. firstFrameInBuffer = 0;
  209977. CDReadBuffer readBuffer (4);
  209978. readBuffer.wantsIndex = true;
  209979. int i;
  209980. for (i = 5; --i >= 0;)
  209981. {
  209982. readBuffer.startFrame = frameNeeded;
  209983. readBuffer.numFrames = framesPerIndexRead;
  209984. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  209985. break;
  209986. }
  209987. if (i < 0)
  209988. break;
  209989. if (readBuffer.index > last && readBuffer.index > 1)
  209990. {
  209991. last = readBuffer.index;
  209992. indexes.add (pos);
  209993. }
  209994. pos += samplesPerFrame * framesPerIndexRead;
  209995. }
  209996. indexes.removeValue (trackStart);
  209997. }
  209998. return indexes;
  209999. }
  210000. int AudioCDReader::getCDDBId()
  210001. {
  210002. using namespace CDReaderHelpers;
  210003. refreshTrackLengths();
  210004. if (numTracks > 0)
  210005. {
  210006. TOC toc;
  210007. zerostruct (toc);
  210008. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  210009. {
  210010. int n = 0;
  210011. for (int i = numTracks; --i >= 0;)
  210012. {
  210013. int j = getMSFAddressOf (&toc.tracks[i]);
  210014. while (j > 0)
  210015. {
  210016. n += (j % 10);
  210017. j /= 10;
  210018. }
  210019. }
  210020. if (n != 0)
  210021. {
  210022. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  210023. - getMSFAddressOf (&toc.tracks[0]);
  210024. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  210025. }
  210026. }
  210027. }
  210028. return 0;
  210029. }
  210030. void AudioCDReader::ejectDisk()
  210031. {
  210032. using namespace CDReaderHelpers;
  210033. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  210034. }
  210035. #endif
  210036. #if JUCE_USE_CDBURNER
  210037. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  210038. {
  210039. CoInitialize (0);
  210040. IDiscMaster* dm;
  210041. IDiscRecorder* result = 0;
  210042. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  210043. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  210044. IID_IDiscMaster,
  210045. (void**) &dm)))
  210046. {
  210047. if (SUCCEEDED (dm->Open()))
  210048. {
  210049. IEnumDiscRecorders* drEnum = 0;
  210050. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  210051. {
  210052. IDiscRecorder* dr = 0;
  210053. DWORD dummy;
  210054. int index = 0;
  210055. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  210056. {
  210057. if (indexToOpen == index)
  210058. {
  210059. result = dr;
  210060. break;
  210061. }
  210062. else if (list != 0)
  210063. {
  210064. BSTR path;
  210065. if (SUCCEEDED (dr->GetPath (&path)))
  210066. list->add ((const WCHAR*) path);
  210067. }
  210068. ++index;
  210069. dr->Release();
  210070. }
  210071. drEnum->Release();
  210072. }
  210073. if (master == 0)
  210074. dm->Close();
  210075. }
  210076. if (master != 0)
  210077. *master = dm;
  210078. else
  210079. dm->Release();
  210080. }
  210081. return result;
  210082. }
  210083. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  210084. public Timer
  210085. {
  210086. public:
  210087. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  210088. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  210089. listener (0), progress (0), shouldCancel (false)
  210090. {
  210091. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  210092. jassert (SUCCEEDED (hr));
  210093. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  210094. //jassert (SUCCEEDED (hr));
  210095. lastState = getDiskState();
  210096. startTimer (2000);
  210097. }
  210098. ~Pimpl() {}
  210099. void releaseObjects()
  210100. {
  210101. discRecorder->Close();
  210102. if (redbook != 0)
  210103. redbook->Release();
  210104. discRecorder->Release();
  210105. discMaster->Release();
  210106. Release();
  210107. }
  210108. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  210109. {
  210110. if (listener != 0 && ! shouldCancel)
  210111. shouldCancel = listener->audioCDBurnProgress (progress);
  210112. *pbCancel = shouldCancel;
  210113. return S_OK;
  210114. }
  210115. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  210116. {
  210117. progress = nCompleted / (float) nTotal;
  210118. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  210119. return E_NOTIMPL;
  210120. }
  210121. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  210122. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  210123. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  210124. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210125. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210126. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210127. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210128. class ScopedDiscOpener
  210129. {
  210130. public:
  210131. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  210132. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  210133. private:
  210134. Pimpl& pimpl;
  210135. ScopedDiscOpener (const ScopedDiscOpener&);
  210136. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  210137. };
  210138. DiskState getDiskState()
  210139. {
  210140. const ScopedDiscOpener opener (*this);
  210141. long type, flags;
  210142. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  210143. if (FAILED (hr))
  210144. return unknown;
  210145. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  210146. return writableDiskPresent;
  210147. if (type == 0)
  210148. return noDisc;
  210149. else
  210150. return readOnlyDiskPresent;
  210151. }
  210152. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  210153. {
  210154. ComSmartPtr<IPropertyStorage> prop;
  210155. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210156. return defaultReturn;
  210157. PROPSPEC iPropSpec;
  210158. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210159. iPropSpec.lpwstr = name;
  210160. PROPVARIANT iPropVariant;
  210161. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  210162. ? defaultReturn : (int) iPropVariant.lVal;
  210163. }
  210164. bool setIntProperty (const LPOLESTR name, const int value) const
  210165. {
  210166. ComSmartPtr<IPropertyStorage> prop;
  210167. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210168. return false;
  210169. PROPSPEC iPropSpec;
  210170. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210171. iPropSpec.lpwstr = name;
  210172. PROPVARIANT iPropVariant;
  210173. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  210174. return false;
  210175. iPropVariant.lVal = (long) value;
  210176. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  210177. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  210178. }
  210179. void timerCallback()
  210180. {
  210181. const DiskState state = getDiskState();
  210182. if (state != lastState)
  210183. {
  210184. lastState = state;
  210185. owner.sendChangeMessage (&owner);
  210186. }
  210187. }
  210188. AudioCDBurner& owner;
  210189. DiskState lastState;
  210190. IDiscMaster* discMaster;
  210191. IDiscRecorder* discRecorder;
  210192. IRedbookDiscMaster* redbook;
  210193. AudioCDBurner::BurnProgressListener* listener;
  210194. float progress;
  210195. bool shouldCancel;
  210196. };
  210197. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  210198. {
  210199. IDiscMaster* discMaster = 0;
  210200. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  210201. if (discRecorder != 0)
  210202. pimpl = new Pimpl (*this, discMaster, discRecorder);
  210203. }
  210204. AudioCDBurner::~AudioCDBurner()
  210205. {
  210206. if (pimpl != 0)
  210207. pimpl.release()->releaseObjects();
  210208. }
  210209. const StringArray AudioCDBurner::findAvailableDevices()
  210210. {
  210211. StringArray devs;
  210212. enumCDBurners (&devs, -1, 0);
  210213. return devs;
  210214. }
  210215. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  210216. {
  210217. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  210218. if (b->pimpl == 0)
  210219. b = 0;
  210220. return b.release();
  210221. }
  210222. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  210223. {
  210224. return pimpl->getDiskState();
  210225. }
  210226. bool AudioCDBurner::isDiskPresent() const
  210227. {
  210228. return getDiskState() == writableDiskPresent;
  210229. }
  210230. bool AudioCDBurner::openTray()
  210231. {
  210232. const Pimpl::ScopedDiscOpener opener (*pimpl);
  210233. return SUCCEEDED (pimpl->discRecorder->Eject());
  210234. }
  210235. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  210236. {
  210237. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  210238. DiskState oldState = getDiskState();
  210239. DiskState newState = oldState;
  210240. while (newState == oldState && Time::currentTimeMillis() < timeout)
  210241. {
  210242. newState = getDiskState();
  210243. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  210244. }
  210245. return newState;
  210246. }
  210247. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  210248. {
  210249. Array<int> results;
  210250. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  210251. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  210252. for (int i = 0; i < numElementsInArray (speeds); ++i)
  210253. if (speeds[i] <= maxSpeed)
  210254. results.add (speeds[i]);
  210255. results.addIfNotAlreadyThere (maxSpeed);
  210256. return results;
  210257. }
  210258. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  210259. {
  210260. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  210261. return false;
  210262. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  210263. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  210264. }
  210265. int AudioCDBurner::getNumAvailableAudioBlocks() const
  210266. {
  210267. long blocksFree = 0;
  210268. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  210269. return blocksFree;
  210270. }
  210271. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  210272. bool performFakeBurnForTesting, int writeSpeed)
  210273. {
  210274. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  210275. pimpl->listener = listener;
  210276. pimpl->progress = 0;
  210277. pimpl->shouldCancel = false;
  210278. UINT_PTR cookie;
  210279. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  210280. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  210281. ejectDiscAfterwards);
  210282. String error;
  210283. if (hr != S_OK)
  210284. {
  210285. const char* e = "Couldn't open or write to the CD device";
  210286. if (hr == IMAPI_E_USERABORT)
  210287. e = "User cancelled the write operation";
  210288. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  210289. e = "No Disk present";
  210290. error = e;
  210291. }
  210292. pimpl->discMaster->ProgressUnadvise (cookie);
  210293. pimpl->listener = 0;
  210294. return error;
  210295. }
  210296. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  210297. {
  210298. if (audioSource == 0)
  210299. return false;
  210300. ScopedPointer<AudioSource> source (audioSource);
  210301. long bytesPerBlock;
  210302. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  210303. const int samplesPerBlock = bytesPerBlock / 4;
  210304. bool ok = true;
  210305. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  210306. HeapBlock <byte> buffer (bytesPerBlock);
  210307. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  210308. int samplesDone = 0;
  210309. source->prepareToPlay (samplesPerBlock, 44100.0);
  210310. while (ok)
  210311. {
  210312. {
  210313. AudioSourceChannelInfo info;
  210314. info.buffer = &sourceBuffer;
  210315. info.numSamples = samplesPerBlock;
  210316. info.startSample = 0;
  210317. sourceBuffer.clear();
  210318. source->getNextAudioBlock (info);
  210319. }
  210320. zeromem (buffer, bytesPerBlock);
  210321. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  210322. buffer, samplesPerBlock, 4);
  210323. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  210324. buffer + 2, samplesPerBlock, 4);
  210325. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  210326. if (FAILED (hr))
  210327. ok = false;
  210328. samplesDone += samplesPerBlock;
  210329. if (samplesDone >= numSamples)
  210330. break;
  210331. }
  210332. hr = pimpl->redbook->CloseAudioTrack();
  210333. return ok && hr == S_OK;
  210334. }
  210335. #endif
  210336. #endif
  210337. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  210338. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  210339. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210340. // compiled on its own).
  210341. #if JUCE_INCLUDED_FILE
  210342. using ::free;
  210343. namespace MidiConstants
  210344. {
  210345. static const int midiBufferSize = 1024 * 10;
  210346. static const int numInHeaders = 32;
  210347. static const int inBufferSize = 256;
  210348. }
  210349. class MidiInThread : public Thread
  210350. {
  210351. public:
  210352. MidiInThread (MidiInput* const input_,
  210353. MidiInputCallback* const callback_)
  210354. : Thread ("Juce Midi"),
  210355. hIn (0),
  210356. input (input_),
  210357. callback (callback_),
  210358. isStarted (false),
  210359. startTime (0),
  210360. pendingLength(0)
  210361. {
  210362. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210363. {
  210364. zeromem (&hdr[i], sizeof (MIDIHDR));
  210365. hdr[i].lpData = inData[i];
  210366. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  210367. }
  210368. };
  210369. ~MidiInThread()
  210370. {
  210371. stop();
  210372. if (hIn != 0)
  210373. {
  210374. int count = 5;
  210375. while (--count >= 0)
  210376. {
  210377. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  210378. break;
  210379. Sleep (20);
  210380. }
  210381. }
  210382. }
  210383. void handle (const uint32 message, const uint32 timeStamp)
  210384. {
  210385. const int byte = message & 0xff;
  210386. if (byte < 0x80)
  210387. return;
  210388. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  210389. const double time = timeStampToTime (timeStamp);
  210390. {
  210391. const ScopedLock sl (lock);
  210392. if (pendingLength < MidiConstants::midiBufferSize - 12)
  210393. {
  210394. char* const p = pending + pendingLength;
  210395. *(double*) p = time;
  210396. *(uint32*) (p + 8) = numBytes;
  210397. *(uint32*) (p + 12) = message;
  210398. pendingLength += 12 + numBytes;
  210399. }
  210400. else
  210401. {
  210402. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210403. }
  210404. }
  210405. notify();
  210406. }
  210407. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  210408. {
  210409. const int num = hdr->dwBytesRecorded;
  210410. if (num > 0)
  210411. {
  210412. const double time = timeStampToTime (timeStamp);
  210413. {
  210414. const ScopedLock sl (lock);
  210415. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  210416. {
  210417. char* const p = pending + pendingLength;
  210418. *(double*) p = time;
  210419. *(uint32*) (p + 8) = num;
  210420. memcpy (p + 12, hdr->lpData, num);
  210421. pendingLength += 12 + num;
  210422. }
  210423. else
  210424. {
  210425. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210426. }
  210427. }
  210428. notify();
  210429. }
  210430. }
  210431. void writeBlock (const int i)
  210432. {
  210433. hdr[i].dwBytesRecorded = 0;
  210434. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  210435. jassert (res == MMSYSERR_NOERROR);
  210436. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  210437. jassert (res == MMSYSERR_NOERROR);
  210438. }
  210439. void run()
  210440. {
  210441. MemoryBlock pendingCopy (64);
  210442. while (! threadShouldExit())
  210443. {
  210444. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  210445. {
  210446. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  210447. {
  210448. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  210449. (void) res;
  210450. jassert (res == MMSYSERR_NOERROR);
  210451. writeBlock (i);
  210452. }
  210453. }
  210454. int len;
  210455. {
  210456. const ScopedLock sl (lock);
  210457. len = pendingLength;
  210458. if (len > 0)
  210459. {
  210460. pendingCopy.ensureSize (len);
  210461. pendingCopy.copyFrom (pending, 0, len);
  210462. pendingLength = 0;
  210463. }
  210464. }
  210465. //xxx needs to figure out if blocks are broken up or not
  210466. if (len == 0)
  210467. {
  210468. wait (500);
  210469. }
  210470. else
  210471. {
  210472. const char* p = (const char*) pendingCopy.getData();
  210473. while (len > 0)
  210474. {
  210475. const double time = *(const double*) p;
  210476. const int messageLen = *(const int*) (p + 8);
  210477. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  210478. callback->handleIncomingMidiMessage (input, message);
  210479. p += 12 + messageLen;
  210480. len -= 12 + messageLen;
  210481. }
  210482. }
  210483. }
  210484. }
  210485. void start()
  210486. {
  210487. jassert (hIn != 0);
  210488. if (hIn != 0 && ! isStarted)
  210489. {
  210490. stop();
  210491. activeMidiThreads.addIfNotAlreadyThere (this);
  210492. int i;
  210493. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  210494. writeBlock (i);
  210495. startTime = Time::getMillisecondCounter();
  210496. MMRESULT res = midiInStart (hIn);
  210497. jassert (res == MMSYSERR_NOERROR);
  210498. if (res == MMSYSERR_NOERROR)
  210499. {
  210500. isStarted = true;
  210501. pendingLength = 0;
  210502. startThread (6);
  210503. }
  210504. }
  210505. }
  210506. void stop()
  210507. {
  210508. if (isStarted)
  210509. {
  210510. stopThread (5000);
  210511. midiInReset (hIn);
  210512. midiInStop (hIn);
  210513. activeMidiThreads.removeValue (this);
  210514. { const ScopedLock sl (lock); }
  210515. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210516. {
  210517. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  210518. {
  210519. int c = 10;
  210520. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  210521. Sleep (20);
  210522. jassert (c >= 0);
  210523. }
  210524. }
  210525. isStarted = false;
  210526. pendingLength = 0;
  210527. }
  210528. }
  210529. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  210530. {
  210531. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  210532. if (thread != 0 && activeMidiThreads.contains (thread))
  210533. {
  210534. if (uMsg == MIM_DATA)
  210535. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  210536. else if (uMsg == MIM_LONGDATA)
  210537. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  210538. }
  210539. }
  210540. juce_UseDebuggingNewOperator
  210541. HMIDIIN hIn;
  210542. private:
  210543. static Array <void*, CriticalSection> activeMidiThreads;
  210544. MidiInput* input;
  210545. MidiInputCallback* callback;
  210546. bool isStarted;
  210547. uint32 startTime;
  210548. CriticalSection lock;
  210549. MIDIHDR hdr [MidiConstants::numInHeaders];
  210550. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  210551. int pendingLength;
  210552. char pending [MidiConstants::midiBufferSize];
  210553. double timeStampToTime (uint32 timeStamp)
  210554. {
  210555. timeStamp += startTime;
  210556. const uint32 now = Time::getMillisecondCounter();
  210557. if (timeStamp > now)
  210558. {
  210559. if (timeStamp > now + 2)
  210560. --startTime;
  210561. timeStamp = now;
  210562. }
  210563. return 0.001 * timeStamp;
  210564. }
  210565. MidiInThread (const MidiInThread&);
  210566. MidiInThread& operator= (const MidiInThread&);
  210567. };
  210568. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  210569. const StringArray MidiInput::getDevices()
  210570. {
  210571. StringArray s;
  210572. const int num = midiInGetNumDevs();
  210573. for (int i = 0; i < num; ++i)
  210574. {
  210575. MIDIINCAPS mc;
  210576. zerostruct (mc);
  210577. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210578. s.add (String (mc.szPname, sizeof (mc.szPname)));
  210579. }
  210580. return s;
  210581. }
  210582. int MidiInput::getDefaultDeviceIndex()
  210583. {
  210584. return 0;
  210585. }
  210586. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  210587. {
  210588. if (callback == 0)
  210589. return 0;
  210590. UINT deviceId = MIDI_MAPPER;
  210591. int n = 0;
  210592. String name;
  210593. const int num = midiInGetNumDevs();
  210594. for (int i = 0; i < num; ++i)
  210595. {
  210596. MIDIINCAPS mc;
  210597. zerostruct (mc);
  210598. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210599. {
  210600. if (index == n)
  210601. {
  210602. deviceId = i;
  210603. name = String (mc.szPname, sizeof (mc.szPname));
  210604. break;
  210605. }
  210606. ++n;
  210607. }
  210608. }
  210609. ScopedPointer <MidiInput> in (new MidiInput (name));
  210610. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  210611. HMIDIIN h;
  210612. HRESULT err = midiInOpen (&h, deviceId,
  210613. (DWORD_PTR) &MidiInThread::midiInCallback,
  210614. (DWORD_PTR) (MidiInThread*) thread,
  210615. CALLBACK_FUNCTION);
  210616. if (err == MMSYSERR_NOERROR)
  210617. {
  210618. thread->hIn = h;
  210619. in->internal = thread.release();
  210620. return in.release();
  210621. }
  210622. return 0;
  210623. }
  210624. MidiInput::MidiInput (const String& name_)
  210625. : name (name_),
  210626. internal (0)
  210627. {
  210628. }
  210629. MidiInput::~MidiInput()
  210630. {
  210631. delete static_cast <MidiInThread*> (internal);
  210632. }
  210633. void MidiInput::start()
  210634. {
  210635. static_cast <MidiInThread*> (internal)->start();
  210636. }
  210637. void MidiInput::stop()
  210638. {
  210639. static_cast <MidiInThread*> (internal)->stop();
  210640. }
  210641. struct MidiOutHandle
  210642. {
  210643. int refCount;
  210644. UINT deviceId;
  210645. HMIDIOUT handle;
  210646. static Array<MidiOutHandle*> activeHandles;
  210647. juce_UseDebuggingNewOperator
  210648. };
  210649. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  210650. const StringArray MidiOutput::getDevices()
  210651. {
  210652. StringArray s;
  210653. const int num = midiOutGetNumDevs();
  210654. for (int i = 0; i < num; ++i)
  210655. {
  210656. MIDIOUTCAPS mc;
  210657. zerostruct (mc);
  210658. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210659. s.add (String (mc.szPname, sizeof (mc.szPname)));
  210660. }
  210661. return s;
  210662. }
  210663. int MidiOutput::getDefaultDeviceIndex()
  210664. {
  210665. const int num = midiOutGetNumDevs();
  210666. int n = 0;
  210667. for (int i = 0; i < num; ++i)
  210668. {
  210669. MIDIOUTCAPS mc;
  210670. zerostruct (mc);
  210671. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210672. {
  210673. if ((mc.wTechnology & MOD_MAPPER) != 0)
  210674. return n;
  210675. ++n;
  210676. }
  210677. }
  210678. return 0;
  210679. }
  210680. MidiOutput* MidiOutput::openDevice (int index)
  210681. {
  210682. UINT deviceId = MIDI_MAPPER;
  210683. const int num = midiOutGetNumDevs();
  210684. int i, n = 0;
  210685. for (i = 0; i < num; ++i)
  210686. {
  210687. MIDIOUTCAPS mc;
  210688. zerostruct (mc);
  210689. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210690. {
  210691. // use the microsoft sw synth as a default - best not to allow deviceId
  210692. // to be MIDI_MAPPER, or else device sharing breaks
  210693. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  210694. deviceId = i;
  210695. if (index == n)
  210696. {
  210697. deviceId = i;
  210698. break;
  210699. }
  210700. ++n;
  210701. }
  210702. }
  210703. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  210704. {
  210705. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  210706. if (han != 0 && han->deviceId == deviceId)
  210707. {
  210708. han->refCount++;
  210709. MidiOutput* const out = new MidiOutput();
  210710. out->internal = han;
  210711. return out;
  210712. }
  210713. }
  210714. for (i = 4; --i >= 0;)
  210715. {
  210716. HMIDIOUT h = 0;
  210717. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  210718. if (res == MMSYSERR_NOERROR)
  210719. {
  210720. MidiOutHandle* const han = new MidiOutHandle();
  210721. han->deviceId = deviceId;
  210722. han->refCount = 1;
  210723. han->handle = h;
  210724. MidiOutHandle::activeHandles.add (han);
  210725. MidiOutput* const out = new MidiOutput();
  210726. out->internal = han;
  210727. return out;
  210728. }
  210729. else if (res == MMSYSERR_ALLOCATED)
  210730. {
  210731. Sleep (100);
  210732. }
  210733. else
  210734. {
  210735. break;
  210736. }
  210737. }
  210738. return 0;
  210739. }
  210740. MidiOutput::~MidiOutput()
  210741. {
  210742. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  210743. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  210744. {
  210745. midiOutClose (h->handle);
  210746. MidiOutHandle::activeHandles.removeValue (h);
  210747. delete h;
  210748. }
  210749. }
  210750. void MidiOutput::reset()
  210751. {
  210752. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  210753. midiOutReset (h->handle);
  210754. }
  210755. bool MidiOutput::getVolume (float& leftVol,
  210756. float& rightVol)
  210757. {
  210758. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  210759. DWORD n;
  210760. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  210761. {
  210762. const unsigned short* const nn = (const unsigned short*) &n;
  210763. rightVol = nn[0] / (float) 0xffff;
  210764. leftVol = nn[1] / (float) 0xffff;
  210765. return true;
  210766. }
  210767. else
  210768. {
  210769. rightVol = leftVol = 1.0f;
  210770. return false;
  210771. }
  210772. }
  210773. void MidiOutput::setVolume (float leftVol,
  210774. float rightVol)
  210775. {
  210776. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  210777. DWORD n;
  210778. unsigned short* const nn = (unsigned short*) &n;
  210779. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  210780. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  210781. midiOutSetVolume (handle->handle, n);
  210782. }
  210783. void MidiOutput::sendMessageNow (const MidiMessage& message)
  210784. {
  210785. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  210786. if (message.getRawDataSize() > 3
  210787. || message.isSysEx())
  210788. {
  210789. MIDIHDR h;
  210790. zerostruct (h);
  210791. h.lpData = (char*) message.getRawData();
  210792. h.dwBufferLength = message.getRawDataSize();
  210793. h.dwBytesRecorded = message.getRawDataSize();
  210794. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  210795. {
  210796. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  210797. if (res == MMSYSERR_NOERROR)
  210798. {
  210799. while ((h.dwFlags & MHDR_DONE) == 0)
  210800. Sleep (1);
  210801. int count = 500; // 1 sec timeout
  210802. while (--count >= 0)
  210803. {
  210804. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  210805. if (res == MIDIERR_STILLPLAYING)
  210806. Sleep (2);
  210807. else
  210808. break;
  210809. }
  210810. }
  210811. }
  210812. }
  210813. else
  210814. {
  210815. midiOutShortMsg (handle->handle,
  210816. *(unsigned int*) message.getRawData());
  210817. }
  210818. }
  210819. #endif
  210820. /*** End of inlined file: juce_win32_Midi.cpp ***/
  210821. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  210822. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210823. // compiled on its own).
  210824. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  210825. #undef WINDOWS
  210826. // #define ASIO_DEBUGGING
  210827. #ifdef ASIO_DEBUGGING
  210828. #define log(a) { Logger::writeToLog (a); DBG (a) }
  210829. #else
  210830. #define log(a) {}
  210831. #endif
  210832. #ifdef ASIO_DEBUGGING
  210833. static void logError (const String& context, long error)
  210834. {
  210835. String err ("unknown error");
  210836. if (error == ASE_NotPresent)
  210837. err = "Not Present";
  210838. else if (error == ASE_HWMalfunction)
  210839. err = "Hardware Malfunction";
  210840. else if (error == ASE_InvalidParameter)
  210841. err = "Invalid Parameter";
  210842. else if (error == ASE_InvalidMode)
  210843. err = "Invalid Mode";
  210844. else if (error == ASE_SPNotAdvancing)
  210845. err = "Sample position not advancing";
  210846. else if (error == ASE_NoClock)
  210847. err = "No Clock";
  210848. else if (error == ASE_NoMemory)
  210849. err = "Out of memory";
  210850. log ("!!error: " + context + " - " + err);
  210851. }
  210852. #else
  210853. #define logError(a, b) {}
  210854. #endif
  210855. class ASIOAudioIODevice;
  210856. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  210857. static const int maxASIOChannels = 160;
  210858. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  210859. private Timer
  210860. {
  210861. public:
  210862. Component ourWindow;
  210863. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  210864. const String& optionalDllForDirectLoading_)
  210865. : AudioIODevice (name_, "ASIO"),
  210866. asioObject (0),
  210867. classId (classId_),
  210868. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  210869. currentBitDepth (16),
  210870. currentSampleRate (0),
  210871. isOpen_ (false),
  210872. isStarted (false),
  210873. postOutput (true),
  210874. insideControlPanelModalLoop (false),
  210875. shouldUsePreferredSize (false)
  210876. {
  210877. name = name_;
  210878. ourWindow.addToDesktop (0);
  210879. windowHandle = ourWindow.getWindowHandle();
  210880. jassert (currentASIODev [slotNumber] == 0);
  210881. currentASIODev [slotNumber] = this;
  210882. openDevice();
  210883. }
  210884. ~ASIOAudioIODevice()
  210885. {
  210886. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  210887. if (currentASIODev[i] == this)
  210888. currentASIODev[i] = 0;
  210889. close();
  210890. log ("ASIO - exiting");
  210891. removeCurrentDriver();
  210892. }
  210893. void updateSampleRates()
  210894. {
  210895. // find a list of sample rates..
  210896. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  210897. sampleRates.clear();
  210898. if (asioObject != 0)
  210899. {
  210900. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  210901. {
  210902. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  210903. if (err == 0)
  210904. {
  210905. sampleRates.add ((int) possibleSampleRates[index]);
  210906. log ("rate: " + String ((int) possibleSampleRates[index]));
  210907. }
  210908. else if (err != ASE_NoClock)
  210909. {
  210910. logError ("CanSampleRate", err);
  210911. }
  210912. }
  210913. if (sampleRates.size() == 0)
  210914. {
  210915. double cr = 0;
  210916. const long err = asioObject->getSampleRate (&cr);
  210917. log ("No sample rates supported - current rate: " + String ((int) cr));
  210918. if (err == 0)
  210919. sampleRates.add ((int) cr);
  210920. }
  210921. }
  210922. }
  210923. const StringArray getOutputChannelNames()
  210924. {
  210925. return outputChannelNames;
  210926. }
  210927. const StringArray getInputChannelNames()
  210928. {
  210929. return inputChannelNames;
  210930. }
  210931. int getNumSampleRates()
  210932. {
  210933. return sampleRates.size();
  210934. }
  210935. double getSampleRate (int index)
  210936. {
  210937. return sampleRates [index];
  210938. }
  210939. int getNumBufferSizesAvailable()
  210940. {
  210941. return bufferSizes.size();
  210942. }
  210943. int getBufferSizeSamples (int index)
  210944. {
  210945. return bufferSizes [index];
  210946. }
  210947. int getDefaultBufferSize()
  210948. {
  210949. return preferredSize;
  210950. }
  210951. const String open (const BigInteger& inputChannels,
  210952. const BigInteger& outputChannels,
  210953. double sr,
  210954. int bufferSizeSamples)
  210955. {
  210956. close();
  210957. currentCallback = 0;
  210958. if (bufferSizeSamples <= 0)
  210959. shouldUsePreferredSize = true;
  210960. if (asioObject == 0 || ! isASIOOpen)
  210961. {
  210962. log ("Warning: device not open");
  210963. const String err (openDevice());
  210964. if (asioObject == 0 || ! isASIOOpen)
  210965. return err;
  210966. }
  210967. isStarted = false;
  210968. bufferIndex = -1;
  210969. long err = 0;
  210970. long newPreferredSize = 0;
  210971. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  210972. minSize = 0;
  210973. maxSize = 0;
  210974. newPreferredSize = 0;
  210975. granularity = 0;
  210976. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  210977. {
  210978. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  210979. shouldUsePreferredSize = true;
  210980. preferredSize = newPreferredSize;
  210981. }
  210982. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  210983. // dynamic changes to the buffer size...
  210984. shouldUsePreferredSize = shouldUsePreferredSize
  210985. || getName().containsIgnoreCase ("Digidesign");
  210986. if (shouldUsePreferredSize)
  210987. {
  210988. log ("Using preferred size for buffer..");
  210989. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  210990. {
  210991. bufferSizeSamples = preferredSize;
  210992. }
  210993. else
  210994. {
  210995. bufferSizeSamples = 1024;
  210996. logError ("GetBufferSize1", err);
  210997. }
  210998. shouldUsePreferredSize = false;
  210999. }
  211000. int sampleRate = roundDoubleToInt (sr);
  211001. currentSampleRate = sampleRate;
  211002. currentBlockSizeSamples = bufferSizeSamples;
  211003. currentChansOut.clear();
  211004. currentChansIn.clear();
  211005. zeromem (inBuffers, sizeof (inBuffers));
  211006. zeromem (outBuffers, sizeof (outBuffers));
  211007. updateSampleRates();
  211008. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  211009. sampleRate = sampleRates[0];
  211010. jassert (sampleRate != 0);
  211011. if (sampleRate == 0)
  211012. sampleRate = 44100;
  211013. long numSources = 32;
  211014. ASIOClockSource clocks[32];
  211015. zeromem (clocks, sizeof (clocks));
  211016. asioObject->getClockSources (clocks, &numSources);
  211017. bool isSourceSet = false;
  211018. // careful not to remove this loop because it does more than just logging!
  211019. int i;
  211020. for (i = 0; i < numSources; ++i)
  211021. {
  211022. String s ("clock: ");
  211023. s += clocks[i].name;
  211024. if (clocks[i].isCurrentSource)
  211025. {
  211026. isSourceSet = true;
  211027. s << " (cur)";
  211028. }
  211029. log (s);
  211030. }
  211031. if (numSources > 1 && ! isSourceSet)
  211032. {
  211033. log ("setting clock source");
  211034. asioObject->setClockSource (clocks[0].index);
  211035. Thread::sleep (20);
  211036. }
  211037. else
  211038. {
  211039. if (numSources == 0)
  211040. {
  211041. log ("ASIO - no clock sources!");
  211042. }
  211043. }
  211044. double cr = 0;
  211045. err = asioObject->getSampleRate (&cr);
  211046. if (err == 0)
  211047. {
  211048. currentSampleRate = cr;
  211049. }
  211050. else
  211051. {
  211052. logError ("GetSampleRate", err);
  211053. currentSampleRate = 0;
  211054. }
  211055. error = String::empty;
  211056. needToReset = false;
  211057. isReSync = false;
  211058. err = 0;
  211059. bool buffersCreated = false;
  211060. if (currentSampleRate != sampleRate)
  211061. {
  211062. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  211063. err = asioObject->setSampleRate (sampleRate);
  211064. if (err == ASE_NoClock && numSources > 0)
  211065. {
  211066. log ("trying to set a clock source..");
  211067. Thread::sleep (10);
  211068. err = asioObject->setClockSource (clocks[0].index);
  211069. if (err != 0)
  211070. {
  211071. logError ("SetClock", err);
  211072. }
  211073. Thread::sleep (10);
  211074. err = asioObject->setSampleRate (sampleRate);
  211075. }
  211076. }
  211077. if (err == 0)
  211078. {
  211079. currentSampleRate = sampleRate;
  211080. if (needToReset)
  211081. {
  211082. if (isReSync)
  211083. {
  211084. log ("Resync request");
  211085. }
  211086. log ("! Resetting ASIO after sample rate change");
  211087. removeCurrentDriver();
  211088. loadDriver();
  211089. const String error (initDriver());
  211090. if (error.isNotEmpty())
  211091. {
  211092. log ("ASIOInit: " + error);
  211093. }
  211094. needToReset = false;
  211095. isReSync = false;
  211096. }
  211097. numActiveInputChans = 0;
  211098. numActiveOutputChans = 0;
  211099. ASIOBufferInfo* info = bufferInfos;
  211100. int i;
  211101. for (i = 0; i < totalNumInputChans; ++i)
  211102. {
  211103. if (inputChannels[i])
  211104. {
  211105. currentChansIn.setBit (i);
  211106. info->isInput = 1;
  211107. info->channelNum = i;
  211108. info->buffers[0] = info->buffers[1] = 0;
  211109. ++info;
  211110. ++numActiveInputChans;
  211111. }
  211112. }
  211113. for (i = 0; i < totalNumOutputChans; ++i)
  211114. {
  211115. if (outputChannels[i])
  211116. {
  211117. currentChansOut.setBit (i);
  211118. info->isInput = 0;
  211119. info->channelNum = i;
  211120. info->buffers[0] = info->buffers[1] = 0;
  211121. ++info;
  211122. ++numActiveOutputChans;
  211123. }
  211124. }
  211125. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  211126. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211127. if (currentASIODev[0] == this)
  211128. {
  211129. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211130. callbacks.asioMessage = &asioMessagesCallback0;
  211131. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211132. }
  211133. else if (currentASIODev[1] == this)
  211134. {
  211135. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211136. callbacks.asioMessage = &asioMessagesCallback1;
  211137. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211138. }
  211139. else if (currentASIODev[2] == this)
  211140. {
  211141. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211142. callbacks.asioMessage = &asioMessagesCallback2;
  211143. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211144. }
  211145. else
  211146. {
  211147. jassertfalse;
  211148. }
  211149. log ("disposing buffers");
  211150. err = asioObject->disposeBuffers();
  211151. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  211152. err = asioObject->createBuffers (bufferInfos,
  211153. totalBuffers,
  211154. currentBlockSizeSamples,
  211155. &callbacks);
  211156. if (err != 0)
  211157. {
  211158. currentBlockSizeSamples = preferredSize;
  211159. logError ("create buffers 2", err);
  211160. asioObject->disposeBuffers();
  211161. err = asioObject->createBuffers (bufferInfos,
  211162. totalBuffers,
  211163. currentBlockSizeSamples,
  211164. &callbacks);
  211165. }
  211166. if (err == 0)
  211167. {
  211168. buffersCreated = true;
  211169. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  211170. int n = 0;
  211171. Array <int> types;
  211172. currentBitDepth = 16;
  211173. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  211174. {
  211175. if (inputChannels[i])
  211176. {
  211177. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  211178. ASIOChannelInfo channelInfo;
  211179. zerostruct (channelInfo);
  211180. channelInfo.channel = i;
  211181. channelInfo.isInput = 1;
  211182. asioObject->getChannelInfo (&channelInfo);
  211183. types.addIfNotAlreadyThere (channelInfo.type);
  211184. typeToFormatParameters (channelInfo.type,
  211185. inputChannelBitDepths[n],
  211186. inputChannelBytesPerSample[n],
  211187. inputChannelIsFloat[n],
  211188. inputChannelLittleEndian[n]);
  211189. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  211190. ++n;
  211191. }
  211192. }
  211193. jassert (numActiveInputChans == n);
  211194. n = 0;
  211195. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  211196. {
  211197. if (outputChannels[i])
  211198. {
  211199. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  211200. ASIOChannelInfo channelInfo;
  211201. zerostruct (channelInfo);
  211202. channelInfo.channel = i;
  211203. channelInfo.isInput = 0;
  211204. asioObject->getChannelInfo (&channelInfo);
  211205. types.addIfNotAlreadyThere (channelInfo.type);
  211206. typeToFormatParameters (channelInfo.type,
  211207. outputChannelBitDepths[n],
  211208. outputChannelBytesPerSample[n],
  211209. outputChannelIsFloat[n],
  211210. outputChannelLittleEndian[n]);
  211211. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  211212. ++n;
  211213. }
  211214. }
  211215. jassert (numActiveOutputChans == n);
  211216. for (i = types.size(); --i >= 0;)
  211217. {
  211218. log ("channel format: " + String (types[i]));
  211219. }
  211220. jassert (n <= totalBuffers);
  211221. for (i = 0; i < numActiveOutputChans; ++i)
  211222. {
  211223. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  211224. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  211225. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  211226. {
  211227. log ("!! Null buffers");
  211228. }
  211229. else
  211230. {
  211231. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  211232. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  211233. }
  211234. }
  211235. inputLatency = outputLatency = 0;
  211236. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211237. {
  211238. log ("ASIO - no latencies");
  211239. }
  211240. else
  211241. {
  211242. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  211243. }
  211244. isOpen_ = true;
  211245. log ("starting ASIO");
  211246. calledback = false;
  211247. err = asioObject->start();
  211248. if (err != 0)
  211249. {
  211250. isOpen_ = false;
  211251. log ("ASIO - stop on failure");
  211252. Thread::sleep (10);
  211253. asioObject->stop();
  211254. error = "Can't start device";
  211255. Thread::sleep (10);
  211256. }
  211257. else
  211258. {
  211259. int count = 300;
  211260. while (--count > 0 && ! calledback)
  211261. Thread::sleep (10);
  211262. isStarted = true;
  211263. if (! calledback)
  211264. {
  211265. error = "Device didn't start correctly";
  211266. log ("ASIO didn't callback - stopping..");
  211267. asioObject->stop();
  211268. }
  211269. }
  211270. }
  211271. else
  211272. {
  211273. error = "Can't create i/o buffers";
  211274. }
  211275. }
  211276. else
  211277. {
  211278. error = "Can't set sample rate: ";
  211279. error << sampleRate;
  211280. }
  211281. if (error.isNotEmpty())
  211282. {
  211283. logError (error, err);
  211284. if (asioObject != 0 && buffersCreated)
  211285. asioObject->disposeBuffers();
  211286. Thread::sleep (20);
  211287. isStarted = false;
  211288. isOpen_ = false;
  211289. const String errorCopy (error);
  211290. close(); // (this resets the error string)
  211291. error = errorCopy;
  211292. }
  211293. needToReset = false;
  211294. isReSync = false;
  211295. return error;
  211296. }
  211297. void close()
  211298. {
  211299. error = String::empty;
  211300. stopTimer();
  211301. stop();
  211302. if (isASIOOpen && isOpen_)
  211303. {
  211304. const ScopedLock sl (callbackLock);
  211305. isOpen_ = false;
  211306. isStarted = false;
  211307. needToReset = false;
  211308. isReSync = false;
  211309. log ("ASIO - stopping");
  211310. if (asioObject != 0)
  211311. {
  211312. Thread::sleep (20);
  211313. asioObject->stop();
  211314. Thread::sleep (10);
  211315. asioObject->disposeBuffers();
  211316. }
  211317. Thread::sleep (10);
  211318. }
  211319. }
  211320. bool isOpen()
  211321. {
  211322. return isOpen_ || insideControlPanelModalLoop;
  211323. }
  211324. int getCurrentBufferSizeSamples()
  211325. {
  211326. return currentBlockSizeSamples;
  211327. }
  211328. double getCurrentSampleRate()
  211329. {
  211330. return currentSampleRate;
  211331. }
  211332. const BigInteger getActiveOutputChannels() const
  211333. {
  211334. return currentChansOut;
  211335. }
  211336. const BigInteger getActiveInputChannels() const
  211337. {
  211338. return currentChansIn;
  211339. }
  211340. int getCurrentBitDepth()
  211341. {
  211342. return currentBitDepth;
  211343. }
  211344. int getOutputLatencyInSamples()
  211345. {
  211346. return outputLatency + currentBlockSizeSamples / 4;
  211347. }
  211348. int getInputLatencyInSamples()
  211349. {
  211350. return inputLatency + currentBlockSizeSamples / 4;
  211351. }
  211352. void start (AudioIODeviceCallback* callback)
  211353. {
  211354. if (callback != 0)
  211355. {
  211356. callback->audioDeviceAboutToStart (this);
  211357. const ScopedLock sl (callbackLock);
  211358. currentCallback = callback;
  211359. }
  211360. }
  211361. void stop()
  211362. {
  211363. AudioIODeviceCallback* const lastCallback = currentCallback;
  211364. {
  211365. const ScopedLock sl (callbackLock);
  211366. currentCallback = 0;
  211367. }
  211368. if (lastCallback != 0)
  211369. lastCallback->audioDeviceStopped();
  211370. }
  211371. bool isPlaying()
  211372. {
  211373. return isASIOOpen && (currentCallback != 0);
  211374. }
  211375. const String getLastError()
  211376. {
  211377. return error;
  211378. }
  211379. bool hasControlPanel() const
  211380. {
  211381. return true;
  211382. }
  211383. bool showControlPanel()
  211384. {
  211385. log ("ASIO - showing control panel");
  211386. Component modalWindow (String::empty);
  211387. modalWindow.setOpaque (true);
  211388. modalWindow.addToDesktop (0);
  211389. modalWindow.enterModalState();
  211390. bool done = false;
  211391. JUCE_TRY
  211392. {
  211393. // are there are devices that need to be closed before showing their control panel?
  211394. // close();
  211395. insideControlPanelModalLoop = true;
  211396. const uint32 started = Time::getMillisecondCounter();
  211397. if (asioObject != 0)
  211398. {
  211399. asioObject->controlPanel();
  211400. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  211401. log ("spent: " + String (spent));
  211402. if (spent > 300)
  211403. {
  211404. shouldUsePreferredSize = true;
  211405. done = true;
  211406. }
  211407. }
  211408. }
  211409. JUCE_CATCH_ALL
  211410. insideControlPanelModalLoop = false;
  211411. return done;
  211412. }
  211413. void resetRequest() throw()
  211414. {
  211415. needToReset = true;
  211416. }
  211417. void resyncRequest() throw()
  211418. {
  211419. needToReset = true;
  211420. isReSync = true;
  211421. }
  211422. void timerCallback()
  211423. {
  211424. if (! insideControlPanelModalLoop)
  211425. {
  211426. stopTimer();
  211427. // used to cause a reset
  211428. log ("! ASIO restart request!");
  211429. if (isOpen_)
  211430. {
  211431. AudioIODeviceCallback* const oldCallback = currentCallback;
  211432. close();
  211433. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  211434. currentSampleRate, currentBlockSizeSamples);
  211435. if (oldCallback != 0)
  211436. start (oldCallback);
  211437. }
  211438. }
  211439. else
  211440. {
  211441. startTimer (100);
  211442. }
  211443. }
  211444. juce_UseDebuggingNewOperator
  211445. private:
  211446. IASIO* volatile asioObject;
  211447. ASIOCallbacks callbacks;
  211448. void* windowHandle;
  211449. CLSID classId;
  211450. const String optionalDllForDirectLoading;
  211451. String error;
  211452. long totalNumInputChans, totalNumOutputChans;
  211453. StringArray inputChannelNames, outputChannelNames;
  211454. Array<int> sampleRates, bufferSizes;
  211455. long inputLatency, outputLatency;
  211456. long minSize, maxSize, preferredSize, granularity;
  211457. int volatile currentBlockSizeSamples;
  211458. int volatile currentBitDepth;
  211459. double volatile currentSampleRate;
  211460. BigInteger currentChansOut, currentChansIn;
  211461. AudioIODeviceCallback* volatile currentCallback;
  211462. CriticalSection callbackLock;
  211463. ASIOBufferInfo bufferInfos [maxASIOChannels];
  211464. float* inBuffers [maxASIOChannels];
  211465. float* outBuffers [maxASIOChannels];
  211466. int inputChannelBitDepths [maxASIOChannels];
  211467. int outputChannelBitDepths [maxASIOChannels];
  211468. int inputChannelBytesPerSample [maxASIOChannels];
  211469. int outputChannelBytesPerSample [maxASIOChannels];
  211470. bool inputChannelIsFloat [maxASIOChannels];
  211471. bool outputChannelIsFloat [maxASIOChannels];
  211472. bool inputChannelLittleEndian [maxASIOChannels];
  211473. bool outputChannelLittleEndian [maxASIOChannels];
  211474. WaitableEvent event1;
  211475. HeapBlock <float> tempBuffer;
  211476. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  211477. bool isOpen_, isStarted;
  211478. bool volatile isASIOOpen;
  211479. bool volatile calledback;
  211480. bool volatile littleEndian, postOutput, needToReset, isReSync;
  211481. bool volatile insideControlPanelModalLoop;
  211482. bool volatile shouldUsePreferredSize;
  211483. void removeCurrentDriver()
  211484. {
  211485. if (asioObject != 0)
  211486. {
  211487. asioObject->Release();
  211488. asioObject = 0;
  211489. }
  211490. }
  211491. bool loadDriver()
  211492. {
  211493. removeCurrentDriver();
  211494. JUCE_TRY
  211495. {
  211496. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  211497. classId, (void**) &asioObject) == S_OK)
  211498. {
  211499. return true;
  211500. }
  211501. // If a class isn't registered but we have a path for it, we can fallback to
  211502. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  211503. if (optionalDllForDirectLoading.isNotEmpty())
  211504. {
  211505. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  211506. if (h != 0)
  211507. {
  211508. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  211509. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  211510. if (dllGetClassObject != 0)
  211511. {
  211512. IClassFactory* classFactory = 0;
  211513. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  211514. if (classFactory != 0)
  211515. {
  211516. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  211517. classFactory->Release();
  211518. }
  211519. return asioObject != 0;
  211520. }
  211521. }
  211522. }
  211523. }
  211524. JUCE_CATCH_ALL
  211525. asioObject = 0;
  211526. return false;
  211527. }
  211528. const String initDriver()
  211529. {
  211530. if (asioObject != 0)
  211531. {
  211532. char buffer [256];
  211533. zeromem (buffer, sizeof (buffer));
  211534. if (! asioObject->init (windowHandle))
  211535. {
  211536. asioObject->getErrorMessage (buffer);
  211537. return String (buffer, sizeof (buffer) - 1);
  211538. }
  211539. // just in case any daft drivers expect this to be called..
  211540. asioObject->getDriverName (buffer);
  211541. return String::empty;
  211542. }
  211543. return "No Driver";
  211544. }
  211545. const String openDevice()
  211546. {
  211547. // use this in case the driver starts opening dialog boxes..
  211548. Component modalWindow (String::empty);
  211549. modalWindow.setOpaque (true);
  211550. modalWindow.addToDesktop (0);
  211551. modalWindow.enterModalState();
  211552. // open the device and get its info..
  211553. log ("opening ASIO device: " + getName());
  211554. needToReset = false;
  211555. isReSync = false;
  211556. outputChannelNames.clear();
  211557. inputChannelNames.clear();
  211558. bufferSizes.clear();
  211559. sampleRates.clear();
  211560. isASIOOpen = false;
  211561. isOpen_ = false;
  211562. totalNumInputChans = 0;
  211563. totalNumOutputChans = 0;
  211564. numActiveInputChans = 0;
  211565. numActiveOutputChans = 0;
  211566. currentCallback = 0;
  211567. error = String::empty;
  211568. if (getName().isEmpty())
  211569. return error;
  211570. long err = 0;
  211571. if (loadDriver())
  211572. {
  211573. if ((error = initDriver()).isEmpty())
  211574. {
  211575. numActiveInputChans = 0;
  211576. numActiveOutputChans = 0;
  211577. totalNumInputChans = 0;
  211578. totalNumOutputChans = 0;
  211579. if (asioObject != 0
  211580. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  211581. {
  211582. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  211583. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211584. {
  211585. // find a list of buffer sizes..
  211586. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  211587. if (granularity >= 0)
  211588. {
  211589. granularity = jmax (1, (int) granularity);
  211590. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  211591. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  211592. }
  211593. else if (granularity < 0)
  211594. {
  211595. for (int i = 0; i < 18; ++i)
  211596. {
  211597. const int s = (1 << i);
  211598. if (s >= minSize && s <= maxSize)
  211599. bufferSizes.add (s);
  211600. }
  211601. }
  211602. if (! bufferSizes.contains (preferredSize))
  211603. bufferSizes.insert (0, preferredSize);
  211604. double currentRate = 0;
  211605. asioObject->getSampleRate (&currentRate);
  211606. if (currentRate <= 0.0 || currentRate > 192001.0)
  211607. {
  211608. log ("setting sample rate");
  211609. err = asioObject->setSampleRate (44100.0);
  211610. if (err != 0)
  211611. {
  211612. logError ("setting sample rate", err);
  211613. }
  211614. asioObject->getSampleRate (&currentRate);
  211615. }
  211616. currentSampleRate = currentRate;
  211617. postOutput = (asioObject->outputReady() == 0);
  211618. if (postOutput)
  211619. {
  211620. log ("ASIO outputReady = ok");
  211621. }
  211622. updateSampleRates();
  211623. // ..because cubase does it at this point
  211624. inputLatency = outputLatency = 0;
  211625. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211626. {
  211627. log ("ASIO - no latencies");
  211628. }
  211629. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  211630. // create some dummy buffers now.. because cubase does..
  211631. numActiveInputChans = 0;
  211632. numActiveOutputChans = 0;
  211633. ASIOBufferInfo* info = bufferInfos;
  211634. int i, numChans = 0;
  211635. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  211636. {
  211637. info->isInput = 1;
  211638. info->channelNum = i;
  211639. info->buffers[0] = info->buffers[1] = 0;
  211640. ++info;
  211641. ++numChans;
  211642. }
  211643. const int outputBufferIndex = numChans;
  211644. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  211645. {
  211646. info->isInput = 0;
  211647. info->channelNum = i;
  211648. info->buffers[0] = info->buffers[1] = 0;
  211649. ++info;
  211650. ++numChans;
  211651. }
  211652. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211653. if (currentASIODev[0] == this)
  211654. {
  211655. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211656. callbacks.asioMessage = &asioMessagesCallback0;
  211657. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211658. }
  211659. else if (currentASIODev[1] == this)
  211660. {
  211661. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211662. callbacks.asioMessage = &asioMessagesCallback1;
  211663. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211664. }
  211665. else if (currentASIODev[2] == this)
  211666. {
  211667. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211668. callbacks.asioMessage = &asioMessagesCallback2;
  211669. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211670. }
  211671. else
  211672. {
  211673. jassertfalse;
  211674. }
  211675. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  211676. if (preferredSize > 0)
  211677. {
  211678. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  211679. if (err != 0)
  211680. {
  211681. logError ("dummy buffers", err);
  211682. }
  211683. }
  211684. long newInps = 0, newOuts = 0;
  211685. asioObject->getChannels (&newInps, &newOuts);
  211686. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  211687. {
  211688. totalNumInputChans = newInps;
  211689. totalNumOutputChans = newOuts;
  211690. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  211691. }
  211692. updateSampleRates();
  211693. ASIOChannelInfo channelInfo;
  211694. channelInfo.type = 0;
  211695. for (i = 0; i < totalNumInputChans; ++i)
  211696. {
  211697. zerostruct (channelInfo);
  211698. channelInfo.channel = i;
  211699. channelInfo.isInput = 1;
  211700. asioObject->getChannelInfo (&channelInfo);
  211701. inputChannelNames.add (String (channelInfo.name));
  211702. }
  211703. for (i = 0; i < totalNumOutputChans; ++i)
  211704. {
  211705. zerostruct (channelInfo);
  211706. channelInfo.channel = i;
  211707. channelInfo.isInput = 0;
  211708. asioObject->getChannelInfo (&channelInfo);
  211709. outputChannelNames.add (String (channelInfo.name));
  211710. typeToFormatParameters (channelInfo.type,
  211711. outputChannelBitDepths[i],
  211712. outputChannelBytesPerSample[i],
  211713. outputChannelIsFloat[i],
  211714. outputChannelLittleEndian[i]);
  211715. if (i < 2)
  211716. {
  211717. // clear the channels that are used with the dummy stuff
  211718. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  211719. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  211720. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  211721. }
  211722. }
  211723. outputChannelNames.trim();
  211724. inputChannelNames.trim();
  211725. outputChannelNames.appendNumbersToDuplicates (false, true);
  211726. inputChannelNames.appendNumbersToDuplicates (false, true);
  211727. // start and stop because cubase does it..
  211728. asioObject->getLatencies (&inputLatency, &outputLatency);
  211729. if ((err = asioObject->start()) != 0)
  211730. {
  211731. // ignore an error here, as it might start later after setting other stuff up
  211732. logError ("ASIO start", err);
  211733. }
  211734. Thread::sleep (100);
  211735. asioObject->stop();
  211736. }
  211737. else
  211738. {
  211739. error = "Can't detect buffer sizes";
  211740. }
  211741. }
  211742. else
  211743. {
  211744. error = "Can't detect asio channels";
  211745. }
  211746. }
  211747. }
  211748. else
  211749. {
  211750. error = "No such device";
  211751. }
  211752. if (error.isNotEmpty())
  211753. {
  211754. logError (error, err);
  211755. if (asioObject != 0)
  211756. asioObject->disposeBuffers();
  211757. removeCurrentDriver();
  211758. isASIOOpen = false;
  211759. }
  211760. else
  211761. {
  211762. isASIOOpen = true;
  211763. log ("ASIO device open");
  211764. }
  211765. isOpen_ = false;
  211766. needToReset = false;
  211767. isReSync = false;
  211768. return error;
  211769. }
  211770. void callback (const long index)
  211771. {
  211772. if (isStarted)
  211773. {
  211774. bufferIndex = index;
  211775. processBuffer();
  211776. }
  211777. else
  211778. {
  211779. if (postOutput && (asioObject != 0))
  211780. asioObject->outputReady();
  211781. }
  211782. calledback = true;
  211783. }
  211784. void processBuffer()
  211785. {
  211786. const ASIOBufferInfo* const infos = bufferInfos;
  211787. const int bi = bufferIndex;
  211788. const ScopedLock sl (callbackLock);
  211789. if (needToReset)
  211790. {
  211791. needToReset = false;
  211792. if (isReSync)
  211793. {
  211794. log ("! ASIO resync");
  211795. isReSync = false;
  211796. }
  211797. else
  211798. {
  211799. startTimer (20);
  211800. }
  211801. }
  211802. if (bi >= 0)
  211803. {
  211804. const int samps = currentBlockSizeSamples;
  211805. if (currentCallback != 0)
  211806. {
  211807. int i;
  211808. for (i = 0; i < numActiveInputChans; ++i)
  211809. {
  211810. float* const dst = inBuffers[i];
  211811. jassert (dst != 0);
  211812. const char* const src = (const char*) (infos[i].buffers[bi]);
  211813. if (inputChannelIsFloat[i])
  211814. {
  211815. memcpy (dst, src, samps * sizeof (float));
  211816. }
  211817. else
  211818. {
  211819. jassert (dst == tempBuffer + (samps * i));
  211820. switch (inputChannelBitDepths[i])
  211821. {
  211822. case 16:
  211823. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  211824. samps, inputChannelLittleEndian[i]);
  211825. break;
  211826. case 24:
  211827. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  211828. samps, inputChannelLittleEndian[i]);
  211829. break;
  211830. case 32:
  211831. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  211832. samps, inputChannelLittleEndian[i]);
  211833. break;
  211834. case 64:
  211835. jassertfalse;
  211836. break;
  211837. }
  211838. }
  211839. }
  211840. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  211841. numActiveInputChans,
  211842. outBuffers,
  211843. numActiveOutputChans,
  211844. samps);
  211845. for (i = 0; i < numActiveOutputChans; ++i)
  211846. {
  211847. float* const src = outBuffers[i];
  211848. jassert (src != 0);
  211849. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  211850. if (outputChannelIsFloat[i])
  211851. {
  211852. memcpy (dst, src, samps * sizeof (float));
  211853. }
  211854. else
  211855. {
  211856. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  211857. switch (outputChannelBitDepths[i])
  211858. {
  211859. case 16:
  211860. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  211861. samps, outputChannelLittleEndian[i]);
  211862. break;
  211863. case 24:
  211864. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  211865. samps, outputChannelLittleEndian[i]);
  211866. break;
  211867. case 32:
  211868. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  211869. samps, outputChannelLittleEndian[i]);
  211870. break;
  211871. case 64:
  211872. jassertfalse;
  211873. break;
  211874. }
  211875. }
  211876. }
  211877. }
  211878. else
  211879. {
  211880. for (int i = 0; i < numActiveOutputChans; ++i)
  211881. {
  211882. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  211883. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  211884. }
  211885. }
  211886. }
  211887. if (postOutput)
  211888. asioObject->outputReady();
  211889. }
  211890. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  211891. {
  211892. if (currentASIODev[0] != 0)
  211893. currentASIODev[0]->callback (index);
  211894. return 0;
  211895. }
  211896. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  211897. {
  211898. if (currentASIODev[1] != 0)
  211899. currentASIODev[1]->callback (index);
  211900. return 0;
  211901. }
  211902. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  211903. {
  211904. if (currentASIODev[2] != 0)
  211905. currentASIODev[2]->callback (index);
  211906. return 0;
  211907. }
  211908. static void bufferSwitchCallback0 (long index, long)
  211909. {
  211910. if (currentASIODev[0] != 0)
  211911. currentASIODev[0]->callback (index);
  211912. }
  211913. static void bufferSwitchCallback1 (long index, long)
  211914. {
  211915. if (currentASIODev[1] != 0)
  211916. currentASIODev[1]->callback (index);
  211917. }
  211918. static void bufferSwitchCallback2 (long index, long)
  211919. {
  211920. if (currentASIODev[2] != 0)
  211921. currentASIODev[2]->callback (index);
  211922. }
  211923. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  211924. {
  211925. return asioMessagesCallback (selector, value, 0);
  211926. }
  211927. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  211928. {
  211929. return asioMessagesCallback (selector, value, 1);
  211930. }
  211931. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  211932. {
  211933. return asioMessagesCallback (selector, value, 2);
  211934. }
  211935. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  211936. {
  211937. switch (selector)
  211938. {
  211939. case kAsioSelectorSupported:
  211940. if (value == kAsioResetRequest
  211941. || value == kAsioEngineVersion
  211942. || value == kAsioResyncRequest
  211943. || value == kAsioLatenciesChanged
  211944. || value == kAsioSupportsInputMonitor)
  211945. return 1;
  211946. break;
  211947. case kAsioBufferSizeChange:
  211948. break;
  211949. case kAsioResetRequest:
  211950. if (currentASIODev[deviceIndex] != 0)
  211951. currentASIODev[deviceIndex]->resetRequest();
  211952. return 1;
  211953. case kAsioResyncRequest:
  211954. if (currentASIODev[deviceIndex] != 0)
  211955. currentASIODev[deviceIndex]->resyncRequest();
  211956. return 1;
  211957. case kAsioLatenciesChanged:
  211958. return 1;
  211959. case kAsioEngineVersion:
  211960. return 2;
  211961. case kAsioSupportsTimeInfo:
  211962. case kAsioSupportsTimeCode:
  211963. return 0;
  211964. }
  211965. return 0;
  211966. }
  211967. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  211968. {
  211969. }
  211970. static void convertInt16ToFloat (const char* src,
  211971. float* dest,
  211972. const int srcStrideBytes,
  211973. int numSamples,
  211974. const bool littleEndian) throw()
  211975. {
  211976. const double g = 1.0 / 32768.0;
  211977. if (littleEndian)
  211978. {
  211979. while (--numSamples >= 0)
  211980. {
  211981. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  211982. src += srcStrideBytes;
  211983. }
  211984. }
  211985. else
  211986. {
  211987. while (--numSamples >= 0)
  211988. {
  211989. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  211990. src += srcStrideBytes;
  211991. }
  211992. }
  211993. }
  211994. static void convertFloatToInt16 (const float* src,
  211995. char* dest,
  211996. const int dstStrideBytes,
  211997. int numSamples,
  211998. const bool littleEndian) throw()
  211999. {
  212000. const double maxVal = (double) 0x7fff;
  212001. if (littleEndian)
  212002. {
  212003. while (--numSamples >= 0)
  212004. {
  212005. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212006. dest += dstStrideBytes;
  212007. }
  212008. }
  212009. else
  212010. {
  212011. while (--numSamples >= 0)
  212012. {
  212013. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212014. dest += dstStrideBytes;
  212015. }
  212016. }
  212017. }
  212018. static void convertInt24ToFloat (const char* src,
  212019. float* dest,
  212020. const int srcStrideBytes,
  212021. int numSamples,
  212022. const bool littleEndian) throw()
  212023. {
  212024. const double g = 1.0 / 0x7fffff;
  212025. if (littleEndian)
  212026. {
  212027. while (--numSamples >= 0)
  212028. {
  212029. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  212030. src += srcStrideBytes;
  212031. }
  212032. }
  212033. else
  212034. {
  212035. while (--numSamples >= 0)
  212036. {
  212037. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  212038. src += srcStrideBytes;
  212039. }
  212040. }
  212041. }
  212042. static void convertFloatToInt24 (const float* src,
  212043. char* dest,
  212044. const int dstStrideBytes,
  212045. int numSamples,
  212046. const bool littleEndian) throw()
  212047. {
  212048. const double maxVal = (double) 0x7fffff;
  212049. if (littleEndian)
  212050. {
  212051. while (--numSamples >= 0)
  212052. {
  212053. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212054. dest += dstStrideBytes;
  212055. }
  212056. }
  212057. else
  212058. {
  212059. while (--numSamples >= 0)
  212060. {
  212061. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212062. dest += dstStrideBytes;
  212063. }
  212064. }
  212065. }
  212066. static void convertInt32ToFloat (const char* src,
  212067. float* dest,
  212068. const int srcStrideBytes,
  212069. int numSamples,
  212070. const bool littleEndian) throw()
  212071. {
  212072. const double g = 1.0 / 0x7fffffff;
  212073. if (littleEndian)
  212074. {
  212075. while (--numSamples >= 0)
  212076. {
  212077. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  212078. src += srcStrideBytes;
  212079. }
  212080. }
  212081. else
  212082. {
  212083. while (--numSamples >= 0)
  212084. {
  212085. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  212086. src += srcStrideBytes;
  212087. }
  212088. }
  212089. }
  212090. static void convertFloatToInt32 (const float* src,
  212091. char* dest,
  212092. const int dstStrideBytes,
  212093. int numSamples,
  212094. const bool littleEndian) throw()
  212095. {
  212096. const double maxVal = (double) 0x7fffffff;
  212097. if (littleEndian)
  212098. {
  212099. while (--numSamples >= 0)
  212100. {
  212101. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212102. dest += dstStrideBytes;
  212103. }
  212104. }
  212105. else
  212106. {
  212107. while (--numSamples >= 0)
  212108. {
  212109. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212110. dest += dstStrideBytes;
  212111. }
  212112. }
  212113. }
  212114. static void typeToFormatParameters (const long type,
  212115. int& bitDepth,
  212116. int& byteStride,
  212117. bool& formatIsFloat,
  212118. bool& littleEndian) throw()
  212119. {
  212120. bitDepth = 0;
  212121. littleEndian = false;
  212122. formatIsFloat = false;
  212123. switch (type)
  212124. {
  212125. case ASIOSTInt16MSB:
  212126. case ASIOSTInt16LSB:
  212127. case ASIOSTInt32MSB16:
  212128. case ASIOSTInt32LSB16:
  212129. bitDepth = 16; break;
  212130. case ASIOSTFloat32MSB:
  212131. case ASIOSTFloat32LSB:
  212132. formatIsFloat = true;
  212133. bitDepth = 32; break;
  212134. case ASIOSTInt32MSB:
  212135. case ASIOSTInt32LSB:
  212136. bitDepth = 32; break;
  212137. case ASIOSTInt24MSB:
  212138. case ASIOSTInt24LSB:
  212139. case ASIOSTInt32MSB24:
  212140. case ASIOSTInt32LSB24:
  212141. case ASIOSTInt32MSB18:
  212142. case ASIOSTInt32MSB20:
  212143. case ASIOSTInt32LSB18:
  212144. case ASIOSTInt32LSB20:
  212145. bitDepth = 24; break;
  212146. case ASIOSTFloat64MSB:
  212147. case ASIOSTFloat64LSB:
  212148. default:
  212149. bitDepth = 64;
  212150. break;
  212151. }
  212152. switch (type)
  212153. {
  212154. case ASIOSTInt16MSB:
  212155. case ASIOSTInt32MSB16:
  212156. case ASIOSTFloat32MSB:
  212157. case ASIOSTFloat64MSB:
  212158. case ASIOSTInt32MSB:
  212159. case ASIOSTInt32MSB18:
  212160. case ASIOSTInt32MSB20:
  212161. case ASIOSTInt32MSB24:
  212162. case ASIOSTInt24MSB:
  212163. littleEndian = false; break;
  212164. case ASIOSTInt16LSB:
  212165. case ASIOSTInt32LSB16:
  212166. case ASIOSTFloat32LSB:
  212167. case ASIOSTFloat64LSB:
  212168. case ASIOSTInt32LSB:
  212169. case ASIOSTInt32LSB18:
  212170. case ASIOSTInt32LSB20:
  212171. case ASIOSTInt32LSB24:
  212172. case ASIOSTInt24LSB:
  212173. littleEndian = true; break;
  212174. default:
  212175. break;
  212176. }
  212177. switch (type)
  212178. {
  212179. case ASIOSTInt16LSB:
  212180. case ASIOSTInt16MSB:
  212181. byteStride = 2; break;
  212182. case ASIOSTInt24LSB:
  212183. case ASIOSTInt24MSB:
  212184. byteStride = 3; break;
  212185. case ASIOSTInt32MSB16:
  212186. case ASIOSTInt32LSB16:
  212187. case ASIOSTInt32MSB:
  212188. case ASIOSTInt32MSB18:
  212189. case ASIOSTInt32MSB20:
  212190. case ASIOSTInt32MSB24:
  212191. case ASIOSTInt32LSB:
  212192. case ASIOSTInt32LSB18:
  212193. case ASIOSTInt32LSB20:
  212194. case ASIOSTInt32LSB24:
  212195. case ASIOSTFloat32LSB:
  212196. case ASIOSTFloat32MSB:
  212197. byteStride = 4; break;
  212198. case ASIOSTFloat64MSB:
  212199. case ASIOSTFloat64LSB:
  212200. byteStride = 8; break;
  212201. default:
  212202. break;
  212203. }
  212204. }
  212205. };
  212206. class ASIOAudioIODeviceType : public AudioIODeviceType
  212207. {
  212208. public:
  212209. ASIOAudioIODeviceType()
  212210. : AudioIODeviceType ("ASIO"),
  212211. hasScanned (false)
  212212. {
  212213. CoInitialize (0);
  212214. }
  212215. ~ASIOAudioIODeviceType()
  212216. {
  212217. }
  212218. void scanForDevices()
  212219. {
  212220. hasScanned = true;
  212221. deviceNames.clear();
  212222. classIds.clear();
  212223. HKEY hk = 0;
  212224. int index = 0;
  212225. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  212226. {
  212227. for (;;)
  212228. {
  212229. char name [256];
  212230. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  212231. {
  212232. addDriverInfo (name, hk);
  212233. }
  212234. else
  212235. {
  212236. break;
  212237. }
  212238. }
  212239. RegCloseKey (hk);
  212240. }
  212241. }
  212242. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  212243. {
  212244. jassert (hasScanned); // need to call scanForDevices() before doing this
  212245. return deviceNames;
  212246. }
  212247. int getDefaultDeviceIndex (bool) const
  212248. {
  212249. jassert (hasScanned); // need to call scanForDevices() before doing this
  212250. for (int i = deviceNames.size(); --i >= 0;)
  212251. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  212252. return i; // asio4all is a safe choice for a default..
  212253. #if JUCE_DEBUG
  212254. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  212255. return 1; // (the digi m-box driver crashes the app when you run
  212256. // it in the debugger, which can be a bit annoying)
  212257. #endif
  212258. return 0;
  212259. }
  212260. static int findFreeSlot()
  212261. {
  212262. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212263. if (currentASIODev[i] == 0)
  212264. return i;
  212265. jassertfalse; // unfortunately you can only have a finite number
  212266. // of ASIO devices open at the same time..
  212267. return -1;
  212268. }
  212269. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  212270. {
  212271. jassert (hasScanned); // need to call scanForDevices() before doing this
  212272. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  212273. }
  212274. bool hasSeparateInputsAndOutputs() const { return false; }
  212275. AudioIODevice* createDevice (const String& outputDeviceName,
  212276. const String& inputDeviceName)
  212277. {
  212278. // ASIO can't open two different devices for input and output - they must be the same one.
  212279. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  212280. jassert (hasScanned); // need to call scanForDevices() before doing this
  212281. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  212282. : inputDeviceName);
  212283. if (index >= 0)
  212284. {
  212285. const int freeSlot = findFreeSlot();
  212286. if (freeSlot >= 0)
  212287. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  212288. }
  212289. return 0;
  212290. }
  212291. juce_UseDebuggingNewOperator
  212292. private:
  212293. StringArray deviceNames;
  212294. OwnedArray <CLSID> classIds;
  212295. bool hasScanned;
  212296. static bool checkClassIsOk (const String& classId)
  212297. {
  212298. HKEY hk = 0;
  212299. bool ok = false;
  212300. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  212301. {
  212302. int index = 0;
  212303. for (;;)
  212304. {
  212305. WCHAR buf [512];
  212306. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  212307. {
  212308. if (classId.equalsIgnoreCase (buf))
  212309. {
  212310. HKEY subKey, pathKey;
  212311. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212312. {
  212313. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  212314. {
  212315. WCHAR pathName [1024];
  212316. DWORD dtype = REG_SZ;
  212317. DWORD dsize = sizeof (pathName);
  212318. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  212319. ok = File (pathName).exists();
  212320. RegCloseKey (pathKey);
  212321. }
  212322. RegCloseKey (subKey);
  212323. }
  212324. break;
  212325. }
  212326. }
  212327. else
  212328. {
  212329. break;
  212330. }
  212331. }
  212332. RegCloseKey (hk);
  212333. }
  212334. return ok;
  212335. }
  212336. void addDriverInfo (const String& keyName, HKEY hk)
  212337. {
  212338. HKEY subKey;
  212339. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212340. {
  212341. WCHAR buf [256];
  212342. zerostruct (buf);
  212343. DWORD dtype = REG_SZ;
  212344. DWORD dsize = sizeof (buf);
  212345. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212346. {
  212347. if (dsize > 0 && checkClassIsOk (buf))
  212348. {
  212349. CLSID classId;
  212350. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  212351. {
  212352. dtype = REG_SZ;
  212353. dsize = sizeof (buf);
  212354. String deviceName;
  212355. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212356. deviceName = buf;
  212357. else
  212358. deviceName = keyName;
  212359. log ("found " + deviceName);
  212360. deviceNames.add (deviceName);
  212361. classIds.add (new CLSID (classId));
  212362. }
  212363. }
  212364. RegCloseKey (subKey);
  212365. }
  212366. }
  212367. }
  212368. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  212369. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  212370. };
  212371. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  212372. {
  212373. return new ASIOAudioIODeviceType();
  212374. }
  212375. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  212376. void* guid,
  212377. const String& optionalDllForDirectLoading)
  212378. {
  212379. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  212380. if (freeSlot < 0)
  212381. return 0;
  212382. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  212383. }
  212384. #undef log
  212385. #endif
  212386. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  212387. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  212388. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212389. // compiled on its own).
  212390. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  212391. END_JUCE_NAMESPACE
  212392. extern "C"
  212393. {
  212394. // Declare just the minimum number of interfaces for the DSound objects that we need..
  212395. typedef struct typeDSBUFFERDESC
  212396. {
  212397. DWORD dwSize;
  212398. DWORD dwFlags;
  212399. DWORD dwBufferBytes;
  212400. DWORD dwReserved;
  212401. LPWAVEFORMATEX lpwfxFormat;
  212402. GUID guid3DAlgorithm;
  212403. } DSBUFFERDESC;
  212404. struct IDirectSoundBuffer;
  212405. #undef INTERFACE
  212406. #define INTERFACE IDirectSound
  212407. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  212408. {
  212409. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212410. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212411. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212412. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  212413. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212414. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  212415. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  212416. STDMETHOD(Compact) (THIS) PURE;
  212417. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  212418. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  212419. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  212420. };
  212421. #undef INTERFACE
  212422. #define INTERFACE IDirectSoundBuffer
  212423. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  212424. {
  212425. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212426. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212427. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212428. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212429. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  212430. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  212431. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  212432. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  212433. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  212434. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  212435. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  212436. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  212437. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  212438. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  212439. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  212440. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  212441. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  212442. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  212443. STDMETHOD(Stop) (THIS) PURE;
  212444. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  212445. STDMETHOD(Restore) (THIS) PURE;
  212446. };
  212447. typedef struct typeDSCBUFFERDESC
  212448. {
  212449. DWORD dwSize;
  212450. DWORD dwFlags;
  212451. DWORD dwBufferBytes;
  212452. DWORD dwReserved;
  212453. LPWAVEFORMATEX lpwfxFormat;
  212454. } DSCBUFFERDESC;
  212455. struct IDirectSoundCaptureBuffer;
  212456. #undef INTERFACE
  212457. #define INTERFACE IDirectSoundCapture
  212458. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  212459. {
  212460. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212461. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212462. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212463. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  212464. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212465. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  212466. };
  212467. #undef INTERFACE
  212468. #define INTERFACE IDirectSoundCaptureBuffer
  212469. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  212470. {
  212471. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212472. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212473. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212474. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212475. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  212476. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  212477. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  212478. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  212479. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  212480. STDMETHOD(Start) (THIS_ DWORD) PURE;
  212481. STDMETHOD(Stop) (THIS) PURE;
  212482. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  212483. };
  212484. };
  212485. BEGIN_JUCE_NAMESPACE
  212486. static const String getDSErrorMessage (HRESULT hr)
  212487. {
  212488. const char* result = 0;
  212489. switch (hr)
  212490. {
  212491. case MAKE_HRESULT(1, 0x878, 10):
  212492. result = "Device already allocated";
  212493. break;
  212494. case MAKE_HRESULT(1, 0x878, 30):
  212495. result = "Control unavailable";
  212496. break;
  212497. case E_INVALIDARG:
  212498. result = "Invalid parameter";
  212499. break;
  212500. case MAKE_HRESULT(1, 0x878, 50):
  212501. result = "Invalid call";
  212502. break;
  212503. case E_FAIL:
  212504. result = "Generic error";
  212505. break;
  212506. case MAKE_HRESULT(1, 0x878, 70):
  212507. result = "Priority level error";
  212508. break;
  212509. case E_OUTOFMEMORY:
  212510. result = "Out of memory";
  212511. break;
  212512. case MAKE_HRESULT(1, 0x878, 100):
  212513. result = "Bad format";
  212514. break;
  212515. case E_NOTIMPL:
  212516. result = "Unsupported function";
  212517. break;
  212518. case MAKE_HRESULT(1, 0x878, 120):
  212519. result = "No driver";
  212520. break;
  212521. case MAKE_HRESULT(1, 0x878, 130):
  212522. result = "Already initialised";
  212523. break;
  212524. case CLASS_E_NOAGGREGATION:
  212525. result = "No aggregation";
  212526. break;
  212527. case MAKE_HRESULT(1, 0x878, 150):
  212528. result = "Buffer lost";
  212529. break;
  212530. case MAKE_HRESULT(1, 0x878, 160):
  212531. result = "Another app has priority";
  212532. break;
  212533. case MAKE_HRESULT(1, 0x878, 170):
  212534. result = "Uninitialised";
  212535. break;
  212536. case E_NOINTERFACE:
  212537. result = "No interface";
  212538. break;
  212539. case S_OK:
  212540. result = "No error";
  212541. break;
  212542. default:
  212543. return "Unknown error: " + String ((int) hr);
  212544. }
  212545. return result;
  212546. }
  212547. #define DS_DEBUGGING 1
  212548. #ifdef DS_DEBUGGING
  212549. #define CATCH JUCE_CATCH_EXCEPTION
  212550. #undef log
  212551. #define log(a) Logger::writeToLog(a);
  212552. #undef logError
  212553. #define logError(a) logDSError(a, __LINE__);
  212554. static void logDSError (HRESULT hr, int lineNum)
  212555. {
  212556. if (hr != S_OK)
  212557. {
  212558. String error ("DS error at line ");
  212559. error << lineNum << " - " << getDSErrorMessage (hr);
  212560. log (error);
  212561. }
  212562. }
  212563. #else
  212564. #define CATCH JUCE_CATCH_ALL
  212565. #define log(a)
  212566. #define logError(a)
  212567. #endif
  212568. #define DSOUND_FUNCTION(functionName, params) \
  212569. typedef HRESULT (WINAPI *type##functionName) params; \
  212570. static type##functionName ds##functionName = 0;
  212571. #define DSOUND_FUNCTION_LOAD(functionName) \
  212572. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  212573. jassert (ds##functionName != 0);
  212574. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  212575. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  212576. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  212577. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  212578. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  212579. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  212580. static void initialiseDSoundFunctions()
  212581. {
  212582. if (dsDirectSoundCreate == 0)
  212583. {
  212584. HMODULE h = LoadLibraryA ("dsound.dll");
  212585. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  212586. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  212587. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  212588. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  212589. }
  212590. }
  212591. class DSoundInternalOutChannel
  212592. {
  212593. String name;
  212594. LPGUID guid;
  212595. int sampleRate, bufferSizeSamples;
  212596. float* leftBuffer;
  212597. float* rightBuffer;
  212598. IDirectSound* pDirectSound;
  212599. IDirectSoundBuffer* pOutputBuffer;
  212600. DWORD writeOffset;
  212601. int totalBytesPerBuffer;
  212602. int bytesPerBuffer;
  212603. unsigned int lastPlayCursor;
  212604. public:
  212605. int bitDepth;
  212606. bool doneFlag;
  212607. DSoundInternalOutChannel (const String& name_,
  212608. LPGUID guid_,
  212609. int rate,
  212610. int bufferSize,
  212611. float* left,
  212612. float* right)
  212613. : name (name_),
  212614. guid (guid_),
  212615. sampleRate (rate),
  212616. bufferSizeSamples (bufferSize),
  212617. leftBuffer (left),
  212618. rightBuffer (right),
  212619. pDirectSound (0),
  212620. pOutputBuffer (0),
  212621. bitDepth (16)
  212622. {
  212623. }
  212624. ~DSoundInternalOutChannel()
  212625. {
  212626. close();
  212627. }
  212628. void close()
  212629. {
  212630. HRESULT hr;
  212631. if (pOutputBuffer != 0)
  212632. {
  212633. JUCE_TRY
  212634. {
  212635. log ("closing dsound out: " + name);
  212636. hr = pOutputBuffer->Stop();
  212637. logError (hr);
  212638. }
  212639. CATCH
  212640. JUCE_TRY
  212641. {
  212642. hr = pOutputBuffer->Release();
  212643. logError (hr);
  212644. }
  212645. CATCH
  212646. pOutputBuffer = 0;
  212647. }
  212648. if (pDirectSound != 0)
  212649. {
  212650. JUCE_TRY
  212651. {
  212652. hr = pDirectSound->Release();
  212653. logError (hr);
  212654. }
  212655. CATCH
  212656. pDirectSound = 0;
  212657. }
  212658. }
  212659. const String open()
  212660. {
  212661. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  212662. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  212663. pDirectSound = 0;
  212664. pOutputBuffer = 0;
  212665. writeOffset = 0;
  212666. String error;
  212667. HRESULT hr = E_NOINTERFACE;
  212668. if (dsDirectSoundCreate != 0)
  212669. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  212670. if (hr == S_OK)
  212671. {
  212672. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  212673. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  212674. const int numChannels = 2;
  212675. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  212676. logError (hr);
  212677. if (hr == S_OK)
  212678. {
  212679. IDirectSoundBuffer* pPrimaryBuffer;
  212680. DSBUFFERDESC primaryDesc;
  212681. zerostruct (primaryDesc);
  212682. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  212683. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  212684. primaryDesc.dwBufferBytes = 0;
  212685. primaryDesc.lpwfxFormat = 0;
  212686. log ("opening dsound out step 2");
  212687. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  212688. logError (hr);
  212689. if (hr == S_OK)
  212690. {
  212691. WAVEFORMATEX wfFormat;
  212692. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  212693. wfFormat.nChannels = (unsigned short) numChannels;
  212694. wfFormat.nSamplesPerSec = sampleRate;
  212695. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  212696. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  212697. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  212698. wfFormat.cbSize = 0;
  212699. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  212700. logError (hr);
  212701. if (hr == S_OK)
  212702. {
  212703. DSBUFFERDESC secondaryDesc;
  212704. zerostruct (secondaryDesc);
  212705. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  212706. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  212707. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  212708. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  212709. secondaryDesc.lpwfxFormat = &wfFormat;
  212710. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  212711. logError (hr);
  212712. if (hr == S_OK)
  212713. {
  212714. log ("opening dsound out step 3");
  212715. DWORD dwDataLen;
  212716. unsigned char* pDSBuffData;
  212717. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  212718. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  212719. logError (hr);
  212720. if (hr == S_OK)
  212721. {
  212722. zeromem (pDSBuffData, dwDataLen);
  212723. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  212724. if (hr == S_OK)
  212725. {
  212726. hr = pOutputBuffer->SetCurrentPosition (0);
  212727. if (hr == S_OK)
  212728. {
  212729. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  212730. if (hr == S_OK)
  212731. return String::empty;
  212732. }
  212733. }
  212734. }
  212735. }
  212736. }
  212737. }
  212738. }
  212739. }
  212740. error = getDSErrorMessage (hr);
  212741. close();
  212742. return error;
  212743. }
  212744. void synchronisePosition()
  212745. {
  212746. if (pOutputBuffer != 0)
  212747. {
  212748. DWORD playCursor;
  212749. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  212750. }
  212751. }
  212752. bool service()
  212753. {
  212754. if (pOutputBuffer == 0)
  212755. return true;
  212756. DWORD playCursor, writeCursor;
  212757. for (;;)
  212758. {
  212759. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  212760. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  212761. {
  212762. pOutputBuffer->Restore();
  212763. continue;
  212764. }
  212765. if (hr == S_OK)
  212766. break;
  212767. logError (hr);
  212768. jassertfalse;
  212769. return true;
  212770. }
  212771. int playWriteGap = writeCursor - playCursor;
  212772. if (playWriteGap < 0)
  212773. playWriteGap += totalBytesPerBuffer;
  212774. int bytesEmpty = playCursor - writeOffset;
  212775. if (bytesEmpty < 0)
  212776. bytesEmpty += totalBytesPerBuffer;
  212777. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  212778. {
  212779. writeOffset = writeCursor;
  212780. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  212781. }
  212782. if (bytesEmpty >= bytesPerBuffer)
  212783. {
  212784. LPBYTE lpbuf1 = 0;
  212785. LPBYTE lpbuf2 = 0;
  212786. DWORD dwSize1 = 0;
  212787. DWORD dwSize2 = 0;
  212788. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  212789. bytesPerBuffer,
  212790. (void**) &lpbuf1, &dwSize1,
  212791. (void**) &lpbuf2, &dwSize2, 0);
  212792. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  212793. {
  212794. pOutputBuffer->Restore();
  212795. hr = pOutputBuffer->Lock (writeOffset,
  212796. bytesPerBuffer,
  212797. (void**) &lpbuf1, &dwSize1,
  212798. (void**) &lpbuf2, &dwSize2, 0);
  212799. }
  212800. if (hr == S_OK)
  212801. {
  212802. if (bitDepth == 16)
  212803. {
  212804. const float gainL = 32767.0f;
  212805. const float gainR = 32767.0f;
  212806. int* dest = (int*)lpbuf1;
  212807. const float* left = leftBuffer;
  212808. const float* right = rightBuffer;
  212809. int samples1 = dwSize1 >> 2;
  212810. int samples2 = dwSize2 >> 2;
  212811. if (left == 0)
  212812. {
  212813. while (--samples1 >= 0)
  212814. {
  212815. int r = roundToInt (gainR * *right++);
  212816. if (r < -32768)
  212817. r = -32768;
  212818. else if (r > 32767)
  212819. r = 32767;
  212820. *dest++ = (r << 16);
  212821. }
  212822. dest = (int*)lpbuf2;
  212823. while (--samples2 >= 0)
  212824. {
  212825. int r = roundToInt (gainR * *right++);
  212826. if (r < -32768)
  212827. r = -32768;
  212828. else if (r > 32767)
  212829. r = 32767;
  212830. *dest++ = (r << 16);
  212831. }
  212832. }
  212833. else if (right == 0)
  212834. {
  212835. while (--samples1 >= 0)
  212836. {
  212837. int l = roundToInt (gainL * *left++);
  212838. if (l < -32768)
  212839. l = -32768;
  212840. else if (l > 32767)
  212841. l = 32767;
  212842. l &= 0xffff;
  212843. *dest++ = l;
  212844. }
  212845. dest = (int*)lpbuf2;
  212846. while (--samples2 >= 0)
  212847. {
  212848. int l = roundToInt (gainL * *left++);
  212849. if (l < -32768)
  212850. l = -32768;
  212851. else if (l > 32767)
  212852. l = 32767;
  212853. l &= 0xffff;
  212854. *dest++ = l;
  212855. }
  212856. }
  212857. else
  212858. {
  212859. while (--samples1 >= 0)
  212860. {
  212861. int l = roundToInt (gainL * *left++);
  212862. if (l < -32768)
  212863. l = -32768;
  212864. else if (l > 32767)
  212865. l = 32767;
  212866. l &= 0xffff;
  212867. int r = roundToInt (gainR * *right++);
  212868. if (r < -32768)
  212869. r = -32768;
  212870. else if (r > 32767)
  212871. r = 32767;
  212872. *dest++ = (r << 16) | l;
  212873. }
  212874. dest = (int*)lpbuf2;
  212875. while (--samples2 >= 0)
  212876. {
  212877. int l = roundToInt (gainL * *left++);
  212878. if (l < -32768)
  212879. l = -32768;
  212880. else if (l > 32767)
  212881. l = 32767;
  212882. l &= 0xffff;
  212883. int r = roundToInt (gainR * *right++);
  212884. if (r < -32768)
  212885. r = -32768;
  212886. else if (r > 32767)
  212887. r = 32767;
  212888. *dest++ = (r << 16) | l;
  212889. }
  212890. }
  212891. }
  212892. else
  212893. {
  212894. jassertfalse;
  212895. }
  212896. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  212897. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  212898. }
  212899. else
  212900. {
  212901. jassertfalse;
  212902. logError (hr);
  212903. }
  212904. bytesEmpty -= bytesPerBuffer;
  212905. return true;
  212906. }
  212907. else
  212908. {
  212909. return false;
  212910. }
  212911. }
  212912. };
  212913. struct DSoundInternalInChannel
  212914. {
  212915. String name;
  212916. LPGUID guid;
  212917. int sampleRate, bufferSizeSamples;
  212918. float* leftBuffer;
  212919. float* rightBuffer;
  212920. IDirectSound* pDirectSound;
  212921. IDirectSoundCapture* pDirectSoundCapture;
  212922. IDirectSoundCaptureBuffer* pInputBuffer;
  212923. public:
  212924. unsigned int readOffset;
  212925. int bytesPerBuffer, totalBytesPerBuffer;
  212926. int bitDepth;
  212927. bool doneFlag;
  212928. DSoundInternalInChannel (const String& name_,
  212929. LPGUID guid_,
  212930. int rate,
  212931. int bufferSize,
  212932. float* left,
  212933. float* right)
  212934. : name (name_),
  212935. guid (guid_),
  212936. sampleRate (rate),
  212937. bufferSizeSamples (bufferSize),
  212938. leftBuffer (left),
  212939. rightBuffer (right),
  212940. pDirectSound (0),
  212941. pDirectSoundCapture (0),
  212942. pInputBuffer (0),
  212943. bitDepth (16)
  212944. {
  212945. }
  212946. ~DSoundInternalInChannel()
  212947. {
  212948. close();
  212949. }
  212950. void close()
  212951. {
  212952. HRESULT hr;
  212953. if (pInputBuffer != 0)
  212954. {
  212955. JUCE_TRY
  212956. {
  212957. log ("closing dsound in: " + name);
  212958. hr = pInputBuffer->Stop();
  212959. logError (hr);
  212960. }
  212961. CATCH
  212962. JUCE_TRY
  212963. {
  212964. hr = pInputBuffer->Release();
  212965. logError (hr);
  212966. }
  212967. CATCH
  212968. pInputBuffer = 0;
  212969. }
  212970. if (pDirectSoundCapture != 0)
  212971. {
  212972. JUCE_TRY
  212973. {
  212974. hr = pDirectSoundCapture->Release();
  212975. logError (hr);
  212976. }
  212977. CATCH
  212978. pDirectSoundCapture = 0;
  212979. }
  212980. if (pDirectSound != 0)
  212981. {
  212982. JUCE_TRY
  212983. {
  212984. hr = pDirectSound->Release();
  212985. logError (hr);
  212986. }
  212987. CATCH
  212988. pDirectSound = 0;
  212989. }
  212990. }
  212991. const String open()
  212992. {
  212993. log ("opening dsound in device: " + name
  212994. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  212995. pDirectSound = 0;
  212996. pDirectSoundCapture = 0;
  212997. pInputBuffer = 0;
  212998. readOffset = 0;
  212999. totalBytesPerBuffer = 0;
  213000. String error;
  213001. HRESULT hr = E_NOINTERFACE;
  213002. if (dsDirectSoundCaptureCreate != 0)
  213003. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213004. logError (hr);
  213005. if (hr == S_OK)
  213006. {
  213007. const int numChannels = 2;
  213008. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213009. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213010. WAVEFORMATEX wfFormat;
  213011. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213012. wfFormat.nChannels = (unsigned short)numChannels;
  213013. wfFormat.nSamplesPerSec = sampleRate;
  213014. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213015. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213016. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213017. wfFormat.cbSize = 0;
  213018. DSCBUFFERDESC captureDesc;
  213019. zerostruct (captureDesc);
  213020. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213021. captureDesc.dwFlags = 0;
  213022. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213023. captureDesc.lpwfxFormat = &wfFormat;
  213024. log ("opening dsound in step 2");
  213025. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213026. logError (hr);
  213027. if (hr == S_OK)
  213028. {
  213029. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213030. logError (hr);
  213031. if (hr == S_OK)
  213032. return String::empty;
  213033. }
  213034. }
  213035. error = getDSErrorMessage (hr);
  213036. close();
  213037. return error;
  213038. }
  213039. void synchronisePosition()
  213040. {
  213041. if (pInputBuffer != 0)
  213042. {
  213043. DWORD capturePos;
  213044. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213045. }
  213046. }
  213047. bool service()
  213048. {
  213049. if (pInputBuffer == 0)
  213050. return true;
  213051. DWORD capturePos, readPos;
  213052. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213053. logError (hr);
  213054. if (hr != S_OK)
  213055. return true;
  213056. int bytesFilled = readPos - readOffset;
  213057. if (bytesFilled < 0)
  213058. bytesFilled += totalBytesPerBuffer;
  213059. if (bytesFilled >= bytesPerBuffer)
  213060. {
  213061. LPBYTE lpbuf1 = 0;
  213062. LPBYTE lpbuf2 = 0;
  213063. DWORD dwsize1 = 0;
  213064. DWORD dwsize2 = 0;
  213065. HRESULT hr = pInputBuffer->Lock (readOffset,
  213066. bytesPerBuffer,
  213067. (void**) &lpbuf1, &dwsize1,
  213068. (void**) &lpbuf2, &dwsize2, 0);
  213069. if (hr == S_OK)
  213070. {
  213071. if (bitDepth == 16)
  213072. {
  213073. const float g = 1.0f / 32768.0f;
  213074. float* destL = leftBuffer;
  213075. float* destR = rightBuffer;
  213076. int samples1 = dwsize1 >> 2;
  213077. int samples2 = dwsize2 >> 2;
  213078. const short* src = (const short*)lpbuf1;
  213079. if (destL == 0)
  213080. {
  213081. while (--samples1 >= 0)
  213082. {
  213083. ++src;
  213084. *destR++ = *src++ * g;
  213085. }
  213086. src = (const short*)lpbuf2;
  213087. while (--samples2 >= 0)
  213088. {
  213089. ++src;
  213090. *destR++ = *src++ * g;
  213091. }
  213092. }
  213093. else if (destR == 0)
  213094. {
  213095. while (--samples1 >= 0)
  213096. {
  213097. *destL++ = *src++ * g;
  213098. ++src;
  213099. }
  213100. src = (const short*)lpbuf2;
  213101. while (--samples2 >= 0)
  213102. {
  213103. *destL++ = *src++ * g;
  213104. ++src;
  213105. }
  213106. }
  213107. else
  213108. {
  213109. while (--samples1 >= 0)
  213110. {
  213111. *destL++ = *src++ * g;
  213112. *destR++ = *src++ * g;
  213113. }
  213114. src = (const short*)lpbuf2;
  213115. while (--samples2 >= 0)
  213116. {
  213117. *destL++ = *src++ * g;
  213118. *destR++ = *src++ * g;
  213119. }
  213120. }
  213121. }
  213122. else
  213123. {
  213124. jassertfalse;
  213125. }
  213126. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  213127. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  213128. }
  213129. else
  213130. {
  213131. logError (hr);
  213132. jassertfalse;
  213133. }
  213134. bytesFilled -= bytesPerBuffer;
  213135. return true;
  213136. }
  213137. else
  213138. {
  213139. return false;
  213140. }
  213141. }
  213142. };
  213143. class DSoundAudioIODevice : public AudioIODevice,
  213144. public Thread
  213145. {
  213146. public:
  213147. DSoundAudioIODevice (const String& deviceName,
  213148. const int outputDeviceIndex_,
  213149. const int inputDeviceIndex_)
  213150. : AudioIODevice (deviceName, "DirectSound"),
  213151. Thread ("Juce DSound"),
  213152. isOpen_ (false),
  213153. isStarted (false),
  213154. outputDeviceIndex (outputDeviceIndex_),
  213155. inputDeviceIndex (inputDeviceIndex_),
  213156. totalSamplesOut (0),
  213157. sampleRate (0.0),
  213158. inputBuffers (1, 1),
  213159. outputBuffers (1, 1),
  213160. callback (0),
  213161. bufferSizeSamples (0)
  213162. {
  213163. if (outputDeviceIndex_ >= 0)
  213164. {
  213165. outChannels.add (TRANS("Left"));
  213166. outChannels.add (TRANS("Right"));
  213167. }
  213168. if (inputDeviceIndex_ >= 0)
  213169. {
  213170. inChannels.add (TRANS("Left"));
  213171. inChannels.add (TRANS("Right"));
  213172. }
  213173. }
  213174. ~DSoundAudioIODevice()
  213175. {
  213176. close();
  213177. }
  213178. const StringArray getOutputChannelNames()
  213179. {
  213180. return outChannels;
  213181. }
  213182. const StringArray getInputChannelNames()
  213183. {
  213184. return inChannels;
  213185. }
  213186. int getNumSampleRates()
  213187. {
  213188. return 4;
  213189. }
  213190. double getSampleRate (int index)
  213191. {
  213192. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  213193. return samps [jlimit (0, 3, index)];
  213194. }
  213195. int getNumBufferSizesAvailable()
  213196. {
  213197. return 50;
  213198. }
  213199. int getBufferSizeSamples (int index)
  213200. {
  213201. int n = 64;
  213202. for (int i = 0; i < index; ++i)
  213203. n += (n < 512) ? 32
  213204. : ((n < 1024) ? 64
  213205. : ((n < 2048) ? 128 : 256));
  213206. return n;
  213207. }
  213208. int getDefaultBufferSize()
  213209. {
  213210. return 2560;
  213211. }
  213212. const String open (const BigInteger& inputChannels,
  213213. const BigInteger& outputChannels,
  213214. double sampleRate,
  213215. int bufferSizeSamples)
  213216. {
  213217. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  213218. isOpen_ = lastError.isEmpty();
  213219. return lastError;
  213220. }
  213221. void close()
  213222. {
  213223. stop();
  213224. if (isOpen_)
  213225. {
  213226. closeDevice();
  213227. isOpen_ = false;
  213228. }
  213229. }
  213230. bool isOpen()
  213231. {
  213232. return isOpen_ && isThreadRunning();
  213233. }
  213234. int getCurrentBufferSizeSamples()
  213235. {
  213236. return bufferSizeSamples;
  213237. }
  213238. double getCurrentSampleRate()
  213239. {
  213240. return sampleRate;
  213241. }
  213242. int getCurrentBitDepth()
  213243. {
  213244. int i, bits = 256;
  213245. for (i = inChans.size(); --i >= 0;)
  213246. bits = jmin (bits, inChans[i]->bitDepth);
  213247. for (i = outChans.size(); --i >= 0;)
  213248. bits = jmin (bits, outChans[i]->bitDepth);
  213249. if (bits > 32)
  213250. bits = 16;
  213251. return bits;
  213252. }
  213253. const BigInteger getActiveOutputChannels() const
  213254. {
  213255. return enabledOutputs;
  213256. }
  213257. const BigInteger getActiveInputChannels() const
  213258. {
  213259. return enabledInputs;
  213260. }
  213261. int getOutputLatencyInSamples()
  213262. {
  213263. return (int) (getCurrentBufferSizeSamples() * 1.5);
  213264. }
  213265. int getInputLatencyInSamples()
  213266. {
  213267. return getOutputLatencyInSamples();
  213268. }
  213269. void start (AudioIODeviceCallback* call)
  213270. {
  213271. if (isOpen_ && call != 0 && ! isStarted)
  213272. {
  213273. if (! isThreadRunning())
  213274. {
  213275. // something gone wrong and the thread's stopped..
  213276. isOpen_ = false;
  213277. return;
  213278. }
  213279. call->audioDeviceAboutToStart (this);
  213280. const ScopedLock sl (startStopLock);
  213281. callback = call;
  213282. isStarted = true;
  213283. }
  213284. }
  213285. void stop()
  213286. {
  213287. if (isStarted)
  213288. {
  213289. AudioIODeviceCallback* const callbackLocal = callback;
  213290. {
  213291. const ScopedLock sl (startStopLock);
  213292. isStarted = false;
  213293. }
  213294. if (callbackLocal != 0)
  213295. callbackLocal->audioDeviceStopped();
  213296. }
  213297. }
  213298. bool isPlaying()
  213299. {
  213300. return isStarted && isOpen_ && isThreadRunning();
  213301. }
  213302. const String getLastError()
  213303. {
  213304. return lastError;
  213305. }
  213306. juce_UseDebuggingNewOperator
  213307. StringArray inChannels, outChannels;
  213308. int outputDeviceIndex, inputDeviceIndex;
  213309. private:
  213310. bool isOpen_;
  213311. bool isStarted;
  213312. String lastError;
  213313. OwnedArray <DSoundInternalInChannel> inChans;
  213314. OwnedArray <DSoundInternalOutChannel> outChans;
  213315. WaitableEvent startEvent;
  213316. int bufferSizeSamples;
  213317. int volatile totalSamplesOut;
  213318. int64 volatile lastBlockTime;
  213319. double sampleRate;
  213320. BigInteger enabledInputs, enabledOutputs;
  213321. AudioSampleBuffer inputBuffers, outputBuffers;
  213322. AudioIODeviceCallback* callback;
  213323. CriticalSection startStopLock;
  213324. DSoundAudioIODevice (const DSoundAudioIODevice&);
  213325. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  213326. const String openDevice (const BigInteger& inputChannels,
  213327. const BigInteger& outputChannels,
  213328. double sampleRate_,
  213329. int bufferSizeSamples_);
  213330. void closeDevice()
  213331. {
  213332. isStarted = false;
  213333. stopThread (5000);
  213334. inChans.clear();
  213335. outChans.clear();
  213336. inputBuffers.setSize (1, 1);
  213337. outputBuffers.setSize (1, 1);
  213338. }
  213339. void resync()
  213340. {
  213341. if (! threadShouldExit())
  213342. {
  213343. sleep (5);
  213344. int i;
  213345. for (i = 0; i < outChans.size(); ++i)
  213346. outChans.getUnchecked(i)->synchronisePosition();
  213347. for (i = 0; i < inChans.size(); ++i)
  213348. inChans.getUnchecked(i)->synchronisePosition();
  213349. }
  213350. }
  213351. public:
  213352. void run()
  213353. {
  213354. while (! threadShouldExit())
  213355. {
  213356. if (wait (100))
  213357. break;
  213358. }
  213359. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  213360. const int maxTimeMS = jmax (5, 3 * latencyMs);
  213361. while (! threadShouldExit())
  213362. {
  213363. int numToDo = 0;
  213364. uint32 startTime = Time::getMillisecondCounter();
  213365. int i;
  213366. for (i = inChans.size(); --i >= 0;)
  213367. {
  213368. inChans.getUnchecked(i)->doneFlag = false;
  213369. ++numToDo;
  213370. }
  213371. for (i = outChans.size(); --i >= 0;)
  213372. {
  213373. outChans.getUnchecked(i)->doneFlag = false;
  213374. ++numToDo;
  213375. }
  213376. if (numToDo > 0)
  213377. {
  213378. const int maxCount = 3;
  213379. int count = maxCount;
  213380. for (;;)
  213381. {
  213382. for (i = inChans.size(); --i >= 0;)
  213383. {
  213384. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  213385. if ((! in->doneFlag) && in->service())
  213386. {
  213387. in->doneFlag = true;
  213388. --numToDo;
  213389. }
  213390. }
  213391. for (i = outChans.size(); --i >= 0;)
  213392. {
  213393. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  213394. if ((! out->doneFlag) && out->service())
  213395. {
  213396. out->doneFlag = true;
  213397. --numToDo;
  213398. }
  213399. }
  213400. if (numToDo <= 0)
  213401. break;
  213402. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  213403. {
  213404. resync();
  213405. break;
  213406. }
  213407. if (--count <= 0)
  213408. {
  213409. Sleep (1);
  213410. count = maxCount;
  213411. }
  213412. if (threadShouldExit())
  213413. return;
  213414. }
  213415. }
  213416. else
  213417. {
  213418. sleep (1);
  213419. }
  213420. const ScopedLock sl (startStopLock);
  213421. if (isStarted)
  213422. {
  213423. JUCE_TRY
  213424. {
  213425. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  213426. inputBuffers.getNumChannels(),
  213427. outputBuffers.getArrayOfChannels(),
  213428. outputBuffers.getNumChannels(),
  213429. bufferSizeSamples);
  213430. }
  213431. JUCE_CATCH_EXCEPTION
  213432. totalSamplesOut += bufferSizeSamples;
  213433. }
  213434. else
  213435. {
  213436. outputBuffers.clear();
  213437. totalSamplesOut = 0;
  213438. sleep (1);
  213439. }
  213440. }
  213441. }
  213442. };
  213443. class DSoundAudioIODeviceType : public AudioIODeviceType
  213444. {
  213445. public:
  213446. DSoundAudioIODeviceType()
  213447. : AudioIODeviceType ("DirectSound"),
  213448. hasScanned (false)
  213449. {
  213450. initialiseDSoundFunctions();
  213451. }
  213452. ~DSoundAudioIODeviceType()
  213453. {
  213454. }
  213455. void scanForDevices()
  213456. {
  213457. hasScanned = true;
  213458. outputDeviceNames.clear();
  213459. outputGuids.clear();
  213460. inputDeviceNames.clear();
  213461. inputGuids.clear();
  213462. if (dsDirectSoundEnumerateW != 0)
  213463. {
  213464. dsDirectSoundEnumerateW (outputEnumProcW, this);
  213465. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  213466. }
  213467. }
  213468. const StringArray getDeviceNames (bool wantInputNames) const
  213469. {
  213470. jassert (hasScanned); // need to call scanForDevices() before doing this
  213471. return wantInputNames ? inputDeviceNames
  213472. : outputDeviceNames;
  213473. }
  213474. int getDefaultDeviceIndex (bool /*forInput*/) const
  213475. {
  213476. jassert (hasScanned); // need to call scanForDevices() before doing this
  213477. return 0;
  213478. }
  213479. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  213480. {
  213481. jassert (hasScanned); // need to call scanForDevices() before doing this
  213482. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  213483. if (d == 0)
  213484. return -1;
  213485. return asInput ? d->inputDeviceIndex
  213486. : d->outputDeviceIndex;
  213487. }
  213488. bool hasSeparateInputsAndOutputs() const { return true; }
  213489. AudioIODevice* createDevice (const String& outputDeviceName,
  213490. const String& inputDeviceName)
  213491. {
  213492. jassert (hasScanned); // need to call scanForDevices() before doing this
  213493. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  213494. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  213495. if (outputIndex >= 0 || inputIndex >= 0)
  213496. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  213497. : inputDeviceName,
  213498. outputIndex, inputIndex);
  213499. return 0;
  213500. }
  213501. juce_UseDebuggingNewOperator
  213502. StringArray outputDeviceNames;
  213503. OwnedArray <GUID> outputGuids;
  213504. StringArray inputDeviceNames;
  213505. OwnedArray <GUID> inputGuids;
  213506. private:
  213507. bool hasScanned;
  213508. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  213509. {
  213510. desc = desc.trim();
  213511. if (desc.isNotEmpty())
  213512. {
  213513. const String origDesc (desc);
  213514. int n = 2;
  213515. while (outputDeviceNames.contains (desc))
  213516. desc = origDesc + " (" + String (n++) + ")";
  213517. outputDeviceNames.add (desc);
  213518. if (lpGUID != 0)
  213519. outputGuids.add (new GUID (*lpGUID));
  213520. else
  213521. outputGuids.add (0);
  213522. }
  213523. return TRUE;
  213524. }
  213525. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  213526. {
  213527. return ((DSoundAudioIODeviceType*) object)
  213528. ->outputEnumProc (lpGUID, String (description));
  213529. }
  213530. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  213531. {
  213532. return ((DSoundAudioIODeviceType*) object)
  213533. ->outputEnumProc (lpGUID, String (description));
  213534. }
  213535. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  213536. {
  213537. desc = desc.trim();
  213538. if (desc.isNotEmpty())
  213539. {
  213540. const String origDesc (desc);
  213541. int n = 2;
  213542. while (inputDeviceNames.contains (desc))
  213543. desc = origDesc + " (" + String (n++) + ")";
  213544. inputDeviceNames.add (desc);
  213545. if (lpGUID != 0)
  213546. inputGuids.add (new GUID (*lpGUID));
  213547. else
  213548. inputGuids.add (0);
  213549. }
  213550. return TRUE;
  213551. }
  213552. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  213553. {
  213554. return ((DSoundAudioIODeviceType*) object)
  213555. ->inputEnumProc (lpGUID, String (description));
  213556. }
  213557. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  213558. {
  213559. return ((DSoundAudioIODeviceType*) object)
  213560. ->inputEnumProc (lpGUID, String (description));
  213561. }
  213562. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  213563. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  213564. };
  213565. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  213566. const BigInteger& outputChannels,
  213567. double sampleRate_,
  213568. int bufferSizeSamples_)
  213569. {
  213570. closeDevice();
  213571. totalSamplesOut = 0;
  213572. sampleRate = sampleRate_;
  213573. if (bufferSizeSamples_ <= 0)
  213574. bufferSizeSamples_ = 960; // use as a default size if none is set.
  213575. bufferSizeSamples = bufferSizeSamples_ & ~7;
  213576. DSoundAudioIODeviceType dlh;
  213577. dlh.scanForDevices();
  213578. enabledInputs = inputChannels;
  213579. enabledInputs.setRange (inChannels.size(),
  213580. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  213581. false);
  213582. inputBuffers.setSize (enabledInputs.countNumberOfSetBits(), bufferSizeSamples);
  213583. int i, numIns = 0;
  213584. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  213585. {
  213586. float* left = 0;
  213587. if (enabledInputs[i])
  213588. left = inputBuffers.getSampleData (numIns++);
  213589. float* right = 0;
  213590. if (enabledInputs[i + 1])
  213591. right = inputBuffers.getSampleData (numIns++);
  213592. if (left != 0 || right != 0)
  213593. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  213594. dlh.inputGuids [inputDeviceIndex],
  213595. (int) sampleRate, bufferSizeSamples,
  213596. left, right));
  213597. }
  213598. enabledOutputs = outputChannels;
  213599. enabledOutputs.setRange (outChannels.size(),
  213600. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  213601. false);
  213602. outputBuffers.setSize (enabledOutputs.countNumberOfSetBits(), bufferSizeSamples);
  213603. int numOuts = 0;
  213604. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  213605. {
  213606. float* left = 0;
  213607. if (enabledOutputs[i])
  213608. left = outputBuffers.getSampleData (numOuts++);
  213609. float* right = 0;
  213610. if (enabledOutputs[i + 1])
  213611. right = outputBuffers.getSampleData (numOuts++);
  213612. if (left != 0 || right != 0)
  213613. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  213614. dlh.outputGuids [outputDeviceIndex],
  213615. (int) sampleRate, bufferSizeSamples,
  213616. left, right));
  213617. }
  213618. String error;
  213619. // boost our priority while opening the devices to try to get better sync between them
  213620. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  213621. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  213622. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  213623. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  213624. for (i = 0; i < outChans.size(); ++i)
  213625. {
  213626. error = outChans[i]->open();
  213627. if (error.isNotEmpty())
  213628. {
  213629. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  213630. break;
  213631. }
  213632. }
  213633. if (error.isEmpty())
  213634. {
  213635. for (i = 0; i < inChans.size(); ++i)
  213636. {
  213637. error = inChans[i]->open();
  213638. if (error.isNotEmpty())
  213639. {
  213640. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  213641. break;
  213642. }
  213643. }
  213644. }
  213645. if (error.isEmpty())
  213646. {
  213647. totalSamplesOut = 0;
  213648. for (i = 0; i < outChans.size(); ++i)
  213649. outChans.getUnchecked(i)->synchronisePosition();
  213650. for (i = 0; i < inChans.size(); ++i)
  213651. inChans.getUnchecked(i)->synchronisePosition();
  213652. startThread (9);
  213653. sleep (10);
  213654. notify();
  213655. }
  213656. else
  213657. {
  213658. log (error);
  213659. }
  213660. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  213661. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  213662. return error;
  213663. }
  213664. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  213665. {
  213666. return new DSoundAudioIODeviceType();
  213667. }
  213668. #undef log
  213669. #endif
  213670. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  213671. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  213672. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213673. // compiled on its own).
  213674. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  213675. #if 1
  213676. const String getAudioErrorDesc (HRESULT hr)
  213677. {
  213678. const char* e = 0;
  213679. switch (hr)
  213680. {
  213681. case E_POINTER: e = "E_POINTER"; break;
  213682. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  213683. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  213684. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  213685. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  213686. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  213687. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  213688. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  213689. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  213690. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  213691. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  213692. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  213693. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  213694. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  213695. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  213696. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  213697. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  213698. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  213699. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  213700. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  213701. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  213702. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  213703. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  213704. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  213705. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  213706. default: return String::toHexString ((int) hr);
  213707. }
  213708. return e;
  213709. }
  213710. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  213711. #define OK(a) wasapi_checkResult(a)
  213712. static bool wasapi_checkResult (HRESULT hr)
  213713. {
  213714. logFailure (hr);
  213715. return SUCCEEDED (hr);
  213716. }
  213717. #else
  213718. #define logFailure(hr) {}
  213719. #define OK(a) SUCCEEDED(a)
  213720. #endif
  213721. static const String wasapi_getDeviceID (IMMDevice* const device)
  213722. {
  213723. String s;
  213724. WCHAR* deviceId = 0;
  213725. if (OK (device->GetId (&deviceId)))
  213726. {
  213727. s = String (deviceId);
  213728. CoTaskMemFree (deviceId);
  213729. }
  213730. return s;
  213731. }
  213732. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  213733. {
  213734. EDataFlow flow = eRender;
  213735. ComSmartPtr <IMMEndpoint> endPoint;
  213736. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  213737. (void) OK (endPoint->GetDataFlow (&flow));
  213738. return flow;
  213739. }
  213740. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  213741. {
  213742. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  213743. }
  213744. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  213745. {
  213746. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  213747. : sizeof (WAVEFORMATEX));
  213748. }
  213749. class WASAPIDeviceBase
  213750. {
  213751. public:
  213752. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  213753. : device (device_),
  213754. sampleRate (0),
  213755. numChannels (0),
  213756. actualNumChannels (0),
  213757. defaultSampleRate (0),
  213758. minBufferSize (0),
  213759. defaultBufferSize (0),
  213760. latencySamples (0),
  213761. useExclusiveMode (useExclusiveMode_)
  213762. {
  213763. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  213764. ComSmartPtr <IAudioClient> tempClient (createClient());
  213765. if (tempClient == 0)
  213766. return;
  213767. REFERENCE_TIME defaultPeriod, minPeriod;
  213768. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  213769. return;
  213770. WAVEFORMATEX* mixFormat = 0;
  213771. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  213772. return;
  213773. WAVEFORMATEXTENSIBLE format;
  213774. wasapi_copyWavFormat (format, mixFormat);
  213775. CoTaskMemFree (mixFormat);
  213776. actualNumChannels = numChannels = format.Format.nChannels;
  213777. defaultSampleRate = format.Format.nSamplesPerSec;
  213778. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  213779. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  213780. rates.addUsingDefaultSort (defaultSampleRate);
  213781. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  213782. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  213783. {
  213784. if (ratesToTest[i] == defaultSampleRate)
  213785. continue;
  213786. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  213787. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  213788. (WAVEFORMATEX*) &format, 0)))
  213789. if (! rates.contains (ratesToTest[i]))
  213790. rates.addUsingDefaultSort (ratesToTest[i]);
  213791. }
  213792. }
  213793. ~WASAPIDeviceBase()
  213794. {
  213795. device = 0;
  213796. CloseHandle (clientEvent);
  213797. }
  213798. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  213799. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  213800. {
  213801. sampleRate = newSampleRate;
  213802. channels = newChannels;
  213803. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  213804. numChannels = channels.getHighestBit() + 1;
  213805. if (numChannels == 0)
  213806. return true;
  213807. client = createClient();
  213808. if (client != 0
  213809. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  213810. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  213811. {
  213812. channelMaps.clear();
  213813. for (int i = 0; i <= channels.getHighestBit(); ++i)
  213814. if (channels[i])
  213815. channelMaps.add (i);
  213816. REFERENCE_TIME latency;
  213817. if (OK (client->GetStreamLatency (&latency)))
  213818. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  213819. (void) OK (client->GetBufferSize (&actualBufferSize));
  213820. return OK (client->SetEventHandle (clientEvent));
  213821. }
  213822. return false;
  213823. }
  213824. void closeClient()
  213825. {
  213826. if (client != 0)
  213827. client->Stop();
  213828. client = 0;
  213829. ResetEvent (clientEvent);
  213830. }
  213831. ComSmartPtr <IMMDevice> device;
  213832. ComSmartPtr <IAudioClient> client;
  213833. double sampleRate, defaultSampleRate;
  213834. int numChannels, actualNumChannels;
  213835. int minBufferSize, defaultBufferSize, latencySamples;
  213836. const bool useExclusiveMode;
  213837. Array <double> rates;
  213838. HANDLE clientEvent;
  213839. BigInteger channels;
  213840. AudioDataConverters::DataFormat dataFormat;
  213841. Array <int> channelMaps;
  213842. UINT32 actualBufferSize;
  213843. int bytesPerSample;
  213844. private:
  213845. const ComSmartPtr <IAudioClient> createClient()
  213846. {
  213847. ComSmartPtr <IAudioClient> client;
  213848. if (device != 0)
  213849. {
  213850. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  213851. logFailure (hr);
  213852. }
  213853. return client;
  213854. }
  213855. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  213856. {
  213857. WAVEFORMATEXTENSIBLE format;
  213858. zerostruct (format);
  213859. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  213860. {
  213861. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  213862. }
  213863. else
  213864. {
  213865. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  213866. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  213867. }
  213868. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  213869. format.Format.nChannels = (WORD) numChannels;
  213870. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  213871. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  213872. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  213873. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  213874. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  213875. switch (numChannels)
  213876. {
  213877. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  213878. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  213879. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  213880. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  213881. case 8: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER; break;
  213882. default: break;
  213883. }
  213884. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  213885. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  213886. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  213887. logFailure (hr);
  213888. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  213889. {
  213890. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  213891. hr = S_OK;
  213892. }
  213893. CoTaskMemFree (nearestFormat);
  213894. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  213895. if (useExclusiveMode)
  213896. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  213897. GUID session;
  213898. if (hr == S_OK
  213899. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  213900. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  213901. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  213902. {
  213903. actualNumChannels = format.Format.nChannels;
  213904. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  213905. bytesPerSample = format.Format.wBitsPerSample / 8;
  213906. dataFormat = isFloat ? AudioDataConverters::float32LE
  213907. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  213908. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  213909. : AudioDataConverters::int16LE)));
  213910. return true;
  213911. }
  213912. return false;
  213913. }
  213914. WASAPIDeviceBase (const WASAPIDeviceBase&);
  213915. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  213916. };
  213917. class WASAPIInputDevice : public WASAPIDeviceBase
  213918. {
  213919. public:
  213920. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  213921. : WASAPIDeviceBase (device_, useExclusiveMode_),
  213922. reservoir (1, 1)
  213923. {
  213924. }
  213925. ~WASAPIInputDevice()
  213926. {
  213927. close();
  213928. }
  213929. bool open (const double newSampleRate, const BigInteger& newChannels)
  213930. {
  213931. reservoirSize = 0;
  213932. reservoirCapacity = 16384;
  213933. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  213934. return openClient (newSampleRate, newChannels)
  213935. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  213936. }
  213937. void close()
  213938. {
  213939. closeClient();
  213940. captureClient = 0;
  213941. reservoir.setSize (0);
  213942. }
  213943. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  213944. {
  213945. if (numChannels <= 0)
  213946. return;
  213947. int offset = 0;
  213948. while (bufferSize > 0)
  213949. {
  213950. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  213951. {
  213952. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  213953. for (int i = 0; i < numDestBuffers; ++i)
  213954. {
  213955. float* const dest = destBuffers[i] + offset;
  213956. const int srcChan = channelMaps.getUnchecked(i);
  213957. switch (dataFormat)
  213958. {
  213959. case AudioDataConverters::float32LE:
  213960. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  213961. break;
  213962. case AudioDataConverters::int32LE:
  213963. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  213964. break;
  213965. case AudioDataConverters::int24LE:
  213966. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  213967. break;
  213968. case AudioDataConverters::int16LE:
  213969. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  213970. break;
  213971. default: jassertfalse; break;
  213972. }
  213973. }
  213974. bufferSize -= samplesToDo;
  213975. offset += samplesToDo;
  213976. reservoirSize -= samplesToDo;
  213977. }
  213978. else
  213979. {
  213980. UINT32 packetLength = 0;
  213981. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  213982. break;
  213983. if (packetLength == 0)
  213984. {
  213985. if (thread.threadShouldExit())
  213986. break;
  213987. Thread::sleep (1);
  213988. continue;
  213989. }
  213990. uint8* inputData = 0;
  213991. UINT32 numSamplesAvailable;
  213992. DWORD flags;
  213993. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  213994. {
  213995. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  213996. for (int i = 0; i < numDestBuffers; ++i)
  213997. {
  213998. float* const dest = destBuffers[i] + offset;
  213999. const int srcChan = channelMaps.getUnchecked(i);
  214000. switch (dataFormat)
  214001. {
  214002. case AudioDataConverters::float32LE:
  214003. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214004. break;
  214005. case AudioDataConverters::int32LE:
  214006. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214007. break;
  214008. case AudioDataConverters::int24LE:
  214009. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214010. break;
  214011. case AudioDataConverters::int16LE:
  214012. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214013. break;
  214014. default: jassertfalse; break;
  214015. }
  214016. }
  214017. bufferSize -= samplesToDo;
  214018. offset += samplesToDo;
  214019. if (samplesToDo < (int) numSamplesAvailable)
  214020. {
  214021. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214022. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214023. bytesPerSample * actualNumChannels * reservoirSize);
  214024. }
  214025. captureClient->ReleaseBuffer (numSamplesAvailable);
  214026. }
  214027. }
  214028. }
  214029. }
  214030. ComSmartPtr <IAudioCaptureClient> captureClient;
  214031. MemoryBlock reservoir;
  214032. int reservoirSize, reservoirCapacity;
  214033. private:
  214034. WASAPIInputDevice (const WASAPIInputDevice&);
  214035. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  214036. };
  214037. class WASAPIOutputDevice : public WASAPIDeviceBase
  214038. {
  214039. public:
  214040. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214041. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214042. {
  214043. }
  214044. ~WASAPIOutputDevice()
  214045. {
  214046. close();
  214047. }
  214048. bool open (const double newSampleRate, const BigInteger& newChannels)
  214049. {
  214050. return openClient (newSampleRate, newChannels)
  214051. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  214052. }
  214053. void close()
  214054. {
  214055. closeClient();
  214056. renderClient = 0;
  214057. }
  214058. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214059. {
  214060. if (numChannels <= 0)
  214061. return;
  214062. int offset = 0;
  214063. while (bufferSize > 0)
  214064. {
  214065. UINT32 padding = 0;
  214066. if (! OK (client->GetCurrentPadding (&padding)))
  214067. return;
  214068. int samplesToDo = useExclusiveMode ? bufferSize
  214069. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214070. if (samplesToDo <= 0)
  214071. {
  214072. if (thread.threadShouldExit())
  214073. break;
  214074. Thread::sleep (0);
  214075. continue;
  214076. }
  214077. uint8* outputData = 0;
  214078. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  214079. {
  214080. for (int i = 0; i < numSrcBuffers; ++i)
  214081. {
  214082. const float* const source = srcBuffers[i] + offset;
  214083. const int destChan = channelMaps.getUnchecked(i);
  214084. switch (dataFormat)
  214085. {
  214086. case AudioDataConverters::float32LE:
  214087. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214088. break;
  214089. case AudioDataConverters::int32LE:
  214090. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214091. break;
  214092. case AudioDataConverters::int24LE:
  214093. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  214094. break;
  214095. case AudioDataConverters::int16LE:
  214096. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  214097. break;
  214098. default: jassertfalse; break;
  214099. }
  214100. }
  214101. renderClient->ReleaseBuffer (samplesToDo, 0);
  214102. offset += samplesToDo;
  214103. bufferSize -= samplesToDo;
  214104. }
  214105. }
  214106. }
  214107. ComSmartPtr <IAudioRenderClient> renderClient;
  214108. private:
  214109. WASAPIOutputDevice (const WASAPIOutputDevice&);
  214110. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  214111. };
  214112. class WASAPIAudioIODevice : public AudioIODevice,
  214113. public Thread
  214114. {
  214115. public:
  214116. WASAPIAudioIODevice (const String& deviceName,
  214117. const String& outputDeviceId_,
  214118. const String& inputDeviceId_,
  214119. const bool useExclusiveMode_)
  214120. : AudioIODevice (deviceName, "Windows Audio"),
  214121. Thread ("Juce WASAPI"),
  214122. isOpen_ (false),
  214123. isStarted (false),
  214124. outputDevice (0),
  214125. outputDeviceId (outputDeviceId_),
  214126. inputDevice (0),
  214127. inputDeviceId (inputDeviceId_),
  214128. useExclusiveMode (useExclusiveMode_),
  214129. currentBufferSizeSamples (0),
  214130. currentSampleRate (0),
  214131. callback (0)
  214132. {
  214133. }
  214134. ~WASAPIAudioIODevice()
  214135. {
  214136. close();
  214137. deleteAndZero (inputDevice);
  214138. deleteAndZero (outputDevice);
  214139. }
  214140. bool initialise()
  214141. {
  214142. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214143. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214144. latencyIn = latencyOut = 0;
  214145. Array <double> ratesIn, ratesOut;
  214146. if (createDevices())
  214147. {
  214148. jassert (inputDevice != 0 || outputDevice != 0);
  214149. if (inputDevice != 0 && outputDevice != 0)
  214150. {
  214151. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214152. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214153. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214154. sampleRates = inputDevice->rates;
  214155. sampleRates.removeValuesNotIn (outputDevice->rates);
  214156. }
  214157. else
  214158. {
  214159. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  214160. defaultSampleRate = d->defaultSampleRate;
  214161. minBufferSize = d->minBufferSize;
  214162. defaultBufferSize = d->defaultBufferSize;
  214163. sampleRates = d->rates;
  214164. }
  214165. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  214166. if (minBufferSize != defaultBufferSize)
  214167. bufferSizes.addUsingDefaultSort (minBufferSize);
  214168. int n = 64;
  214169. for (int i = 0; i < 40; ++i)
  214170. {
  214171. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  214172. bufferSizes.addUsingDefaultSort (n);
  214173. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  214174. }
  214175. return true;
  214176. }
  214177. return false;
  214178. }
  214179. const StringArray getOutputChannelNames()
  214180. {
  214181. StringArray outChannels;
  214182. if (outputDevice != 0)
  214183. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  214184. outChannels.add ("Output channel " + String (i));
  214185. return outChannels;
  214186. }
  214187. const StringArray getInputChannelNames()
  214188. {
  214189. StringArray inChannels;
  214190. if (inputDevice != 0)
  214191. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  214192. inChannels.add ("Input channel " + String (i));
  214193. return inChannels;
  214194. }
  214195. int getNumSampleRates() { return sampleRates.size(); }
  214196. double getSampleRate (int index) { return sampleRates [index]; }
  214197. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  214198. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  214199. int getDefaultBufferSize() { return defaultBufferSize; }
  214200. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  214201. double getCurrentSampleRate() { return currentSampleRate; }
  214202. int getCurrentBitDepth() { return 32; }
  214203. int getOutputLatencyInSamples() { return latencyOut; }
  214204. int getInputLatencyInSamples() { return latencyIn; }
  214205. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  214206. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  214207. const String getLastError() { return lastError; }
  214208. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  214209. double sampleRate, int bufferSizeSamples)
  214210. {
  214211. close();
  214212. lastError = String::empty;
  214213. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  214214. {
  214215. lastError = "The input and output devices don't share a common sample rate!";
  214216. return lastError;
  214217. }
  214218. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  214219. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  214220. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  214221. {
  214222. lastError = "Couldn't open the input device!";
  214223. return lastError;
  214224. }
  214225. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  214226. {
  214227. close();
  214228. lastError = "Couldn't open the output device!";
  214229. return lastError;
  214230. }
  214231. if (inputDevice != 0)
  214232. ResetEvent (inputDevice->clientEvent);
  214233. if (outputDevice != 0)
  214234. ResetEvent (outputDevice->clientEvent);
  214235. startThread (8);
  214236. Thread::sleep (5);
  214237. if (inputDevice != 0 && inputDevice->client != 0)
  214238. {
  214239. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  214240. HRESULT hr = inputDevice->client->Start();
  214241. logFailure (hr); //xxx handle this
  214242. }
  214243. if (outputDevice != 0 && outputDevice->client != 0)
  214244. {
  214245. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  214246. HRESULT hr = outputDevice->client->Start();
  214247. logFailure (hr); //xxx handle this
  214248. }
  214249. isOpen_ = true;
  214250. return lastError;
  214251. }
  214252. void close()
  214253. {
  214254. stop();
  214255. if (inputDevice != 0)
  214256. SetEvent (inputDevice->clientEvent);
  214257. if (outputDevice != 0)
  214258. SetEvent (outputDevice->clientEvent);
  214259. stopThread (5000);
  214260. if (inputDevice != 0)
  214261. inputDevice->close();
  214262. if (outputDevice != 0)
  214263. outputDevice->close();
  214264. isOpen_ = false;
  214265. }
  214266. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214267. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214268. void start (AudioIODeviceCallback* call)
  214269. {
  214270. if (isOpen_ && call != 0 && ! isStarted)
  214271. {
  214272. if (! isThreadRunning())
  214273. {
  214274. // something's gone wrong and the thread's stopped..
  214275. isOpen_ = false;
  214276. return;
  214277. }
  214278. call->audioDeviceAboutToStart (this);
  214279. const ScopedLock sl (startStopLock);
  214280. callback = call;
  214281. isStarted = true;
  214282. }
  214283. }
  214284. void stop()
  214285. {
  214286. if (isStarted)
  214287. {
  214288. AudioIODeviceCallback* const callbackLocal = callback;
  214289. {
  214290. const ScopedLock sl (startStopLock);
  214291. isStarted = false;
  214292. }
  214293. if (callbackLocal != 0)
  214294. callbackLocal->audioDeviceStopped();
  214295. }
  214296. }
  214297. void setMMThreadPriority()
  214298. {
  214299. DynamicLibraryLoader dll ("avrt.dll");
  214300. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  214301. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  214302. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  214303. {
  214304. DWORD dummy = 0;
  214305. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  214306. if (h != 0)
  214307. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  214308. }
  214309. }
  214310. void run()
  214311. {
  214312. setMMThreadPriority();
  214313. const int bufferSize = currentBufferSizeSamples;
  214314. HANDLE events[2];
  214315. int numEvents = 0;
  214316. if (inputDevice != 0)
  214317. events [numEvents++] = inputDevice->clientEvent;
  214318. if (outputDevice != 0)
  214319. events [numEvents++] = outputDevice->clientEvent;
  214320. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  214321. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  214322. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  214323. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  214324. float** const inputBuffers = ins.getArrayOfChannels();
  214325. float** const outputBuffers = outs.getArrayOfChannels();
  214326. ins.clear();
  214327. while (! threadShouldExit())
  214328. {
  214329. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  214330. : WaitForMultipleObjects (numEvents, events, true, 1000);
  214331. if (result == WAIT_TIMEOUT)
  214332. continue;
  214333. if (threadShouldExit())
  214334. break;
  214335. if (inputDevice != 0)
  214336. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  214337. // Make the callback..
  214338. {
  214339. const ScopedLock sl (startStopLock);
  214340. if (isStarted)
  214341. {
  214342. JUCE_TRY
  214343. {
  214344. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  214345. numInputBuffers,
  214346. outputBuffers,
  214347. numOutputBuffers,
  214348. bufferSize);
  214349. }
  214350. JUCE_CATCH_EXCEPTION
  214351. }
  214352. else
  214353. {
  214354. outs.clear();
  214355. }
  214356. }
  214357. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  214358. continue;
  214359. if (outputDevice != 0)
  214360. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  214361. }
  214362. }
  214363. juce_UseDebuggingNewOperator
  214364. String outputDeviceId, inputDeviceId;
  214365. String lastError;
  214366. private:
  214367. // Device stats...
  214368. WASAPIInputDevice* inputDevice;
  214369. WASAPIOutputDevice* outputDevice;
  214370. const bool useExclusiveMode;
  214371. double defaultSampleRate;
  214372. int minBufferSize, defaultBufferSize;
  214373. int latencyIn, latencyOut;
  214374. Array <double> sampleRates;
  214375. Array <int> bufferSizes;
  214376. // Active state...
  214377. bool isOpen_, isStarted;
  214378. int currentBufferSizeSamples;
  214379. double currentSampleRate;
  214380. AudioIODeviceCallback* callback;
  214381. CriticalSection startStopLock;
  214382. bool createDevices()
  214383. {
  214384. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214385. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214386. return false;
  214387. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214388. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  214389. return false;
  214390. UINT32 numDevices = 0;
  214391. if (! OK (deviceCollection->GetCount (&numDevices)))
  214392. return false;
  214393. for (UINT32 i = 0; i < numDevices; ++i)
  214394. {
  214395. ComSmartPtr <IMMDevice> device;
  214396. if (! OK (deviceCollection->Item (i, &device)))
  214397. continue;
  214398. const String deviceId (wasapi_getDeviceID (device));
  214399. if (deviceId.isEmpty())
  214400. continue;
  214401. const EDataFlow flow = wasapi_getDataFlow (device);
  214402. if (deviceId == inputDeviceId && flow == eCapture)
  214403. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  214404. else if (deviceId == outputDeviceId && flow == eRender)
  214405. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  214406. }
  214407. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  214408. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  214409. }
  214410. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  214411. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  214412. };
  214413. class WASAPIAudioIODeviceType : public AudioIODeviceType
  214414. {
  214415. public:
  214416. WASAPIAudioIODeviceType()
  214417. : AudioIODeviceType ("Windows Audio"),
  214418. hasScanned (false)
  214419. {
  214420. }
  214421. ~WASAPIAudioIODeviceType()
  214422. {
  214423. }
  214424. void scanForDevices()
  214425. {
  214426. hasScanned = true;
  214427. outputDeviceNames.clear();
  214428. inputDeviceNames.clear();
  214429. outputDeviceIds.clear();
  214430. inputDeviceIds.clear();
  214431. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214432. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214433. return;
  214434. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  214435. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  214436. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214437. UINT32 numDevices = 0;
  214438. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  214439. && OK (deviceCollection->GetCount (&numDevices))))
  214440. return;
  214441. for (UINT32 i = 0; i < numDevices; ++i)
  214442. {
  214443. ComSmartPtr <IMMDevice> device;
  214444. if (! OK (deviceCollection->Item (i, &device)))
  214445. continue;
  214446. const String deviceId (wasapi_getDeviceID (device));
  214447. DWORD state = 0;
  214448. if (! OK (device->GetState (&state)))
  214449. continue;
  214450. if (state != DEVICE_STATE_ACTIVE)
  214451. continue;
  214452. String name;
  214453. {
  214454. ComSmartPtr <IPropertyStore> properties;
  214455. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  214456. continue;
  214457. PROPVARIANT value;
  214458. PropVariantInit (&value);
  214459. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  214460. name = value.pwszVal;
  214461. PropVariantClear (&value);
  214462. }
  214463. const EDataFlow flow = wasapi_getDataFlow (device);
  214464. if (flow == eRender)
  214465. {
  214466. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  214467. outputDeviceIds.insert (index, deviceId);
  214468. outputDeviceNames.insert (index, name);
  214469. }
  214470. else if (flow == eCapture)
  214471. {
  214472. const int index = (deviceId == defaultCapture) ? 0 : -1;
  214473. inputDeviceIds.insert (index, deviceId);
  214474. inputDeviceNames.insert (index, name);
  214475. }
  214476. }
  214477. inputDeviceNames.appendNumbersToDuplicates (false, false);
  214478. outputDeviceNames.appendNumbersToDuplicates (false, false);
  214479. }
  214480. const StringArray getDeviceNames (bool wantInputNames) const
  214481. {
  214482. jassert (hasScanned); // need to call scanForDevices() before doing this
  214483. return wantInputNames ? inputDeviceNames
  214484. : outputDeviceNames;
  214485. }
  214486. int getDefaultDeviceIndex (bool /*forInput*/) const
  214487. {
  214488. jassert (hasScanned); // need to call scanForDevices() before doing this
  214489. return 0;
  214490. }
  214491. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214492. {
  214493. jassert (hasScanned); // need to call scanForDevices() before doing this
  214494. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  214495. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  214496. : outputDeviceIds.indexOf (d->outputDeviceId));
  214497. }
  214498. bool hasSeparateInputsAndOutputs() const { return true; }
  214499. AudioIODevice* createDevice (const String& outputDeviceName,
  214500. const String& inputDeviceName)
  214501. {
  214502. jassert (hasScanned); // need to call scanForDevices() before doing this
  214503. const bool useExclusiveMode = false;
  214504. ScopedPointer<WASAPIAudioIODevice> device;
  214505. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214506. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214507. if (outputIndex >= 0 || inputIndex >= 0)
  214508. {
  214509. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214510. : inputDeviceName,
  214511. outputDeviceIds [outputIndex],
  214512. inputDeviceIds [inputIndex],
  214513. useExclusiveMode);
  214514. if (! device->initialise())
  214515. device = 0;
  214516. }
  214517. return device.release();
  214518. }
  214519. juce_UseDebuggingNewOperator
  214520. StringArray outputDeviceNames, outputDeviceIds;
  214521. StringArray inputDeviceNames, inputDeviceIds;
  214522. private:
  214523. bool hasScanned;
  214524. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  214525. {
  214526. String s;
  214527. IMMDevice* dev = 0;
  214528. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  214529. eMultimedia, &dev)))
  214530. {
  214531. WCHAR* deviceId = 0;
  214532. if (OK (dev->GetId (&deviceId)))
  214533. {
  214534. s = String (deviceId);
  214535. CoTaskMemFree (deviceId);
  214536. }
  214537. dev->Release();
  214538. }
  214539. return s;
  214540. }
  214541. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  214542. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  214543. };
  214544. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  214545. {
  214546. return new WASAPIAudioIODeviceType();
  214547. }
  214548. #undef logFailure
  214549. #undef OK
  214550. #endif
  214551. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  214552. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  214553. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214554. // compiled on its own).
  214555. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  214556. class DShowCameraDeviceInteral : public ChangeBroadcaster
  214557. {
  214558. public:
  214559. DShowCameraDeviceInteral (CameraDevice* const owner_,
  214560. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  214561. const ComSmartPtr <IBaseFilter>& filter_,
  214562. int minWidth, int minHeight,
  214563. int maxWidth, int maxHeight)
  214564. : owner (owner_),
  214565. captureGraphBuilder (captureGraphBuilder_),
  214566. filter (filter_),
  214567. ok (false),
  214568. imageNeedsFlipping (false),
  214569. width (0),
  214570. height (0),
  214571. activeUsers (0),
  214572. recordNextFrameTime (false)
  214573. {
  214574. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  214575. if (FAILED (hr))
  214576. return;
  214577. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  214578. if (FAILED (hr))
  214579. return;
  214580. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  214581. if (FAILED (hr))
  214582. return;
  214583. {
  214584. ComSmartPtr <IAMStreamConfig> streamConfig;
  214585. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  214586. IID_IAMStreamConfig, (void**) &streamConfig);
  214587. if (streamConfig != 0)
  214588. {
  214589. getVideoSizes (streamConfig);
  214590. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  214591. return;
  214592. }
  214593. }
  214594. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  214595. if (FAILED (hr))
  214596. return;
  214597. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  214598. if (FAILED (hr))
  214599. return;
  214600. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  214601. if (FAILED (hr))
  214602. return;
  214603. if (! connectFilters (filter, smartTee))
  214604. return;
  214605. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  214606. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  214607. if (FAILED (hr))
  214608. return;
  214609. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  214610. if (FAILED (hr))
  214611. return;
  214612. AM_MEDIA_TYPE mt;
  214613. zerostruct (mt);
  214614. mt.majortype = MEDIATYPE_Video;
  214615. mt.subtype = MEDIASUBTYPE_RGB24;
  214616. mt.formattype = FORMAT_VideoInfo;
  214617. sampleGrabber->SetMediaType (&mt);
  214618. callback = new GrabberCallback (*this);
  214619. sampleGrabber->SetCallback (callback, 1);
  214620. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  214621. if (FAILED (hr))
  214622. return;
  214623. ComSmartPtr <IPin> grabberInputPin;
  214624. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  214625. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  214626. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  214627. return;
  214628. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  214629. if (FAILED (hr))
  214630. return;
  214631. zerostruct (mt);
  214632. hr = sampleGrabber->GetConnectedMediaType (&mt);
  214633. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  214634. width = pVih->bmiHeader.biWidth;
  214635. height = pVih->bmiHeader.biHeight;
  214636. ComSmartPtr <IBaseFilter> nullFilter;
  214637. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  214638. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  214639. if (connectFilters (sampleGrabberBase, nullFilter)
  214640. && addGraphToRot())
  214641. {
  214642. activeImage = Image (Image::RGB, width, height, true);
  214643. loadingImage = Image (Image::RGB, width, height, true);
  214644. ok = true;
  214645. }
  214646. }
  214647. ~DShowCameraDeviceInteral()
  214648. {
  214649. if (mediaControl != 0)
  214650. mediaControl->Stop();
  214651. removeGraphFromRot();
  214652. for (int i = viewerComps.size(); --i >= 0;)
  214653. viewerComps.getUnchecked(i)->ownerDeleted();
  214654. callback = 0;
  214655. graphBuilder = 0;
  214656. sampleGrabber = 0;
  214657. mediaControl = 0;
  214658. filter = 0;
  214659. captureGraphBuilder = 0;
  214660. smartTee = 0;
  214661. smartTeePreviewOutputPin = 0;
  214662. smartTeeCaptureOutputPin = 0;
  214663. asfWriter = 0;
  214664. }
  214665. void addUser()
  214666. {
  214667. if (ok && activeUsers++ == 0)
  214668. mediaControl->Run();
  214669. }
  214670. void removeUser()
  214671. {
  214672. if (ok && --activeUsers == 0)
  214673. mediaControl->Stop();
  214674. }
  214675. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  214676. {
  214677. if (recordNextFrameTime)
  214678. {
  214679. const double defaultCameraLatency = 0.1;
  214680. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  214681. recordNextFrameTime = false;
  214682. ComSmartPtr <IPin> pin;
  214683. if (getPin (filter, PINDIR_OUTPUT, &pin))
  214684. {
  214685. ComSmartPtr <IAMPushSource> pushSource;
  214686. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  214687. if (pushSource != 0)
  214688. {
  214689. REFERENCE_TIME latency = 0;
  214690. hr = pushSource->GetLatency (&latency);
  214691. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  214692. }
  214693. }
  214694. }
  214695. {
  214696. const int lineStride = width * 3;
  214697. const ScopedLock sl (imageSwapLock);
  214698. {
  214699. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  214700. for (int i = 0; i < height; ++i)
  214701. memcpy (destData.getLinePointer ((height - 1) - i),
  214702. buffer + lineStride * i,
  214703. lineStride);
  214704. }
  214705. imageNeedsFlipping = true;
  214706. }
  214707. if (listeners.size() > 0)
  214708. callListeners (loadingImage);
  214709. sendChangeMessage (this);
  214710. }
  214711. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  214712. {
  214713. if (imageNeedsFlipping)
  214714. {
  214715. const ScopedLock sl (imageSwapLock);
  214716. swapVariables (loadingImage, activeImage);
  214717. imageNeedsFlipping = false;
  214718. }
  214719. RectanglePlacement rp (RectanglePlacement::centred);
  214720. double dx = 0, dy = 0, dw = width, dh = height;
  214721. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  214722. const int rx = roundToInt (dx), ry = roundToInt (dy);
  214723. const int rw = roundToInt (dw), rh = roundToInt (dh);
  214724. g.saveState();
  214725. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  214726. g.fillAll (Colours::black);
  214727. g.restoreState();
  214728. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  214729. }
  214730. bool createFileCaptureFilter (const File& file)
  214731. {
  214732. removeFileCaptureFilter();
  214733. file.deleteFile();
  214734. mediaControl->Stop();
  214735. firstRecordedTime = Time();
  214736. recordNextFrameTime = true;
  214737. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  214738. if (SUCCEEDED (hr))
  214739. {
  214740. ComSmartPtr <IFileSinkFilter> fileSink;
  214741. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  214742. if (SUCCEEDED (hr))
  214743. {
  214744. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  214745. if (SUCCEEDED (hr))
  214746. {
  214747. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  214748. if (SUCCEEDED (hr))
  214749. {
  214750. ComSmartPtr <IConfigAsfWriter> asfConfig;
  214751. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  214752. asfConfig->SetIndexMode (true);
  214753. ComSmartPtr <IWMProfileManager> profileManager;
  214754. hr = WMCreateProfileManager (&profileManager);
  214755. // This gibberish is the DirectShow profile for a video-only wmv file.
  214756. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  214757. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  214758. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  214759. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  214760. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  214761. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  214762. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  214763. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  214764. prof = prof.replace ("$WIDTH", String (width))
  214765. .replace ("$HEIGHT", String (height));
  214766. ComSmartPtr <IWMProfile> currentProfile;
  214767. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  214768. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  214769. if (SUCCEEDED (hr))
  214770. {
  214771. ComSmartPtr <IPin> asfWriterInputPin;
  214772. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  214773. {
  214774. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  214775. if (SUCCEEDED (hr)
  214776. && ok && activeUsers > 0
  214777. && SUCCEEDED (mediaControl->Run()))
  214778. {
  214779. return true;
  214780. }
  214781. }
  214782. }
  214783. }
  214784. }
  214785. }
  214786. }
  214787. removeFileCaptureFilter();
  214788. if (ok && activeUsers > 0)
  214789. mediaControl->Run();
  214790. return false;
  214791. }
  214792. void removeFileCaptureFilter()
  214793. {
  214794. mediaControl->Stop();
  214795. if (asfWriter != 0)
  214796. {
  214797. graphBuilder->RemoveFilter (asfWriter);
  214798. asfWriter = 0;
  214799. }
  214800. if (ok && activeUsers > 0)
  214801. mediaControl->Run();
  214802. }
  214803. void addListener (CameraImageListener* listenerToAdd)
  214804. {
  214805. const ScopedLock sl (listenerLock);
  214806. if (listeners.size() == 0)
  214807. addUser();
  214808. listeners.addIfNotAlreadyThere (listenerToAdd);
  214809. }
  214810. void removeListener (CameraImageListener* listenerToRemove)
  214811. {
  214812. const ScopedLock sl (listenerLock);
  214813. listeners.removeValue (listenerToRemove);
  214814. if (listeners.size() == 0)
  214815. removeUser();
  214816. }
  214817. void callListeners (const Image& image)
  214818. {
  214819. const ScopedLock sl (listenerLock);
  214820. for (int i = listeners.size(); --i >= 0;)
  214821. {
  214822. CameraImageListener* const l = listeners[i];
  214823. if (l != 0)
  214824. l->imageReceived (image);
  214825. }
  214826. }
  214827. class DShowCaptureViewerComp : public Component,
  214828. public ChangeListener
  214829. {
  214830. public:
  214831. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  214832. : owner (owner_)
  214833. {
  214834. setOpaque (true);
  214835. owner->addChangeListener (this);
  214836. owner->addUser();
  214837. owner->viewerComps.add (this);
  214838. setSize (owner_->width, owner_->height);
  214839. }
  214840. ~DShowCaptureViewerComp()
  214841. {
  214842. if (owner != 0)
  214843. {
  214844. owner->viewerComps.removeValue (this);
  214845. owner->removeUser();
  214846. owner->removeChangeListener (this);
  214847. }
  214848. }
  214849. void ownerDeleted()
  214850. {
  214851. owner = 0;
  214852. }
  214853. void paint (Graphics& g)
  214854. {
  214855. g.setColour (Colours::black);
  214856. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  214857. if (owner != 0)
  214858. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  214859. else
  214860. g.fillAll (Colours::black);
  214861. }
  214862. void changeListenerCallback (void*)
  214863. {
  214864. repaint();
  214865. }
  214866. private:
  214867. DShowCameraDeviceInteral* owner;
  214868. };
  214869. bool ok;
  214870. int width, height;
  214871. Time firstRecordedTime;
  214872. Array <DShowCaptureViewerComp*> viewerComps;
  214873. private:
  214874. CameraDevice* const owner;
  214875. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  214876. ComSmartPtr <IBaseFilter> filter;
  214877. ComSmartPtr <IBaseFilter> smartTee;
  214878. ComSmartPtr <IGraphBuilder> graphBuilder;
  214879. ComSmartPtr <ISampleGrabber> sampleGrabber;
  214880. ComSmartPtr <IMediaControl> mediaControl;
  214881. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  214882. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  214883. ComSmartPtr <IBaseFilter> asfWriter;
  214884. int activeUsers;
  214885. Array <int> widths, heights;
  214886. DWORD graphRegistrationID;
  214887. CriticalSection imageSwapLock;
  214888. bool imageNeedsFlipping;
  214889. Image loadingImage;
  214890. Image activeImage;
  214891. bool recordNextFrameTime;
  214892. void getVideoSizes (IAMStreamConfig* const streamConfig)
  214893. {
  214894. widths.clear();
  214895. heights.clear();
  214896. int count = 0, size = 0;
  214897. streamConfig->GetNumberOfCapabilities (&count, &size);
  214898. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  214899. {
  214900. for (int i = 0; i < count; ++i)
  214901. {
  214902. VIDEO_STREAM_CONFIG_CAPS scc;
  214903. AM_MEDIA_TYPE* config;
  214904. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  214905. if (SUCCEEDED (hr))
  214906. {
  214907. const int w = scc.InputSize.cx;
  214908. const int h = scc.InputSize.cy;
  214909. bool duplicate = false;
  214910. for (int j = widths.size(); --j >= 0;)
  214911. {
  214912. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  214913. {
  214914. duplicate = true;
  214915. break;
  214916. }
  214917. }
  214918. if (! duplicate)
  214919. {
  214920. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  214921. widths.add (w);
  214922. heights.add (h);
  214923. }
  214924. deleteMediaType (config);
  214925. }
  214926. }
  214927. }
  214928. }
  214929. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  214930. const int minWidth, const int minHeight,
  214931. const int maxWidth, const int maxHeight)
  214932. {
  214933. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  214934. streamConfig->GetNumberOfCapabilities (&count, &size);
  214935. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  214936. {
  214937. AM_MEDIA_TYPE* config;
  214938. VIDEO_STREAM_CONFIG_CAPS scc;
  214939. for (int i = 0; i < count; ++i)
  214940. {
  214941. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  214942. if (SUCCEEDED (hr))
  214943. {
  214944. if (scc.InputSize.cx >= minWidth
  214945. && scc.InputSize.cy >= minHeight
  214946. && scc.InputSize.cx <= maxWidth
  214947. && scc.InputSize.cy <= maxHeight)
  214948. {
  214949. int area = scc.InputSize.cx * scc.InputSize.cy;
  214950. if (area > bestArea)
  214951. {
  214952. bestIndex = i;
  214953. bestArea = area;
  214954. }
  214955. }
  214956. deleteMediaType (config);
  214957. }
  214958. }
  214959. if (bestIndex >= 0)
  214960. {
  214961. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  214962. hr = streamConfig->SetFormat (config);
  214963. deleteMediaType (config);
  214964. return SUCCEEDED (hr);
  214965. }
  214966. }
  214967. return false;
  214968. }
  214969. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  214970. {
  214971. ComSmartPtr <IEnumPins> enumerator;
  214972. ComSmartPtr <IPin> pin;
  214973. filter->EnumPins (&enumerator);
  214974. while (enumerator->Next (1, &pin, 0) == S_OK)
  214975. {
  214976. PIN_DIRECTION dir;
  214977. pin->QueryDirection (&dir);
  214978. if (wantedDirection == dir)
  214979. {
  214980. PIN_INFO info;
  214981. zerostruct (info);
  214982. pin->QueryPinInfo (&info);
  214983. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  214984. {
  214985. pin->AddRef();
  214986. *result = pin;
  214987. return true;
  214988. }
  214989. }
  214990. }
  214991. return false;
  214992. }
  214993. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  214994. {
  214995. ComSmartPtr <IPin> in, out;
  214996. return getPin (first, PINDIR_OUTPUT, &out)
  214997. && getPin (second, PINDIR_INPUT, &in)
  214998. && SUCCEEDED (graphBuilder->Connect (out, in));
  214999. }
  215000. bool addGraphToRot()
  215001. {
  215002. ComSmartPtr <IRunningObjectTable> rot;
  215003. if (FAILED (GetRunningObjectTable (0, &rot)))
  215004. return false;
  215005. ComSmartPtr <IMoniker> moniker;
  215006. WCHAR buffer[128];
  215007. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  215008. if (FAILED (hr))
  215009. return false;
  215010. graphRegistrationID = 0;
  215011. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215012. }
  215013. void removeGraphFromRot()
  215014. {
  215015. ComSmartPtr <IRunningObjectTable> rot;
  215016. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  215017. rot->Revoke (graphRegistrationID);
  215018. }
  215019. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215020. {
  215021. if (pmt->cbFormat != 0)
  215022. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215023. if (pmt->pUnk != 0)
  215024. pmt->pUnk->Release();
  215025. CoTaskMemFree (pmt);
  215026. }
  215027. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215028. {
  215029. public:
  215030. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215031. : owner (owner_)
  215032. {
  215033. }
  215034. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215035. {
  215036. return E_FAIL;
  215037. }
  215038. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215039. {
  215040. owner.handleFrame (time, buffer, bufferSize);
  215041. return S_OK;
  215042. }
  215043. private:
  215044. DShowCameraDeviceInteral& owner;
  215045. GrabberCallback (const GrabberCallback&);
  215046. GrabberCallback& operator= (const GrabberCallback&);
  215047. };
  215048. ComSmartPtr <GrabberCallback> callback;
  215049. Array <CameraImageListener*> listeners;
  215050. CriticalSection listenerLock;
  215051. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  215052. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  215053. };
  215054. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215055. : name (name_)
  215056. {
  215057. isRecording = false;
  215058. }
  215059. CameraDevice::~CameraDevice()
  215060. {
  215061. stopRecording();
  215062. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215063. internal = 0;
  215064. }
  215065. Component* CameraDevice::createViewerComponent()
  215066. {
  215067. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215068. }
  215069. const String CameraDevice::getFileExtension()
  215070. {
  215071. return ".wmv";
  215072. }
  215073. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215074. {
  215075. stopRecording();
  215076. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215077. d->addUser();
  215078. isRecording = d->createFileCaptureFilter (file);
  215079. }
  215080. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215081. {
  215082. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215083. return d->firstRecordedTime;
  215084. }
  215085. void CameraDevice::stopRecording()
  215086. {
  215087. if (isRecording)
  215088. {
  215089. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215090. d->removeFileCaptureFilter();
  215091. d->removeUser();
  215092. isRecording = false;
  215093. }
  215094. }
  215095. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  215096. {
  215097. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215098. if (listenerToAdd != 0)
  215099. d->addListener (listenerToAdd);
  215100. }
  215101. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  215102. {
  215103. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215104. if (listenerToRemove != 0)
  215105. d->removeListener (listenerToRemove);
  215106. }
  215107. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215108. const int deviceIndexToOpen,
  215109. String& name)
  215110. {
  215111. int index = 0;
  215112. ComSmartPtr <IBaseFilter> result;
  215113. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215114. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215115. if (SUCCEEDED (hr))
  215116. {
  215117. ComSmartPtr <IEnumMoniker> enumerator;
  215118. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  215119. if (SUCCEEDED (hr) && enumerator != 0)
  215120. {
  215121. ComSmartPtr <IBaseFilter> captureFilter;
  215122. ComSmartPtr <IMoniker> moniker;
  215123. ULONG fetched;
  215124. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  215125. {
  215126. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  215127. if (SUCCEEDED (hr))
  215128. {
  215129. ComSmartPtr <IPropertyBag> propertyBag;
  215130. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  215131. if (SUCCEEDED (hr))
  215132. {
  215133. VARIANT var;
  215134. var.vt = VT_BSTR;
  215135. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215136. propertyBag = 0;
  215137. if (SUCCEEDED (hr))
  215138. {
  215139. if (names != 0)
  215140. names->add (var.bstrVal);
  215141. if (index == deviceIndexToOpen)
  215142. {
  215143. name = var.bstrVal;
  215144. result = captureFilter;
  215145. captureFilter = 0;
  215146. break;
  215147. }
  215148. ++index;
  215149. }
  215150. moniker = 0;
  215151. }
  215152. captureFilter = 0;
  215153. }
  215154. }
  215155. }
  215156. }
  215157. return result;
  215158. }
  215159. const StringArray CameraDevice::getAvailableDevices()
  215160. {
  215161. StringArray devs;
  215162. String dummy;
  215163. enumerateCameras (&devs, -1, dummy);
  215164. return devs;
  215165. }
  215166. CameraDevice* CameraDevice::openDevice (int index,
  215167. int minWidth, int minHeight,
  215168. int maxWidth, int maxHeight)
  215169. {
  215170. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215171. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  215172. if (SUCCEEDED (hr))
  215173. {
  215174. String name;
  215175. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  215176. if (filter != 0)
  215177. {
  215178. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  215179. DShowCameraDeviceInteral* const intern
  215180. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  215181. minWidth, minHeight, maxWidth, maxHeight);
  215182. cam->internal = intern;
  215183. if (intern->ok)
  215184. return cam.release();
  215185. }
  215186. }
  215187. return 0;
  215188. }
  215189. #endif
  215190. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  215191. #endif
  215192. // Auto-link the other win32 libs that are needed by library calls..
  215193. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  215194. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215195. // Auto-links to various win32 libs that are needed by library calls..
  215196. #pragma comment(lib, "kernel32.lib")
  215197. #pragma comment(lib, "user32.lib")
  215198. #pragma comment(lib, "shell32.lib")
  215199. #pragma comment(lib, "gdi32.lib")
  215200. #pragma comment(lib, "vfw32.lib")
  215201. #pragma comment(lib, "comdlg32.lib")
  215202. #pragma comment(lib, "winmm.lib")
  215203. #pragma comment(lib, "wininet.lib")
  215204. #pragma comment(lib, "ole32.lib")
  215205. #pragma comment(lib, "oleaut32.lib")
  215206. #pragma comment(lib, "advapi32.lib")
  215207. #pragma comment(lib, "ws2_32.lib")
  215208. #pragma comment(lib, "comsupp.lib")
  215209. #pragma comment(lib, "version.lib")
  215210. #if JUCE_OPENGL
  215211. #pragma comment(lib, "OpenGL32.Lib")
  215212. #pragma comment(lib, "GlU32.Lib")
  215213. #endif
  215214. #if JUCE_QUICKTIME
  215215. #pragma comment (lib, "QTMLClient.lib")
  215216. #endif
  215217. #if JUCE_USE_CAMERA
  215218. #pragma comment (lib, "Strmiids.lib")
  215219. #pragma comment (lib, "wmvcore.lib")
  215220. #endif
  215221. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215222. #endif
  215223. END_JUCE_NAMESPACE
  215224. #endif
  215225. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  215226. #endif
  215227. #if JUCE_LINUX
  215228. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  215229. /*
  215230. This file wraps together all the mac-specific code, so that
  215231. we can include all the native headers just once, and compile all our
  215232. platform-specific stuff in one big lump, keeping it out of the way of
  215233. the rest of the codebase.
  215234. */
  215235. #if JUCE_LINUX
  215236. BEGIN_JUCE_NAMESPACE
  215237. #define JUCE_INCLUDED_FILE 1
  215238. // Now include the actual code files..
  215239. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  215240. /*
  215241. This file contains posix routines that are common to both the Linux and Mac builds.
  215242. It gets included directly in the cpp files for these platforms.
  215243. */
  215244. CriticalSection::CriticalSection() throw()
  215245. {
  215246. pthread_mutexattr_t atts;
  215247. pthread_mutexattr_init (&atts);
  215248. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  215249. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215250. pthread_mutex_init (&internal, &atts);
  215251. }
  215252. CriticalSection::~CriticalSection() throw()
  215253. {
  215254. pthread_mutex_destroy (&internal);
  215255. }
  215256. void CriticalSection::enter() const throw()
  215257. {
  215258. pthread_mutex_lock (&internal);
  215259. }
  215260. bool CriticalSection::tryEnter() const throw()
  215261. {
  215262. return pthread_mutex_trylock (&internal) == 0;
  215263. }
  215264. void CriticalSection::exit() const throw()
  215265. {
  215266. pthread_mutex_unlock (&internal);
  215267. }
  215268. class WaitableEventImpl
  215269. {
  215270. public:
  215271. WaitableEventImpl (const bool manualReset_)
  215272. : triggered (false),
  215273. manualReset (manualReset_)
  215274. {
  215275. pthread_cond_init (&condition, 0);
  215276. pthread_mutex_init (&mutex, 0);
  215277. }
  215278. ~WaitableEventImpl()
  215279. {
  215280. pthread_cond_destroy (&condition);
  215281. pthread_mutex_destroy (&mutex);
  215282. }
  215283. bool wait (const int timeOutMillisecs) throw()
  215284. {
  215285. pthread_mutex_lock (&mutex);
  215286. if (! triggered)
  215287. {
  215288. if (timeOutMillisecs < 0)
  215289. {
  215290. do
  215291. {
  215292. pthread_cond_wait (&condition, &mutex);
  215293. }
  215294. while (! triggered);
  215295. }
  215296. else
  215297. {
  215298. struct timeval now;
  215299. gettimeofday (&now, 0);
  215300. struct timespec time;
  215301. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  215302. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  215303. if (time.tv_nsec >= 1000000000)
  215304. {
  215305. time.tv_nsec -= 1000000000;
  215306. time.tv_sec++;
  215307. }
  215308. do
  215309. {
  215310. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  215311. {
  215312. pthread_mutex_unlock (&mutex);
  215313. return false;
  215314. }
  215315. }
  215316. while (! triggered);
  215317. }
  215318. }
  215319. if (! manualReset)
  215320. triggered = false;
  215321. pthread_mutex_unlock (&mutex);
  215322. return true;
  215323. }
  215324. void signal() throw()
  215325. {
  215326. pthread_mutex_lock (&mutex);
  215327. triggered = true;
  215328. pthread_cond_broadcast (&condition);
  215329. pthread_mutex_unlock (&mutex);
  215330. }
  215331. void reset() throw()
  215332. {
  215333. pthread_mutex_lock (&mutex);
  215334. triggered = false;
  215335. pthread_mutex_unlock (&mutex);
  215336. }
  215337. private:
  215338. pthread_cond_t condition;
  215339. pthread_mutex_t mutex;
  215340. bool triggered;
  215341. const bool manualReset;
  215342. WaitableEventImpl (const WaitableEventImpl&);
  215343. WaitableEventImpl& operator= (const WaitableEventImpl&);
  215344. };
  215345. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  215346. : internal (new WaitableEventImpl (manualReset))
  215347. {
  215348. }
  215349. WaitableEvent::~WaitableEvent() throw()
  215350. {
  215351. delete static_cast <WaitableEventImpl*> (internal);
  215352. }
  215353. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  215354. {
  215355. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  215356. }
  215357. void WaitableEvent::signal() const throw()
  215358. {
  215359. static_cast <WaitableEventImpl*> (internal)->signal();
  215360. }
  215361. void WaitableEvent::reset() const throw()
  215362. {
  215363. static_cast <WaitableEventImpl*> (internal)->reset();
  215364. }
  215365. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  215366. {
  215367. struct timespec time;
  215368. time.tv_sec = millisecs / 1000;
  215369. time.tv_nsec = (millisecs % 1000) * 1000000;
  215370. nanosleep (&time, 0);
  215371. }
  215372. const juce_wchar File::separator = '/';
  215373. const String File::separatorString ("/");
  215374. const File File::getCurrentWorkingDirectory()
  215375. {
  215376. HeapBlock<char> heapBuffer;
  215377. char localBuffer [1024];
  215378. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  215379. int bufferSize = 4096;
  215380. while (cwd == 0 && errno == ERANGE)
  215381. {
  215382. heapBuffer.malloc (bufferSize);
  215383. cwd = getcwd (heapBuffer, bufferSize - 1);
  215384. bufferSize += 1024;
  215385. }
  215386. return File (String::fromUTF8 (cwd));
  215387. }
  215388. bool File::setAsCurrentWorkingDirectory() const
  215389. {
  215390. return chdir (getFullPathName().toUTF8()) == 0;
  215391. }
  215392. static bool juce_stat (const String& fileName, struct stat& info)
  215393. {
  215394. return fileName.isNotEmpty()
  215395. && (stat (fileName.toUTF8(), &info) == 0);
  215396. }
  215397. bool File::isDirectory() const
  215398. {
  215399. struct stat info;
  215400. return fullPath.isEmpty()
  215401. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  215402. }
  215403. bool File::exists() const
  215404. {
  215405. return fullPath.isNotEmpty()
  215406. && access (fullPath.toUTF8(), F_OK) == 0;
  215407. }
  215408. bool File::existsAsFile() const
  215409. {
  215410. return exists() && ! isDirectory();
  215411. }
  215412. int64 File::getSize() const
  215413. {
  215414. struct stat info;
  215415. return juce_stat (fullPath, info) ? info.st_size : 0;
  215416. }
  215417. bool File::hasWriteAccess() const
  215418. {
  215419. if (exists())
  215420. return access (fullPath.toUTF8(), W_OK) == 0;
  215421. if ((! isDirectory()) && fullPath.containsChar (separator))
  215422. return getParentDirectory().hasWriteAccess();
  215423. return false;
  215424. }
  215425. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  215426. {
  215427. struct stat info;
  215428. const int res = stat (fullPath.toUTF8(), &info);
  215429. if (res != 0)
  215430. return false;
  215431. info.st_mode &= 0777; // Just permissions
  215432. if (shouldBeReadOnly)
  215433. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  215434. else
  215435. // Give everybody write permission?
  215436. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  215437. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  215438. }
  215439. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  215440. {
  215441. modificationTime = 0;
  215442. accessTime = 0;
  215443. creationTime = 0;
  215444. struct stat info;
  215445. const int res = stat (fullPath.toUTF8(), &info);
  215446. if (res == 0)
  215447. {
  215448. modificationTime = (int64) info.st_mtime * 1000;
  215449. accessTime = (int64) info.st_atime * 1000;
  215450. creationTime = (int64) info.st_ctime * 1000;
  215451. }
  215452. }
  215453. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  215454. {
  215455. struct utimbuf times;
  215456. times.actime = (time_t) (accessTime / 1000);
  215457. times.modtime = (time_t) (modificationTime / 1000);
  215458. return utime (fullPath.toUTF8(), &times) == 0;
  215459. }
  215460. bool File::deleteFile() const
  215461. {
  215462. if (! exists())
  215463. return true;
  215464. else if (isDirectory())
  215465. return rmdir (fullPath.toUTF8()) == 0;
  215466. else
  215467. return remove (fullPath.toUTF8()) == 0;
  215468. }
  215469. bool File::moveInternal (const File& dest) const
  215470. {
  215471. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  215472. return true;
  215473. if (hasWriteAccess() && copyInternal (dest))
  215474. {
  215475. if (deleteFile())
  215476. return true;
  215477. dest.deleteFile();
  215478. }
  215479. return false;
  215480. }
  215481. void File::createDirectoryInternal (const String& fileName) const
  215482. {
  215483. mkdir (fileName.toUTF8(), 0777);
  215484. }
  215485. void* juce_fileOpen (const File& file, bool forWriting)
  215486. {
  215487. int flags = O_RDONLY;
  215488. if (forWriting)
  215489. {
  215490. if (file.exists())
  215491. {
  215492. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  215493. if (f != -1)
  215494. lseek (f, 0, SEEK_END);
  215495. return (void*) f;
  215496. }
  215497. else
  215498. {
  215499. flags = O_RDWR + O_CREAT;
  215500. }
  215501. }
  215502. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  215503. }
  215504. void juce_fileClose (void* handle)
  215505. {
  215506. if (handle != 0)
  215507. close ((int) (pointer_sized_int) handle);
  215508. }
  215509. int juce_fileRead (void* handle, void* buffer, int size)
  215510. {
  215511. if (handle != 0)
  215512. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  215513. return 0;
  215514. }
  215515. int juce_fileWrite (void* handle, const void* buffer, int size)
  215516. {
  215517. if (handle != 0)
  215518. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  215519. return 0;
  215520. }
  215521. int64 juce_fileSetPosition (void* handle, int64 pos)
  215522. {
  215523. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  215524. return pos;
  215525. return -1;
  215526. }
  215527. int64 FileOutputStream::getPositionInternal() const
  215528. {
  215529. if (fileHandle != 0)
  215530. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  215531. return -1;
  215532. }
  215533. void FileOutputStream::flushInternal()
  215534. {
  215535. if (fileHandle != 0)
  215536. fsync ((int) (pointer_sized_int) fileHandle);
  215537. }
  215538. const File juce_getExecutableFile()
  215539. {
  215540. Dl_info exeInfo;
  215541. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  215542. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  215543. }
  215544. // if this file doesn't exist, find a parent of it that does..
  215545. static bool juce_doStatFS (File f, struct statfs& result)
  215546. {
  215547. for (int i = 5; --i >= 0;)
  215548. {
  215549. if (f.exists())
  215550. break;
  215551. f = f.getParentDirectory();
  215552. }
  215553. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  215554. }
  215555. int64 File::getBytesFreeOnVolume() const
  215556. {
  215557. struct statfs buf;
  215558. if (juce_doStatFS (*this, buf))
  215559. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  215560. return 0;
  215561. }
  215562. int64 File::getVolumeTotalSize() const
  215563. {
  215564. struct statfs buf;
  215565. if (juce_doStatFS (*this, buf))
  215566. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  215567. return 0;
  215568. }
  215569. const String File::getVolumeLabel() const
  215570. {
  215571. #if JUCE_MAC
  215572. struct VolAttrBuf
  215573. {
  215574. u_int32_t length;
  215575. attrreference_t mountPointRef;
  215576. char mountPointSpace [MAXPATHLEN];
  215577. } attrBuf;
  215578. struct attrlist attrList;
  215579. zerostruct (attrList);
  215580. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  215581. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  215582. File f (*this);
  215583. for (;;)
  215584. {
  215585. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  215586. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  215587. (int) attrBuf.mountPointRef.attr_length);
  215588. const File parent (f.getParentDirectory());
  215589. if (f == parent)
  215590. break;
  215591. f = parent;
  215592. }
  215593. #endif
  215594. return String::empty;
  215595. }
  215596. int File::getVolumeSerialNumber() const
  215597. {
  215598. return 0; // xxx
  215599. }
  215600. void juce_runSystemCommand (const String& command)
  215601. {
  215602. int result = system (command.toUTF8());
  215603. (void) result;
  215604. }
  215605. const String juce_getOutputFromCommand (const String& command)
  215606. {
  215607. // slight bodge here, as we just pipe the output into a temp file and read it...
  215608. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  215609. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  215610. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  215611. String result (tempFile.loadFileAsString());
  215612. tempFile.deleteFile();
  215613. return result;
  215614. }
  215615. class InterProcessLock::Pimpl
  215616. {
  215617. public:
  215618. Pimpl (const String& name, const int timeOutMillisecs)
  215619. : handle (0), refCount (1)
  215620. {
  215621. #if JUCE_MAC
  215622. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  215623. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  215624. #else
  215625. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  215626. #endif
  215627. temp.create();
  215628. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  215629. if (handle != 0)
  215630. {
  215631. struct flock fl;
  215632. zerostruct (fl);
  215633. fl.l_whence = SEEK_SET;
  215634. fl.l_type = F_WRLCK;
  215635. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  215636. for (;;)
  215637. {
  215638. const int result = fcntl (handle, F_SETLK, &fl);
  215639. if (result >= 0)
  215640. return;
  215641. if (errno != EINTR)
  215642. {
  215643. if (timeOutMillisecs == 0
  215644. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  215645. break;
  215646. Thread::sleep (10);
  215647. }
  215648. }
  215649. }
  215650. closeFile();
  215651. }
  215652. ~Pimpl()
  215653. {
  215654. closeFile();
  215655. }
  215656. void closeFile()
  215657. {
  215658. if (handle != 0)
  215659. {
  215660. struct flock fl;
  215661. zerostruct (fl);
  215662. fl.l_whence = SEEK_SET;
  215663. fl.l_type = F_UNLCK;
  215664. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  215665. {}
  215666. close (handle);
  215667. handle = 0;
  215668. }
  215669. }
  215670. int handle, refCount;
  215671. };
  215672. InterProcessLock::InterProcessLock (const String& name_)
  215673. : name (name_)
  215674. {
  215675. }
  215676. InterProcessLock::~InterProcessLock()
  215677. {
  215678. }
  215679. bool InterProcessLock::enter (const int timeOutMillisecs)
  215680. {
  215681. const ScopedLock sl (lock);
  215682. if (pimpl == 0)
  215683. {
  215684. pimpl = new Pimpl (name, timeOutMillisecs);
  215685. if (pimpl->handle == 0)
  215686. pimpl = 0;
  215687. }
  215688. else
  215689. {
  215690. pimpl->refCount++;
  215691. }
  215692. return pimpl != 0;
  215693. }
  215694. void InterProcessLock::exit()
  215695. {
  215696. const ScopedLock sl (lock);
  215697. // Trying to release the lock too many times!
  215698. jassert (pimpl != 0);
  215699. if (pimpl != 0 && --(pimpl->refCount) == 0)
  215700. pimpl = 0;
  215701. }
  215702. /*** End of inlined file: juce_posix_SharedCode.h ***/
  215703. /*** Start of inlined file: juce_linux_Files.cpp ***/
  215704. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215705. // compiled on its own).
  215706. #if JUCE_INCLUDED_FILE
  215707. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  215708. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  215709. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  215710. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  215711. bool File::copyInternal (const File& dest) const
  215712. {
  215713. FileInputStream in (*this);
  215714. if (dest.deleteFile())
  215715. {
  215716. {
  215717. FileOutputStream out (dest);
  215718. if (out.failedToOpen())
  215719. return false;
  215720. if (out.writeFromInputStream (in, -1) == getSize())
  215721. return true;
  215722. }
  215723. dest.deleteFile();
  215724. }
  215725. return false;
  215726. }
  215727. void File::findFileSystemRoots (Array<File>& destArray)
  215728. {
  215729. destArray.add (File ("/"));
  215730. }
  215731. bool File::isOnCDRomDrive() const
  215732. {
  215733. struct statfs buf;
  215734. return statfs (getFullPathName().toUTF8(), &buf) == 0
  215735. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  215736. }
  215737. bool File::isOnHardDisk() const
  215738. {
  215739. struct statfs buf;
  215740. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  215741. {
  215742. switch (buf.f_type)
  215743. {
  215744. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  215745. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  215746. case U_NFS_SUPER_MAGIC: // Network NFS
  215747. case U_SMB_SUPER_MAGIC: // Network Samba
  215748. return false;
  215749. default:
  215750. // Assume anything else is a hard-disk (but note it could
  215751. // be a RAM disk. There isn't a good way of determining
  215752. // this for sure)
  215753. return true;
  215754. }
  215755. }
  215756. // Assume so if this fails for some reason
  215757. return true;
  215758. }
  215759. bool File::isOnRemovableDrive() const
  215760. {
  215761. jassertfalse; // xxx not implemented for linux!
  215762. return false;
  215763. }
  215764. bool File::isHidden() const
  215765. {
  215766. return getFileName().startsWithChar ('.');
  215767. }
  215768. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  215769. const File File::getSpecialLocation (const SpecialLocationType type)
  215770. {
  215771. switch (type)
  215772. {
  215773. case userHomeDirectory:
  215774. {
  215775. const char* homeDir = getenv ("HOME");
  215776. if (homeDir == 0)
  215777. {
  215778. struct passwd* const pw = getpwuid (getuid());
  215779. if (pw != 0)
  215780. homeDir = pw->pw_dir;
  215781. }
  215782. return File (String::fromUTF8 (homeDir));
  215783. }
  215784. case userDocumentsDirectory:
  215785. case userMusicDirectory:
  215786. case userMoviesDirectory:
  215787. case userApplicationDataDirectory:
  215788. return File ("~");
  215789. case userDesktopDirectory:
  215790. return File ("~/Desktop");
  215791. case commonApplicationDataDirectory:
  215792. return File ("/var");
  215793. case globalApplicationsDirectory:
  215794. return File ("/usr");
  215795. case tempDirectory:
  215796. {
  215797. File tmp ("/var/tmp");
  215798. if (! tmp.isDirectory())
  215799. {
  215800. tmp = "/tmp";
  215801. if (! tmp.isDirectory())
  215802. tmp = File::getCurrentWorkingDirectory();
  215803. }
  215804. return tmp;
  215805. }
  215806. case invokedExecutableFile:
  215807. if (juce_Argv0 != 0)
  215808. return File (String::fromUTF8 (juce_Argv0));
  215809. // deliberate fall-through...
  215810. case currentExecutableFile:
  215811. case currentApplicationFile:
  215812. return juce_getExecutableFile();
  215813. default:
  215814. jassertfalse; // unknown type?
  215815. break;
  215816. }
  215817. return File::nonexistent;
  215818. }
  215819. const String File::getVersion() const
  215820. {
  215821. return String::empty; // xxx not yet implemented
  215822. }
  215823. const File File::getLinkedTarget() const
  215824. {
  215825. char buffer [4096];
  215826. size_t numChars = readlink (getFullPathName().toUTF8(),
  215827. buffer, sizeof (buffer));
  215828. if (numChars > 0 && numChars <= sizeof (buffer))
  215829. return File (String::fromUTF8 (buffer, (int) numChars));
  215830. return *this;
  215831. }
  215832. bool File::moveToTrash() const
  215833. {
  215834. if (! exists())
  215835. return true;
  215836. File trashCan ("~/.Trash");
  215837. if (! trashCan.isDirectory())
  215838. trashCan = "~/.local/share/Trash/files";
  215839. if (! trashCan.isDirectory())
  215840. return false;
  215841. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  215842. getFileExtension()));
  215843. }
  215844. class DirectoryIterator::NativeIterator::Pimpl
  215845. {
  215846. public:
  215847. Pimpl (const File& directory, const String& wildCard_)
  215848. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  215849. wildCard (wildCard_),
  215850. dir (opendir (directory.getFullPathName().toUTF8()))
  215851. {
  215852. if (wildCard == "*.*")
  215853. wildCard = "*";
  215854. wildcardUTF8 = wildCard.toUTF8();
  215855. }
  215856. ~Pimpl()
  215857. {
  215858. if (dir != 0)
  215859. closedir (dir);
  215860. }
  215861. bool next (String& filenameFound,
  215862. bool* const isDir, bool* const isHidden, int64* const fileSize,
  215863. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  215864. {
  215865. if (dir == 0)
  215866. return false;
  215867. for (;;)
  215868. {
  215869. struct dirent* const de = readdir (dir);
  215870. if (de == 0)
  215871. return false;
  215872. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  215873. {
  215874. filenameFound = String::fromUTF8 (de->d_name);
  215875. const String path (parentDir + filenameFound);
  215876. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  215877. {
  215878. struct stat info;
  215879. const bool statOk = juce_stat (path, info);
  215880. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  215881. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  215882. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  215883. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  215884. }
  215885. if (isHidden != 0)
  215886. *isHidden = filenameFound.startsWithChar ('.');
  215887. if (isReadOnly != 0)
  215888. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  215889. return true;
  215890. }
  215891. }
  215892. }
  215893. private:
  215894. String parentDir, wildCard;
  215895. const char* wildcardUTF8;
  215896. DIR* dir;
  215897. Pimpl (const Pimpl&);
  215898. Pimpl& operator= (const Pimpl&);
  215899. };
  215900. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  215901. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  215902. {
  215903. }
  215904. DirectoryIterator::NativeIterator::~NativeIterator()
  215905. {
  215906. }
  215907. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  215908. bool* const isDir, bool* const isHidden, int64* const fileSize,
  215909. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  215910. {
  215911. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  215912. }
  215913. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  215914. {
  215915. String cmdString (fileName.replace (" ", "\\ ",false));
  215916. cmdString << " " << parameters;
  215917. if (URL::isProbablyAWebsiteURL (fileName)
  215918. || cmdString.startsWithIgnoreCase ("file:")
  215919. || URL::isProbablyAnEmailAddress (fileName))
  215920. {
  215921. // create a command that tries to launch a bunch of likely browsers
  215922. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  215923. StringArray cmdLines;
  215924. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  215925. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  215926. cmdString = cmdLines.joinIntoString (" || ");
  215927. }
  215928. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  215929. const int cpid = fork();
  215930. if (cpid == 0)
  215931. {
  215932. setsid();
  215933. // Child process
  215934. execve (argv[0], (char**) argv, environ);
  215935. exit (0);
  215936. }
  215937. return cpid >= 0;
  215938. }
  215939. void File::revealToUser() const
  215940. {
  215941. if (isDirectory())
  215942. startAsProcess();
  215943. else if (getParentDirectory().exists())
  215944. getParentDirectory().startAsProcess();
  215945. }
  215946. #endif
  215947. /*** End of inlined file: juce_linux_Files.cpp ***/
  215948. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  215949. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  215950. // compiled on its own).
  215951. #if JUCE_INCLUDED_FILE
  215952. struct NamedPipeInternal
  215953. {
  215954. String pipeInName, pipeOutName;
  215955. int pipeIn, pipeOut;
  215956. bool volatile createdPipe, blocked, stopReadOperation;
  215957. static void signalHandler (int) {}
  215958. };
  215959. void NamedPipe::cancelPendingReads()
  215960. {
  215961. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  215962. {
  215963. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215964. intern->stopReadOperation = true;
  215965. char buffer [1] = { 0 };
  215966. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  215967. (void) bytesWritten;
  215968. int timeout = 2000;
  215969. while (intern->blocked && --timeout >= 0)
  215970. Thread::sleep (2);
  215971. intern->stopReadOperation = false;
  215972. }
  215973. }
  215974. void NamedPipe::close()
  215975. {
  215976. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215977. if (intern != 0)
  215978. {
  215979. internal = 0;
  215980. if (intern->pipeIn != -1)
  215981. ::close (intern->pipeIn);
  215982. if (intern->pipeOut != -1)
  215983. ::close (intern->pipeOut);
  215984. if (intern->createdPipe)
  215985. {
  215986. unlink (intern->pipeInName.toUTF8());
  215987. unlink (intern->pipeOutName.toUTF8());
  215988. }
  215989. delete intern;
  215990. }
  215991. }
  215992. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  215993. {
  215994. close();
  215995. NamedPipeInternal* const intern = new NamedPipeInternal();
  215996. internal = intern;
  215997. intern->createdPipe = createPipe;
  215998. intern->blocked = false;
  215999. intern->stopReadOperation = false;
  216000. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  216001. siginterrupt (SIGPIPE, 1);
  216002. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  216003. intern->pipeInName = pipePath + "_in";
  216004. intern->pipeOutName = pipePath + "_out";
  216005. intern->pipeIn = -1;
  216006. intern->pipeOut = -1;
  216007. if (createPipe)
  216008. {
  216009. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  216010. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  216011. {
  216012. delete intern;
  216013. internal = 0;
  216014. return false;
  216015. }
  216016. }
  216017. return true;
  216018. }
  216019. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  216020. {
  216021. int bytesRead = -1;
  216022. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216023. if (intern != 0)
  216024. {
  216025. intern->blocked = true;
  216026. if (intern->pipeIn == -1)
  216027. {
  216028. if (intern->createdPipe)
  216029. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  216030. else
  216031. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  216032. if (intern->pipeIn == -1)
  216033. {
  216034. intern->blocked = false;
  216035. return -1;
  216036. }
  216037. }
  216038. bytesRead = 0;
  216039. char* p = (char*) destBuffer;
  216040. while (bytesRead < maxBytesToRead)
  216041. {
  216042. const int bytesThisTime = maxBytesToRead - bytesRead;
  216043. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  216044. if (numRead <= 0 || intern->stopReadOperation)
  216045. {
  216046. bytesRead = -1;
  216047. break;
  216048. }
  216049. bytesRead += numRead;
  216050. p += bytesRead;
  216051. }
  216052. intern->blocked = false;
  216053. }
  216054. return bytesRead;
  216055. }
  216056. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  216057. {
  216058. int bytesWritten = -1;
  216059. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216060. if (intern != 0)
  216061. {
  216062. if (intern->pipeOut == -1)
  216063. {
  216064. if (intern->createdPipe)
  216065. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  216066. else
  216067. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  216068. if (intern->pipeOut == -1)
  216069. {
  216070. return -1;
  216071. }
  216072. }
  216073. const char* p = (const char*) sourceBuffer;
  216074. bytesWritten = 0;
  216075. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  216076. while (bytesWritten < numBytesToWrite
  216077. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  216078. {
  216079. const int bytesThisTime = numBytesToWrite - bytesWritten;
  216080. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  216081. if (numWritten <= 0)
  216082. {
  216083. bytesWritten = -1;
  216084. break;
  216085. }
  216086. bytesWritten += numWritten;
  216087. p += bytesWritten;
  216088. }
  216089. }
  216090. return bytesWritten;
  216091. }
  216092. #endif
  216093. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  216094. /*** Start of inlined file: juce_linux_Network.cpp ***/
  216095. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216096. // compiled on its own).
  216097. #if JUCE_INCLUDED_FILE
  216098. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  216099. {
  216100. int numResults = 0;
  216101. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  216102. if (s != -1)
  216103. {
  216104. char buf [1024];
  216105. struct ifconf ifc;
  216106. ifc.ifc_len = sizeof (buf);
  216107. ifc.ifc_buf = buf;
  216108. ioctl (s, SIOCGIFCONF, &ifc);
  216109. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  216110. {
  216111. struct ifreq ifr;
  216112. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  216113. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  216114. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  216115. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  216116. && numResults < maxNum)
  216117. {
  216118. int64 a = 0;
  216119. for (int j = 6; --j >= 0;)
  216120. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  216121. *addresses++ = a;
  216122. ++numResults;
  216123. }
  216124. }
  216125. close (s);
  216126. }
  216127. return numResults;
  216128. }
  216129. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216130. const String& emailSubject,
  216131. const String& bodyText,
  216132. const StringArray& filesToAttach)
  216133. {
  216134. jassertfalse; // xxx todo
  216135. return false;
  216136. }
  216137. /** A HTTP input stream that uses sockets.
  216138. */
  216139. class JUCE_HTTPSocketStream
  216140. {
  216141. public:
  216142. JUCE_HTTPSocketStream()
  216143. : readPosition (0),
  216144. socketHandle (-1),
  216145. levelsOfRedirection (0),
  216146. timeoutSeconds (15)
  216147. {
  216148. }
  216149. ~JUCE_HTTPSocketStream()
  216150. {
  216151. closeSocket();
  216152. }
  216153. bool open (const String& url,
  216154. const String& headers,
  216155. const MemoryBlock& postData,
  216156. const bool isPost,
  216157. URL::OpenStreamProgressCallback* callback,
  216158. void* callbackContext,
  216159. int timeOutMs)
  216160. {
  216161. closeSocket();
  216162. uint32 timeOutTime = Time::getMillisecondCounter();
  216163. if (timeOutMs == 0)
  216164. timeOutTime += 60000;
  216165. else if (timeOutMs < 0)
  216166. timeOutTime = 0xffffffff;
  216167. else
  216168. timeOutTime += timeOutMs;
  216169. String hostName, hostPath;
  216170. int hostPort;
  216171. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216172. return false;
  216173. const struct hostent* host = 0;
  216174. int port = 0;
  216175. String proxyName, proxyPath;
  216176. int proxyPort = 0;
  216177. String proxyURL (getenv ("http_proxy"));
  216178. if (proxyURL.startsWithIgnoreCase ("http://"))
  216179. {
  216180. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216181. return false;
  216182. host = gethostbyname (proxyName.toUTF8());
  216183. port = proxyPort;
  216184. }
  216185. else
  216186. {
  216187. host = gethostbyname (hostName.toUTF8());
  216188. port = hostPort;
  216189. }
  216190. if (host == 0)
  216191. return false;
  216192. struct sockaddr_in address;
  216193. zerostruct (address);
  216194. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  216195. address.sin_family = host->h_addrtype;
  216196. address.sin_port = htons (port);
  216197. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216198. if (socketHandle == -1)
  216199. return false;
  216200. int receiveBufferSize = 16384;
  216201. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216202. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216203. #if JUCE_MAC
  216204. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216205. #endif
  216206. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216207. {
  216208. closeSocket();
  216209. return false;
  216210. }
  216211. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216212. proxyName, proxyPort,
  216213. hostPath, url,
  216214. headers, postData,
  216215. isPost));
  216216. size_t totalHeaderSent = 0;
  216217. while (totalHeaderSent < requestHeader.getSize())
  216218. {
  216219. if (Time::getMillisecondCounter() > timeOutTime)
  216220. {
  216221. closeSocket();
  216222. return false;
  216223. }
  216224. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  216225. if (send (socketHandle,
  216226. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216227. numToSend, 0)
  216228. != numToSend)
  216229. {
  216230. closeSocket();
  216231. return false;
  216232. }
  216233. totalHeaderSent += numToSend;
  216234. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216235. {
  216236. closeSocket();
  216237. return false;
  216238. }
  216239. }
  216240. const String responseHeader (readResponse (timeOutTime));
  216241. if (responseHeader.isNotEmpty())
  216242. {
  216243. //DBG (responseHeader);
  216244. headerLines.clear();
  216245. headerLines.addLines (responseHeader);
  216246. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  216247. .substring (0, 3).getIntValue();
  216248. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  216249. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  216250. String location (findHeaderItem (headerLines, "Location:"));
  216251. if (statusCode >= 300 && statusCode < 400
  216252. && location.isNotEmpty())
  216253. {
  216254. if (! location.startsWithIgnoreCase ("http://"))
  216255. location = "http://" + location;
  216256. if (levelsOfRedirection++ < 3)
  216257. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216258. }
  216259. else
  216260. {
  216261. levelsOfRedirection = 0;
  216262. return true;
  216263. }
  216264. }
  216265. closeSocket();
  216266. return false;
  216267. }
  216268. int read (void* buffer, int bytesToRead)
  216269. {
  216270. fd_set readbits;
  216271. FD_ZERO (&readbits);
  216272. FD_SET (socketHandle, &readbits);
  216273. struct timeval tv;
  216274. tv.tv_sec = timeoutSeconds;
  216275. tv.tv_usec = 0;
  216276. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216277. return 0; // (timeout)
  216278. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216279. readPosition += bytesRead;
  216280. return bytesRead;
  216281. }
  216282. int readPosition;
  216283. StringArray headerLines;
  216284. juce_UseDebuggingNewOperator
  216285. private:
  216286. int socketHandle, levelsOfRedirection;
  216287. const int timeoutSeconds;
  216288. void closeSocket()
  216289. {
  216290. if (socketHandle >= 0)
  216291. close (socketHandle);
  216292. socketHandle = -1;
  216293. }
  216294. const MemoryBlock createRequestHeader (const String& hostName,
  216295. const int hostPort,
  216296. const String& proxyName,
  216297. const int proxyPort,
  216298. const String& hostPath,
  216299. const String& originalURL,
  216300. const String& headers,
  216301. const MemoryBlock& postData,
  216302. const bool isPost)
  216303. {
  216304. String header (isPost ? "POST " : "GET ");
  216305. if (proxyName.isEmpty())
  216306. {
  216307. header << hostPath << " HTTP/1.0\r\nHost: "
  216308. << hostName << ':' << hostPort;
  216309. }
  216310. else
  216311. {
  216312. header << originalURL << " HTTP/1.0\r\nHost: "
  216313. << proxyName << ':' << proxyPort;
  216314. }
  216315. header << "\r\nUser-Agent: JUCE/"
  216316. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216317. << "\r\nConnection: Close\r\nContent-Length: "
  216318. << postData.getSize() << "\r\n"
  216319. << headers << "\r\n";
  216320. MemoryBlock mb;
  216321. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216322. mb.append (postData.getData(), postData.getSize());
  216323. return mb;
  216324. }
  216325. const String readResponse (const uint32 timeOutTime)
  216326. {
  216327. int bytesRead = 0, numConsecutiveLFs = 0;
  216328. MemoryBlock buffer (1024, true);
  216329. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216330. && Time::getMillisecondCounter() <= timeOutTime)
  216331. {
  216332. fd_set readbits;
  216333. FD_ZERO (&readbits);
  216334. FD_SET (socketHandle, &readbits);
  216335. struct timeval tv;
  216336. tv.tv_sec = timeoutSeconds;
  216337. tv.tv_usec = 0;
  216338. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216339. return String::empty; // (timeout)
  216340. buffer.ensureSize (bytesRead + 8, true);
  216341. char* const dest = (char*) buffer.getData() + bytesRead;
  216342. if (recv (socketHandle, dest, 1, 0) == -1)
  216343. return String::empty;
  216344. const char lastByte = *dest;
  216345. ++bytesRead;
  216346. if (lastByte == '\n')
  216347. ++numConsecutiveLFs;
  216348. else if (lastByte != '\r')
  216349. numConsecutiveLFs = 0;
  216350. }
  216351. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  216352. if (header.startsWithIgnoreCase ("HTTP/"))
  216353. return header.trimEnd();
  216354. return String::empty;
  216355. }
  216356. static bool decomposeURL (const String& url,
  216357. String& host, String& path, int& port)
  216358. {
  216359. if (! url.startsWithIgnoreCase ("http://"))
  216360. return false;
  216361. const int nextSlash = url.indexOfChar (7, '/');
  216362. int nextColon = url.indexOfChar (7, ':');
  216363. if (nextColon > nextSlash && nextSlash > 0)
  216364. nextColon = -1;
  216365. if (nextColon >= 0)
  216366. {
  216367. host = url.substring (7, nextColon);
  216368. if (nextSlash >= 0)
  216369. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216370. else
  216371. port = url.substring (nextColon + 1).getIntValue();
  216372. }
  216373. else
  216374. {
  216375. port = 80;
  216376. if (nextSlash >= 0)
  216377. host = url.substring (7, nextSlash);
  216378. else
  216379. host = url.substring (7);
  216380. }
  216381. if (nextSlash >= 0)
  216382. path = url.substring (nextSlash);
  216383. else
  216384. path = "/";
  216385. return true;
  216386. }
  216387. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216388. {
  216389. for (int i = 0; i < lines.size(); ++i)
  216390. if (lines[i].startsWithIgnoreCase (itemName))
  216391. return lines[i].substring (itemName.length()).trim();
  216392. return String::empty;
  216393. }
  216394. };
  216395. void* juce_openInternetFile (const String& url,
  216396. const String& headers,
  216397. const MemoryBlock& postData,
  216398. const bool isPost,
  216399. URL::OpenStreamProgressCallback* callback,
  216400. void* callbackContext,
  216401. int timeOutMs)
  216402. {
  216403. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  216404. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  216405. return s.release();
  216406. return 0;
  216407. }
  216408. void juce_closeInternetFile (void* handle)
  216409. {
  216410. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  216411. }
  216412. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216413. {
  216414. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216415. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  216416. }
  216417. int64 juce_getInternetFileContentLength (void* handle)
  216418. {
  216419. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216420. if (s != 0)
  216421. {
  216422. //xxx todo
  216423. jassertfalse
  216424. }
  216425. return -1;
  216426. }
  216427. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  216428. {
  216429. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216430. if (s != 0)
  216431. {
  216432. for (int i = 0; i < s->headerLines.size(); ++i)
  216433. {
  216434. const String& headersEntry = s->headerLines[i];
  216435. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  216436. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  216437. const String previousValue (headers [key]);
  216438. headers.set (key, previousValue.isEmpty() ? value : (previousValue + ";" + value));
  216439. }
  216440. }
  216441. }
  216442. int juce_seekInInternetFile (void* handle, int newPosition)
  216443. {
  216444. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216445. return s != 0 ? s->readPosition : 0;
  216446. }
  216447. #endif
  216448. /*** End of inlined file: juce_linux_Network.cpp ***/
  216449. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  216450. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216451. // compiled on its own).
  216452. #if JUCE_INCLUDED_FILE
  216453. void Logger::outputDebugString (const String& text)
  216454. {
  216455. std::cerr << text << std::endl;
  216456. }
  216457. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  216458. {
  216459. return Linux;
  216460. }
  216461. const String SystemStats::getOperatingSystemName()
  216462. {
  216463. return "Linux";
  216464. }
  216465. bool SystemStats::isOperatingSystem64Bit()
  216466. {
  216467. #if JUCE_64BIT
  216468. return true;
  216469. #else
  216470. //xxx not sure how to find this out?..
  216471. return false;
  216472. #endif
  216473. }
  216474. static const String juce_getCpuInfo (const char* const key)
  216475. {
  216476. StringArray lines;
  216477. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  216478. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  216479. if (lines[i].startsWithIgnoreCase (key))
  216480. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  216481. return String::empty;
  216482. }
  216483. bool SystemStats::hasMMX() { return juce_getCpuInfo ("flags").contains ("mmx"); }
  216484. bool SystemStats::hasSSE() { return juce_getCpuInfo ("flags").contains ("sse"); }
  216485. bool SystemStats::hasSSE2() { return juce_getCpuInfo ("flags").contains ("sse2"); }
  216486. bool SystemStats::has3DNow() { return juce_getCpuInfo ("flags").contains ("3dnow"); }
  216487. const String SystemStats::getCpuVendor()
  216488. {
  216489. return juce_getCpuInfo ("vendor_id");
  216490. }
  216491. int SystemStats::getCpuSpeedInMegaherz()
  216492. {
  216493. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  216494. }
  216495. int SystemStats::getMemorySizeInMegabytes()
  216496. {
  216497. struct sysinfo sysi;
  216498. if (sysinfo (&sysi) == 0)
  216499. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  216500. return 0;
  216501. }
  216502. int SystemStats::getPageSize()
  216503. {
  216504. return sysconf (_SC_PAGESIZE);
  216505. }
  216506. int SystemStats::getNumCpus()
  216507. {
  216508. return juce_getCpuInfo ("processor").getIntValue() + 1;
  216509. }
  216510. const String SystemStats::getLogonName()
  216511. {
  216512. const char* user = getenv ("USER");
  216513. if (user == 0)
  216514. {
  216515. struct passwd* const pw = getpwuid (getuid());
  216516. if (pw != 0)
  216517. user = pw->pw_name;
  216518. }
  216519. return String::fromUTF8 (user);
  216520. }
  216521. const String SystemStats::getFullUserName()
  216522. {
  216523. return getLogonName();
  216524. }
  216525. void SystemStats::initialiseStats()
  216526. {
  216527. }
  216528. void PlatformUtilities::fpuReset()
  216529. {
  216530. }
  216531. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  216532. {
  216533. if (gettimeofday (t, 0) != 0)
  216534. return false;
  216535. static unsigned int calibrate = 0;
  216536. static bool calibrated = false;
  216537. if (! calibrated)
  216538. {
  216539. calibrated = true;
  216540. struct sysinfo sysi;
  216541. if (sysinfo (&sysi) == 0)
  216542. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  216543. }
  216544. t->tv_sec -= calibrate;
  216545. return true;
  216546. }
  216547. uint32 juce_millisecondsSinceStartup() throw()
  216548. {
  216549. timeval t;
  216550. if (juce_getTimeSinceStartup (&t))
  216551. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  216552. return 0;
  216553. }
  216554. int64 Time::getHighResolutionTicks() throw()
  216555. {
  216556. timeval t;
  216557. if (juce_getTimeSinceStartup (&t))
  216558. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  216559. return 0;
  216560. }
  216561. int64 Time::getHighResolutionTicksPerSecond() throw()
  216562. {
  216563. return 1000000; // (microseconds)
  216564. }
  216565. double Time::getMillisecondCounterHiRes() throw()
  216566. {
  216567. return getHighResolutionTicks() * 0.001;
  216568. }
  216569. bool Time::setSystemTimeToThisTime() const
  216570. {
  216571. timeval t;
  216572. t.tv_sec = millisSinceEpoch % 1000000;
  216573. t.tv_usec = millisSinceEpoch - t.tv_sec;
  216574. return settimeofday (&t, 0) ? false : true;
  216575. }
  216576. #endif
  216577. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  216578. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  216579. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216580. // compiled on its own).
  216581. #if JUCE_INCLUDED_FILE
  216582. /*
  216583. Note that a lot of methods that you'd expect to find in this file actually
  216584. live in juce_posix_SharedCode.h!
  216585. */
  216586. void JUCE_API juce_threadEntryPoint (void*);
  216587. void* threadEntryProc (void* value)
  216588. {
  216589. juce_threadEntryPoint (value);
  216590. return 0;
  216591. }
  216592. void* juce_createThread (void* userData)
  216593. {
  216594. pthread_t handle = 0;
  216595. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  216596. {
  216597. pthread_detach (handle);
  216598. return (void*) handle;
  216599. }
  216600. return 0;
  216601. }
  216602. void juce_killThread (void* handle)
  216603. {
  216604. if (handle != 0)
  216605. pthread_cancel ((pthread_t) handle);
  216606. }
  216607. void juce_setCurrentThreadName (const String& /*name*/)
  216608. {
  216609. }
  216610. Thread::ThreadID Thread::getCurrentThreadId()
  216611. {
  216612. return (ThreadID) pthread_self();
  216613. }
  216614. /* This is all a bit non-ideal... the trouble is that on Linux you
  216615. need to call setpriority to affect the dynamic priority for
  216616. non-realtime processes, but this requires the pid, which is not
  216617. accessible from the pthread_t. We could get it by calling getpid
  216618. once each thread has started, but then we would need a list of
  216619. running threads etc etc.
  216620. Also there is no such thing as IDLE priority on Linux.
  216621. For the moment, map idle, low and normal process priorities to
  216622. SCHED_OTHER, with the thread priority ignored for these classes.
  216623. Map high priority processes to the lower half of the SCHED_RR
  216624. range, and realtime to the upper half.
  216625. priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  216626. priority of the current thread
  216627. */
  216628. bool juce_setThreadPriority (void* handle, int priority)
  216629. {
  216630. struct sched_param param;
  216631. int policy;
  216632. if (handle == 0)
  216633. handle = (void*) pthread_self();
  216634. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  216635. && policy != SCHED_OTHER)
  216636. {
  216637. int minp = sched_get_priority_min (policy);
  216638. int maxp = sched_get_priority_max (policy);
  216639. int pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  216640. if (param.sched_priority >= (minp + (maxp - minp) / 2))
  216641. param.sched_priority = minp + ((maxp - minp) / 2) + pri; // (realtime)
  216642. else
  216643. param.sched_priority = minp + pri; // (high)
  216644. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  216645. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216646. }
  216647. return false;
  216648. }
  216649. /* Remove this macro if you're having problems compiling the cpu affinity
  216650. calls (the API for these has changed about quite a bit in various Linux
  216651. versions, and a lot of distros seem to ship with obsolete versions)
  216652. */
  216653. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216654. #define SUPPORT_AFFINITIES 1
  216655. #endif
  216656. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216657. {
  216658. #if SUPPORT_AFFINITIES
  216659. cpu_set_t affinity;
  216660. CPU_ZERO (&affinity);
  216661. for (int i = 0; i < 32; ++i)
  216662. if ((affinityMask & (1 << i)) != 0)
  216663. CPU_SET (i, &affinity);
  216664. /*
  216665. N.B. If this line causes a compile error, then you've probably not got the latest
  216666. version of glibc installed.
  216667. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216668. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216669. */
  216670. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216671. sched_yield();
  216672. #else
  216673. /* affinities aren't supported because either the appropriate header files weren't found,
  216674. or the SUPPORT_AFFINITIES macro was turned off
  216675. */
  216676. jassertfalse;
  216677. #endif
  216678. }
  216679. void Thread::yield()
  216680. {
  216681. sched_yield();
  216682. }
  216683. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  216684. void Process::setPriority (ProcessPriority prior)
  216685. {
  216686. struct sched_param param;
  216687. int policy, maxp, minp;
  216688. const int p = (int) prior;
  216689. if (p <= 1)
  216690. policy = SCHED_OTHER;
  216691. else
  216692. policy = SCHED_RR;
  216693. minp = sched_get_priority_min (policy);
  216694. maxp = sched_get_priority_max (policy);
  216695. if (p < 2)
  216696. param.sched_priority = 0;
  216697. else if (p == 2 )
  216698. // Set to middle of lower realtime priority range
  216699. param.sched_priority = minp + (maxp - minp) / 4;
  216700. else
  216701. // Set to middle of higher realtime priority range
  216702. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  216703. pthread_setschedparam (pthread_self(), policy, &param);
  216704. }
  216705. void Process::terminate()
  216706. {
  216707. exit (0);
  216708. }
  216709. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  216710. {
  216711. static char testResult = 0;
  216712. if (testResult == 0)
  216713. {
  216714. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  216715. if (testResult >= 0)
  216716. {
  216717. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  216718. testResult = 1;
  216719. }
  216720. }
  216721. return testResult < 0;
  216722. }
  216723. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  216724. {
  216725. return juce_isRunningUnderDebugger();
  216726. }
  216727. void Process::raisePrivilege()
  216728. {
  216729. // If running suid root, change effective user
  216730. // to root
  216731. if (geteuid() != 0 && getuid() == 0)
  216732. {
  216733. setreuid (geteuid(), getuid());
  216734. setregid (getegid(), getgid());
  216735. }
  216736. }
  216737. void Process::lowerPrivilege()
  216738. {
  216739. // If runing suid root, change effective user
  216740. // back to real user
  216741. if (geteuid() == 0 && getuid() != 0)
  216742. {
  216743. setreuid (geteuid(), getuid());
  216744. setregid (getegid(), getgid());
  216745. }
  216746. }
  216747. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  216748. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  216749. {
  216750. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  216751. }
  216752. void PlatformUtilities::freeDynamicLibrary (void* handle)
  216753. {
  216754. dlclose(handle);
  216755. }
  216756. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  216757. {
  216758. return dlsym (libraryHandle, procedureName.toCString());
  216759. }
  216760. #endif
  216761. #endif
  216762. /*** End of inlined file: juce_linux_Threads.cpp ***/
  216763. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  216764. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  216765. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216766. // compiled on its own).
  216767. #if JUCE_INCLUDED_FILE
  216768. #if JUCE_DEBUG
  216769. #define JUCE_DEBUG_XERRORS 1
  216770. #endif
  216771. extern Display* display;
  216772. extern Window juce_messageWindowHandle;
  216773. namespace ClipboardHelpers
  216774. {
  216775. static String localClipboardContent;
  216776. static Atom atom_UTF8_STRING;
  216777. static Atom atom_CLIPBOARD;
  216778. static Atom atom_TARGETS;
  216779. static void initSelectionAtoms()
  216780. {
  216781. static bool isInitialised = false;
  216782. if (! isInitialised)
  216783. {
  216784. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  216785. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  216786. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  216787. }
  216788. }
  216789. // Read the content of a window property as either a locale-dependent string or an utf8 string
  216790. // works only for strings shorter than 1000000 bytes
  216791. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  216792. {
  216793. String returnData;
  216794. char* clipData;
  216795. Atom actualType;
  216796. int actualFormat;
  216797. unsigned long numItems, bytesLeft;
  216798. if (XGetWindowProperty (display, window, prop,
  216799. 0L /* offset */, 1000000 /* length (max) */, False,
  216800. AnyPropertyType /* format */,
  216801. &actualType, &actualFormat, &numItems, &bytesLeft,
  216802. (unsigned char**) &clipData) == Success)
  216803. {
  216804. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  216805. returnData = String::fromUTF8 (clipData, numItems);
  216806. else if (actualType == XA_STRING && actualFormat == 8)
  216807. returnData = String (clipData, numItems);
  216808. if (clipData != 0)
  216809. XFree (clipData);
  216810. jassert (bytesLeft == 0 || numItems == 1000000);
  216811. }
  216812. XDeleteProperty (display, window, prop);
  216813. return returnData;
  216814. }
  216815. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  216816. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  216817. {
  216818. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  216819. // The selection owner will be asked to set the JUCE_SEL property on the
  216820. // juce_messageWindowHandle with the selection content
  216821. XConvertSelection (display, selection, requestedFormat, property_name,
  216822. juce_messageWindowHandle, CurrentTime);
  216823. int count = 50; // will wait at most for 200 ms
  216824. while (--count >= 0)
  216825. {
  216826. XEvent event;
  216827. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  216828. {
  216829. if (event.xselection.property == property_name)
  216830. {
  216831. jassert (event.xselection.requestor == juce_messageWindowHandle);
  216832. selectionContent = readWindowProperty (event.xselection.requestor,
  216833. event.xselection.property,
  216834. requestedFormat);
  216835. return true;
  216836. }
  216837. else
  216838. {
  216839. return false; // the format we asked for was denied.. (event.xselection.property == None)
  216840. }
  216841. }
  216842. // not very elegant.. we could do a select() or something like that...
  216843. // however clipboard content requesting is inherently slow on x11, it
  216844. // often takes 50ms or more so...
  216845. Thread::sleep (4);
  216846. }
  216847. return false;
  216848. }
  216849. }
  216850. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  216851. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  216852. {
  216853. ClipboardHelpers::initSelectionAtoms();
  216854. // the selection content is sent to the target window as a window property
  216855. XSelectionEvent reply;
  216856. reply.type = SelectionNotify;
  216857. reply.display = evt.display;
  216858. reply.requestor = evt.requestor;
  216859. reply.selection = evt.selection;
  216860. reply.target = evt.target;
  216861. reply.property = None; // == "fail"
  216862. reply.time = evt.time;
  216863. HeapBlock <char> data;
  216864. int propertyFormat = 0, numDataItems = 0;
  216865. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  216866. {
  216867. if (evt.target == XA_STRING)
  216868. {
  216869. // format data according to system locale
  216870. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  216871. data.calloc (numDataItems + 1);
  216872. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  216873. propertyFormat = 8; // bits/item
  216874. }
  216875. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  216876. {
  216877. // translate to utf8
  216878. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  216879. data.calloc (numDataItems + 1);
  216880. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  216881. propertyFormat = 8; // bits/item
  216882. }
  216883. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  216884. {
  216885. // another application wants to know what we are able to send
  216886. numDataItems = 2;
  216887. propertyFormat = 32; // atoms are 32-bit
  216888. data.calloc (numDataItems * 4);
  216889. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  216890. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  216891. atoms[1] = XA_STRING;
  216892. }
  216893. }
  216894. else
  216895. {
  216896. DBG ("requested unsupported clipboard");
  216897. }
  216898. if (data != 0)
  216899. {
  216900. const int maxReasonableSelectionSize = 1000000;
  216901. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  216902. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  216903. {
  216904. XChangeProperty (evt.display, evt.requestor,
  216905. evt.property, evt.target,
  216906. propertyFormat /* 8 or 32 */, PropModeReplace,
  216907. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  216908. reply.property = evt.property; // " == success"
  216909. }
  216910. }
  216911. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  216912. }
  216913. void SystemClipboard::copyTextToClipboard (const String& clipText)
  216914. {
  216915. ClipboardHelpers::initSelectionAtoms();
  216916. ClipboardHelpers::localClipboardContent = clipText;
  216917. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  216918. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  216919. }
  216920. const String SystemClipboard::getTextFromClipboard()
  216921. {
  216922. ClipboardHelpers::initSelectionAtoms();
  216923. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  216924. level" clipboard that is supposed to be filled by ctrl-C
  216925. etc). When a clipboard manager is running, the content of this
  216926. selection is preserved even when the original selection owner
  216927. exits.
  216928. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  216929. filled by good old x11 apps such as xterm)
  216930. */
  216931. String content;
  216932. Atom selection = XA_PRIMARY;
  216933. Window selectionOwner = None;
  216934. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  216935. {
  216936. selection = ClipboardHelpers::atom_CLIPBOARD;
  216937. selectionOwner = XGetSelectionOwner (display, selection);
  216938. }
  216939. if (selectionOwner != None)
  216940. {
  216941. if (selectionOwner == juce_messageWindowHandle)
  216942. {
  216943. content = ClipboardHelpers::localClipboardContent;
  216944. }
  216945. else
  216946. {
  216947. // first try: we want an utf8 string
  216948. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  216949. if (! ok)
  216950. {
  216951. // second chance, ask for a good old locale-dependent string ..
  216952. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  216953. }
  216954. }
  216955. }
  216956. return content;
  216957. }
  216958. #endif
  216959. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  216960. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  216961. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216962. // compiled on its own).
  216963. #if JUCE_INCLUDED_FILE
  216964. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  216965. #define JUCE_DEBUG_XERRORS 1
  216966. #endif
  216967. Display* display = 0;
  216968. Window juce_messageWindowHandle = None;
  216969. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  216970. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  216971. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  216972. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  216973. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  216974. class InternalMessageQueue
  216975. {
  216976. public:
  216977. InternalMessageQueue()
  216978. : bytesInSocket (0),
  216979. totalEventCount (0)
  216980. {
  216981. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  216982. (void) ret; jassert (ret == 0);
  216983. //setNonBlocking (fd[0]);
  216984. //setNonBlocking (fd[1]);
  216985. }
  216986. ~InternalMessageQueue()
  216987. {
  216988. close (fd[0]);
  216989. close (fd[1]);
  216990. clearSingletonInstance();
  216991. }
  216992. void postMessage (Message* msg)
  216993. {
  216994. const int maxBytesInSocketQueue = 128;
  216995. ScopedLock sl (lock);
  216996. queue.add (msg);
  216997. if (bytesInSocket < maxBytesInSocketQueue)
  216998. {
  216999. ++bytesInSocket;
  217000. ScopedUnlock ul (lock);
  217001. const unsigned char x = 0xff;
  217002. size_t bytesWritten = write (fd[0], &x, 1);
  217003. (void) bytesWritten;
  217004. }
  217005. }
  217006. bool isEmpty() const
  217007. {
  217008. ScopedLock sl (lock);
  217009. return queue.size() == 0;
  217010. }
  217011. bool dispatchNextEvent()
  217012. {
  217013. // This alternates between giving priority to XEvents or internal messages,
  217014. // to keep everything running smoothly..
  217015. if ((++totalEventCount & 1) != 0)
  217016. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217017. else
  217018. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217019. }
  217020. // Wait for an event (either XEvent, or an internal Message)
  217021. bool sleepUntilEvent (const int timeoutMs)
  217022. {
  217023. if (! isEmpty())
  217024. return true;
  217025. if (display != 0)
  217026. {
  217027. ScopedXLock xlock;
  217028. if (XPending (display))
  217029. return true;
  217030. }
  217031. struct timeval tv;
  217032. tv.tv_sec = 0;
  217033. tv.tv_usec = timeoutMs * 1000;
  217034. int fd0 = getWaitHandle();
  217035. int fdmax = fd0;
  217036. fd_set readset;
  217037. FD_ZERO (&readset);
  217038. FD_SET (fd0, &readset);
  217039. if (display != 0)
  217040. {
  217041. ScopedXLock xlock;
  217042. int fd1 = XConnectionNumber (display);
  217043. FD_SET (fd1, &readset);
  217044. fdmax = jmax (fd0, fd1);
  217045. }
  217046. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217047. return (ret > 0); // ret <= 0 if error or timeout
  217048. }
  217049. struct MessageThreadFuncCall
  217050. {
  217051. enum { uniqueID = 0x73774623 };
  217052. MessageCallbackFunction* func;
  217053. void* parameter;
  217054. void* result;
  217055. CriticalSection lock;
  217056. WaitableEvent event;
  217057. };
  217058. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217059. private:
  217060. CriticalSection lock;
  217061. OwnedArray <Message> queue;
  217062. int fd[2];
  217063. int bytesInSocket;
  217064. int totalEventCount;
  217065. int getWaitHandle() const throw() { return fd[1]; }
  217066. static bool setNonBlocking (int handle)
  217067. {
  217068. int socketFlags = fcntl (handle, F_GETFL, 0);
  217069. if (socketFlags == -1)
  217070. return false;
  217071. socketFlags |= O_NONBLOCK;
  217072. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217073. }
  217074. static bool dispatchNextXEvent()
  217075. {
  217076. if (display == 0)
  217077. return false;
  217078. XEvent evt;
  217079. {
  217080. ScopedXLock xlock;
  217081. if (! XPending (display))
  217082. return false;
  217083. XNextEvent (display, &evt);
  217084. }
  217085. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217086. juce_handleSelectionRequest (evt.xselectionrequest);
  217087. else if (evt.xany.window != juce_messageWindowHandle)
  217088. juce_windowMessageReceive (&evt);
  217089. return true;
  217090. }
  217091. Message* popNextMessage()
  217092. {
  217093. ScopedLock sl (lock);
  217094. if (bytesInSocket > 0)
  217095. {
  217096. --bytesInSocket;
  217097. ScopedUnlock ul (lock);
  217098. unsigned char x;
  217099. size_t numBytes = read (fd[1], &x, 1);
  217100. (void) numBytes;
  217101. }
  217102. Message* m = queue[0];
  217103. queue.remove (0, false /* deleteObject */);
  217104. return m;
  217105. }
  217106. bool dispatchNextInternalMessage()
  217107. {
  217108. ScopedPointer <Message> msg (popNextMessage());
  217109. if (msg == 0)
  217110. return false;
  217111. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217112. {
  217113. // Handle callback message
  217114. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217115. call->result = (*(call->func)) (call->parameter);
  217116. call->event.signal();
  217117. }
  217118. else
  217119. {
  217120. // Handle "normal" messages
  217121. MessageManager::getInstance()->deliverMessage (msg.release());
  217122. }
  217123. return true;
  217124. }
  217125. };
  217126. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  217127. namespace LinuxErrorHandling
  217128. {
  217129. static bool errorOccurred = false;
  217130. static bool keyboardBreakOccurred = false;
  217131. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  217132. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  217133. // Usually happens when client-server connection is broken
  217134. static int ioErrorHandler (Display* display)
  217135. {
  217136. DBG ("ERROR: connection to X server broken.. terminating.");
  217137. errorOccurred = true;
  217138. if (JUCEApplication::getInstance() != 0)
  217139. Process::terminate();
  217140. return 0;
  217141. }
  217142. // A protocol error has occurred
  217143. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  217144. {
  217145. #if JUCE_DEBUG_XERRORS
  217146. char errorStr[64] = { 0 };
  217147. char requestStr[64] = { 0 };
  217148. XGetErrorText (display, event->error_code, errorStr, 64);
  217149. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  217150. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  217151. #endif
  217152. return 0;
  217153. }
  217154. static void installXErrorHandlers()
  217155. {
  217156. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  217157. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  217158. }
  217159. static void removeXErrorHandlers()
  217160. {
  217161. XSetIOErrorHandler (oldIOErrorHandler);
  217162. oldIOErrorHandler = 0;
  217163. XSetErrorHandler (oldErrorHandler);
  217164. oldErrorHandler = 0;
  217165. }
  217166. static void keyboardBreakSignalHandler (int sig)
  217167. {
  217168. if (sig == SIGINT)
  217169. keyboardBreakOccurred = true;
  217170. }
  217171. static void installKeyboardBreakHandler()
  217172. {
  217173. struct sigaction saction;
  217174. sigset_t maskSet;
  217175. sigemptyset (&maskSet);
  217176. saction.sa_handler = keyboardBreakSignalHandler;
  217177. saction.sa_mask = maskSet;
  217178. saction.sa_flags = 0;
  217179. sigaction (SIGINT, &saction, 0);
  217180. }
  217181. }
  217182. void MessageManager::doPlatformSpecificInitialisation()
  217183. {
  217184. // Initialise xlib for multiple thread support
  217185. static bool initThreadCalled = false;
  217186. if (! initThreadCalled)
  217187. {
  217188. if (! XInitThreads())
  217189. {
  217190. // This is fatal! Print error and closedown
  217191. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  217192. if (JUCEApplication::getInstance() != 0)
  217193. Process::terminate();
  217194. return;
  217195. }
  217196. initThreadCalled = true;
  217197. }
  217198. LinuxErrorHandling::installXErrorHandlers();
  217199. LinuxErrorHandling::installKeyboardBreakHandler();
  217200. // Create the internal message queue
  217201. InternalMessageQueue::getInstance();
  217202. // Try to connect to a display
  217203. String displayName (getenv ("DISPLAY"));
  217204. if (displayName.isEmpty())
  217205. displayName = ":0.0";
  217206. display = XOpenDisplay (displayName.toCString());
  217207. if (display != 0) // This is not fatal! we can run headless.
  217208. {
  217209. // Create a context to store user data associated with Windows we create in WindowDriver
  217210. windowHandleXContext = XUniqueContext();
  217211. // We're only interested in client messages for this window, which are always sent
  217212. XSetWindowAttributes swa;
  217213. swa.event_mask = NoEventMask;
  217214. // Create our message window (this will never be mapped)
  217215. const int screen = DefaultScreen (display);
  217216. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  217217. 0, 0, 1, 1, 0, 0, InputOnly,
  217218. DefaultVisual (display, screen),
  217219. CWEventMask, &swa);
  217220. }
  217221. }
  217222. void MessageManager::doPlatformSpecificShutdown()
  217223. {
  217224. InternalMessageQueue::deleteInstance();
  217225. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  217226. {
  217227. XDestroyWindow (display, juce_messageWindowHandle);
  217228. XCloseDisplay (display);
  217229. juce_messageWindowHandle = 0;
  217230. display = 0;
  217231. LinuxErrorHandling::removeXErrorHandlers();
  217232. }
  217233. }
  217234. bool juce_postMessageToSystemQueue (void* message)
  217235. {
  217236. if (LinuxErrorHandling::errorOccurred)
  217237. return false;
  217238. InternalMessageQueue::getInstanceWithoutCreating()->postMessage ((Message*) message);
  217239. return true;
  217240. }
  217241. void MessageManager::broadcastMessage (const String& value) throw()
  217242. {
  217243. /* TODO */
  217244. }
  217245. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  217246. void* parameter)
  217247. {
  217248. if (LinuxErrorHandling::errorOccurred)
  217249. return 0;
  217250. if (isThisTheMessageThread())
  217251. return func (parameter);
  217252. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  217253. messageCallContext.func = func;
  217254. messageCallContext.parameter = parameter;
  217255. InternalMessageQueue::getInstanceWithoutCreating()
  217256. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  217257. 0, 0, &messageCallContext));
  217258. // Wait for it to complete before continuing
  217259. messageCallContext.event.wait();
  217260. return messageCallContext.result;
  217261. }
  217262. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  217263. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  217264. {
  217265. while (! LinuxErrorHandling::errorOccurred)
  217266. {
  217267. if (LinuxErrorHandling::keyboardBreakOccurred)
  217268. {
  217269. LinuxErrorHandling::errorOccurred = true;
  217270. if (JUCEApplication::getInstance() != 0)
  217271. Process::terminate();
  217272. break;
  217273. }
  217274. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  217275. return true;
  217276. if (returnIfNoPendingMessages)
  217277. break;
  217278. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  217279. }
  217280. return false;
  217281. }
  217282. #endif
  217283. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  217284. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  217285. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217286. // compiled on its own).
  217287. #if JUCE_INCLUDED_FILE
  217288. class FreeTypeFontFace
  217289. {
  217290. public:
  217291. enum FontStyle
  217292. {
  217293. Plain = 0,
  217294. Bold = 1,
  217295. Italic = 2
  217296. };
  217297. FreeTypeFontFace (const String& familyName)
  217298. : hasSerif (false),
  217299. monospaced (false)
  217300. {
  217301. family = familyName;
  217302. }
  217303. void setFileName (const String& name, const int faceIndex, FontStyle style)
  217304. {
  217305. if (names [(int) style].fileName.isEmpty())
  217306. {
  217307. names [(int) style].fileName = name;
  217308. names [(int) style].faceIndex = faceIndex;
  217309. }
  217310. }
  217311. const String& getFamilyName() const throw() { return family; }
  217312. const String& getFileName (const int style, int& faceIndex) const throw()
  217313. {
  217314. faceIndex = names[style].faceIndex;
  217315. return names[style].fileName;
  217316. }
  217317. void setMonospaced (bool mono) throw() { monospaced = mono; }
  217318. bool getMonospaced() const throw() { return monospaced; }
  217319. void setSerif (const bool serif) throw() { hasSerif = serif; }
  217320. bool getSerif() const throw() { return hasSerif; }
  217321. private:
  217322. String family;
  217323. struct FontNameIndex
  217324. {
  217325. String fileName;
  217326. int faceIndex;
  217327. };
  217328. FontNameIndex names[4];
  217329. bool hasSerif, monospaced;
  217330. };
  217331. class FreeTypeInterface : public DeletedAtShutdown
  217332. {
  217333. public:
  217334. FreeTypeInterface()
  217335. : ftLib (0),
  217336. lastFace (0),
  217337. lastBold (false),
  217338. lastItalic (false)
  217339. {
  217340. if (FT_Init_FreeType (&ftLib) != 0)
  217341. {
  217342. ftLib = 0;
  217343. DBG ("Failed to initialize FreeType");
  217344. }
  217345. StringArray fontDirs;
  217346. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  217347. fontDirs.removeEmptyStrings (true);
  217348. if (fontDirs.size() == 0)
  217349. {
  217350. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  217351. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  217352. if (fontsInfo != 0)
  217353. {
  217354. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  217355. {
  217356. fontDirs.add (e->getAllSubText().trim());
  217357. }
  217358. }
  217359. }
  217360. if (fontDirs.size() == 0)
  217361. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  217362. for (int i = 0; i < fontDirs.size(); ++i)
  217363. enumerateFaces (fontDirs[i]);
  217364. }
  217365. ~FreeTypeInterface()
  217366. {
  217367. if (lastFace != 0)
  217368. FT_Done_Face (lastFace);
  217369. if (ftLib != 0)
  217370. FT_Done_FreeType (ftLib);
  217371. clearSingletonInstance();
  217372. }
  217373. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  217374. {
  217375. for (int i = 0; i < faces.size(); i++)
  217376. if (faces[i]->getFamilyName() == familyName)
  217377. return faces[i];
  217378. if (! create)
  217379. return 0;
  217380. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  217381. faces.add (newFace);
  217382. return newFace;
  217383. }
  217384. // Enumerate all font faces available in a given directory
  217385. void enumerateFaces (const String& path)
  217386. {
  217387. File dirPath (path);
  217388. if (path.isEmpty() || ! dirPath.isDirectory())
  217389. return;
  217390. DirectoryIterator di (dirPath, true);
  217391. while (di.next())
  217392. {
  217393. File possible (di.getFile());
  217394. if (possible.hasFileExtension ("ttf")
  217395. || possible.hasFileExtension ("pfb")
  217396. || possible.hasFileExtension ("pcf"))
  217397. {
  217398. FT_Face face;
  217399. int faceIndex = 0;
  217400. int numFaces = 0;
  217401. do
  217402. {
  217403. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  217404. faceIndex, &face) == 0)
  217405. {
  217406. if (faceIndex == 0)
  217407. numFaces = face->num_faces;
  217408. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  217409. {
  217410. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  217411. int style = (int) FreeTypeFontFace::Plain;
  217412. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  217413. style |= (int) FreeTypeFontFace::Bold;
  217414. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  217415. style |= (int) FreeTypeFontFace::Italic;
  217416. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  217417. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  217418. // Surely there must be a better way to do this?
  217419. const String name (face->family_name);
  217420. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  217421. || name.containsIgnoreCase ("Verdana")
  217422. || name.containsIgnoreCase ("Arial")));
  217423. }
  217424. FT_Done_Face (face);
  217425. }
  217426. ++faceIndex;
  217427. }
  217428. while (faceIndex < numFaces);
  217429. }
  217430. }
  217431. }
  217432. // Create a FreeType face object for a given font
  217433. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  217434. {
  217435. FT_Face face = 0;
  217436. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  217437. {
  217438. face = lastFace;
  217439. }
  217440. else
  217441. {
  217442. if (lastFace != 0)
  217443. {
  217444. FT_Done_Face (lastFace);
  217445. lastFace = 0;
  217446. }
  217447. lastFontName = fontName;
  217448. lastBold = bold;
  217449. lastItalic = italic;
  217450. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  217451. if (ftFace != 0)
  217452. {
  217453. int style = (int) FreeTypeFontFace::Plain;
  217454. if (bold)
  217455. style |= (int) FreeTypeFontFace::Bold;
  217456. if (italic)
  217457. style |= (int) FreeTypeFontFace::Italic;
  217458. int faceIndex;
  217459. String fileName (ftFace->getFileName (style, faceIndex));
  217460. if (fileName.isEmpty())
  217461. {
  217462. style ^= (int) FreeTypeFontFace::Bold;
  217463. fileName = ftFace->getFileName (style, faceIndex);
  217464. if (fileName.isEmpty())
  217465. {
  217466. style ^= (int) FreeTypeFontFace::Bold;
  217467. style ^= (int) FreeTypeFontFace::Italic;
  217468. fileName = ftFace->getFileName (style, faceIndex);
  217469. if (! fileName.length())
  217470. {
  217471. style ^= (int) FreeTypeFontFace::Bold;
  217472. fileName = ftFace->getFileName (style, faceIndex);
  217473. }
  217474. }
  217475. }
  217476. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  217477. {
  217478. face = lastFace;
  217479. // If there isn't a unicode charmap then select the first one.
  217480. if (FT_Select_Charmap (face, ft_encoding_unicode))
  217481. FT_Set_Charmap (face, face->charmaps[0]);
  217482. }
  217483. }
  217484. }
  217485. return face;
  217486. }
  217487. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  217488. {
  217489. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  217490. const float height = (float) (face->ascender - face->descender);
  217491. const float scaleX = 1.0f / height;
  217492. const float scaleY = -1.0f / height;
  217493. Path destShape;
  217494. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  217495. || face->glyph->format != ft_glyph_format_outline)
  217496. {
  217497. return false;
  217498. }
  217499. const FT_Outline* const outline = &face->glyph->outline;
  217500. const short* const contours = outline->contours;
  217501. const char* const tags = outline->tags;
  217502. FT_Vector* const points = outline->points;
  217503. for (int c = 0; c < outline->n_contours; c++)
  217504. {
  217505. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  217506. const int endPoint = contours[c];
  217507. for (int p = startPoint; p <= endPoint; p++)
  217508. {
  217509. const float x = scaleX * points[p].x;
  217510. const float y = scaleY * points[p].y;
  217511. if (p == startPoint)
  217512. {
  217513. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  217514. {
  217515. float x2 = scaleX * points [endPoint].x;
  217516. float y2 = scaleY * points [endPoint].y;
  217517. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  217518. {
  217519. x2 = (x + x2) * 0.5f;
  217520. y2 = (y + y2) * 0.5f;
  217521. }
  217522. destShape.startNewSubPath (x2, y2);
  217523. }
  217524. else
  217525. {
  217526. destShape.startNewSubPath (x, y);
  217527. }
  217528. }
  217529. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  217530. {
  217531. if (p != startPoint)
  217532. destShape.lineTo (x, y);
  217533. }
  217534. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  217535. {
  217536. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  217537. float x2 = scaleX * points [nextIndex].x;
  217538. float y2 = scaleY * points [nextIndex].y;
  217539. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  217540. {
  217541. x2 = (x + x2) * 0.5f;
  217542. y2 = (y + y2) * 0.5f;
  217543. }
  217544. else
  217545. {
  217546. ++p;
  217547. }
  217548. destShape.quadraticTo (x, y, x2, y2);
  217549. }
  217550. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  217551. {
  217552. if (p >= endPoint)
  217553. return false;
  217554. const int next1 = p + 1;
  217555. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  217556. const float x2 = scaleX * points [next1].x;
  217557. const float y2 = scaleY * points [next1].y;
  217558. const float x3 = scaleX * points [next2].x;
  217559. const float y3 = scaleY * points [next2].y;
  217560. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  217561. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  217562. return false;
  217563. destShape.cubicTo (x, y, x2, y2, x3, y3);
  217564. p += 2;
  217565. }
  217566. }
  217567. destShape.closeSubPath();
  217568. }
  217569. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  217570. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  217571. addKerning (face, dest, character, glyphIndex);
  217572. return true;
  217573. }
  217574. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  217575. {
  217576. const float height = (float) (face->ascender - face->descender);
  217577. uint32 rightGlyphIndex;
  217578. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  217579. while (rightGlyphIndex != 0)
  217580. {
  217581. FT_Vector kerning;
  217582. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  217583. {
  217584. if (kerning.x != 0)
  217585. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  217586. }
  217587. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  217588. }
  217589. }
  217590. // Add a glyph to a font
  217591. bool addGlyphToFont (const uint32 character, const String& fontName,
  217592. bool bold, bool italic, CustomTypeface& dest)
  217593. {
  217594. FT_Face face = createFT_Face (fontName, bold, italic);
  217595. return face != 0 && addGlyph (face, dest, character);
  217596. }
  217597. void getFamilyNames (StringArray& familyNames) const
  217598. {
  217599. for (int i = 0; i < faces.size(); i++)
  217600. familyNames.add (faces[i]->getFamilyName());
  217601. }
  217602. void getMonospacedNames (StringArray& monoSpaced) const
  217603. {
  217604. for (int i = 0; i < faces.size(); i++)
  217605. if (faces[i]->getMonospaced())
  217606. monoSpaced.add (faces[i]->getFamilyName());
  217607. }
  217608. void getSerifNames (StringArray& serif) const
  217609. {
  217610. for (int i = 0; i < faces.size(); i++)
  217611. if (faces[i]->getSerif())
  217612. serif.add (faces[i]->getFamilyName());
  217613. }
  217614. void getSansSerifNames (StringArray& sansSerif) const
  217615. {
  217616. for (int i = 0; i < faces.size(); i++)
  217617. if (! faces[i]->getSerif())
  217618. sansSerif.add (faces[i]->getFamilyName());
  217619. }
  217620. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  217621. private:
  217622. FT_Library ftLib;
  217623. FT_Face lastFace;
  217624. String lastFontName;
  217625. bool lastBold, lastItalic;
  217626. OwnedArray<FreeTypeFontFace> faces;
  217627. };
  217628. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  217629. class FreetypeTypeface : public CustomTypeface
  217630. {
  217631. public:
  217632. FreetypeTypeface (const Font& font)
  217633. {
  217634. FT_Face face = FreeTypeInterface::getInstance()
  217635. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  217636. if (face == 0)
  217637. {
  217638. #if JUCE_DEBUG
  217639. String msg ("Failed to create typeface: ");
  217640. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  217641. DBG (msg);
  217642. #endif
  217643. }
  217644. else
  217645. {
  217646. setCharacteristics (font.getTypefaceName(),
  217647. face->ascender / (float) (face->ascender - face->descender),
  217648. font.isBold(), font.isItalic(),
  217649. L' ');
  217650. }
  217651. }
  217652. bool loadGlyphIfPossible (juce_wchar character)
  217653. {
  217654. return FreeTypeInterface::getInstance()
  217655. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  217656. }
  217657. };
  217658. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  217659. {
  217660. return new FreetypeTypeface (font);
  217661. }
  217662. const StringArray Font::findAllTypefaceNames()
  217663. {
  217664. StringArray s;
  217665. FreeTypeInterface::getInstance()->getFamilyNames (s);
  217666. s.sort (true);
  217667. return s;
  217668. }
  217669. static const String pickBestFont (const StringArray& names,
  217670. const char* const choicesString)
  217671. {
  217672. StringArray choices;
  217673. choices.addTokens (String (choicesString), ",", String::empty);
  217674. choices.trim();
  217675. choices.removeEmptyStrings();
  217676. int i, j;
  217677. for (j = 0; j < choices.size(); ++j)
  217678. if (names.contains (choices[j], true))
  217679. return choices[j];
  217680. for (j = 0; j < choices.size(); ++j)
  217681. for (i = 0; i < names.size(); i++)
  217682. if (names[i].startsWithIgnoreCase (choices[j]))
  217683. return names[i];
  217684. for (j = 0; j < choices.size(); ++j)
  217685. for (i = 0; i < names.size(); i++)
  217686. if (names[i].containsIgnoreCase (choices[j]))
  217687. return names[i];
  217688. return names[0];
  217689. }
  217690. static const String linux_getDefaultSansSerifFontName()
  217691. {
  217692. StringArray allFonts;
  217693. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  217694. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  217695. }
  217696. static const String linux_getDefaultSerifFontName()
  217697. {
  217698. StringArray allFonts;
  217699. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  217700. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  217701. }
  217702. static const String linux_getDefaultMonospacedFontName()
  217703. {
  217704. StringArray allFonts;
  217705. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  217706. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  217707. }
  217708. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  217709. {
  217710. defaultSans = linux_getDefaultSansSerifFontName();
  217711. defaultSerif = linux_getDefaultSerifFontName();
  217712. defaultFixed = linux_getDefaultMonospacedFontName();
  217713. }
  217714. #endif
  217715. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  217716. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  217717. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217718. // compiled on its own).
  217719. #if JUCE_INCLUDED_FILE
  217720. // These are defined in juce_linux_Messaging.cpp
  217721. extern Display* display;
  217722. extern XContext windowHandleXContext;
  217723. namespace Atoms
  217724. {
  217725. enum ProtocolItems
  217726. {
  217727. TAKE_FOCUS = 0,
  217728. DELETE_WINDOW = 1,
  217729. PING = 2
  217730. };
  217731. static Atom Protocols, ProtocolList[3], ChangeState, State,
  217732. ActiveWin, Pid, WindowType, WindowState,
  217733. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  217734. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  217735. XdndActionDescription, XdndActionCopy,
  217736. allowedActions[5],
  217737. allowedMimeTypes[2];
  217738. const unsigned long DndVersion = 3;
  217739. static void initialiseAtoms()
  217740. {
  217741. static bool atomsInitialised = false;
  217742. if (! atomsInitialised)
  217743. {
  217744. atomsInitialised = true;
  217745. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  217746. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  217747. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  217748. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  217749. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  217750. State = XInternAtom (display, "WM_STATE", True);
  217751. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  217752. Pid = XInternAtom (display, "_NET_WM_PID", False);
  217753. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  217754. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  217755. XdndAware = XInternAtom (display, "XdndAware", False);
  217756. XdndEnter = XInternAtom (display, "XdndEnter", False);
  217757. XdndLeave = XInternAtom (display, "XdndLeave", False);
  217758. XdndPosition = XInternAtom (display, "XdndPosition", False);
  217759. XdndStatus = XInternAtom (display, "XdndStatus", False);
  217760. XdndDrop = XInternAtom (display, "XdndDrop", False);
  217761. XdndFinished = XInternAtom (display, "XdndFinished", False);
  217762. XdndSelection = XInternAtom (display, "XdndSelection", False);
  217763. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  217764. XdndActionList = XInternAtom (display, "XdndActionList", False);
  217765. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  217766. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  217767. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  217768. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  217769. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  217770. allowedActions[1] = XdndActionCopy;
  217771. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  217772. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  217773. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  217774. }
  217775. }
  217776. }
  217777. namespace Keys
  217778. {
  217779. enum MouseButtons
  217780. {
  217781. NoButton = 0,
  217782. LeftButton = 1,
  217783. MiddleButton = 2,
  217784. RightButton = 3,
  217785. WheelUp = 4,
  217786. WheelDown = 5
  217787. };
  217788. static int AltMask = 0;
  217789. static int NumLockMask = 0;
  217790. static bool numLock = false;
  217791. static bool capsLock = false;
  217792. static char keyStates [32];
  217793. static const int extendedKeyModifier = 0x10000000;
  217794. }
  217795. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  217796. {
  217797. int keysym;
  217798. if (keyCode & Keys::extendedKeyModifier)
  217799. {
  217800. keysym = 0xff00 | (keyCode & 0xff);
  217801. }
  217802. else
  217803. {
  217804. keysym = keyCode;
  217805. if (keysym == (XK_Tab & 0xff)
  217806. || keysym == (XK_Return & 0xff)
  217807. || keysym == (XK_Escape & 0xff)
  217808. || keysym == (XK_BackSpace & 0xff))
  217809. {
  217810. keysym |= 0xff00;
  217811. }
  217812. }
  217813. ScopedXLock xlock;
  217814. const int keycode = XKeysymToKeycode (display, keysym);
  217815. const int keybyte = keycode >> 3;
  217816. const int keybit = (1 << (keycode & 7));
  217817. return (Keys::keyStates [keybyte] & keybit) != 0;
  217818. }
  217819. #if JUCE_USE_XSHM
  217820. namespace XSHMHelpers
  217821. {
  217822. static int trappedErrorCode = 0;
  217823. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  217824. {
  217825. trappedErrorCode = err->error_code;
  217826. return 0;
  217827. }
  217828. static bool isShmAvailable() throw()
  217829. {
  217830. static bool isChecked = false;
  217831. static bool isAvailable = false;
  217832. if (! isChecked)
  217833. {
  217834. isChecked = true;
  217835. int major, minor;
  217836. Bool pixmaps;
  217837. ScopedXLock xlock;
  217838. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  217839. {
  217840. trappedErrorCode = 0;
  217841. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  217842. XShmSegmentInfo segmentInfo;
  217843. zerostruct (segmentInfo);
  217844. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  217845. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  217846. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  217847. xImage->bytes_per_line * xImage->height,
  217848. IPC_CREAT | 0777)) >= 0)
  217849. {
  217850. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  217851. if (segmentInfo.shmaddr != (void*) -1)
  217852. {
  217853. segmentInfo.readOnly = False;
  217854. xImage->data = segmentInfo.shmaddr;
  217855. XSync (display, False);
  217856. if (XShmAttach (display, &segmentInfo) != 0)
  217857. {
  217858. XSync (display, False);
  217859. XShmDetach (display, &segmentInfo);
  217860. isAvailable = true;
  217861. }
  217862. }
  217863. XFlush (display);
  217864. XDestroyImage (xImage);
  217865. shmdt (segmentInfo.shmaddr);
  217866. }
  217867. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  217868. XSetErrorHandler (oldHandler);
  217869. if (trappedErrorCode != 0)
  217870. isAvailable = false;
  217871. }
  217872. }
  217873. return isAvailable;
  217874. }
  217875. }
  217876. #endif
  217877. #if JUCE_USE_XRENDER
  217878. namespace XRender
  217879. {
  217880. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  217881. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  217882. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  217883. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  217884. static tXRenderQueryVersion xRenderQueryVersion = 0;
  217885. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  217886. static tXRenderFindFormat xRenderFindFormat = 0;
  217887. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  217888. static bool isAvailable()
  217889. {
  217890. static bool hasLoaded = false;
  217891. if (! hasLoaded)
  217892. {
  217893. ScopedXLock xlock;
  217894. hasLoaded = true;
  217895. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  217896. if (h != 0)
  217897. {
  217898. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  217899. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  217900. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  217901. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  217902. }
  217903. if (xRenderQueryVersion != 0
  217904. && xRenderFindStandardFormat != 0
  217905. && xRenderFindFormat != 0
  217906. && xRenderFindVisualFormat != 0)
  217907. {
  217908. int major, minor;
  217909. if (xRenderQueryVersion (display, &major, &minor))
  217910. return true;
  217911. }
  217912. xRenderQueryVersion = 0;
  217913. }
  217914. return xRenderQueryVersion != 0;
  217915. }
  217916. static XRenderPictFormat* findPictureFormat()
  217917. {
  217918. ScopedXLock xlock;
  217919. XRenderPictFormat* pictFormat = 0;
  217920. if (isAvailable())
  217921. {
  217922. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  217923. if (pictFormat == 0)
  217924. {
  217925. XRenderPictFormat desiredFormat;
  217926. desiredFormat.type = PictTypeDirect;
  217927. desiredFormat.depth = 32;
  217928. desiredFormat.direct.alphaMask = 0xff;
  217929. desiredFormat.direct.redMask = 0xff;
  217930. desiredFormat.direct.greenMask = 0xff;
  217931. desiredFormat.direct.blueMask = 0xff;
  217932. desiredFormat.direct.alpha = 24;
  217933. desiredFormat.direct.red = 16;
  217934. desiredFormat.direct.green = 8;
  217935. desiredFormat.direct.blue = 0;
  217936. pictFormat = xRenderFindFormat (display,
  217937. PictFormatType | PictFormatDepth
  217938. | PictFormatRedMask | PictFormatRed
  217939. | PictFormatGreenMask | PictFormatGreen
  217940. | PictFormatBlueMask | PictFormatBlue
  217941. | PictFormatAlphaMask | PictFormatAlpha,
  217942. &desiredFormat,
  217943. 0);
  217944. }
  217945. }
  217946. return pictFormat;
  217947. }
  217948. }
  217949. #endif
  217950. namespace Visuals
  217951. {
  217952. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  217953. {
  217954. ScopedXLock xlock;
  217955. Visual* visual = 0;
  217956. int numVisuals = 0;
  217957. long desiredMask = VisualNoMask;
  217958. XVisualInfo desiredVisual;
  217959. desiredVisual.screen = DefaultScreen (display);
  217960. desiredVisual.depth = desiredDepth;
  217961. desiredMask = VisualScreenMask | VisualDepthMask;
  217962. if (desiredDepth == 32)
  217963. {
  217964. desiredVisual.c_class = TrueColor;
  217965. desiredVisual.red_mask = 0x00FF0000;
  217966. desiredVisual.green_mask = 0x0000FF00;
  217967. desiredVisual.blue_mask = 0x000000FF;
  217968. desiredVisual.bits_per_rgb = 8;
  217969. desiredMask |= VisualClassMask;
  217970. desiredMask |= VisualRedMaskMask;
  217971. desiredMask |= VisualGreenMaskMask;
  217972. desiredMask |= VisualBlueMaskMask;
  217973. desiredMask |= VisualBitsPerRGBMask;
  217974. }
  217975. XVisualInfo* xvinfos = XGetVisualInfo (display,
  217976. desiredMask,
  217977. &desiredVisual,
  217978. &numVisuals);
  217979. if (xvinfos != 0)
  217980. {
  217981. for (int i = 0; i < numVisuals; i++)
  217982. {
  217983. if (xvinfos[i].depth == desiredDepth)
  217984. {
  217985. visual = xvinfos[i].visual;
  217986. break;
  217987. }
  217988. }
  217989. XFree (xvinfos);
  217990. }
  217991. return visual;
  217992. }
  217993. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  217994. {
  217995. Visual* visual = 0;
  217996. if (desiredDepth == 32)
  217997. {
  217998. #if JUCE_USE_XSHM
  217999. if (XSHMHelpers::isShmAvailable())
  218000. {
  218001. #if JUCE_USE_XRENDER
  218002. if (XRender::isAvailable())
  218003. {
  218004. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218005. if (pictFormat != 0)
  218006. {
  218007. int numVisuals = 0;
  218008. XVisualInfo desiredVisual;
  218009. desiredVisual.screen = DefaultScreen (display);
  218010. desiredVisual.depth = 32;
  218011. desiredVisual.bits_per_rgb = 8;
  218012. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218013. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218014. &desiredVisual, &numVisuals);
  218015. if (xvinfos != 0)
  218016. {
  218017. for (int i = 0; i < numVisuals; ++i)
  218018. {
  218019. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218020. if (pictVisualFormat != 0
  218021. && pictVisualFormat->type == PictTypeDirect
  218022. && pictVisualFormat->direct.alphaMask)
  218023. {
  218024. visual = xvinfos[i].visual;
  218025. matchedDepth = 32;
  218026. break;
  218027. }
  218028. }
  218029. XFree (xvinfos);
  218030. }
  218031. }
  218032. }
  218033. #endif
  218034. if (visual == 0)
  218035. {
  218036. visual = findVisualWithDepth (32);
  218037. if (visual != 0)
  218038. matchedDepth = 32;
  218039. }
  218040. }
  218041. #endif
  218042. }
  218043. if (visual == 0 && desiredDepth >= 24)
  218044. {
  218045. visual = findVisualWithDepth (24);
  218046. if (visual != 0)
  218047. matchedDepth = 24;
  218048. }
  218049. if (visual == 0 && desiredDepth >= 16)
  218050. {
  218051. visual = findVisualWithDepth (16);
  218052. if (visual != 0)
  218053. matchedDepth = 16;
  218054. }
  218055. return visual;
  218056. }
  218057. }
  218058. class XBitmapImage : public Image::SharedImage
  218059. {
  218060. public:
  218061. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218062. const bool clearImage, const int imageDepth_, Visual* visual)
  218063. : Image::SharedImage (format_, w, h),
  218064. imageDepth (imageDepth_),
  218065. gc (None)
  218066. {
  218067. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218068. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218069. lineStride = ((w * pixelStride + 3) & ~3);
  218070. ScopedXLock xlock;
  218071. #if JUCE_USE_XSHM
  218072. usingXShm = false;
  218073. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218074. {
  218075. zerostruct (segmentInfo);
  218076. segmentInfo.shmid = -1;
  218077. segmentInfo.shmaddr = (char *) -1;
  218078. segmentInfo.readOnly = False;
  218079. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218080. if (xImage != 0)
  218081. {
  218082. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218083. xImage->bytes_per_line * xImage->height,
  218084. IPC_CREAT | 0777)) >= 0)
  218085. {
  218086. if (segmentInfo.shmid != -1)
  218087. {
  218088. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218089. if (segmentInfo.shmaddr != (void*) -1)
  218090. {
  218091. segmentInfo.readOnly = False;
  218092. xImage->data = segmentInfo.shmaddr;
  218093. imageData = (uint8*) segmentInfo.shmaddr;
  218094. if (XShmAttach (display, &segmentInfo) != 0)
  218095. usingXShm = true;
  218096. else
  218097. jassertfalse;
  218098. }
  218099. else
  218100. {
  218101. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218102. }
  218103. }
  218104. }
  218105. }
  218106. }
  218107. if (! usingXShm)
  218108. #endif
  218109. {
  218110. imageDataAllocated.malloc (lineStride * h);
  218111. imageData = imageDataAllocated;
  218112. if (format_ == Image::ARGB && clearImage)
  218113. zeromem (imageData, h * lineStride);
  218114. xImage = (XImage*) juce_calloc (sizeof (XImage));
  218115. xImage->width = w;
  218116. xImage->height = h;
  218117. xImage->xoffset = 0;
  218118. xImage->format = ZPixmap;
  218119. xImage->data = (char*) imageData;
  218120. xImage->byte_order = ImageByteOrder (display);
  218121. xImage->bitmap_unit = BitmapUnit (display);
  218122. xImage->bitmap_bit_order = BitmapBitOrder (display);
  218123. xImage->bitmap_pad = 32;
  218124. xImage->depth = pixelStride * 8;
  218125. xImage->bytes_per_line = lineStride;
  218126. xImage->bits_per_pixel = pixelStride * 8;
  218127. xImage->red_mask = 0x00FF0000;
  218128. xImage->green_mask = 0x0000FF00;
  218129. xImage->blue_mask = 0x000000FF;
  218130. if (imageDepth == 16)
  218131. {
  218132. const int pixelStride = 2;
  218133. const int lineStride = ((w * pixelStride + 3) & ~3);
  218134. imageData16Bit.malloc (lineStride * h);
  218135. xImage->data = imageData16Bit;
  218136. xImage->bitmap_pad = 16;
  218137. xImage->depth = pixelStride * 8;
  218138. xImage->bytes_per_line = lineStride;
  218139. xImage->bits_per_pixel = pixelStride * 8;
  218140. xImage->red_mask = visual->red_mask;
  218141. xImage->green_mask = visual->green_mask;
  218142. xImage->blue_mask = visual->blue_mask;
  218143. }
  218144. if (! XInitImage (xImage))
  218145. jassertfalse;
  218146. }
  218147. }
  218148. ~XBitmapImage()
  218149. {
  218150. ScopedXLock xlock;
  218151. if (gc != None)
  218152. XFreeGC (display, gc);
  218153. #if JUCE_USE_XSHM
  218154. if (usingXShm)
  218155. {
  218156. XShmDetach (display, &segmentInfo);
  218157. XFlush (display);
  218158. XDestroyImage (xImage);
  218159. shmdt (segmentInfo.shmaddr);
  218160. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218161. }
  218162. else
  218163. #endif
  218164. {
  218165. xImage->data = 0;
  218166. XDestroyImage (xImage);
  218167. }
  218168. }
  218169. Image::ImageType getType() const { return Image::NativeImage; }
  218170. LowLevelGraphicsContext* createLowLevelContext()
  218171. {
  218172. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  218173. }
  218174. SharedImage* clone()
  218175. {
  218176. jassertfalse;
  218177. return 0;
  218178. }
  218179. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  218180. {
  218181. ScopedXLock xlock;
  218182. if (gc == None)
  218183. {
  218184. XGCValues gcvalues;
  218185. gcvalues.foreground = None;
  218186. gcvalues.background = None;
  218187. gcvalues.function = GXcopy;
  218188. gcvalues.plane_mask = AllPlanes;
  218189. gcvalues.clip_mask = None;
  218190. gcvalues.graphics_exposures = False;
  218191. gc = XCreateGC (display, window,
  218192. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  218193. &gcvalues);
  218194. }
  218195. if (imageDepth == 16)
  218196. {
  218197. const uint32 rMask = xImage->red_mask;
  218198. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  218199. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  218200. const uint32 gMask = xImage->green_mask;
  218201. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  218202. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  218203. const uint32 bMask = xImage->blue_mask;
  218204. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  218205. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  218206. const Image::BitmapData srcData (Image (this), 0, 0, width, height);
  218207. for (int y = sy; y < sy + dh; ++y)
  218208. {
  218209. const uint8* p = srcData.getPixelPointer (sx, y);
  218210. for (int x = sx; x < sx + dw; ++x)
  218211. {
  218212. const PixelRGB* const pixel = (const PixelRGB*) p;
  218213. p += srcData.pixelStride;
  218214. XPutPixel (xImage, x, y,
  218215. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  218216. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  218217. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  218218. }
  218219. }
  218220. }
  218221. // blit results to screen.
  218222. #if JUCE_USE_XSHM
  218223. if (usingXShm)
  218224. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  218225. else
  218226. #endif
  218227. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  218228. }
  218229. juce_UseDebuggingNewOperator
  218230. private:
  218231. XImage* xImage;
  218232. const int imageDepth;
  218233. HeapBlock <uint8> imageDataAllocated;
  218234. HeapBlock <char> imageData16Bit;
  218235. GC gc;
  218236. #if JUCE_USE_XSHM
  218237. XShmSegmentInfo segmentInfo;
  218238. bool usingXShm;
  218239. #endif
  218240. static int getShiftNeeded (const uint32 mask) throw()
  218241. {
  218242. for (int i = 32; --i >= 0;)
  218243. if (((mask >> i) & 1) != 0)
  218244. return i - 7;
  218245. jassertfalse;
  218246. return 0;
  218247. }
  218248. };
  218249. class LinuxComponentPeer : public ComponentPeer
  218250. {
  218251. public:
  218252. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  218253. : ComponentPeer (component, windowStyleFlags),
  218254. windowH (0),
  218255. parentWindow (0),
  218256. wx (0),
  218257. wy (0),
  218258. ww (0),
  218259. wh (0),
  218260. fullScreen (false),
  218261. mapped (false),
  218262. visual (0),
  218263. depth (0)
  218264. {
  218265. // it's dangerous to create a window on a thread other than the message thread..
  218266. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218267. repainter = new LinuxRepaintManager (this);
  218268. createWindow();
  218269. setTitle (component->getName());
  218270. }
  218271. ~LinuxComponentPeer()
  218272. {
  218273. // it's dangerous to delete a window on a thread other than the message thread..
  218274. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218275. deleteIconPixmaps();
  218276. destroyWindow();
  218277. windowH = 0;
  218278. }
  218279. void* getNativeHandle() const
  218280. {
  218281. return (void*) windowH;
  218282. }
  218283. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  218284. {
  218285. XPointer peer = 0;
  218286. ScopedXLock xlock;
  218287. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  218288. {
  218289. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  218290. peer = 0;
  218291. }
  218292. return (LinuxComponentPeer*) peer;
  218293. }
  218294. void setVisible (bool shouldBeVisible)
  218295. {
  218296. ScopedXLock xlock;
  218297. if (shouldBeVisible)
  218298. XMapWindow (display, windowH);
  218299. else
  218300. XUnmapWindow (display, windowH);
  218301. }
  218302. void setTitle (const String& title)
  218303. {
  218304. setWindowTitle (windowH, title);
  218305. }
  218306. void setPosition (int x, int y)
  218307. {
  218308. setBounds (x, y, ww, wh, false);
  218309. }
  218310. void setSize (int w, int h)
  218311. {
  218312. setBounds (wx, wy, w, h, false);
  218313. }
  218314. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  218315. {
  218316. fullScreen = isNowFullScreen;
  218317. if (windowH != 0)
  218318. {
  218319. Component::SafePointer<Component> deletionChecker (component);
  218320. wx = x;
  218321. wy = y;
  218322. ww = jmax (1, w);
  218323. wh = jmax (1, h);
  218324. ScopedXLock xlock;
  218325. // Make sure the Window manager does what we want
  218326. XSizeHints* hints = XAllocSizeHints();
  218327. hints->flags = USSize | USPosition;
  218328. hints->width = ww;
  218329. hints->height = wh;
  218330. hints->x = wx;
  218331. hints->y = wy;
  218332. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  218333. {
  218334. hints->min_width = hints->max_width = hints->width;
  218335. hints->min_height = hints->max_height = hints->height;
  218336. hints->flags |= PMinSize | PMaxSize;
  218337. }
  218338. XSetWMNormalHints (display, windowH, hints);
  218339. XFree (hints);
  218340. XMoveResizeWindow (display, windowH,
  218341. wx - windowBorder.getLeft(),
  218342. wy - windowBorder.getTop(), ww, wh);
  218343. if (deletionChecker != 0)
  218344. {
  218345. updateBorderSize();
  218346. handleMovedOrResized();
  218347. }
  218348. }
  218349. }
  218350. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  218351. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  218352. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  218353. {
  218354. return relativePosition + getScreenPosition();
  218355. }
  218356. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  218357. {
  218358. return screenPosition - getScreenPosition();
  218359. }
  218360. void setMinimised (bool shouldBeMinimised)
  218361. {
  218362. if (shouldBeMinimised)
  218363. {
  218364. Window root = RootWindow (display, DefaultScreen (display));
  218365. XClientMessageEvent clientMsg;
  218366. clientMsg.display = display;
  218367. clientMsg.window = windowH;
  218368. clientMsg.type = ClientMessage;
  218369. clientMsg.format = 32;
  218370. clientMsg.message_type = Atoms::ChangeState;
  218371. clientMsg.data.l[0] = IconicState;
  218372. ScopedXLock xlock;
  218373. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  218374. }
  218375. else
  218376. {
  218377. setVisible (true);
  218378. }
  218379. }
  218380. bool isMinimised() const
  218381. {
  218382. bool minimised = false;
  218383. unsigned char* stateProp;
  218384. unsigned long nitems, bytesLeft;
  218385. Atom actualType;
  218386. int actualFormat;
  218387. ScopedXLock xlock;
  218388. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  218389. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  218390. &stateProp) == Success
  218391. && actualType == Atoms::State
  218392. && actualFormat == 32
  218393. && nitems > 0)
  218394. {
  218395. if (((unsigned long*) stateProp)[0] == IconicState)
  218396. minimised = true;
  218397. XFree (stateProp);
  218398. }
  218399. return minimised;
  218400. }
  218401. void setFullScreen (const bool shouldBeFullScreen)
  218402. {
  218403. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  218404. setMinimised (false);
  218405. if (fullScreen != shouldBeFullScreen)
  218406. {
  218407. if (shouldBeFullScreen)
  218408. r = Desktop::getInstance().getMainMonitorArea();
  218409. if (! r.isEmpty())
  218410. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  218411. getComponent()->repaint();
  218412. }
  218413. }
  218414. bool isFullScreen() const
  218415. {
  218416. return fullScreen;
  218417. }
  218418. bool isChildWindowOf (Window possibleParent) const
  218419. {
  218420. Window* windowList = 0;
  218421. uint32 windowListSize = 0;
  218422. Window parent, root;
  218423. ScopedXLock xlock;
  218424. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  218425. {
  218426. if (windowList != 0)
  218427. XFree (windowList);
  218428. return parent == possibleParent;
  218429. }
  218430. return false;
  218431. }
  218432. bool isFrontWindow() const
  218433. {
  218434. Window* windowList = 0;
  218435. uint32 windowListSize = 0;
  218436. bool result = false;
  218437. ScopedXLock xlock;
  218438. Window parent, root = RootWindow (display, DefaultScreen (display));
  218439. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  218440. {
  218441. for (int i = windowListSize; --i >= 0;)
  218442. {
  218443. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  218444. if (peer != 0)
  218445. {
  218446. result = (peer == this);
  218447. break;
  218448. }
  218449. }
  218450. }
  218451. if (windowList != 0)
  218452. XFree (windowList);
  218453. return result;
  218454. }
  218455. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  218456. {
  218457. int x = position.getX();
  218458. int y = position.getY();
  218459. if (((unsigned int) x) >= (unsigned int) ww
  218460. || ((unsigned int) y) >= (unsigned int) wh)
  218461. return false;
  218462. bool inFront = false;
  218463. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  218464. {
  218465. Component* const c = Desktop::getInstance().getComponent (i);
  218466. if (inFront)
  218467. {
  218468. if (c->contains (x + wx - c->getScreenX(),
  218469. y + wy - c->getScreenY()))
  218470. {
  218471. return false;
  218472. }
  218473. }
  218474. else if (c == getComponent())
  218475. {
  218476. inFront = true;
  218477. }
  218478. }
  218479. if (trueIfInAChildWindow)
  218480. return true;
  218481. ::Window root, child;
  218482. unsigned int bw, depth;
  218483. int wx, wy, w, h;
  218484. ScopedXLock xlock;
  218485. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  218486. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  218487. &bw, &depth))
  218488. {
  218489. return false;
  218490. }
  218491. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  218492. return false;
  218493. return child == None;
  218494. }
  218495. const BorderSize getFrameSize() const
  218496. {
  218497. return BorderSize();
  218498. }
  218499. bool setAlwaysOnTop (bool alwaysOnTop)
  218500. {
  218501. return false;
  218502. }
  218503. void toFront (bool makeActive)
  218504. {
  218505. if (makeActive)
  218506. {
  218507. setVisible (true);
  218508. grabFocus();
  218509. }
  218510. XEvent ev;
  218511. ev.xclient.type = ClientMessage;
  218512. ev.xclient.serial = 0;
  218513. ev.xclient.send_event = True;
  218514. ev.xclient.message_type = Atoms::ActiveWin;
  218515. ev.xclient.window = windowH;
  218516. ev.xclient.format = 32;
  218517. ev.xclient.data.l[0] = 2;
  218518. ev.xclient.data.l[1] = CurrentTime;
  218519. ev.xclient.data.l[2] = 0;
  218520. ev.xclient.data.l[3] = 0;
  218521. ev.xclient.data.l[4] = 0;
  218522. {
  218523. ScopedXLock xlock;
  218524. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  218525. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  218526. XWindowAttributes attr;
  218527. XGetWindowAttributes (display, windowH, &attr);
  218528. if (component->isAlwaysOnTop())
  218529. XRaiseWindow (display, windowH);
  218530. XSync (display, False);
  218531. }
  218532. handleBroughtToFront();
  218533. }
  218534. void toBehind (ComponentPeer* other)
  218535. {
  218536. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  218537. jassert (otherPeer != 0); // wrong type of window?
  218538. if (otherPeer != 0)
  218539. {
  218540. setMinimised (false);
  218541. Window newStack[] = { otherPeer->windowH, windowH };
  218542. ScopedXLock xlock;
  218543. XRestackWindows (display, newStack, 2);
  218544. }
  218545. }
  218546. bool isFocused() const
  218547. {
  218548. int revert = 0;
  218549. Window focusedWindow = 0;
  218550. ScopedXLock xlock;
  218551. XGetInputFocus (display, &focusedWindow, &revert);
  218552. return focusedWindow == windowH;
  218553. }
  218554. void grabFocus()
  218555. {
  218556. XWindowAttributes atts;
  218557. ScopedXLock xlock;
  218558. if (windowH != 0
  218559. && XGetWindowAttributes (display, windowH, &atts)
  218560. && atts.map_state == IsViewable
  218561. && ! isFocused())
  218562. {
  218563. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  218564. isActiveApplication = true;
  218565. }
  218566. }
  218567. void textInputRequired (const Point<int>&)
  218568. {
  218569. }
  218570. void repaint (const Rectangle<int>& area)
  218571. {
  218572. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  218573. }
  218574. void performAnyPendingRepaintsNow()
  218575. {
  218576. repainter->performAnyPendingRepaintsNow();
  218577. }
  218578. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  218579. {
  218580. ScopedXLock xlock;
  218581. const int width = image.getWidth();
  218582. const int height = image.getHeight();
  218583. HeapBlock <char> colour (width * height);
  218584. int index = 0;
  218585. for (int y = 0; y < height; ++y)
  218586. for (int x = 0; x < width; ++x)
  218587. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  218588. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  218589. 0, colour.getData(),
  218590. width, height, 32, 0);
  218591. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  218592. width, height, 24);
  218593. GC gc = XCreateGC (display, pixmap, 0, 0);
  218594. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  218595. XFreeGC (display, gc);
  218596. return pixmap;
  218597. }
  218598. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  218599. {
  218600. ScopedXLock xlock;
  218601. const int width = image.getWidth();
  218602. const int height = image.getHeight();
  218603. const int stride = (width + 7) >> 3;
  218604. HeapBlock <char> mask;
  218605. mask.calloc (stride * height);
  218606. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  218607. for (int y = 0; y < height; ++y)
  218608. {
  218609. for (int x = 0; x < width; ++x)
  218610. {
  218611. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  218612. const int offset = y * stride + (x >> 3);
  218613. if (image.getPixelAt (x, y).getAlpha() >= 128)
  218614. mask[offset] |= bit;
  218615. }
  218616. }
  218617. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  218618. mask.getData(), width, height, 1, 0, 1);
  218619. }
  218620. void setIcon (const Image& newIcon)
  218621. {
  218622. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  218623. HeapBlock <unsigned long> data (dataSize);
  218624. int index = 0;
  218625. data[index++] = newIcon.getWidth();
  218626. data[index++] = newIcon.getHeight();
  218627. for (int y = 0; y < newIcon.getHeight(); ++y)
  218628. for (int x = 0; x < newIcon.getWidth(); ++x)
  218629. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  218630. ScopedXLock xlock;
  218631. XChangeProperty (display, windowH,
  218632. XInternAtom (display, "_NET_WM_ICON", False),
  218633. XA_CARDINAL, 32, PropModeReplace,
  218634. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  218635. deleteIconPixmaps();
  218636. XWMHints* wmHints = XGetWMHints (display, windowH);
  218637. if (wmHints == 0)
  218638. wmHints = XAllocWMHints();
  218639. wmHints->flags |= IconPixmapHint | IconMaskHint;
  218640. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  218641. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  218642. XSetWMHints (display, windowH, wmHints);
  218643. XFree (wmHints);
  218644. XSync (display, False);
  218645. }
  218646. void deleteIconPixmaps()
  218647. {
  218648. ScopedXLock xlock;
  218649. XWMHints* wmHints = XGetWMHints (display, windowH);
  218650. if (wmHints != 0)
  218651. {
  218652. if ((wmHints->flags & IconPixmapHint) != 0)
  218653. {
  218654. wmHints->flags &= ~IconPixmapHint;
  218655. XFreePixmap (display, wmHints->icon_pixmap);
  218656. }
  218657. if ((wmHints->flags & IconMaskHint) != 0)
  218658. {
  218659. wmHints->flags &= ~IconMaskHint;
  218660. XFreePixmap (display, wmHints->icon_mask);
  218661. }
  218662. XSetWMHints (display, windowH, wmHints);
  218663. XFree (wmHints);
  218664. }
  218665. }
  218666. void handleWindowMessage (XEvent* event)
  218667. {
  218668. switch (event->xany.type)
  218669. {
  218670. case 2: // 'KeyPress'
  218671. {
  218672. ScopedXLock xlock;
  218673. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  218674. updateKeyStates (keyEvent->keycode, true);
  218675. char utf8 [64];
  218676. zeromem (utf8, sizeof (utf8));
  218677. KeySym sym;
  218678. {
  218679. const char* oldLocale = ::setlocale (LC_ALL, 0);
  218680. ::setlocale (LC_ALL, "");
  218681. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  218682. ::setlocale (LC_ALL, oldLocale);
  218683. }
  218684. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  218685. int keyCode = (int) unicodeChar;
  218686. if (keyCode < 0x20)
  218687. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  218688. const ModifierKeys oldMods (currentModifiers);
  218689. bool keyPressed = false;
  218690. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  218691. if ((sym & 0xff00) == 0xff00)
  218692. {
  218693. // Translate keypad
  218694. if (sym == XK_KP_Divide)
  218695. keyCode = XK_slash;
  218696. else if (sym == XK_KP_Multiply)
  218697. keyCode = XK_asterisk;
  218698. else if (sym == XK_KP_Subtract)
  218699. keyCode = XK_hyphen;
  218700. else if (sym == XK_KP_Add)
  218701. keyCode = XK_plus;
  218702. else if (sym == XK_KP_Enter)
  218703. keyCode = XK_Return;
  218704. else if (sym == XK_KP_Decimal)
  218705. keyCode = Keys::numLock ? XK_period : XK_Delete;
  218706. else if (sym == XK_KP_0)
  218707. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  218708. else if (sym == XK_KP_1)
  218709. keyCode = Keys::numLock ? XK_1 : XK_End;
  218710. else if (sym == XK_KP_2)
  218711. keyCode = Keys::numLock ? XK_2 : XK_Down;
  218712. else if (sym == XK_KP_3)
  218713. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  218714. else if (sym == XK_KP_4)
  218715. keyCode = Keys::numLock ? XK_4 : XK_Left;
  218716. else if (sym == XK_KP_5)
  218717. keyCode = XK_5;
  218718. else if (sym == XK_KP_6)
  218719. keyCode = Keys::numLock ? XK_6 : XK_Right;
  218720. else if (sym == XK_KP_7)
  218721. keyCode = Keys::numLock ? XK_7 : XK_Home;
  218722. else if (sym == XK_KP_8)
  218723. keyCode = Keys::numLock ? XK_8 : XK_Up;
  218724. else if (sym == XK_KP_9)
  218725. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  218726. switch (sym)
  218727. {
  218728. case XK_Left:
  218729. case XK_Right:
  218730. case XK_Up:
  218731. case XK_Down:
  218732. case XK_Page_Up:
  218733. case XK_Page_Down:
  218734. case XK_End:
  218735. case XK_Home:
  218736. case XK_Delete:
  218737. case XK_Insert:
  218738. keyPressed = true;
  218739. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  218740. break;
  218741. case XK_Tab:
  218742. case XK_Return:
  218743. case XK_Escape:
  218744. case XK_BackSpace:
  218745. keyPressed = true;
  218746. keyCode &= 0xff;
  218747. break;
  218748. default:
  218749. {
  218750. if (sym >= XK_F1 && sym <= XK_F16)
  218751. {
  218752. keyPressed = true;
  218753. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  218754. }
  218755. break;
  218756. }
  218757. }
  218758. }
  218759. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  218760. keyPressed = true;
  218761. if (oldMods != currentModifiers)
  218762. handleModifierKeysChange();
  218763. if (keyDownChange)
  218764. handleKeyUpOrDown (true);
  218765. if (keyPressed)
  218766. handleKeyPress (keyCode, unicodeChar);
  218767. break;
  218768. }
  218769. case KeyRelease:
  218770. {
  218771. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  218772. updateKeyStates (keyEvent->keycode, false);
  218773. ScopedXLock xlock;
  218774. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  218775. const ModifierKeys oldMods (currentModifiers);
  218776. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  218777. if (oldMods != currentModifiers)
  218778. handleModifierKeysChange();
  218779. if (keyDownChange)
  218780. handleKeyUpOrDown (false);
  218781. break;
  218782. }
  218783. case ButtonPress:
  218784. {
  218785. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  218786. updateKeyModifiers (buttonPressEvent->state);
  218787. bool buttonMsg = false;
  218788. const int map = pointerMap [buttonPressEvent->button - Button1];
  218789. if (map == Keys::WheelUp || map == Keys::WheelDown)
  218790. {
  218791. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  218792. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  218793. }
  218794. if (map == Keys::LeftButton)
  218795. {
  218796. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  218797. buttonMsg = true;
  218798. }
  218799. else if (map == Keys::RightButton)
  218800. {
  218801. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  218802. buttonMsg = true;
  218803. }
  218804. else if (map == Keys::MiddleButton)
  218805. {
  218806. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  218807. buttonMsg = true;
  218808. }
  218809. if (buttonMsg)
  218810. {
  218811. toFront (true);
  218812. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  218813. getEventTime (buttonPressEvent->time));
  218814. }
  218815. clearLastMousePos();
  218816. break;
  218817. }
  218818. case ButtonRelease:
  218819. {
  218820. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  218821. updateKeyModifiers (buttonRelEvent->state);
  218822. const int map = pointerMap [buttonRelEvent->button - Button1];
  218823. if (map == Keys::LeftButton)
  218824. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  218825. else if (map == Keys::RightButton)
  218826. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  218827. else if (map == Keys::MiddleButton)
  218828. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  218829. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  218830. getEventTime (buttonRelEvent->time));
  218831. clearLastMousePos();
  218832. break;
  218833. }
  218834. case MotionNotify:
  218835. {
  218836. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  218837. updateKeyModifiers (movedEvent->state);
  218838. const Point<int> mousePos (Desktop::getMousePosition());
  218839. if (lastMousePos != mousePos)
  218840. {
  218841. lastMousePos = mousePos;
  218842. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  218843. {
  218844. Window wRoot = 0, wParent = 0;
  218845. {
  218846. ScopedXLock xlock;
  218847. unsigned int numChildren;
  218848. Window* wChild = 0;
  218849. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  218850. }
  218851. if (wParent != 0
  218852. && wParent != windowH
  218853. && wParent != wRoot)
  218854. {
  218855. parentWindow = wParent;
  218856. updateBounds();
  218857. }
  218858. else
  218859. {
  218860. parentWindow = 0;
  218861. }
  218862. }
  218863. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  218864. }
  218865. break;
  218866. }
  218867. case EnterNotify:
  218868. {
  218869. clearLastMousePos();
  218870. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  218871. if (! currentModifiers.isAnyMouseButtonDown())
  218872. {
  218873. updateKeyModifiers (enterEvent->state);
  218874. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  218875. }
  218876. break;
  218877. }
  218878. case LeaveNotify:
  218879. {
  218880. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  218881. // Suppress the normal leave if we've got a pointer grab, or if
  218882. // it's a bogus one caused by clicking a mouse button when running
  218883. // in a Window manager
  218884. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  218885. || leaveEvent->mode == NotifyUngrab)
  218886. {
  218887. updateKeyModifiers (leaveEvent->state);
  218888. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  218889. }
  218890. break;
  218891. }
  218892. case FocusIn:
  218893. {
  218894. isActiveApplication = true;
  218895. if (isFocused())
  218896. handleFocusGain();
  218897. break;
  218898. }
  218899. case FocusOut:
  218900. {
  218901. isActiveApplication = false;
  218902. if (! isFocused())
  218903. handleFocusLoss();
  218904. break;
  218905. }
  218906. case Expose:
  218907. {
  218908. // Batch together all pending expose events
  218909. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  218910. XEvent nextEvent;
  218911. ScopedXLock xlock;
  218912. if (exposeEvent->window != windowH)
  218913. {
  218914. Window child;
  218915. XTranslateCoordinates (display, exposeEvent->window, windowH,
  218916. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  218917. &child);
  218918. }
  218919. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  218920. exposeEvent->width, exposeEvent->height));
  218921. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  218922. {
  218923. XPeekEvent (display, (XEvent*) &nextEvent);
  218924. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  218925. break;
  218926. XNextEvent (display, (XEvent*) &nextEvent);
  218927. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  218928. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  218929. nextExposeEvent->width, nextExposeEvent->height));
  218930. }
  218931. break;
  218932. }
  218933. case CirculateNotify:
  218934. case CreateNotify:
  218935. case DestroyNotify:
  218936. // Think we can ignore these
  218937. break;
  218938. case ConfigureNotify:
  218939. {
  218940. updateBounds();
  218941. updateBorderSize();
  218942. handleMovedOrResized();
  218943. // if the native title bar is dragged, need to tell any active menus, etc.
  218944. if ((styleFlags & windowHasTitleBar) != 0
  218945. && component->isCurrentlyBlockedByAnotherModalComponent())
  218946. {
  218947. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  218948. if (currentModalComp != 0)
  218949. currentModalComp->inputAttemptWhenModal();
  218950. }
  218951. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  218952. if (confEvent->window == windowH
  218953. && confEvent->above != 0
  218954. && isFrontWindow())
  218955. {
  218956. handleBroughtToFront();
  218957. }
  218958. break;
  218959. }
  218960. case ReparentNotify:
  218961. {
  218962. parentWindow = 0;
  218963. Window wRoot = 0;
  218964. Window* wChild = 0;
  218965. unsigned int numChildren;
  218966. {
  218967. ScopedXLock xlock;
  218968. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  218969. }
  218970. if (parentWindow == windowH || parentWindow == wRoot)
  218971. parentWindow = 0;
  218972. updateBounds();
  218973. updateBorderSize();
  218974. handleMovedOrResized();
  218975. break;
  218976. }
  218977. case GravityNotify:
  218978. {
  218979. updateBounds();
  218980. updateBorderSize();
  218981. handleMovedOrResized();
  218982. break;
  218983. }
  218984. case MapNotify:
  218985. mapped = true;
  218986. handleBroughtToFront();
  218987. break;
  218988. case UnmapNotify:
  218989. mapped = false;
  218990. break;
  218991. case MappingNotify:
  218992. {
  218993. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  218994. if (mappingEvent->request != MappingPointer)
  218995. {
  218996. // Deal with modifier/keyboard mapping
  218997. ScopedXLock xlock;
  218998. XRefreshKeyboardMapping (mappingEvent);
  218999. updateModifierMappings();
  219000. }
  219001. break;
  219002. }
  219003. case ClientMessage:
  219004. {
  219005. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  219006. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219007. {
  219008. const Atom atom = (Atom) clientMsg->data.l[0];
  219009. if (atom == Atoms::ProtocolList [Atoms::PING])
  219010. {
  219011. Window root = RootWindow (display, DefaultScreen (display));
  219012. event->xclient.window = root;
  219013. XSendEvent (display, root, False, NoEventMask, event);
  219014. XFlush (display);
  219015. }
  219016. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219017. {
  219018. XWindowAttributes atts;
  219019. ScopedXLock xlock;
  219020. if (clientMsg->window != 0
  219021. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219022. {
  219023. if (atts.map_state == IsViewable)
  219024. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219025. }
  219026. }
  219027. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219028. {
  219029. handleUserClosingWindow();
  219030. }
  219031. }
  219032. else if (clientMsg->message_type == Atoms::XdndEnter)
  219033. {
  219034. handleDragAndDropEnter (clientMsg);
  219035. }
  219036. else if (clientMsg->message_type == Atoms::XdndLeave)
  219037. {
  219038. resetDragAndDrop();
  219039. }
  219040. else if (clientMsg->message_type == Atoms::XdndPosition)
  219041. {
  219042. handleDragAndDropPosition (clientMsg);
  219043. }
  219044. else if (clientMsg->message_type == Atoms::XdndDrop)
  219045. {
  219046. handleDragAndDropDrop (clientMsg);
  219047. }
  219048. else if (clientMsg->message_type == Atoms::XdndStatus)
  219049. {
  219050. handleDragAndDropStatus (clientMsg);
  219051. }
  219052. else if (clientMsg->message_type == Atoms::XdndFinished)
  219053. {
  219054. resetDragAndDrop();
  219055. }
  219056. break;
  219057. }
  219058. case SelectionNotify:
  219059. handleDragAndDropSelection (event);
  219060. break;
  219061. case SelectionClear:
  219062. case SelectionRequest:
  219063. break;
  219064. default:
  219065. #if JUCE_USE_XSHM
  219066. {
  219067. ScopedXLock xlock;
  219068. if (event->xany.type == XShmGetEventBase (display))
  219069. repainter->notifyPaintCompleted();
  219070. }
  219071. #endif
  219072. break;
  219073. }
  219074. }
  219075. void showMouseCursor (Cursor cursor) throw()
  219076. {
  219077. ScopedXLock xlock;
  219078. XDefineCursor (display, windowH, cursor);
  219079. }
  219080. void setTaskBarIcon (const Image& image)
  219081. {
  219082. ScopedXLock xlock;
  219083. taskbarImage = image;
  219084. Screen* const screen = XDefaultScreenOfDisplay (display);
  219085. const int screenNumber = XScreenNumberOfScreen (screen);
  219086. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219087. screenAtom << screenNumber;
  219088. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219089. XGrabServer (display);
  219090. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219091. if (managerWin != None)
  219092. XSelectInput (display, managerWin, StructureNotifyMask);
  219093. XUngrabServer (display);
  219094. XFlush (display);
  219095. if (managerWin != None)
  219096. {
  219097. XEvent ev;
  219098. zerostruct (ev);
  219099. ev.xclient.type = ClientMessage;
  219100. ev.xclient.window = managerWin;
  219101. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219102. ev.xclient.format = 32;
  219103. ev.xclient.data.l[0] = CurrentTime;
  219104. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219105. ev.xclient.data.l[2] = windowH;
  219106. ev.xclient.data.l[3] = 0;
  219107. ev.xclient.data.l[4] = 0;
  219108. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219109. XSync (display, False);
  219110. }
  219111. // For older KDE's ...
  219112. long atomData = 1;
  219113. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219114. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219115. // For more recent KDE's...
  219116. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219117. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219118. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219119. XSizeHints* hints = XAllocSizeHints();
  219120. hints->flags = PMinSize;
  219121. hints->min_width = 22;
  219122. hints->min_height = 22;
  219123. XSetWMNormalHints (display, windowH, hints);
  219124. XFree (hints);
  219125. }
  219126. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  219127. juce_UseDebuggingNewOperator
  219128. bool dontRepaint;
  219129. static ModifierKeys currentModifiers;
  219130. static bool isActiveApplication;
  219131. private:
  219132. class LinuxRepaintManager : public Timer
  219133. {
  219134. public:
  219135. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  219136. : peer (peer_),
  219137. lastTimeImageUsed (0)
  219138. {
  219139. #if JUCE_USE_XSHM
  219140. shmCompletedDrawing = true;
  219141. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  219142. if (useARGBImagesForRendering)
  219143. {
  219144. ScopedXLock xlock;
  219145. XShmSegmentInfo segmentinfo;
  219146. XImage* const testImage
  219147. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219148. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  219149. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  219150. XDestroyImage (testImage);
  219151. }
  219152. #endif
  219153. }
  219154. ~LinuxRepaintManager()
  219155. {
  219156. }
  219157. void timerCallback()
  219158. {
  219159. #if JUCE_USE_XSHM
  219160. if (! shmCompletedDrawing)
  219161. return;
  219162. #endif
  219163. if (! regionsNeedingRepaint.isEmpty())
  219164. {
  219165. stopTimer();
  219166. performAnyPendingRepaintsNow();
  219167. }
  219168. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  219169. {
  219170. stopTimer();
  219171. image = Image();
  219172. }
  219173. }
  219174. void repaint (const Rectangle<int>& area)
  219175. {
  219176. if (! isTimerRunning())
  219177. startTimer (repaintTimerPeriod);
  219178. regionsNeedingRepaint.add (area);
  219179. }
  219180. void performAnyPendingRepaintsNow()
  219181. {
  219182. #if JUCE_USE_XSHM
  219183. if (! shmCompletedDrawing)
  219184. {
  219185. startTimer (repaintTimerPeriod);
  219186. return;
  219187. }
  219188. #endif
  219189. peer->clearMaskedRegion();
  219190. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  219191. regionsNeedingRepaint.clear();
  219192. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  219193. if (! totalArea.isEmpty())
  219194. {
  219195. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  219196. || image.getHeight() < totalArea.getHeight())
  219197. {
  219198. #if JUCE_USE_XSHM
  219199. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  219200. : Image::RGB,
  219201. #else
  219202. image = Image (new XBitmapImage (Image::RGB,
  219203. #endif
  219204. (totalArea.getWidth() + 31) & ~31,
  219205. (totalArea.getHeight() + 31) & ~31,
  219206. false, peer->depth, peer->visual));
  219207. }
  219208. startTimer (repaintTimerPeriod);
  219209. RectangleList adjustedList (originalRepaintRegion);
  219210. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  219211. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  219212. if (peer->depth == 32)
  219213. {
  219214. RectangleList::Iterator i (originalRepaintRegion);
  219215. while (i.next())
  219216. image.clear (*i.getRectangle() - totalArea.getPosition());
  219217. }
  219218. peer->handlePaint (context);
  219219. if (! peer->maskedRegion.isEmpty())
  219220. originalRepaintRegion.subtract (peer->maskedRegion);
  219221. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  219222. {
  219223. #if JUCE_USE_XSHM
  219224. shmCompletedDrawing = false;
  219225. #endif
  219226. const Rectangle<int>& r = *i.getRectangle();
  219227. static_cast<XBitmapImage*> (image.getSharedImage())
  219228. ->blitToWindow (peer->windowH,
  219229. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  219230. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  219231. }
  219232. }
  219233. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  219234. startTimer (repaintTimerPeriod);
  219235. }
  219236. #if JUCE_USE_XSHM
  219237. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  219238. #endif
  219239. private:
  219240. enum { repaintTimerPeriod = 1000 / 100 };
  219241. LinuxComponentPeer* const peer;
  219242. Image image;
  219243. uint32 lastTimeImageUsed;
  219244. RectangleList regionsNeedingRepaint;
  219245. #if JUCE_USE_XSHM
  219246. bool useARGBImagesForRendering, shmCompletedDrawing;
  219247. #endif
  219248. LinuxRepaintManager (const LinuxRepaintManager&);
  219249. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  219250. };
  219251. ScopedPointer <LinuxRepaintManager> repainter;
  219252. friend class LinuxRepaintManager;
  219253. Window windowH, parentWindow;
  219254. int wx, wy, ww, wh;
  219255. Image taskbarImage;
  219256. bool fullScreen, mapped;
  219257. Visual* visual;
  219258. int depth;
  219259. BorderSize windowBorder;
  219260. struct MotifWmHints
  219261. {
  219262. unsigned long flags;
  219263. unsigned long functions;
  219264. unsigned long decorations;
  219265. long input_mode;
  219266. unsigned long status;
  219267. };
  219268. static void updateKeyStates (const int keycode, const bool press) throw()
  219269. {
  219270. const int keybyte = keycode >> 3;
  219271. const int keybit = (1 << (keycode & 7));
  219272. if (press)
  219273. Keys::keyStates [keybyte] |= keybit;
  219274. else
  219275. Keys::keyStates [keybyte] &= ~keybit;
  219276. }
  219277. static void updateKeyModifiers (const int status) throw()
  219278. {
  219279. int keyMods = 0;
  219280. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  219281. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  219282. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  219283. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  219284. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  219285. Keys::capsLock = ((status & LockMask) != 0);
  219286. }
  219287. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  219288. {
  219289. int modifier = 0;
  219290. bool isModifier = true;
  219291. switch (sym)
  219292. {
  219293. case XK_Shift_L:
  219294. case XK_Shift_R:
  219295. modifier = ModifierKeys::shiftModifier;
  219296. break;
  219297. case XK_Control_L:
  219298. case XK_Control_R:
  219299. modifier = ModifierKeys::ctrlModifier;
  219300. break;
  219301. case XK_Alt_L:
  219302. case XK_Alt_R:
  219303. modifier = ModifierKeys::altModifier;
  219304. break;
  219305. case XK_Num_Lock:
  219306. if (press)
  219307. Keys::numLock = ! Keys::numLock;
  219308. break;
  219309. case XK_Caps_Lock:
  219310. if (press)
  219311. Keys::capsLock = ! Keys::capsLock;
  219312. break;
  219313. case XK_Scroll_Lock:
  219314. break;
  219315. default:
  219316. isModifier = false;
  219317. break;
  219318. }
  219319. if (modifier != 0)
  219320. {
  219321. if (press)
  219322. currentModifiers = currentModifiers.withFlags (modifier);
  219323. else
  219324. currentModifiers = currentModifiers.withoutFlags (modifier);
  219325. }
  219326. return isModifier;
  219327. }
  219328. // Alt and Num lock are not defined by standard X
  219329. // modifier constants: check what they're mapped to
  219330. static void updateModifierMappings() throw()
  219331. {
  219332. ScopedXLock xlock;
  219333. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  219334. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  219335. Keys::AltMask = 0;
  219336. Keys::NumLockMask = 0;
  219337. XModifierKeymap* mapping = XGetModifierMapping (display);
  219338. if (mapping)
  219339. {
  219340. for (int i = 0; i < 8; i++)
  219341. {
  219342. if (mapping->modifiermap [i << 1] == altLeftCode)
  219343. Keys::AltMask = 1 << i;
  219344. else if (mapping->modifiermap [i << 1] == numLockCode)
  219345. Keys::NumLockMask = 1 << i;
  219346. }
  219347. XFreeModifiermap (mapping);
  219348. }
  219349. }
  219350. void removeWindowDecorations (Window wndH)
  219351. {
  219352. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219353. if (hints != None)
  219354. {
  219355. MotifWmHints motifHints;
  219356. zerostruct (motifHints);
  219357. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  219358. motifHints.decorations = 0;
  219359. ScopedXLock xlock;
  219360. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219361. (unsigned char*) &motifHints, 4);
  219362. }
  219363. hints = XInternAtom (display, "_WIN_HINTS", True);
  219364. if (hints != None)
  219365. {
  219366. long gnomeHints = 0;
  219367. ScopedXLock xlock;
  219368. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219369. (unsigned char*) &gnomeHints, 1);
  219370. }
  219371. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  219372. if (hints != None)
  219373. {
  219374. long kwmHints = 2; /*KDE_tinyDecoration*/
  219375. ScopedXLock xlock;
  219376. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219377. (unsigned char*) &kwmHints, 1);
  219378. }
  219379. }
  219380. void addWindowButtons (Window wndH)
  219381. {
  219382. ScopedXLock xlock;
  219383. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219384. if (hints != None)
  219385. {
  219386. MotifWmHints motifHints;
  219387. zerostruct (motifHints);
  219388. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  219389. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  219390. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  219391. if ((styleFlags & windowHasCloseButton) != 0)
  219392. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  219393. if ((styleFlags & windowHasMinimiseButton) != 0)
  219394. {
  219395. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  219396. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  219397. }
  219398. if ((styleFlags & windowHasMaximiseButton) != 0)
  219399. {
  219400. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  219401. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  219402. }
  219403. if ((styleFlags & windowIsResizable) != 0)
  219404. {
  219405. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  219406. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  219407. }
  219408. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  219409. }
  219410. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  219411. if (hints != None)
  219412. {
  219413. int netHints [6];
  219414. int num = 0;
  219415. if ((styleFlags & windowIsResizable) != 0)
  219416. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  219417. if ((styleFlags & windowHasMaximiseButton) != 0)
  219418. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  219419. if ((styleFlags & windowHasMinimiseButton) != 0)
  219420. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  219421. if ((styleFlags & windowHasCloseButton) != 0)
  219422. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  219423. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  219424. }
  219425. }
  219426. void setWindowType()
  219427. {
  219428. int netHints [2];
  219429. int numHints = 0;
  219430. if ((styleFlags & windowIsTemporary) != 0
  219431. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  219432. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  219433. else
  219434. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  219435. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  219436. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  219437. (unsigned char*) &netHints, numHints);
  219438. numHints = 0;
  219439. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  219440. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  219441. if (component->isAlwaysOnTop())
  219442. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  219443. if (numHints > 0)
  219444. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  219445. (unsigned char*) &netHints, numHints);
  219446. }
  219447. void createWindow()
  219448. {
  219449. ScopedXLock xlock;
  219450. Atoms::initialiseAtoms();
  219451. resetDragAndDrop();
  219452. // Get defaults for various properties
  219453. const int screen = DefaultScreen (display);
  219454. Window root = RootWindow (display, screen);
  219455. // Try to obtain a 32-bit visual or fallback to 24 or 16
  219456. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  219457. if (visual == 0)
  219458. {
  219459. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  219460. Process::terminate();
  219461. }
  219462. // Create and install a colormap suitable fr our visual
  219463. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  219464. XInstallColormap (display, colormap);
  219465. // Set up the window attributes
  219466. XSetWindowAttributes swa;
  219467. swa.border_pixel = 0;
  219468. swa.background_pixmap = None;
  219469. swa.colormap = colormap;
  219470. swa.event_mask = getAllEventsMask();
  219471. windowH = XCreateWindow (display, root,
  219472. 0, 0, 1, 1,
  219473. 0, depth, InputOutput, visual,
  219474. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  219475. &swa);
  219476. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  219477. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  219478. GrabModeAsync, GrabModeAsync, None, None);
  219479. // Set the window context to identify the window handle object
  219480. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  219481. {
  219482. // Failed
  219483. jassertfalse;
  219484. Logger::outputDebugString ("Failed to create context information for window.\n");
  219485. XDestroyWindow (display, windowH);
  219486. windowH = 0;
  219487. return;
  219488. }
  219489. // Set window manager hints
  219490. XWMHints* wmHints = XAllocWMHints();
  219491. wmHints->flags = InputHint | StateHint;
  219492. wmHints->input = True; // Locally active input model
  219493. wmHints->initial_state = NormalState;
  219494. XSetWMHints (display, windowH, wmHints);
  219495. XFree (wmHints);
  219496. // Set the window type
  219497. setWindowType();
  219498. // Define decoration
  219499. if ((styleFlags & windowHasTitleBar) == 0)
  219500. removeWindowDecorations (windowH);
  219501. else
  219502. addWindowButtons (windowH);
  219503. // Set window name
  219504. setWindowTitle (windowH, getComponent()->getName());
  219505. // Associate the PID, allowing to be shut down when something goes wrong
  219506. unsigned long pid = getpid();
  219507. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  219508. (unsigned char*) &pid, 1);
  219509. // Set window manager protocols
  219510. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  219511. (unsigned char*) Atoms::ProtocolList, 2);
  219512. // Set drag and drop flags
  219513. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  219514. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  219515. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  219516. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  219517. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  219518. (const unsigned char*) "", 0);
  219519. unsigned long dndVersion = Atoms::DndVersion;
  219520. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  219521. (const unsigned char*) &dndVersion, 1);
  219522. // Initialise the pointer and keyboard mapping
  219523. // This is not the same as the logical pointer mapping the X server uses:
  219524. // we don't mess with this.
  219525. static bool mappingInitialised = false;
  219526. if (! mappingInitialised)
  219527. {
  219528. mappingInitialised = true;
  219529. const int numButtons = XGetPointerMapping (display, 0, 0);
  219530. if (numButtons == 2)
  219531. {
  219532. pointerMap[0] = Keys::LeftButton;
  219533. pointerMap[1] = Keys::RightButton;
  219534. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  219535. }
  219536. else if (numButtons >= 3)
  219537. {
  219538. pointerMap[0] = Keys::LeftButton;
  219539. pointerMap[1] = Keys::MiddleButton;
  219540. pointerMap[2] = Keys::RightButton;
  219541. if (numButtons >= 5)
  219542. {
  219543. pointerMap[3] = Keys::WheelUp;
  219544. pointerMap[4] = Keys::WheelDown;
  219545. }
  219546. }
  219547. updateModifierMappings();
  219548. }
  219549. }
  219550. void destroyWindow()
  219551. {
  219552. ScopedXLock xlock;
  219553. XPointer handlePointer;
  219554. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  219555. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  219556. XDestroyWindow (display, windowH);
  219557. // Wait for it to complete and then remove any events for this
  219558. // window from the event queue.
  219559. XSync (display, false);
  219560. XEvent event;
  219561. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  219562. {}
  219563. }
  219564. static int getAllEventsMask() throw()
  219565. {
  219566. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  219567. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  219568. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  219569. }
  219570. static int64 getEventTime (::Time t)
  219571. {
  219572. static int64 eventTimeOffset = 0x12345678;
  219573. const int64 thisMessageTime = t;
  219574. if (eventTimeOffset == 0x12345678)
  219575. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  219576. return eventTimeOffset + thisMessageTime;
  219577. }
  219578. static void setWindowTitle (Window xwin, const String& title)
  219579. {
  219580. XTextProperty nameProperty;
  219581. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  219582. ScopedXLock xlock;
  219583. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219584. {
  219585. XSetWMName (display, xwin, &nameProperty);
  219586. XSetWMIconName (display, xwin, &nameProperty);
  219587. XFree (nameProperty.value);
  219588. }
  219589. }
  219590. void updateBorderSize()
  219591. {
  219592. if ((styleFlags & windowHasTitleBar) == 0)
  219593. {
  219594. windowBorder = BorderSize (0);
  219595. }
  219596. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  219597. {
  219598. ScopedXLock xlock;
  219599. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  219600. if (hints != None)
  219601. {
  219602. unsigned char* data = 0;
  219603. unsigned long nitems, bytesLeft;
  219604. Atom actualType;
  219605. int actualFormat;
  219606. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  219607. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  219608. &data) == Success)
  219609. {
  219610. const unsigned long* const sizes = (const unsigned long*) data;
  219611. if (actualFormat == 32)
  219612. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  219613. (int) sizes[3], (int) sizes[1]);
  219614. XFree (data);
  219615. }
  219616. }
  219617. }
  219618. }
  219619. void updateBounds()
  219620. {
  219621. jassert (windowH != 0);
  219622. if (windowH != 0)
  219623. {
  219624. Window root, child;
  219625. unsigned int bw, depth;
  219626. ScopedXLock xlock;
  219627. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219628. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  219629. &bw, &depth))
  219630. {
  219631. wx = wy = ww = wh = 0;
  219632. }
  219633. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  219634. {
  219635. wx = wy = 0;
  219636. }
  219637. }
  219638. }
  219639. void resetDragAndDrop()
  219640. {
  219641. dragAndDropFiles.clear();
  219642. lastDropPos = Point<int> (-1, -1);
  219643. dragAndDropCurrentMimeType = 0;
  219644. dragAndDropSourceWindow = 0;
  219645. srcMimeTypeAtomList.clear();
  219646. }
  219647. void sendDragAndDropMessage (XClientMessageEvent& msg)
  219648. {
  219649. msg.type = ClientMessage;
  219650. msg.display = display;
  219651. msg.window = dragAndDropSourceWindow;
  219652. msg.format = 32;
  219653. msg.data.l[0] = windowH;
  219654. ScopedXLock xlock;
  219655. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  219656. }
  219657. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  219658. {
  219659. XClientMessageEvent msg;
  219660. zerostruct (msg);
  219661. msg.message_type = Atoms::XdndStatus;
  219662. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  219663. msg.data.l[4] = dropAction;
  219664. sendDragAndDropMessage (msg);
  219665. }
  219666. void sendDragAndDropLeave()
  219667. {
  219668. XClientMessageEvent msg;
  219669. zerostruct (msg);
  219670. msg.message_type = Atoms::XdndLeave;
  219671. sendDragAndDropMessage (msg);
  219672. }
  219673. void sendDragAndDropFinish()
  219674. {
  219675. XClientMessageEvent msg;
  219676. zerostruct (msg);
  219677. msg.message_type = Atoms::XdndFinished;
  219678. sendDragAndDropMessage (msg);
  219679. }
  219680. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  219681. {
  219682. if ((clientMsg->data.l[1] & 1) == 0)
  219683. {
  219684. sendDragAndDropLeave();
  219685. if (dragAndDropFiles.size() > 0)
  219686. handleFileDragExit (dragAndDropFiles);
  219687. dragAndDropFiles.clear();
  219688. }
  219689. }
  219690. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  219691. {
  219692. if (dragAndDropSourceWindow == 0)
  219693. return;
  219694. dragAndDropSourceWindow = clientMsg->data.l[0];
  219695. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  219696. (int) clientMsg->data.l[2] & 0xffff);
  219697. dropPos -= getScreenPosition();
  219698. if (lastDropPos != dropPos)
  219699. {
  219700. lastDropPos = dropPos;
  219701. dragAndDropTimestamp = clientMsg->data.l[3];
  219702. Atom targetAction = Atoms::XdndActionCopy;
  219703. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  219704. {
  219705. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  219706. {
  219707. targetAction = Atoms::allowedActions[i];
  219708. break;
  219709. }
  219710. }
  219711. sendDragAndDropStatus (true, targetAction);
  219712. if (dragAndDropFiles.size() == 0)
  219713. updateDraggedFileList (clientMsg);
  219714. if (dragAndDropFiles.size() > 0)
  219715. handleFileDragMove (dragAndDropFiles, dropPos);
  219716. }
  219717. }
  219718. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  219719. {
  219720. if (dragAndDropFiles.size() == 0)
  219721. updateDraggedFileList (clientMsg);
  219722. const StringArray files (dragAndDropFiles);
  219723. const Point<int> lastPos (lastDropPos);
  219724. sendDragAndDropFinish();
  219725. resetDragAndDrop();
  219726. if (files.size() > 0)
  219727. handleFileDragDrop (files, lastPos);
  219728. }
  219729. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  219730. {
  219731. dragAndDropFiles.clear();
  219732. srcMimeTypeAtomList.clear();
  219733. dragAndDropCurrentMimeType = 0;
  219734. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  219735. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  219736. {
  219737. dragAndDropSourceWindow = 0;
  219738. return;
  219739. }
  219740. dragAndDropSourceWindow = clientMsg->data.l[0];
  219741. if ((clientMsg->data.l[1] & 1) != 0)
  219742. {
  219743. Atom actual;
  219744. int format;
  219745. unsigned long count = 0, remaining = 0;
  219746. unsigned char* data = 0;
  219747. ScopedXLock xlock;
  219748. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  219749. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  219750. &count, &remaining, &data);
  219751. if (data != 0)
  219752. {
  219753. if (actual == XA_ATOM && format == 32 && count != 0)
  219754. {
  219755. const unsigned long* const types = (const unsigned long*) data;
  219756. for (unsigned int i = 0; i < count; ++i)
  219757. if (types[i] != None)
  219758. srcMimeTypeAtomList.add (types[i]);
  219759. }
  219760. XFree (data);
  219761. }
  219762. }
  219763. if (srcMimeTypeAtomList.size() == 0)
  219764. {
  219765. for (int i = 2; i < 5; ++i)
  219766. if (clientMsg->data.l[i] != None)
  219767. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  219768. if (srcMimeTypeAtomList.size() == 0)
  219769. {
  219770. dragAndDropSourceWindow = 0;
  219771. return;
  219772. }
  219773. }
  219774. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  219775. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  219776. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  219777. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  219778. handleDragAndDropPosition (clientMsg);
  219779. }
  219780. void handleDragAndDropSelection (const XEvent* const evt)
  219781. {
  219782. dragAndDropFiles.clear();
  219783. if (evt->xselection.property != 0)
  219784. {
  219785. StringArray lines;
  219786. {
  219787. MemoryBlock dropData;
  219788. for (;;)
  219789. {
  219790. Atom actual;
  219791. uint8* data = 0;
  219792. unsigned long count = 0, remaining = 0;
  219793. int format = 0;
  219794. ScopedXLock xlock;
  219795. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  219796. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  219797. &format, &count, &remaining, &data) == Success)
  219798. {
  219799. dropData.append (data, count * format / 8);
  219800. XFree (data);
  219801. if (remaining == 0)
  219802. break;
  219803. }
  219804. else
  219805. {
  219806. XFree (data);
  219807. break;
  219808. }
  219809. }
  219810. lines.addLines (dropData.toString());
  219811. }
  219812. for (int i = 0; i < lines.size(); ++i)
  219813. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  219814. dragAndDropFiles.trim();
  219815. dragAndDropFiles.removeEmptyStrings();
  219816. }
  219817. }
  219818. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  219819. {
  219820. dragAndDropFiles.clear();
  219821. if (dragAndDropSourceWindow != None
  219822. && dragAndDropCurrentMimeType != 0)
  219823. {
  219824. dragAndDropTimestamp = clientMsg->data.l[2];
  219825. ScopedXLock xlock;
  219826. XConvertSelection (display,
  219827. Atoms::XdndSelection,
  219828. dragAndDropCurrentMimeType,
  219829. XInternAtom (display, "JXSelectionWindowProperty", 0),
  219830. windowH,
  219831. dragAndDropTimestamp);
  219832. }
  219833. }
  219834. StringArray dragAndDropFiles;
  219835. int dragAndDropTimestamp;
  219836. Point<int> lastDropPos;
  219837. Atom dragAndDropCurrentMimeType;
  219838. Window dragAndDropSourceWindow;
  219839. Array <Atom> srcMimeTypeAtomList;
  219840. static int pointerMap[5];
  219841. static Point<int> lastMousePos;
  219842. static void clearLastMousePos() throw()
  219843. {
  219844. lastMousePos = Point<int> (0x100000, 0x100000);
  219845. }
  219846. };
  219847. ModifierKeys LinuxComponentPeer::currentModifiers;
  219848. bool LinuxComponentPeer::isActiveApplication = false;
  219849. int LinuxComponentPeer::pointerMap[5];
  219850. Point<int> LinuxComponentPeer::lastMousePos;
  219851. bool Process::isForegroundProcess()
  219852. {
  219853. return LinuxComponentPeer::isActiveApplication;
  219854. }
  219855. void ModifierKeys::updateCurrentModifiers() throw()
  219856. {
  219857. currentModifiers = LinuxComponentPeer::currentModifiers;
  219858. }
  219859. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  219860. {
  219861. Window root, child;
  219862. int x, y, winx, winy;
  219863. unsigned int mask;
  219864. int mouseMods = 0;
  219865. ScopedXLock xlock;
  219866. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  219867. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  219868. {
  219869. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  219870. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  219871. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  219872. }
  219873. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  219874. return LinuxComponentPeer::currentModifiers;
  219875. }
  219876. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  219877. {
  219878. if (enableOrDisable)
  219879. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  219880. }
  219881. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  219882. {
  219883. return new LinuxComponentPeer (this, styleFlags);
  219884. }
  219885. // (this callback is hooked up in the messaging code)
  219886. void juce_windowMessageReceive (XEvent* event)
  219887. {
  219888. if (event->xany.window != None)
  219889. {
  219890. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  219891. if (ComponentPeer::isValidPeer (peer))
  219892. peer->handleWindowMessage (event);
  219893. }
  219894. else
  219895. {
  219896. switch (event->xany.type)
  219897. {
  219898. case KeymapNotify:
  219899. {
  219900. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  219901. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  219902. break;
  219903. }
  219904. default:
  219905. break;
  219906. }
  219907. }
  219908. }
  219909. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  219910. {
  219911. if (display == 0)
  219912. return;
  219913. #if JUCE_USE_XINERAMA
  219914. int major_opcode, first_event, first_error;
  219915. ScopedXLock xlock;
  219916. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  219917. {
  219918. typedef Bool (*tXineramaIsActive) (Display*);
  219919. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  219920. static tXineramaIsActive xXineramaIsActive = 0;
  219921. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  219922. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  219923. {
  219924. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  219925. if (h == 0)
  219926. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  219927. if (h != 0)
  219928. {
  219929. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  219930. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  219931. }
  219932. }
  219933. if (xXineramaIsActive != 0
  219934. && xXineramaQueryScreens != 0
  219935. && xXineramaIsActive (display))
  219936. {
  219937. int numMonitors = 0;
  219938. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  219939. if (screens != 0)
  219940. {
  219941. for (int i = numMonitors; --i >= 0;)
  219942. {
  219943. int index = screens[i].screen_number;
  219944. if (index >= 0)
  219945. {
  219946. while (monitorCoords.size() < index)
  219947. monitorCoords.add (Rectangle<int>());
  219948. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  219949. screens[i].y_org,
  219950. screens[i].width,
  219951. screens[i].height));
  219952. }
  219953. }
  219954. XFree (screens);
  219955. }
  219956. }
  219957. }
  219958. if (monitorCoords.size() == 0)
  219959. #endif
  219960. {
  219961. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  219962. if (hints != None)
  219963. {
  219964. const int numMonitors = ScreenCount (display);
  219965. for (int i = 0; i < numMonitors; ++i)
  219966. {
  219967. Window root = RootWindow (display, i);
  219968. unsigned long nitems, bytesLeft;
  219969. Atom actualType;
  219970. int actualFormat;
  219971. unsigned char* data = 0;
  219972. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  219973. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  219974. &data) == Success)
  219975. {
  219976. const long* const position = (const long*) data;
  219977. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  219978. monitorCoords.add (Rectangle<int> (position[0], position[1],
  219979. position[2], position[3]));
  219980. XFree (data);
  219981. }
  219982. }
  219983. }
  219984. if (monitorCoords.size() == 0)
  219985. {
  219986. monitorCoords.add (Rectangle<int> (0, 0,
  219987. DisplayWidth (display, DefaultScreen (display)),
  219988. DisplayHeight (display, DefaultScreen (display))));
  219989. }
  219990. }
  219991. }
  219992. void Desktop::createMouseInputSources()
  219993. {
  219994. mouseSources.add (new MouseInputSource (0, true));
  219995. }
  219996. bool Desktop::canUseSemiTransparentWindows() throw()
  219997. {
  219998. int matchedDepth = 0;
  219999. const int desiredDepth = 32;
  220000. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220001. && (matchedDepth == desiredDepth);
  220002. }
  220003. const Point<int> Desktop::getMousePosition()
  220004. {
  220005. Window root, child;
  220006. int x, y, winx, winy;
  220007. unsigned int mask;
  220008. ScopedXLock xlock;
  220009. if (XQueryPointer (display,
  220010. RootWindow (display, DefaultScreen (display)),
  220011. &root, &child,
  220012. &x, &y, &winx, &winy, &mask) == False)
  220013. {
  220014. // Pointer not on the default screen
  220015. x = y = -1;
  220016. }
  220017. return Point<int> (x, y);
  220018. }
  220019. void Desktop::setMousePosition (const Point<int>& newPosition)
  220020. {
  220021. ScopedXLock xlock;
  220022. Window root = RootWindow (display, DefaultScreen (display));
  220023. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220024. }
  220025. static bool screenSaverAllowed = true;
  220026. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220027. {
  220028. if (screenSaverAllowed != isEnabled)
  220029. {
  220030. screenSaverAllowed = isEnabled;
  220031. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220032. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220033. if (xScreenSaverSuspend == 0)
  220034. {
  220035. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220036. if (h != 0)
  220037. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220038. }
  220039. ScopedXLock xlock;
  220040. if (xScreenSaverSuspend != 0)
  220041. xScreenSaverSuspend (display, ! isEnabled);
  220042. }
  220043. }
  220044. bool Desktop::isScreenSaverEnabled()
  220045. {
  220046. return screenSaverAllowed;
  220047. }
  220048. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220049. {
  220050. ScopedXLock xlock;
  220051. const unsigned int imageW = image.getWidth();
  220052. const unsigned int imageH = image.getHeight();
  220053. #if JUCE_USE_XCURSOR
  220054. {
  220055. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220056. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220057. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220058. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220059. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220060. static tXcursorImageCreate xXcursorImageCreate = 0;
  220061. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220062. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220063. static bool hasBeenLoaded = false;
  220064. if (! hasBeenLoaded)
  220065. {
  220066. hasBeenLoaded = true;
  220067. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220068. if (h != 0)
  220069. {
  220070. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220071. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220072. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220073. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220074. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220075. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220076. || ! xXcursorSupportsARGB (display))
  220077. xXcursorSupportsARGB = 0;
  220078. }
  220079. }
  220080. if (xXcursorSupportsARGB != 0)
  220081. {
  220082. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220083. if (xcImage != 0)
  220084. {
  220085. xcImage->xhot = hotspotX;
  220086. xcImage->yhot = hotspotY;
  220087. XcursorPixel* dest = xcImage->pixels;
  220088. for (int y = 0; y < (int) imageH; ++y)
  220089. for (int x = 0; x < (int) imageW; ++x)
  220090. *dest++ = image.getPixelAt (x, y).getARGB();
  220091. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220092. xXcursorImageDestroy (xcImage);
  220093. if (result != 0)
  220094. return result;
  220095. }
  220096. }
  220097. }
  220098. #endif
  220099. Window root = RootWindow (display, DefaultScreen (display));
  220100. unsigned int cursorW, cursorH;
  220101. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220102. return 0;
  220103. Image im (Image::ARGB, cursorW, cursorH, true);
  220104. {
  220105. Graphics g (im);
  220106. if (imageW > cursorW || imageH > cursorH)
  220107. {
  220108. hotspotX = (hotspotX * cursorW) / imageW;
  220109. hotspotY = (hotspotY * cursorH) / imageH;
  220110. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220111. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220112. false);
  220113. }
  220114. else
  220115. {
  220116. g.drawImageAt (image, 0, 0);
  220117. }
  220118. }
  220119. const int stride = (cursorW + 7) >> 3;
  220120. HeapBlock <char> maskPlane, sourcePlane;
  220121. maskPlane.calloc (stride * cursorH);
  220122. sourcePlane.calloc (stride * cursorH);
  220123. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220124. for (int y = cursorH; --y >= 0;)
  220125. {
  220126. for (int x = cursorW; --x >= 0;)
  220127. {
  220128. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220129. const int offset = y * stride + (x >> 3);
  220130. const Colour c (im.getPixelAt (x, y));
  220131. if (c.getAlpha() >= 128)
  220132. maskPlane[offset] |= mask;
  220133. if (c.getBrightness() >= 0.5f)
  220134. sourcePlane[offset] |= mask;
  220135. }
  220136. }
  220137. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220138. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220139. XColor white, black;
  220140. black.red = black.green = black.blue = 0;
  220141. white.red = white.green = white.blue = 0xffff;
  220142. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  220143. XFreePixmap (display, sourcePixmap);
  220144. XFreePixmap (display, maskPixmap);
  220145. return result;
  220146. }
  220147. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  220148. {
  220149. ScopedXLock xlock;
  220150. if (cursorHandle != 0)
  220151. XFreeCursor (display, (Cursor) cursorHandle);
  220152. }
  220153. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  220154. {
  220155. unsigned int shape;
  220156. switch (type)
  220157. {
  220158. case NormalCursor: return None; // Use parent cursor
  220159. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  220160. case WaitCursor: shape = XC_watch; break;
  220161. case IBeamCursor: shape = XC_xterm; break;
  220162. case PointingHandCursor: shape = XC_hand2; break;
  220163. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  220164. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  220165. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  220166. case TopEdgeResizeCursor: shape = XC_top_side; break;
  220167. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  220168. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  220169. case RightEdgeResizeCursor: shape = XC_right_side; break;
  220170. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  220171. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  220172. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  220173. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  220174. case CrosshairCursor: shape = XC_crosshair; break;
  220175. case DraggingHandCursor:
  220176. {
  220177. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  220178. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0, 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  220179. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217, 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  220180. const int dragHandDataSize = 99;
  220181. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  220182. }
  220183. case CopyingCursor:
  220184. {
  220185. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  220186. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0, 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  220187. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  220188. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  220189. const int copyCursorSize = 119;
  220190. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  220191. }
  220192. default:
  220193. jassertfalse;
  220194. return None;
  220195. }
  220196. ScopedXLock xlock;
  220197. return (void*) XCreateFontCursor (display, shape);
  220198. }
  220199. void MouseCursor::showInWindow (ComponentPeer* peer) const
  220200. {
  220201. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  220202. if (lp != 0)
  220203. lp->showMouseCursor ((Cursor) getHandle());
  220204. }
  220205. void MouseCursor::showInAllWindows() const
  220206. {
  220207. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220208. showInWindow (ComponentPeer::getPeer (i));
  220209. }
  220210. const Image juce_createIconForFile (const File& file)
  220211. {
  220212. return Image();
  220213. }
  220214. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  220215. {
  220216. return createSoftwareImage (format, width, height, clearImage);
  220217. }
  220218. #if JUCE_OPENGL
  220219. class WindowedGLContext : public OpenGLContext
  220220. {
  220221. public:
  220222. WindowedGLContext (Component* const component,
  220223. const OpenGLPixelFormat& pixelFormat_,
  220224. GLXContext sharedContext)
  220225. : renderContext (0),
  220226. embeddedWindow (0),
  220227. pixelFormat (pixelFormat_)
  220228. {
  220229. jassert (component != 0);
  220230. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  220231. if (peer == 0)
  220232. return;
  220233. ScopedXLock xlock;
  220234. XSync (display, False);
  220235. GLint attribs [64];
  220236. int n = 0;
  220237. attribs[n++] = GLX_RGBA;
  220238. attribs[n++] = GLX_DOUBLEBUFFER;
  220239. attribs[n++] = GLX_RED_SIZE;
  220240. attribs[n++] = pixelFormat.redBits;
  220241. attribs[n++] = GLX_GREEN_SIZE;
  220242. attribs[n++] = pixelFormat.greenBits;
  220243. attribs[n++] = GLX_BLUE_SIZE;
  220244. attribs[n++] = pixelFormat.blueBits;
  220245. attribs[n++] = GLX_ALPHA_SIZE;
  220246. attribs[n++] = pixelFormat.alphaBits;
  220247. attribs[n++] = GLX_DEPTH_SIZE;
  220248. attribs[n++] = pixelFormat.depthBufferBits;
  220249. attribs[n++] = GLX_STENCIL_SIZE;
  220250. attribs[n++] = pixelFormat.stencilBufferBits;
  220251. attribs[n++] = GLX_ACCUM_RED_SIZE;
  220252. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  220253. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  220254. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  220255. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  220256. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  220257. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  220258. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  220259. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  220260. attribs[n++] = None;
  220261. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  220262. if (bestVisual == 0)
  220263. return;
  220264. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  220265. Window windowH = (Window) peer->getNativeHandle();
  220266. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  220267. XSetWindowAttributes swa;
  220268. swa.colormap = colourMap;
  220269. swa.border_pixel = 0;
  220270. swa.event_mask = ExposureMask | StructureNotifyMask;
  220271. embeddedWindow = XCreateWindow (display, windowH,
  220272. 0, 0, 1, 1, 0,
  220273. bestVisual->depth,
  220274. InputOutput,
  220275. bestVisual->visual,
  220276. CWBorderPixel | CWColormap | CWEventMask,
  220277. &swa);
  220278. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  220279. XMapWindow (display, embeddedWindow);
  220280. XFreeColormap (display, colourMap);
  220281. XFree (bestVisual);
  220282. XSync (display, False);
  220283. }
  220284. ~WindowedGLContext()
  220285. {
  220286. makeInactive();
  220287. ScopedXLock xlock;
  220288. glXDestroyContext (display, renderContext);
  220289. XUnmapWindow (display, embeddedWindow);
  220290. XDestroyWindow (display, embeddedWindow);
  220291. }
  220292. bool makeActive() const throw()
  220293. {
  220294. jassert (renderContext != 0);
  220295. ScopedXLock xlock;
  220296. return glXMakeCurrent (display, embeddedWindow, renderContext)
  220297. && XSync (display, False);
  220298. }
  220299. bool makeInactive() const throw()
  220300. {
  220301. ScopedXLock xlock;
  220302. return (! isActive()) || glXMakeCurrent (display, None, 0);
  220303. }
  220304. bool isActive() const throw()
  220305. {
  220306. ScopedXLock xlock;
  220307. return glXGetCurrentContext() == renderContext;
  220308. }
  220309. const OpenGLPixelFormat getPixelFormat() const
  220310. {
  220311. return pixelFormat;
  220312. }
  220313. void* getRawContext() const throw()
  220314. {
  220315. return renderContext;
  220316. }
  220317. void updateWindowPosition (int x, int y, int w, int h, int)
  220318. {
  220319. ScopedXLock xlock;
  220320. XMoveResizeWindow (display, embeddedWindow,
  220321. x, y, jmax (1, w), jmax (1, h));
  220322. }
  220323. void swapBuffers()
  220324. {
  220325. ScopedXLock xlock;
  220326. glXSwapBuffers (display, embeddedWindow);
  220327. }
  220328. bool setSwapInterval (const int numFramesPerSwap)
  220329. {
  220330. // xxx needs doing..
  220331. return false;
  220332. }
  220333. int getSwapInterval() const
  220334. {
  220335. // xxx needs doing..
  220336. return 0;
  220337. }
  220338. void repaint()
  220339. {
  220340. }
  220341. juce_UseDebuggingNewOperator
  220342. GLXContext renderContext;
  220343. private:
  220344. Window embeddedWindow;
  220345. OpenGLPixelFormat pixelFormat;
  220346. WindowedGLContext (const WindowedGLContext&);
  220347. WindowedGLContext& operator= (const WindowedGLContext&);
  220348. };
  220349. OpenGLContext* OpenGLComponent::createContext()
  220350. {
  220351. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  220352. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  220353. return (c->renderContext != 0) ? c.release() : 0;
  220354. }
  220355. void juce_glViewport (const int w, const int h)
  220356. {
  220357. glViewport (0, 0, w, h);
  220358. }
  220359. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  220360. OwnedArray <OpenGLPixelFormat>& results)
  220361. {
  220362. results.add (new OpenGLPixelFormat()); // xxx
  220363. }
  220364. #endif
  220365. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220366. {
  220367. jassertfalse; // not implemented!
  220368. return false;
  220369. }
  220370. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220371. {
  220372. jassertfalse; // not implemented!
  220373. return false;
  220374. }
  220375. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  220376. {
  220377. if (! isOnDesktop ())
  220378. addToDesktop (0);
  220379. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220380. if (wp != 0)
  220381. {
  220382. wp->setTaskBarIcon (newImage);
  220383. setVisible (true);
  220384. toFront (false);
  220385. repaint();
  220386. }
  220387. }
  220388. void SystemTrayIconComponent::paint (Graphics& g)
  220389. {
  220390. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220391. if (wp != 0)
  220392. {
  220393. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  220394. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220395. false);
  220396. }
  220397. }
  220398. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  220399. {
  220400. // xxx not yet implemented!
  220401. }
  220402. void PlatformUtilities::beep()
  220403. {
  220404. std::cout << "\a" << std::flush;
  220405. }
  220406. bool AlertWindow::showNativeDialogBox (const String& title,
  220407. const String& bodyText,
  220408. bool isOkCancel)
  220409. {
  220410. // use a non-native one for the time being..
  220411. if (isOkCancel)
  220412. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  220413. else
  220414. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  220415. return true;
  220416. }
  220417. const int KeyPress::spaceKey = XK_space & 0xff;
  220418. const int KeyPress::returnKey = XK_Return & 0xff;
  220419. const int KeyPress::escapeKey = XK_Escape & 0xff;
  220420. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  220421. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  220422. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  220423. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  220424. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  220425. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  220426. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  220427. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  220428. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  220429. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  220430. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  220431. const int KeyPress::tabKey = XK_Tab & 0xff;
  220432. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  220433. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  220434. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  220435. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  220436. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  220437. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  220438. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  220439. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  220440. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  220441. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  220442. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  220443. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  220444. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  220445. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  220446. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  220447. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  220448. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  220449. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  220450. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  220451. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  220452. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  220453. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  220454. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  220455. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  220456. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  220457. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  220458. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  220459. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  220460. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  220461. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  220462. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  220463. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  220464. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  220465. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  220466. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  220467. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  220468. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  220469. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  220470. #endif
  220471. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  220472. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  220473. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220474. // compiled on its own).
  220475. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  220476. static const int maxNumChans = 64;
  220477. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  220478. {
  220479. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  220480. snd_pcm_hw_params_t* hwParams;
  220481. snd_pcm_hw_params_alloca (&hwParams);
  220482. for (int i = 0; ratesToTry[i] != 0; ++i)
  220483. {
  220484. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  220485. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  220486. {
  220487. rates.addIfNotAlreadyThere (ratesToTry[i]);
  220488. }
  220489. }
  220490. }
  220491. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  220492. {
  220493. snd_pcm_hw_params_t *params;
  220494. snd_pcm_hw_params_alloca (&params);
  220495. if (snd_pcm_hw_params_any (handle, params) >= 0)
  220496. {
  220497. snd_pcm_hw_params_get_channels_min (params, minChans);
  220498. snd_pcm_hw_params_get_channels_max (params, maxChans);
  220499. }
  220500. }
  220501. static void getDeviceProperties (const String& deviceID,
  220502. unsigned int& minChansOut,
  220503. unsigned int& maxChansOut,
  220504. unsigned int& minChansIn,
  220505. unsigned int& maxChansIn,
  220506. Array <int>& rates)
  220507. {
  220508. if (deviceID.isEmpty())
  220509. return;
  220510. snd_ctl_t* handle;
  220511. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  220512. {
  220513. snd_pcm_info_t* info;
  220514. snd_pcm_info_alloca (&info);
  220515. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  220516. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  220517. snd_pcm_info_set_subdevice (info, 0);
  220518. if (snd_ctl_pcm_info (handle, info) >= 0)
  220519. {
  220520. snd_pcm_t* pcmHandle;
  220521. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  220522. {
  220523. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  220524. getDeviceSampleRates (pcmHandle, rates);
  220525. snd_pcm_close (pcmHandle);
  220526. }
  220527. }
  220528. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  220529. if (snd_ctl_pcm_info (handle, info) >= 0)
  220530. {
  220531. snd_pcm_t* pcmHandle;
  220532. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  220533. {
  220534. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  220535. if (rates.size() == 0)
  220536. getDeviceSampleRates (pcmHandle, rates);
  220537. snd_pcm_close (pcmHandle);
  220538. }
  220539. }
  220540. snd_ctl_close (handle);
  220541. }
  220542. }
  220543. class ALSADevice
  220544. {
  220545. public:
  220546. ALSADevice (const String& deviceID,
  220547. const bool forInput)
  220548. : handle (0),
  220549. bitDepth (16),
  220550. numChannelsRunning (0),
  220551. isInput (forInput),
  220552. sampleFormat (AudioDataConverters::int16LE)
  220553. {
  220554. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  220555. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  220556. SND_PCM_ASYNC));
  220557. }
  220558. ~ALSADevice()
  220559. {
  220560. if (handle != 0)
  220561. snd_pcm_close (handle);
  220562. }
  220563. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  220564. {
  220565. if (handle == 0)
  220566. return false;
  220567. snd_pcm_hw_params_t* hwParams;
  220568. snd_pcm_hw_params_alloca (&hwParams);
  220569. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  220570. return false;
  220571. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  220572. isInterleaved = false;
  220573. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  220574. isInterleaved = true;
  220575. else
  220576. {
  220577. jassertfalse;
  220578. return false;
  220579. }
  220580. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  220581. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  220582. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  220583. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  220584. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  220585. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  220586. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  220587. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  220588. bitDepth = 0;
  220589. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  220590. {
  220591. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  220592. {
  220593. bitDepth = formatsToTry [i + 1];
  220594. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  220595. break;
  220596. }
  220597. }
  220598. if (bitDepth == 0)
  220599. {
  220600. error = "device doesn't support a compatible PCM format";
  220601. DBG ("ALSA error: " + error + "\n");
  220602. return false;
  220603. }
  220604. int dir = 0;
  220605. unsigned int periods = 4;
  220606. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  220607. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  220608. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  220609. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  220610. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  220611. || failed (snd_pcm_hw_params (handle, hwParams)))
  220612. {
  220613. return false;
  220614. }
  220615. snd_pcm_sw_params_t* swParams;
  220616. snd_pcm_sw_params_alloca (&swParams);
  220617. snd_pcm_uframes_t boundary;
  220618. if (failed (snd_pcm_sw_params_current (handle, swParams))
  220619. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  220620. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  220621. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  220622. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  220623. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  220624. || failed (snd_pcm_sw_params (handle, swParams)))
  220625. {
  220626. return false;
  220627. }
  220628. /*
  220629. #if JUCE_DEBUG
  220630. // enable this to dump the config of the devices that get opened
  220631. snd_output_t* out;
  220632. snd_output_stdio_attach (&out, stderr, 0);
  220633. snd_pcm_hw_params_dump (hwParams, out);
  220634. snd_pcm_sw_params_dump (swParams, out);
  220635. #endif
  220636. */
  220637. numChannelsRunning = numChannels;
  220638. return true;
  220639. }
  220640. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  220641. {
  220642. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  220643. float** const data = outputChannelBuffer.getArrayOfChannels();
  220644. if (isInterleaved)
  220645. {
  220646. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  220647. float* interleaved = static_cast <float*> (scratch.getData());
  220648. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  220649. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  220650. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  220651. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  220652. return false;
  220653. }
  220654. else
  220655. {
  220656. for (int i = 0; i < numChannelsRunning; ++i)
  220657. if (data[i] != 0)
  220658. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  220659. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  220660. if (failed (num))
  220661. {
  220662. if (num == -EPIPE)
  220663. {
  220664. if (failed (snd_pcm_prepare (handle)))
  220665. return false;
  220666. }
  220667. else if (num != -ESTRPIPE)
  220668. return false;
  220669. }
  220670. }
  220671. return true;
  220672. }
  220673. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  220674. {
  220675. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  220676. float** const data = inputChannelBuffer.getArrayOfChannels();
  220677. if (isInterleaved)
  220678. {
  220679. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  220680. float* interleaved = static_cast <float*> (scratch.getData());
  220681. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  220682. if (failed (num))
  220683. {
  220684. if (num == -EPIPE)
  220685. {
  220686. if (failed (snd_pcm_prepare (handle)))
  220687. return false;
  220688. }
  220689. else if (num != -ESTRPIPE)
  220690. return false;
  220691. }
  220692. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  220693. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  220694. }
  220695. else
  220696. {
  220697. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  220698. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  220699. return false;
  220700. for (int i = 0; i < numChannelsRunning; ++i)
  220701. if (data[i] != 0)
  220702. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  220703. }
  220704. return true;
  220705. }
  220706. juce_UseDebuggingNewOperator
  220707. snd_pcm_t* handle;
  220708. String error;
  220709. int bitDepth, numChannelsRunning;
  220710. private:
  220711. const bool isInput;
  220712. bool isInterleaved;
  220713. MemoryBlock scratch;
  220714. AudioDataConverters::DataFormat sampleFormat;
  220715. bool failed (const int errorNum)
  220716. {
  220717. if (errorNum >= 0)
  220718. return false;
  220719. error = snd_strerror (errorNum);
  220720. DBG ("ALSA error: " + error + "\n");
  220721. return true;
  220722. }
  220723. };
  220724. class ALSAThread : public Thread
  220725. {
  220726. public:
  220727. ALSAThread (const String& inputId_,
  220728. const String& outputId_)
  220729. : Thread ("Juce ALSA"),
  220730. sampleRate (0),
  220731. bufferSize (0),
  220732. callback (0),
  220733. inputId (inputId_),
  220734. outputId (outputId_),
  220735. outputDevice (0),
  220736. inputDevice (0),
  220737. numCallbacks (0),
  220738. inputChannelBuffer (1, 1),
  220739. outputChannelBuffer (1, 1)
  220740. {
  220741. initialiseRatesAndChannels();
  220742. }
  220743. ~ALSAThread()
  220744. {
  220745. close();
  220746. }
  220747. void open (BigInteger inputChannels,
  220748. BigInteger outputChannels,
  220749. const double sampleRate_,
  220750. const int bufferSize_)
  220751. {
  220752. close();
  220753. error = String::empty;
  220754. sampleRate = sampleRate_;
  220755. bufferSize = bufferSize_;
  220756. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  220757. inputChannelBuffer.clear();
  220758. inputChannelDataForCallback.clear();
  220759. currentInputChans.clear();
  220760. if (inputChannels.getHighestBit() >= 0)
  220761. {
  220762. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  220763. {
  220764. if (inputChannels[i])
  220765. {
  220766. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  220767. currentInputChans.setBit (i);
  220768. }
  220769. }
  220770. }
  220771. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  220772. outputChannelBuffer.clear();
  220773. outputChannelDataForCallback.clear();
  220774. currentOutputChans.clear();
  220775. if (outputChannels.getHighestBit() >= 0)
  220776. {
  220777. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  220778. {
  220779. if (outputChannels[i])
  220780. {
  220781. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  220782. currentOutputChans.setBit (i);
  220783. }
  220784. }
  220785. }
  220786. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  220787. {
  220788. outputDevice = new ALSADevice (outputId, false);
  220789. if (outputDevice->error.isNotEmpty())
  220790. {
  220791. error = outputDevice->error;
  220792. deleteAndZero (outputDevice);
  220793. return;
  220794. }
  220795. currentOutputChans.setRange (0, minChansOut, true);
  220796. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  220797. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  220798. bufferSize))
  220799. {
  220800. error = outputDevice->error;
  220801. deleteAndZero (outputDevice);
  220802. return;
  220803. }
  220804. }
  220805. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  220806. {
  220807. inputDevice = new ALSADevice (inputId, true);
  220808. if (inputDevice->error.isNotEmpty())
  220809. {
  220810. error = inputDevice->error;
  220811. deleteAndZero (inputDevice);
  220812. return;
  220813. }
  220814. currentInputChans.setRange (0, minChansIn, true);
  220815. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  220816. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  220817. bufferSize))
  220818. {
  220819. error = inputDevice->error;
  220820. deleteAndZero (inputDevice);
  220821. return;
  220822. }
  220823. }
  220824. if (outputDevice == 0 && inputDevice == 0)
  220825. {
  220826. error = "no channels";
  220827. return;
  220828. }
  220829. if (outputDevice != 0 && inputDevice != 0)
  220830. {
  220831. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  220832. }
  220833. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  220834. return;
  220835. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  220836. return;
  220837. startThread (9);
  220838. int count = 1000;
  220839. while (numCallbacks == 0)
  220840. {
  220841. sleep (5);
  220842. if (--count < 0 || ! isThreadRunning())
  220843. {
  220844. error = "device didn't start";
  220845. break;
  220846. }
  220847. }
  220848. }
  220849. void close()
  220850. {
  220851. stopThread (6000);
  220852. deleteAndZero (inputDevice);
  220853. deleteAndZero (outputDevice);
  220854. inputChannelBuffer.setSize (1, 1);
  220855. outputChannelBuffer.setSize (1, 1);
  220856. numCallbacks = 0;
  220857. }
  220858. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  220859. {
  220860. const ScopedLock sl (callbackLock);
  220861. callback = newCallback;
  220862. }
  220863. void run()
  220864. {
  220865. while (! threadShouldExit())
  220866. {
  220867. if (inputDevice != 0)
  220868. {
  220869. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  220870. {
  220871. DBG ("ALSA: read failure");
  220872. break;
  220873. }
  220874. }
  220875. if (threadShouldExit())
  220876. break;
  220877. {
  220878. const ScopedLock sl (callbackLock);
  220879. ++numCallbacks;
  220880. if (callback != 0)
  220881. {
  220882. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  220883. inputChannelDataForCallback.size(),
  220884. outputChannelDataForCallback.getRawDataPointer(),
  220885. outputChannelDataForCallback.size(),
  220886. bufferSize);
  220887. }
  220888. else
  220889. {
  220890. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  220891. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  220892. }
  220893. }
  220894. if (outputDevice != 0)
  220895. {
  220896. failed (snd_pcm_wait (outputDevice->handle, 2000));
  220897. if (threadShouldExit())
  220898. break;
  220899. failed (snd_pcm_avail_update (outputDevice->handle));
  220900. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  220901. {
  220902. DBG ("ALSA: write failure");
  220903. break;
  220904. }
  220905. }
  220906. }
  220907. }
  220908. int getBitDepth() const throw()
  220909. {
  220910. if (outputDevice != 0)
  220911. return outputDevice->bitDepth;
  220912. if (inputDevice != 0)
  220913. return inputDevice->bitDepth;
  220914. return 16;
  220915. }
  220916. juce_UseDebuggingNewOperator
  220917. String error;
  220918. double sampleRate;
  220919. int bufferSize;
  220920. BigInteger currentInputChans, currentOutputChans;
  220921. Array <int> sampleRates;
  220922. StringArray channelNamesOut, channelNamesIn;
  220923. AudioIODeviceCallback* callback;
  220924. private:
  220925. const String inputId, outputId;
  220926. ALSADevice* outputDevice;
  220927. ALSADevice* inputDevice;
  220928. int numCallbacks;
  220929. CriticalSection callbackLock;
  220930. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  220931. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  220932. unsigned int minChansOut, maxChansOut;
  220933. unsigned int minChansIn, maxChansIn;
  220934. bool failed (const int errorNum)
  220935. {
  220936. if (errorNum >= 0)
  220937. return false;
  220938. error = snd_strerror (errorNum);
  220939. DBG ("ALSA error: " + error + "\n");
  220940. return true;
  220941. }
  220942. void initialiseRatesAndChannels()
  220943. {
  220944. sampleRates.clear();
  220945. channelNamesOut.clear();
  220946. channelNamesIn.clear();
  220947. minChansOut = 0;
  220948. maxChansOut = 0;
  220949. minChansIn = 0;
  220950. maxChansIn = 0;
  220951. unsigned int dummy = 0;
  220952. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  220953. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  220954. unsigned int i;
  220955. for (i = 0; i < maxChansOut; ++i)
  220956. channelNamesOut.add ("channel " + String ((int) i + 1));
  220957. for (i = 0; i < maxChansIn; ++i)
  220958. channelNamesIn.add ("channel " + String ((int) i + 1));
  220959. }
  220960. };
  220961. class ALSAAudioIODevice : public AudioIODevice
  220962. {
  220963. public:
  220964. ALSAAudioIODevice (const String& deviceName,
  220965. const String& inputId_,
  220966. const String& outputId_)
  220967. : AudioIODevice (deviceName, "ALSA"),
  220968. inputId (inputId_),
  220969. outputId (outputId_),
  220970. isOpen_ (false),
  220971. isStarted (false),
  220972. internal (new ALSAThread (inputId_, outputId_))
  220973. {
  220974. }
  220975. ~ALSAAudioIODevice()
  220976. {
  220977. }
  220978. const StringArray getOutputChannelNames()
  220979. {
  220980. return internal->channelNamesOut;
  220981. }
  220982. const StringArray getInputChannelNames()
  220983. {
  220984. return internal->channelNamesIn;
  220985. }
  220986. int getNumSampleRates()
  220987. {
  220988. return internal->sampleRates.size();
  220989. }
  220990. double getSampleRate (int index)
  220991. {
  220992. return internal->sampleRates [index];
  220993. }
  220994. int getNumBufferSizesAvailable()
  220995. {
  220996. return 50;
  220997. }
  220998. int getBufferSizeSamples (int index)
  220999. {
  221000. int n = 16;
  221001. for (int i = 0; i < index; ++i)
  221002. n += n < 64 ? 16
  221003. : (n < 512 ? 32
  221004. : (n < 1024 ? 64
  221005. : (n < 2048 ? 128 : 256)));
  221006. return n;
  221007. }
  221008. int getDefaultBufferSize()
  221009. {
  221010. return 512;
  221011. }
  221012. const String open (const BigInteger& inputChannels,
  221013. const BigInteger& outputChannels,
  221014. double sampleRate,
  221015. int bufferSizeSamples)
  221016. {
  221017. close();
  221018. if (bufferSizeSamples <= 0)
  221019. bufferSizeSamples = getDefaultBufferSize();
  221020. if (sampleRate <= 0)
  221021. {
  221022. for (int i = 0; i < getNumSampleRates(); ++i)
  221023. {
  221024. if (getSampleRate (i) >= 44100)
  221025. {
  221026. sampleRate = getSampleRate (i);
  221027. break;
  221028. }
  221029. }
  221030. }
  221031. internal->open (inputChannels, outputChannels,
  221032. sampleRate, bufferSizeSamples);
  221033. isOpen_ = internal->error.isEmpty();
  221034. return internal->error;
  221035. }
  221036. void close()
  221037. {
  221038. stop();
  221039. internal->close();
  221040. isOpen_ = false;
  221041. }
  221042. bool isOpen()
  221043. {
  221044. return isOpen_;
  221045. }
  221046. int getCurrentBufferSizeSamples()
  221047. {
  221048. return internal->bufferSize;
  221049. }
  221050. double getCurrentSampleRate()
  221051. {
  221052. return internal->sampleRate;
  221053. }
  221054. int getCurrentBitDepth()
  221055. {
  221056. return internal->getBitDepth();
  221057. }
  221058. const BigInteger getActiveOutputChannels() const
  221059. {
  221060. return internal->currentOutputChans;
  221061. }
  221062. const BigInteger getActiveInputChannels() const
  221063. {
  221064. return internal->currentInputChans;
  221065. }
  221066. int getOutputLatencyInSamples()
  221067. {
  221068. return 0;
  221069. }
  221070. int getInputLatencyInSamples()
  221071. {
  221072. return 0;
  221073. }
  221074. void start (AudioIODeviceCallback* callback)
  221075. {
  221076. if (! isOpen_)
  221077. callback = 0;
  221078. internal->setCallback (callback);
  221079. if (callback != 0)
  221080. callback->audioDeviceAboutToStart (this);
  221081. isStarted = (callback != 0);
  221082. }
  221083. void stop()
  221084. {
  221085. AudioIODeviceCallback* const oldCallback = internal->callback;
  221086. start (0);
  221087. if (oldCallback != 0)
  221088. oldCallback->audioDeviceStopped();
  221089. }
  221090. bool isPlaying()
  221091. {
  221092. return isStarted && internal->error.isEmpty();
  221093. }
  221094. const String getLastError()
  221095. {
  221096. return internal->error;
  221097. }
  221098. String inputId, outputId;
  221099. private:
  221100. bool isOpen_, isStarted;
  221101. ScopedPointer<ALSAThread> internal;
  221102. };
  221103. class ALSAAudioIODeviceType : public AudioIODeviceType
  221104. {
  221105. public:
  221106. ALSAAudioIODeviceType()
  221107. : AudioIODeviceType ("ALSA"),
  221108. hasScanned (false)
  221109. {
  221110. }
  221111. ~ALSAAudioIODeviceType()
  221112. {
  221113. }
  221114. void scanForDevices()
  221115. {
  221116. if (hasScanned)
  221117. return;
  221118. hasScanned = true;
  221119. inputNames.clear();
  221120. inputIds.clear();
  221121. outputNames.clear();
  221122. outputIds.clear();
  221123. snd_ctl_t* handle;
  221124. snd_ctl_card_info_t* info;
  221125. snd_ctl_card_info_alloca (&info);
  221126. int cardNum = -1;
  221127. while (outputIds.size() + inputIds.size() <= 32)
  221128. {
  221129. snd_card_next (&cardNum);
  221130. if (cardNum < 0)
  221131. break;
  221132. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221133. {
  221134. if (snd_ctl_card_info (handle, info) >= 0)
  221135. {
  221136. String cardId (snd_ctl_card_info_get_id (info));
  221137. if (cardId.removeCharacters ("0123456789").isEmpty())
  221138. cardId = String (cardNum);
  221139. int device = -1;
  221140. for (;;)
  221141. {
  221142. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  221143. break;
  221144. String id, name;
  221145. id << "hw:" << cardId << ',' << device;
  221146. bool isInput, isOutput;
  221147. if (testDevice (id, isInput, isOutput))
  221148. {
  221149. name << snd_ctl_card_info_get_name (info);
  221150. if (name.isEmpty())
  221151. name = id;
  221152. if (isInput)
  221153. {
  221154. inputNames.add (name);
  221155. inputIds.add (id);
  221156. }
  221157. if (isOutput)
  221158. {
  221159. outputNames.add (name);
  221160. outputIds.add (id);
  221161. }
  221162. }
  221163. }
  221164. }
  221165. snd_ctl_close (handle);
  221166. }
  221167. }
  221168. inputNames.appendNumbersToDuplicates (false, true);
  221169. outputNames.appendNumbersToDuplicates (false, true);
  221170. }
  221171. const StringArray getDeviceNames (bool wantInputNames) const
  221172. {
  221173. jassert (hasScanned); // need to call scanForDevices() before doing this
  221174. return wantInputNames ? inputNames : outputNames;
  221175. }
  221176. int getDefaultDeviceIndex (bool forInput) const
  221177. {
  221178. jassert (hasScanned); // need to call scanForDevices() before doing this
  221179. return 0;
  221180. }
  221181. bool hasSeparateInputsAndOutputs() const { return true; }
  221182. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221183. {
  221184. jassert (hasScanned); // need to call scanForDevices() before doing this
  221185. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  221186. if (d == 0)
  221187. return -1;
  221188. return asInput ? inputIds.indexOf (d->inputId)
  221189. : outputIds.indexOf (d->outputId);
  221190. }
  221191. AudioIODevice* createDevice (const String& outputDeviceName,
  221192. const String& inputDeviceName)
  221193. {
  221194. jassert (hasScanned); // need to call scanForDevices() before doing this
  221195. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221196. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221197. String deviceName (outputIndex >= 0 ? outputDeviceName
  221198. : inputDeviceName);
  221199. if (inputIndex >= 0 || outputIndex >= 0)
  221200. return new ALSAAudioIODevice (deviceName,
  221201. inputIds [inputIndex],
  221202. outputIds [outputIndex]);
  221203. return 0;
  221204. }
  221205. juce_UseDebuggingNewOperator
  221206. private:
  221207. StringArray inputNames, outputNames, inputIds, outputIds;
  221208. bool hasScanned;
  221209. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  221210. {
  221211. unsigned int minChansOut = 0, maxChansOut = 0;
  221212. unsigned int minChansIn = 0, maxChansIn = 0;
  221213. Array <int> rates;
  221214. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  221215. DBG ("ALSA device: " + id
  221216. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  221217. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  221218. + " rates=" + String (rates.size()));
  221219. isInput = maxChansIn > 0;
  221220. isOutput = maxChansOut > 0;
  221221. return (isInput || isOutput) && rates.size() > 0;
  221222. }
  221223. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  221224. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  221225. };
  221226. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  221227. {
  221228. return new ALSAAudioIODeviceType();
  221229. }
  221230. #endif
  221231. /*** End of inlined file: juce_linux_Audio.cpp ***/
  221232. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  221233. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221234. // compiled on its own).
  221235. #ifdef JUCE_INCLUDED_FILE
  221236. #if JUCE_JACK
  221237. static void* juce_libjack_handle = 0;
  221238. void* juce_load_jack_function (const char* const name)
  221239. {
  221240. if (juce_libjack_handle == 0)
  221241. return 0;
  221242. return dlsym (juce_libjack_handle, name);
  221243. }
  221244. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  221245. typedef return_type (*fn_name##_ptr_t)argument_types; \
  221246. return_type fn_name argument_types { \
  221247. static fn_name##_ptr_t fn = 0; \
  221248. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221249. if (fn) return (*fn)arguments; \
  221250. else return 0; \
  221251. }
  221252. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  221253. typedef void (*fn_name##_ptr_t)argument_types; \
  221254. void fn_name argument_types { \
  221255. static fn_name##_ptr_t fn = 0; \
  221256. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221257. if (fn) (*fn)arguments; \
  221258. }
  221259. JUCE_DECL_JACK_FUNCTION (jack_client_t*, jack_client_open, (const char* client_name, jack_options_t options, jack_status_t* status), (client_name, options, status));
  221260. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  221261. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  221262. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  221263. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  221264. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  221265. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  221266. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  221267. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  221268. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_register, (jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size), (client, port_name, port_type, flags, buffer_size));
  221269. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  221270. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  221271. JUCE_DECL_JACK_FUNCTION (const char**, jack_get_ports, (jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags), (client, port_name_pattern, type_name_pattern, flags));
  221272. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  221273. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  221274. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  221275. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  221276. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  221277. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  221278. #if JUCE_DEBUG
  221279. #define JACK_LOGGING_ENABLED 1
  221280. #endif
  221281. #if JACK_LOGGING_ENABLED
  221282. static void jack_Log (const String& s)
  221283. {
  221284. std::cerr << s << std::endl;
  221285. }
  221286. static void dumpJackErrorMessage (const jack_status_t status)
  221287. {
  221288. if (status & JackServerFailed || status & JackServerError)
  221289. jack_Log ("Unable to connect to JACK server");
  221290. if (status & JackVersionError)
  221291. jack_Log ("Client's protocol version does not match");
  221292. if (status & JackInvalidOption)
  221293. jack_Log ("The operation contained an invalid or unsupported option");
  221294. if (status & JackNameNotUnique)
  221295. jack_Log ("The desired client name was not unique");
  221296. if (status & JackNoSuchClient)
  221297. jack_Log ("Requested client does not exist");
  221298. if (status & JackInitFailure)
  221299. jack_Log ("Unable to initialize client");
  221300. }
  221301. #else
  221302. #define dumpJackErrorMessage(a) {}
  221303. #define jack_Log(...) {}
  221304. #endif
  221305. #ifndef JUCE_JACK_CLIENT_NAME
  221306. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  221307. #endif
  221308. class JackAudioIODevice : public AudioIODevice
  221309. {
  221310. public:
  221311. JackAudioIODevice (const String& deviceName,
  221312. const String& inputId_,
  221313. const String& outputId_)
  221314. : AudioIODevice (deviceName, "JACK"),
  221315. inputId (inputId_),
  221316. outputId (outputId_),
  221317. isOpen_ (false),
  221318. callback (0),
  221319. totalNumberOfInputChannels (0),
  221320. totalNumberOfOutputChannels (0)
  221321. {
  221322. jassert (deviceName.isNotEmpty());
  221323. jack_status_t status;
  221324. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  221325. if (client == 0)
  221326. {
  221327. dumpJackErrorMessage (status);
  221328. }
  221329. else
  221330. {
  221331. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  221332. // open input ports
  221333. const StringArray inputChannels (getInputChannelNames());
  221334. for (int i = 0; i < inputChannels.size(); i++)
  221335. {
  221336. String inputName;
  221337. inputName << "in_" << ++totalNumberOfInputChannels;
  221338. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  221339. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  221340. }
  221341. // open output ports
  221342. const StringArray outputChannels (getOutputChannelNames());
  221343. for (int i = 0; i < outputChannels.size (); i++)
  221344. {
  221345. String outputName;
  221346. outputName << "out_" << ++totalNumberOfOutputChannels;
  221347. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  221348. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  221349. }
  221350. inChans.calloc (totalNumberOfInputChannels + 2);
  221351. outChans.calloc (totalNumberOfOutputChannels + 2);
  221352. }
  221353. }
  221354. ~JackAudioIODevice()
  221355. {
  221356. close();
  221357. if (client != 0)
  221358. {
  221359. JUCE_NAMESPACE::jack_client_close (client);
  221360. client = 0;
  221361. }
  221362. }
  221363. const StringArray getChannelNames (bool forInput) const
  221364. {
  221365. StringArray names;
  221366. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  221367. forInput ? JackPortIsInput : JackPortIsOutput);
  221368. if (ports != 0)
  221369. {
  221370. int j = 0;
  221371. while (ports[j] != 0)
  221372. {
  221373. const String portName (ports [j++]);
  221374. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221375. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  221376. }
  221377. free (ports);
  221378. }
  221379. return names;
  221380. }
  221381. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  221382. const StringArray getInputChannelNames() { return getChannelNames (true); }
  221383. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  221384. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  221385. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  221386. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  221387. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  221388. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  221389. double sampleRate, int bufferSizeSamples)
  221390. {
  221391. if (client == 0)
  221392. {
  221393. lastError = "No JACK client running";
  221394. return lastError;
  221395. }
  221396. lastError = String::empty;
  221397. close();
  221398. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  221399. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  221400. JUCE_NAMESPACE::jack_activate (client);
  221401. isOpen_ = true;
  221402. if (! inputChannels.isZero())
  221403. {
  221404. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221405. if (ports != 0)
  221406. {
  221407. const int numInputChannels = inputChannels.getHighestBit() + 1;
  221408. for (int i = 0; i < numInputChannels; ++i)
  221409. {
  221410. const String portName (ports[i]);
  221411. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221412. {
  221413. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  221414. if (error != 0)
  221415. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221416. }
  221417. }
  221418. free (ports);
  221419. }
  221420. }
  221421. if (! outputChannels.isZero())
  221422. {
  221423. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221424. if (ports != 0)
  221425. {
  221426. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  221427. for (int i = 0; i < numOutputChannels; ++i)
  221428. {
  221429. const String portName (ports[i]);
  221430. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221431. {
  221432. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  221433. if (error != 0)
  221434. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221435. }
  221436. }
  221437. free (ports);
  221438. }
  221439. }
  221440. return lastError;
  221441. }
  221442. void close()
  221443. {
  221444. stop();
  221445. if (client != 0)
  221446. {
  221447. JUCE_NAMESPACE::jack_deactivate (client);
  221448. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  221449. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  221450. }
  221451. isOpen_ = false;
  221452. }
  221453. void start (AudioIODeviceCallback* newCallback)
  221454. {
  221455. if (isOpen_ && newCallback != callback)
  221456. {
  221457. if (newCallback != 0)
  221458. newCallback->audioDeviceAboutToStart (this);
  221459. AudioIODeviceCallback* const oldCallback = callback;
  221460. {
  221461. const ScopedLock sl (callbackLock);
  221462. callback = newCallback;
  221463. }
  221464. if (oldCallback != 0)
  221465. oldCallback->audioDeviceStopped();
  221466. }
  221467. }
  221468. void stop()
  221469. {
  221470. start (0);
  221471. }
  221472. bool isOpen() { return isOpen_; }
  221473. bool isPlaying() { return callback != 0; }
  221474. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  221475. double getCurrentSampleRate() { return getSampleRate (0); }
  221476. int getCurrentBitDepth() { return 32; }
  221477. const String getLastError() { return lastError; }
  221478. const BigInteger getActiveOutputChannels() const
  221479. {
  221480. BigInteger outputBits;
  221481. for (int i = 0; i < outputPorts.size(); i++)
  221482. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  221483. outputBits.setBit (i);
  221484. return outputBits;
  221485. }
  221486. const BigInteger getActiveInputChannels() const
  221487. {
  221488. BigInteger inputBits;
  221489. for (int i = 0; i < inputPorts.size(); i++)
  221490. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  221491. inputBits.setBit (i);
  221492. return inputBits;
  221493. }
  221494. int getOutputLatencyInSamples()
  221495. {
  221496. int latency = 0;
  221497. for (int i = 0; i < outputPorts.size(); i++)
  221498. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  221499. return latency;
  221500. }
  221501. int getInputLatencyInSamples()
  221502. {
  221503. int latency = 0;
  221504. for (int i = 0; i < inputPorts.size(); i++)
  221505. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  221506. return latency;
  221507. }
  221508. String inputId, outputId;
  221509. private:
  221510. void process (const int numSamples)
  221511. {
  221512. int i, numActiveInChans = 0, numActiveOutChans = 0;
  221513. for (i = 0; i < totalNumberOfInputChannels; ++i)
  221514. {
  221515. jack_default_audio_sample_t* in
  221516. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  221517. if (in != 0)
  221518. inChans [numActiveInChans++] = (float*) in;
  221519. }
  221520. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  221521. {
  221522. jack_default_audio_sample_t* out
  221523. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  221524. if (out != 0)
  221525. outChans [numActiveOutChans++] = (float*) out;
  221526. }
  221527. const ScopedLock sl (callbackLock);
  221528. if (callback != 0)
  221529. {
  221530. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  221531. outChans, numActiveOutChans, numSamples);
  221532. }
  221533. else
  221534. {
  221535. for (i = 0; i < numActiveOutChans; ++i)
  221536. zeromem (outChans[i], sizeof (float) * numSamples);
  221537. }
  221538. }
  221539. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  221540. {
  221541. if (callbackArgument != 0)
  221542. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  221543. return 0;
  221544. }
  221545. static void threadInitCallback (void* callbackArgument)
  221546. {
  221547. jack_Log ("JackAudioIODevice::initialise");
  221548. }
  221549. static void shutdownCallback (void* callbackArgument)
  221550. {
  221551. jack_Log ("JackAudioIODevice::shutdown");
  221552. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  221553. if (device != 0)
  221554. {
  221555. device->client = 0;
  221556. device->close();
  221557. }
  221558. }
  221559. static void errorCallback (const char* msg)
  221560. {
  221561. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  221562. }
  221563. bool isOpen_;
  221564. jack_client_t* client;
  221565. String lastError;
  221566. AudioIODeviceCallback* callback;
  221567. CriticalSection callbackLock;
  221568. HeapBlock <float*> inChans, outChans;
  221569. int totalNumberOfInputChannels;
  221570. int totalNumberOfOutputChannels;
  221571. Array<void*> inputPorts, outputPorts;
  221572. };
  221573. class JackAudioIODeviceType : public AudioIODeviceType
  221574. {
  221575. public:
  221576. JackAudioIODeviceType()
  221577. : AudioIODeviceType ("JACK"),
  221578. hasScanned (false)
  221579. {
  221580. }
  221581. ~JackAudioIODeviceType()
  221582. {
  221583. }
  221584. void scanForDevices()
  221585. {
  221586. hasScanned = true;
  221587. inputNames.clear();
  221588. inputIds.clear();
  221589. outputNames.clear();
  221590. outputIds.clear();
  221591. if (juce_libjack_handle == 0)
  221592. {
  221593. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  221594. if (juce_libjack_handle == 0)
  221595. return;
  221596. }
  221597. // open a dummy client
  221598. jack_status_t status;
  221599. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  221600. if (client == 0)
  221601. {
  221602. dumpJackErrorMessage (status);
  221603. }
  221604. else
  221605. {
  221606. // scan for output devices
  221607. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221608. if (ports != 0)
  221609. {
  221610. int j = 0;
  221611. while (ports[j] != 0)
  221612. {
  221613. String clientName (ports[j]);
  221614. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  221615. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  221616. && ! inputNames.contains (clientName))
  221617. {
  221618. inputNames.add (clientName);
  221619. inputIds.add (ports [j]);
  221620. }
  221621. ++j;
  221622. }
  221623. free (ports);
  221624. }
  221625. // scan for input devices
  221626. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221627. if (ports != 0)
  221628. {
  221629. int j = 0;
  221630. while (ports[j] != 0)
  221631. {
  221632. String clientName (ports[j]);
  221633. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  221634. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  221635. && ! outputNames.contains (clientName))
  221636. {
  221637. outputNames.add (clientName);
  221638. outputIds.add (ports [j]);
  221639. }
  221640. ++j;
  221641. }
  221642. free (ports);
  221643. }
  221644. JUCE_NAMESPACE::jack_client_close (client);
  221645. }
  221646. }
  221647. const StringArray getDeviceNames (bool wantInputNames) const
  221648. {
  221649. jassert (hasScanned); // need to call scanForDevices() before doing this
  221650. return wantInputNames ? inputNames : outputNames;
  221651. }
  221652. int getDefaultDeviceIndex (bool forInput) const
  221653. {
  221654. jassert (hasScanned); // need to call scanForDevices() before doing this
  221655. return 0;
  221656. }
  221657. bool hasSeparateInputsAndOutputs() const { return true; }
  221658. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221659. {
  221660. jassert (hasScanned); // need to call scanForDevices() before doing this
  221661. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  221662. if (d == 0)
  221663. return -1;
  221664. return asInput ? inputIds.indexOf (d->inputId)
  221665. : outputIds.indexOf (d->outputId);
  221666. }
  221667. AudioIODevice* createDevice (const String& outputDeviceName,
  221668. const String& inputDeviceName)
  221669. {
  221670. jassert (hasScanned); // need to call scanForDevices() before doing this
  221671. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221672. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221673. if (inputIndex >= 0 || outputIndex >= 0)
  221674. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  221675. : inputDeviceName,
  221676. inputIds [inputIndex],
  221677. outputIds [outputIndex]);
  221678. return 0;
  221679. }
  221680. juce_UseDebuggingNewOperator
  221681. private:
  221682. StringArray inputNames, outputNames, inputIds, outputIds;
  221683. bool hasScanned;
  221684. JackAudioIODeviceType (const JackAudioIODeviceType&);
  221685. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  221686. };
  221687. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  221688. {
  221689. return new JackAudioIODeviceType();
  221690. }
  221691. #else // if JACK is turned off..
  221692. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  221693. #endif
  221694. #endif
  221695. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  221696. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  221697. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221698. // compiled on its own).
  221699. #if JUCE_INCLUDED_FILE
  221700. #if JUCE_ALSA
  221701. static snd_seq_t* iterateDevices (const bool forInput,
  221702. StringArray& deviceNamesFound,
  221703. const int deviceIndexToOpen)
  221704. {
  221705. snd_seq_t* returnedHandle = 0;
  221706. snd_seq_t* seqHandle;
  221707. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  221708. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  221709. {
  221710. snd_seq_system_info_t* systemInfo;
  221711. snd_seq_client_info_t* clientInfo;
  221712. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  221713. {
  221714. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  221715. && snd_seq_client_info_malloc (&clientInfo) == 0)
  221716. {
  221717. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  221718. while (--numClients >= 0 && returnedHandle == 0)
  221719. {
  221720. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  221721. {
  221722. snd_seq_port_info_t* portInfo;
  221723. if (snd_seq_port_info_malloc (&portInfo) == 0)
  221724. {
  221725. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  221726. const int client = snd_seq_client_info_get_client (clientInfo);
  221727. snd_seq_port_info_set_client (portInfo, client);
  221728. snd_seq_port_info_set_port (portInfo, -1);
  221729. while (--numPorts >= 0)
  221730. {
  221731. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  221732. && (snd_seq_port_info_get_capability (portInfo)
  221733. & (forInput ? SND_SEQ_PORT_CAP_READ
  221734. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  221735. {
  221736. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  221737. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  221738. {
  221739. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  221740. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  221741. if (sourcePort != -1)
  221742. {
  221743. snd_seq_set_client_name (seqHandle,
  221744. forInput ? "Juce Midi Input"
  221745. : "Juce Midi Output");
  221746. const int portId
  221747. = snd_seq_create_simple_port (seqHandle,
  221748. forInput ? "Juce Midi In Port"
  221749. : "Juce Midi Out Port",
  221750. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  221751. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  221752. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  221753. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  221754. returnedHandle = seqHandle;
  221755. }
  221756. }
  221757. }
  221758. }
  221759. snd_seq_port_info_free (portInfo);
  221760. }
  221761. }
  221762. }
  221763. snd_seq_client_info_free (clientInfo);
  221764. }
  221765. snd_seq_system_info_free (systemInfo);
  221766. }
  221767. if (returnedHandle == 0)
  221768. snd_seq_close (seqHandle);
  221769. }
  221770. deviceNamesFound.appendNumbersToDuplicates (true, true);
  221771. return returnedHandle;
  221772. }
  221773. static snd_seq_t* createDevice (const bool forInput,
  221774. const String& deviceNameToOpen)
  221775. {
  221776. snd_seq_t* seqHandle = 0;
  221777. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  221778. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  221779. {
  221780. snd_seq_set_client_name (seqHandle,
  221781. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  221782. const int portId
  221783. = snd_seq_create_simple_port (seqHandle,
  221784. forInput ? "in"
  221785. : "out",
  221786. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  221787. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  221788. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  221789. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  221790. if (portId < 0)
  221791. {
  221792. snd_seq_close (seqHandle);
  221793. seqHandle = 0;
  221794. }
  221795. }
  221796. return seqHandle;
  221797. }
  221798. class MidiOutputDevice
  221799. {
  221800. public:
  221801. MidiOutputDevice (MidiOutput* const midiOutput_,
  221802. snd_seq_t* const seqHandle_)
  221803. :
  221804. midiOutput (midiOutput_),
  221805. seqHandle (seqHandle_),
  221806. maxEventSize (16 * 1024)
  221807. {
  221808. jassert (seqHandle != 0 && midiOutput != 0);
  221809. snd_midi_event_new (maxEventSize, &midiParser);
  221810. }
  221811. ~MidiOutputDevice()
  221812. {
  221813. snd_midi_event_free (midiParser);
  221814. snd_seq_close (seqHandle);
  221815. }
  221816. void sendMessageNow (const MidiMessage& message)
  221817. {
  221818. if (message.getRawDataSize() > maxEventSize)
  221819. {
  221820. maxEventSize = message.getRawDataSize();
  221821. snd_midi_event_free (midiParser);
  221822. snd_midi_event_new (maxEventSize, &midiParser);
  221823. }
  221824. snd_seq_event_t event;
  221825. snd_seq_ev_clear (&event);
  221826. snd_midi_event_encode (midiParser,
  221827. message.getRawData(),
  221828. message.getRawDataSize(),
  221829. &event);
  221830. snd_midi_event_reset_encode (midiParser);
  221831. snd_seq_ev_set_source (&event, 0);
  221832. snd_seq_ev_set_subs (&event);
  221833. snd_seq_ev_set_direct (&event);
  221834. snd_seq_event_output (seqHandle, &event);
  221835. snd_seq_drain_output (seqHandle);
  221836. }
  221837. juce_UseDebuggingNewOperator
  221838. private:
  221839. MidiOutput* const midiOutput;
  221840. snd_seq_t* const seqHandle;
  221841. snd_midi_event_t* midiParser;
  221842. int maxEventSize;
  221843. };
  221844. const StringArray MidiOutput::getDevices()
  221845. {
  221846. StringArray devices;
  221847. iterateDevices (false, devices, -1);
  221848. return devices;
  221849. }
  221850. int MidiOutput::getDefaultDeviceIndex()
  221851. {
  221852. return 0;
  221853. }
  221854. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  221855. {
  221856. MidiOutput* newDevice = 0;
  221857. StringArray devices;
  221858. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  221859. if (handle != 0)
  221860. {
  221861. newDevice = new MidiOutput();
  221862. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  221863. }
  221864. return newDevice;
  221865. }
  221866. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  221867. {
  221868. MidiOutput* newDevice = 0;
  221869. snd_seq_t* const handle = createDevice (false, deviceName);
  221870. if (handle != 0)
  221871. {
  221872. newDevice = new MidiOutput();
  221873. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  221874. }
  221875. return newDevice;
  221876. }
  221877. MidiOutput::~MidiOutput()
  221878. {
  221879. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  221880. delete device;
  221881. }
  221882. void MidiOutput::reset()
  221883. {
  221884. }
  221885. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  221886. {
  221887. return false;
  221888. }
  221889. void MidiOutput::setVolume (float leftVol, float rightVol)
  221890. {
  221891. }
  221892. void MidiOutput::sendMessageNow (const MidiMessage& message)
  221893. {
  221894. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  221895. }
  221896. class MidiInputThread : public Thread
  221897. {
  221898. public:
  221899. MidiInputThread (MidiInput* const midiInput_,
  221900. snd_seq_t* const seqHandle_,
  221901. MidiInputCallback* const callback_)
  221902. : Thread ("Juce MIDI Input"),
  221903. midiInput (midiInput_),
  221904. seqHandle (seqHandle_),
  221905. callback (callback_)
  221906. {
  221907. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  221908. }
  221909. ~MidiInputThread()
  221910. {
  221911. snd_seq_close (seqHandle);
  221912. }
  221913. void run()
  221914. {
  221915. const int maxEventSize = 16 * 1024;
  221916. snd_midi_event_t* midiParser;
  221917. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  221918. {
  221919. HeapBlock <uint8> buffer (maxEventSize);
  221920. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  221921. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  221922. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  221923. while (! threadShouldExit())
  221924. {
  221925. if (poll (pfd, numPfds, 500) > 0)
  221926. {
  221927. snd_seq_event_t* inputEvent = 0;
  221928. snd_seq_nonblock (seqHandle, 1);
  221929. do
  221930. {
  221931. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  221932. {
  221933. // xxx what about SYSEXes that are too big for the buffer?
  221934. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  221935. snd_midi_event_reset_decode (midiParser);
  221936. if (numBytes > 0)
  221937. {
  221938. const MidiMessage message ((const uint8*) buffer,
  221939. numBytes,
  221940. Time::getMillisecondCounter() * 0.001);
  221941. callback->handleIncomingMidiMessage (midiInput, message);
  221942. }
  221943. snd_seq_free_event (inputEvent);
  221944. }
  221945. }
  221946. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  221947. snd_seq_free_event (inputEvent);
  221948. }
  221949. }
  221950. snd_midi_event_free (midiParser);
  221951. }
  221952. };
  221953. juce_UseDebuggingNewOperator
  221954. private:
  221955. MidiInput* const midiInput;
  221956. snd_seq_t* const seqHandle;
  221957. MidiInputCallback* const callback;
  221958. };
  221959. MidiInput::MidiInput (const String& name_)
  221960. : name (name_),
  221961. internal (0)
  221962. {
  221963. }
  221964. MidiInput::~MidiInput()
  221965. {
  221966. stop();
  221967. MidiInputThread* const thread = (MidiInputThread*) internal;
  221968. delete thread;
  221969. }
  221970. void MidiInput::start()
  221971. {
  221972. ((MidiInputThread*) internal)->startThread();
  221973. }
  221974. void MidiInput::stop()
  221975. {
  221976. ((MidiInputThread*) internal)->stopThread (3000);
  221977. }
  221978. int MidiInput::getDefaultDeviceIndex()
  221979. {
  221980. return 0;
  221981. }
  221982. const StringArray MidiInput::getDevices()
  221983. {
  221984. StringArray devices;
  221985. iterateDevices (true, devices, -1);
  221986. return devices;
  221987. }
  221988. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  221989. {
  221990. MidiInput* newDevice = 0;
  221991. StringArray devices;
  221992. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  221993. if (handle != 0)
  221994. {
  221995. newDevice = new MidiInput (devices [deviceIndex]);
  221996. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  221997. }
  221998. return newDevice;
  221999. }
  222000. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222001. {
  222002. MidiInput* newDevice = 0;
  222003. snd_seq_t* const handle = createDevice (true, deviceName);
  222004. if (handle != 0)
  222005. {
  222006. newDevice = new MidiInput (deviceName);
  222007. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222008. }
  222009. return newDevice;
  222010. }
  222011. #else
  222012. // (These are just stub functions if ALSA is unavailable...)
  222013. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222014. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222015. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222016. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222017. MidiOutput::~MidiOutput() {}
  222018. void MidiOutput::reset() {}
  222019. bool MidiOutput::getVolume (float&, float&) { return false; }
  222020. void MidiOutput::setVolume (float, float) {}
  222021. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222022. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222023. MidiInput::~MidiInput() {}
  222024. void MidiInput::start() {}
  222025. void MidiInput::stop() {}
  222026. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222027. const StringArray MidiInput::getDevices() { return StringArray(); }
  222028. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222029. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222030. #endif
  222031. #endif
  222032. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222033. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222034. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222035. // compiled on its own).
  222036. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222037. AudioCDReader::AudioCDReader()
  222038. : AudioFormatReader (0, "CD Audio")
  222039. {
  222040. }
  222041. const StringArray AudioCDReader::getAvailableCDNames()
  222042. {
  222043. StringArray names;
  222044. return names;
  222045. }
  222046. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222047. {
  222048. return 0;
  222049. }
  222050. AudioCDReader::~AudioCDReader()
  222051. {
  222052. }
  222053. void AudioCDReader::refreshTrackLengths()
  222054. {
  222055. }
  222056. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222057. int64 startSampleInFile, int numSamples)
  222058. {
  222059. return false;
  222060. }
  222061. bool AudioCDReader::isCDStillPresent() const
  222062. {
  222063. return false;
  222064. }
  222065. int AudioCDReader::getNumTracks() const
  222066. {
  222067. return 0;
  222068. }
  222069. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  222070. {
  222071. return 0;
  222072. }
  222073. bool AudioCDReader::isTrackAudio (int trackNum) const
  222074. {
  222075. return false;
  222076. }
  222077. void AudioCDReader::enableIndexScanning (bool b)
  222078. {
  222079. }
  222080. int AudioCDReader::getLastIndex() const
  222081. {
  222082. return 0;
  222083. }
  222084. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222085. {
  222086. return Array<int>();
  222087. }
  222088. int AudioCDReader::getCDDBId()
  222089. {
  222090. return 0;
  222091. }
  222092. #endif
  222093. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222094. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222095. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222096. // compiled on its own).
  222097. #if JUCE_INCLUDED_FILE
  222098. void FileChooser::showPlatformDialog (Array<File>& results,
  222099. const String& title,
  222100. const File& file,
  222101. const String& filters,
  222102. bool isDirectory,
  222103. bool selectsFiles,
  222104. bool isSave,
  222105. bool warnAboutOverwritingExistingFiles,
  222106. bool selectMultipleFiles,
  222107. FilePreviewComponent* previewComponent)
  222108. {
  222109. const String separator (":");
  222110. String command ("zenity --file-selection");
  222111. if (title.isNotEmpty())
  222112. command << " --title=\"" << title << "\"";
  222113. if (file != File::nonexistent)
  222114. command << " --filename=\"" << file.getFullPathName () << "\"";
  222115. if (isDirectory)
  222116. command << " --directory";
  222117. if (isSave)
  222118. command << " --save";
  222119. if (selectMultipleFiles)
  222120. command << " --multiple --separator=\"" << separator << "\"";
  222121. command << " 2>&1";
  222122. MemoryOutputStream result;
  222123. int status = -1;
  222124. FILE* stream = popen (command.toUTF8(), "r");
  222125. if (stream != 0)
  222126. {
  222127. for (;;)
  222128. {
  222129. char buffer [1024];
  222130. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  222131. if (bytesRead <= 0)
  222132. break;
  222133. result.write (buffer, bytesRead);
  222134. }
  222135. status = pclose (stream);
  222136. }
  222137. if (status == 0)
  222138. {
  222139. StringArray tokens;
  222140. if (selectMultipleFiles)
  222141. tokens.addTokens (result.toUTF8(), separator, String::empty);
  222142. else
  222143. tokens.add (result.toUTF8());
  222144. for (int i = 0; i < tokens.size(); i++)
  222145. results.add (File (tokens[i]));
  222146. return;
  222147. }
  222148. //xxx ain't got one!
  222149. jassertfalse;
  222150. }
  222151. #endif
  222152. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  222153. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222154. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222155. // compiled on its own).
  222156. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222157. /*
  222158. Sorry.. This class isn't implemented on Linux!
  222159. */
  222160. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222161. : browser (0),
  222162. blankPageShown (false),
  222163. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222164. {
  222165. setOpaque (true);
  222166. }
  222167. WebBrowserComponent::~WebBrowserComponent()
  222168. {
  222169. }
  222170. void WebBrowserComponent::goToURL (const String& url,
  222171. const StringArray* headers,
  222172. const MemoryBlock* postData)
  222173. {
  222174. lastURL = url;
  222175. lastHeaders.clear();
  222176. if (headers != 0)
  222177. lastHeaders = *headers;
  222178. lastPostData.setSize (0);
  222179. if (postData != 0)
  222180. lastPostData = *postData;
  222181. blankPageShown = false;
  222182. }
  222183. void WebBrowserComponent::stop()
  222184. {
  222185. }
  222186. void WebBrowserComponent::goBack()
  222187. {
  222188. lastURL = String::empty;
  222189. blankPageShown = false;
  222190. }
  222191. void WebBrowserComponent::goForward()
  222192. {
  222193. lastURL = String::empty;
  222194. }
  222195. void WebBrowserComponent::refresh()
  222196. {
  222197. }
  222198. void WebBrowserComponent::paint (Graphics& g)
  222199. {
  222200. g.fillAll (Colours::white);
  222201. }
  222202. void WebBrowserComponent::checkWindowAssociation()
  222203. {
  222204. }
  222205. void WebBrowserComponent::reloadLastURL()
  222206. {
  222207. if (lastURL.isNotEmpty())
  222208. {
  222209. goToURL (lastURL, &lastHeaders, &lastPostData);
  222210. lastURL = String::empty;
  222211. }
  222212. }
  222213. void WebBrowserComponent::parentHierarchyChanged()
  222214. {
  222215. checkWindowAssociation();
  222216. }
  222217. void WebBrowserComponent::resized()
  222218. {
  222219. }
  222220. void WebBrowserComponent::visibilityChanged()
  222221. {
  222222. checkWindowAssociation();
  222223. }
  222224. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222225. {
  222226. return true;
  222227. }
  222228. #endif
  222229. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222230. #endif
  222231. END_JUCE_NAMESPACE
  222232. #endif
  222233. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  222234. #endif
  222235. #if JUCE_MAC || JUCE_IPHONE
  222236. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  222237. /*
  222238. This file wraps together all the mac-specific code, so that
  222239. we can include all the native headers just once, and compile all our
  222240. platform-specific stuff in one big lump, keeping it out of the way of
  222241. the rest of the codebase.
  222242. */
  222243. #if JUCE_MAC || JUCE_IPHONE
  222244. BEGIN_JUCE_NAMESPACE
  222245. #undef Point
  222246. #define JUCE_INCLUDED_FILE 1
  222247. // Now include the actual code files..
  222248. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  222249. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  222250. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  222251. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  222252. cross-linked so that when you make a call to a class that you thought was private, it ends up
  222253. actually calling into a similarly named class in the other module's address space.
  222254. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  222255. have unique names, and should avoid this problem.
  222256. If you're using the amalgamated version, you can just set this macro to something unique before
  222257. you include juce_amalgamated.cpp.
  222258. */
  222259. #ifndef JUCE_ObjCExtraSuffix
  222260. #define JUCE_ObjCExtraSuffix 3
  222261. #endif
  222262. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  222263. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  222264. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  222265. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  222266. /*** Start of inlined file: juce_mac_Strings.mm ***/
  222267. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222268. // compiled on its own).
  222269. #if JUCE_INCLUDED_FILE
  222270. static const String nsStringToJuce (NSString* s)
  222271. {
  222272. return String::fromUTF8 ([s UTF8String]);
  222273. }
  222274. static NSString* juceStringToNS (const String& s)
  222275. {
  222276. return [NSString stringWithUTF8String: s.toUTF8()];
  222277. }
  222278. static const String convertUTF16ToString (const UniChar* utf16)
  222279. {
  222280. String s;
  222281. while (*utf16 != 0)
  222282. s += (juce_wchar) *utf16++;
  222283. return s;
  222284. }
  222285. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  222286. {
  222287. String result;
  222288. if (cfString != 0)
  222289. {
  222290. CFRange range = { 0, CFStringGetLength (cfString) };
  222291. HeapBlock <UniChar> u (range.length + 1);
  222292. CFStringGetCharacters (cfString, range, u);
  222293. u[range.length] = 0;
  222294. result = convertUTF16ToString (u);
  222295. }
  222296. return result;
  222297. }
  222298. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  222299. {
  222300. const int len = s.length();
  222301. HeapBlock <UniChar> temp (len + 2);
  222302. for (int i = 0; i <= len; ++i)
  222303. temp[i] = s[i];
  222304. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  222305. }
  222306. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  222307. {
  222308. #if JUCE_IPHONE
  222309. const ScopedAutoReleasePool pool;
  222310. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  222311. #else
  222312. UnicodeMapping map;
  222313. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222314. kUnicodeNoSubset,
  222315. kTextEncodingDefaultFormat);
  222316. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222317. kUnicodeCanonicalCompVariant,
  222318. kTextEncodingDefaultFormat);
  222319. map.mappingVersion = kUnicodeUseLatestMapping;
  222320. UnicodeToTextInfo conversionInfo = 0;
  222321. String result;
  222322. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  222323. {
  222324. const int len = s.length();
  222325. HeapBlock <UniChar> tempIn, tempOut;
  222326. tempIn.calloc (len + 2);
  222327. tempOut.calloc (len + 2);
  222328. for (int i = 0; i <= len; ++i)
  222329. tempIn[i] = s[i];
  222330. ByteCount bytesRead = 0;
  222331. ByteCount outputBufferSize = 0;
  222332. if (ConvertFromUnicodeToText (conversionInfo,
  222333. len * sizeof (UniChar), tempIn,
  222334. kUnicodeDefaultDirectionMask,
  222335. 0, 0, 0, 0,
  222336. len * sizeof (UniChar), &bytesRead,
  222337. &outputBufferSize, tempOut) == noErr)
  222338. {
  222339. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  222340. juce_wchar* t = result;
  222341. unsigned int i;
  222342. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  222343. t[i] = (juce_wchar) tempOut[i];
  222344. t[i] = 0;
  222345. }
  222346. DisposeUnicodeToTextInfo (&conversionInfo);
  222347. }
  222348. return result;
  222349. #endif
  222350. }
  222351. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222352. void SystemClipboard::copyTextToClipboard (const String& text)
  222353. {
  222354. #if JUCE_IPHONE
  222355. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  222356. forPasteboardType: @"public.text"];
  222357. #else
  222358. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  222359. owner: nil];
  222360. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  222361. forType: NSStringPboardType];
  222362. #endif
  222363. }
  222364. const String SystemClipboard::getTextFromClipboard()
  222365. {
  222366. #if JUCE_IPHONE
  222367. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  222368. #else
  222369. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  222370. #endif
  222371. return text == 0 ? String::empty
  222372. : nsStringToJuce (text);
  222373. }
  222374. #endif
  222375. #endif
  222376. /*** End of inlined file: juce_mac_Strings.mm ***/
  222377. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  222378. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222379. // compiled on its own).
  222380. #if JUCE_INCLUDED_FILE
  222381. namespace SystemStatsHelpers
  222382. {
  222383. static int64 highResTimerFrequency = 0;
  222384. static double highResTimerToMillisecRatio = 0;
  222385. #if JUCE_INTEL
  222386. static void juce_getCpuVendor (char* const v) throw()
  222387. {
  222388. int vendor[4];
  222389. zerostruct (vendor);
  222390. int dummy = 0;
  222391. asm ("mov %%ebx, %%esi \n\t"
  222392. "cpuid \n\t"
  222393. "xchg %%esi, %%ebx"
  222394. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  222395. memcpy (v, vendor, 16);
  222396. }
  222397. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  222398. {
  222399. unsigned int cpu = 0;
  222400. unsigned int ext = 0;
  222401. unsigned int family = 0;
  222402. unsigned int dummy = 0;
  222403. asm ("mov %%ebx, %%esi \n\t"
  222404. "cpuid \n\t"
  222405. "xchg %%esi, %%ebx"
  222406. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  222407. familyModel = family;
  222408. extFeatures = ext;
  222409. return cpu;
  222410. }
  222411. struct CPUFlags
  222412. {
  222413. bool hasMMX : 1;
  222414. bool hasSSE : 1;
  222415. bool hasSSE2 : 1;
  222416. bool has3DNow : 1;
  222417. };
  222418. static CPUFlags cpuFlags;
  222419. #endif
  222420. }
  222421. void SystemStats::initialiseStats()
  222422. {
  222423. using namespace SystemStatsHelpers;
  222424. static bool initialised = false;
  222425. if (! initialised)
  222426. {
  222427. initialised = true;
  222428. #if JUCE_MAC
  222429. // extremely annoying: adding this line stops the apple menu items from working. Of
  222430. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  222431. // any events.
  222432. //NSApplicationLoad();
  222433. [NSApplication sharedApplication];
  222434. #endif
  222435. #if JUCE_INTEL
  222436. {
  222437. unsigned int familyModel, extFeatures;
  222438. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  222439. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  222440. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  222441. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  222442. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  222443. }
  222444. #endif
  222445. mach_timebase_info_data_t timebase;
  222446. (void) mach_timebase_info (&timebase);
  222447. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  222448. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  222449. String s (SystemStats::getJUCEVersion());
  222450. rlimit lim;
  222451. getrlimit (RLIMIT_NOFILE, &lim);
  222452. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  222453. setrlimit (RLIMIT_NOFILE, &lim);
  222454. }
  222455. }
  222456. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  222457. {
  222458. return MacOSX;
  222459. }
  222460. const String SystemStats::getOperatingSystemName()
  222461. {
  222462. return "Mac OS X";
  222463. }
  222464. bool SystemStats::isOperatingSystem64Bit()
  222465. {
  222466. #if JUCE_64BIT
  222467. return true;
  222468. #else
  222469. //xxx not sure how to find this out?..
  222470. return false;
  222471. #endif
  222472. }
  222473. int SystemStats::getMemorySizeInMegabytes()
  222474. {
  222475. uint64 mem = 0;
  222476. size_t memSize = sizeof (mem);
  222477. int mib[] = { CTL_HW, HW_MEMSIZE };
  222478. sysctl (mib, 2, &mem, &memSize, 0, 0);
  222479. return (int) (mem / (1024 * 1024));
  222480. }
  222481. bool SystemStats::hasMMX()
  222482. {
  222483. #if JUCE_INTEL
  222484. return SystemStatsHelpers::cpuFlags.hasMMX;
  222485. #else
  222486. return false;
  222487. #endif
  222488. }
  222489. bool SystemStats::hasSSE()
  222490. {
  222491. #if JUCE_INTEL
  222492. return SystemStatsHelpers::cpuFlags.hasSSE;
  222493. #else
  222494. return false;
  222495. #endif
  222496. }
  222497. bool SystemStats::hasSSE2()
  222498. {
  222499. #if JUCE_INTEL
  222500. return SystemStatsHelpers::cpuFlags.hasSSE2;
  222501. #else
  222502. return false;
  222503. #endif
  222504. }
  222505. bool SystemStats::has3DNow()
  222506. {
  222507. #if JUCE_INTEL
  222508. return SystemStatsHelpers::cpuFlags.has3DNow;
  222509. #else
  222510. return false;
  222511. #endif
  222512. }
  222513. const String SystemStats::getCpuVendor()
  222514. {
  222515. #if JUCE_INTEL
  222516. char v [16];
  222517. SystemStatsHelpers::juce_getCpuVendor (v);
  222518. return String (v, 16);
  222519. #else
  222520. return String::empty;
  222521. #endif
  222522. }
  222523. int SystemStats::getCpuSpeedInMegaherz()
  222524. {
  222525. uint64 speedHz = 0;
  222526. size_t speedSize = sizeof (speedHz);
  222527. int mib[] = { CTL_HW, HW_CPU_FREQ };
  222528. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  222529. #if JUCE_BIG_ENDIAN
  222530. if (speedSize == 4)
  222531. speedHz >>= 32;
  222532. #endif
  222533. return (int) (speedHz / 1000000);
  222534. }
  222535. int SystemStats::getNumCpus()
  222536. {
  222537. #if JUCE_IPHONE || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  222538. return (int) [[NSProcessInfo processInfo] activeProcessorCount];
  222539. #else
  222540. return MPProcessors();
  222541. #endif
  222542. }
  222543. const String SystemStats::getLogonName()
  222544. {
  222545. return nsStringToJuce (NSUserName());
  222546. }
  222547. const String SystemStats::getFullUserName()
  222548. {
  222549. return nsStringToJuce (NSFullUserName());
  222550. }
  222551. uint32 juce_millisecondsSinceStartup() throw()
  222552. {
  222553. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  222554. }
  222555. double Time::getMillisecondCounterHiRes() throw()
  222556. {
  222557. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  222558. }
  222559. int64 Time::getHighResolutionTicks() throw()
  222560. {
  222561. return (int64) mach_absolute_time();
  222562. }
  222563. int64 Time::getHighResolutionTicksPerSecond() throw()
  222564. {
  222565. return SystemStatsHelpers::highResTimerFrequency;
  222566. }
  222567. bool Time::setSystemTimeToThisTime() const
  222568. {
  222569. jassertfalse;
  222570. return false;
  222571. }
  222572. int SystemStats::getPageSize()
  222573. {
  222574. return (int) NSPageSize();
  222575. }
  222576. void PlatformUtilities::fpuReset()
  222577. {
  222578. }
  222579. #endif
  222580. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  222581. /*** Start of inlined file: juce_mac_Network.mm ***/
  222582. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222583. // compiled on its own).
  222584. #if JUCE_INCLUDED_FILE
  222585. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  222586. {
  222587. #ifndef IFT_ETHER
  222588. #define IFT_ETHER 6
  222589. #endif
  222590. ifaddrs* addrs = 0;
  222591. int numResults = 0;
  222592. if (getifaddrs (&addrs) == 0)
  222593. {
  222594. const ifaddrs* cursor = addrs;
  222595. while (cursor != 0 && numResults < maxNum)
  222596. {
  222597. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  222598. if (sto->ss_family == AF_LINK)
  222599. {
  222600. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  222601. if (sadd->sdl_type == IFT_ETHER)
  222602. {
  222603. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  222604. uint64 a = 0;
  222605. for (int i = 6; --i >= 0;)
  222606. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  222607. *addresses++ = (int64) a;
  222608. ++numResults;
  222609. }
  222610. }
  222611. cursor = cursor->ifa_next;
  222612. }
  222613. freeifaddrs (addrs);
  222614. }
  222615. return numResults;
  222616. }
  222617. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  222618. const String& emailSubject,
  222619. const String& bodyText,
  222620. const StringArray& filesToAttach)
  222621. {
  222622. #if JUCE_IPHONE
  222623. //xxx probably need to use MFMailComposeViewController
  222624. jassertfalse;
  222625. return false;
  222626. #else
  222627. const ScopedAutoReleasePool pool;
  222628. String script;
  222629. script << "tell application \"Mail\"\r\n"
  222630. "set newMessage to make new outgoing message with properties {subject:\""
  222631. << emailSubject.replace ("\"", "\\\"")
  222632. << "\", content:\""
  222633. << bodyText.replace ("\"", "\\\"")
  222634. << "\" & return & return}\r\n"
  222635. "tell newMessage\r\n"
  222636. "set visible to true\r\n"
  222637. "set sender to \"sdfsdfsdfewf\"\r\n"
  222638. "make new to recipient at end of to recipients with properties {address:\""
  222639. << targetEmailAddress
  222640. << "\"}\r\n";
  222641. for (int i = 0; i < filesToAttach.size(); ++i)
  222642. {
  222643. script << "tell content\r\n"
  222644. "make new attachment with properties {file name:\""
  222645. << filesToAttach[i].replace ("\"", "\\\"")
  222646. << "\"} at after the last paragraph\r\n"
  222647. "end tell\r\n";
  222648. }
  222649. script << "end tell\r\n"
  222650. "end tell\r\n";
  222651. NSAppleScript* s = [[NSAppleScript alloc]
  222652. initWithSource: juceStringToNS (script)];
  222653. NSDictionary* error = 0;
  222654. const bool ok = [s executeAndReturnError: &error] != nil;
  222655. [s release];
  222656. return ok;
  222657. #endif
  222658. }
  222659. END_JUCE_NAMESPACE
  222660. using namespace JUCE_NAMESPACE;
  222661. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  222662. @interface JuceURLConnection : NSObject
  222663. {
  222664. @public
  222665. NSURLRequest* request;
  222666. NSURLConnection* connection;
  222667. NSMutableData* data;
  222668. Thread* runLoopThread;
  222669. bool initialised, hasFailed, hasFinished;
  222670. int position;
  222671. int64 contentLength;
  222672. NSDictionary* headers;
  222673. NSLock* dataLock;
  222674. }
  222675. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  222676. - (void) dealloc;
  222677. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  222678. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  222679. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  222680. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  222681. - (BOOL) isOpen;
  222682. - (int) read: (char*) dest numBytes: (int) num;
  222683. - (int) readPosition;
  222684. - (void) stop;
  222685. - (void) createConnection;
  222686. @end
  222687. class JuceURLConnectionMessageThread : public Thread
  222688. {
  222689. JuceURLConnection* owner;
  222690. public:
  222691. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  222692. : Thread ("http connection"),
  222693. owner (owner_)
  222694. {
  222695. }
  222696. ~JuceURLConnectionMessageThread()
  222697. {
  222698. stopThread (10000);
  222699. }
  222700. void run()
  222701. {
  222702. [owner createConnection];
  222703. while (! threadShouldExit())
  222704. {
  222705. const ScopedAutoReleasePool pool;
  222706. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  222707. }
  222708. }
  222709. };
  222710. @implementation JuceURLConnection
  222711. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  222712. withCallback: (URL::OpenStreamProgressCallback*) callback
  222713. withContext: (void*) context;
  222714. {
  222715. [super init];
  222716. request = req;
  222717. [request retain];
  222718. data = [[NSMutableData data] retain];
  222719. dataLock = [[NSLock alloc] init];
  222720. connection = 0;
  222721. initialised = false;
  222722. hasFailed = false;
  222723. hasFinished = false;
  222724. contentLength = -1;
  222725. headers = 0;
  222726. runLoopThread = new JuceURLConnectionMessageThread (self);
  222727. runLoopThread->startThread();
  222728. while (runLoopThread->isThreadRunning() && ! initialised)
  222729. {
  222730. if (callback != 0)
  222731. callback (context, -1, (int) [[request HTTPBody] length]);
  222732. Thread::sleep (1);
  222733. }
  222734. return self;
  222735. }
  222736. - (void) dealloc
  222737. {
  222738. [self stop];
  222739. deleteAndZero (runLoopThread);
  222740. [connection release];
  222741. [data release];
  222742. [dataLock release];
  222743. [request release];
  222744. [headers release];
  222745. [super dealloc];
  222746. }
  222747. - (void) createConnection
  222748. {
  222749. connection = [[NSURLConnection alloc] initWithRequest: request
  222750. delegate: [self retain]];
  222751. if (connection == nil)
  222752. runLoopThread->signalThreadShouldExit();
  222753. }
  222754. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  222755. {
  222756. (void) conn;
  222757. [dataLock lock];
  222758. [data setLength: 0];
  222759. [dataLock unlock];
  222760. initialised = true;
  222761. contentLength = [response expectedContentLength];
  222762. [headers release];
  222763. headers = 0;
  222764. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  222765. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  222766. }
  222767. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  222768. {
  222769. (void) conn;
  222770. DBG (nsStringToJuce ([error description]));
  222771. hasFailed = true;
  222772. initialised = true;
  222773. if (runLoopThread != 0)
  222774. runLoopThread->signalThreadShouldExit();
  222775. }
  222776. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  222777. {
  222778. (void) conn;
  222779. [dataLock lock];
  222780. [data appendData: newData];
  222781. [dataLock unlock];
  222782. initialised = true;
  222783. }
  222784. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  222785. {
  222786. (void) conn;
  222787. hasFinished = true;
  222788. initialised = true;
  222789. if (runLoopThread != 0)
  222790. runLoopThread->signalThreadShouldExit();
  222791. }
  222792. - (BOOL) isOpen
  222793. {
  222794. return connection != 0 && ! hasFailed;
  222795. }
  222796. - (int) readPosition
  222797. {
  222798. return position;
  222799. }
  222800. - (int) read: (char*) dest numBytes: (int) numNeeded
  222801. {
  222802. int numDone = 0;
  222803. while (numNeeded > 0)
  222804. {
  222805. int available = jmin (numNeeded, (int) [data length]);
  222806. if (available > 0)
  222807. {
  222808. [dataLock lock];
  222809. [data getBytes: dest length: available];
  222810. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  222811. [dataLock unlock];
  222812. numDone += available;
  222813. numNeeded -= available;
  222814. dest += available;
  222815. }
  222816. else
  222817. {
  222818. if (hasFailed || hasFinished)
  222819. break;
  222820. Thread::sleep (1);
  222821. }
  222822. }
  222823. position += numDone;
  222824. return numDone;
  222825. }
  222826. - (void) stop
  222827. {
  222828. [connection cancel];
  222829. if (runLoopThread != 0)
  222830. runLoopThread->stopThread (10000);
  222831. }
  222832. @end
  222833. BEGIN_JUCE_NAMESPACE
  222834. void* juce_openInternetFile (const String& url,
  222835. const String& headers,
  222836. const MemoryBlock& postData,
  222837. const bool isPost,
  222838. URL::OpenStreamProgressCallback* callback,
  222839. void* callbackContext,
  222840. int timeOutMs)
  222841. {
  222842. const ScopedAutoReleasePool pool;
  222843. NSMutableURLRequest* req = [NSMutableURLRequest
  222844. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  222845. cachePolicy: NSURLRequestUseProtocolCachePolicy
  222846. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  222847. if (req == nil)
  222848. return 0;
  222849. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  222850. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  222851. StringArray headerLines;
  222852. headerLines.addLines (headers);
  222853. headerLines.removeEmptyStrings (true);
  222854. for (int i = 0; i < headerLines.size(); ++i)
  222855. {
  222856. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  222857. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  222858. if (key.isNotEmpty() && value.isNotEmpty())
  222859. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  222860. }
  222861. if (isPost && postData.getSize() > 0)
  222862. {
  222863. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  222864. length: postData.getSize()]];
  222865. }
  222866. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  222867. withCallback: callback
  222868. withContext: callbackContext];
  222869. if ([s isOpen])
  222870. return s;
  222871. [s release];
  222872. return 0;
  222873. }
  222874. void juce_closeInternetFile (void* handle)
  222875. {
  222876. JuceURLConnection* const s = (JuceURLConnection*) handle;
  222877. if (s != 0)
  222878. {
  222879. const ScopedAutoReleasePool pool;
  222880. [s stop];
  222881. [s release];
  222882. }
  222883. }
  222884. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  222885. {
  222886. JuceURLConnection* const s = (JuceURLConnection*) handle;
  222887. if (s != 0)
  222888. {
  222889. const ScopedAutoReleasePool pool;
  222890. return [s read: (char*) buffer numBytes: bytesToRead];
  222891. }
  222892. return 0;
  222893. }
  222894. int64 juce_getInternetFileContentLength (void* handle)
  222895. {
  222896. JuceURLConnection* const s = (JuceURLConnection*) handle;
  222897. if (s != 0)
  222898. return s->contentLength;
  222899. return -1;
  222900. }
  222901. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  222902. {
  222903. JuceURLConnection* const s = (JuceURLConnection*) handle;
  222904. if (s != 0 && s->headers != 0)
  222905. {
  222906. NSEnumerator* enumerator = [s->headers keyEnumerator];
  222907. NSString* key;
  222908. while ((key = [enumerator nextObject]) != nil)
  222909. headers.set (nsStringToJuce (key),
  222910. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  222911. }
  222912. }
  222913. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  222914. {
  222915. JuceURLConnection* const s = (JuceURLConnection*) handle;
  222916. if (s != 0)
  222917. return [s readPosition];
  222918. return 0;
  222919. }
  222920. #endif
  222921. /*** End of inlined file: juce_mac_Network.mm ***/
  222922. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  222923. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222924. // compiled on its own).
  222925. #if JUCE_INCLUDED_FILE
  222926. struct NamedPipeInternal
  222927. {
  222928. String pipeInName, pipeOutName;
  222929. int pipeIn, pipeOut;
  222930. bool volatile createdPipe, blocked, stopReadOperation;
  222931. static void signalHandler (int) {}
  222932. };
  222933. void NamedPipe::cancelPendingReads()
  222934. {
  222935. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  222936. {
  222937. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  222938. intern->stopReadOperation = true;
  222939. char buffer [1] = { 0 };
  222940. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  222941. (void) bytesWritten;
  222942. int timeout = 2000;
  222943. while (intern->blocked && --timeout >= 0)
  222944. Thread::sleep (2);
  222945. intern->stopReadOperation = false;
  222946. }
  222947. }
  222948. void NamedPipe::close()
  222949. {
  222950. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  222951. if (intern != 0)
  222952. {
  222953. internal = 0;
  222954. if (intern->pipeIn != -1)
  222955. ::close (intern->pipeIn);
  222956. if (intern->pipeOut != -1)
  222957. ::close (intern->pipeOut);
  222958. if (intern->createdPipe)
  222959. {
  222960. unlink (intern->pipeInName.toUTF8());
  222961. unlink (intern->pipeOutName.toUTF8());
  222962. }
  222963. delete intern;
  222964. }
  222965. }
  222966. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  222967. {
  222968. close();
  222969. NamedPipeInternal* const intern = new NamedPipeInternal();
  222970. internal = intern;
  222971. intern->createdPipe = createPipe;
  222972. intern->blocked = false;
  222973. intern->stopReadOperation = false;
  222974. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  222975. siginterrupt (SIGPIPE, 1);
  222976. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  222977. intern->pipeInName = pipePath + "_in";
  222978. intern->pipeOutName = pipePath + "_out";
  222979. intern->pipeIn = -1;
  222980. intern->pipeOut = -1;
  222981. if (createPipe)
  222982. {
  222983. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  222984. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  222985. {
  222986. delete intern;
  222987. internal = 0;
  222988. return false;
  222989. }
  222990. }
  222991. return true;
  222992. }
  222993. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  222994. {
  222995. int bytesRead = -1;
  222996. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  222997. if (intern != 0)
  222998. {
  222999. intern->blocked = true;
  223000. if (intern->pipeIn == -1)
  223001. {
  223002. if (intern->createdPipe)
  223003. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223004. else
  223005. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223006. if (intern->pipeIn == -1)
  223007. {
  223008. intern->blocked = false;
  223009. return -1;
  223010. }
  223011. }
  223012. bytesRead = 0;
  223013. char* p = (char*) destBuffer;
  223014. while (bytesRead < maxBytesToRead)
  223015. {
  223016. const int bytesThisTime = maxBytesToRead - bytesRead;
  223017. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223018. if (numRead <= 0 || intern->stopReadOperation)
  223019. {
  223020. bytesRead = -1;
  223021. break;
  223022. }
  223023. bytesRead += numRead;
  223024. p += bytesRead;
  223025. }
  223026. intern->blocked = false;
  223027. }
  223028. return bytesRead;
  223029. }
  223030. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223031. {
  223032. int bytesWritten = -1;
  223033. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223034. if (intern != 0)
  223035. {
  223036. if (intern->pipeOut == -1)
  223037. {
  223038. if (intern->createdPipe)
  223039. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223040. else
  223041. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223042. if (intern->pipeOut == -1)
  223043. {
  223044. return -1;
  223045. }
  223046. }
  223047. const char* p = (const char*) sourceBuffer;
  223048. bytesWritten = 0;
  223049. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223050. while (bytesWritten < numBytesToWrite
  223051. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223052. {
  223053. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223054. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223055. if (numWritten <= 0)
  223056. {
  223057. bytesWritten = -1;
  223058. break;
  223059. }
  223060. bytesWritten += numWritten;
  223061. p += bytesWritten;
  223062. }
  223063. }
  223064. return bytesWritten;
  223065. }
  223066. #endif
  223067. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  223068. /*** Start of inlined file: juce_mac_Threads.mm ***/
  223069. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223070. // compiled on its own).
  223071. #if JUCE_INCLUDED_FILE
  223072. /*
  223073. Note that a lot of methods that you'd expect to find in this file actually
  223074. live in juce_posix_SharedCode.h!
  223075. */
  223076. void JUCE_API juce_threadEntryPoint (void*);
  223077. void* threadEntryProc (void* userData)
  223078. {
  223079. const ScopedAutoReleasePool pool;
  223080. juce_threadEntryPoint (userData);
  223081. return 0;
  223082. }
  223083. void* juce_createThread (void* userData)
  223084. {
  223085. pthread_t handle = 0;
  223086. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  223087. {
  223088. pthread_detach (handle);
  223089. return (void*) handle;
  223090. }
  223091. return 0;
  223092. }
  223093. void juce_killThread (void* handle)
  223094. {
  223095. if (handle != 0)
  223096. pthread_cancel ((pthread_t) handle);
  223097. }
  223098. void juce_setCurrentThreadName (const String& /*name*/)
  223099. {
  223100. }
  223101. bool juce_setThreadPriority (void* handle, int priority)
  223102. {
  223103. if (handle == 0)
  223104. handle = (void*) pthread_self();
  223105. struct sched_param param;
  223106. int policy;
  223107. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  223108. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  223109. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  223110. }
  223111. Thread::ThreadID Thread::getCurrentThreadId()
  223112. {
  223113. return static_cast <ThreadID> (pthread_self());
  223114. }
  223115. void Thread::yield()
  223116. {
  223117. sched_yield();
  223118. }
  223119. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  223120. {
  223121. // xxx
  223122. jassertfalse;
  223123. }
  223124. bool Process::isForegroundProcess()
  223125. {
  223126. #if JUCE_MAC
  223127. return [NSApp isActive];
  223128. #else
  223129. return true; // xxx change this if more than one app is ever possible on the iPhone!
  223130. #endif
  223131. }
  223132. void Process::raisePrivilege()
  223133. {
  223134. jassertfalse;
  223135. }
  223136. void Process::lowerPrivilege()
  223137. {
  223138. jassertfalse;
  223139. }
  223140. void Process::terminate()
  223141. {
  223142. exit (0);
  223143. }
  223144. void Process::setPriority (ProcessPriority)
  223145. {
  223146. // xxx
  223147. }
  223148. #endif
  223149. /*** End of inlined file: juce_mac_Threads.mm ***/
  223150. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  223151. /*
  223152. This file contains posix routines that are common to both the Linux and Mac builds.
  223153. It gets included directly in the cpp files for these platforms.
  223154. */
  223155. CriticalSection::CriticalSection() throw()
  223156. {
  223157. pthread_mutexattr_t atts;
  223158. pthread_mutexattr_init (&atts);
  223159. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  223160. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223161. pthread_mutex_init (&internal, &atts);
  223162. }
  223163. CriticalSection::~CriticalSection() throw()
  223164. {
  223165. pthread_mutex_destroy (&internal);
  223166. }
  223167. void CriticalSection::enter() const throw()
  223168. {
  223169. pthread_mutex_lock (&internal);
  223170. }
  223171. bool CriticalSection::tryEnter() const throw()
  223172. {
  223173. return pthread_mutex_trylock (&internal) == 0;
  223174. }
  223175. void CriticalSection::exit() const throw()
  223176. {
  223177. pthread_mutex_unlock (&internal);
  223178. }
  223179. class WaitableEventImpl
  223180. {
  223181. public:
  223182. WaitableEventImpl (const bool manualReset_)
  223183. : triggered (false),
  223184. manualReset (manualReset_)
  223185. {
  223186. pthread_cond_init (&condition, 0);
  223187. pthread_mutex_init (&mutex, 0);
  223188. }
  223189. ~WaitableEventImpl()
  223190. {
  223191. pthread_cond_destroy (&condition);
  223192. pthread_mutex_destroy (&mutex);
  223193. }
  223194. bool wait (const int timeOutMillisecs) throw()
  223195. {
  223196. pthread_mutex_lock (&mutex);
  223197. if (! triggered)
  223198. {
  223199. if (timeOutMillisecs < 0)
  223200. {
  223201. do
  223202. {
  223203. pthread_cond_wait (&condition, &mutex);
  223204. }
  223205. while (! triggered);
  223206. }
  223207. else
  223208. {
  223209. struct timeval now;
  223210. gettimeofday (&now, 0);
  223211. struct timespec time;
  223212. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  223213. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  223214. if (time.tv_nsec >= 1000000000)
  223215. {
  223216. time.tv_nsec -= 1000000000;
  223217. time.tv_sec++;
  223218. }
  223219. do
  223220. {
  223221. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  223222. {
  223223. pthread_mutex_unlock (&mutex);
  223224. return false;
  223225. }
  223226. }
  223227. while (! triggered);
  223228. }
  223229. }
  223230. if (! manualReset)
  223231. triggered = false;
  223232. pthread_mutex_unlock (&mutex);
  223233. return true;
  223234. }
  223235. void signal() throw()
  223236. {
  223237. pthread_mutex_lock (&mutex);
  223238. triggered = true;
  223239. pthread_cond_broadcast (&condition);
  223240. pthread_mutex_unlock (&mutex);
  223241. }
  223242. void reset() throw()
  223243. {
  223244. pthread_mutex_lock (&mutex);
  223245. triggered = false;
  223246. pthread_mutex_unlock (&mutex);
  223247. }
  223248. private:
  223249. pthread_cond_t condition;
  223250. pthread_mutex_t mutex;
  223251. bool triggered;
  223252. const bool manualReset;
  223253. WaitableEventImpl (const WaitableEventImpl&);
  223254. WaitableEventImpl& operator= (const WaitableEventImpl&);
  223255. };
  223256. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  223257. : internal (new WaitableEventImpl (manualReset))
  223258. {
  223259. }
  223260. WaitableEvent::~WaitableEvent() throw()
  223261. {
  223262. delete static_cast <WaitableEventImpl*> (internal);
  223263. }
  223264. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  223265. {
  223266. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  223267. }
  223268. void WaitableEvent::signal() const throw()
  223269. {
  223270. static_cast <WaitableEventImpl*> (internal)->signal();
  223271. }
  223272. void WaitableEvent::reset() const throw()
  223273. {
  223274. static_cast <WaitableEventImpl*> (internal)->reset();
  223275. }
  223276. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  223277. {
  223278. struct timespec time;
  223279. time.tv_sec = millisecs / 1000;
  223280. time.tv_nsec = (millisecs % 1000) * 1000000;
  223281. nanosleep (&time, 0);
  223282. }
  223283. const juce_wchar File::separator = '/';
  223284. const String File::separatorString ("/");
  223285. const File File::getCurrentWorkingDirectory()
  223286. {
  223287. HeapBlock<char> heapBuffer;
  223288. char localBuffer [1024];
  223289. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  223290. int bufferSize = 4096;
  223291. while (cwd == 0 && errno == ERANGE)
  223292. {
  223293. heapBuffer.malloc (bufferSize);
  223294. cwd = getcwd (heapBuffer, bufferSize - 1);
  223295. bufferSize += 1024;
  223296. }
  223297. return File (String::fromUTF8 (cwd));
  223298. }
  223299. bool File::setAsCurrentWorkingDirectory() const
  223300. {
  223301. return chdir (getFullPathName().toUTF8()) == 0;
  223302. }
  223303. static bool juce_stat (const String& fileName, struct stat& info)
  223304. {
  223305. return fileName.isNotEmpty()
  223306. && (stat (fileName.toUTF8(), &info) == 0);
  223307. }
  223308. bool File::isDirectory() const
  223309. {
  223310. struct stat info;
  223311. return fullPath.isEmpty()
  223312. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  223313. }
  223314. bool File::exists() const
  223315. {
  223316. return fullPath.isNotEmpty()
  223317. && access (fullPath.toUTF8(), F_OK) == 0;
  223318. }
  223319. bool File::existsAsFile() const
  223320. {
  223321. return exists() && ! isDirectory();
  223322. }
  223323. int64 File::getSize() const
  223324. {
  223325. struct stat info;
  223326. return juce_stat (fullPath, info) ? info.st_size : 0;
  223327. }
  223328. bool File::hasWriteAccess() const
  223329. {
  223330. if (exists())
  223331. return access (fullPath.toUTF8(), W_OK) == 0;
  223332. if ((! isDirectory()) && fullPath.containsChar (separator))
  223333. return getParentDirectory().hasWriteAccess();
  223334. return false;
  223335. }
  223336. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  223337. {
  223338. struct stat info;
  223339. const int res = stat (fullPath.toUTF8(), &info);
  223340. if (res != 0)
  223341. return false;
  223342. info.st_mode &= 0777; // Just permissions
  223343. if (shouldBeReadOnly)
  223344. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  223345. else
  223346. // Give everybody write permission?
  223347. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  223348. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  223349. }
  223350. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  223351. {
  223352. modificationTime = 0;
  223353. accessTime = 0;
  223354. creationTime = 0;
  223355. struct stat info;
  223356. const int res = stat (fullPath.toUTF8(), &info);
  223357. if (res == 0)
  223358. {
  223359. modificationTime = (int64) info.st_mtime * 1000;
  223360. accessTime = (int64) info.st_atime * 1000;
  223361. creationTime = (int64) info.st_ctime * 1000;
  223362. }
  223363. }
  223364. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  223365. {
  223366. struct utimbuf times;
  223367. times.actime = (time_t) (accessTime / 1000);
  223368. times.modtime = (time_t) (modificationTime / 1000);
  223369. return utime (fullPath.toUTF8(), &times) == 0;
  223370. }
  223371. bool File::deleteFile() const
  223372. {
  223373. if (! exists())
  223374. return true;
  223375. else if (isDirectory())
  223376. return rmdir (fullPath.toUTF8()) == 0;
  223377. else
  223378. return remove (fullPath.toUTF8()) == 0;
  223379. }
  223380. bool File::moveInternal (const File& dest) const
  223381. {
  223382. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  223383. return true;
  223384. if (hasWriteAccess() && copyInternal (dest))
  223385. {
  223386. if (deleteFile())
  223387. return true;
  223388. dest.deleteFile();
  223389. }
  223390. return false;
  223391. }
  223392. void File::createDirectoryInternal (const String& fileName) const
  223393. {
  223394. mkdir (fileName.toUTF8(), 0777);
  223395. }
  223396. void* juce_fileOpen (const File& file, bool forWriting)
  223397. {
  223398. int flags = O_RDONLY;
  223399. if (forWriting)
  223400. {
  223401. if (file.exists())
  223402. {
  223403. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  223404. if (f != -1)
  223405. lseek (f, 0, SEEK_END);
  223406. return (void*) f;
  223407. }
  223408. else
  223409. {
  223410. flags = O_RDWR + O_CREAT;
  223411. }
  223412. }
  223413. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  223414. }
  223415. void juce_fileClose (void* handle)
  223416. {
  223417. if (handle != 0)
  223418. close ((int) (pointer_sized_int) handle);
  223419. }
  223420. int juce_fileRead (void* handle, void* buffer, int size)
  223421. {
  223422. if (handle != 0)
  223423. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  223424. return 0;
  223425. }
  223426. int juce_fileWrite (void* handle, const void* buffer, int size)
  223427. {
  223428. if (handle != 0)
  223429. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  223430. return 0;
  223431. }
  223432. int64 juce_fileSetPosition (void* handle, int64 pos)
  223433. {
  223434. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  223435. return pos;
  223436. return -1;
  223437. }
  223438. int64 FileOutputStream::getPositionInternal() const
  223439. {
  223440. if (fileHandle != 0)
  223441. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  223442. return -1;
  223443. }
  223444. void FileOutputStream::flushInternal()
  223445. {
  223446. if (fileHandle != 0)
  223447. fsync ((int) (pointer_sized_int) fileHandle);
  223448. }
  223449. const File juce_getExecutableFile()
  223450. {
  223451. Dl_info exeInfo;
  223452. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  223453. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  223454. }
  223455. // if this file doesn't exist, find a parent of it that does..
  223456. static bool juce_doStatFS (File f, struct statfs& result)
  223457. {
  223458. for (int i = 5; --i >= 0;)
  223459. {
  223460. if (f.exists())
  223461. break;
  223462. f = f.getParentDirectory();
  223463. }
  223464. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  223465. }
  223466. int64 File::getBytesFreeOnVolume() const
  223467. {
  223468. struct statfs buf;
  223469. if (juce_doStatFS (*this, buf))
  223470. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  223471. return 0;
  223472. }
  223473. int64 File::getVolumeTotalSize() const
  223474. {
  223475. struct statfs buf;
  223476. if (juce_doStatFS (*this, buf))
  223477. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  223478. return 0;
  223479. }
  223480. const String File::getVolumeLabel() const
  223481. {
  223482. #if JUCE_MAC
  223483. struct VolAttrBuf
  223484. {
  223485. u_int32_t length;
  223486. attrreference_t mountPointRef;
  223487. char mountPointSpace [MAXPATHLEN];
  223488. } attrBuf;
  223489. struct attrlist attrList;
  223490. zerostruct (attrList);
  223491. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  223492. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  223493. File f (*this);
  223494. for (;;)
  223495. {
  223496. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  223497. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  223498. (int) attrBuf.mountPointRef.attr_length);
  223499. const File parent (f.getParentDirectory());
  223500. if (f == parent)
  223501. break;
  223502. f = parent;
  223503. }
  223504. #endif
  223505. return String::empty;
  223506. }
  223507. int File::getVolumeSerialNumber() const
  223508. {
  223509. return 0; // xxx
  223510. }
  223511. void juce_runSystemCommand (const String& command)
  223512. {
  223513. int result = system (command.toUTF8());
  223514. (void) result;
  223515. }
  223516. const String juce_getOutputFromCommand (const String& command)
  223517. {
  223518. // slight bodge here, as we just pipe the output into a temp file and read it...
  223519. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  223520. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  223521. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  223522. String result (tempFile.loadFileAsString());
  223523. tempFile.deleteFile();
  223524. return result;
  223525. }
  223526. class InterProcessLock::Pimpl
  223527. {
  223528. public:
  223529. Pimpl (const String& name, const int timeOutMillisecs)
  223530. : handle (0), refCount (1)
  223531. {
  223532. #if JUCE_MAC
  223533. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  223534. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  223535. #else
  223536. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  223537. #endif
  223538. temp.create();
  223539. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  223540. if (handle != 0)
  223541. {
  223542. struct flock fl;
  223543. zerostruct (fl);
  223544. fl.l_whence = SEEK_SET;
  223545. fl.l_type = F_WRLCK;
  223546. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  223547. for (;;)
  223548. {
  223549. const int result = fcntl (handle, F_SETLK, &fl);
  223550. if (result >= 0)
  223551. return;
  223552. if (errno != EINTR)
  223553. {
  223554. if (timeOutMillisecs == 0
  223555. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  223556. break;
  223557. Thread::sleep (10);
  223558. }
  223559. }
  223560. }
  223561. closeFile();
  223562. }
  223563. ~Pimpl()
  223564. {
  223565. closeFile();
  223566. }
  223567. void closeFile()
  223568. {
  223569. if (handle != 0)
  223570. {
  223571. struct flock fl;
  223572. zerostruct (fl);
  223573. fl.l_whence = SEEK_SET;
  223574. fl.l_type = F_UNLCK;
  223575. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  223576. {}
  223577. close (handle);
  223578. handle = 0;
  223579. }
  223580. }
  223581. int handle, refCount;
  223582. };
  223583. InterProcessLock::InterProcessLock (const String& name_)
  223584. : name (name_)
  223585. {
  223586. }
  223587. InterProcessLock::~InterProcessLock()
  223588. {
  223589. }
  223590. bool InterProcessLock::enter (const int timeOutMillisecs)
  223591. {
  223592. const ScopedLock sl (lock);
  223593. if (pimpl == 0)
  223594. {
  223595. pimpl = new Pimpl (name, timeOutMillisecs);
  223596. if (pimpl->handle == 0)
  223597. pimpl = 0;
  223598. }
  223599. else
  223600. {
  223601. pimpl->refCount++;
  223602. }
  223603. return pimpl != 0;
  223604. }
  223605. void InterProcessLock::exit()
  223606. {
  223607. const ScopedLock sl (lock);
  223608. // Trying to release the lock too many times!
  223609. jassert (pimpl != 0);
  223610. if (pimpl != 0 && --(pimpl->refCount) == 0)
  223611. pimpl = 0;
  223612. }
  223613. /*** End of inlined file: juce_posix_SharedCode.h ***/
  223614. /*** Start of inlined file: juce_mac_Files.mm ***/
  223615. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223616. // compiled on its own).
  223617. #if JUCE_INCLUDED_FILE
  223618. /*
  223619. Note that a lot of methods that you'd expect to find in this file actually
  223620. live in juce_posix_SharedCode.h!
  223621. */
  223622. bool File::copyInternal (const File& dest) const
  223623. {
  223624. const ScopedAutoReleasePool pool;
  223625. NSFileManager* fm = [NSFileManager defaultManager];
  223626. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  223627. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  223628. && [fm copyItemAtPath: juceStringToNS (fullPath)
  223629. toPath: juceStringToNS (dest.getFullPathName())
  223630. error: nil];
  223631. #else
  223632. && [fm copyPath: juceStringToNS (fullPath)
  223633. toPath: juceStringToNS (dest.getFullPathName())
  223634. handler: nil];
  223635. #endif
  223636. }
  223637. void File::findFileSystemRoots (Array<File>& destArray)
  223638. {
  223639. destArray.add (File ("/"));
  223640. }
  223641. static bool isFileOnDriveType (const File& f, const char* const* types)
  223642. {
  223643. struct statfs buf;
  223644. if (juce_doStatFS (f, buf))
  223645. {
  223646. const String type (buf.f_fstypename);
  223647. while (*types != 0)
  223648. if (type.equalsIgnoreCase (*types++))
  223649. return true;
  223650. }
  223651. return false;
  223652. }
  223653. bool File::isOnCDRomDrive() const
  223654. {
  223655. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  223656. return isFileOnDriveType (*this, cdTypes);
  223657. }
  223658. bool File::isOnHardDisk() const
  223659. {
  223660. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  223661. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  223662. }
  223663. bool File::isOnRemovableDrive() const
  223664. {
  223665. #if JUCE_IPHONE
  223666. return false; // xxx is this possible?
  223667. #else
  223668. const ScopedAutoReleasePool pool;
  223669. BOOL removable = false;
  223670. [[NSWorkspace sharedWorkspace]
  223671. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  223672. isRemovable: &removable
  223673. isWritable: nil
  223674. isUnmountable: nil
  223675. description: nil
  223676. type: nil];
  223677. return removable;
  223678. #endif
  223679. }
  223680. static bool juce_isHiddenFile (const String& path)
  223681. {
  223682. #if JUCE_IPHONE
  223683. return File (path).getFileName().startsWithChar ('.');
  223684. #else
  223685. FSRef ref;
  223686. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  223687. return false;
  223688. FSCatalogInfo info;
  223689. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  223690. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  223691. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  223692. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  223693. #endif
  223694. }
  223695. bool File::isHidden() const
  223696. {
  223697. return juce_isHiddenFile (getFullPathName());
  223698. }
  223699. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  223700. const File File::getSpecialLocation (const SpecialLocationType type)
  223701. {
  223702. const ScopedAutoReleasePool pool;
  223703. String resultPath;
  223704. switch (type)
  223705. {
  223706. case userHomeDirectory:
  223707. resultPath = nsStringToJuce (NSHomeDirectory());
  223708. break;
  223709. case userDocumentsDirectory:
  223710. resultPath = "~/Documents";
  223711. break;
  223712. case userDesktopDirectory:
  223713. resultPath = "~/Desktop";
  223714. break;
  223715. case userApplicationDataDirectory:
  223716. resultPath = "~/Library";
  223717. break;
  223718. case commonApplicationDataDirectory:
  223719. resultPath = "/Library";
  223720. break;
  223721. case globalApplicationsDirectory:
  223722. resultPath = "/Applications";
  223723. break;
  223724. case userMusicDirectory:
  223725. resultPath = "~/Music";
  223726. break;
  223727. case userMoviesDirectory:
  223728. resultPath = "~/Movies";
  223729. break;
  223730. case tempDirectory:
  223731. {
  223732. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  223733. tmp.createDirectory();
  223734. return tmp.getFullPathName();
  223735. }
  223736. case invokedExecutableFile:
  223737. if (juce_Argv0 != 0)
  223738. return File (String::fromUTF8 (juce_Argv0));
  223739. // deliberate fall-through...
  223740. case currentExecutableFile:
  223741. return juce_getExecutableFile();
  223742. case currentApplicationFile:
  223743. {
  223744. const File exe (juce_getExecutableFile());
  223745. const File parent (exe.getParentDirectory());
  223746. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  223747. ? parent.getParentDirectory().getParentDirectory()
  223748. : exe;
  223749. }
  223750. default:
  223751. jassertfalse; // unknown type?
  223752. break;
  223753. }
  223754. if (resultPath.isNotEmpty())
  223755. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  223756. return File::nonexistent;
  223757. }
  223758. const String File::getVersion() const
  223759. {
  223760. const ScopedAutoReleasePool pool;
  223761. String result;
  223762. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  223763. if (bundle != 0)
  223764. {
  223765. NSDictionary* info = [bundle infoDictionary];
  223766. if (info != 0)
  223767. {
  223768. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  223769. if (name != nil)
  223770. result = nsStringToJuce (name);
  223771. }
  223772. }
  223773. return result;
  223774. }
  223775. const File File::getLinkedTarget() const
  223776. {
  223777. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  223778. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  223779. #else
  223780. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  223781. #endif
  223782. if (dest != nil)
  223783. return File (nsStringToJuce (dest));
  223784. return *this;
  223785. }
  223786. bool File::moveToTrash() const
  223787. {
  223788. if (! exists())
  223789. return true;
  223790. #if JUCE_IPHONE
  223791. return deleteFile(); //xxx is there a trashcan on the iPhone?
  223792. #else
  223793. const ScopedAutoReleasePool pool;
  223794. NSString* p = juceStringToNS (getFullPathName());
  223795. return [[NSWorkspace sharedWorkspace]
  223796. performFileOperation: NSWorkspaceRecycleOperation
  223797. source: [p stringByDeletingLastPathComponent]
  223798. destination: @""
  223799. files: [NSArray arrayWithObject: [p lastPathComponent]]
  223800. tag: nil ];
  223801. #endif
  223802. }
  223803. class DirectoryIterator::NativeIterator::Pimpl
  223804. {
  223805. public:
  223806. Pimpl (const File& directory, const String& wildCard_)
  223807. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  223808. wildCard (wildCard_),
  223809. enumerator (0)
  223810. {
  223811. ScopedAutoReleasePool pool;
  223812. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  223813. wildcardUTF8 = wildCard.toUTF8();
  223814. }
  223815. ~Pimpl()
  223816. {
  223817. [enumerator release];
  223818. }
  223819. bool next (String& filenameFound,
  223820. bool* const isDir, bool* const isHidden, int64* const fileSize,
  223821. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  223822. {
  223823. ScopedAutoReleasePool pool;
  223824. for (;;)
  223825. {
  223826. NSString* file;
  223827. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  223828. return false;
  223829. [enumerator skipDescendents];
  223830. filenameFound = nsStringToJuce (file);
  223831. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  223832. continue;
  223833. const String path (parentDir + filenameFound);
  223834. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  223835. {
  223836. struct stat info;
  223837. const bool statOk = juce_stat (path, info);
  223838. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  223839. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  223840. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  223841. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  223842. }
  223843. if (isHidden != 0)
  223844. *isHidden = juce_isHiddenFile (path);
  223845. if (isReadOnly != 0)
  223846. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  223847. return true;
  223848. }
  223849. }
  223850. private:
  223851. String parentDir, wildCard;
  223852. const char* wildcardUTF8;
  223853. NSDirectoryEnumerator* enumerator;
  223854. Pimpl (const Pimpl&);
  223855. Pimpl& operator= (const Pimpl&);
  223856. };
  223857. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  223858. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  223859. {
  223860. }
  223861. DirectoryIterator::NativeIterator::~NativeIterator()
  223862. {
  223863. }
  223864. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  223865. bool* const isDir, bool* const isHidden, int64* const fileSize,
  223866. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  223867. {
  223868. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  223869. }
  223870. bool juce_launchExecutable (const String& pathAndArguments)
  223871. {
  223872. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  223873. const int cpid = fork();
  223874. if (cpid == 0)
  223875. {
  223876. // Child process
  223877. if (execve (argv[0], (char**) argv, 0) < 0)
  223878. exit (0);
  223879. }
  223880. else
  223881. {
  223882. if (cpid < 0)
  223883. return false;
  223884. }
  223885. return true;
  223886. }
  223887. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  223888. {
  223889. #if JUCE_IPHONE
  223890. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  223891. #else
  223892. const ScopedAutoReleasePool pool;
  223893. if (parameters.isEmpty())
  223894. {
  223895. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  223896. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  223897. }
  223898. bool ok = false;
  223899. FSRef ref;
  223900. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  223901. {
  223902. if (PlatformUtilities::isBundle (fileName))
  223903. {
  223904. NSMutableArray* urls = [NSMutableArray array];
  223905. StringArray docs;
  223906. docs.addTokens (parameters, true);
  223907. for (int i = 0; i < docs.size(); ++i)
  223908. [urls addObject: juceStringToNS (docs[i])];
  223909. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  223910. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  223911. options: 0
  223912. additionalEventParamDescriptor: nil
  223913. launchIdentifiers: nil];
  223914. }
  223915. else
  223916. {
  223917. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  223918. }
  223919. }
  223920. return ok;
  223921. #endif
  223922. }
  223923. void File::revealToUser() const
  223924. {
  223925. #if ! JUCE_IPHONE
  223926. if (exists())
  223927. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  223928. else if (getParentDirectory().exists())
  223929. getParentDirectory().revealToUser();
  223930. #endif
  223931. }
  223932. #if ! JUCE_IPHONE
  223933. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  223934. {
  223935. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  223936. }
  223937. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  223938. {
  223939. char path [2048];
  223940. zerostruct (path);
  223941. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  223942. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  223943. return String::empty;
  223944. }
  223945. #endif
  223946. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  223947. {
  223948. const ScopedAutoReleasePool pool;
  223949. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  223950. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  223951. #else
  223952. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  223953. #endif
  223954. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  223955. return [fileDict fileHFSTypeCode];
  223956. }
  223957. bool PlatformUtilities::isBundle (const String& filename)
  223958. {
  223959. #if JUCE_IPHONE
  223960. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  223961. #else
  223962. const ScopedAutoReleasePool pool;
  223963. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  223964. #endif
  223965. }
  223966. #endif
  223967. /*** End of inlined file: juce_mac_Files.mm ***/
  223968. #if JUCE_IPHONE
  223969. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  223970. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223971. // compiled on its own).
  223972. #if JUCE_INCLUDED_FILE
  223973. static JUCEApplication* juce_intialisingApp;
  223974. END_JUCE_NAMESPACE
  223975. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  223976. {
  223977. }
  223978. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  223979. - (void) applicationWillResignActive: (UIApplication*) application;
  223980. @end
  223981. @implementation JuceAppStartupDelegate
  223982. - (void) applicationDidFinishLaunching: (UIApplication*) application
  223983. {
  223984. String dummy;
  223985. if (! juce_intialisingApp->initialiseApp (dummy))
  223986. exit (0);
  223987. }
  223988. - (void) applicationWillResignActive: (UIApplication*) application
  223989. {
  223990. JUCEApplication::shutdownAppAndClearUp();
  223991. }
  223992. @end
  223993. BEGIN_JUCE_NAMESPACE
  223994. int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app)
  223995. {
  223996. juce_intialisingApp = app;
  223997. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  223998. }
  223999. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224000. {
  224001. pool = [[NSAutoreleasePool alloc] init];
  224002. }
  224003. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224004. {
  224005. [((NSAutoreleasePool*) pool) release];
  224006. }
  224007. void PlatformUtilities::beep()
  224008. {
  224009. //xxx
  224010. //AudioServicesPlaySystemSound ();
  224011. }
  224012. void PlatformUtilities::addItemToDock (const File& file)
  224013. {
  224014. }
  224015. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224016. END_JUCE_NAMESPACE
  224017. @interface JuceAlertBoxDelegate : NSObject
  224018. {
  224019. @public
  224020. bool clickedOk;
  224021. }
  224022. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  224023. @end
  224024. @implementation JuceAlertBoxDelegate
  224025. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  224026. {
  224027. clickedOk = (buttonIndex == 0);
  224028. alertView.hidden = true;
  224029. }
  224030. @end
  224031. BEGIN_JUCE_NAMESPACE
  224032. // (This function is used directly by other bits of code)
  224033. bool juce_iPhoneShowModalAlert (const String& title,
  224034. const String& bodyText,
  224035. NSString* okButtonText,
  224036. NSString* cancelButtonText)
  224037. {
  224038. const ScopedAutoReleasePool pool;
  224039. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  224040. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  224041. message: juceStringToNS (bodyText)
  224042. delegate: callback
  224043. cancelButtonTitle: okButtonText
  224044. otherButtonTitles: cancelButtonText, nil];
  224045. [alert retain];
  224046. [alert show];
  224047. while (! alert.hidden && alert.superview != nil)
  224048. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224049. const bool result = callback->clickedOk;
  224050. [alert release];
  224051. [callback release];
  224052. return result;
  224053. }
  224054. bool AlertWindow::showNativeDialogBox (const String& title,
  224055. const String& bodyText,
  224056. bool isOkCancel)
  224057. {
  224058. return juce_iPhoneShowModalAlert (title, bodyText,
  224059. @"OK",
  224060. isOkCancel ? @"Cancel" : nil);
  224061. }
  224062. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  224063. {
  224064. jassertfalse; // no such thing on the iphone!
  224065. return false;
  224066. }
  224067. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  224068. {
  224069. jassertfalse; // no such thing on the iphone!
  224070. return false;
  224071. }
  224072. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224073. {
  224074. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  224075. }
  224076. bool Desktop::isScreenSaverEnabled()
  224077. {
  224078. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  224079. }
  224080. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  224081. {
  224082. const ScopedAutoReleasePool pool;
  224083. monitorCoords.clear();
  224084. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  224085. : [[UIScreen mainScreen] bounds];
  224086. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224087. (int) r.origin.y,
  224088. (int) r.size.width,
  224089. (int) r.size.height));
  224090. }
  224091. #endif
  224092. #endif
  224093. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  224094. #else
  224095. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  224096. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224097. // compiled on its own).
  224098. #if JUCE_INCLUDED_FILE
  224099. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224100. {
  224101. pool = [[NSAutoreleasePool alloc] init];
  224102. }
  224103. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224104. {
  224105. [((NSAutoreleasePool*) pool) release];
  224106. }
  224107. void PlatformUtilities::beep()
  224108. {
  224109. NSBeep();
  224110. }
  224111. void PlatformUtilities::addItemToDock (const File& file)
  224112. {
  224113. // check that it's not already there...
  224114. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  224115. .containsIgnoreCase (file.getFullPathName()))
  224116. {
  224117. juce_runSystemCommand ("defaults write com.apple.dock persistent-apps -array-add \"<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>"
  224118. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  224119. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  224120. }
  224121. }
  224122. int PlatformUtilities::getOSXMinorVersionNumber()
  224123. {
  224124. SInt32 versionMinor = 0;
  224125. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224126. (void) err;
  224127. jassert (err == noErr);
  224128. return (int) versionMinor;
  224129. }
  224130. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224131. bool AlertWindow::showNativeDialogBox (const String& title,
  224132. const String& bodyText,
  224133. bool isOkCancel)
  224134. {
  224135. const ScopedAutoReleasePool pool;
  224136. return NSRunAlertPanel (juceStringToNS (title),
  224137. juceStringToNS (bodyText),
  224138. @"Ok",
  224139. isOkCancel ? @"Cancel" : nil,
  224140. nil) == NSAlertDefaultReturn;
  224141. }
  224142. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  224143. {
  224144. if (files.size() == 0)
  224145. return false;
  224146. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  224147. if (draggingSource == 0)
  224148. {
  224149. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224150. return false;
  224151. }
  224152. Component* sourceComp = draggingSource->getComponentUnderMouse();
  224153. if (sourceComp == 0)
  224154. {
  224155. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224156. return false;
  224157. }
  224158. const ScopedAutoReleasePool pool;
  224159. NSView* view = (NSView*) sourceComp->getWindowHandle();
  224160. if (view == 0)
  224161. return false;
  224162. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  224163. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  224164. owner: nil];
  224165. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  224166. for (int i = 0; i < files.size(); ++i)
  224167. [filesArray addObject: juceStringToNS (files[i])];
  224168. [pboard setPropertyList: filesArray
  224169. forType: NSFilenamesPboardType];
  224170. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  224171. fromView: nil];
  224172. dragPosition.x -= 16;
  224173. dragPosition.y -= 16;
  224174. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  224175. at: dragPosition
  224176. offset: NSMakeSize (0, 0)
  224177. event: [[view window] currentEvent]
  224178. pasteboard: pboard
  224179. source: view
  224180. slideBack: YES];
  224181. return true;
  224182. }
  224183. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  224184. {
  224185. jassertfalse; // not implemented!
  224186. return false;
  224187. }
  224188. bool Desktop::canUseSemiTransparentWindows() throw()
  224189. {
  224190. return true;
  224191. }
  224192. const Point<int> Desktop::getMousePosition()
  224193. {
  224194. const ScopedAutoReleasePool pool;
  224195. const NSPoint p ([NSEvent mouseLocation]);
  224196. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  224197. }
  224198. void Desktop::setMousePosition (const Point<int>& newPosition)
  224199. {
  224200. // this rubbish needs to be done around the warp call, to avoid causing a
  224201. // bizarre glitch..
  224202. CGAssociateMouseAndMouseCursorPosition (false);
  224203. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  224204. CGAssociateMouseAndMouseCursorPosition (true);
  224205. }
  224206. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224207. class ScreenSaverDefeater : public Timer,
  224208. public DeletedAtShutdown
  224209. {
  224210. public:
  224211. ScreenSaverDefeater()
  224212. {
  224213. startTimer (10000);
  224214. timerCallback();
  224215. }
  224216. ~ScreenSaverDefeater() {}
  224217. void timerCallback()
  224218. {
  224219. if (Process::isForegroundProcess())
  224220. UpdateSystemActivity (UsrActivity);
  224221. }
  224222. };
  224223. static ScreenSaverDefeater* screenSaverDefeater = 0;
  224224. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224225. {
  224226. if (isEnabled)
  224227. deleteAndZero (screenSaverDefeater);
  224228. else if (screenSaverDefeater == 0)
  224229. screenSaverDefeater = new ScreenSaverDefeater();
  224230. }
  224231. bool Desktop::isScreenSaverEnabled()
  224232. {
  224233. return screenSaverDefeater == 0;
  224234. }
  224235. #else
  224236. static IOPMAssertionID screenSaverDisablerID = 0;
  224237. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224238. {
  224239. if (isEnabled)
  224240. {
  224241. if (screenSaverDisablerID != 0)
  224242. {
  224243. IOPMAssertionRelease (screenSaverDisablerID);
  224244. screenSaverDisablerID = 0;
  224245. }
  224246. }
  224247. else
  224248. {
  224249. if (screenSaverDisablerID == 0)
  224250. {
  224251. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224252. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224253. CFSTR ("Juce"), &screenSaverDisablerID);
  224254. #else
  224255. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224256. &screenSaverDisablerID);
  224257. #endif
  224258. }
  224259. }
  224260. }
  224261. bool Desktop::isScreenSaverEnabled()
  224262. {
  224263. return screenSaverDisablerID == 0;
  224264. }
  224265. #endif
  224266. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  224267. {
  224268. const ScopedAutoReleasePool pool;
  224269. monitorCoords.clear();
  224270. NSArray* screens = [NSScreen screens];
  224271. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  224272. for (unsigned int i = 0; i < [screens count]; ++i)
  224273. {
  224274. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  224275. NSRect r = clipToWorkArea ? [s visibleFrame]
  224276. : [s frame];
  224277. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224278. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  224279. (int) r.size.width,
  224280. (int) r.size.height));
  224281. }
  224282. jassert (monitorCoords.size() > 0);
  224283. }
  224284. #endif
  224285. #endif
  224286. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  224287. #endif
  224288. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  224289. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224290. // compiled on its own).
  224291. #if JUCE_INCLUDED_FILE
  224292. void Logger::outputDebugString (const String& text)
  224293. {
  224294. std::cerr << text << std::endl;
  224295. }
  224296. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  224297. {
  224298. static char testResult = 0;
  224299. if (testResult == 0)
  224300. {
  224301. struct kinfo_proc info;
  224302. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  224303. size_t sz = sizeof (info);
  224304. sysctl (m, 4, &info, &sz, 0, 0);
  224305. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  224306. }
  224307. return testResult > 0;
  224308. }
  224309. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  224310. {
  224311. return juce_isRunningUnderDebugger();
  224312. }
  224313. #endif
  224314. /*** End of inlined file: juce_mac_Debugging.mm ***/
  224315. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224316. #if JUCE_IPHONE
  224317. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  224318. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224319. // compiled on its own).
  224320. #if JUCE_INCLUDED_FILE
  224321. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224322. #define SUPPORT_10_4_FONTS 1
  224323. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  224324. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  224325. #define SUPPORT_ONLY_10_4_FONTS 1
  224326. #endif
  224327. END_JUCE_NAMESPACE
  224328. @interface NSFont (PrivateHack)
  224329. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  224330. @end
  224331. BEGIN_JUCE_NAMESPACE
  224332. #endif
  224333. class MacTypeface : public Typeface
  224334. {
  224335. public:
  224336. MacTypeface (const Font& font)
  224337. : Typeface (font.getTypefaceName())
  224338. {
  224339. const ScopedAutoReleasePool pool;
  224340. renderingTransform = CGAffineTransformIdentity;
  224341. bool needsItalicTransform = false;
  224342. #if JUCE_IPHONE
  224343. NSString* fontName = juceStringToNS (font.getTypefaceName());
  224344. if (font.isItalic() || font.isBold())
  224345. {
  224346. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  224347. for (NSString* i in familyFonts)
  224348. {
  224349. const String fn (nsStringToJuce (i));
  224350. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  224351. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  224352. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  224353. || afterDash.containsIgnoreCase ("italic")
  224354. || fn.endsWithIgnoreCase ("oblique")
  224355. || fn.endsWithIgnoreCase ("italic");
  224356. if (probablyBold == font.isBold()
  224357. && probablyItalic == font.isItalic())
  224358. {
  224359. fontName = i;
  224360. needsItalicTransform = false;
  224361. break;
  224362. }
  224363. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  224364. {
  224365. fontName = i;
  224366. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  224367. }
  224368. }
  224369. if (needsItalicTransform)
  224370. renderingTransform.c = 0.15f;
  224371. }
  224372. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  224373. const int ascender = abs (CGFontGetAscent (fontRef));
  224374. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  224375. ascent = ascender / totalHeight;
  224376. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224377. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  224378. #else
  224379. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  224380. if (font.isItalic())
  224381. {
  224382. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  224383. toHaveTrait: NSItalicFontMask];
  224384. if (newFont == nsFont)
  224385. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  224386. nsFont = newFont;
  224387. }
  224388. if (font.isBold())
  224389. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  224390. [nsFont retain];
  224391. ascent = std::abs ((float) [nsFont ascender]);
  224392. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  224393. ascent /= totalSize;
  224394. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  224395. if (needsItalicTransform)
  224396. {
  224397. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  224398. renderingTransform.c = 0.15f;
  224399. }
  224400. #if SUPPORT_ONLY_10_4_FONTS
  224401. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224402. if (atsFont == 0)
  224403. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224404. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224405. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224406. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224407. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224408. #else
  224409. #if SUPPORT_10_4_FONTS
  224410. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224411. {
  224412. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224413. if (atsFont == 0)
  224414. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224415. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224416. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224417. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224418. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224419. }
  224420. else
  224421. #endif
  224422. {
  224423. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  224424. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  224425. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224426. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  224427. }
  224428. #endif
  224429. #endif
  224430. }
  224431. ~MacTypeface()
  224432. {
  224433. #if ! JUCE_IPHONE
  224434. [nsFont release];
  224435. #endif
  224436. if (fontRef != 0)
  224437. CGFontRelease (fontRef);
  224438. }
  224439. float getAscent() const
  224440. {
  224441. return ascent;
  224442. }
  224443. float getDescent() const
  224444. {
  224445. return 1.0f - ascent;
  224446. }
  224447. float getStringWidth (const String& text)
  224448. {
  224449. if (fontRef == 0 || text.isEmpty())
  224450. return 0;
  224451. const int length = text.length();
  224452. HeapBlock <CGGlyph> glyphs;
  224453. createGlyphsForString (text, length, glyphs);
  224454. float x = 0;
  224455. #if SUPPORT_ONLY_10_4_FONTS
  224456. HeapBlock <NSSize> advances (length);
  224457. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224458. for (int i = 0; i < length; ++i)
  224459. x += advances[i].width;
  224460. #else
  224461. #if SUPPORT_10_4_FONTS
  224462. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224463. {
  224464. HeapBlock <NSSize> advances (length);
  224465. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  224466. for (int i = 0; i < length; ++i)
  224467. x += advances[i].width;
  224468. }
  224469. else
  224470. #endif
  224471. {
  224472. HeapBlock <int> advances (length);
  224473. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224474. for (int i = 0; i < length; ++i)
  224475. x += advances[i];
  224476. }
  224477. #endif
  224478. return x * unitsToHeightScaleFactor;
  224479. }
  224480. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  224481. {
  224482. xOffsets.add (0);
  224483. if (fontRef == 0 || text.isEmpty())
  224484. return;
  224485. const int length = text.length();
  224486. HeapBlock <CGGlyph> glyphs;
  224487. createGlyphsForString (text, length, glyphs);
  224488. #if SUPPORT_ONLY_10_4_FONTS
  224489. HeapBlock <NSSize> advances (length);
  224490. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224491. int x = 0;
  224492. for (int i = 0; i < length; ++i)
  224493. {
  224494. x += advances[i].width;
  224495. xOffsets.add (x * unitsToHeightScaleFactor);
  224496. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  224497. }
  224498. #else
  224499. #if SUPPORT_10_4_FONTS
  224500. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224501. {
  224502. HeapBlock <NSSize> advances (length);
  224503. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  224504. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  224505. float x = 0;
  224506. for (int i = 0; i < length; ++i)
  224507. {
  224508. x += advances[i].width;
  224509. xOffsets.add (x * unitsToHeightScaleFactor);
  224510. resultGlyphs.add (nsGlyphs[i]);
  224511. }
  224512. }
  224513. else
  224514. #endif
  224515. {
  224516. HeapBlock <int> advances (length);
  224517. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224518. {
  224519. int x = 0;
  224520. for (int i = 0; i < length; ++i)
  224521. {
  224522. x += advances [i];
  224523. xOffsets.add (x * unitsToHeightScaleFactor);
  224524. resultGlyphs.add (glyphs[i]);
  224525. }
  224526. }
  224527. }
  224528. #endif
  224529. }
  224530. bool getOutlineForGlyph (int glyphNumber, Path& path)
  224531. {
  224532. #if JUCE_IPHONE
  224533. return false;
  224534. #else
  224535. if (nsFont == 0)
  224536. return false;
  224537. // we might need to apply a transform to the path, so it mustn't have anything else in it
  224538. jassert (path.isEmpty());
  224539. const ScopedAutoReleasePool pool;
  224540. NSBezierPath* bez = [NSBezierPath bezierPath];
  224541. [bez moveToPoint: NSMakePoint (0, 0)];
  224542. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  224543. inFont: nsFont];
  224544. for (int i = 0; i < [bez elementCount]; ++i)
  224545. {
  224546. NSPoint p[3];
  224547. switch ([bez elementAtIndex: i associatedPoints: p])
  224548. {
  224549. case NSMoveToBezierPathElement:
  224550. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  224551. break;
  224552. case NSLineToBezierPathElement:
  224553. path.lineTo ((float) p[0].x, (float) -p[0].y);
  224554. break;
  224555. case NSCurveToBezierPathElement:
  224556. path.cubicTo ((float) p[0].x, (float) -p[0].y, (float) p[1].x, (float) -p[1].y, (float) p[2].x, (float) -p[2].y);
  224557. break;
  224558. case NSClosePathBezierPathElement:
  224559. path.closeSubPath();
  224560. break;
  224561. default:
  224562. jassertfalse;
  224563. break;
  224564. }
  224565. }
  224566. path.applyTransform (pathTransform);
  224567. return true;
  224568. #endif
  224569. }
  224570. juce_UseDebuggingNewOperator
  224571. CGFontRef fontRef;
  224572. float fontHeightToCGSizeFactor;
  224573. CGAffineTransform renderingTransform;
  224574. private:
  224575. float ascent, unitsToHeightScaleFactor;
  224576. #if JUCE_IPHONE
  224577. #else
  224578. NSFont* nsFont;
  224579. AffineTransform pathTransform;
  224580. #endif
  224581. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  224582. {
  224583. #if SUPPORT_10_4_FONTS
  224584. #if ! SUPPORT_ONLY_10_4_FONTS
  224585. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224586. #endif
  224587. {
  224588. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  224589. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  224590. for (int i = 0; i < length; ++i)
  224591. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  224592. return;
  224593. }
  224594. #endif
  224595. #if ! SUPPORT_ONLY_10_4_FONTS
  224596. if (charToGlyphMapper == 0)
  224597. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  224598. glyphs.malloc (length);
  224599. for (int i = 0; i < length; ++i)
  224600. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  224601. #endif
  224602. }
  224603. #if ! SUPPORT_ONLY_10_4_FONTS
  224604. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  224605. class CharToGlyphMapper
  224606. {
  224607. public:
  224608. CharToGlyphMapper (CGFontRef fontRef)
  224609. : segCount (0), endCode (0), startCode (0), idDelta (0),
  224610. idRangeOffset (0), glyphIndexes (0)
  224611. {
  224612. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  224613. if (cmapTable != 0)
  224614. {
  224615. const int numSubtables = getValue16 (cmapTable, 2);
  224616. for (int i = 0; i < numSubtables; ++i)
  224617. {
  224618. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  224619. {
  224620. const int offset = getValue32 (cmapTable, i * 8 + 8);
  224621. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  224622. {
  224623. const int length = getValue16 (cmapTable, offset + 2);
  224624. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  224625. segCount = segCountX2 / 2;
  224626. const int endCodeOffset = offset + 14;
  224627. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  224628. const int idDeltaOffset = startCodeOffset + segCountX2;
  224629. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  224630. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  224631. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  224632. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  224633. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  224634. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  224635. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  224636. }
  224637. break;
  224638. }
  224639. }
  224640. CFRelease (cmapTable);
  224641. }
  224642. }
  224643. ~CharToGlyphMapper()
  224644. {
  224645. if (endCode != 0)
  224646. {
  224647. CFRelease (endCode);
  224648. CFRelease (startCode);
  224649. CFRelease (idDelta);
  224650. CFRelease (idRangeOffset);
  224651. CFRelease (glyphIndexes);
  224652. }
  224653. }
  224654. int getGlyphForCharacter (const juce_wchar c) const
  224655. {
  224656. for (int i = 0; i < segCount; ++i)
  224657. {
  224658. if (getValue16 (endCode, i * 2) >= c)
  224659. {
  224660. const int start = getValue16 (startCode, i * 2);
  224661. if (start > c)
  224662. break;
  224663. const int delta = getValue16 (idDelta, i * 2);
  224664. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  224665. if (rangeOffset == 0)
  224666. return delta + c;
  224667. else
  224668. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  224669. }
  224670. }
  224671. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  224672. return jmax (-1, c - 29);
  224673. }
  224674. private:
  224675. int segCount;
  224676. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  224677. static uint16 getValue16 (CFDataRef data, const int index)
  224678. {
  224679. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  224680. }
  224681. static uint32 getValue32 (CFDataRef data, const int index)
  224682. {
  224683. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  224684. }
  224685. };
  224686. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  224687. #endif
  224688. MacTypeface (const MacTypeface&);
  224689. MacTypeface& operator= (const MacTypeface&);
  224690. };
  224691. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  224692. {
  224693. return new MacTypeface (font);
  224694. }
  224695. const StringArray Font::findAllTypefaceNames()
  224696. {
  224697. StringArray names;
  224698. const ScopedAutoReleasePool pool;
  224699. #if JUCE_IPHONE
  224700. NSArray* fonts = [UIFont familyNames];
  224701. #else
  224702. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  224703. #endif
  224704. for (unsigned int i = 0; i < [fonts count]; ++i)
  224705. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  224706. names.sort (true);
  224707. return names;
  224708. }
  224709. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  224710. {
  224711. #if JUCE_IPHONE
  224712. defaultSans = "Helvetica";
  224713. defaultSerif = "Times New Roman";
  224714. defaultFixed = "Courier New";
  224715. #else
  224716. defaultSans = "Lucida Grande";
  224717. defaultSerif = "Times New Roman";
  224718. defaultFixed = "Monaco";
  224719. #endif
  224720. }
  224721. #endif
  224722. /*** End of inlined file: juce_mac_Fonts.mm ***/
  224723. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  224724. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224725. // compiled on its own).
  224726. #if JUCE_INCLUDED_FILE
  224727. class CoreGraphicsImage : public Image::SharedImage
  224728. {
  224729. public:
  224730. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  224731. : Image::SharedImage (format_, width_, height_)
  224732. {
  224733. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  224734. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  224735. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  224736. imageData = imageDataAllocated;
  224737. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  224738. : CGColorSpaceCreateDeviceRGB();
  224739. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  224740. colourSpace, getCGImageFlags (format_));
  224741. CGColorSpaceRelease (colourSpace);
  224742. }
  224743. ~CoreGraphicsImage()
  224744. {
  224745. CGContextRelease (context);
  224746. }
  224747. Image::ImageType getType() const { return Image::NativeImage; }
  224748. LowLevelGraphicsContext* createLowLevelContext();
  224749. SharedImage* clone()
  224750. {
  224751. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  224752. memcpy (im->imageData, imageData, lineStride * height);
  224753. return im;
  224754. }
  224755. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  224756. {
  224757. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  224758. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  224759. {
  224760. return CGBitmapContextCreateImage (nativeImage->context);
  224761. }
  224762. else
  224763. {
  224764. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  224765. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  224766. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  224767. 8, srcData.pixelStride * 8, srcData.lineStride,
  224768. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  224769. 0, true, kCGRenderingIntentDefault);
  224770. CGDataProviderRelease (provider);
  224771. return imageRef;
  224772. }
  224773. }
  224774. #if JUCE_MAC
  224775. static NSImage* createNSImage (const Image& image)
  224776. {
  224777. const ScopedAutoReleasePool pool;
  224778. NSImage* im = [[NSImage alloc] init];
  224779. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  224780. [im lockFocus];
  224781. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  224782. CGImageRef imageRef = createImage (image, false, colourSpace);
  224783. CGColorSpaceRelease (colourSpace);
  224784. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  224785. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  224786. CGImageRelease (imageRef);
  224787. [im unlockFocus];
  224788. return im;
  224789. }
  224790. #endif
  224791. CGContextRef context;
  224792. HeapBlock<uint8> imageDataAllocated;
  224793. private:
  224794. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  224795. {
  224796. #if JUCE_BIG_ENDIAN
  224797. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  224798. #else
  224799. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  224800. #endif
  224801. }
  224802. };
  224803. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  224804. {
  224805. #if USE_COREGRAPHICS_RENDERING
  224806. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  224807. #else
  224808. return createSoftwareImage (format, width, height, clearImage);
  224809. #endif
  224810. }
  224811. class CoreGraphicsContext : public LowLevelGraphicsContext
  224812. {
  224813. public:
  224814. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  224815. : context (context_),
  224816. flipHeight (flipHeight_),
  224817. state (new SavedState()),
  224818. numGradientLookupEntries (0),
  224819. lastClipRectIsValid (false)
  224820. {
  224821. CGContextRetain (context);
  224822. CGContextSaveGState(context);
  224823. CGContextSetShouldSmoothFonts (context, true);
  224824. CGContextSetShouldAntialias (context, true);
  224825. CGContextSetBlendMode (context, kCGBlendModeNormal);
  224826. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  224827. greyColourSpace = CGColorSpaceCreateDeviceGray();
  224828. gradientCallbacks.version = 0;
  224829. gradientCallbacks.evaluate = gradientCallback;
  224830. gradientCallbacks.releaseInfo = 0;
  224831. setFont (Font());
  224832. }
  224833. ~CoreGraphicsContext()
  224834. {
  224835. CGContextRestoreGState (context);
  224836. CGContextRelease (context);
  224837. CGColorSpaceRelease (rgbColourSpace);
  224838. CGColorSpaceRelease (greyColourSpace);
  224839. }
  224840. bool isVectorDevice() const { return false; }
  224841. void setOrigin (int x, int y)
  224842. {
  224843. CGContextTranslateCTM (context, x, -y);
  224844. if (lastClipRectIsValid)
  224845. lastClipRect.translate (-x, -y);
  224846. }
  224847. bool clipToRectangle (const Rectangle<int>& r)
  224848. {
  224849. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  224850. if (lastClipRectIsValid)
  224851. {
  224852. lastClipRect = lastClipRect.getIntersection (r);
  224853. return ! lastClipRect.isEmpty();
  224854. }
  224855. return ! isClipEmpty();
  224856. }
  224857. bool clipToRectangleList (const RectangleList& clipRegion)
  224858. {
  224859. if (clipRegion.isEmpty())
  224860. {
  224861. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  224862. lastClipRectIsValid = true;
  224863. lastClipRect = Rectangle<int>();
  224864. return false;
  224865. }
  224866. else
  224867. {
  224868. const int numRects = clipRegion.getNumRectangles();
  224869. HeapBlock <CGRect> rects (numRects);
  224870. for (int i = 0; i < numRects; ++i)
  224871. {
  224872. const Rectangle<int>& r = clipRegion.getRectangle(i);
  224873. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  224874. }
  224875. CGContextClipToRects (context, rects, numRects);
  224876. lastClipRectIsValid = false;
  224877. return ! isClipEmpty();
  224878. }
  224879. }
  224880. void excludeClipRectangle (const Rectangle<int>& r)
  224881. {
  224882. RectangleList remaining (getClipBounds());
  224883. remaining.subtract (r);
  224884. clipToRectangleList (remaining);
  224885. lastClipRectIsValid = false;
  224886. }
  224887. void clipToPath (const Path& path, const AffineTransform& transform)
  224888. {
  224889. createPath (path, transform);
  224890. CGContextClip (context);
  224891. lastClipRectIsValid = false;
  224892. }
  224893. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  224894. {
  224895. if (! transform.isSingularity())
  224896. {
  224897. Image singleChannelImage (sourceImage);
  224898. if (sourceImage.getFormat() != Image::SingleChannel)
  224899. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  224900. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  224901. if (srcClip != sourceImage.getBounds())
  224902. {
  224903. CGImageRef fullImage = image;
  224904. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  224905. srcClip.getWidth(), srcClip.getHeight()));
  224906. CGImageRelease (fullImage);
  224907. }
  224908. flip();
  224909. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  224910. applyTransform (t);
  224911. CGRect r = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  224912. CGContextClipToMask (context, r, image);
  224913. applyTransform (t.inverted());
  224914. flip();
  224915. CGImageRelease (image);
  224916. lastClipRectIsValid = false;
  224917. }
  224918. }
  224919. bool clipRegionIntersects (const Rectangle<int>& r)
  224920. {
  224921. return getClipBounds().intersects (r);
  224922. }
  224923. const Rectangle<int> getClipBounds() const
  224924. {
  224925. if (! lastClipRectIsValid)
  224926. {
  224927. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  224928. lastClipRectIsValid = true;
  224929. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  224930. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  224931. roundToInt (bounds.size.width),
  224932. roundToInt (bounds.size.height));
  224933. }
  224934. return lastClipRect;
  224935. }
  224936. bool isClipEmpty() const
  224937. {
  224938. return getClipBounds().isEmpty();
  224939. }
  224940. void saveState()
  224941. {
  224942. CGContextSaveGState (context);
  224943. stateStack.add (new SavedState (*state));
  224944. }
  224945. void restoreState()
  224946. {
  224947. CGContextRestoreGState (context);
  224948. SavedState* const top = stateStack.getLast();
  224949. if (top != 0)
  224950. {
  224951. state = top;
  224952. stateStack.removeLast (1, false);
  224953. lastClipRectIsValid = false;
  224954. }
  224955. else
  224956. {
  224957. jassertfalse; // trying to pop with an empty stack!
  224958. }
  224959. }
  224960. void setFill (const FillType& fillType)
  224961. {
  224962. state->fillType = fillType;
  224963. if (fillType.isColour())
  224964. {
  224965. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  224966. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  224967. CGContextSetAlpha (context, 1.0f);
  224968. }
  224969. }
  224970. void setOpacity (float newOpacity)
  224971. {
  224972. state->fillType.setOpacity (newOpacity);
  224973. setFill (state->fillType);
  224974. }
  224975. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  224976. {
  224977. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  224978. ? kCGInterpolationLow
  224979. : kCGInterpolationHigh);
  224980. }
  224981. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  224982. {
  224983. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  224984. if (replaceExistingContents)
  224985. {
  224986. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  224987. CGContextClearRect (context, cgRect);
  224988. #else
  224989. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224990. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  224991. CGContextClearRect (context, cgRect);
  224992. else
  224993. #endif
  224994. CGContextSetBlendMode (context, kCGBlendModeCopy);
  224995. #endif
  224996. fillRect (r, false);
  224997. CGContextSetBlendMode (context, kCGBlendModeNormal);
  224998. }
  224999. else
  225000. {
  225001. if (state->fillType.isColour())
  225002. {
  225003. CGContextFillRect (context, cgRect);
  225004. }
  225005. else if (state->fillType.isGradient())
  225006. {
  225007. CGContextSaveGState (context);
  225008. CGContextClipToRect (context, cgRect);
  225009. drawGradient();
  225010. CGContextRestoreGState (context);
  225011. }
  225012. else
  225013. {
  225014. CGContextSaveGState (context);
  225015. CGContextClipToRect (context, cgRect);
  225016. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  225017. CGContextRestoreGState (context);
  225018. }
  225019. }
  225020. }
  225021. void fillPath (const Path& path, const AffineTransform& transform)
  225022. {
  225023. CGContextSaveGState (context);
  225024. if (state->fillType.isColour())
  225025. {
  225026. flip();
  225027. applyTransform (transform);
  225028. createPath (path);
  225029. if (path.isUsingNonZeroWinding())
  225030. CGContextFillPath (context);
  225031. else
  225032. CGContextEOFillPath (context);
  225033. }
  225034. else
  225035. {
  225036. createPath (path, transform);
  225037. if (path.isUsingNonZeroWinding())
  225038. CGContextClip (context);
  225039. else
  225040. CGContextEOClip (context);
  225041. if (state->fillType.isGradient())
  225042. drawGradient();
  225043. else
  225044. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  225045. }
  225046. CGContextRestoreGState (context);
  225047. }
  225048. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  225049. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  225050. {
  225051. jassert (sourceImage.getBounds().contains (srcClip));
  225052. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  225053. CGImageRef image = fullImage;
  225054. if (srcClip != sourceImage.getBounds())
  225055. {
  225056. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  225057. srcClip.getWidth(), srcClip.getHeight()));
  225058. CGImageRelease (fullImage);
  225059. }
  225060. CGContextSaveGState (context);
  225061. CGContextSetAlpha (context, state->fillType.getOpacity());
  225062. flip();
  225063. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  225064. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  225065. if (fillEntireClipAsTiles)
  225066. {
  225067. #if JUCE_IPHONE
  225068. CGContextDrawTiledImage (context, imageRect, image);
  225069. #else
  225070. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  225071. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  225072. // if it's doing a transformation - it's quicker to just draw lots of images manually
  225073. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  225074. CGContextDrawTiledImage (context, imageRect, image);
  225075. else
  225076. #endif
  225077. {
  225078. // Fallback to manually doing a tiled fill on 10.4
  225079. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225080. const int iw = srcClip.getWidth();
  225081. const int ih = srcClip.getHeight();
  225082. int x = 0, y = 0;
  225083. while (x > clip.origin.x) x -= iw;
  225084. while (y > clip.origin.y) y -= ih;
  225085. const int right = (int) (clip.origin.x + clip.size.width);
  225086. const int bottom = (int) (clip.origin.y + clip.size.height);
  225087. while (y < bottom)
  225088. {
  225089. for (int x2 = x; x2 < right; x2 += iw)
  225090. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  225091. y += ih;
  225092. }
  225093. }
  225094. #endif
  225095. }
  225096. else
  225097. {
  225098. CGContextDrawImage (context, imageRect, image);
  225099. }
  225100. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  225101. CGContextRestoreGState (context);
  225102. }
  225103. void drawLine (const Line<float>& line)
  225104. {
  225105. CGContextSetLineCap (context, kCGLineCapSquare);
  225106. CGContextSetLineWidth (context, 1.0f);
  225107. CGContextSetRGBStrokeColor (context,
  225108. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  225109. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  225110. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  225111. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  225112. CGContextStrokeLineSegments (context, cgLine, 1);
  225113. }
  225114. void drawVerticalLine (const int x, float top, float bottom)
  225115. {
  225116. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225117. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  225118. #else
  225119. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225120. // the x co-ord slightly to trick it..
  225121. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  225122. #endif
  225123. }
  225124. void drawHorizontalLine (const int y, float left, float right)
  225125. {
  225126. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225127. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  225128. #else
  225129. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225130. // the x co-ord slightly to trick it..
  225131. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  225132. #endif
  225133. }
  225134. void setFont (const Font& newFont)
  225135. {
  225136. if (state->font != newFont)
  225137. {
  225138. state->fontRef = 0;
  225139. state->font = newFont;
  225140. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  225141. if (mf != 0)
  225142. {
  225143. state->fontRef = mf->fontRef;
  225144. CGContextSetFont (context, state->fontRef);
  225145. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  225146. state->fontTransform = mf->renderingTransform;
  225147. state->fontTransform.a *= state->font.getHorizontalScale();
  225148. CGContextSetTextMatrix (context, state->fontTransform);
  225149. }
  225150. }
  225151. }
  225152. const Font getFont()
  225153. {
  225154. return state->font;
  225155. }
  225156. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  225157. {
  225158. if (state->fontRef != 0 && state->fillType.isColour())
  225159. {
  225160. if (transform.isOnlyTranslation())
  225161. {
  225162. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  225163. CGGlyph g = glyphNumber;
  225164. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  225165. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  225166. }
  225167. else
  225168. {
  225169. CGContextSaveGState (context);
  225170. flip();
  225171. applyTransform (transform);
  225172. CGAffineTransform t = state->fontTransform;
  225173. t.d = -t.d;
  225174. CGContextSetTextMatrix (context, t);
  225175. CGGlyph g = glyphNumber;
  225176. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  225177. CGContextRestoreGState (context);
  225178. }
  225179. }
  225180. else
  225181. {
  225182. Path p;
  225183. Font& f = state->font;
  225184. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  225185. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  225186. .followedBy (transform));
  225187. }
  225188. }
  225189. private:
  225190. CGContextRef context;
  225191. const CGFloat flipHeight;
  225192. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  225193. CGFunctionCallbacks gradientCallbacks;
  225194. mutable Rectangle<int> lastClipRect;
  225195. mutable bool lastClipRectIsValid;
  225196. struct SavedState
  225197. {
  225198. SavedState()
  225199. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  225200. {
  225201. }
  225202. SavedState (const SavedState& other)
  225203. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  225204. fontTransform (other.fontTransform)
  225205. {
  225206. }
  225207. ~SavedState()
  225208. {
  225209. }
  225210. FillType fillType;
  225211. Font font;
  225212. CGFontRef fontRef;
  225213. CGAffineTransform fontTransform;
  225214. };
  225215. ScopedPointer <SavedState> state;
  225216. OwnedArray <SavedState> stateStack;
  225217. HeapBlock <PixelARGB> gradientLookupTable;
  225218. int numGradientLookupEntries;
  225219. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  225220. {
  225221. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  225222. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  225223. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  225224. colour.unpremultiply();
  225225. outData[0] = colour.getRed() / 255.0f;
  225226. outData[1] = colour.getGreen() / 255.0f;
  225227. outData[2] = colour.getBlue() / 255.0f;
  225228. outData[3] = colour.getAlpha() / 255.0f;
  225229. }
  225230. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  225231. {
  225232. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  225233. --numGradientLookupEntries;
  225234. CGShadingRef result = 0;
  225235. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  225236. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  225237. if (gradient.isRadial)
  225238. {
  225239. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  225240. p1, gradient.point1.getDistanceFrom (gradient.point2),
  225241. function, true, true);
  225242. }
  225243. else
  225244. {
  225245. result = CGShadingCreateAxial (rgbColourSpace, p1,
  225246. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  225247. function, true, true);
  225248. }
  225249. CGFunctionRelease (function);
  225250. return result;
  225251. }
  225252. void drawGradient()
  225253. {
  225254. flip();
  225255. applyTransform (state->fillType.transform);
  225256. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  225257. // you draw a gradient with high quality interp enabled).
  225258. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  225259. CGContextSetAlpha (context, state->fillType.getOpacity());
  225260. CGContextDrawShading (context, shading);
  225261. CGShadingRelease (shading);
  225262. }
  225263. void createPath (const Path& path) const
  225264. {
  225265. CGContextBeginPath (context);
  225266. Path::Iterator i (path);
  225267. while (i.next())
  225268. {
  225269. switch (i.elementType)
  225270. {
  225271. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  225272. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  225273. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  225274. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  225275. case Path::Iterator::closePath: CGContextClosePath (context); break;
  225276. default: jassertfalse; break;
  225277. }
  225278. }
  225279. }
  225280. void createPath (const Path& path, const AffineTransform& transform) const
  225281. {
  225282. CGContextBeginPath (context);
  225283. Path::Iterator i (path);
  225284. while (i.next())
  225285. {
  225286. switch (i.elementType)
  225287. {
  225288. case Path::Iterator::startNewSubPath:
  225289. transform.transformPoint (i.x1, i.y1);
  225290. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  225291. break;
  225292. case Path::Iterator::lineTo:
  225293. transform.transformPoint (i.x1, i.y1);
  225294. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  225295. break;
  225296. case Path::Iterator::quadraticTo:
  225297. transform.transformPoint (i.x1, i.y1);
  225298. transform.transformPoint (i.x2, i.y2);
  225299. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  225300. break;
  225301. case Path::Iterator::cubicTo:
  225302. transform.transformPoint (i.x1, i.y1);
  225303. transform.transformPoint (i.x2, i.y2);
  225304. transform.transformPoint (i.x3, i.y3);
  225305. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  225306. break;
  225307. case Path::Iterator::closePath:
  225308. CGContextClosePath (context); break;
  225309. default:
  225310. jassertfalse;
  225311. break;
  225312. }
  225313. }
  225314. }
  225315. void flip() const
  225316. {
  225317. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  225318. }
  225319. void applyTransform (const AffineTransform& transform) const
  225320. {
  225321. CGAffineTransform t;
  225322. t.a = transform.mat00;
  225323. t.b = transform.mat10;
  225324. t.c = transform.mat01;
  225325. t.d = transform.mat11;
  225326. t.tx = transform.mat02;
  225327. t.ty = transform.mat12;
  225328. CGContextConcatCTM (context, t);
  225329. }
  225330. CoreGraphicsContext (const CoreGraphicsContext&);
  225331. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  225332. };
  225333. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  225334. {
  225335. return new CoreGraphicsContext (context, height);
  225336. }
  225337. #endif
  225338. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225339. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  225340. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225341. // compiled on its own).
  225342. #if JUCE_INCLUDED_FILE
  225343. class UIViewComponentPeer;
  225344. END_JUCE_NAMESPACE
  225345. #define JuceUIView MakeObjCClassName(JuceUIView)
  225346. @interface JuceUIView : UIView <UITextFieldDelegate>
  225347. {
  225348. @public
  225349. UIViewComponentPeer* owner;
  225350. UITextField *hiddenTextField;
  225351. }
  225352. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  225353. - (void) dealloc;
  225354. - (void) drawRect: (CGRect) r;
  225355. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  225356. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  225357. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  225358. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  225359. - (BOOL) becomeFirstResponder;
  225360. - (BOOL) resignFirstResponder;
  225361. - (BOOL) canBecomeFirstResponder;
  225362. - (void) asyncRepaint: (id) rect;
  225363. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  225364. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  225365. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  225366. @end
  225367. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  225368. @interface JuceUIWindow : UIWindow
  225369. {
  225370. @private
  225371. UIViewComponentPeer* owner;
  225372. bool isZooming;
  225373. }
  225374. - (void) setOwner: (UIViewComponentPeer*) owner;
  225375. - (void) becomeKeyWindow;
  225376. @end
  225377. BEGIN_JUCE_NAMESPACE
  225378. class UIViewComponentPeer : public ComponentPeer,
  225379. public FocusChangeListener
  225380. {
  225381. public:
  225382. UIViewComponentPeer (Component* const component,
  225383. const int windowStyleFlags,
  225384. UIView* viewToAttachTo);
  225385. ~UIViewComponentPeer();
  225386. void* getNativeHandle() const;
  225387. void setVisible (bool shouldBeVisible);
  225388. void setTitle (const String& title);
  225389. void setPosition (int x, int y);
  225390. void setSize (int w, int h);
  225391. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  225392. const Rectangle<int> getBounds() const;
  225393. const Rectangle<int> getBounds (const bool global) const;
  225394. const Point<int> getScreenPosition() const;
  225395. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  225396. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  225397. void setMinimised (bool shouldBeMinimised);
  225398. bool isMinimised() const;
  225399. void setFullScreen (bool shouldBeFullScreen);
  225400. bool isFullScreen() const;
  225401. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  225402. const BorderSize getFrameSize() const;
  225403. bool setAlwaysOnTop (bool alwaysOnTop);
  225404. void toFront (bool makeActiveWindow);
  225405. void toBehind (ComponentPeer* other);
  225406. void setIcon (const Image& newIcon);
  225407. virtual void drawRect (CGRect r);
  225408. virtual bool canBecomeKeyWindow();
  225409. virtual bool windowShouldClose();
  225410. virtual void redirectMovedOrResized();
  225411. virtual CGRect constrainRect (CGRect r);
  225412. virtual void viewFocusGain();
  225413. virtual void viewFocusLoss();
  225414. bool isFocused() const;
  225415. void grabFocus();
  225416. void textInputRequired (const Point<int>& position);
  225417. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  225418. virtual BOOL textFieldShouldClear();
  225419. virtual BOOL textFieldShouldReturn();
  225420. void updateHiddenTextContent (TextInputTarget* target);
  225421. void globalFocusChanged (Component*);
  225422. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  225423. void repaint (const Rectangle<int>& area);
  225424. void performAnyPendingRepaintsNow();
  225425. juce_UseDebuggingNewOperator
  225426. UIWindow* window;
  225427. JuceUIView* view;
  225428. bool isSharedWindow, fullScreen, insideDrawRect;
  225429. static ModifierKeys currentModifiers;
  225430. static int64 getMouseTime (UIEvent* e)
  225431. {
  225432. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  225433. + (int64) ([e timestamp] * 1000.0);
  225434. }
  225435. Array <UITouch*> currentTouches;
  225436. };
  225437. END_JUCE_NAMESPACE
  225438. @implementation JuceUIView
  225439. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  225440. withFrame: (CGRect) frame
  225441. {
  225442. [super initWithFrame: frame];
  225443. owner = owner_;
  225444. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  225445. [self addSubview: hiddenTextField];
  225446. hiddenTextField.delegate = self;
  225447. return self;
  225448. }
  225449. - (void) dealloc
  225450. {
  225451. [hiddenTextField removeFromSuperview];
  225452. [hiddenTextField release];
  225453. [super dealloc];
  225454. }
  225455. - (void) drawRect: (CGRect) r
  225456. {
  225457. if (owner != 0)
  225458. owner->drawRect (r);
  225459. }
  225460. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  225461. {
  225462. return false;
  225463. }
  225464. ModifierKeys UIViewComponentPeer::currentModifiers;
  225465. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  225466. {
  225467. return UIViewComponentPeer::currentModifiers;
  225468. }
  225469. void ModifierKeys::updateCurrentModifiers() throw()
  225470. {
  225471. currentModifiers = UIViewComponentPeer::currentModifiers;
  225472. }
  225473. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  225474. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  225475. {
  225476. if (owner != 0)
  225477. owner->handleTouches (event, true, false, false);
  225478. }
  225479. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  225480. {
  225481. if (owner != 0)
  225482. owner->handleTouches (event, false, false, false);
  225483. }
  225484. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  225485. {
  225486. if (owner != 0)
  225487. owner->handleTouches (event, false, true, false);
  225488. }
  225489. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  225490. {
  225491. if (owner != 0)
  225492. owner->handleTouches (event, false, true, true);
  225493. [self touchesEnded: touches withEvent: event];
  225494. }
  225495. - (BOOL) becomeFirstResponder
  225496. {
  225497. if (owner != 0)
  225498. owner->viewFocusGain();
  225499. return true;
  225500. }
  225501. - (BOOL) resignFirstResponder
  225502. {
  225503. if (owner != 0)
  225504. owner->viewFocusLoss();
  225505. return true;
  225506. }
  225507. - (BOOL) canBecomeFirstResponder
  225508. {
  225509. return owner != 0 && owner->canBecomeKeyWindow();
  225510. }
  225511. - (void) asyncRepaint: (id) rect
  225512. {
  225513. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  225514. [self setNeedsDisplayInRect: *r];
  225515. }
  225516. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  225517. {
  225518. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  225519. nsStringToJuce (text));
  225520. }
  225521. - (BOOL) textFieldShouldClear: (UITextField*) textField
  225522. {
  225523. return owner->textFieldShouldClear();
  225524. }
  225525. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  225526. {
  225527. return owner->textFieldShouldReturn();
  225528. }
  225529. @end
  225530. @implementation JuceUIWindow
  225531. - (void) setOwner: (UIViewComponentPeer*) owner_
  225532. {
  225533. owner = owner_;
  225534. isZooming = false;
  225535. }
  225536. - (void) becomeKeyWindow
  225537. {
  225538. [super becomeKeyWindow];
  225539. if (owner != 0)
  225540. owner->grabFocus();
  225541. }
  225542. @end
  225543. BEGIN_JUCE_NAMESPACE
  225544. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  225545. const int windowStyleFlags,
  225546. UIView* viewToAttachTo)
  225547. : ComponentPeer (component, windowStyleFlags),
  225548. window (0),
  225549. view (0),
  225550. isSharedWindow (viewToAttachTo != 0),
  225551. fullScreen (false),
  225552. insideDrawRect (false)
  225553. {
  225554. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  225555. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  225556. if (isSharedWindow)
  225557. {
  225558. window = [viewToAttachTo window];
  225559. [viewToAttachTo addSubview: view];
  225560. setVisible (component->isVisible());
  225561. }
  225562. else
  225563. {
  225564. r.origin.x = (float) component->getX();
  225565. r.origin.y = (float) component->getY();
  225566. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  225567. window = [[JuceUIWindow alloc] init];
  225568. window.frame = r;
  225569. window.opaque = component->isOpaque();
  225570. view.opaque = component->isOpaque();
  225571. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  225572. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  225573. [((JuceUIWindow*) window) setOwner: this];
  225574. if (component->isAlwaysOnTop())
  225575. window.windowLevel = UIWindowLevelAlert;
  225576. [window addSubview: view];
  225577. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  225578. view.hidden = ! component->isVisible();
  225579. window.hidden = ! component->isVisible();
  225580. view.multipleTouchEnabled = YES;
  225581. }
  225582. setTitle (component->getName());
  225583. Desktop::getInstance().addFocusChangeListener (this);
  225584. }
  225585. UIViewComponentPeer::~UIViewComponentPeer()
  225586. {
  225587. Desktop::getInstance().removeFocusChangeListener (this);
  225588. view->owner = 0;
  225589. [view removeFromSuperview];
  225590. [view release];
  225591. if (! isSharedWindow)
  225592. {
  225593. [((JuceUIWindow*) window) setOwner: 0];
  225594. [window release];
  225595. }
  225596. }
  225597. void* UIViewComponentPeer::getNativeHandle() const
  225598. {
  225599. return view;
  225600. }
  225601. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  225602. {
  225603. view.hidden = ! shouldBeVisible;
  225604. if (! isSharedWindow)
  225605. window.hidden = ! shouldBeVisible;
  225606. }
  225607. void UIViewComponentPeer::setTitle (const String& title)
  225608. {
  225609. // xxx is this possible?
  225610. }
  225611. void UIViewComponentPeer::setPosition (int x, int y)
  225612. {
  225613. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  225614. }
  225615. void UIViewComponentPeer::setSize (int w, int h)
  225616. {
  225617. setBounds (component->getX(), component->getY(), w, h, false);
  225618. }
  225619. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  225620. {
  225621. fullScreen = isNowFullScreen;
  225622. w = jmax (0, w);
  225623. h = jmax (0, h);
  225624. CGRect r;
  225625. r.origin.x = (float) x;
  225626. r.origin.y = (float) y;
  225627. r.size.width = (float) w;
  225628. r.size.height = (float) h;
  225629. if (isSharedWindow)
  225630. {
  225631. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  225632. if ([view frame].size.width != r.size.width
  225633. || [view frame].size.height != r.size.height)
  225634. [view setNeedsDisplay];
  225635. view.frame = r;
  225636. }
  225637. else
  225638. {
  225639. window.frame = r;
  225640. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  225641. }
  225642. }
  225643. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  225644. {
  225645. CGRect r = [view frame];
  225646. if (global && [view window] != 0)
  225647. {
  225648. r = [view convertRect: r toView: nil];
  225649. CGRect wr = [[view window] frame];
  225650. r.origin.x += wr.origin.x;
  225651. r.origin.y += wr.origin.y;
  225652. }
  225653. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  225654. (int) r.size.width, (int) r.size.height);
  225655. }
  225656. const Rectangle<int> UIViewComponentPeer::getBounds() const
  225657. {
  225658. return getBounds (! isSharedWindow);
  225659. }
  225660. const Point<int> UIViewComponentPeer::getScreenPosition() const
  225661. {
  225662. return getBounds (true).getPosition();
  225663. }
  225664. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  225665. {
  225666. return relativePosition + getScreenPosition();
  225667. }
  225668. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  225669. {
  225670. return screenPosition - getScreenPosition();
  225671. }
  225672. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  225673. {
  225674. if (constrainer != 0)
  225675. {
  225676. CGRect current = [window frame];
  225677. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  225678. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  225679. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  225680. (int) r.size.width, (int) r.size.height);
  225681. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  225682. (int) current.size.width, (int) current.size.height);
  225683. constrainer->checkBounds (pos, original,
  225684. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  225685. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  225686. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  225687. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  225688. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  225689. r.origin.x = pos.getX();
  225690. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  225691. r.size.width = pos.getWidth();
  225692. r.size.height = pos.getHeight();
  225693. }
  225694. return r;
  225695. }
  225696. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  225697. {
  225698. // xxx
  225699. }
  225700. bool UIViewComponentPeer::isMinimised() const
  225701. {
  225702. return false;
  225703. }
  225704. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  225705. {
  225706. if (! isSharedWindow)
  225707. {
  225708. Rectangle<int> r (lastNonFullscreenBounds);
  225709. setMinimised (false);
  225710. if (fullScreen != shouldBeFullScreen)
  225711. {
  225712. if (shouldBeFullScreen)
  225713. r = Desktop::getInstance().getMainMonitorArea();
  225714. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  225715. if (r != getComponent()->getBounds() && ! r.isEmpty())
  225716. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  225717. }
  225718. }
  225719. }
  225720. bool UIViewComponentPeer::isFullScreen() const
  225721. {
  225722. return fullScreen;
  225723. }
  225724. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  225725. {
  225726. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  225727. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  225728. return false;
  225729. CGPoint p;
  225730. p.x = (float) position.getX();
  225731. p.y = (float) position.getY();
  225732. UIView* v = [view hitTest: p withEvent: nil];
  225733. if (trueIfInAChildWindow)
  225734. return v != nil;
  225735. return v == view;
  225736. }
  225737. const BorderSize UIViewComponentPeer::getFrameSize() const
  225738. {
  225739. BorderSize b;
  225740. if (! isSharedWindow)
  225741. {
  225742. CGRect v = [view convertRect: [view frame] toView: nil];
  225743. CGRect w = [window frame];
  225744. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  225745. b.setBottom ((int) v.origin.y);
  225746. b.setLeft ((int) v.origin.x);
  225747. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  225748. }
  225749. return b;
  225750. }
  225751. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  225752. {
  225753. if (! isSharedWindow)
  225754. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  225755. return true;
  225756. }
  225757. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  225758. {
  225759. if (isSharedWindow)
  225760. [[view superview] bringSubviewToFront: view];
  225761. if (window != 0 && component->isVisible())
  225762. [window makeKeyAndVisible];
  225763. }
  225764. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  225765. {
  225766. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  225767. jassert (otherPeer != 0); // wrong type of window?
  225768. if (otherPeer != 0)
  225769. {
  225770. if (isSharedWindow)
  225771. {
  225772. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  225773. }
  225774. else
  225775. {
  225776. jassertfalse; // don't know how to do this
  225777. }
  225778. }
  225779. }
  225780. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  225781. {
  225782. // to do..
  225783. }
  225784. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  225785. {
  225786. NSArray* touches = [[event touchesForView: view] allObjects];
  225787. for (unsigned int i = 0; i < [touches count]; ++i)
  225788. {
  225789. UITouch* touch = [touches objectAtIndex: i];
  225790. CGPoint p = [touch locationInView: view];
  225791. const Point<int> pos ((int) p.x, (int) p.y);
  225792. juce_lastMousePos = pos + getScreenPosition();
  225793. const int64 time = getMouseTime (event);
  225794. int touchIndex = currentTouches.indexOf (touch);
  225795. if (touchIndex < 0)
  225796. {
  225797. touchIndex = currentTouches.size();
  225798. currentTouches.add (touch);
  225799. }
  225800. if (isDown)
  225801. {
  225802. currentModifiers = currentModifiers.withoutMouseButtons();
  225803. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  225804. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  225805. }
  225806. else if (isUp)
  225807. {
  225808. currentModifiers = currentModifiers.withoutMouseButtons();
  225809. currentTouches.remove (touchIndex);
  225810. }
  225811. if (isCancel)
  225812. currentTouches.clear();
  225813. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  225814. }
  225815. }
  225816. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  225817. void UIViewComponentPeer::viewFocusGain()
  225818. {
  225819. if (currentlyFocusedPeer != this)
  225820. {
  225821. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  225822. currentlyFocusedPeer->handleFocusLoss();
  225823. currentlyFocusedPeer = this;
  225824. handleFocusGain();
  225825. }
  225826. }
  225827. void UIViewComponentPeer::viewFocusLoss()
  225828. {
  225829. if (currentlyFocusedPeer == this)
  225830. {
  225831. currentlyFocusedPeer = 0;
  225832. handleFocusLoss();
  225833. }
  225834. }
  225835. void juce_HandleProcessFocusChange()
  225836. {
  225837. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  225838. {
  225839. if (Process::isForegroundProcess())
  225840. {
  225841. currentlyFocusedPeer->handleFocusGain();
  225842. ComponentPeer::bringModalComponentToFront();
  225843. }
  225844. else
  225845. {
  225846. currentlyFocusedPeer->handleFocusLoss();
  225847. // turn kiosk mode off if we lose focus..
  225848. Desktop::getInstance().setKioskModeComponent (0);
  225849. }
  225850. }
  225851. }
  225852. bool UIViewComponentPeer::isFocused() const
  225853. {
  225854. return isSharedWindow ? this == currentlyFocusedPeer
  225855. : (window != 0 && [window isKeyWindow]);
  225856. }
  225857. void UIViewComponentPeer::grabFocus()
  225858. {
  225859. if (window != 0)
  225860. {
  225861. [window makeKeyWindow];
  225862. viewFocusGain();
  225863. }
  225864. }
  225865. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  225866. {
  225867. }
  225868. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  225869. {
  225870. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  225871. }
  225872. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  225873. {
  225874. TextInputTarget* const target = findCurrentTextInputTarget();
  225875. if (target != 0)
  225876. {
  225877. const Range<int> currentSelection (target->getHighlightedRegion());
  225878. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  225879. if (currentSelection.isEmpty())
  225880. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  225881. target->insertTextAtCaret (text);
  225882. updateHiddenTextContent (target);
  225883. }
  225884. return NO;
  225885. }
  225886. BOOL UIViewComponentPeer::textFieldShouldClear()
  225887. {
  225888. TextInputTarget* const target = findCurrentTextInputTarget();
  225889. if (target != 0)
  225890. {
  225891. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  225892. target->insertTextAtCaret (String::empty);
  225893. updateHiddenTextContent (target);
  225894. }
  225895. return YES;
  225896. }
  225897. BOOL UIViewComponentPeer::textFieldShouldReturn()
  225898. {
  225899. TextInputTarget* const target = findCurrentTextInputTarget();
  225900. if (target != 0)
  225901. {
  225902. target->insertTextAtCaret ("\n");
  225903. updateHiddenTextContent (target);
  225904. }
  225905. return YES;
  225906. }
  225907. void UIViewComponentPeer::globalFocusChanged (Component*)
  225908. {
  225909. TextInputTarget* const target = findCurrentTextInputTarget();
  225910. if (target != 0)
  225911. {
  225912. Component* comp = dynamic_cast<Component*> (target);
  225913. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  225914. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  225915. updateHiddenTextContent (target);
  225916. [view->hiddenTextField becomeFirstResponder];
  225917. }
  225918. else
  225919. {
  225920. [view->hiddenTextField resignFirstResponder];
  225921. }
  225922. }
  225923. void UIViewComponentPeer::drawRect (CGRect r)
  225924. {
  225925. if (r.size.width < 1.0f || r.size.height < 1.0f)
  225926. return;
  225927. CGContextRef cg = UIGraphicsGetCurrentContext();
  225928. if (! component->isOpaque())
  225929. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  225930. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  225931. CoreGraphicsContext g (cg, view.bounds.size.height);
  225932. insideDrawRect = true;
  225933. handlePaint (g);
  225934. insideDrawRect = false;
  225935. }
  225936. bool UIViewComponentPeer::canBecomeKeyWindow()
  225937. {
  225938. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  225939. }
  225940. bool UIViewComponentPeer::windowShouldClose()
  225941. {
  225942. if (! isValidPeer (this))
  225943. return YES;
  225944. handleUserClosingWindow();
  225945. return NO;
  225946. }
  225947. void UIViewComponentPeer::redirectMovedOrResized()
  225948. {
  225949. handleMovedOrResized();
  225950. }
  225951. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  225952. {
  225953. }
  225954. class AsyncRepaintMessage : public CallbackMessage
  225955. {
  225956. public:
  225957. UIViewComponentPeer* const peer;
  225958. const Rectangle<int> rect;
  225959. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  225960. : peer (peer_), rect (rect_)
  225961. {
  225962. }
  225963. void messageCallback()
  225964. {
  225965. if (ComponentPeer::isValidPeer (peer))
  225966. peer->repaint (rect);
  225967. }
  225968. };
  225969. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  225970. {
  225971. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  225972. {
  225973. (new AsyncRepaintMessage (this, area))->post();
  225974. }
  225975. else
  225976. {
  225977. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  225978. (float) area.getWidth(), (float) area.getHeight())];
  225979. }
  225980. }
  225981. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  225982. {
  225983. }
  225984. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  225985. {
  225986. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  225987. }
  225988. const Image juce_createIconForFile (const File& file)
  225989. {
  225990. return Image();
  225991. }
  225992. void Desktop::createMouseInputSources()
  225993. {
  225994. for (int i = 0; i < 10; ++i)
  225995. mouseSources.add (new MouseInputSource (i, false));
  225996. }
  225997. bool Desktop::canUseSemiTransparentWindows() throw()
  225998. {
  225999. return true;
  226000. }
  226001. const Point<int> Desktop::getMousePosition()
  226002. {
  226003. return juce_lastMousePos;
  226004. }
  226005. void Desktop::setMousePosition (const Point<int>&)
  226006. {
  226007. }
  226008. const int KeyPress::spaceKey = ' ';
  226009. const int KeyPress::returnKey = 0x0d;
  226010. const int KeyPress::escapeKey = 0x1b;
  226011. const int KeyPress::backspaceKey = 0x7f;
  226012. const int KeyPress::leftKey = 0x1000;
  226013. const int KeyPress::rightKey = 0x1001;
  226014. const int KeyPress::upKey = 0x1002;
  226015. const int KeyPress::downKey = 0x1003;
  226016. const int KeyPress::pageUpKey = 0x1004;
  226017. const int KeyPress::pageDownKey = 0x1005;
  226018. const int KeyPress::endKey = 0x1006;
  226019. const int KeyPress::homeKey = 0x1007;
  226020. const int KeyPress::deleteKey = 0x1008;
  226021. const int KeyPress::insertKey = -1;
  226022. const int KeyPress::tabKey = 9;
  226023. const int KeyPress::F1Key = 0x2001;
  226024. const int KeyPress::F2Key = 0x2002;
  226025. const int KeyPress::F3Key = 0x2003;
  226026. const int KeyPress::F4Key = 0x2004;
  226027. const int KeyPress::F5Key = 0x2005;
  226028. const int KeyPress::F6Key = 0x2006;
  226029. const int KeyPress::F7Key = 0x2007;
  226030. const int KeyPress::F8Key = 0x2008;
  226031. const int KeyPress::F9Key = 0x2009;
  226032. const int KeyPress::F10Key = 0x200a;
  226033. const int KeyPress::F11Key = 0x200b;
  226034. const int KeyPress::F12Key = 0x200c;
  226035. const int KeyPress::F13Key = 0x200d;
  226036. const int KeyPress::F14Key = 0x200e;
  226037. const int KeyPress::F15Key = 0x200f;
  226038. const int KeyPress::F16Key = 0x2010;
  226039. const int KeyPress::numberPad0 = 0x30020;
  226040. const int KeyPress::numberPad1 = 0x30021;
  226041. const int KeyPress::numberPad2 = 0x30022;
  226042. const int KeyPress::numberPad3 = 0x30023;
  226043. const int KeyPress::numberPad4 = 0x30024;
  226044. const int KeyPress::numberPad5 = 0x30025;
  226045. const int KeyPress::numberPad6 = 0x30026;
  226046. const int KeyPress::numberPad7 = 0x30027;
  226047. const int KeyPress::numberPad8 = 0x30028;
  226048. const int KeyPress::numberPad9 = 0x30029;
  226049. const int KeyPress::numberPadAdd = 0x3002a;
  226050. const int KeyPress::numberPadSubtract = 0x3002b;
  226051. const int KeyPress::numberPadMultiply = 0x3002c;
  226052. const int KeyPress::numberPadDivide = 0x3002d;
  226053. const int KeyPress::numberPadSeparator = 0x3002e;
  226054. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  226055. const int KeyPress::numberPadEquals = 0x30030;
  226056. const int KeyPress::numberPadDelete = 0x30031;
  226057. const int KeyPress::playKey = 0x30000;
  226058. const int KeyPress::stopKey = 0x30001;
  226059. const int KeyPress::fastForwardKey = 0x30002;
  226060. const int KeyPress::rewindKey = 0x30003;
  226061. #endif
  226062. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226063. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  226064. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226065. // compiled on its own).
  226066. #if JUCE_INCLUDED_FILE
  226067. struct CallbackMessagePayload
  226068. {
  226069. MessageCallbackFunction* function;
  226070. void* parameter;
  226071. void* volatile result;
  226072. bool volatile hasBeenExecuted;
  226073. };
  226074. END_JUCE_NAMESPACE
  226075. @interface JuceCustomMessageHandler : NSObject
  226076. {
  226077. }
  226078. - (void) performCallback: (id) info;
  226079. @end
  226080. @implementation JuceCustomMessageHandler
  226081. - (void) performCallback: (id) info
  226082. {
  226083. if ([info isKindOfClass: [NSData class]])
  226084. {
  226085. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  226086. if (pl != 0)
  226087. {
  226088. pl->result = (*pl->function) (pl->parameter);
  226089. pl->hasBeenExecuted = true;
  226090. }
  226091. }
  226092. else
  226093. {
  226094. jassertfalse; // should never get here!
  226095. }
  226096. }
  226097. @end
  226098. BEGIN_JUCE_NAMESPACE
  226099. void MessageManager::runDispatchLoop()
  226100. {
  226101. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226102. runDispatchLoopUntil (-1);
  226103. }
  226104. void MessageManager::stopDispatchLoop()
  226105. {
  226106. exit (0); // iPhone apps get no mercy..
  226107. }
  226108. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  226109. {
  226110. const ScopedAutoReleasePool pool;
  226111. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226112. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  226113. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  226114. while (! quitMessagePosted)
  226115. {
  226116. const ScopedAutoReleasePool pool;
  226117. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  226118. beforeDate: endDate];
  226119. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  226120. break;
  226121. }
  226122. return ! quitMessagePosted;
  226123. }
  226124. static CFRunLoopRef runLoop = 0;
  226125. static CFRunLoopSourceRef runLoopSource = 0;
  226126. static Array <void*, CriticalSection>* pendingMessages = 0;
  226127. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  226128. static void runLoopSourceCallback (void*)
  226129. {
  226130. if (pendingMessages != 0)
  226131. {
  226132. int numDispatched = 0;
  226133. do
  226134. {
  226135. void* const nextMessage = pendingMessages->remove (0);
  226136. if (nextMessage == 0)
  226137. return;
  226138. const ScopedAutoReleasePool pool;
  226139. MessageManager::getInstance()->deliverMessage (nextMessage);
  226140. } while (++numDispatched <= 4);
  226141. CFRunLoopSourceSignal (runLoopSource);
  226142. CFRunLoopWakeUp (runLoop);
  226143. }
  226144. }
  226145. void MessageManager::doPlatformSpecificInitialisation()
  226146. {
  226147. pendingMessages = new Array <void*, CriticalSection>();
  226148. runLoop = CFRunLoopGetCurrent();
  226149. CFRunLoopSourceContext sourceContext;
  226150. zerostruct (sourceContext);
  226151. sourceContext.perform = runLoopSourceCallback;
  226152. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  226153. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  226154. if (juceCustomMessageHandler == 0)
  226155. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  226156. }
  226157. void MessageManager::doPlatformSpecificShutdown()
  226158. {
  226159. CFRunLoopSourceInvalidate (runLoopSource);
  226160. CFRelease (runLoopSource);
  226161. runLoopSource = 0;
  226162. if (pendingMessages != 0)
  226163. {
  226164. while (pendingMessages->size() > 0)
  226165. delete ((Message*) pendingMessages->remove(0));
  226166. deleteAndZero (pendingMessages);
  226167. }
  226168. if (juceCustomMessageHandler != 0)
  226169. {
  226170. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  226171. [juceCustomMessageHandler release];
  226172. juceCustomMessageHandler = 0;
  226173. }
  226174. }
  226175. bool juce_postMessageToSystemQueue (void* message)
  226176. {
  226177. if (pendingMessages != 0)
  226178. {
  226179. pendingMessages->add (message);
  226180. CFRunLoopSourceSignal (runLoopSource);
  226181. CFRunLoopWakeUp (runLoop);
  226182. }
  226183. return true;
  226184. }
  226185. void MessageManager::broadcastMessage (const String& value) throw()
  226186. {
  226187. }
  226188. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  226189. void* data)
  226190. {
  226191. if (isThisTheMessageThread())
  226192. {
  226193. return (*callback) (data);
  226194. }
  226195. else
  226196. {
  226197. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  226198. // deadlock because the message manager is blocked from running, so can never
  226199. // call your function..
  226200. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  226201. const ScopedAutoReleasePool pool;
  226202. CallbackMessagePayload cmp;
  226203. cmp.function = callback;
  226204. cmp.parameter = data;
  226205. cmp.result = 0;
  226206. cmp.hasBeenExecuted = false;
  226207. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  226208. withObject: [NSData dataWithBytesNoCopy: &cmp
  226209. length: sizeof (cmp)
  226210. freeWhenDone: NO]
  226211. waitUntilDone: YES];
  226212. return cmp.result;
  226213. }
  226214. }
  226215. #endif
  226216. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  226217. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  226218. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226219. // compiled on its own).
  226220. #if JUCE_INCLUDED_FILE
  226221. #if JUCE_MAC
  226222. END_JUCE_NAMESPACE
  226223. using namespace JUCE_NAMESPACE;
  226224. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  226225. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226226. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  226227. #else
  226228. @interface JuceFileChooserDelegate : NSObject
  226229. #endif
  226230. {
  226231. StringArray* filters;
  226232. }
  226233. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  226234. - (void) dealloc;
  226235. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  226236. @end
  226237. @implementation JuceFileChooserDelegate
  226238. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  226239. {
  226240. [super init];
  226241. filters = filters_;
  226242. return self;
  226243. }
  226244. - (void) dealloc
  226245. {
  226246. delete filters;
  226247. [super dealloc];
  226248. }
  226249. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  226250. {
  226251. (void) sender;
  226252. const File f (nsStringToJuce (filename));
  226253. for (int i = filters->size(); --i >= 0;)
  226254. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  226255. return true;
  226256. return f.isDirectory();
  226257. }
  226258. @end
  226259. BEGIN_JUCE_NAMESPACE
  226260. void FileChooser::showPlatformDialog (Array<File>& results,
  226261. const String& title,
  226262. const File& currentFileOrDirectory,
  226263. const String& filter,
  226264. bool selectsDirectory,
  226265. bool selectsFiles,
  226266. bool isSaveDialogue,
  226267. bool warnAboutOverwritingExistingFiles,
  226268. bool selectMultipleFiles,
  226269. FilePreviewComponent* extraInfoComponent)
  226270. {
  226271. const ScopedAutoReleasePool pool;
  226272. StringArray* filters = new StringArray();
  226273. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  226274. filters->trim();
  226275. filters->removeEmptyStrings();
  226276. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  226277. [delegate autorelease];
  226278. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  226279. : [NSOpenPanel openPanel];
  226280. [panel setTitle: juceStringToNS (title)];
  226281. if (! isSaveDialogue)
  226282. {
  226283. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226284. [openPanel setCanChooseDirectories: selectsDirectory];
  226285. [openPanel setCanChooseFiles: selectsFiles];
  226286. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  226287. }
  226288. [panel setDelegate: delegate];
  226289. if (isSaveDialogue || selectsDirectory)
  226290. [panel setCanCreateDirectories: YES];
  226291. String directory, filename;
  226292. if (currentFileOrDirectory.isDirectory())
  226293. {
  226294. directory = currentFileOrDirectory.getFullPathName();
  226295. }
  226296. else
  226297. {
  226298. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  226299. filename = currentFileOrDirectory.getFileName();
  226300. }
  226301. if ([panel runModalForDirectory: juceStringToNS (directory)
  226302. file: juceStringToNS (filename)]
  226303. == NSOKButton)
  226304. {
  226305. if (isSaveDialogue)
  226306. {
  226307. results.add (File (nsStringToJuce ([panel filename])));
  226308. }
  226309. else
  226310. {
  226311. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226312. NSArray* urls = [openPanel filenames];
  226313. for (unsigned int i = 0; i < [urls count]; ++i)
  226314. {
  226315. NSString* f = [urls objectAtIndex: i];
  226316. results.add (File (nsStringToJuce (f)));
  226317. }
  226318. }
  226319. }
  226320. [panel setDelegate: nil];
  226321. }
  226322. #else
  226323. void FileChooser::showPlatformDialog (Array<File>& results,
  226324. const String& title,
  226325. const File& currentFileOrDirectory,
  226326. const String& filter,
  226327. bool selectsDirectory,
  226328. bool selectsFiles,
  226329. bool isSaveDialogue,
  226330. bool warnAboutOverwritingExistingFiles,
  226331. bool selectMultipleFiles,
  226332. FilePreviewComponent* extraInfoComponent)
  226333. {
  226334. const ScopedAutoReleasePool pool;
  226335. jassertfalse; //xxx to do
  226336. }
  226337. #endif
  226338. #endif
  226339. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  226340. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  226341. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226342. // compiled on its own).
  226343. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  226344. #if JUCE_MAC
  226345. END_JUCE_NAMESPACE
  226346. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  226347. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  226348. {
  226349. CriticalSection* contextLock;
  226350. bool needsUpdate;
  226351. }
  226352. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  226353. - (bool) makeActive;
  226354. - (void) makeInactive;
  226355. - (void) reshape;
  226356. @end
  226357. @implementation ThreadSafeNSOpenGLView
  226358. - (id) initWithFrame: (NSRect) frameRect
  226359. pixelFormat: (NSOpenGLPixelFormat*) format
  226360. {
  226361. contextLock = new CriticalSection();
  226362. self = [super initWithFrame: frameRect pixelFormat: format];
  226363. if (self != nil)
  226364. [[NSNotificationCenter defaultCenter] addObserver: self
  226365. selector: @selector (_surfaceNeedsUpdate:)
  226366. name: NSViewGlobalFrameDidChangeNotification
  226367. object: self];
  226368. return self;
  226369. }
  226370. - (void) dealloc
  226371. {
  226372. [[NSNotificationCenter defaultCenter] removeObserver: self];
  226373. delete contextLock;
  226374. [super dealloc];
  226375. }
  226376. - (bool) makeActive
  226377. {
  226378. const ScopedLock sl (*contextLock);
  226379. if ([self openGLContext] == 0)
  226380. return false;
  226381. [[self openGLContext] makeCurrentContext];
  226382. if (needsUpdate)
  226383. {
  226384. [super update];
  226385. needsUpdate = false;
  226386. }
  226387. return true;
  226388. }
  226389. - (void) makeInactive
  226390. {
  226391. const ScopedLock sl (*contextLock);
  226392. [NSOpenGLContext clearCurrentContext];
  226393. }
  226394. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  226395. {
  226396. const ScopedLock sl (*contextLock);
  226397. needsUpdate = true;
  226398. }
  226399. - (void) update
  226400. {
  226401. const ScopedLock sl (*contextLock);
  226402. needsUpdate = true;
  226403. }
  226404. - (void) reshape
  226405. {
  226406. const ScopedLock sl (*contextLock);
  226407. needsUpdate = true;
  226408. }
  226409. @end
  226410. BEGIN_JUCE_NAMESPACE
  226411. class WindowedGLContext : public OpenGLContext
  226412. {
  226413. public:
  226414. WindowedGLContext (Component* const component,
  226415. const OpenGLPixelFormat& pixelFormat_,
  226416. NSOpenGLContext* sharedContext)
  226417. : renderContext (0),
  226418. pixelFormat (pixelFormat_)
  226419. {
  226420. jassert (component != 0);
  226421. NSOpenGLPixelFormatAttribute attribs [64];
  226422. int n = 0;
  226423. attribs[n++] = NSOpenGLPFADoubleBuffer;
  226424. attribs[n++] = NSOpenGLPFAAccelerated;
  226425. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  226426. attribs[n++] = NSOpenGLPFAColorSize;
  226427. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  226428. pixelFormat.greenBits,
  226429. pixelFormat.blueBits);
  226430. attribs[n++] = NSOpenGLPFAAlphaSize;
  226431. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  226432. attribs[n++] = NSOpenGLPFADepthSize;
  226433. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  226434. attribs[n++] = NSOpenGLPFAStencilSize;
  226435. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  226436. attribs[n++] = NSOpenGLPFAAccumSize;
  226437. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  226438. pixelFormat.accumulationBufferGreenBits,
  226439. pixelFormat.accumulationBufferBlueBits,
  226440. pixelFormat.accumulationBufferAlphaBits);
  226441. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  226442. attribs[n++] = NSOpenGLPFASampleBuffers;
  226443. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  226444. attribs[n++] = NSOpenGLPFAClosestPolicy;
  226445. attribs[n++] = NSOpenGLPFANoRecovery;
  226446. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  226447. NSOpenGLPixelFormat* format
  226448. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  226449. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226450. pixelFormat: format];
  226451. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  226452. shareContext: sharedContext] autorelease];
  226453. const GLint swapInterval = 1;
  226454. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  226455. [view setOpenGLContext: renderContext];
  226456. [renderContext setView: view];
  226457. [format release];
  226458. viewHolder = new NSViewComponentInternal (view, component);
  226459. }
  226460. ~WindowedGLContext()
  226461. {
  226462. makeInactive();
  226463. [renderContext clearDrawable];
  226464. viewHolder = 0;
  226465. }
  226466. bool makeActive() const throw()
  226467. {
  226468. jassert (renderContext != 0);
  226469. [view makeActive];
  226470. return isActive();
  226471. }
  226472. bool makeInactive() const throw()
  226473. {
  226474. [view makeInactive];
  226475. return true;
  226476. }
  226477. bool isActive() const throw()
  226478. {
  226479. return [NSOpenGLContext currentContext] == renderContext;
  226480. }
  226481. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226482. void* getRawContext() const throw() { return renderContext; }
  226483. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226484. {
  226485. }
  226486. void swapBuffers()
  226487. {
  226488. [renderContext flushBuffer];
  226489. }
  226490. bool setSwapInterval (const int numFramesPerSwap)
  226491. {
  226492. [renderContext setValues: (const GLint*) &numFramesPerSwap
  226493. forParameter: NSOpenGLCPSwapInterval];
  226494. return true;
  226495. }
  226496. int getSwapInterval() const
  226497. {
  226498. GLint numFrames = 0;
  226499. [renderContext getValues: &numFrames
  226500. forParameter: NSOpenGLCPSwapInterval];
  226501. return numFrames;
  226502. }
  226503. void repaint()
  226504. {
  226505. // we need to invalidate the juce view that holds this gl view, to make it
  226506. // cause a repaint callback
  226507. NSView* v = (NSView*) viewHolder->view;
  226508. NSRect r = [v frame];
  226509. // bit of a bodge here.. if we only invalidate the area of the gl component,
  226510. // it's completely covered by the NSOpenGLView, so the OS throws away the
  226511. // repaint message, thus never causing our paint() callback, and never repainting
  226512. // the comp. So invalidating just a little bit around the edge helps..
  226513. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  226514. }
  226515. void* getNativeWindowHandle() const { return viewHolder->view; }
  226516. juce_UseDebuggingNewOperator
  226517. NSOpenGLContext* renderContext;
  226518. ThreadSafeNSOpenGLView* view;
  226519. private:
  226520. OpenGLPixelFormat pixelFormat;
  226521. ScopedPointer <NSViewComponentInternal> viewHolder;
  226522. WindowedGLContext (const WindowedGLContext&);
  226523. WindowedGLContext& operator= (const WindowedGLContext&);
  226524. };
  226525. OpenGLContext* OpenGLComponent::createContext()
  226526. {
  226527. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  226528. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  226529. return (c->renderContext != 0) ? c.release() : 0;
  226530. }
  226531. void* OpenGLComponent::getNativeWindowHandle() const
  226532. {
  226533. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  226534. : 0;
  226535. }
  226536. void juce_glViewport (const int w, const int h)
  226537. {
  226538. glViewport (0, 0, w, h);
  226539. }
  226540. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  226541. OwnedArray <OpenGLPixelFormat>& results)
  226542. {
  226543. /* GLint attribs [64];
  226544. int n = 0;
  226545. attribs[n++] = AGL_RGBA;
  226546. attribs[n++] = AGL_DOUBLEBUFFER;
  226547. attribs[n++] = AGL_ACCELERATED;
  226548. attribs[n++] = AGL_NO_RECOVERY;
  226549. attribs[n++] = AGL_NONE;
  226550. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  226551. while (p != 0)
  226552. {
  226553. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  226554. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  226555. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  226556. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  226557. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  226558. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  226559. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  226560. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  226561. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  226562. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  226563. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  226564. results.add (pf);
  226565. p = aglNextPixelFormat (p);
  226566. }*/
  226567. //jassertfalse //xxx can't see how you do this in cocoa!
  226568. }
  226569. #else
  226570. END_JUCE_NAMESPACE
  226571. @interface JuceGLView : UIView
  226572. {
  226573. }
  226574. + (Class) layerClass;
  226575. @end
  226576. @implementation JuceGLView
  226577. + (Class) layerClass
  226578. {
  226579. return [CAEAGLLayer class];
  226580. }
  226581. @end
  226582. BEGIN_JUCE_NAMESPACE
  226583. class GLESContext : public OpenGLContext
  226584. {
  226585. public:
  226586. GLESContext (UIViewComponentPeer* peer,
  226587. Component* const component_,
  226588. const OpenGLPixelFormat& pixelFormat_,
  226589. const GLESContext* const sharedContext,
  226590. NSUInteger apiType)
  226591. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  226592. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  226593. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  226594. {
  226595. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  226596. view.opaque = YES;
  226597. view.hidden = NO;
  226598. view.backgroundColor = [UIColor blackColor];
  226599. view.userInteractionEnabled = NO;
  226600. glLayer = (CAEAGLLayer*) [view layer];
  226601. [peer->view addSubview: view];
  226602. if (sharedContext != 0)
  226603. context = [[EAGLContext alloc] initWithAPI: apiType
  226604. sharegroup: [sharedContext->context sharegroup]];
  226605. else
  226606. context = [[EAGLContext alloc] initWithAPI: apiType];
  226607. createGLBuffers();
  226608. }
  226609. ~GLESContext()
  226610. {
  226611. makeInactive();
  226612. [context release];
  226613. [view removeFromSuperview];
  226614. [view release];
  226615. freeGLBuffers();
  226616. }
  226617. bool makeActive() const throw()
  226618. {
  226619. jassert (context != 0);
  226620. [EAGLContext setCurrentContext: context];
  226621. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  226622. return true;
  226623. }
  226624. void swapBuffers()
  226625. {
  226626. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226627. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  226628. }
  226629. bool makeInactive() const throw()
  226630. {
  226631. return [EAGLContext setCurrentContext: nil];
  226632. }
  226633. bool isActive() const throw()
  226634. {
  226635. return [EAGLContext currentContext] == context;
  226636. }
  226637. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226638. void* getRawContext() const throw() { return glLayer; }
  226639. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226640. {
  226641. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  226642. if (lastWidth != w || lastHeight != h)
  226643. {
  226644. lastWidth = w;
  226645. lastHeight = h;
  226646. freeGLBuffers();
  226647. createGLBuffers();
  226648. }
  226649. }
  226650. bool setSwapInterval (const int numFramesPerSwap)
  226651. {
  226652. numFrames = numFramesPerSwap;
  226653. return true;
  226654. }
  226655. int getSwapInterval() const
  226656. {
  226657. return numFrames;
  226658. }
  226659. void repaint()
  226660. {
  226661. }
  226662. void createGLBuffers()
  226663. {
  226664. makeActive();
  226665. glGenFramebuffersOES (1, &frameBufferHandle);
  226666. glGenRenderbuffersOES (1, &colorBufferHandle);
  226667. glGenRenderbuffersOES (1, &depthBufferHandle);
  226668. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226669. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  226670. GLint width, height;
  226671. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  226672. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  226673. if (useDepthBuffer)
  226674. {
  226675. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  226676. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  226677. }
  226678. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226679. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  226680. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  226681. if (useDepthBuffer)
  226682. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  226683. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  226684. }
  226685. void freeGLBuffers()
  226686. {
  226687. if (frameBufferHandle != 0)
  226688. {
  226689. glDeleteFramebuffersOES (1, &frameBufferHandle);
  226690. frameBufferHandle = 0;
  226691. }
  226692. if (colorBufferHandle != 0)
  226693. {
  226694. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  226695. colorBufferHandle = 0;
  226696. }
  226697. if (depthBufferHandle != 0)
  226698. {
  226699. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  226700. depthBufferHandle = 0;
  226701. }
  226702. }
  226703. juce_UseDebuggingNewOperator
  226704. private:
  226705. Component::SafePointer<Component> component;
  226706. OpenGLPixelFormat pixelFormat;
  226707. JuceGLView* view;
  226708. CAEAGLLayer* glLayer;
  226709. EAGLContext* context;
  226710. bool useDepthBuffer;
  226711. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  226712. int numFrames;
  226713. int lastWidth, lastHeight;
  226714. GLESContext (const GLESContext&);
  226715. GLESContext& operator= (const GLESContext&);
  226716. };
  226717. OpenGLContext* OpenGLComponent::createContext()
  226718. {
  226719. ScopedAutoReleasePool pool;
  226720. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  226721. if (peer != 0)
  226722. return new GLESContext (peer, this, preferredPixelFormat,
  226723. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  226724. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  226725. return 0;
  226726. }
  226727. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  226728. OwnedArray <OpenGLPixelFormat>& /*results*/)
  226729. {
  226730. }
  226731. void juce_glViewport (const int w, const int h)
  226732. {
  226733. glViewport (0, 0, w, h);
  226734. }
  226735. #endif
  226736. #endif
  226737. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  226738. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  226739. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226740. // compiled on its own).
  226741. #if JUCE_INCLUDED_FILE
  226742. #if JUCE_MAC
  226743. namespace MouseCursorHelpers
  226744. {
  226745. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  226746. {
  226747. NSImage* im = CoreGraphicsImage::createNSImage (image);
  226748. NSCursor* c = [[NSCursor alloc] initWithImage: im
  226749. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  226750. [im release];
  226751. return c;
  226752. }
  226753. static void* fromWebKitFile (const char* filename, float hx, float hy)
  226754. {
  226755. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  226756. BufferedInputStream buf (&fileStream, 4096, false);
  226757. PNGImageFormat pngFormat;
  226758. Image im (pngFormat.decodeImage (buf));
  226759. if (im.isValid())
  226760. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  226761. jassertfalse;
  226762. return 0;
  226763. }
  226764. }
  226765. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  226766. {
  226767. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  226768. }
  226769. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  226770. {
  226771. const ScopedAutoReleasePool pool;
  226772. NSCursor* c = 0;
  226773. switch (type)
  226774. {
  226775. case NormalCursor: c = [NSCursor arrowCursor]; break;
  226776. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  226777. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  226778. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  226779. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  226780. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  226781. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  226782. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  226783. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  226784. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  226785. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  226786. case UpDownResizeCursor:
  226787. case TopEdgeResizeCursor:
  226788. case BottomEdgeResizeCursor:
  226789. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  226790. case TopLeftCornerResizeCursor:
  226791. case BottomRightCornerResizeCursor:
  226792. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  226793. case TopRightCornerResizeCursor:
  226794. case BottomLeftCornerResizeCursor:
  226795. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  226796. case UpDownLeftRightResizeCursor:
  226797. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  226798. default:
  226799. jassertfalse;
  226800. break;
  226801. }
  226802. [c retain];
  226803. return c;
  226804. }
  226805. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  226806. {
  226807. [((NSCursor*) cursorHandle) release];
  226808. }
  226809. void MouseCursor::showInAllWindows() const
  226810. {
  226811. showInWindow (0);
  226812. }
  226813. void MouseCursor::showInWindow (ComponentPeer*) const
  226814. {
  226815. [((NSCursor*) getHandle()) set];
  226816. }
  226817. #else
  226818. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  226819. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  226820. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  226821. void MouseCursor::showInAllWindows() const {}
  226822. void MouseCursor::showInWindow (ComponentPeer*) const {}
  226823. #endif
  226824. #endif
  226825. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  226826. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  226827. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226828. // compiled on its own).
  226829. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  226830. #if JUCE_MAC
  226831. END_JUCE_NAMESPACE
  226832. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  226833. @interface DownloadClickDetector : NSObject
  226834. {
  226835. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  226836. }
  226837. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  226838. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  226839. request: (NSURLRequest*) request
  226840. frame: (WebFrame*) frame
  226841. decisionListener: (id<WebPolicyDecisionListener>) listener;
  226842. @end
  226843. @implementation DownloadClickDetector
  226844. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  226845. {
  226846. [super init];
  226847. ownerComponent = ownerComponent_;
  226848. return self;
  226849. }
  226850. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  226851. request: (NSURLRequest*) request
  226852. frame: (WebFrame*) frame
  226853. decisionListener: (id <WebPolicyDecisionListener>) listener
  226854. {
  226855. (void) sender;
  226856. (void) request;
  226857. (void) frame;
  226858. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  226859. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  226860. [listener use];
  226861. else
  226862. [listener ignore];
  226863. }
  226864. @end
  226865. BEGIN_JUCE_NAMESPACE
  226866. class WebBrowserComponentInternal : public NSViewComponent
  226867. {
  226868. public:
  226869. WebBrowserComponentInternal (WebBrowserComponent* owner)
  226870. {
  226871. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226872. frameName: @""
  226873. groupName: @""];
  226874. setView (webView);
  226875. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  226876. [webView setPolicyDelegate: clickListener];
  226877. }
  226878. ~WebBrowserComponentInternal()
  226879. {
  226880. [webView setPolicyDelegate: nil];
  226881. [clickListener release];
  226882. setView (0);
  226883. }
  226884. void goToURL (const String& url,
  226885. const StringArray* headers,
  226886. const MemoryBlock* postData)
  226887. {
  226888. NSMutableURLRequest* r
  226889. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  226890. cachePolicy: NSURLRequestUseProtocolCachePolicy
  226891. timeoutInterval: 30.0];
  226892. if (postData != 0 && postData->getSize() > 0)
  226893. {
  226894. [r setHTTPMethod: @"POST"];
  226895. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  226896. length: postData->getSize()]];
  226897. }
  226898. if (headers != 0)
  226899. {
  226900. for (int i = 0; i < headers->size(); ++i)
  226901. {
  226902. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  226903. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  226904. [r setValue: juceStringToNS (headerValue)
  226905. forHTTPHeaderField: juceStringToNS (headerName)];
  226906. }
  226907. }
  226908. stop();
  226909. [[webView mainFrame] loadRequest: r];
  226910. }
  226911. void goBack()
  226912. {
  226913. [webView goBack];
  226914. }
  226915. void goForward()
  226916. {
  226917. [webView goForward];
  226918. }
  226919. void stop()
  226920. {
  226921. [webView stopLoading: nil];
  226922. }
  226923. void refresh()
  226924. {
  226925. [webView reload: nil];
  226926. }
  226927. private:
  226928. WebView* webView;
  226929. DownloadClickDetector* clickListener;
  226930. };
  226931. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  226932. : browser (0),
  226933. blankPageShown (false),
  226934. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  226935. {
  226936. setOpaque (true);
  226937. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  226938. }
  226939. WebBrowserComponent::~WebBrowserComponent()
  226940. {
  226941. deleteAndZero (browser);
  226942. }
  226943. void WebBrowserComponent::goToURL (const String& url,
  226944. const StringArray* headers,
  226945. const MemoryBlock* postData)
  226946. {
  226947. lastURL = url;
  226948. lastHeaders.clear();
  226949. if (headers != 0)
  226950. lastHeaders = *headers;
  226951. lastPostData.setSize (0);
  226952. if (postData != 0)
  226953. lastPostData = *postData;
  226954. blankPageShown = false;
  226955. browser->goToURL (url, headers, postData);
  226956. }
  226957. void WebBrowserComponent::stop()
  226958. {
  226959. browser->stop();
  226960. }
  226961. void WebBrowserComponent::goBack()
  226962. {
  226963. lastURL = String::empty;
  226964. blankPageShown = false;
  226965. browser->goBack();
  226966. }
  226967. void WebBrowserComponent::goForward()
  226968. {
  226969. lastURL = String::empty;
  226970. browser->goForward();
  226971. }
  226972. void WebBrowserComponent::refresh()
  226973. {
  226974. browser->refresh();
  226975. }
  226976. void WebBrowserComponent::paint (Graphics&)
  226977. {
  226978. }
  226979. void WebBrowserComponent::checkWindowAssociation()
  226980. {
  226981. if (isShowing())
  226982. {
  226983. if (blankPageShown)
  226984. goBack();
  226985. }
  226986. else
  226987. {
  226988. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  226989. {
  226990. // when the component becomes invisible, some stuff like flash
  226991. // carries on playing audio, so we need to force it onto a blank
  226992. // page to avoid this, (and send it back when it's made visible again).
  226993. blankPageShown = true;
  226994. browser->goToURL ("about:blank", 0, 0);
  226995. }
  226996. }
  226997. }
  226998. void WebBrowserComponent::reloadLastURL()
  226999. {
  227000. if (lastURL.isNotEmpty())
  227001. {
  227002. goToURL (lastURL, &lastHeaders, &lastPostData);
  227003. lastURL = String::empty;
  227004. }
  227005. }
  227006. void WebBrowserComponent::parentHierarchyChanged()
  227007. {
  227008. checkWindowAssociation();
  227009. }
  227010. void WebBrowserComponent::resized()
  227011. {
  227012. browser->setSize (getWidth(), getHeight());
  227013. }
  227014. void WebBrowserComponent::visibilityChanged()
  227015. {
  227016. checkWindowAssociation();
  227017. }
  227018. bool WebBrowserComponent::pageAboutToLoad (const String&)
  227019. {
  227020. return true;
  227021. }
  227022. #else
  227023. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227024. {
  227025. }
  227026. WebBrowserComponent::~WebBrowserComponent()
  227027. {
  227028. }
  227029. void WebBrowserComponent::goToURL (const String& url,
  227030. const StringArray* headers,
  227031. const MemoryBlock* postData)
  227032. {
  227033. }
  227034. void WebBrowserComponent::stop()
  227035. {
  227036. }
  227037. void WebBrowserComponent::goBack()
  227038. {
  227039. }
  227040. void WebBrowserComponent::goForward()
  227041. {
  227042. }
  227043. void WebBrowserComponent::refresh()
  227044. {
  227045. }
  227046. void WebBrowserComponent::paint (Graphics& g)
  227047. {
  227048. }
  227049. void WebBrowserComponent::checkWindowAssociation()
  227050. {
  227051. }
  227052. void WebBrowserComponent::reloadLastURL()
  227053. {
  227054. }
  227055. void WebBrowserComponent::parentHierarchyChanged()
  227056. {
  227057. }
  227058. void WebBrowserComponent::resized()
  227059. {
  227060. }
  227061. void WebBrowserComponent::visibilityChanged()
  227062. {
  227063. }
  227064. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  227065. {
  227066. return true;
  227067. }
  227068. #endif
  227069. #endif
  227070. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227071. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  227072. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227073. // compiled on its own).
  227074. #if JUCE_INCLUDED_FILE
  227075. class IPhoneAudioIODevice : public AudioIODevice
  227076. {
  227077. public:
  227078. IPhoneAudioIODevice (const String& deviceName)
  227079. : AudioIODevice (deviceName, "Audio"),
  227080. audioUnit (0),
  227081. isRunning (false),
  227082. callback (0),
  227083. actualBufferSize (0),
  227084. floatData (1, 2)
  227085. {
  227086. numInputChannels = 2;
  227087. numOutputChannels = 2;
  227088. preferredBufferSize = 0;
  227089. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  227090. updateDeviceInfo();
  227091. }
  227092. ~IPhoneAudioIODevice()
  227093. {
  227094. close();
  227095. }
  227096. const StringArray getOutputChannelNames()
  227097. {
  227098. StringArray s;
  227099. s.add ("Left");
  227100. s.add ("Right");
  227101. return s;
  227102. }
  227103. const StringArray getInputChannelNames()
  227104. {
  227105. StringArray s;
  227106. if (audioInputIsAvailable)
  227107. {
  227108. s.add ("Left");
  227109. s.add ("Right");
  227110. }
  227111. return s;
  227112. }
  227113. int getNumSampleRates()
  227114. {
  227115. return 1;
  227116. }
  227117. double getSampleRate (int index)
  227118. {
  227119. return sampleRate;
  227120. }
  227121. int getNumBufferSizesAvailable()
  227122. {
  227123. return 1;
  227124. }
  227125. int getBufferSizeSamples (int index)
  227126. {
  227127. return getDefaultBufferSize();
  227128. }
  227129. int getDefaultBufferSize()
  227130. {
  227131. return 1024;
  227132. }
  227133. const String open (const BigInteger& inputChannels,
  227134. const BigInteger& outputChannels,
  227135. double sampleRate,
  227136. int bufferSize)
  227137. {
  227138. close();
  227139. lastError = String::empty;
  227140. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  227141. // xxx set up channel mapping
  227142. activeOutputChans = outputChannels;
  227143. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  227144. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  227145. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  227146. activeInputChans = inputChannels;
  227147. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  227148. numInputChannels = activeInputChans.countNumberOfSetBits();
  227149. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  227150. AudioSessionSetActive (true);
  227151. UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord;
  227152. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  227153. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  227154. fixAudioRouteIfSetToReceiver();
  227155. updateDeviceInfo();
  227156. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227157. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  227158. actualBufferSize = preferredBufferSize;
  227159. prepareFloatBuffers();
  227160. isRunning = true;
  227161. propertyChanged (0, 0, 0); // creates and starts the AU
  227162. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  227163. return lastError;
  227164. }
  227165. void close()
  227166. {
  227167. if (isRunning)
  227168. {
  227169. isRunning = false;
  227170. AudioSessionSetActive (false);
  227171. if (audioUnit != 0)
  227172. {
  227173. AudioComponentInstanceDispose (audioUnit);
  227174. audioUnit = 0;
  227175. }
  227176. }
  227177. }
  227178. bool isOpen()
  227179. {
  227180. return isRunning;
  227181. }
  227182. int getCurrentBufferSizeSamples()
  227183. {
  227184. return actualBufferSize;
  227185. }
  227186. double getCurrentSampleRate()
  227187. {
  227188. return sampleRate;
  227189. }
  227190. int getCurrentBitDepth()
  227191. {
  227192. return 16;
  227193. }
  227194. const BigInteger getActiveOutputChannels() const
  227195. {
  227196. return activeOutputChans;
  227197. }
  227198. const BigInteger getActiveInputChannels() const
  227199. {
  227200. return activeInputChans;
  227201. }
  227202. int getOutputLatencyInSamples()
  227203. {
  227204. return 0; //xxx
  227205. }
  227206. int getInputLatencyInSamples()
  227207. {
  227208. return 0; //xxx
  227209. }
  227210. void start (AudioIODeviceCallback* callback_)
  227211. {
  227212. if (isRunning && callback != callback_)
  227213. {
  227214. if (callback_ != 0)
  227215. callback_->audioDeviceAboutToStart (this);
  227216. const ScopedLock sl (callbackLock);
  227217. callback = callback_;
  227218. }
  227219. }
  227220. void stop()
  227221. {
  227222. if (isRunning)
  227223. {
  227224. AudioIODeviceCallback* lastCallback;
  227225. {
  227226. const ScopedLock sl (callbackLock);
  227227. lastCallback = callback;
  227228. callback = 0;
  227229. }
  227230. if (lastCallback != 0)
  227231. lastCallback->audioDeviceStopped();
  227232. }
  227233. }
  227234. bool isPlaying()
  227235. {
  227236. return isRunning && callback != 0;
  227237. }
  227238. const String getLastError()
  227239. {
  227240. return lastError;
  227241. }
  227242. private:
  227243. CriticalSection callbackLock;
  227244. Float64 sampleRate;
  227245. int numInputChannels, numOutputChannels;
  227246. int preferredBufferSize;
  227247. int actualBufferSize;
  227248. bool isRunning;
  227249. String lastError;
  227250. AudioStreamBasicDescription format;
  227251. AudioUnit audioUnit;
  227252. UInt32 audioInputIsAvailable;
  227253. AudioIODeviceCallback* callback;
  227254. BigInteger activeOutputChans, activeInputChans;
  227255. AudioSampleBuffer floatData;
  227256. float* inputChannels[3];
  227257. float* outputChannels[3];
  227258. bool monoInputChannelNumber, monoOutputChannelNumber;
  227259. void prepareFloatBuffers()
  227260. {
  227261. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  227262. zerostruct (inputChannels);
  227263. zerostruct (outputChannels);
  227264. for (int i = 0; i < numInputChannels; ++i)
  227265. inputChannels[i] = floatData.getSampleData (i);
  227266. for (int i = 0; i < numOutputChannels; ++i)
  227267. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  227268. }
  227269. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227270. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227271. {
  227272. OSStatus err = noErr;
  227273. if (audioInputIsAvailable)
  227274. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  227275. const ScopedLock sl (callbackLock);
  227276. if (callback != 0)
  227277. {
  227278. if (audioInputIsAvailable && numInputChannels > 0)
  227279. {
  227280. short* shortData = (short*) ioData->mBuffers[0].mData;
  227281. if (numInputChannels >= 2)
  227282. {
  227283. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227284. {
  227285. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227286. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  227287. }
  227288. }
  227289. else
  227290. {
  227291. if (monoInputChannelNumber > 0)
  227292. ++shortData;
  227293. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227294. {
  227295. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227296. ++shortData;
  227297. }
  227298. }
  227299. }
  227300. else
  227301. {
  227302. for (int i = numInputChannels; --i >= 0;)
  227303. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  227304. }
  227305. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  227306. outputChannels, numOutputChannels,
  227307. (int) inNumberFrames);
  227308. short* shortData = (short*) ioData->mBuffers[0].mData;
  227309. int n = 0;
  227310. if (numOutputChannels >= 2)
  227311. {
  227312. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227313. {
  227314. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  227315. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  227316. }
  227317. }
  227318. else if (numOutputChannels == 1)
  227319. {
  227320. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227321. {
  227322. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  227323. shortData [n++] = s;
  227324. shortData [n++] = s;
  227325. }
  227326. }
  227327. else
  227328. {
  227329. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227330. }
  227331. }
  227332. else
  227333. {
  227334. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227335. }
  227336. return err;
  227337. }
  227338. void updateDeviceInfo()
  227339. {
  227340. UInt32 size = sizeof (sampleRate);
  227341. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  227342. size = sizeof (audioInputIsAvailable);
  227343. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  227344. }
  227345. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227346. {
  227347. if (! isRunning)
  227348. return;
  227349. if (inPropertyValue != 0)
  227350. {
  227351. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  227352. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  227353. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  227354. SInt32 routeChangeReason;
  227355. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  227356. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  227357. fixAudioRouteIfSetToReceiver();
  227358. }
  227359. updateDeviceInfo();
  227360. createAudioUnit();
  227361. AudioSessionSetActive (true);
  227362. if (audioUnit != 0)
  227363. {
  227364. UInt32 formatSize = sizeof (format);
  227365. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  227366. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227367. UInt32 bufferDurationSize = sizeof (bufferDuration);
  227368. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  227369. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  227370. AudioOutputUnitStart (audioUnit);
  227371. }
  227372. }
  227373. void interruptionListener (UInt32 inInterruption)
  227374. {
  227375. /*if (inInterruption == kAudioSessionBeginInterruption)
  227376. {
  227377. isRunning = false;
  227378. AudioOutputUnitStop (audioUnit);
  227379. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  227380. "This could have been interrupted by another application or by unplugging a headset",
  227381. @"Resume",
  227382. @"Cancel"))
  227383. {
  227384. isRunning = true;
  227385. propertyChanged (0, 0, 0);
  227386. }
  227387. }*/
  227388. if (inInterruption == kAudioSessionEndInterruption)
  227389. {
  227390. isRunning = true;
  227391. AudioSessionSetActive (true);
  227392. AudioOutputUnitStart (audioUnit);
  227393. }
  227394. }
  227395. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227396. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227397. {
  227398. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  227399. }
  227400. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227401. {
  227402. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  227403. }
  227404. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  227405. {
  227406. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  227407. }
  227408. void resetFormat (const int numChannels)
  227409. {
  227410. memset (&format, 0, sizeof (format));
  227411. format.mFormatID = kAudioFormatLinearPCM;
  227412. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  227413. format.mBitsPerChannel = 8 * sizeof (short);
  227414. format.mChannelsPerFrame = 2;
  227415. format.mFramesPerPacket = 1;
  227416. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  227417. }
  227418. bool createAudioUnit()
  227419. {
  227420. if (audioUnit != 0)
  227421. {
  227422. AudioComponentInstanceDispose (audioUnit);
  227423. audioUnit = 0;
  227424. }
  227425. resetFormat (2);
  227426. AudioComponentDescription desc;
  227427. desc.componentType = kAudioUnitType_Output;
  227428. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  227429. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  227430. desc.componentFlags = 0;
  227431. desc.componentFlagsMask = 0;
  227432. AudioComponent comp = AudioComponentFindNext (0, &desc);
  227433. AudioComponentInstanceNew (comp, &audioUnit);
  227434. if (audioUnit == 0)
  227435. return false;
  227436. const UInt32 one = 1;
  227437. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  227438. AudioChannelLayout layout;
  227439. layout.mChannelBitmap = 0;
  227440. layout.mNumberChannelDescriptions = 0;
  227441. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  227442. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  227443. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  227444. AURenderCallbackStruct inputProc;
  227445. inputProc.inputProc = processStatic;
  227446. inputProc.inputProcRefCon = this;
  227447. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  227448. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  227449. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  227450. AudioUnitInitialize (audioUnit);
  227451. return true;
  227452. }
  227453. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  227454. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  227455. static void fixAudioRouteIfSetToReceiver()
  227456. {
  227457. CFStringRef audioRoute = 0;
  227458. UInt32 propertySize = sizeof (audioRoute);
  227459. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  227460. {
  227461. NSString* route = (NSString*) audioRoute;
  227462. //DBG ("audio route: " + nsStringToJuce (route));
  227463. if ([route hasPrefix: @"Receiver"])
  227464. {
  227465. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  227466. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  227467. }
  227468. CFRelease (audioRoute);
  227469. }
  227470. }
  227471. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  227472. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  227473. };
  227474. class IPhoneAudioIODeviceType : public AudioIODeviceType
  227475. {
  227476. public:
  227477. IPhoneAudioIODeviceType()
  227478. : AudioIODeviceType ("iPhone Audio")
  227479. {
  227480. }
  227481. ~IPhoneAudioIODeviceType()
  227482. {
  227483. }
  227484. void scanForDevices()
  227485. {
  227486. }
  227487. const StringArray getDeviceNames (bool wantInputNames) const
  227488. {
  227489. StringArray s;
  227490. s.add ("iPhone Audio");
  227491. return s;
  227492. }
  227493. int getDefaultDeviceIndex (bool forInput) const
  227494. {
  227495. return 0;
  227496. }
  227497. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  227498. {
  227499. return device != 0 ? 0 : -1;
  227500. }
  227501. bool hasSeparateInputsAndOutputs() const { return false; }
  227502. AudioIODevice* createDevice (const String& outputDeviceName,
  227503. const String& inputDeviceName)
  227504. {
  227505. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  227506. {
  227507. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  227508. : inputDeviceName);
  227509. }
  227510. return 0;
  227511. }
  227512. juce_UseDebuggingNewOperator
  227513. private:
  227514. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  227515. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  227516. };
  227517. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  227518. {
  227519. return new IPhoneAudioIODeviceType();
  227520. }
  227521. #endif
  227522. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  227523. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  227524. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227525. // compiled on its own).
  227526. #if JUCE_INCLUDED_FILE
  227527. #if JUCE_MAC
  227528. #undef log
  227529. #define log(a) Logger::writeToLog(a)
  227530. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  227531. {
  227532. if (err == noErr)
  227533. return true;
  227534. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  227535. jassertfalse;
  227536. return false;
  227537. }
  227538. #undef OK
  227539. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  227540. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  227541. {
  227542. String result;
  227543. CFStringRef str = 0;
  227544. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  227545. if (str != 0)
  227546. {
  227547. result = PlatformUtilities::cfStringToJuceString (str);
  227548. CFRelease (str);
  227549. str = 0;
  227550. }
  227551. MIDIEntityRef entity = 0;
  227552. MIDIEndpointGetEntity (endpoint, &entity);
  227553. if (entity == 0)
  227554. return result; // probably virtual
  227555. if (result.isEmpty())
  227556. {
  227557. // endpoint name has zero length - try the entity
  227558. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  227559. if (str != 0)
  227560. {
  227561. result += PlatformUtilities::cfStringToJuceString (str);
  227562. CFRelease (str);
  227563. str = 0;
  227564. }
  227565. }
  227566. // now consider the device's name
  227567. MIDIDeviceRef device = 0;
  227568. MIDIEntityGetDevice (entity, &device);
  227569. if (device == 0)
  227570. return result;
  227571. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  227572. if (str != 0)
  227573. {
  227574. const String s (PlatformUtilities::cfStringToJuceString (str));
  227575. CFRelease (str);
  227576. // if an external device has only one entity, throw away
  227577. // the endpoint name and just use the device name
  227578. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  227579. {
  227580. result = s;
  227581. }
  227582. else if (! result.startsWithIgnoreCase (s))
  227583. {
  227584. // prepend the device name to the entity name
  227585. result = (s + " " + result).trimEnd();
  227586. }
  227587. }
  227588. return result;
  227589. }
  227590. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  227591. {
  227592. String result;
  227593. // Does the endpoint have connections?
  227594. CFDataRef connections = 0;
  227595. int numConnections = 0;
  227596. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  227597. if (connections != 0)
  227598. {
  227599. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  227600. if (numConnections > 0)
  227601. {
  227602. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  227603. for (int i = 0; i < numConnections; ++i, ++pid)
  227604. {
  227605. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  227606. MIDIObjectRef connObject;
  227607. MIDIObjectType connObjectType;
  227608. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  227609. if (err == noErr)
  227610. {
  227611. String s;
  227612. if (connObjectType == kMIDIObjectType_ExternalSource
  227613. || connObjectType == kMIDIObjectType_ExternalDestination)
  227614. {
  227615. // Connected to an external device's endpoint (10.3 and later).
  227616. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  227617. }
  227618. else
  227619. {
  227620. // Connected to an external device (10.2) (or something else, catch-all)
  227621. CFStringRef str = 0;
  227622. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  227623. if (str != 0)
  227624. {
  227625. s = PlatformUtilities::cfStringToJuceString (str);
  227626. CFRelease (str);
  227627. }
  227628. }
  227629. if (s.isNotEmpty())
  227630. {
  227631. if (result.isNotEmpty())
  227632. result += ", ";
  227633. result += s;
  227634. }
  227635. }
  227636. }
  227637. }
  227638. CFRelease (connections);
  227639. }
  227640. if (result.isNotEmpty())
  227641. return result;
  227642. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  227643. return getEndpointName (endpoint, false);
  227644. }
  227645. const StringArray MidiOutput::getDevices()
  227646. {
  227647. StringArray s;
  227648. const ItemCount num = MIDIGetNumberOfDestinations();
  227649. for (ItemCount i = 0; i < num; ++i)
  227650. {
  227651. MIDIEndpointRef dest = MIDIGetDestination (i);
  227652. if (dest != 0)
  227653. {
  227654. String name (getConnectedEndpointName (dest));
  227655. if (name.isEmpty())
  227656. name = "<error>";
  227657. s.add (name);
  227658. }
  227659. else
  227660. {
  227661. s.add ("<error>");
  227662. }
  227663. }
  227664. return s;
  227665. }
  227666. int MidiOutput::getDefaultDeviceIndex()
  227667. {
  227668. return 0;
  227669. }
  227670. static MIDIClientRef globalMidiClient;
  227671. static bool hasGlobalClientBeenCreated = false;
  227672. static bool makeSureClientExists()
  227673. {
  227674. if (! hasGlobalClientBeenCreated)
  227675. {
  227676. String name ("JUCE");
  227677. if (JUCEApplication::getInstance() != 0)
  227678. name = JUCEApplication::getInstance()->getApplicationName();
  227679. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  227680. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  227681. CFRelease (appName);
  227682. }
  227683. return hasGlobalClientBeenCreated;
  227684. }
  227685. class MidiPortAndEndpoint
  227686. {
  227687. public:
  227688. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  227689. : port (port_), endPoint (endPoint_)
  227690. {
  227691. }
  227692. ~MidiPortAndEndpoint()
  227693. {
  227694. if (port != 0)
  227695. MIDIPortDispose (port);
  227696. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  227697. MIDIEndpointDispose (endPoint);
  227698. }
  227699. MIDIPortRef port;
  227700. MIDIEndpointRef endPoint;
  227701. };
  227702. MidiOutput* MidiOutput::openDevice (int index)
  227703. {
  227704. MidiOutput* mo = 0;
  227705. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  227706. {
  227707. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  227708. CFStringRef pname;
  227709. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  227710. {
  227711. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  227712. if (makeSureClientExists())
  227713. {
  227714. MIDIPortRef port;
  227715. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  227716. {
  227717. mo = new MidiOutput();
  227718. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  227719. }
  227720. }
  227721. CFRelease (pname);
  227722. }
  227723. }
  227724. return mo;
  227725. }
  227726. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  227727. {
  227728. MidiOutput* mo = 0;
  227729. if (makeSureClientExists())
  227730. {
  227731. MIDIEndpointRef endPoint;
  227732. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  227733. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  227734. {
  227735. mo = new MidiOutput();
  227736. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  227737. }
  227738. CFRelease (name);
  227739. }
  227740. return mo;
  227741. }
  227742. MidiOutput::~MidiOutput()
  227743. {
  227744. delete (MidiPortAndEndpoint*) internal;
  227745. }
  227746. void MidiOutput::reset()
  227747. {
  227748. }
  227749. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  227750. {
  227751. return false;
  227752. }
  227753. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  227754. {
  227755. }
  227756. void MidiOutput::sendMessageNow (const MidiMessage& message)
  227757. {
  227758. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  227759. if (message.isSysEx())
  227760. {
  227761. const int maxPacketSize = 256;
  227762. int pos = 0, bytesLeft = message.getRawDataSize();
  227763. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  227764. HeapBlock <MIDIPacketList> packets;
  227765. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  227766. packets->numPackets = numPackets;
  227767. MIDIPacket* p = packets->packet;
  227768. for (int i = 0; i < numPackets; ++i)
  227769. {
  227770. p->timeStamp = 0;
  227771. p->length = jmin (maxPacketSize, bytesLeft);
  227772. memcpy (p->data, message.getRawData() + pos, p->length);
  227773. pos += p->length;
  227774. bytesLeft -= p->length;
  227775. p = MIDIPacketNext (p);
  227776. }
  227777. if (mpe->port != 0)
  227778. MIDISend (mpe->port, mpe->endPoint, packets);
  227779. else
  227780. MIDIReceived (mpe->endPoint, packets);
  227781. }
  227782. else
  227783. {
  227784. MIDIPacketList packets;
  227785. packets.numPackets = 1;
  227786. packets.packet[0].timeStamp = 0;
  227787. packets.packet[0].length = message.getRawDataSize();
  227788. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  227789. if (mpe->port != 0)
  227790. MIDISend (mpe->port, mpe->endPoint, &packets);
  227791. else
  227792. MIDIReceived (mpe->endPoint, &packets);
  227793. }
  227794. }
  227795. const StringArray MidiInput::getDevices()
  227796. {
  227797. StringArray s;
  227798. const ItemCount num = MIDIGetNumberOfSources();
  227799. for (ItemCount i = 0; i < num; ++i)
  227800. {
  227801. MIDIEndpointRef source = MIDIGetSource (i);
  227802. if (source != 0)
  227803. {
  227804. String name (getConnectedEndpointName (source));
  227805. if (name.isEmpty())
  227806. name = "<error>";
  227807. s.add (name);
  227808. }
  227809. else
  227810. {
  227811. s.add ("<error>");
  227812. }
  227813. }
  227814. return s;
  227815. }
  227816. int MidiInput::getDefaultDeviceIndex()
  227817. {
  227818. return 0;
  227819. }
  227820. struct MidiPortAndCallback
  227821. {
  227822. MidiInput* input;
  227823. MidiPortAndEndpoint* portAndEndpoint;
  227824. MidiInputCallback* callback;
  227825. MemoryBlock pendingData;
  227826. int pendingBytes;
  227827. double pendingDataTime;
  227828. bool active;
  227829. void processSysex (const uint8*& d, int& size, const double time)
  227830. {
  227831. if (*d == 0xf0)
  227832. {
  227833. pendingBytes = 0;
  227834. pendingDataTime = time;
  227835. }
  227836. pendingData.ensureSize (pendingBytes + size, false);
  227837. uint8* totalMessage = (uint8*) pendingData.getData();
  227838. uint8* dest = totalMessage + pendingBytes;
  227839. while (size > 0)
  227840. {
  227841. if (pendingBytes > 0 && *d >= 0x80)
  227842. {
  227843. if (*d >= 0xfa || *d == 0xf8)
  227844. {
  227845. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  227846. ++d;
  227847. --size;
  227848. }
  227849. else
  227850. {
  227851. if (*d == 0xf7)
  227852. {
  227853. *dest++ = *d++;
  227854. pendingBytes++;
  227855. --size;
  227856. }
  227857. break;
  227858. }
  227859. }
  227860. else
  227861. {
  227862. *dest++ = *d++;
  227863. pendingBytes++;
  227864. --size;
  227865. }
  227866. }
  227867. if (totalMessage [pendingBytes - 1] == 0xf7)
  227868. {
  227869. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  227870. pendingBytes = 0;
  227871. }
  227872. else
  227873. {
  227874. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  227875. }
  227876. }
  227877. };
  227878. namespace CoreMidiCallbacks
  227879. {
  227880. static CriticalSection callbackLock;
  227881. static Array<void*> activeCallbacks;
  227882. }
  227883. static void midiInputProc (const MIDIPacketList* pktlist,
  227884. void* readProcRefCon,
  227885. void* /*srcConnRefCon*/)
  227886. {
  227887. double time = Time::getMillisecondCounterHiRes() * 0.001;
  227888. const double originalTime = time;
  227889. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  227890. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  227891. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  227892. {
  227893. const MIDIPacket* packet = &pktlist->packet[0];
  227894. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  227895. {
  227896. const uint8* d = (const uint8*) (packet->data);
  227897. int size = packet->length;
  227898. while (size > 0)
  227899. {
  227900. time = originalTime;
  227901. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  227902. {
  227903. mpc->processSysex (d, size, time);
  227904. }
  227905. else
  227906. {
  227907. int used = 0;
  227908. const MidiMessage m (d, size, used, 0, time);
  227909. if (used <= 0)
  227910. {
  227911. jassertfalse; // malformed midi message
  227912. break;
  227913. }
  227914. else
  227915. {
  227916. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  227917. }
  227918. size -= used;
  227919. d += used;
  227920. }
  227921. }
  227922. packet = MIDIPacketNext (packet);
  227923. }
  227924. }
  227925. }
  227926. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  227927. {
  227928. MidiInput* mi = 0;
  227929. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  227930. {
  227931. MIDIEndpointRef endPoint = MIDIGetSource (index);
  227932. if (endPoint != 0)
  227933. {
  227934. CFStringRef pname;
  227935. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  227936. {
  227937. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  227938. if (makeSureClientExists())
  227939. {
  227940. MIDIPortRef port;
  227941. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  227942. mpc->active = false;
  227943. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  227944. {
  227945. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  227946. {
  227947. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  227948. mpc->callback = callback;
  227949. mpc->pendingBytes = 0;
  227950. mpc->pendingData.ensureSize (128);
  227951. mi = new MidiInput (getDevices() [index]);
  227952. mpc->input = mi;
  227953. mi->internal = mpc;
  227954. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  227955. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  227956. }
  227957. else
  227958. {
  227959. OK (MIDIPortDispose (port));
  227960. }
  227961. }
  227962. }
  227963. }
  227964. CFRelease (pname);
  227965. }
  227966. }
  227967. return mi;
  227968. }
  227969. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  227970. {
  227971. MidiInput* mi = 0;
  227972. if (makeSureClientExists())
  227973. {
  227974. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  227975. mpc->active = false;
  227976. MIDIEndpointRef endPoint;
  227977. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  227978. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  227979. {
  227980. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  227981. mpc->callback = callback;
  227982. mpc->pendingBytes = 0;
  227983. mpc->pendingData.ensureSize (128);
  227984. mi = new MidiInput (deviceName);
  227985. mpc->input = mi;
  227986. mi->internal = mpc;
  227987. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  227988. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  227989. }
  227990. CFRelease (name);
  227991. }
  227992. return mi;
  227993. }
  227994. MidiInput::MidiInput (const String& name_)
  227995. : name (name_)
  227996. {
  227997. }
  227998. MidiInput::~MidiInput()
  227999. {
  228000. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  228001. mpc->active = false;
  228002. {
  228003. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228004. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  228005. }
  228006. if (mpc->portAndEndpoint->port != 0)
  228007. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  228008. delete mpc->portAndEndpoint;
  228009. delete mpc;
  228010. }
  228011. void MidiInput::start()
  228012. {
  228013. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228014. ((MidiPortAndCallback*) internal)->active = true;
  228015. }
  228016. void MidiInput::stop()
  228017. {
  228018. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228019. ((MidiPortAndCallback*) internal)->active = false;
  228020. }
  228021. #undef log
  228022. #else
  228023. MidiOutput::~MidiOutput()
  228024. {
  228025. }
  228026. void MidiOutput::reset()
  228027. {
  228028. }
  228029. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228030. {
  228031. return false;
  228032. }
  228033. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228034. {
  228035. }
  228036. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228037. {
  228038. }
  228039. const StringArray MidiOutput::getDevices()
  228040. {
  228041. return StringArray();
  228042. }
  228043. MidiOutput* MidiOutput::openDevice (int index)
  228044. {
  228045. return 0;
  228046. }
  228047. const StringArray MidiInput::getDevices()
  228048. {
  228049. return StringArray();
  228050. }
  228051. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228052. {
  228053. return 0;
  228054. }
  228055. #endif
  228056. #endif
  228057. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  228058. #else
  228059. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  228060. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228061. // compiled on its own).
  228062. #if JUCE_INCLUDED_FILE
  228063. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228064. #define SUPPORT_10_4_FONTS 1
  228065. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  228066. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228067. #define SUPPORT_ONLY_10_4_FONTS 1
  228068. #endif
  228069. END_JUCE_NAMESPACE
  228070. @interface NSFont (PrivateHack)
  228071. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  228072. @end
  228073. BEGIN_JUCE_NAMESPACE
  228074. #endif
  228075. class MacTypeface : public Typeface
  228076. {
  228077. public:
  228078. MacTypeface (const Font& font)
  228079. : Typeface (font.getTypefaceName())
  228080. {
  228081. const ScopedAutoReleasePool pool;
  228082. renderingTransform = CGAffineTransformIdentity;
  228083. bool needsItalicTransform = false;
  228084. #if JUCE_IPHONE
  228085. NSString* fontName = juceStringToNS (font.getTypefaceName());
  228086. if (font.isItalic() || font.isBold())
  228087. {
  228088. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  228089. for (NSString* i in familyFonts)
  228090. {
  228091. const String fn (nsStringToJuce (i));
  228092. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  228093. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  228094. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  228095. || afterDash.containsIgnoreCase ("italic")
  228096. || fn.endsWithIgnoreCase ("oblique")
  228097. || fn.endsWithIgnoreCase ("italic");
  228098. if (probablyBold == font.isBold()
  228099. && probablyItalic == font.isItalic())
  228100. {
  228101. fontName = i;
  228102. needsItalicTransform = false;
  228103. break;
  228104. }
  228105. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  228106. {
  228107. fontName = i;
  228108. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  228109. }
  228110. }
  228111. if (needsItalicTransform)
  228112. renderingTransform.c = 0.15f;
  228113. }
  228114. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  228115. const int ascender = abs (CGFontGetAscent (fontRef));
  228116. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  228117. ascent = ascender / totalHeight;
  228118. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228119. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  228120. #else
  228121. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  228122. if (font.isItalic())
  228123. {
  228124. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  228125. toHaveTrait: NSItalicFontMask];
  228126. if (newFont == nsFont)
  228127. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  228128. nsFont = newFont;
  228129. }
  228130. if (font.isBold())
  228131. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  228132. [nsFont retain];
  228133. ascent = std::abs ((float) [nsFont ascender]);
  228134. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  228135. ascent /= totalSize;
  228136. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  228137. if (needsItalicTransform)
  228138. {
  228139. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  228140. renderingTransform.c = 0.15f;
  228141. }
  228142. #if SUPPORT_ONLY_10_4_FONTS
  228143. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228144. if (atsFont == 0)
  228145. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228146. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228147. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228148. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228149. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228150. #else
  228151. #if SUPPORT_10_4_FONTS
  228152. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228153. {
  228154. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228155. if (atsFont == 0)
  228156. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228157. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228158. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228159. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228160. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228161. }
  228162. else
  228163. #endif
  228164. {
  228165. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  228166. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  228167. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228168. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  228169. }
  228170. #endif
  228171. #endif
  228172. }
  228173. ~MacTypeface()
  228174. {
  228175. #if ! JUCE_IPHONE
  228176. [nsFont release];
  228177. #endif
  228178. if (fontRef != 0)
  228179. CGFontRelease (fontRef);
  228180. }
  228181. float getAscent() const
  228182. {
  228183. return ascent;
  228184. }
  228185. float getDescent() const
  228186. {
  228187. return 1.0f - ascent;
  228188. }
  228189. float getStringWidth (const String& text)
  228190. {
  228191. if (fontRef == 0 || text.isEmpty())
  228192. return 0;
  228193. const int length = text.length();
  228194. HeapBlock <CGGlyph> glyphs;
  228195. createGlyphsForString (text, length, glyphs);
  228196. float x = 0;
  228197. #if SUPPORT_ONLY_10_4_FONTS
  228198. HeapBlock <NSSize> advances (length);
  228199. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228200. for (int i = 0; i < length; ++i)
  228201. x += advances[i].width;
  228202. #else
  228203. #if SUPPORT_10_4_FONTS
  228204. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228205. {
  228206. HeapBlock <NSSize> advances (length);
  228207. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  228208. for (int i = 0; i < length; ++i)
  228209. x += advances[i].width;
  228210. }
  228211. else
  228212. #endif
  228213. {
  228214. HeapBlock <int> advances (length);
  228215. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228216. for (int i = 0; i < length; ++i)
  228217. x += advances[i];
  228218. }
  228219. #endif
  228220. return x * unitsToHeightScaleFactor;
  228221. }
  228222. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  228223. {
  228224. xOffsets.add (0);
  228225. if (fontRef == 0 || text.isEmpty())
  228226. return;
  228227. const int length = text.length();
  228228. HeapBlock <CGGlyph> glyphs;
  228229. createGlyphsForString (text, length, glyphs);
  228230. #if SUPPORT_ONLY_10_4_FONTS
  228231. HeapBlock <NSSize> advances (length);
  228232. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228233. int x = 0;
  228234. for (int i = 0; i < length; ++i)
  228235. {
  228236. x += advances[i].width;
  228237. xOffsets.add (x * unitsToHeightScaleFactor);
  228238. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  228239. }
  228240. #else
  228241. #if SUPPORT_10_4_FONTS
  228242. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228243. {
  228244. HeapBlock <NSSize> advances (length);
  228245. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228246. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  228247. float x = 0;
  228248. for (int i = 0; i < length; ++i)
  228249. {
  228250. x += advances[i].width;
  228251. xOffsets.add (x * unitsToHeightScaleFactor);
  228252. resultGlyphs.add (nsGlyphs[i]);
  228253. }
  228254. }
  228255. else
  228256. #endif
  228257. {
  228258. HeapBlock <int> advances (length);
  228259. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228260. {
  228261. int x = 0;
  228262. for (int i = 0; i < length; ++i)
  228263. {
  228264. x += advances [i];
  228265. xOffsets.add (x * unitsToHeightScaleFactor);
  228266. resultGlyphs.add (glyphs[i]);
  228267. }
  228268. }
  228269. }
  228270. #endif
  228271. }
  228272. bool getOutlineForGlyph (int glyphNumber, Path& path)
  228273. {
  228274. #if JUCE_IPHONE
  228275. return false;
  228276. #else
  228277. if (nsFont == 0)
  228278. return false;
  228279. // we might need to apply a transform to the path, so it mustn't have anything else in it
  228280. jassert (path.isEmpty());
  228281. const ScopedAutoReleasePool pool;
  228282. NSBezierPath* bez = [NSBezierPath bezierPath];
  228283. [bez moveToPoint: NSMakePoint (0, 0)];
  228284. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  228285. inFont: nsFont];
  228286. for (int i = 0; i < [bez elementCount]; ++i)
  228287. {
  228288. NSPoint p[3];
  228289. switch ([bez elementAtIndex: i associatedPoints: p])
  228290. {
  228291. case NSMoveToBezierPathElement:
  228292. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  228293. break;
  228294. case NSLineToBezierPathElement:
  228295. path.lineTo ((float) p[0].x, (float) -p[0].y);
  228296. break;
  228297. case NSCurveToBezierPathElement:
  228298. path.cubicTo ((float) p[0].x, (float) -p[0].y, (float) p[1].x, (float) -p[1].y, (float) p[2].x, (float) -p[2].y);
  228299. break;
  228300. case NSClosePathBezierPathElement:
  228301. path.closeSubPath();
  228302. break;
  228303. default:
  228304. jassertfalse;
  228305. break;
  228306. }
  228307. }
  228308. path.applyTransform (pathTransform);
  228309. return true;
  228310. #endif
  228311. }
  228312. juce_UseDebuggingNewOperator
  228313. CGFontRef fontRef;
  228314. float fontHeightToCGSizeFactor;
  228315. CGAffineTransform renderingTransform;
  228316. private:
  228317. float ascent, unitsToHeightScaleFactor;
  228318. #if JUCE_IPHONE
  228319. #else
  228320. NSFont* nsFont;
  228321. AffineTransform pathTransform;
  228322. #endif
  228323. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  228324. {
  228325. #if SUPPORT_10_4_FONTS
  228326. #if ! SUPPORT_ONLY_10_4_FONTS
  228327. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228328. #endif
  228329. {
  228330. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  228331. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228332. for (int i = 0; i < length; ++i)
  228333. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  228334. return;
  228335. }
  228336. #endif
  228337. #if ! SUPPORT_ONLY_10_4_FONTS
  228338. if (charToGlyphMapper == 0)
  228339. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  228340. glyphs.malloc (length);
  228341. for (int i = 0; i < length; ++i)
  228342. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  228343. #endif
  228344. }
  228345. #if ! SUPPORT_ONLY_10_4_FONTS
  228346. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  228347. class CharToGlyphMapper
  228348. {
  228349. public:
  228350. CharToGlyphMapper (CGFontRef fontRef)
  228351. : segCount (0), endCode (0), startCode (0), idDelta (0),
  228352. idRangeOffset (0), glyphIndexes (0)
  228353. {
  228354. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  228355. if (cmapTable != 0)
  228356. {
  228357. const int numSubtables = getValue16 (cmapTable, 2);
  228358. for (int i = 0; i < numSubtables; ++i)
  228359. {
  228360. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  228361. {
  228362. const int offset = getValue32 (cmapTable, i * 8 + 8);
  228363. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  228364. {
  228365. const int length = getValue16 (cmapTable, offset + 2);
  228366. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  228367. segCount = segCountX2 / 2;
  228368. const int endCodeOffset = offset + 14;
  228369. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  228370. const int idDeltaOffset = startCodeOffset + segCountX2;
  228371. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  228372. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  228373. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  228374. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  228375. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  228376. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  228377. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  228378. }
  228379. break;
  228380. }
  228381. }
  228382. CFRelease (cmapTable);
  228383. }
  228384. }
  228385. ~CharToGlyphMapper()
  228386. {
  228387. if (endCode != 0)
  228388. {
  228389. CFRelease (endCode);
  228390. CFRelease (startCode);
  228391. CFRelease (idDelta);
  228392. CFRelease (idRangeOffset);
  228393. CFRelease (glyphIndexes);
  228394. }
  228395. }
  228396. int getGlyphForCharacter (const juce_wchar c) const
  228397. {
  228398. for (int i = 0; i < segCount; ++i)
  228399. {
  228400. if (getValue16 (endCode, i * 2) >= c)
  228401. {
  228402. const int start = getValue16 (startCode, i * 2);
  228403. if (start > c)
  228404. break;
  228405. const int delta = getValue16 (idDelta, i * 2);
  228406. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  228407. if (rangeOffset == 0)
  228408. return delta + c;
  228409. else
  228410. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  228411. }
  228412. }
  228413. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  228414. return jmax (-1, c - 29);
  228415. }
  228416. private:
  228417. int segCount;
  228418. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  228419. static uint16 getValue16 (CFDataRef data, const int index)
  228420. {
  228421. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  228422. }
  228423. static uint32 getValue32 (CFDataRef data, const int index)
  228424. {
  228425. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  228426. }
  228427. };
  228428. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  228429. #endif
  228430. MacTypeface (const MacTypeface&);
  228431. MacTypeface& operator= (const MacTypeface&);
  228432. };
  228433. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  228434. {
  228435. return new MacTypeface (font);
  228436. }
  228437. const StringArray Font::findAllTypefaceNames()
  228438. {
  228439. StringArray names;
  228440. const ScopedAutoReleasePool pool;
  228441. #if JUCE_IPHONE
  228442. NSArray* fonts = [UIFont familyNames];
  228443. #else
  228444. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  228445. #endif
  228446. for (unsigned int i = 0; i < [fonts count]; ++i)
  228447. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  228448. names.sort (true);
  228449. return names;
  228450. }
  228451. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  228452. {
  228453. #if JUCE_IPHONE
  228454. defaultSans = "Helvetica";
  228455. defaultSerif = "Times New Roman";
  228456. defaultFixed = "Courier New";
  228457. #else
  228458. defaultSans = "Lucida Grande";
  228459. defaultSerif = "Times New Roman";
  228460. defaultFixed = "Monaco";
  228461. #endif
  228462. }
  228463. #endif
  228464. /*** End of inlined file: juce_mac_Fonts.mm ***/
  228465. // (must go before juce_mac_CoreGraphicsContext.mm)
  228466. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  228467. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228468. // compiled on its own).
  228469. #if JUCE_INCLUDED_FILE
  228470. class CoreGraphicsImage : public Image::SharedImage
  228471. {
  228472. public:
  228473. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  228474. : Image::SharedImage (format_, width_, height_)
  228475. {
  228476. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  228477. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  228478. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  228479. imageData = imageDataAllocated;
  228480. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  228481. : CGColorSpaceCreateDeviceRGB();
  228482. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  228483. colourSpace, getCGImageFlags (format_));
  228484. CGColorSpaceRelease (colourSpace);
  228485. }
  228486. ~CoreGraphicsImage()
  228487. {
  228488. CGContextRelease (context);
  228489. }
  228490. Image::ImageType getType() const { return Image::NativeImage; }
  228491. LowLevelGraphicsContext* createLowLevelContext();
  228492. SharedImage* clone()
  228493. {
  228494. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  228495. memcpy (im->imageData, imageData, lineStride * height);
  228496. return im;
  228497. }
  228498. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  228499. {
  228500. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  228501. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  228502. {
  228503. return CGBitmapContextCreateImage (nativeImage->context);
  228504. }
  228505. else
  228506. {
  228507. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  228508. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  228509. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  228510. 8, srcData.pixelStride * 8, srcData.lineStride,
  228511. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  228512. 0, true, kCGRenderingIntentDefault);
  228513. CGDataProviderRelease (provider);
  228514. return imageRef;
  228515. }
  228516. }
  228517. #if JUCE_MAC
  228518. static NSImage* createNSImage (const Image& image)
  228519. {
  228520. const ScopedAutoReleasePool pool;
  228521. NSImage* im = [[NSImage alloc] init];
  228522. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  228523. [im lockFocus];
  228524. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  228525. CGImageRef imageRef = createImage (image, false, colourSpace);
  228526. CGColorSpaceRelease (colourSpace);
  228527. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  228528. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  228529. CGImageRelease (imageRef);
  228530. [im unlockFocus];
  228531. return im;
  228532. }
  228533. #endif
  228534. CGContextRef context;
  228535. HeapBlock<uint8> imageDataAllocated;
  228536. private:
  228537. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  228538. {
  228539. #if JUCE_BIG_ENDIAN
  228540. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  228541. #else
  228542. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  228543. #endif
  228544. }
  228545. };
  228546. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  228547. {
  228548. #if USE_COREGRAPHICS_RENDERING
  228549. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  228550. #else
  228551. return createSoftwareImage (format, width, height, clearImage);
  228552. #endif
  228553. }
  228554. class CoreGraphicsContext : public LowLevelGraphicsContext
  228555. {
  228556. public:
  228557. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  228558. : context (context_),
  228559. flipHeight (flipHeight_),
  228560. state (new SavedState()),
  228561. numGradientLookupEntries (0),
  228562. lastClipRectIsValid (false)
  228563. {
  228564. CGContextRetain (context);
  228565. CGContextSaveGState(context);
  228566. CGContextSetShouldSmoothFonts (context, true);
  228567. CGContextSetShouldAntialias (context, true);
  228568. CGContextSetBlendMode (context, kCGBlendModeNormal);
  228569. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  228570. greyColourSpace = CGColorSpaceCreateDeviceGray();
  228571. gradientCallbacks.version = 0;
  228572. gradientCallbacks.evaluate = gradientCallback;
  228573. gradientCallbacks.releaseInfo = 0;
  228574. setFont (Font());
  228575. }
  228576. ~CoreGraphicsContext()
  228577. {
  228578. CGContextRestoreGState (context);
  228579. CGContextRelease (context);
  228580. CGColorSpaceRelease (rgbColourSpace);
  228581. CGColorSpaceRelease (greyColourSpace);
  228582. }
  228583. bool isVectorDevice() const { return false; }
  228584. void setOrigin (int x, int y)
  228585. {
  228586. CGContextTranslateCTM (context, x, -y);
  228587. if (lastClipRectIsValid)
  228588. lastClipRect.translate (-x, -y);
  228589. }
  228590. bool clipToRectangle (const Rectangle<int>& r)
  228591. {
  228592. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  228593. if (lastClipRectIsValid)
  228594. {
  228595. lastClipRect = lastClipRect.getIntersection (r);
  228596. return ! lastClipRect.isEmpty();
  228597. }
  228598. return ! isClipEmpty();
  228599. }
  228600. bool clipToRectangleList (const RectangleList& clipRegion)
  228601. {
  228602. if (clipRegion.isEmpty())
  228603. {
  228604. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  228605. lastClipRectIsValid = true;
  228606. lastClipRect = Rectangle<int>();
  228607. return false;
  228608. }
  228609. else
  228610. {
  228611. const int numRects = clipRegion.getNumRectangles();
  228612. HeapBlock <CGRect> rects (numRects);
  228613. for (int i = 0; i < numRects; ++i)
  228614. {
  228615. const Rectangle<int>& r = clipRegion.getRectangle(i);
  228616. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  228617. }
  228618. CGContextClipToRects (context, rects, numRects);
  228619. lastClipRectIsValid = false;
  228620. return ! isClipEmpty();
  228621. }
  228622. }
  228623. void excludeClipRectangle (const Rectangle<int>& r)
  228624. {
  228625. RectangleList remaining (getClipBounds());
  228626. remaining.subtract (r);
  228627. clipToRectangleList (remaining);
  228628. lastClipRectIsValid = false;
  228629. }
  228630. void clipToPath (const Path& path, const AffineTransform& transform)
  228631. {
  228632. createPath (path, transform);
  228633. CGContextClip (context);
  228634. lastClipRectIsValid = false;
  228635. }
  228636. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  228637. {
  228638. if (! transform.isSingularity())
  228639. {
  228640. Image singleChannelImage (sourceImage);
  228641. if (sourceImage.getFormat() != Image::SingleChannel)
  228642. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  228643. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  228644. if (srcClip != sourceImage.getBounds())
  228645. {
  228646. CGImageRef fullImage = image;
  228647. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  228648. srcClip.getWidth(), srcClip.getHeight()));
  228649. CGImageRelease (fullImage);
  228650. }
  228651. flip();
  228652. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  228653. applyTransform (t);
  228654. CGRect r = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  228655. CGContextClipToMask (context, r, image);
  228656. applyTransform (t.inverted());
  228657. flip();
  228658. CGImageRelease (image);
  228659. lastClipRectIsValid = false;
  228660. }
  228661. }
  228662. bool clipRegionIntersects (const Rectangle<int>& r)
  228663. {
  228664. return getClipBounds().intersects (r);
  228665. }
  228666. const Rectangle<int> getClipBounds() const
  228667. {
  228668. if (! lastClipRectIsValid)
  228669. {
  228670. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  228671. lastClipRectIsValid = true;
  228672. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  228673. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  228674. roundToInt (bounds.size.width),
  228675. roundToInt (bounds.size.height));
  228676. }
  228677. return lastClipRect;
  228678. }
  228679. bool isClipEmpty() const
  228680. {
  228681. return getClipBounds().isEmpty();
  228682. }
  228683. void saveState()
  228684. {
  228685. CGContextSaveGState (context);
  228686. stateStack.add (new SavedState (*state));
  228687. }
  228688. void restoreState()
  228689. {
  228690. CGContextRestoreGState (context);
  228691. SavedState* const top = stateStack.getLast();
  228692. if (top != 0)
  228693. {
  228694. state = top;
  228695. stateStack.removeLast (1, false);
  228696. lastClipRectIsValid = false;
  228697. }
  228698. else
  228699. {
  228700. jassertfalse; // trying to pop with an empty stack!
  228701. }
  228702. }
  228703. void setFill (const FillType& fillType)
  228704. {
  228705. state->fillType = fillType;
  228706. if (fillType.isColour())
  228707. {
  228708. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  228709. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  228710. CGContextSetAlpha (context, 1.0f);
  228711. }
  228712. }
  228713. void setOpacity (float newOpacity)
  228714. {
  228715. state->fillType.setOpacity (newOpacity);
  228716. setFill (state->fillType);
  228717. }
  228718. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  228719. {
  228720. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  228721. ? kCGInterpolationLow
  228722. : kCGInterpolationHigh);
  228723. }
  228724. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  228725. {
  228726. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  228727. if (replaceExistingContents)
  228728. {
  228729. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228730. CGContextClearRect (context, cgRect);
  228731. #else
  228732. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228733. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  228734. CGContextClearRect (context, cgRect);
  228735. else
  228736. #endif
  228737. CGContextSetBlendMode (context, kCGBlendModeCopy);
  228738. #endif
  228739. fillRect (r, false);
  228740. CGContextSetBlendMode (context, kCGBlendModeNormal);
  228741. }
  228742. else
  228743. {
  228744. if (state->fillType.isColour())
  228745. {
  228746. CGContextFillRect (context, cgRect);
  228747. }
  228748. else if (state->fillType.isGradient())
  228749. {
  228750. CGContextSaveGState (context);
  228751. CGContextClipToRect (context, cgRect);
  228752. drawGradient();
  228753. CGContextRestoreGState (context);
  228754. }
  228755. else
  228756. {
  228757. CGContextSaveGState (context);
  228758. CGContextClipToRect (context, cgRect);
  228759. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  228760. CGContextRestoreGState (context);
  228761. }
  228762. }
  228763. }
  228764. void fillPath (const Path& path, const AffineTransform& transform)
  228765. {
  228766. CGContextSaveGState (context);
  228767. if (state->fillType.isColour())
  228768. {
  228769. flip();
  228770. applyTransform (transform);
  228771. createPath (path);
  228772. if (path.isUsingNonZeroWinding())
  228773. CGContextFillPath (context);
  228774. else
  228775. CGContextEOFillPath (context);
  228776. }
  228777. else
  228778. {
  228779. createPath (path, transform);
  228780. if (path.isUsingNonZeroWinding())
  228781. CGContextClip (context);
  228782. else
  228783. CGContextEOClip (context);
  228784. if (state->fillType.isGradient())
  228785. drawGradient();
  228786. else
  228787. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  228788. }
  228789. CGContextRestoreGState (context);
  228790. }
  228791. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  228792. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  228793. {
  228794. jassert (sourceImage.getBounds().contains (srcClip));
  228795. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  228796. CGImageRef image = fullImage;
  228797. if (srcClip != sourceImage.getBounds())
  228798. {
  228799. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  228800. srcClip.getWidth(), srcClip.getHeight()));
  228801. CGImageRelease (fullImage);
  228802. }
  228803. CGContextSaveGState (context);
  228804. CGContextSetAlpha (context, state->fillType.getOpacity());
  228805. flip();
  228806. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  228807. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  228808. if (fillEntireClipAsTiles)
  228809. {
  228810. #if JUCE_IPHONE
  228811. CGContextDrawTiledImage (context, imageRect, image);
  228812. #else
  228813. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  228814. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  228815. // if it's doing a transformation - it's quicker to just draw lots of images manually
  228816. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  228817. CGContextDrawTiledImage (context, imageRect, image);
  228818. else
  228819. #endif
  228820. {
  228821. // Fallback to manually doing a tiled fill on 10.4
  228822. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  228823. const int iw = srcClip.getWidth();
  228824. const int ih = srcClip.getHeight();
  228825. int x = 0, y = 0;
  228826. while (x > clip.origin.x) x -= iw;
  228827. while (y > clip.origin.y) y -= ih;
  228828. const int right = (int) (clip.origin.x + clip.size.width);
  228829. const int bottom = (int) (clip.origin.y + clip.size.height);
  228830. while (y < bottom)
  228831. {
  228832. for (int x2 = x; x2 < right; x2 += iw)
  228833. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  228834. y += ih;
  228835. }
  228836. }
  228837. #endif
  228838. }
  228839. else
  228840. {
  228841. CGContextDrawImage (context, imageRect, image);
  228842. }
  228843. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  228844. CGContextRestoreGState (context);
  228845. }
  228846. void drawLine (const Line<float>& line)
  228847. {
  228848. CGContextSetLineCap (context, kCGLineCapSquare);
  228849. CGContextSetLineWidth (context, 1.0f);
  228850. CGContextSetRGBStrokeColor (context,
  228851. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  228852. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  228853. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  228854. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  228855. CGContextStrokeLineSegments (context, cgLine, 1);
  228856. }
  228857. void drawVerticalLine (const int x, float top, float bottom)
  228858. {
  228859. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  228860. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  228861. #else
  228862. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  228863. // the x co-ord slightly to trick it..
  228864. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  228865. #endif
  228866. }
  228867. void drawHorizontalLine (const int y, float left, float right)
  228868. {
  228869. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  228870. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  228871. #else
  228872. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  228873. // the x co-ord slightly to trick it..
  228874. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  228875. #endif
  228876. }
  228877. void setFont (const Font& newFont)
  228878. {
  228879. if (state->font != newFont)
  228880. {
  228881. state->fontRef = 0;
  228882. state->font = newFont;
  228883. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  228884. if (mf != 0)
  228885. {
  228886. state->fontRef = mf->fontRef;
  228887. CGContextSetFont (context, state->fontRef);
  228888. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  228889. state->fontTransform = mf->renderingTransform;
  228890. state->fontTransform.a *= state->font.getHorizontalScale();
  228891. CGContextSetTextMatrix (context, state->fontTransform);
  228892. }
  228893. }
  228894. }
  228895. const Font getFont()
  228896. {
  228897. return state->font;
  228898. }
  228899. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  228900. {
  228901. if (state->fontRef != 0 && state->fillType.isColour())
  228902. {
  228903. if (transform.isOnlyTranslation())
  228904. {
  228905. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  228906. CGGlyph g = glyphNumber;
  228907. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  228908. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  228909. }
  228910. else
  228911. {
  228912. CGContextSaveGState (context);
  228913. flip();
  228914. applyTransform (transform);
  228915. CGAffineTransform t = state->fontTransform;
  228916. t.d = -t.d;
  228917. CGContextSetTextMatrix (context, t);
  228918. CGGlyph g = glyphNumber;
  228919. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  228920. CGContextRestoreGState (context);
  228921. }
  228922. }
  228923. else
  228924. {
  228925. Path p;
  228926. Font& f = state->font;
  228927. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  228928. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  228929. .followedBy (transform));
  228930. }
  228931. }
  228932. private:
  228933. CGContextRef context;
  228934. const CGFloat flipHeight;
  228935. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  228936. CGFunctionCallbacks gradientCallbacks;
  228937. mutable Rectangle<int> lastClipRect;
  228938. mutable bool lastClipRectIsValid;
  228939. struct SavedState
  228940. {
  228941. SavedState()
  228942. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  228943. {
  228944. }
  228945. SavedState (const SavedState& other)
  228946. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  228947. fontTransform (other.fontTransform)
  228948. {
  228949. }
  228950. ~SavedState()
  228951. {
  228952. }
  228953. FillType fillType;
  228954. Font font;
  228955. CGFontRef fontRef;
  228956. CGAffineTransform fontTransform;
  228957. };
  228958. ScopedPointer <SavedState> state;
  228959. OwnedArray <SavedState> stateStack;
  228960. HeapBlock <PixelARGB> gradientLookupTable;
  228961. int numGradientLookupEntries;
  228962. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  228963. {
  228964. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  228965. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  228966. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  228967. colour.unpremultiply();
  228968. outData[0] = colour.getRed() / 255.0f;
  228969. outData[1] = colour.getGreen() / 255.0f;
  228970. outData[2] = colour.getBlue() / 255.0f;
  228971. outData[3] = colour.getAlpha() / 255.0f;
  228972. }
  228973. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  228974. {
  228975. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  228976. --numGradientLookupEntries;
  228977. CGShadingRef result = 0;
  228978. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  228979. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  228980. if (gradient.isRadial)
  228981. {
  228982. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  228983. p1, gradient.point1.getDistanceFrom (gradient.point2),
  228984. function, true, true);
  228985. }
  228986. else
  228987. {
  228988. result = CGShadingCreateAxial (rgbColourSpace, p1,
  228989. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  228990. function, true, true);
  228991. }
  228992. CGFunctionRelease (function);
  228993. return result;
  228994. }
  228995. void drawGradient()
  228996. {
  228997. flip();
  228998. applyTransform (state->fillType.transform);
  228999. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  229000. // you draw a gradient with high quality interp enabled).
  229001. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  229002. CGContextSetAlpha (context, state->fillType.getOpacity());
  229003. CGContextDrawShading (context, shading);
  229004. CGShadingRelease (shading);
  229005. }
  229006. void createPath (const Path& path) const
  229007. {
  229008. CGContextBeginPath (context);
  229009. Path::Iterator i (path);
  229010. while (i.next())
  229011. {
  229012. switch (i.elementType)
  229013. {
  229014. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  229015. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  229016. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  229017. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  229018. case Path::Iterator::closePath: CGContextClosePath (context); break;
  229019. default: jassertfalse; break;
  229020. }
  229021. }
  229022. }
  229023. void createPath (const Path& path, const AffineTransform& transform) const
  229024. {
  229025. CGContextBeginPath (context);
  229026. Path::Iterator i (path);
  229027. while (i.next())
  229028. {
  229029. switch (i.elementType)
  229030. {
  229031. case Path::Iterator::startNewSubPath:
  229032. transform.transformPoint (i.x1, i.y1);
  229033. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  229034. break;
  229035. case Path::Iterator::lineTo:
  229036. transform.transformPoint (i.x1, i.y1);
  229037. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  229038. break;
  229039. case Path::Iterator::quadraticTo:
  229040. transform.transformPoint (i.x1, i.y1);
  229041. transform.transformPoint (i.x2, i.y2);
  229042. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  229043. break;
  229044. case Path::Iterator::cubicTo:
  229045. transform.transformPoint (i.x1, i.y1);
  229046. transform.transformPoint (i.x2, i.y2);
  229047. transform.transformPoint (i.x3, i.y3);
  229048. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  229049. break;
  229050. case Path::Iterator::closePath:
  229051. CGContextClosePath (context); break;
  229052. default:
  229053. jassertfalse;
  229054. break;
  229055. }
  229056. }
  229057. }
  229058. void flip() const
  229059. {
  229060. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  229061. }
  229062. void applyTransform (const AffineTransform& transform) const
  229063. {
  229064. CGAffineTransform t;
  229065. t.a = transform.mat00;
  229066. t.b = transform.mat10;
  229067. t.c = transform.mat01;
  229068. t.d = transform.mat11;
  229069. t.tx = transform.mat02;
  229070. t.ty = transform.mat12;
  229071. CGContextConcatCTM (context, t);
  229072. }
  229073. CoreGraphicsContext (const CoreGraphicsContext&);
  229074. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  229075. };
  229076. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  229077. {
  229078. return new CoreGraphicsContext (context, height);
  229079. }
  229080. #endif
  229081. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229082. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  229083. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229084. // compiled on its own).
  229085. #if JUCE_INCLUDED_FILE
  229086. class NSViewComponentPeer;
  229087. END_JUCE_NAMESPACE
  229088. #define JuceNSView MakeObjCClassName(JuceNSView)
  229089. @interface JuceNSView : NSView<NSTextInput>
  229090. {
  229091. @public
  229092. NSViewComponentPeer* owner;
  229093. NSNotificationCenter* notificationCenter;
  229094. String* stringBeingComposed;
  229095. bool textWasInserted;
  229096. }
  229097. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  229098. - (void) dealloc;
  229099. - (BOOL) isOpaque;
  229100. - (void) drawRect: (NSRect) r;
  229101. - (void) mouseDown: (NSEvent*) ev;
  229102. - (void) asyncMouseDown: (NSEvent*) ev;
  229103. - (void) mouseUp: (NSEvent*) ev;
  229104. - (void) asyncMouseUp: (NSEvent*) ev;
  229105. - (void) mouseDragged: (NSEvent*) ev;
  229106. - (void) mouseMoved: (NSEvent*) ev;
  229107. - (void) mouseEntered: (NSEvent*) ev;
  229108. - (void) mouseExited: (NSEvent*) ev;
  229109. - (void) rightMouseDown: (NSEvent*) ev;
  229110. - (void) rightMouseDragged: (NSEvent*) ev;
  229111. - (void) rightMouseUp: (NSEvent*) ev;
  229112. - (void) otherMouseDown: (NSEvent*) ev;
  229113. - (void) otherMouseDragged: (NSEvent*) ev;
  229114. - (void) otherMouseUp: (NSEvent*) ev;
  229115. - (void) scrollWheel: (NSEvent*) ev;
  229116. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  229117. - (void) frameChanged: (NSNotification*) n;
  229118. - (void) viewDidMoveToWindow;
  229119. - (void) keyDown: (NSEvent*) ev;
  229120. - (void) keyUp: (NSEvent*) ev;
  229121. // NSTextInput Methods
  229122. - (void) insertText: (id) aString;
  229123. - (void) doCommandBySelector: (SEL) aSelector;
  229124. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  229125. - (void) unmarkText;
  229126. - (BOOL) hasMarkedText;
  229127. - (long) conversationIdentifier;
  229128. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  229129. - (NSRange) markedRange;
  229130. - (NSRange) selectedRange;
  229131. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  229132. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint;
  229133. - (NSArray*) validAttributesForMarkedText;
  229134. - (void) flagsChanged: (NSEvent*) ev;
  229135. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229136. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  229137. #endif
  229138. - (BOOL) becomeFirstResponder;
  229139. - (BOOL) resignFirstResponder;
  229140. - (BOOL) acceptsFirstResponder;
  229141. - (void) asyncRepaint: (id) rect;
  229142. - (NSArray*) getSupportedDragTypes;
  229143. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  229144. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  229145. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  229146. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  229147. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  229148. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  229149. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  229150. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  229151. @end
  229152. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  229153. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229154. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  229155. #else
  229156. @interface JuceNSWindow : NSWindow
  229157. #endif
  229158. {
  229159. @private
  229160. NSViewComponentPeer* owner;
  229161. bool isZooming;
  229162. }
  229163. - (void) setOwner: (NSViewComponentPeer*) owner;
  229164. - (BOOL) canBecomeKeyWindow;
  229165. - (void) becomeKeyWindow;
  229166. - (BOOL) windowShouldClose: (id) window;
  229167. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  229168. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  229169. - (void) zoom: (id) sender;
  229170. @end
  229171. BEGIN_JUCE_NAMESPACE
  229172. class NSViewComponentPeer : public ComponentPeer
  229173. {
  229174. public:
  229175. NSViewComponentPeer (Component* const component,
  229176. const int windowStyleFlags,
  229177. NSView* viewToAttachTo);
  229178. ~NSViewComponentPeer();
  229179. void* getNativeHandle() const;
  229180. void setVisible (bool shouldBeVisible);
  229181. void setTitle (const String& title);
  229182. void setPosition (int x, int y);
  229183. void setSize (int w, int h);
  229184. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  229185. const Rectangle<int> getBounds (const bool global) const;
  229186. const Rectangle<int> getBounds() const;
  229187. const Point<int> getScreenPosition() const;
  229188. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  229189. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  229190. void setMinimised (bool shouldBeMinimised);
  229191. bool isMinimised() const;
  229192. void setFullScreen (bool shouldBeFullScreen);
  229193. bool isFullScreen() const;
  229194. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  229195. const BorderSize getFrameSize() const;
  229196. bool setAlwaysOnTop (bool alwaysOnTop);
  229197. void toFront (bool makeActiveWindow);
  229198. void toBehind (ComponentPeer* other);
  229199. void setIcon (const Image& newIcon);
  229200. const StringArray getAvailableRenderingEngines() throw();
  229201. int getCurrentRenderingEngine() throw();
  229202. void setCurrentRenderingEngine (int index) throw();
  229203. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  229204. for example having more than one juce plugin loaded into a host, then when a
  229205. method is called, the actual code that runs might actually be in a different module
  229206. than the one you expect... So any calls to library functions or statics that are
  229207. made inside obj-c methods will probably end up getting executed in a different DLL's
  229208. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  229209. To work around this insanity, I'm only allowing obj-c methods to make calls to
  229210. virtual methods of an object that's known to live inside the right module's space.
  229211. */
  229212. virtual void redirectMouseDown (NSEvent* ev);
  229213. virtual void redirectMouseUp (NSEvent* ev);
  229214. virtual void redirectMouseDrag (NSEvent* ev);
  229215. virtual void redirectMouseMove (NSEvent* ev);
  229216. virtual void redirectMouseEnter (NSEvent* ev);
  229217. virtual void redirectMouseExit (NSEvent* ev);
  229218. virtual void redirectMouseWheel (NSEvent* ev);
  229219. void sendMouseEvent (NSEvent* ev);
  229220. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  229221. virtual bool redirectKeyDown (NSEvent* ev);
  229222. virtual bool redirectKeyUp (NSEvent* ev);
  229223. virtual void redirectModKeyChange (NSEvent* ev);
  229224. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229225. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  229226. #endif
  229227. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  229228. virtual bool isOpaque();
  229229. virtual void drawRect (NSRect r);
  229230. virtual bool canBecomeKeyWindow();
  229231. virtual bool windowShouldClose();
  229232. virtual void redirectMovedOrResized();
  229233. virtual void viewMovedToWindow();
  229234. virtual NSRect constrainRect (NSRect r);
  229235. static void showArrowCursorIfNeeded();
  229236. static void updateModifiers (NSEvent* e);
  229237. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  229238. static int getKeyCodeFromEvent (NSEvent* ev)
  229239. {
  229240. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  229241. int keyCode = unmodified[0];
  229242. if (keyCode == 0x19) // (backwards-tab)
  229243. keyCode = '\t';
  229244. else if (keyCode == 0x03) // (enter)
  229245. keyCode = '\r';
  229246. return keyCode;
  229247. }
  229248. static int64 getMouseTime (NSEvent* e)
  229249. {
  229250. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  229251. + (int64) ([e timestamp] * 1000.0);
  229252. }
  229253. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  229254. {
  229255. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  229256. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  229257. }
  229258. static int getModifierForButtonNumber (const NSInteger num)
  229259. {
  229260. return num == 0 ? ModifierKeys::leftButtonModifier
  229261. : (num == 1 ? ModifierKeys::rightButtonModifier
  229262. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  229263. }
  229264. virtual void viewFocusGain();
  229265. virtual void viewFocusLoss();
  229266. bool isFocused() const;
  229267. void grabFocus();
  229268. void textInputRequired (const Point<int>& position);
  229269. void repaint (const Rectangle<int>& area);
  229270. void performAnyPendingRepaintsNow();
  229271. juce_UseDebuggingNewOperator
  229272. NSWindow* window;
  229273. JuceNSView* view;
  229274. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  229275. static ModifierKeys currentModifiers;
  229276. static ComponentPeer* currentlyFocusedPeer;
  229277. static Array<int> keysCurrentlyDown;
  229278. };
  229279. END_JUCE_NAMESPACE
  229280. @implementation JuceNSView
  229281. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  229282. withFrame: (NSRect) frame
  229283. {
  229284. [super initWithFrame: frame];
  229285. owner = owner_;
  229286. stringBeingComposed = 0;
  229287. textWasInserted = false;
  229288. notificationCenter = [NSNotificationCenter defaultCenter];
  229289. [notificationCenter addObserver: self
  229290. selector: @selector (frameChanged:)
  229291. name: NSViewFrameDidChangeNotification
  229292. object: self];
  229293. if (! owner_->isSharedWindow)
  229294. {
  229295. [notificationCenter addObserver: self
  229296. selector: @selector (frameChanged:)
  229297. name: NSWindowDidMoveNotification
  229298. object: owner_->window];
  229299. }
  229300. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  229301. return self;
  229302. }
  229303. - (void) dealloc
  229304. {
  229305. [notificationCenter removeObserver: self];
  229306. delete stringBeingComposed;
  229307. [super dealloc];
  229308. }
  229309. - (void) drawRect: (NSRect) r
  229310. {
  229311. if (owner != 0)
  229312. owner->drawRect (r);
  229313. }
  229314. - (BOOL) isOpaque
  229315. {
  229316. return owner == 0 || owner->isOpaque();
  229317. }
  229318. - (void) mouseDown: (NSEvent*) ev
  229319. {
  229320. // In some host situations, the host will stop modal loops from working
  229321. // correctly if they're called from a mouse event, so we'll trigger
  229322. // the event asynchronously..
  229323. if (JUCEApplication::getInstance() == 0)
  229324. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  229325. withObject: ev
  229326. waitUntilDone: NO];
  229327. else
  229328. [self asyncMouseDown: ev];
  229329. }
  229330. - (void) asyncMouseDown: (NSEvent*) ev
  229331. {
  229332. if (owner != 0)
  229333. owner->redirectMouseDown (ev);
  229334. }
  229335. - (void) mouseUp: (NSEvent*) ev
  229336. {
  229337. // In some host situations, the host will stop modal loops from working
  229338. // correctly if they're called from a mouse event, so we'll trigger
  229339. // the event asynchronously..
  229340. if (JUCEApplication::getInstance() == 0)
  229341. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  229342. withObject: ev
  229343. waitUntilDone: NO];
  229344. else
  229345. [self asyncMouseUp: ev];
  229346. }
  229347. - (void) asyncMouseUp: (NSEvent*) ev
  229348. {
  229349. if (owner != 0)
  229350. owner->redirectMouseUp (ev);
  229351. }
  229352. - (void) mouseDragged: (NSEvent*) ev
  229353. {
  229354. if (owner != 0)
  229355. owner->redirectMouseDrag (ev);
  229356. }
  229357. - (void) mouseMoved: (NSEvent*) ev
  229358. {
  229359. if (owner != 0)
  229360. owner->redirectMouseMove (ev);
  229361. }
  229362. - (void) mouseEntered: (NSEvent*) ev
  229363. {
  229364. if (owner != 0)
  229365. owner->redirectMouseEnter (ev);
  229366. }
  229367. - (void) mouseExited: (NSEvent*) ev
  229368. {
  229369. if (owner != 0)
  229370. owner->redirectMouseExit (ev);
  229371. }
  229372. - (void) rightMouseDown: (NSEvent*) ev
  229373. {
  229374. [self mouseDown: ev];
  229375. }
  229376. - (void) rightMouseDragged: (NSEvent*) ev
  229377. {
  229378. [self mouseDragged: ev];
  229379. }
  229380. - (void) rightMouseUp: (NSEvent*) ev
  229381. {
  229382. [self mouseUp: ev];
  229383. }
  229384. - (void) otherMouseDown: (NSEvent*) ev
  229385. {
  229386. [self mouseDown: ev];
  229387. }
  229388. - (void) otherMouseDragged: (NSEvent*) ev
  229389. {
  229390. [self mouseDragged: ev];
  229391. }
  229392. - (void) otherMouseUp: (NSEvent*) ev
  229393. {
  229394. [self mouseUp: ev];
  229395. }
  229396. - (void) scrollWheel: (NSEvent*) ev
  229397. {
  229398. if (owner != 0)
  229399. owner->redirectMouseWheel (ev);
  229400. }
  229401. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  229402. {
  229403. (void) ev;
  229404. return YES;
  229405. }
  229406. - (void) frameChanged: (NSNotification*) n
  229407. {
  229408. (void) n;
  229409. if (owner != 0)
  229410. owner->redirectMovedOrResized();
  229411. }
  229412. - (void) viewDidMoveToWindow
  229413. {
  229414. if (owner != 0)
  229415. owner->viewMovedToWindow();
  229416. }
  229417. - (void) asyncRepaint: (id) rect
  229418. {
  229419. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  229420. [self setNeedsDisplayInRect: *r];
  229421. }
  229422. - (void) keyDown: (NSEvent*) ev
  229423. {
  229424. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229425. textWasInserted = false;
  229426. if (target != 0)
  229427. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  229428. else
  229429. deleteAndZero (stringBeingComposed);
  229430. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  229431. [super keyDown: ev];
  229432. }
  229433. - (void) keyUp: (NSEvent*) ev
  229434. {
  229435. if (owner == 0 || ! owner->redirectKeyUp (ev))
  229436. [super keyUp: ev];
  229437. }
  229438. - (void) insertText: (id) aString
  229439. {
  229440. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  229441. if ([aString length] > 0)
  229442. {
  229443. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229444. if (target != 0)
  229445. {
  229446. target->insertTextAtCaret (nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString));
  229447. textWasInserted = true;
  229448. }
  229449. }
  229450. deleteAndZero (stringBeingComposed);
  229451. }
  229452. - (void) doCommandBySelector: (SEL) aSelector
  229453. {
  229454. (void) aSelector;
  229455. }
  229456. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  229457. {
  229458. (void) selectionRange;
  229459. if (stringBeingComposed == 0)
  229460. stringBeingComposed = new String();
  229461. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  229462. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229463. if (target != 0)
  229464. {
  229465. const Range<int> currentHighlight (target->getHighlightedRegion());
  229466. target->insertTextAtCaret (*stringBeingComposed);
  229467. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  229468. textWasInserted = true;
  229469. }
  229470. }
  229471. - (void) unmarkText
  229472. {
  229473. if (stringBeingComposed != 0)
  229474. {
  229475. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229476. if (target != 0)
  229477. {
  229478. target->insertTextAtCaret (*stringBeingComposed);
  229479. textWasInserted = true;
  229480. }
  229481. }
  229482. deleteAndZero (stringBeingComposed);
  229483. }
  229484. - (BOOL) hasMarkedText
  229485. {
  229486. return stringBeingComposed != 0;
  229487. }
  229488. - (long) conversationIdentifier
  229489. {
  229490. return (long) (pointer_sized_int) self;
  229491. }
  229492. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  229493. {
  229494. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229495. if (target != 0)
  229496. {
  229497. const Range<int> r ((int) theRange.location,
  229498. (int) (theRange.location + theRange.length));
  229499. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  229500. }
  229501. return nil;
  229502. }
  229503. - (NSRange) markedRange
  229504. {
  229505. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  229506. : NSMakeRange (NSNotFound, 0);
  229507. }
  229508. - (NSRange) selectedRange
  229509. {
  229510. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229511. if (target != 0)
  229512. {
  229513. const Range<int> highlight (target->getHighlightedRegion());
  229514. if (! highlight.isEmpty())
  229515. return NSMakeRange (highlight.getStart(), highlight.getLength());
  229516. }
  229517. return NSMakeRange (NSNotFound, 0);
  229518. }
  229519. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  229520. {
  229521. (void) theRange;
  229522. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  229523. if (comp == 0)
  229524. return NSMakeRect (0, 0, 0, 0);
  229525. const Rectangle<int> bounds (comp->getScreenBounds());
  229526. return NSMakeRect (bounds.getX(),
  229527. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  229528. bounds.getWidth(),
  229529. bounds.getHeight());
  229530. }
  229531. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint
  229532. {
  229533. (void) thePoint;
  229534. return NSNotFound;
  229535. }
  229536. - (NSArray*) validAttributesForMarkedText
  229537. {
  229538. return [NSArray array];
  229539. }
  229540. - (void) flagsChanged: (NSEvent*) ev
  229541. {
  229542. if (owner != 0)
  229543. owner->redirectModKeyChange (ev);
  229544. }
  229545. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229546. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  229547. {
  229548. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  229549. return true;
  229550. return [super performKeyEquivalent: ev];
  229551. }
  229552. #endif
  229553. - (BOOL) becomeFirstResponder
  229554. {
  229555. if (owner != 0)
  229556. owner->viewFocusGain();
  229557. return true;
  229558. }
  229559. - (BOOL) resignFirstResponder
  229560. {
  229561. if (owner != 0)
  229562. owner->viewFocusLoss();
  229563. return true;
  229564. }
  229565. - (BOOL) acceptsFirstResponder
  229566. {
  229567. return owner != 0 && owner->canBecomeKeyWindow();
  229568. }
  229569. - (NSArray*) getSupportedDragTypes
  229570. {
  229571. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  229572. }
  229573. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  229574. {
  229575. return owner != 0 && owner->sendDragCallback (type, sender);
  229576. }
  229577. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  229578. {
  229579. if ([self sendDragCallback: 0 sender: sender])
  229580. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  229581. else
  229582. return NSDragOperationNone;
  229583. }
  229584. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  229585. {
  229586. if ([self sendDragCallback: 0 sender: sender])
  229587. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  229588. else
  229589. return NSDragOperationNone;
  229590. }
  229591. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  229592. {
  229593. [self sendDragCallback: 1 sender: sender];
  229594. }
  229595. - (void) draggingExited: (id <NSDraggingInfo>) sender
  229596. {
  229597. [self sendDragCallback: 1 sender: sender];
  229598. }
  229599. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  229600. {
  229601. (void) sender;
  229602. return YES;
  229603. }
  229604. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  229605. {
  229606. return [self sendDragCallback: 2 sender: sender];
  229607. }
  229608. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  229609. {
  229610. (void) sender;
  229611. }
  229612. @end
  229613. @implementation JuceNSWindow
  229614. - (void) setOwner: (NSViewComponentPeer*) owner_
  229615. {
  229616. owner = owner_;
  229617. isZooming = false;
  229618. }
  229619. - (BOOL) canBecomeKeyWindow
  229620. {
  229621. return owner != 0 && owner->canBecomeKeyWindow();
  229622. }
  229623. - (void) becomeKeyWindow
  229624. {
  229625. [super becomeKeyWindow];
  229626. if (owner != 0)
  229627. owner->grabFocus();
  229628. }
  229629. - (BOOL) windowShouldClose: (id) window
  229630. {
  229631. (void) window;
  229632. return owner == 0 || owner->windowShouldClose();
  229633. }
  229634. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  229635. {
  229636. (void) screen;
  229637. if (owner != 0)
  229638. frameRect = owner->constrainRect (frameRect);
  229639. return frameRect;
  229640. }
  229641. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  229642. {
  229643. (void) window;
  229644. if (isZooming)
  229645. return proposedFrameSize;
  229646. NSRect frameRect = [self frame];
  229647. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  229648. frameRect.size = proposedFrameSize;
  229649. if (owner != 0)
  229650. frameRect = owner->constrainRect (frameRect);
  229651. return frameRect.size;
  229652. }
  229653. - (void) zoom: (id) sender
  229654. {
  229655. isZooming = true;
  229656. [super zoom: sender];
  229657. isZooming = false;
  229658. }
  229659. - (void) windowWillMove: (NSNotification*) notification
  229660. {
  229661. (void) notification;
  229662. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  229663. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  229664. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  229665. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  229666. }
  229667. @end
  229668. BEGIN_JUCE_NAMESPACE
  229669. ModifierKeys NSViewComponentPeer::currentModifiers;
  229670. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  229671. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  229672. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  229673. {
  229674. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  229675. return true;
  229676. if (keyCode >= 'A' && keyCode <= 'Z'
  229677. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  229678. return true;
  229679. if (keyCode >= 'a' && keyCode <= 'z'
  229680. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  229681. return true;
  229682. return false;
  229683. }
  229684. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  229685. {
  229686. int m = 0;
  229687. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  229688. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  229689. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  229690. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  229691. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  229692. }
  229693. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  229694. {
  229695. updateModifiers (ev);
  229696. int keyCode = getKeyCodeFromEvent (ev);
  229697. if (keyCode != 0)
  229698. {
  229699. if (isKeyDown)
  229700. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  229701. else
  229702. keysCurrentlyDown.removeValue (keyCode);
  229703. }
  229704. }
  229705. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  229706. {
  229707. return NSViewComponentPeer::currentModifiers;
  229708. }
  229709. void ModifierKeys::updateCurrentModifiers() throw()
  229710. {
  229711. currentModifiers = NSViewComponentPeer::currentModifiers;
  229712. }
  229713. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  229714. const int windowStyleFlags,
  229715. NSView* viewToAttachTo)
  229716. : ComponentPeer (component_, windowStyleFlags),
  229717. window (0),
  229718. view (0),
  229719. isSharedWindow (viewToAttachTo != 0),
  229720. fullScreen (false),
  229721. insideDrawRect (false),
  229722. #if USE_COREGRAPHICS_RENDERING
  229723. usingCoreGraphics (true),
  229724. #else
  229725. usingCoreGraphics (false),
  229726. #endif
  229727. recursiveToFrontCall (false)
  229728. {
  229729. NSRect r;
  229730. r.origin.x = 0;
  229731. r.origin.y = 0;
  229732. r.size.width = (float) component->getWidth();
  229733. r.size.height = (float) component->getHeight();
  229734. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  229735. [view setPostsFrameChangedNotifications: YES];
  229736. if (isSharedWindow)
  229737. {
  229738. window = [viewToAttachTo window];
  229739. [viewToAttachTo addSubview: view];
  229740. setVisible (component->isVisible());
  229741. }
  229742. else
  229743. {
  229744. r.origin.x = (float) component->getX();
  229745. r.origin.y = (float) component->getY();
  229746. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  229747. unsigned int style = 0;
  229748. if ((windowStyleFlags & windowHasTitleBar) == 0)
  229749. style = NSBorderlessWindowMask;
  229750. else
  229751. style = NSTitledWindowMask;
  229752. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  229753. style |= NSMiniaturizableWindowMask;
  229754. if ((windowStyleFlags & windowHasCloseButton) != 0)
  229755. style |= NSClosableWindowMask;
  229756. if ((windowStyleFlags & windowIsResizable) != 0)
  229757. style |= NSResizableWindowMask;
  229758. window = [[JuceNSWindow alloc] initWithContentRect: r
  229759. styleMask: style
  229760. backing: NSBackingStoreBuffered
  229761. defer: YES];
  229762. [((JuceNSWindow*) window) setOwner: this];
  229763. [window orderOut: nil];
  229764. [window setDelegate: (JuceNSWindow*) window];
  229765. [window setOpaque: component->isOpaque()];
  229766. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  229767. if (component->isAlwaysOnTop())
  229768. [window setLevel: NSFloatingWindowLevel];
  229769. [window setContentView: view];
  229770. [window setAutodisplay: YES];
  229771. [window setAcceptsMouseMovedEvents: YES];
  229772. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  229773. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  229774. [window setReleasedWhenClosed: YES];
  229775. [window retain];
  229776. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  229777. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  229778. }
  229779. setTitle (component->getName());
  229780. }
  229781. NSViewComponentPeer::~NSViewComponentPeer()
  229782. {
  229783. view->owner = 0;
  229784. [view removeFromSuperview];
  229785. [view release];
  229786. if (! isSharedWindow)
  229787. {
  229788. [((JuceNSWindow*) window) setOwner: 0];
  229789. [window close];
  229790. [window release];
  229791. }
  229792. }
  229793. void* NSViewComponentPeer::getNativeHandle() const
  229794. {
  229795. return view;
  229796. }
  229797. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  229798. {
  229799. if (isSharedWindow)
  229800. {
  229801. [view setHidden: ! shouldBeVisible];
  229802. }
  229803. else
  229804. {
  229805. if (shouldBeVisible)
  229806. {
  229807. [window orderFront: nil];
  229808. handleBroughtToFront();
  229809. }
  229810. else
  229811. {
  229812. [window orderOut: nil];
  229813. }
  229814. }
  229815. }
  229816. void NSViewComponentPeer::setTitle (const String& title)
  229817. {
  229818. const ScopedAutoReleasePool pool;
  229819. if (! isSharedWindow)
  229820. [window setTitle: juceStringToNS (title)];
  229821. }
  229822. void NSViewComponentPeer::setPosition (int x, int y)
  229823. {
  229824. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  229825. }
  229826. void NSViewComponentPeer::setSize (int w, int h)
  229827. {
  229828. setBounds (component->getX(), component->getY(), w, h, false);
  229829. }
  229830. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  229831. {
  229832. fullScreen = isNowFullScreen;
  229833. w = jmax (0, w);
  229834. h = jmax (0, h);
  229835. NSRect r;
  229836. r.origin.x = (float) x;
  229837. r.origin.y = (float) y;
  229838. r.size.width = (float) w;
  229839. r.size.height = (float) h;
  229840. if (isSharedWindow)
  229841. {
  229842. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  229843. if ([view frame].size.width != r.size.width
  229844. || [view frame].size.height != r.size.height)
  229845. [view setNeedsDisplay: true];
  229846. [view setFrame: r];
  229847. }
  229848. else
  229849. {
  229850. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  229851. [window setFrame: [window frameRectForContentRect: r]
  229852. display: true];
  229853. }
  229854. }
  229855. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  229856. {
  229857. NSRect r = [view frame];
  229858. if (global && [view window] != 0)
  229859. {
  229860. r = [view convertRect: r toView: nil];
  229861. NSRect wr = [[view window] frame];
  229862. r.origin.x += wr.origin.x;
  229863. r.origin.y += wr.origin.y;
  229864. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  229865. }
  229866. else
  229867. {
  229868. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  229869. }
  229870. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  229871. }
  229872. const Rectangle<int> NSViewComponentPeer::getBounds() const
  229873. {
  229874. return getBounds (! isSharedWindow);
  229875. }
  229876. const Point<int> NSViewComponentPeer::getScreenPosition() const
  229877. {
  229878. return getBounds (true).getPosition();
  229879. }
  229880. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  229881. {
  229882. return relativePosition + getScreenPosition();
  229883. }
  229884. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  229885. {
  229886. return screenPosition - getScreenPosition();
  229887. }
  229888. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  229889. {
  229890. if (constrainer != 0)
  229891. {
  229892. NSRect current = [window frame];
  229893. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  229894. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  229895. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  229896. (int) r.size.width, (int) r.size.height);
  229897. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  229898. (int) current.size.width, (int) current.size.height);
  229899. constrainer->checkBounds (pos, original,
  229900. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  229901. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  229902. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  229903. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  229904. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  229905. r.origin.x = pos.getX();
  229906. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  229907. r.size.width = pos.getWidth();
  229908. r.size.height = pos.getHeight();
  229909. }
  229910. return r;
  229911. }
  229912. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  229913. {
  229914. if (! isSharedWindow)
  229915. {
  229916. if (shouldBeMinimised)
  229917. [window miniaturize: nil];
  229918. else
  229919. [window deminiaturize: nil];
  229920. }
  229921. }
  229922. bool NSViewComponentPeer::isMinimised() const
  229923. {
  229924. return window != 0 && [window isMiniaturized];
  229925. }
  229926. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  229927. {
  229928. if (! isSharedWindow)
  229929. {
  229930. Rectangle<int> r (lastNonFullscreenBounds);
  229931. setMinimised (false);
  229932. if (fullScreen != shouldBeFullScreen)
  229933. {
  229934. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  229935. {
  229936. fullScreen = true;
  229937. [window performZoom: nil];
  229938. }
  229939. else
  229940. {
  229941. if (shouldBeFullScreen)
  229942. r = Desktop::getInstance().getMainMonitorArea();
  229943. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  229944. if (r != getComponent()->getBounds() && ! r.isEmpty())
  229945. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  229946. }
  229947. }
  229948. }
  229949. }
  229950. bool NSViewComponentPeer::isFullScreen() const
  229951. {
  229952. return fullScreen;
  229953. }
  229954. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  229955. {
  229956. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  229957. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  229958. return false;
  229959. NSPoint p;
  229960. p.x = (float) position.getX();
  229961. p.y = (float) position.getY();
  229962. NSView* v = [view hitTest: p];
  229963. if (trueIfInAChildWindow)
  229964. return v != nil;
  229965. return v == view;
  229966. }
  229967. const BorderSize NSViewComponentPeer::getFrameSize() const
  229968. {
  229969. BorderSize b;
  229970. if (! isSharedWindow)
  229971. {
  229972. NSRect v = [view convertRect: [view frame] toView: nil];
  229973. NSRect w = [window frame];
  229974. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  229975. b.setBottom ((int) v.origin.y);
  229976. b.setLeft ((int) v.origin.x);
  229977. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  229978. }
  229979. return b;
  229980. }
  229981. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  229982. {
  229983. if (! isSharedWindow)
  229984. {
  229985. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  229986. : NSNormalWindowLevel];
  229987. }
  229988. return true;
  229989. }
  229990. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  229991. {
  229992. if (isSharedWindow)
  229993. {
  229994. [[view superview] addSubview: view
  229995. positioned: NSWindowAbove
  229996. relativeTo: nil];
  229997. }
  229998. if (window != 0 && component->isVisible())
  229999. {
  230000. if (makeActiveWindow)
  230001. [window makeKeyAndOrderFront: nil];
  230002. else
  230003. [window orderFront: nil];
  230004. if (! recursiveToFrontCall)
  230005. {
  230006. recursiveToFrontCall = true;
  230007. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230008. handleBroughtToFront();
  230009. recursiveToFrontCall = false;
  230010. }
  230011. }
  230012. }
  230013. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  230014. {
  230015. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  230016. jassert (otherPeer != 0); // wrong type of window?
  230017. if (otherPeer != 0)
  230018. {
  230019. if (isSharedWindow)
  230020. {
  230021. [[view superview] addSubview: view
  230022. positioned: NSWindowBelow
  230023. relativeTo: otherPeer->view];
  230024. }
  230025. else
  230026. {
  230027. [window orderWindow: NSWindowBelow
  230028. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  230029. : nil ];
  230030. }
  230031. }
  230032. }
  230033. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  230034. {
  230035. // to do..
  230036. }
  230037. void NSViewComponentPeer::viewFocusGain()
  230038. {
  230039. if (currentlyFocusedPeer != this)
  230040. {
  230041. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  230042. currentlyFocusedPeer->handleFocusLoss();
  230043. currentlyFocusedPeer = this;
  230044. handleFocusGain();
  230045. }
  230046. }
  230047. void NSViewComponentPeer::viewFocusLoss()
  230048. {
  230049. if (currentlyFocusedPeer == this)
  230050. {
  230051. currentlyFocusedPeer = 0;
  230052. handleFocusLoss();
  230053. }
  230054. }
  230055. void juce_HandleProcessFocusChange()
  230056. {
  230057. NSViewComponentPeer::keysCurrentlyDown.clear();
  230058. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  230059. {
  230060. if (Process::isForegroundProcess())
  230061. {
  230062. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  230063. ComponentPeer::bringModalComponentToFront();
  230064. }
  230065. else
  230066. {
  230067. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  230068. // turn kiosk mode off if we lose focus..
  230069. Desktop::getInstance().setKioskModeComponent (0);
  230070. }
  230071. }
  230072. }
  230073. bool NSViewComponentPeer::isFocused() const
  230074. {
  230075. return isSharedWindow ? this == currentlyFocusedPeer
  230076. : (window != 0 && [window isKeyWindow]);
  230077. }
  230078. void NSViewComponentPeer::grabFocus()
  230079. {
  230080. if (window != 0)
  230081. {
  230082. [window makeKeyWindow];
  230083. [window makeFirstResponder: view];
  230084. viewFocusGain();
  230085. }
  230086. }
  230087. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  230088. {
  230089. }
  230090. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  230091. {
  230092. String unicode (nsStringToJuce ([ev characters]));
  230093. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230094. int keyCode = getKeyCodeFromEvent (ev);
  230095. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  230096. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  230097. if (unicode.isNotEmpty() || keyCode != 0)
  230098. {
  230099. if (isKeyDown)
  230100. {
  230101. bool used = false;
  230102. while (unicode.length() > 0)
  230103. {
  230104. juce_wchar textCharacter = unicode[0];
  230105. unicode = unicode.substring (1);
  230106. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230107. textCharacter = 0;
  230108. used = handleKeyUpOrDown (true) || used;
  230109. used = handleKeyPress (keyCode, textCharacter) || used;
  230110. }
  230111. return used;
  230112. }
  230113. else
  230114. {
  230115. if (handleKeyUpOrDown (false))
  230116. return true;
  230117. }
  230118. }
  230119. return false;
  230120. }
  230121. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  230122. {
  230123. updateKeysDown (ev, true);
  230124. bool used = handleKeyEvent (ev, true);
  230125. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230126. {
  230127. // for command keys, the key-up event is thrown away, so simulate one..
  230128. updateKeysDown (ev, false);
  230129. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  230130. }
  230131. // (If we're running modally, don't allow unused keystrokes to be passed
  230132. // along to other blocked views..)
  230133. if (Component::getCurrentlyModalComponent() != 0)
  230134. used = true;
  230135. return used;
  230136. }
  230137. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  230138. {
  230139. updateKeysDown (ev, false);
  230140. return handleKeyEvent (ev, false)
  230141. || Component::getCurrentlyModalComponent() != 0;
  230142. }
  230143. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  230144. {
  230145. keysCurrentlyDown.clear();
  230146. handleKeyUpOrDown (true);
  230147. updateModifiers (ev);
  230148. handleModifierKeysChange();
  230149. }
  230150. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230151. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  230152. {
  230153. if ([ev type] == NSKeyDown)
  230154. return redirectKeyDown (ev);
  230155. else if ([ev type] == NSKeyUp)
  230156. return redirectKeyUp (ev);
  230157. return false;
  230158. }
  230159. #endif
  230160. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  230161. {
  230162. updateModifiers (ev);
  230163. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  230164. }
  230165. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  230166. {
  230167. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230168. sendMouseEvent (ev);
  230169. }
  230170. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  230171. {
  230172. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230173. sendMouseEvent (ev);
  230174. showArrowCursorIfNeeded();
  230175. }
  230176. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  230177. {
  230178. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230179. sendMouseEvent (ev);
  230180. }
  230181. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  230182. {
  230183. currentModifiers = currentModifiers.withoutMouseButtons();
  230184. sendMouseEvent (ev);
  230185. showArrowCursorIfNeeded();
  230186. }
  230187. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  230188. {
  230189. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230190. currentModifiers = currentModifiers.withoutMouseButtons();
  230191. sendMouseEvent (ev);
  230192. }
  230193. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  230194. {
  230195. currentModifiers = currentModifiers.withoutMouseButtons();
  230196. sendMouseEvent (ev);
  230197. }
  230198. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  230199. {
  230200. updateModifiers (ev);
  230201. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev),
  230202. [ev deltaX] * 10.0f, [ev deltaY] * 10.0f);
  230203. }
  230204. void NSViewComponentPeer::showArrowCursorIfNeeded()
  230205. {
  230206. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  230207. if (mouse.getComponentUnderMouse() == 0
  230208. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  230209. {
  230210. [[NSCursor arrowCursor] set];
  230211. }
  230212. }
  230213. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  230214. {
  230215. NSString* bestType
  230216. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  230217. if (bestType == nil)
  230218. return false;
  230219. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  230220. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  230221. StringArray files;
  230222. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  230223. if (list == nil)
  230224. return false;
  230225. if ([list isKindOfClass: [NSArray class]])
  230226. {
  230227. NSArray* items = (NSArray*) list;
  230228. for (unsigned int i = 0; i < [items count]; ++i)
  230229. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  230230. }
  230231. if (files.size() == 0)
  230232. return false;
  230233. if (type == 0)
  230234. handleFileDragMove (files, pos);
  230235. else if (type == 1)
  230236. handleFileDragExit (files);
  230237. else if (type == 2)
  230238. handleFileDragDrop (files, pos);
  230239. return true;
  230240. }
  230241. bool NSViewComponentPeer::isOpaque()
  230242. {
  230243. return component == 0 || component->isOpaque();
  230244. }
  230245. void NSViewComponentPeer::drawRect (NSRect r)
  230246. {
  230247. if (r.size.width < 1.0f || r.size.height < 1.0f)
  230248. return;
  230249. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230250. if (! component->isOpaque())
  230251. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  230252. #if USE_COREGRAPHICS_RENDERING
  230253. if (usingCoreGraphics)
  230254. {
  230255. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  230256. insideDrawRect = true;
  230257. handlePaint (context);
  230258. insideDrawRect = false;
  230259. }
  230260. else
  230261. #endif
  230262. {
  230263. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  230264. (int) (r.size.width + 0.5f),
  230265. (int) (r.size.height + 0.5f),
  230266. ! getComponent()->isOpaque());
  230267. const int xOffset = -roundToInt (r.origin.x);
  230268. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  230269. const NSRect* rects = 0;
  230270. NSInteger numRects = 0;
  230271. [view getRectsBeingDrawn: &rects count: &numRects];
  230272. const Rectangle<int> clipBounds (temp.getBounds());
  230273. RectangleList clip;
  230274. for (int i = 0; i < numRects; ++i)
  230275. {
  230276. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  230277. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  230278. roundToInt (rects[i].size.width),
  230279. roundToInt (rects[i].size.height))));
  230280. }
  230281. if (! clip.isEmpty())
  230282. {
  230283. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  230284. insideDrawRect = true;
  230285. handlePaint (context);
  230286. insideDrawRect = false;
  230287. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230288. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  230289. CGColorSpaceRelease (colourSpace);
  230290. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  230291. CGImageRelease (image);
  230292. }
  230293. }
  230294. }
  230295. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  230296. {
  230297. StringArray s;
  230298. s.add ("Software Renderer");
  230299. #if USE_COREGRAPHICS_RENDERING
  230300. s.add ("CoreGraphics Renderer");
  230301. #endif
  230302. return s;
  230303. }
  230304. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  230305. {
  230306. return usingCoreGraphics ? 1 : 0;
  230307. }
  230308. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  230309. {
  230310. #if USE_COREGRAPHICS_RENDERING
  230311. if (usingCoreGraphics != (index > 0))
  230312. {
  230313. usingCoreGraphics = index > 0;
  230314. [view setNeedsDisplay: true];
  230315. }
  230316. #endif
  230317. }
  230318. bool NSViewComponentPeer::canBecomeKeyWindow()
  230319. {
  230320. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  230321. }
  230322. bool NSViewComponentPeer::windowShouldClose()
  230323. {
  230324. if (! isValidPeer (this))
  230325. return YES;
  230326. handleUserClosingWindow();
  230327. return NO;
  230328. }
  230329. void NSViewComponentPeer::redirectMovedOrResized()
  230330. {
  230331. handleMovedOrResized();
  230332. }
  230333. void NSViewComponentPeer::viewMovedToWindow()
  230334. {
  230335. if (isSharedWindow)
  230336. window = [view window];
  230337. }
  230338. void Desktop::createMouseInputSources()
  230339. {
  230340. mouseSources.add (new MouseInputSource (0, true));
  230341. }
  230342. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  230343. {
  230344. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  230345. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  230346. // is apparently still available in 64-bit apps..
  230347. if (enableOrDisable)
  230348. {
  230349. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  230350. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  230351. }
  230352. else
  230353. {
  230354. SetSystemUIMode (kUIModeNormal, 0);
  230355. }
  230356. }
  230357. class AsyncRepaintMessage : public CallbackMessage
  230358. {
  230359. public:
  230360. NSViewComponentPeer* const peer;
  230361. const Rectangle<int> rect;
  230362. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  230363. : peer (peer_), rect (rect_)
  230364. {
  230365. }
  230366. void messageCallback()
  230367. {
  230368. if (ComponentPeer::isValidPeer (peer))
  230369. peer->repaint (rect);
  230370. }
  230371. };
  230372. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  230373. {
  230374. if (insideDrawRect)
  230375. {
  230376. (new AsyncRepaintMessage (this, area))->post();
  230377. }
  230378. else
  230379. {
  230380. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  230381. (float) area.getWidth(), (float) area.getHeight())];
  230382. }
  230383. }
  230384. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  230385. {
  230386. [view displayIfNeeded];
  230387. }
  230388. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  230389. {
  230390. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  230391. }
  230392. const Image juce_createIconForFile (const File& file)
  230393. {
  230394. const ScopedAutoReleasePool pool;
  230395. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  230396. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  230397. [NSGraphicsContext saveGraphicsState];
  230398. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  230399. [image drawAtPoint: NSMakePoint (0, 0)
  230400. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  230401. operation: NSCompositeSourceOver fraction: 1.0f];
  230402. [[NSGraphicsContext currentContext] flushGraphics];
  230403. [NSGraphicsContext restoreGraphicsState];
  230404. return Image (result);
  230405. }
  230406. const int KeyPress::spaceKey = ' ';
  230407. const int KeyPress::returnKey = 0x0d;
  230408. const int KeyPress::escapeKey = 0x1b;
  230409. const int KeyPress::backspaceKey = 0x7f;
  230410. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  230411. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  230412. const int KeyPress::upKey = NSUpArrowFunctionKey;
  230413. const int KeyPress::downKey = NSDownArrowFunctionKey;
  230414. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  230415. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  230416. const int KeyPress::endKey = NSEndFunctionKey;
  230417. const int KeyPress::homeKey = NSHomeFunctionKey;
  230418. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  230419. const int KeyPress::insertKey = -1;
  230420. const int KeyPress::tabKey = 9;
  230421. const int KeyPress::F1Key = NSF1FunctionKey;
  230422. const int KeyPress::F2Key = NSF2FunctionKey;
  230423. const int KeyPress::F3Key = NSF3FunctionKey;
  230424. const int KeyPress::F4Key = NSF4FunctionKey;
  230425. const int KeyPress::F5Key = NSF5FunctionKey;
  230426. const int KeyPress::F6Key = NSF6FunctionKey;
  230427. const int KeyPress::F7Key = NSF7FunctionKey;
  230428. const int KeyPress::F8Key = NSF8FunctionKey;
  230429. const int KeyPress::F9Key = NSF9FunctionKey;
  230430. const int KeyPress::F10Key = NSF10FunctionKey;
  230431. const int KeyPress::F11Key = NSF1FunctionKey;
  230432. const int KeyPress::F12Key = NSF12FunctionKey;
  230433. const int KeyPress::F13Key = NSF13FunctionKey;
  230434. const int KeyPress::F14Key = NSF14FunctionKey;
  230435. const int KeyPress::F15Key = NSF15FunctionKey;
  230436. const int KeyPress::F16Key = NSF16FunctionKey;
  230437. const int KeyPress::numberPad0 = 0x30020;
  230438. const int KeyPress::numberPad1 = 0x30021;
  230439. const int KeyPress::numberPad2 = 0x30022;
  230440. const int KeyPress::numberPad3 = 0x30023;
  230441. const int KeyPress::numberPad4 = 0x30024;
  230442. const int KeyPress::numberPad5 = 0x30025;
  230443. const int KeyPress::numberPad6 = 0x30026;
  230444. const int KeyPress::numberPad7 = 0x30027;
  230445. const int KeyPress::numberPad8 = 0x30028;
  230446. const int KeyPress::numberPad9 = 0x30029;
  230447. const int KeyPress::numberPadAdd = 0x3002a;
  230448. const int KeyPress::numberPadSubtract = 0x3002b;
  230449. const int KeyPress::numberPadMultiply = 0x3002c;
  230450. const int KeyPress::numberPadDivide = 0x3002d;
  230451. const int KeyPress::numberPadSeparator = 0x3002e;
  230452. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  230453. const int KeyPress::numberPadEquals = 0x30030;
  230454. const int KeyPress::numberPadDelete = 0x30031;
  230455. const int KeyPress::playKey = 0x30000;
  230456. const int KeyPress::stopKey = 0x30001;
  230457. const int KeyPress::fastForwardKey = 0x30002;
  230458. const int KeyPress::rewindKey = 0x30003;
  230459. #endif
  230460. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230461. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  230462. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230463. // compiled on its own).
  230464. #if JUCE_INCLUDED_FILE
  230465. #if JUCE_MAC
  230466. namespace MouseCursorHelpers
  230467. {
  230468. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  230469. {
  230470. NSImage* im = CoreGraphicsImage::createNSImage (image);
  230471. NSCursor* c = [[NSCursor alloc] initWithImage: im
  230472. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  230473. [im release];
  230474. return c;
  230475. }
  230476. static void* fromWebKitFile (const char* filename, float hx, float hy)
  230477. {
  230478. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  230479. BufferedInputStream buf (&fileStream, 4096, false);
  230480. PNGImageFormat pngFormat;
  230481. Image im (pngFormat.decodeImage (buf));
  230482. if (im.isValid())
  230483. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  230484. jassertfalse;
  230485. return 0;
  230486. }
  230487. }
  230488. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  230489. {
  230490. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  230491. }
  230492. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  230493. {
  230494. const ScopedAutoReleasePool pool;
  230495. NSCursor* c = 0;
  230496. switch (type)
  230497. {
  230498. case NormalCursor: c = [NSCursor arrowCursor]; break;
  230499. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  230500. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  230501. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  230502. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  230503. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  230504. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  230505. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  230506. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  230507. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  230508. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  230509. case UpDownResizeCursor:
  230510. case TopEdgeResizeCursor:
  230511. case BottomEdgeResizeCursor:
  230512. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  230513. case TopLeftCornerResizeCursor:
  230514. case BottomRightCornerResizeCursor:
  230515. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  230516. case TopRightCornerResizeCursor:
  230517. case BottomLeftCornerResizeCursor:
  230518. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  230519. case UpDownLeftRightResizeCursor:
  230520. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  230521. default:
  230522. jassertfalse;
  230523. break;
  230524. }
  230525. [c retain];
  230526. return c;
  230527. }
  230528. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  230529. {
  230530. [((NSCursor*) cursorHandle) release];
  230531. }
  230532. void MouseCursor::showInAllWindows() const
  230533. {
  230534. showInWindow (0);
  230535. }
  230536. void MouseCursor::showInWindow (ComponentPeer*) const
  230537. {
  230538. [((NSCursor*) getHandle()) set];
  230539. }
  230540. #else
  230541. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  230542. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  230543. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  230544. void MouseCursor::showInAllWindows() const {}
  230545. void MouseCursor::showInWindow (ComponentPeer*) const {}
  230546. #endif
  230547. #endif
  230548. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  230549. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  230550. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230551. // compiled on its own).
  230552. #if JUCE_INCLUDED_FILE
  230553. class NSViewComponentInternal : public ComponentMovementWatcher
  230554. {
  230555. Component* const owner;
  230556. NSViewComponentPeer* currentPeer;
  230557. bool wasShowing;
  230558. public:
  230559. NSView* const view;
  230560. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  230561. : ComponentMovementWatcher (owner_),
  230562. owner (owner_),
  230563. currentPeer (0),
  230564. wasShowing (false),
  230565. view (view_)
  230566. {
  230567. [view_ retain];
  230568. if (owner_->isShowing())
  230569. componentPeerChanged();
  230570. }
  230571. ~NSViewComponentInternal()
  230572. {
  230573. [view removeFromSuperview];
  230574. [view release];
  230575. }
  230576. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  230577. {
  230578. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  230579. // The ComponentMovementWatcher version of this method avoids calling
  230580. // us when the top-level comp is resized, but for an NSView we need to know this
  230581. // because with inverted co-ords, we need to update the position even if the
  230582. // top-left pos hasn't changed
  230583. if (comp.isOnDesktop() && wasResized)
  230584. componentMovedOrResized (wasMoved, wasResized);
  230585. }
  230586. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  230587. {
  230588. Component* const topComp = owner->getTopLevelComponent();
  230589. if (topComp->getPeer() != 0)
  230590. {
  230591. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  230592. NSRect r;
  230593. r.origin.x = (float) pos.getX();
  230594. r.origin.y = (float) pos.getY();
  230595. r.size.width = (float) owner->getWidth();
  230596. r.size.height = (float) owner->getHeight();
  230597. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230598. [view setFrame: r];
  230599. }
  230600. }
  230601. void componentPeerChanged()
  230602. {
  230603. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  230604. if (currentPeer != peer)
  230605. {
  230606. [view removeFromSuperview];
  230607. currentPeer = peer;
  230608. if (peer != 0)
  230609. {
  230610. [peer->view addSubview: view];
  230611. componentMovedOrResized (false, false);
  230612. }
  230613. }
  230614. [view setHidden: ! owner->isShowing()];
  230615. }
  230616. void componentVisibilityChanged (Component&)
  230617. {
  230618. componentPeerChanged();
  230619. }
  230620. juce_UseDebuggingNewOperator
  230621. private:
  230622. NSViewComponentInternal (const NSViewComponentInternal&);
  230623. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  230624. };
  230625. NSViewComponent::NSViewComponent()
  230626. {
  230627. }
  230628. NSViewComponent::~NSViewComponent()
  230629. {
  230630. }
  230631. void NSViewComponent::setView (void* view)
  230632. {
  230633. if (view != getView())
  230634. {
  230635. if (view != 0)
  230636. info = new NSViewComponentInternal ((NSView*) view, this);
  230637. else
  230638. info = 0;
  230639. }
  230640. }
  230641. void* NSViewComponent::getView() const
  230642. {
  230643. return info == 0 ? 0 : info->view;
  230644. }
  230645. void NSViewComponent::paint (Graphics&)
  230646. {
  230647. }
  230648. #endif
  230649. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  230650. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  230651. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230652. // compiled on its own).
  230653. #if JUCE_INCLUDED_FILE
  230654. AppleRemoteDevice::AppleRemoteDevice()
  230655. : device (0),
  230656. queue (0),
  230657. remoteId (0)
  230658. {
  230659. }
  230660. AppleRemoteDevice::~AppleRemoteDevice()
  230661. {
  230662. stop();
  230663. }
  230664. static io_object_t getAppleRemoteDevice()
  230665. {
  230666. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  230667. io_iterator_t iter = 0;
  230668. io_object_t iod = 0;
  230669. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  230670. && iter != 0)
  230671. {
  230672. iod = IOIteratorNext (iter);
  230673. }
  230674. IOObjectRelease (iter);
  230675. return iod;
  230676. }
  230677. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  230678. {
  230679. jassert (*device == 0);
  230680. io_name_t classname;
  230681. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  230682. {
  230683. IOCFPlugInInterface** cfPlugInInterface = 0;
  230684. SInt32 score = 0;
  230685. if (IOCreatePlugInInterfaceForService (iod,
  230686. kIOHIDDeviceUserClientTypeID,
  230687. kIOCFPlugInInterfaceID,
  230688. &cfPlugInInterface,
  230689. &score) == kIOReturnSuccess)
  230690. {
  230691. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  230692. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  230693. device);
  230694. (void) hr;
  230695. (*cfPlugInInterface)->Release (cfPlugInInterface);
  230696. }
  230697. }
  230698. return *device != 0;
  230699. }
  230700. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  230701. {
  230702. if (queue != 0)
  230703. return true;
  230704. stop();
  230705. bool result = false;
  230706. io_object_t iod = getAppleRemoteDevice();
  230707. if (iod != 0)
  230708. {
  230709. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  230710. result = true;
  230711. else
  230712. stop();
  230713. IOObjectRelease (iod);
  230714. }
  230715. return result;
  230716. }
  230717. void AppleRemoteDevice::stop()
  230718. {
  230719. if (queue != 0)
  230720. {
  230721. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  230722. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  230723. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  230724. queue = 0;
  230725. }
  230726. if (device != 0)
  230727. {
  230728. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  230729. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  230730. device = 0;
  230731. }
  230732. }
  230733. bool AppleRemoteDevice::isActive() const
  230734. {
  230735. return queue != 0;
  230736. }
  230737. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  230738. {
  230739. if (result == kIOReturnSuccess)
  230740. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  230741. }
  230742. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  230743. {
  230744. Array <int> cookies;
  230745. CFArrayRef elements;
  230746. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  230747. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  230748. return false;
  230749. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  230750. {
  230751. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  230752. // get the cookie
  230753. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  230754. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  230755. continue;
  230756. long number;
  230757. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  230758. continue;
  230759. cookies.add ((int) number);
  230760. }
  230761. CFRelease (elements);
  230762. if ((*(IOHIDDeviceInterface**) device)
  230763. ->open ((IOHIDDeviceInterface**) device,
  230764. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  230765. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  230766. {
  230767. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  230768. if (queue != 0)
  230769. {
  230770. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  230771. for (int i = 0; i < cookies.size(); ++i)
  230772. {
  230773. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  230774. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  230775. }
  230776. CFRunLoopSourceRef eventSource;
  230777. if ((*(IOHIDQueueInterface**) queue)
  230778. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  230779. {
  230780. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  230781. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  230782. {
  230783. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  230784. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  230785. return true;
  230786. }
  230787. }
  230788. }
  230789. }
  230790. return false;
  230791. }
  230792. void AppleRemoteDevice::handleCallbackInternal()
  230793. {
  230794. int totalValues = 0;
  230795. AbsoluteTime nullTime = { 0, 0 };
  230796. char cookies [12];
  230797. int numCookies = 0;
  230798. while (numCookies < numElementsInArray (cookies))
  230799. {
  230800. IOHIDEventStruct e;
  230801. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  230802. break;
  230803. if ((int) e.elementCookie == 19)
  230804. {
  230805. remoteId = e.value;
  230806. buttonPressed (switched, false);
  230807. }
  230808. else
  230809. {
  230810. totalValues += e.value;
  230811. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  230812. }
  230813. }
  230814. cookies [numCookies++] = 0;
  230815. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  230816. static const char buttonPatterns[] =
  230817. {
  230818. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  230819. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  230820. 0x1f, 0x1d, 0x1c, 0x12, 0,
  230821. 0x1f, 0x1e, 0x1c, 0x12, 0,
  230822. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  230823. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  230824. 0x1f, 0x12, 0x04, 0x02, 0,
  230825. 0x1f, 0x12, 0x03, 0x02, 0,
  230826. 0x1f, 0x12, 0x1f, 0x12, 0,
  230827. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  230828. 19, 0
  230829. };
  230830. int buttonNum = (int) menuButton;
  230831. int i = 0;
  230832. while (i < numElementsInArray (buttonPatterns))
  230833. {
  230834. if (strcmp (cookies, buttonPatterns + i) == 0)
  230835. {
  230836. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  230837. break;
  230838. }
  230839. i += (int) strlen (buttonPatterns + i) + 1;
  230840. ++buttonNum;
  230841. }
  230842. }
  230843. #endif
  230844. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  230845. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  230846. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230847. // compiled on its own).
  230848. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  230849. #if JUCE_MAC
  230850. END_JUCE_NAMESPACE
  230851. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  230852. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  230853. {
  230854. CriticalSection* contextLock;
  230855. bool needsUpdate;
  230856. }
  230857. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  230858. - (bool) makeActive;
  230859. - (void) makeInactive;
  230860. - (void) reshape;
  230861. @end
  230862. @implementation ThreadSafeNSOpenGLView
  230863. - (id) initWithFrame: (NSRect) frameRect
  230864. pixelFormat: (NSOpenGLPixelFormat*) format
  230865. {
  230866. contextLock = new CriticalSection();
  230867. self = [super initWithFrame: frameRect pixelFormat: format];
  230868. if (self != nil)
  230869. [[NSNotificationCenter defaultCenter] addObserver: self
  230870. selector: @selector (_surfaceNeedsUpdate:)
  230871. name: NSViewGlobalFrameDidChangeNotification
  230872. object: self];
  230873. return self;
  230874. }
  230875. - (void) dealloc
  230876. {
  230877. [[NSNotificationCenter defaultCenter] removeObserver: self];
  230878. delete contextLock;
  230879. [super dealloc];
  230880. }
  230881. - (bool) makeActive
  230882. {
  230883. const ScopedLock sl (*contextLock);
  230884. if ([self openGLContext] == 0)
  230885. return false;
  230886. [[self openGLContext] makeCurrentContext];
  230887. if (needsUpdate)
  230888. {
  230889. [super update];
  230890. needsUpdate = false;
  230891. }
  230892. return true;
  230893. }
  230894. - (void) makeInactive
  230895. {
  230896. const ScopedLock sl (*contextLock);
  230897. [NSOpenGLContext clearCurrentContext];
  230898. }
  230899. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  230900. {
  230901. const ScopedLock sl (*contextLock);
  230902. needsUpdate = true;
  230903. }
  230904. - (void) update
  230905. {
  230906. const ScopedLock sl (*contextLock);
  230907. needsUpdate = true;
  230908. }
  230909. - (void) reshape
  230910. {
  230911. const ScopedLock sl (*contextLock);
  230912. needsUpdate = true;
  230913. }
  230914. @end
  230915. BEGIN_JUCE_NAMESPACE
  230916. class WindowedGLContext : public OpenGLContext
  230917. {
  230918. public:
  230919. WindowedGLContext (Component* const component,
  230920. const OpenGLPixelFormat& pixelFormat_,
  230921. NSOpenGLContext* sharedContext)
  230922. : renderContext (0),
  230923. pixelFormat (pixelFormat_)
  230924. {
  230925. jassert (component != 0);
  230926. NSOpenGLPixelFormatAttribute attribs [64];
  230927. int n = 0;
  230928. attribs[n++] = NSOpenGLPFADoubleBuffer;
  230929. attribs[n++] = NSOpenGLPFAAccelerated;
  230930. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  230931. attribs[n++] = NSOpenGLPFAColorSize;
  230932. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  230933. pixelFormat.greenBits,
  230934. pixelFormat.blueBits);
  230935. attribs[n++] = NSOpenGLPFAAlphaSize;
  230936. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  230937. attribs[n++] = NSOpenGLPFADepthSize;
  230938. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  230939. attribs[n++] = NSOpenGLPFAStencilSize;
  230940. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  230941. attribs[n++] = NSOpenGLPFAAccumSize;
  230942. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  230943. pixelFormat.accumulationBufferGreenBits,
  230944. pixelFormat.accumulationBufferBlueBits,
  230945. pixelFormat.accumulationBufferAlphaBits);
  230946. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  230947. attribs[n++] = NSOpenGLPFASampleBuffers;
  230948. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  230949. attribs[n++] = NSOpenGLPFAClosestPolicy;
  230950. attribs[n++] = NSOpenGLPFANoRecovery;
  230951. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  230952. NSOpenGLPixelFormat* format
  230953. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  230954. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  230955. pixelFormat: format];
  230956. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  230957. shareContext: sharedContext] autorelease];
  230958. const GLint swapInterval = 1;
  230959. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  230960. [view setOpenGLContext: renderContext];
  230961. [renderContext setView: view];
  230962. [format release];
  230963. viewHolder = new NSViewComponentInternal (view, component);
  230964. }
  230965. ~WindowedGLContext()
  230966. {
  230967. makeInactive();
  230968. [renderContext clearDrawable];
  230969. viewHolder = 0;
  230970. }
  230971. bool makeActive() const throw()
  230972. {
  230973. jassert (renderContext != 0);
  230974. [view makeActive];
  230975. return isActive();
  230976. }
  230977. bool makeInactive() const throw()
  230978. {
  230979. [view makeInactive];
  230980. return true;
  230981. }
  230982. bool isActive() const throw()
  230983. {
  230984. return [NSOpenGLContext currentContext] == renderContext;
  230985. }
  230986. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  230987. void* getRawContext() const throw() { return renderContext; }
  230988. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  230989. {
  230990. }
  230991. void swapBuffers()
  230992. {
  230993. [renderContext flushBuffer];
  230994. }
  230995. bool setSwapInterval (const int numFramesPerSwap)
  230996. {
  230997. [renderContext setValues: (const GLint*) &numFramesPerSwap
  230998. forParameter: NSOpenGLCPSwapInterval];
  230999. return true;
  231000. }
  231001. int getSwapInterval() const
  231002. {
  231003. GLint numFrames = 0;
  231004. [renderContext getValues: &numFrames
  231005. forParameter: NSOpenGLCPSwapInterval];
  231006. return numFrames;
  231007. }
  231008. void repaint()
  231009. {
  231010. // we need to invalidate the juce view that holds this gl view, to make it
  231011. // cause a repaint callback
  231012. NSView* v = (NSView*) viewHolder->view;
  231013. NSRect r = [v frame];
  231014. // bit of a bodge here.. if we only invalidate the area of the gl component,
  231015. // it's completely covered by the NSOpenGLView, so the OS throws away the
  231016. // repaint message, thus never causing our paint() callback, and never repainting
  231017. // the comp. So invalidating just a little bit around the edge helps..
  231018. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  231019. }
  231020. void* getNativeWindowHandle() const { return viewHolder->view; }
  231021. juce_UseDebuggingNewOperator
  231022. NSOpenGLContext* renderContext;
  231023. ThreadSafeNSOpenGLView* view;
  231024. private:
  231025. OpenGLPixelFormat pixelFormat;
  231026. ScopedPointer <NSViewComponentInternal> viewHolder;
  231027. WindowedGLContext (const WindowedGLContext&);
  231028. WindowedGLContext& operator= (const WindowedGLContext&);
  231029. };
  231030. OpenGLContext* OpenGLComponent::createContext()
  231031. {
  231032. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  231033. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  231034. return (c->renderContext != 0) ? c.release() : 0;
  231035. }
  231036. void* OpenGLComponent::getNativeWindowHandle() const
  231037. {
  231038. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  231039. : 0;
  231040. }
  231041. void juce_glViewport (const int w, const int h)
  231042. {
  231043. glViewport (0, 0, w, h);
  231044. }
  231045. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231046. OwnedArray <OpenGLPixelFormat>& results)
  231047. {
  231048. /* GLint attribs [64];
  231049. int n = 0;
  231050. attribs[n++] = AGL_RGBA;
  231051. attribs[n++] = AGL_DOUBLEBUFFER;
  231052. attribs[n++] = AGL_ACCELERATED;
  231053. attribs[n++] = AGL_NO_RECOVERY;
  231054. attribs[n++] = AGL_NONE;
  231055. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  231056. while (p != 0)
  231057. {
  231058. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  231059. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  231060. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  231061. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  231062. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  231063. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  231064. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  231065. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  231066. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  231067. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  231068. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  231069. results.add (pf);
  231070. p = aglNextPixelFormat (p);
  231071. }*/
  231072. //jassertfalse //xxx can't see how you do this in cocoa!
  231073. }
  231074. #else
  231075. END_JUCE_NAMESPACE
  231076. @interface JuceGLView : UIView
  231077. {
  231078. }
  231079. + (Class) layerClass;
  231080. @end
  231081. @implementation JuceGLView
  231082. + (Class) layerClass
  231083. {
  231084. return [CAEAGLLayer class];
  231085. }
  231086. @end
  231087. BEGIN_JUCE_NAMESPACE
  231088. class GLESContext : public OpenGLContext
  231089. {
  231090. public:
  231091. GLESContext (UIViewComponentPeer* peer,
  231092. Component* const component_,
  231093. const OpenGLPixelFormat& pixelFormat_,
  231094. const GLESContext* const sharedContext,
  231095. NSUInteger apiType)
  231096. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  231097. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  231098. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  231099. {
  231100. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  231101. view.opaque = YES;
  231102. view.hidden = NO;
  231103. view.backgroundColor = [UIColor blackColor];
  231104. view.userInteractionEnabled = NO;
  231105. glLayer = (CAEAGLLayer*) [view layer];
  231106. [peer->view addSubview: view];
  231107. if (sharedContext != 0)
  231108. context = [[EAGLContext alloc] initWithAPI: apiType
  231109. sharegroup: [sharedContext->context sharegroup]];
  231110. else
  231111. context = [[EAGLContext alloc] initWithAPI: apiType];
  231112. createGLBuffers();
  231113. }
  231114. ~GLESContext()
  231115. {
  231116. makeInactive();
  231117. [context release];
  231118. [view removeFromSuperview];
  231119. [view release];
  231120. freeGLBuffers();
  231121. }
  231122. bool makeActive() const throw()
  231123. {
  231124. jassert (context != 0);
  231125. [EAGLContext setCurrentContext: context];
  231126. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231127. return true;
  231128. }
  231129. void swapBuffers()
  231130. {
  231131. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231132. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  231133. }
  231134. bool makeInactive() const throw()
  231135. {
  231136. return [EAGLContext setCurrentContext: nil];
  231137. }
  231138. bool isActive() const throw()
  231139. {
  231140. return [EAGLContext currentContext] == context;
  231141. }
  231142. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231143. void* getRawContext() const throw() { return glLayer; }
  231144. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231145. {
  231146. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  231147. if (lastWidth != w || lastHeight != h)
  231148. {
  231149. lastWidth = w;
  231150. lastHeight = h;
  231151. freeGLBuffers();
  231152. createGLBuffers();
  231153. }
  231154. }
  231155. bool setSwapInterval (const int numFramesPerSwap)
  231156. {
  231157. numFrames = numFramesPerSwap;
  231158. return true;
  231159. }
  231160. int getSwapInterval() const
  231161. {
  231162. return numFrames;
  231163. }
  231164. void repaint()
  231165. {
  231166. }
  231167. void createGLBuffers()
  231168. {
  231169. makeActive();
  231170. glGenFramebuffersOES (1, &frameBufferHandle);
  231171. glGenRenderbuffersOES (1, &colorBufferHandle);
  231172. glGenRenderbuffersOES (1, &depthBufferHandle);
  231173. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231174. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  231175. GLint width, height;
  231176. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  231177. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  231178. if (useDepthBuffer)
  231179. {
  231180. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  231181. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  231182. }
  231183. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231184. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231185. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  231186. if (useDepthBuffer)
  231187. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  231188. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  231189. }
  231190. void freeGLBuffers()
  231191. {
  231192. if (frameBufferHandle != 0)
  231193. {
  231194. glDeleteFramebuffersOES (1, &frameBufferHandle);
  231195. frameBufferHandle = 0;
  231196. }
  231197. if (colorBufferHandle != 0)
  231198. {
  231199. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  231200. colorBufferHandle = 0;
  231201. }
  231202. if (depthBufferHandle != 0)
  231203. {
  231204. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  231205. depthBufferHandle = 0;
  231206. }
  231207. }
  231208. juce_UseDebuggingNewOperator
  231209. private:
  231210. Component::SafePointer<Component> component;
  231211. OpenGLPixelFormat pixelFormat;
  231212. JuceGLView* view;
  231213. CAEAGLLayer* glLayer;
  231214. EAGLContext* context;
  231215. bool useDepthBuffer;
  231216. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  231217. int numFrames;
  231218. int lastWidth, lastHeight;
  231219. GLESContext (const GLESContext&);
  231220. GLESContext& operator= (const GLESContext&);
  231221. };
  231222. OpenGLContext* OpenGLComponent::createContext()
  231223. {
  231224. ScopedAutoReleasePool pool;
  231225. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  231226. if (peer != 0)
  231227. return new GLESContext (peer, this, preferredPixelFormat,
  231228. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  231229. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  231230. return 0;
  231231. }
  231232. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231233. OwnedArray <OpenGLPixelFormat>& /*results*/)
  231234. {
  231235. }
  231236. void juce_glViewport (const int w, const int h)
  231237. {
  231238. glViewport (0, 0, w, h);
  231239. }
  231240. #endif
  231241. #endif
  231242. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  231243. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  231244. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231245. // compiled on its own).
  231246. #if JUCE_INCLUDED_FILE
  231247. class JuceMainMenuHandler;
  231248. END_JUCE_NAMESPACE
  231249. using namespace JUCE_NAMESPACE;
  231250. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  231251. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231252. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  231253. #else
  231254. @interface JuceMenuCallback : NSObject
  231255. #endif
  231256. {
  231257. JuceMainMenuHandler* owner;
  231258. }
  231259. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  231260. - (void) dealloc;
  231261. - (void) menuItemInvoked: (id) menu;
  231262. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231263. @end
  231264. BEGIN_JUCE_NAMESPACE
  231265. class JuceMainMenuHandler : private MenuBarModelListener,
  231266. private DeletedAtShutdown
  231267. {
  231268. public:
  231269. static JuceMainMenuHandler* instance;
  231270. JuceMainMenuHandler()
  231271. : currentModel (0),
  231272. lastUpdateTime (0)
  231273. {
  231274. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  231275. }
  231276. ~JuceMainMenuHandler()
  231277. {
  231278. setMenu (0);
  231279. jassert (instance == this);
  231280. instance = 0;
  231281. [callback release];
  231282. }
  231283. void setMenu (MenuBarModel* const newMenuBarModel)
  231284. {
  231285. if (currentModel != newMenuBarModel)
  231286. {
  231287. if (currentModel != 0)
  231288. currentModel->removeListener (this);
  231289. currentModel = newMenuBarModel;
  231290. if (currentModel != 0)
  231291. currentModel->addListener (this);
  231292. menuBarItemsChanged (0);
  231293. }
  231294. }
  231295. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  231296. const String& name, const int menuId, const int tag)
  231297. {
  231298. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  231299. action: nil
  231300. keyEquivalent: @""];
  231301. [item setTag: tag];
  231302. NSMenu* sub = createMenu (child, name, menuId, tag);
  231303. [parent setSubmenu: sub forItem: item];
  231304. [sub setAutoenablesItems: false];
  231305. [sub release];
  231306. }
  231307. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  231308. const String& name, const int menuId, const int tag)
  231309. {
  231310. [parentItem setTag: tag];
  231311. NSMenu* menu = [parentItem submenu];
  231312. [menu setTitle: juceStringToNS (name)];
  231313. while ([menu numberOfItems] > 0)
  231314. [menu removeItemAtIndex: 0];
  231315. PopupMenu::MenuItemIterator iter (menuToCopy);
  231316. while (iter.next())
  231317. addMenuItem (iter, menu, menuId, tag);
  231318. [menu setAutoenablesItems: false];
  231319. [menu update];
  231320. }
  231321. void menuBarItemsChanged (MenuBarModel*)
  231322. {
  231323. lastUpdateTime = Time::getMillisecondCounter();
  231324. StringArray menuNames;
  231325. if (currentModel != 0)
  231326. menuNames = currentModel->getMenuBarNames();
  231327. NSMenu* menuBar = [NSApp mainMenu];
  231328. while ([menuBar numberOfItems] > 1 + menuNames.size())
  231329. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  231330. int menuId = 1;
  231331. for (int i = 0; i < menuNames.size(); ++i)
  231332. {
  231333. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  231334. if (i >= [menuBar numberOfItems] - 1)
  231335. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  231336. else
  231337. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  231338. }
  231339. }
  231340. static void flashMenuBar (NSMenu* menu)
  231341. {
  231342. if ([[menu title] isEqualToString: @"Apple"])
  231343. return;
  231344. [menu retain];
  231345. const unichar f35Key = NSF35FunctionKey;
  231346. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  231347. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  231348. action: nil
  231349. keyEquivalent: f35String];
  231350. [item setTarget: nil];
  231351. [menu insertItem: item atIndex: [menu numberOfItems]];
  231352. [item release];
  231353. if ([menu indexOfItem: item] >= 0)
  231354. {
  231355. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  231356. location: NSZeroPoint
  231357. modifierFlags: NSCommandKeyMask
  231358. timestamp: 0
  231359. windowNumber: 0
  231360. context: [NSGraphicsContext currentContext]
  231361. characters: f35String
  231362. charactersIgnoringModifiers: f35String
  231363. isARepeat: NO
  231364. keyCode: 0];
  231365. [menu performKeyEquivalent: f35Event];
  231366. if ([menu indexOfItem: item] >= 0)
  231367. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  231368. }
  231369. [menu release];
  231370. }
  231371. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  231372. {
  231373. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  231374. {
  231375. NSMenuItem* m = [menu itemAtIndex: i];
  231376. if ([m tag] == info.commandID)
  231377. return m;
  231378. if ([m submenu] != 0)
  231379. {
  231380. NSMenuItem* found = findMenuItem ([m submenu], info);
  231381. if (found != 0)
  231382. return found;
  231383. }
  231384. }
  231385. return 0;
  231386. }
  231387. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  231388. {
  231389. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  231390. if (item != 0)
  231391. flashMenuBar ([item menu]);
  231392. }
  231393. void updateMenus()
  231394. {
  231395. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  231396. menuBarItemsChanged (0);
  231397. }
  231398. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  231399. {
  231400. if (currentModel != 0)
  231401. {
  231402. if (commandManager != 0)
  231403. {
  231404. ApplicationCommandTarget::InvocationInfo info (commandId);
  231405. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  231406. commandManager->invoke (info, true);
  231407. }
  231408. currentModel->menuItemSelected (commandId, topLevelIndex);
  231409. }
  231410. }
  231411. MenuBarModel* currentModel;
  231412. uint32 lastUpdateTime;
  231413. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  231414. const int topLevelMenuId, const int topLevelIndex)
  231415. {
  231416. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  231417. if (text == 0)
  231418. text = @"";
  231419. if (iter.isSeparator)
  231420. {
  231421. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  231422. }
  231423. else if (iter.isSectionHeader)
  231424. {
  231425. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231426. action: nil
  231427. keyEquivalent: @""];
  231428. [item setEnabled: false];
  231429. }
  231430. else if (iter.subMenu != 0)
  231431. {
  231432. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231433. action: nil
  231434. keyEquivalent: @""];
  231435. [item setTag: iter.itemId];
  231436. [item setEnabled: iter.isEnabled];
  231437. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  231438. [sub setDelegate: nil];
  231439. [menuToAddTo setSubmenu: sub forItem: item];
  231440. [sub release];
  231441. }
  231442. else
  231443. {
  231444. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231445. action: @selector (menuItemInvoked:)
  231446. keyEquivalent: @""];
  231447. [item setTag: iter.itemId];
  231448. [item setEnabled: iter.isEnabled];
  231449. [item setState: iter.isTicked ? NSOnState : NSOffState];
  231450. [item setTarget: (id) callback];
  231451. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  231452. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  231453. [item setRepresentedObject: info];
  231454. if (iter.commandManager != 0)
  231455. {
  231456. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  231457. ->getKeyPressesAssignedToCommand (iter.itemId));
  231458. if (keyPresses.size() > 0)
  231459. {
  231460. const KeyPress& kp = keyPresses.getReference(0);
  231461. if (kp.getKeyCode() != KeyPress::backspaceKey
  231462. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  231463. // every time you press the key while editing text)
  231464. {
  231465. juce_wchar key = kp.getTextCharacter();
  231466. if (kp.getKeyCode() == KeyPress::backspaceKey)
  231467. key = NSBackspaceCharacter;
  231468. else if (kp.getKeyCode() == KeyPress::deleteKey)
  231469. key = NSDeleteCharacter;
  231470. else if (key == 0)
  231471. key = (juce_wchar) kp.getKeyCode();
  231472. unsigned int mods = 0;
  231473. if (kp.getModifiers().isShiftDown())
  231474. mods |= NSShiftKeyMask;
  231475. if (kp.getModifiers().isCtrlDown())
  231476. mods |= NSControlKeyMask;
  231477. if (kp.getModifiers().isAltDown())
  231478. mods |= NSAlternateKeyMask;
  231479. if (kp.getModifiers().isCommandDown())
  231480. mods |= NSCommandKeyMask;
  231481. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  231482. [item setKeyEquivalentModifierMask: mods];
  231483. }
  231484. }
  231485. }
  231486. }
  231487. }
  231488. JuceMenuCallback* callback;
  231489. private:
  231490. NSMenu* createMenu (const PopupMenu menu,
  231491. const String& menuName,
  231492. const int topLevelMenuId,
  231493. const int topLevelIndex)
  231494. {
  231495. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  231496. [m setAutoenablesItems: false];
  231497. [m setDelegate: callback];
  231498. PopupMenu::MenuItemIterator iter (menu);
  231499. while (iter.next())
  231500. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  231501. [m update];
  231502. return m;
  231503. }
  231504. };
  231505. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  231506. END_JUCE_NAMESPACE
  231507. @implementation JuceMenuCallback
  231508. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  231509. {
  231510. [super init];
  231511. owner = owner_;
  231512. return self;
  231513. }
  231514. - (void) dealloc
  231515. {
  231516. [super dealloc];
  231517. }
  231518. - (void) menuItemInvoked: (id) menu
  231519. {
  231520. NSMenuItem* item = (NSMenuItem*) menu;
  231521. if ([[item representedObject] isKindOfClass: [NSArray class]])
  231522. {
  231523. // If the menu is being triggered by a keypress, the OS will have picked it up before we had a chance to offer it to
  231524. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  231525. // into the focused component and let it trigger the menu item indirectly.
  231526. NSEvent* e = [NSApp currentEvent];
  231527. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  231528. {
  231529. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  231530. {
  231531. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  231532. if (peer != 0)
  231533. {
  231534. if ([e type] == NSKeyDown)
  231535. peer->redirectKeyDown (e);
  231536. else
  231537. peer->redirectKeyUp (e);
  231538. return;
  231539. }
  231540. }
  231541. }
  231542. NSArray* info = (NSArray*) [item representedObject];
  231543. owner->invoke ((int) [item tag],
  231544. (ApplicationCommandManager*) (pointer_sized_int)
  231545. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  231546. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  231547. }
  231548. }
  231549. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231550. {
  231551. (void) menu;
  231552. if (JuceMainMenuHandler::instance != 0)
  231553. JuceMainMenuHandler::instance->updateMenus();
  231554. }
  231555. @end
  231556. BEGIN_JUCE_NAMESPACE
  231557. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  231558. const PopupMenu* extraItems)
  231559. {
  231560. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  231561. {
  231562. PopupMenu::MenuItemIterator iter (*extraItems);
  231563. while (iter.next())
  231564. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  231565. [menu addItem: [NSMenuItem separatorItem]];
  231566. }
  231567. NSMenuItem* item;
  231568. // Services...
  231569. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  231570. action: nil keyEquivalent: @""];
  231571. [menu addItem: item];
  231572. [item release];
  231573. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  231574. [menu setSubmenu: servicesMenu forItem: item];
  231575. [NSApp setServicesMenu: servicesMenu];
  231576. [servicesMenu release];
  231577. [menu addItem: [NSMenuItem separatorItem]];
  231578. // Hide + Show stuff...
  231579. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  231580. action: @selector (hide:) keyEquivalent: @"h"];
  231581. [item setTarget: NSApp];
  231582. [menu addItem: item];
  231583. [item release];
  231584. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  231585. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  231586. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  231587. [item setTarget: NSApp];
  231588. [menu addItem: item];
  231589. [item release];
  231590. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  231591. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  231592. [item setTarget: NSApp];
  231593. [menu addItem: item];
  231594. [item release];
  231595. [menu addItem: [NSMenuItem separatorItem]];
  231596. // Quit item....
  231597. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  231598. action: @selector (terminate:) keyEquivalent: @"q"];
  231599. [item setTarget: NSApp];
  231600. [menu addItem: item];
  231601. [item release];
  231602. return menu;
  231603. }
  231604. // Since our app has no NIB, this initialises a standard app menu...
  231605. static void rebuildMainMenu (const PopupMenu* extraItems)
  231606. {
  231607. // this can't be used in a plugin!
  231608. jassert (JUCEApplication::getInstance() != 0);
  231609. if (JUCEApplication::getInstance() != 0)
  231610. {
  231611. const ScopedAutoReleasePool pool;
  231612. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  231613. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  231614. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  231615. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  231616. [mainMenu setSubmenu: appMenu forItem: item];
  231617. [NSApp setMainMenu: mainMenu];
  231618. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  231619. [appMenu release];
  231620. [mainMenu release];
  231621. }
  231622. }
  231623. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  231624. const PopupMenu* extraAppleMenuItems)
  231625. {
  231626. if (getMacMainMenu() != newMenuBarModel)
  231627. {
  231628. const ScopedAutoReleasePool pool;
  231629. if (newMenuBarModel == 0)
  231630. {
  231631. delete JuceMainMenuHandler::instance;
  231632. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  231633. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  231634. extraAppleMenuItems = 0;
  231635. }
  231636. else
  231637. {
  231638. if (JuceMainMenuHandler::instance == 0)
  231639. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  231640. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  231641. }
  231642. }
  231643. rebuildMainMenu (extraAppleMenuItems);
  231644. if (newMenuBarModel != 0)
  231645. newMenuBarModel->menuItemsChanged();
  231646. }
  231647. MenuBarModel* MenuBarModel::getMacMainMenu()
  231648. {
  231649. return JuceMainMenuHandler::instance != 0
  231650. ? JuceMainMenuHandler::instance->currentModel : 0;
  231651. }
  231652. void initialiseMainMenu()
  231653. {
  231654. if (JUCEApplication::getInstance() != 0) // only needed in an app
  231655. rebuildMainMenu (0);
  231656. }
  231657. #endif
  231658. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  231659. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  231660. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231661. // compiled on its own).
  231662. #if JUCE_INCLUDED_FILE
  231663. #if JUCE_MAC
  231664. END_JUCE_NAMESPACE
  231665. using namespace JUCE_NAMESPACE;
  231666. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  231667. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231668. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  231669. #else
  231670. @interface JuceFileChooserDelegate : NSObject
  231671. #endif
  231672. {
  231673. StringArray* filters;
  231674. }
  231675. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  231676. - (void) dealloc;
  231677. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  231678. @end
  231679. @implementation JuceFileChooserDelegate
  231680. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  231681. {
  231682. [super init];
  231683. filters = filters_;
  231684. return self;
  231685. }
  231686. - (void) dealloc
  231687. {
  231688. delete filters;
  231689. [super dealloc];
  231690. }
  231691. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  231692. {
  231693. (void) sender;
  231694. const File f (nsStringToJuce (filename));
  231695. for (int i = filters->size(); --i >= 0;)
  231696. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  231697. return true;
  231698. return f.isDirectory();
  231699. }
  231700. @end
  231701. BEGIN_JUCE_NAMESPACE
  231702. void FileChooser::showPlatformDialog (Array<File>& results,
  231703. const String& title,
  231704. const File& currentFileOrDirectory,
  231705. const String& filter,
  231706. bool selectsDirectory,
  231707. bool selectsFiles,
  231708. bool isSaveDialogue,
  231709. bool warnAboutOverwritingExistingFiles,
  231710. bool selectMultipleFiles,
  231711. FilePreviewComponent* extraInfoComponent)
  231712. {
  231713. const ScopedAutoReleasePool pool;
  231714. StringArray* filters = new StringArray();
  231715. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  231716. filters->trim();
  231717. filters->removeEmptyStrings();
  231718. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  231719. [delegate autorelease];
  231720. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  231721. : [NSOpenPanel openPanel];
  231722. [panel setTitle: juceStringToNS (title)];
  231723. if (! isSaveDialogue)
  231724. {
  231725. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  231726. [openPanel setCanChooseDirectories: selectsDirectory];
  231727. [openPanel setCanChooseFiles: selectsFiles];
  231728. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  231729. }
  231730. [panel setDelegate: delegate];
  231731. if (isSaveDialogue || selectsDirectory)
  231732. [panel setCanCreateDirectories: YES];
  231733. String directory, filename;
  231734. if (currentFileOrDirectory.isDirectory())
  231735. {
  231736. directory = currentFileOrDirectory.getFullPathName();
  231737. }
  231738. else
  231739. {
  231740. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  231741. filename = currentFileOrDirectory.getFileName();
  231742. }
  231743. if ([panel runModalForDirectory: juceStringToNS (directory)
  231744. file: juceStringToNS (filename)]
  231745. == NSOKButton)
  231746. {
  231747. if (isSaveDialogue)
  231748. {
  231749. results.add (File (nsStringToJuce ([panel filename])));
  231750. }
  231751. else
  231752. {
  231753. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  231754. NSArray* urls = [openPanel filenames];
  231755. for (unsigned int i = 0; i < [urls count]; ++i)
  231756. {
  231757. NSString* f = [urls objectAtIndex: i];
  231758. results.add (File (nsStringToJuce (f)));
  231759. }
  231760. }
  231761. }
  231762. [panel setDelegate: nil];
  231763. }
  231764. #else
  231765. void FileChooser::showPlatformDialog (Array<File>& results,
  231766. const String& title,
  231767. const File& currentFileOrDirectory,
  231768. const String& filter,
  231769. bool selectsDirectory,
  231770. bool selectsFiles,
  231771. bool isSaveDialogue,
  231772. bool warnAboutOverwritingExistingFiles,
  231773. bool selectMultipleFiles,
  231774. FilePreviewComponent* extraInfoComponent)
  231775. {
  231776. const ScopedAutoReleasePool pool;
  231777. jassertfalse; //xxx to do
  231778. }
  231779. #endif
  231780. #endif
  231781. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  231782. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  231783. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231784. // compiled on its own).
  231785. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  231786. END_JUCE_NAMESPACE
  231787. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  231788. @interface NonInterceptingQTMovieView : QTMovieView
  231789. {
  231790. }
  231791. - (id) initWithFrame: (NSRect) frame;
  231792. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  231793. - (NSView*) hitTest: (NSPoint) p;
  231794. @end
  231795. @implementation NonInterceptingQTMovieView
  231796. - (id) initWithFrame: (NSRect) frame
  231797. {
  231798. self = [super initWithFrame: frame];
  231799. [self setNextResponder: [self superview]];
  231800. return self;
  231801. }
  231802. - (void) dealloc
  231803. {
  231804. [super dealloc];
  231805. }
  231806. - (NSView*) hitTest: (NSPoint) point
  231807. {
  231808. return [self isControllerVisible] ? [super hitTest: point] : nil;
  231809. }
  231810. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  231811. {
  231812. return YES;
  231813. }
  231814. @end
  231815. BEGIN_JUCE_NAMESPACE
  231816. #define theMovie (static_cast <QTMovie*> (movie))
  231817. QuickTimeMovieComponent::QuickTimeMovieComponent()
  231818. : movie (0)
  231819. {
  231820. setOpaque (true);
  231821. setVisible (true);
  231822. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  231823. setView (view);
  231824. [view release];
  231825. }
  231826. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  231827. {
  231828. closeMovie();
  231829. setView (0);
  231830. }
  231831. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  231832. {
  231833. return true;
  231834. }
  231835. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  231836. {
  231837. // unfortunately, QTMovie objects can only be created on the main thread..
  231838. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  231839. QTMovie* movie = 0;
  231840. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  231841. if (fin != 0)
  231842. {
  231843. movieFile = fin->getFile();
  231844. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  231845. error: nil];
  231846. }
  231847. else
  231848. {
  231849. MemoryBlock temp;
  231850. movieStream->readIntoMemoryBlock (temp);
  231851. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  231852. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  231853. {
  231854. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  231855. length: temp.getSize()]
  231856. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  231857. MIMEType: @""]
  231858. error: nil];
  231859. if (movie != 0)
  231860. break;
  231861. }
  231862. }
  231863. return movie;
  231864. }
  231865. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  231866. const bool isControllerVisible_)
  231867. {
  231868. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  231869. }
  231870. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  231871. const bool controllerVisible_)
  231872. {
  231873. closeMovie();
  231874. if (getPeer() == 0)
  231875. {
  231876. // To open a movie, this component must be visible inside a functioning window, so that
  231877. // the QT control can be assigned to the window.
  231878. jassertfalse;
  231879. return false;
  231880. }
  231881. movie = openMovieFromStream (movieStream, movieFile);
  231882. [theMovie retain];
  231883. QTMovieView* view = (QTMovieView*) getView();
  231884. [view setMovie: theMovie];
  231885. [view setControllerVisible: controllerVisible_];
  231886. setLooping (looping);
  231887. return movie != nil;
  231888. }
  231889. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  231890. const bool isControllerVisible_)
  231891. {
  231892. // unfortunately, QTMovie objects can only be created on the main thread..
  231893. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  231894. closeMovie();
  231895. if (getPeer() == 0)
  231896. {
  231897. // To open a movie, this component must be visible inside a functioning window, so that
  231898. // the QT control can be assigned to the window.
  231899. jassertfalse;
  231900. return false;
  231901. }
  231902. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  231903. NSError* err;
  231904. if ([QTMovie canInitWithURL: url])
  231905. movie = [QTMovie movieWithURL: url error: &err];
  231906. [theMovie retain];
  231907. QTMovieView* view = (QTMovieView*) getView();
  231908. [view setMovie: theMovie];
  231909. [view setControllerVisible: controllerVisible];
  231910. setLooping (looping);
  231911. return movie != nil;
  231912. }
  231913. void QuickTimeMovieComponent::closeMovie()
  231914. {
  231915. stop();
  231916. QTMovieView* view = (QTMovieView*) getView();
  231917. [view setMovie: nil];
  231918. [theMovie release];
  231919. movie = 0;
  231920. movieFile = File::nonexistent;
  231921. }
  231922. bool QuickTimeMovieComponent::isMovieOpen() const
  231923. {
  231924. return movie != nil;
  231925. }
  231926. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  231927. {
  231928. return movieFile;
  231929. }
  231930. void QuickTimeMovieComponent::play()
  231931. {
  231932. [theMovie play];
  231933. }
  231934. void QuickTimeMovieComponent::stop()
  231935. {
  231936. [theMovie stop];
  231937. }
  231938. bool QuickTimeMovieComponent::isPlaying() const
  231939. {
  231940. return movie != 0 && [theMovie rate] != 0;
  231941. }
  231942. void QuickTimeMovieComponent::setPosition (const double seconds)
  231943. {
  231944. if (movie != 0)
  231945. {
  231946. QTTime t;
  231947. t.timeValue = (uint64) (100000.0 * seconds);
  231948. t.timeScale = 100000;
  231949. t.flags = 0;
  231950. [theMovie setCurrentTime: t];
  231951. }
  231952. }
  231953. double QuickTimeMovieComponent::getPosition() const
  231954. {
  231955. if (movie == 0)
  231956. return 0.0;
  231957. QTTime t = [theMovie currentTime];
  231958. return t.timeValue / (double) t.timeScale;
  231959. }
  231960. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  231961. {
  231962. [theMovie setRate: newSpeed];
  231963. }
  231964. double QuickTimeMovieComponent::getMovieDuration() const
  231965. {
  231966. if (movie == 0)
  231967. return 0.0;
  231968. QTTime t = [theMovie duration];
  231969. return t.timeValue / (double) t.timeScale;
  231970. }
  231971. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  231972. {
  231973. looping = shouldLoop;
  231974. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  231975. forKey: QTMovieLoopsAttribute];
  231976. }
  231977. bool QuickTimeMovieComponent::isLooping() const
  231978. {
  231979. return looping;
  231980. }
  231981. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  231982. {
  231983. [theMovie setVolume: newVolume];
  231984. }
  231985. float QuickTimeMovieComponent::getMovieVolume() const
  231986. {
  231987. return movie != 0 ? [theMovie volume] : 0.0f;
  231988. }
  231989. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  231990. {
  231991. width = 0;
  231992. height = 0;
  231993. if (movie != 0)
  231994. {
  231995. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  231996. width = (int) s.width;
  231997. height = (int) s.height;
  231998. }
  231999. }
  232000. void QuickTimeMovieComponent::paint (Graphics& g)
  232001. {
  232002. if (movie == 0)
  232003. g.fillAll (Colours::black);
  232004. }
  232005. bool QuickTimeMovieComponent::isControllerVisible() const
  232006. {
  232007. return controllerVisible;
  232008. }
  232009. void QuickTimeMovieComponent::goToStart()
  232010. {
  232011. setPosition (0.0);
  232012. }
  232013. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  232014. const RectanglePlacement& placement)
  232015. {
  232016. int normalWidth, normalHeight;
  232017. getMovieNormalSize (normalWidth, normalHeight);
  232018. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  232019. {
  232020. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  232021. placement.applyTo (x, y, w, h,
  232022. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  232023. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  232024. if (w > 0 && h > 0)
  232025. {
  232026. setBounds (roundToInt (x), roundToInt (y),
  232027. roundToInt (w), roundToInt (h));
  232028. }
  232029. }
  232030. else
  232031. {
  232032. setBounds (spaceToFitWithin);
  232033. }
  232034. }
  232035. #if ! (JUCE_MAC && JUCE_64BIT)
  232036. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  232037. {
  232038. if (movieStream == 0)
  232039. return false;
  232040. File file;
  232041. QTMovie* movie = openMovieFromStream (movieStream, file);
  232042. if (movie != nil)
  232043. result = [movie quickTimeMovie];
  232044. return movie != nil;
  232045. }
  232046. #endif
  232047. #endif
  232048. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232049. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  232050. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232051. // compiled on its own).
  232052. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  232053. const int kilobytesPerSecond1x = 176;
  232054. END_JUCE_NAMESPACE
  232055. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  232056. @interface OpenDiskDevice : NSObject
  232057. {
  232058. @public
  232059. DRDevice* device;
  232060. NSMutableArray* tracks;
  232061. bool underrunProtection;
  232062. }
  232063. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  232064. - (void) dealloc;
  232065. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  232066. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232067. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  232068. @end
  232069. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  232070. @interface AudioTrackProducer : NSObject
  232071. {
  232072. JUCE_NAMESPACE::AudioSource* source;
  232073. int readPosition, lengthInFrames;
  232074. }
  232075. - (AudioTrackProducer*) init: (int) lengthInFrames;
  232076. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  232077. - (void) dealloc;
  232078. - (void) setupTrackProperties: (DRTrack*) track;
  232079. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  232080. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  232081. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  232082. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  232083. toMedia:(NSDictionary*)mediaInfo;
  232084. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  232085. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  232086. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232087. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232088. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232089. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232090. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232091. ioFlags:(uint32_t*)flags;
  232092. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  232093. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232094. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232095. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232096. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232097. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232098. ioFlags:(uint32_t*)flags;
  232099. @end
  232100. @implementation OpenDiskDevice
  232101. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  232102. {
  232103. [super init];
  232104. device = device_;
  232105. tracks = [[NSMutableArray alloc] init];
  232106. underrunProtection = true;
  232107. return self;
  232108. }
  232109. - (void) dealloc
  232110. {
  232111. [tracks release];
  232112. [super dealloc];
  232113. }
  232114. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  232115. {
  232116. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  232117. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  232118. [p setupTrackProperties: t];
  232119. [tracks addObject: t];
  232120. [t release];
  232121. [p release];
  232122. }
  232123. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232124. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  232125. {
  232126. DRBurn* burn = [DRBurn burnForDevice: device];
  232127. if (! [device acquireExclusiveAccess])
  232128. {
  232129. *error = "Couldn't open or write to the CD device";
  232130. return;
  232131. }
  232132. [device acquireMediaReservation];
  232133. NSMutableDictionary* d = [[burn properties] mutableCopy];
  232134. [d autorelease];
  232135. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  232136. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  232137. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  232138. if (burnSpeed > 0)
  232139. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  232140. if (! underrunProtection)
  232141. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  232142. [burn setProperties: d];
  232143. [burn writeLayout: tracks];
  232144. for (;;)
  232145. {
  232146. JUCE_NAMESPACE::Thread::sleep (300);
  232147. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  232148. if (listener != 0 && listener->audioCDBurnProgress (progress))
  232149. {
  232150. [burn abort];
  232151. *error = "User cancelled the write operation";
  232152. break;
  232153. }
  232154. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  232155. {
  232156. *error = "Write operation failed";
  232157. break;
  232158. }
  232159. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  232160. {
  232161. break;
  232162. }
  232163. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  232164. objectForKey: DRErrorStatusErrorStringKey];
  232165. if ([err length] > 0)
  232166. {
  232167. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  232168. break;
  232169. }
  232170. }
  232171. [device releaseMediaReservation];
  232172. [device releaseExclusiveAccess];
  232173. }
  232174. @end
  232175. @implementation AudioTrackProducer
  232176. - (AudioTrackProducer*) init: (int) lengthInFrames_
  232177. {
  232178. lengthInFrames = lengthInFrames_;
  232179. readPosition = 0;
  232180. return self;
  232181. }
  232182. - (void) setupTrackProperties: (DRTrack*) track
  232183. {
  232184. NSMutableDictionary* p = [[track properties] mutableCopy];
  232185. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  232186. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  232187. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  232188. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  232189. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  232190. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  232191. [track setProperties: p];
  232192. [p release];
  232193. }
  232194. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  232195. {
  232196. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  232197. if (s != nil)
  232198. s->source = source_;
  232199. return s;
  232200. }
  232201. - (void) dealloc
  232202. {
  232203. if (source != 0)
  232204. {
  232205. source->releaseResources();
  232206. delete source;
  232207. }
  232208. [super dealloc];
  232209. }
  232210. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  232211. {
  232212. }
  232213. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  232214. {
  232215. return true;
  232216. }
  232217. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  232218. {
  232219. return lengthInFrames;
  232220. }
  232221. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  232222. toMedia: (NSDictionary*) mediaInfo
  232223. {
  232224. if (source != 0)
  232225. source->prepareToPlay (44100 / 75, 44100);
  232226. readPosition = 0;
  232227. return true;
  232228. }
  232229. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  232230. {
  232231. if (source != 0)
  232232. source->prepareToPlay (44100 / 75, 44100);
  232233. return true;
  232234. }
  232235. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  232236. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232237. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232238. {
  232239. if (source != 0)
  232240. {
  232241. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  232242. if (numSamples > 0)
  232243. {
  232244. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  232245. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  232246. info.buffer = &tempBuffer;
  232247. info.startSample = 0;
  232248. info.numSamples = numSamples;
  232249. source->getNextAudioBlock (info);
  232250. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  232251. buffer, numSamples, 4);
  232252. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  232253. buffer + 2, numSamples, 4);
  232254. readPosition += numSamples;
  232255. }
  232256. return numSamples * 4;
  232257. }
  232258. return 0;
  232259. }
  232260. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  232261. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  232262. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  232263. ioFlags: (uint32_t*) flags
  232264. {
  232265. zeromem (buffer, bufferLength);
  232266. return bufferLength;
  232267. }
  232268. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  232269. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232270. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232271. {
  232272. return true;
  232273. }
  232274. @end
  232275. BEGIN_JUCE_NAMESPACE
  232276. class AudioCDBurner::Pimpl : public Timer
  232277. {
  232278. public:
  232279. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  232280. : device (0), owner (owner_)
  232281. {
  232282. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  232283. if (dev != 0)
  232284. {
  232285. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  232286. lastState = getDiskState();
  232287. startTimer (1000);
  232288. }
  232289. }
  232290. ~Pimpl()
  232291. {
  232292. stopTimer();
  232293. [device release];
  232294. }
  232295. void timerCallback()
  232296. {
  232297. const DiskState state = getDiskState();
  232298. if (state != lastState)
  232299. {
  232300. lastState = state;
  232301. owner.sendChangeMessage (&owner);
  232302. }
  232303. }
  232304. DiskState getDiskState() const
  232305. {
  232306. if ([device->device isValid])
  232307. {
  232308. NSDictionary* status = [device->device status];
  232309. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  232310. if ([state isEqualTo: DRDeviceMediaStateNone])
  232311. {
  232312. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  232313. return trayOpen;
  232314. return noDisc;
  232315. }
  232316. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  232317. {
  232318. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  232319. return writableDiskPresent;
  232320. else
  232321. return readOnlyDiskPresent;
  232322. }
  232323. }
  232324. return unknown;
  232325. }
  232326. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  232327. const Array<int> getAvailableWriteSpeeds() const
  232328. {
  232329. Array<int> results;
  232330. if ([device->device isValid])
  232331. {
  232332. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  232333. for (unsigned int i = 0; i < [speeds count]; ++i)
  232334. {
  232335. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  232336. results.add (kbPerSec / kilobytesPerSecond1x);
  232337. }
  232338. }
  232339. return results;
  232340. }
  232341. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  232342. {
  232343. if ([device->device isValid])
  232344. {
  232345. device->underrunProtection = shouldBeEnabled;
  232346. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  232347. }
  232348. return false;
  232349. }
  232350. int getNumAvailableAudioBlocks() const
  232351. {
  232352. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  232353. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  232354. }
  232355. OpenDiskDevice* device;
  232356. private:
  232357. DiskState lastState;
  232358. AudioCDBurner& owner;
  232359. };
  232360. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  232361. {
  232362. pimpl = new Pimpl (*this, deviceIndex);
  232363. }
  232364. AudioCDBurner::~AudioCDBurner()
  232365. {
  232366. }
  232367. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  232368. {
  232369. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  232370. if (b->pimpl->device == 0)
  232371. b = 0;
  232372. return b.release();
  232373. }
  232374. static NSArray* findDiskBurnerDevices()
  232375. {
  232376. NSMutableArray* results = [NSMutableArray array];
  232377. NSArray* devs = [DRDevice devices];
  232378. if (devs != 0)
  232379. {
  232380. int num = [devs count];
  232381. int i;
  232382. for (i = 0; i < num; ++i)
  232383. {
  232384. NSDictionary* dic = [[devs objectAtIndex: i] info];
  232385. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  232386. if (name != nil)
  232387. [results addObject: name];
  232388. }
  232389. }
  232390. return results;
  232391. }
  232392. const StringArray AudioCDBurner::findAvailableDevices()
  232393. {
  232394. NSArray* names = findDiskBurnerDevices();
  232395. StringArray s;
  232396. for (unsigned int i = 0; i < [names count]; ++i)
  232397. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  232398. return s;
  232399. }
  232400. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  232401. {
  232402. return pimpl->getDiskState();
  232403. }
  232404. bool AudioCDBurner::isDiskPresent() const
  232405. {
  232406. return getDiskState() == writableDiskPresent;
  232407. }
  232408. bool AudioCDBurner::openTray()
  232409. {
  232410. return pimpl->openTray();
  232411. }
  232412. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  232413. {
  232414. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  232415. DiskState oldState = getDiskState();
  232416. DiskState newState = oldState;
  232417. while (newState == oldState && Time::currentTimeMillis() < timeout)
  232418. {
  232419. newState = getDiskState();
  232420. Thread::sleep (100);
  232421. }
  232422. return newState;
  232423. }
  232424. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  232425. {
  232426. return pimpl->getAvailableWriteSpeeds();
  232427. }
  232428. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  232429. {
  232430. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  232431. }
  232432. int AudioCDBurner::getNumAvailableAudioBlocks() const
  232433. {
  232434. return pimpl->getNumAvailableAudioBlocks();
  232435. }
  232436. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  232437. {
  232438. if ([pimpl->device->device isValid])
  232439. {
  232440. [pimpl->device addSourceTrack: source numSamples: numSamps];
  232441. return true;
  232442. }
  232443. return false;
  232444. }
  232445. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  232446. bool ejectDiscAfterwards,
  232447. bool performFakeBurnForTesting,
  232448. int writeSpeed)
  232449. {
  232450. String error ("Couldn't open or write to the CD device");
  232451. if ([pimpl->device->device isValid])
  232452. {
  232453. error = String::empty;
  232454. [pimpl->device burn: listener
  232455. errorString: &error
  232456. ejectAfterwards: ejectDiscAfterwards
  232457. isFake: performFakeBurnForTesting
  232458. speed: writeSpeed];
  232459. }
  232460. return error;
  232461. }
  232462. #endif
  232463. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232464. void AudioCDReader::ejectDisk()
  232465. {
  232466. const ScopedAutoReleasePool p;
  232467. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  232468. }
  232469. #endif
  232470. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  232471. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  232472. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232473. // compiled on its own).
  232474. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232475. static void juce_findCDs (Array<File>& cds)
  232476. {
  232477. File volumes ("/Volumes");
  232478. volumes.findChildFiles (cds, File::findDirectories, false);
  232479. for (int i = cds.size(); --i >= 0;)
  232480. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  232481. cds.remove (i);
  232482. }
  232483. const StringArray AudioCDReader::getAvailableCDNames()
  232484. {
  232485. Array<File> cds;
  232486. juce_findCDs (cds);
  232487. StringArray names;
  232488. for (int i = 0; i < cds.size(); ++i)
  232489. names.add (cds.getReference(i).getFileName());
  232490. return names;
  232491. }
  232492. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  232493. {
  232494. Array<File> cds;
  232495. juce_findCDs (cds);
  232496. if (cds[index].exists())
  232497. return new AudioCDReader (cds[index]);
  232498. return 0;
  232499. }
  232500. AudioCDReader::AudioCDReader (const File& volume)
  232501. : AudioFormatReader (0, "CD Audio"),
  232502. volumeDir (volume),
  232503. currentReaderTrack (-1),
  232504. reader (0)
  232505. {
  232506. sampleRate = 44100.0;
  232507. bitsPerSample = 16;
  232508. numChannels = 2;
  232509. usesFloatingPointData = false;
  232510. refreshTrackLengths();
  232511. }
  232512. AudioCDReader::~AudioCDReader()
  232513. {
  232514. }
  232515. static int juce_getCDTrackNumber (const File& file)
  232516. {
  232517. return file.getFileName()
  232518. .initialSectionContainingOnly ("0123456789")
  232519. .getIntValue();
  232520. }
  232521. int AudioCDReader::compareElements (const File& first, const File& second)
  232522. {
  232523. const int firstTrack = juce_getCDTrackNumber (first);
  232524. const int secondTrack = juce_getCDTrackNumber (second);
  232525. jassert (firstTrack > 0 && secondTrack > 0);
  232526. return firstTrack - secondTrack;
  232527. }
  232528. void AudioCDReader::refreshTrackLengths()
  232529. {
  232530. tracks.clear();
  232531. trackStartSamples.clear();
  232532. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  232533. tracks.sort (*this);
  232534. AiffAudioFormat format;
  232535. int sample = 0;
  232536. for (int i = 0; i < tracks.size(); ++i)
  232537. {
  232538. trackStartSamples.add (sample);
  232539. FileInputStream* const in = tracks.getReference(i).createInputStream();
  232540. if (in != 0)
  232541. {
  232542. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  232543. if (r != 0)
  232544. sample += (int) r->lengthInSamples;
  232545. }
  232546. }
  232547. trackStartSamples.add (sample);
  232548. lengthInSamples = sample;
  232549. }
  232550. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  232551. int64 startSampleInFile, int numSamples)
  232552. {
  232553. while (numSamples > 0)
  232554. {
  232555. int track = -1;
  232556. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  232557. {
  232558. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  232559. {
  232560. track = i;
  232561. break;
  232562. }
  232563. }
  232564. if (track < 0)
  232565. return false;
  232566. if (track != currentReaderTrack)
  232567. {
  232568. reader = 0;
  232569. FileInputStream* const in = tracks [track].createInputStream();
  232570. if (in != 0)
  232571. {
  232572. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  232573. AiffAudioFormat format;
  232574. reader = format.createReaderFor (bin, true);
  232575. if (reader == 0)
  232576. currentReaderTrack = -1;
  232577. else
  232578. currentReaderTrack = track;
  232579. }
  232580. }
  232581. if (reader == 0)
  232582. return false;
  232583. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  232584. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  232585. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  232586. numSamples -= numAvailable;
  232587. startSampleInFile += numAvailable;
  232588. }
  232589. return true;
  232590. }
  232591. bool AudioCDReader::isCDStillPresent() const
  232592. {
  232593. return volumeDir.exists();
  232594. }
  232595. int AudioCDReader::getNumTracks() const
  232596. {
  232597. return tracks.size();
  232598. }
  232599. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  232600. {
  232601. return trackStartSamples [trackNum];
  232602. }
  232603. bool AudioCDReader::isTrackAudio (int trackNum) const
  232604. {
  232605. return tracks [trackNum] != File::nonexistent;
  232606. }
  232607. void AudioCDReader::enableIndexScanning (bool b)
  232608. {
  232609. // any way to do this on a Mac??
  232610. }
  232611. int AudioCDReader::getLastIndex() const
  232612. {
  232613. return 0;
  232614. }
  232615. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  232616. {
  232617. return Array <int>();
  232618. }
  232619. int AudioCDReader::getCDDBId()
  232620. {
  232621. return 0; //xxx
  232622. }
  232623. #endif
  232624. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  232625. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  232626. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232627. // compiled on its own).
  232628. #if JUCE_INCLUDED_FILE
  232629. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  232630. for example having more than one juce plugin loaded into a host, then when a
  232631. method is called, the actual code that runs might actually be in a different module
  232632. than the one you expect... So any calls to library functions or statics that are
  232633. made inside obj-c methods will probably end up getting executed in a different DLL's
  232634. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  232635. To work around this insanity, I'm only allowing obj-c methods to make calls to
  232636. virtual methods of an object that's known to live inside the right module's space.
  232637. */
  232638. class AppDelegateRedirector
  232639. {
  232640. public:
  232641. AppDelegateRedirector()
  232642. {
  232643. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  232644. runLoop = CFRunLoopGetMain();
  232645. #else
  232646. runLoop = CFRunLoopGetCurrent();
  232647. #endif
  232648. CFRunLoopSourceContext sourceContext;
  232649. zerostruct (sourceContext);
  232650. sourceContext.info = this;
  232651. sourceContext.perform = runLoopSourceCallback;
  232652. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  232653. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  232654. }
  232655. virtual ~AppDelegateRedirector()
  232656. {
  232657. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  232658. CFRunLoopSourceInvalidate (runLoopSource);
  232659. CFRelease (runLoopSource);
  232660. while (messages.size() > 0)
  232661. delete static_cast <Message*> (messages.remove(0));
  232662. }
  232663. virtual NSApplicationTerminateReply shouldTerminate()
  232664. {
  232665. if (JUCEApplication::getInstance() != 0)
  232666. {
  232667. JUCEApplication::getInstance()->systemRequestedQuit();
  232668. return NSTerminateCancel;
  232669. }
  232670. return NSTerminateNow;
  232671. }
  232672. virtual BOOL openFile (const NSString* filename)
  232673. {
  232674. if (JUCEApplication::getInstance() != 0)
  232675. {
  232676. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  232677. return YES;
  232678. }
  232679. return NO;
  232680. }
  232681. virtual void openFiles (NSArray* filenames)
  232682. {
  232683. StringArray files;
  232684. for (unsigned int i = 0; i < [filenames count]; ++i)
  232685. {
  232686. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  232687. if (filename.containsChar (' '))
  232688. filename = filename.quoted('"');
  232689. files.add (filename);
  232690. }
  232691. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  232692. {
  232693. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  232694. }
  232695. }
  232696. virtual void focusChanged()
  232697. {
  232698. juce_HandleProcessFocusChange();
  232699. }
  232700. struct CallbackMessagePayload
  232701. {
  232702. MessageCallbackFunction* function;
  232703. void* parameter;
  232704. void* volatile result;
  232705. bool volatile hasBeenExecuted;
  232706. };
  232707. virtual void performCallback (CallbackMessagePayload* pl)
  232708. {
  232709. pl->result = (*pl->function) (pl->parameter);
  232710. pl->hasBeenExecuted = true;
  232711. }
  232712. virtual void deleteSelf()
  232713. {
  232714. delete this;
  232715. }
  232716. void postMessage (void* m)
  232717. {
  232718. messages.add (m);
  232719. CFRunLoopSourceSignal (runLoopSource);
  232720. CFRunLoopWakeUp (runLoop);
  232721. }
  232722. private:
  232723. CFRunLoopRef runLoop;
  232724. CFRunLoopSourceRef runLoopSource;
  232725. Array <void*, CriticalSection> messages;
  232726. void runLoopCallback()
  232727. {
  232728. int numDispatched = 0;
  232729. do
  232730. {
  232731. void* const nextMessage = messages.remove (0);
  232732. if (nextMessage == 0)
  232733. return;
  232734. const ScopedAutoReleasePool pool;
  232735. MessageManager::getInstance()->deliverMessage (nextMessage);
  232736. } while (++numDispatched <= 4);
  232737. CFRunLoopSourceSignal (runLoopSource);
  232738. CFRunLoopWakeUp (runLoop);
  232739. }
  232740. static void runLoopSourceCallback (void* info)
  232741. {
  232742. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  232743. }
  232744. };
  232745. END_JUCE_NAMESPACE
  232746. using namespace JUCE_NAMESPACE;
  232747. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  232748. @interface JuceAppDelegate : NSObject
  232749. {
  232750. @private
  232751. id oldDelegate;
  232752. @public
  232753. AppDelegateRedirector* redirector;
  232754. }
  232755. - (JuceAppDelegate*) init;
  232756. - (void) dealloc;
  232757. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  232758. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  232759. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  232760. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  232761. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  232762. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  232763. - (void) performCallback: (id) info;
  232764. - (void) dummyMethod;
  232765. @end
  232766. @implementation JuceAppDelegate
  232767. - (JuceAppDelegate*) init
  232768. {
  232769. [super init];
  232770. redirector = new AppDelegateRedirector();
  232771. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  232772. if (JUCEApplication::getInstance() != 0)
  232773. {
  232774. oldDelegate = [NSApp delegate];
  232775. [NSApp setDelegate: self];
  232776. }
  232777. else
  232778. {
  232779. oldDelegate = 0;
  232780. [center addObserver: self selector: @selector (applicationDidResignActive:)
  232781. name: NSApplicationDidResignActiveNotification object: NSApp];
  232782. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  232783. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  232784. [center addObserver: self selector: @selector (applicationWillUnhide:)
  232785. name: NSApplicationWillUnhideNotification object: NSApp];
  232786. }
  232787. return self;
  232788. }
  232789. - (void) dealloc
  232790. {
  232791. if (oldDelegate != 0)
  232792. [NSApp setDelegate: oldDelegate];
  232793. redirector->deleteSelf();
  232794. [super dealloc];
  232795. }
  232796. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  232797. {
  232798. (void) app;
  232799. return redirector->shouldTerminate();
  232800. }
  232801. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  232802. {
  232803. (void) app;
  232804. return redirector->openFile (filename);
  232805. }
  232806. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  232807. {
  232808. (void) sender;
  232809. return redirector->openFiles (filenames);
  232810. }
  232811. - (void) applicationDidBecomeActive: (NSNotification*) notification
  232812. {
  232813. (void) notification;
  232814. redirector->focusChanged();
  232815. }
  232816. - (void) applicationDidResignActive: (NSNotification*) notification
  232817. {
  232818. (void) notification;
  232819. redirector->focusChanged();
  232820. }
  232821. - (void) applicationWillUnhide: (NSNotification*) notification
  232822. {
  232823. (void) notification;
  232824. redirector->focusChanged();
  232825. }
  232826. - (void) performCallback: (id) info
  232827. {
  232828. if ([info isKindOfClass: [NSData class]])
  232829. {
  232830. AppDelegateRedirector::CallbackMessagePayload* pl
  232831. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  232832. if (pl != 0)
  232833. redirector->performCallback (pl);
  232834. }
  232835. else
  232836. {
  232837. jassertfalse; // should never get here!
  232838. }
  232839. }
  232840. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  232841. @end
  232842. BEGIN_JUCE_NAMESPACE
  232843. static JuceAppDelegate* juceAppDelegate = 0;
  232844. void MessageManager::runDispatchLoop()
  232845. {
  232846. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  232847. {
  232848. const ScopedAutoReleasePool pool;
  232849. // must only be called by the message thread!
  232850. jassert (isThisTheMessageThread());
  232851. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  232852. @try
  232853. {
  232854. [NSApp run];
  232855. }
  232856. @catch (NSException* e)
  232857. {
  232858. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  232859. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  232860. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  232861. }
  232862. @finally
  232863. {
  232864. }
  232865. #else
  232866. [NSApp run];
  232867. #endif
  232868. }
  232869. }
  232870. void MessageManager::stopDispatchLoop()
  232871. {
  232872. quitMessagePosted = true;
  232873. [NSApp stop: nil];
  232874. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  232875. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  232876. }
  232877. static bool isEventBlockedByModalComps (NSEvent* e)
  232878. {
  232879. if (Component::getNumCurrentlyModalComponents() == 0)
  232880. return false;
  232881. NSWindow* const w = [e window];
  232882. if (w == 0 || [w worksWhenModal])
  232883. return false;
  232884. bool isKey = false, isInputAttempt = false;
  232885. switch ([e type])
  232886. {
  232887. case NSKeyDown:
  232888. case NSKeyUp:
  232889. isKey = isInputAttempt = true;
  232890. break;
  232891. case NSLeftMouseDown:
  232892. case NSRightMouseDown:
  232893. case NSOtherMouseDown:
  232894. isInputAttempt = true;
  232895. break;
  232896. case NSLeftMouseDragged:
  232897. case NSRightMouseDragged:
  232898. case NSLeftMouseUp:
  232899. case NSRightMouseUp:
  232900. case NSOtherMouseUp:
  232901. case NSOtherMouseDragged:
  232902. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  232903. return false;
  232904. break;
  232905. case NSMouseMoved:
  232906. case NSMouseEntered:
  232907. case NSMouseExited:
  232908. case NSCursorUpdate:
  232909. case NSScrollWheel:
  232910. case NSTabletPoint:
  232911. case NSTabletProximity:
  232912. break;
  232913. default:
  232914. return false;
  232915. }
  232916. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  232917. {
  232918. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  232919. NSView* const compView = (NSView*) peer->getNativeHandle();
  232920. if ([compView window] == w)
  232921. {
  232922. if (isKey)
  232923. {
  232924. if (compView == [w firstResponder])
  232925. return false;
  232926. }
  232927. else
  232928. {
  232929. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  232930. [compView bounds]))
  232931. return false;
  232932. }
  232933. }
  232934. }
  232935. if (isInputAttempt)
  232936. {
  232937. if (! [NSApp isActive])
  232938. [NSApp activateIgnoringOtherApps: YES];
  232939. Component* const modal = Component::getCurrentlyModalComponent (0);
  232940. if (modal != 0)
  232941. modal->inputAttemptWhenModal();
  232942. }
  232943. return true;
  232944. }
  232945. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  232946. {
  232947. const ScopedAutoReleasePool pool;
  232948. jassert (isThisTheMessageThread()); // must only be called by the message thread
  232949. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  232950. while (! quitMessagePosted)
  232951. {
  232952. const ScopedAutoReleasePool pool2;
  232953. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  232954. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  232955. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  232956. inMode: NSDefaultRunLoopMode
  232957. dequeue: YES];
  232958. if (e != 0 && ! isEventBlockedByModalComps (e))
  232959. [NSApp sendEvent: e];
  232960. if (Time::getMillisecondCounter() >= endTime)
  232961. break;
  232962. }
  232963. return ! quitMessagePosted;
  232964. }
  232965. void MessageManager::doPlatformSpecificInitialisation()
  232966. {
  232967. if (juceAppDelegate == 0)
  232968. juceAppDelegate = [[JuceAppDelegate alloc] init];
  232969. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  232970. // correctly (needed prior to 10.5)
  232971. if (! [NSThread isMultiThreaded])
  232972. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  232973. toTarget: juceAppDelegate
  232974. withObject: nil];
  232975. initialiseMainMenu();
  232976. }
  232977. void MessageManager::doPlatformSpecificShutdown()
  232978. {
  232979. if (juceAppDelegate != 0)
  232980. {
  232981. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  232982. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  232983. [juceAppDelegate release];
  232984. juceAppDelegate = 0;
  232985. }
  232986. }
  232987. bool juce_postMessageToSystemQueue (void* message)
  232988. {
  232989. juceAppDelegate->redirector->postMessage (message);
  232990. return true;
  232991. }
  232992. void MessageManager::broadcastMessage (const String& value) throw()
  232993. {
  232994. }
  232995. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  232996. void* data)
  232997. {
  232998. if (isThisTheMessageThread())
  232999. {
  233000. return (*callback) (data);
  233001. }
  233002. else
  233003. {
  233004. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  233005. // deadlock because the message manager is blocked from running, so can never
  233006. // call your function..
  233007. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  233008. const ScopedAutoReleasePool pool;
  233009. AppDelegateRedirector::CallbackMessagePayload cmp;
  233010. cmp.function = callback;
  233011. cmp.parameter = data;
  233012. cmp.result = 0;
  233013. cmp.hasBeenExecuted = false;
  233014. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  233015. withObject: [NSData dataWithBytesNoCopy: &cmp
  233016. length: sizeof (cmp)
  233017. freeWhenDone: NO]
  233018. waitUntilDone: YES];
  233019. return cmp.result;
  233020. }
  233021. }
  233022. #endif
  233023. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  233024. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233025. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233026. // compiled on its own).
  233027. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  233028. #if JUCE_MAC
  233029. END_JUCE_NAMESPACE
  233030. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  233031. @interface DownloadClickDetector : NSObject
  233032. {
  233033. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  233034. }
  233035. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  233036. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233037. request: (NSURLRequest*) request
  233038. frame: (WebFrame*) frame
  233039. decisionListener: (id<WebPolicyDecisionListener>) listener;
  233040. @end
  233041. @implementation DownloadClickDetector
  233042. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  233043. {
  233044. [super init];
  233045. ownerComponent = ownerComponent_;
  233046. return self;
  233047. }
  233048. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233049. request: (NSURLRequest*) request
  233050. frame: (WebFrame*) frame
  233051. decisionListener: (id <WebPolicyDecisionListener>) listener
  233052. {
  233053. (void) sender;
  233054. (void) request;
  233055. (void) frame;
  233056. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  233057. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  233058. [listener use];
  233059. else
  233060. [listener ignore];
  233061. }
  233062. @end
  233063. BEGIN_JUCE_NAMESPACE
  233064. class WebBrowserComponentInternal : public NSViewComponent
  233065. {
  233066. public:
  233067. WebBrowserComponentInternal (WebBrowserComponent* owner)
  233068. {
  233069. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233070. frameName: @""
  233071. groupName: @""];
  233072. setView (webView);
  233073. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  233074. [webView setPolicyDelegate: clickListener];
  233075. }
  233076. ~WebBrowserComponentInternal()
  233077. {
  233078. [webView setPolicyDelegate: nil];
  233079. [clickListener release];
  233080. setView (0);
  233081. }
  233082. void goToURL (const String& url,
  233083. const StringArray* headers,
  233084. const MemoryBlock* postData)
  233085. {
  233086. NSMutableURLRequest* r
  233087. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  233088. cachePolicy: NSURLRequestUseProtocolCachePolicy
  233089. timeoutInterval: 30.0];
  233090. if (postData != 0 && postData->getSize() > 0)
  233091. {
  233092. [r setHTTPMethod: @"POST"];
  233093. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  233094. length: postData->getSize()]];
  233095. }
  233096. if (headers != 0)
  233097. {
  233098. for (int i = 0; i < headers->size(); ++i)
  233099. {
  233100. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  233101. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  233102. [r setValue: juceStringToNS (headerValue)
  233103. forHTTPHeaderField: juceStringToNS (headerName)];
  233104. }
  233105. }
  233106. stop();
  233107. [[webView mainFrame] loadRequest: r];
  233108. }
  233109. void goBack()
  233110. {
  233111. [webView goBack];
  233112. }
  233113. void goForward()
  233114. {
  233115. [webView goForward];
  233116. }
  233117. void stop()
  233118. {
  233119. [webView stopLoading: nil];
  233120. }
  233121. void refresh()
  233122. {
  233123. [webView reload: nil];
  233124. }
  233125. private:
  233126. WebView* webView;
  233127. DownloadClickDetector* clickListener;
  233128. };
  233129. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233130. : browser (0),
  233131. blankPageShown (false),
  233132. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  233133. {
  233134. setOpaque (true);
  233135. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  233136. }
  233137. WebBrowserComponent::~WebBrowserComponent()
  233138. {
  233139. deleteAndZero (browser);
  233140. }
  233141. void WebBrowserComponent::goToURL (const String& url,
  233142. const StringArray* headers,
  233143. const MemoryBlock* postData)
  233144. {
  233145. lastURL = url;
  233146. lastHeaders.clear();
  233147. if (headers != 0)
  233148. lastHeaders = *headers;
  233149. lastPostData.setSize (0);
  233150. if (postData != 0)
  233151. lastPostData = *postData;
  233152. blankPageShown = false;
  233153. browser->goToURL (url, headers, postData);
  233154. }
  233155. void WebBrowserComponent::stop()
  233156. {
  233157. browser->stop();
  233158. }
  233159. void WebBrowserComponent::goBack()
  233160. {
  233161. lastURL = String::empty;
  233162. blankPageShown = false;
  233163. browser->goBack();
  233164. }
  233165. void WebBrowserComponent::goForward()
  233166. {
  233167. lastURL = String::empty;
  233168. browser->goForward();
  233169. }
  233170. void WebBrowserComponent::refresh()
  233171. {
  233172. browser->refresh();
  233173. }
  233174. void WebBrowserComponent::paint (Graphics&)
  233175. {
  233176. }
  233177. void WebBrowserComponent::checkWindowAssociation()
  233178. {
  233179. if (isShowing())
  233180. {
  233181. if (blankPageShown)
  233182. goBack();
  233183. }
  233184. else
  233185. {
  233186. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  233187. {
  233188. // when the component becomes invisible, some stuff like flash
  233189. // carries on playing audio, so we need to force it onto a blank
  233190. // page to avoid this, (and send it back when it's made visible again).
  233191. blankPageShown = true;
  233192. browser->goToURL ("about:blank", 0, 0);
  233193. }
  233194. }
  233195. }
  233196. void WebBrowserComponent::reloadLastURL()
  233197. {
  233198. if (lastURL.isNotEmpty())
  233199. {
  233200. goToURL (lastURL, &lastHeaders, &lastPostData);
  233201. lastURL = String::empty;
  233202. }
  233203. }
  233204. void WebBrowserComponent::parentHierarchyChanged()
  233205. {
  233206. checkWindowAssociation();
  233207. }
  233208. void WebBrowserComponent::resized()
  233209. {
  233210. browser->setSize (getWidth(), getHeight());
  233211. }
  233212. void WebBrowserComponent::visibilityChanged()
  233213. {
  233214. checkWindowAssociation();
  233215. }
  233216. bool WebBrowserComponent::pageAboutToLoad (const String&)
  233217. {
  233218. return true;
  233219. }
  233220. #else
  233221. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233222. {
  233223. }
  233224. WebBrowserComponent::~WebBrowserComponent()
  233225. {
  233226. }
  233227. void WebBrowserComponent::goToURL (const String& url,
  233228. const StringArray* headers,
  233229. const MemoryBlock* postData)
  233230. {
  233231. }
  233232. void WebBrowserComponent::stop()
  233233. {
  233234. }
  233235. void WebBrowserComponent::goBack()
  233236. {
  233237. }
  233238. void WebBrowserComponent::goForward()
  233239. {
  233240. }
  233241. void WebBrowserComponent::refresh()
  233242. {
  233243. }
  233244. void WebBrowserComponent::paint (Graphics& g)
  233245. {
  233246. }
  233247. void WebBrowserComponent::checkWindowAssociation()
  233248. {
  233249. }
  233250. void WebBrowserComponent::reloadLastURL()
  233251. {
  233252. }
  233253. void WebBrowserComponent::parentHierarchyChanged()
  233254. {
  233255. }
  233256. void WebBrowserComponent::resized()
  233257. {
  233258. }
  233259. void WebBrowserComponent::visibilityChanged()
  233260. {
  233261. }
  233262. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  233263. {
  233264. return true;
  233265. }
  233266. #endif
  233267. #endif
  233268. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233269. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  233270. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233271. // compiled on its own).
  233272. #if JUCE_INCLUDED_FILE
  233273. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233274. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  233275. #endif
  233276. #undef log
  233277. #if JUCE_COREAUDIO_LOGGING_ENABLED
  233278. #define log(a) Logger::writeToLog (a)
  233279. #else
  233280. #define log(a)
  233281. #endif
  233282. #undef OK
  233283. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233284. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  233285. {
  233286. if (err == noErr)
  233287. return true;
  233288. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  233289. jassertfalse;
  233290. return false;
  233291. }
  233292. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  233293. #else
  233294. #define OK(a) (a == noErr)
  233295. #endif
  233296. class CoreAudioInternal : public Timer
  233297. {
  233298. public:
  233299. CoreAudioInternal (AudioDeviceID id)
  233300. : inputLatency (0),
  233301. outputLatency (0),
  233302. callback (0),
  233303. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  233304. audioProcID (0),
  233305. #endif
  233306. inputDevice (0),
  233307. isSlaveDevice (false),
  233308. deviceID (id),
  233309. started (false),
  233310. sampleRate (0),
  233311. bufferSize (512),
  233312. numInputChans (0),
  233313. numOutputChans (0),
  233314. callbacksAllowed (true),
  233315. numInputChannelInfos (0),
  233316. numOutputChannelInfos (0)
  233317. {
  233318. jassert (deviceID != 0);
  233319. updateDetailsFromDevice();
  233320. AudioObjectPropertyAddress pa;
  233321. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233322. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233323. pa.mElement = kAudioObjectPropertyElementWildcard;
  233324. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  233325. }
  233326. ~CoreAudioInternal()
  233327. {
  233328. AudioObjectPropertyAddress pa;
  233329. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233330. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233331. pa.mElement = kAudioObjectPropertyElementWildcard;
  233332. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  233333. stop (false);
  233334. delete inputDevice;
  233335. }
  233336. void allocateTempBuffers()
  233337. {
  233338. const int tempBufSize = bufferSize + 4;
  233339. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  233340. tempInputBuffers.calloc (numInputChans + 2);
  233341. tempOutputBuffers.calloc (numOutputChans + 2);
  233342. int i, count = 0;
  233343. for (i = 0; i < numInputChans; ++i)
  233344. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233345. for (i = 0; i < numOutputChans; ++i)
  233346. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233347. }
  233348. // returns the number of actual available channels
  233349. void fillInChannelInfo (const bool input)
  233350. {
  233351. int chanNum = 0;
  233352. UInt32 size;
  233353. AudioObjectPropertyAddress pa;
  233354. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  233355. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233356. pa.mElement = kAudioObjectPropertyElementMaster;
  233357. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233358. {
  233359. HeapBlock <AudioBufferList> bufList;
  233360. bufList.calloc (size, 1);
  233361. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  233362. {
  233363. const int numStreams = bufList->mNumberBuffers;
  233364. for (int i = 0; i < numStreams; ++i)
  233365. {
  233366. const AudioBuffer& b = bufList->mBuffers[i];
  233367. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  233368. {
  233369. String name;
  233370. {
  233371. char channelName [256];
  233372. zerostruct (channelName);
  233373. UInt32 nameSize = sizeof (channelName);
  233374. UInt32 channelNum = chanNum + 1;
  233375. pa.mSelector = kAudioDevicePropertyChannelName;
  233376. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  233377. name = String::fromUTF8 (channelName, nameSize);
  233378. }
  233379. if (input)
  233380. {
  233381. if (activeInputChans[chanNum])
  233382. {
  233383. inputChannelInfo [numInputChannelInfos].streamNum = i;
  233384. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  233385. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233386. ++numInputChannelInfos;
  233387. }
  233388. if (name.isEmpty())
  233389. name << "Input " << (chanNum + 1);
  233390. inChanNames.add (name);
  233391. }
  233392. else
  233393. {
  233394. if (activeOutputChans[chanNum])
  233395. {
  233396. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  233397. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  233398. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233399. ++numOutputChannelInfos;
  233400. }
  233401. if (name.isEmpty())
  233402. name << "Output " << (chanNum + 1);
  233403. outChanNames.add (name);
  233404. }
  233405. ++chanNum;
  233406. }
  233407. }
  233408. }
  233409. }
  233410. }
  233411. void updateDetailsFromDevice()
  233412. {
  233413. stopTimer();
  233414. if (deviceID == 0)
  233415. return;
  233416. const ScopedLock sl (callbackLock);
  233417. Float64 sr;
  233418. UInt32 size = sizeof (Float64);
  233419. AudioObjectPropertyAddress pa;
  233420. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233421. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233422. pa.mElement = kAudioObjectPropertyElementMaster;
  233423. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  233424. sampleRate = sr;
  233425. UInt32 framesPerBuf;
  233426. size = sizeof (framesPerBuf);
  233427. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233428. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  233429. {
  233430. bufferSize = framesPerBuf;
  233431. allocateTempBuffers();
  233432. }
  233433. bufferSizes.clear();
  233434. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  233435. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233436. {
  233437. HeapBlock <AudioValueRange> ranges;
  233438. ranges.calloc (size, 1);
  233439. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233440. {
  233441. bufferSizes.add ((int) ranges[0].mMinimum);
  233442. for (int i = 32; i < 2048; i += 32)
  233443. {
  233444. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233445. {
  233446. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  233447. {
  233448. bufferSizes.addIfNotAlreadyThere (i);
  233449. break;
  233450. }
  233451. }
  233452. }
  233453. if (bufferSize > 0)
  233454. bufferSizes.addIfNotAlreadyThere (bufferSize);
  233455. }
  233456. }
  233457. if (bufferSizes.size() == 0 && bufferSize > 0)
  233458. bufferSizes.add (bufferSize);
  233459. sampleRates.clear();
  233460. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  233461. String rates;
  233462. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  233463. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233464. {
  233465. HeapBlock <AudioValueRange> ranges;
  233466. ranges.calloc (size, 1);
  233467. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233468. {
  233469. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  233470. {
  233471. bool ok = false;
  233472. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233473. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  233474. ok = true;
  233475. if (ok)
  233476. {
  233477. sampleRates.add (possibleRates[i]);
  233478. rates << possibleRates[i] << ' ';
  233479. }
  233480. }
  233481. }
  233482. }
  233483. if (sampleRates.size() == 0 && sampleRate > 0)
  233484. {
  233485. sampleRates.add (sampleRate);
  233486. rates << sampleRate;
  233487. }
  233488. log ("sr: " + rates);
  233489. inputLatency = 0;
  233490. outputLatency = 0;
  233491. UInt32 lat;
  233492. size = sizeof (lat);
  233493. pa.mSelector = kAudioDevicePropertyLatency;
  233494. pa.mScope = kAudioDevicePropertyScopeInput;
  233495. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  233496. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  233497. inputLatency = (int) lat;
  233498. pa.mScope = kAudioDevicePropertyScopeOutput;
  233499. size = sizeof (lat);
  233500. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  233501. outputLatency = (int) lat;
  233502. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  233503. inChanNames.clear();
  233504. outChanNames.clear();
  233505. inputChannelInfo.calloc (numInputChans + 2);
  233506. numInputChannelInfos = 0;
  233507. outputChannelInfo.calloc (numOutputChans + 2);
  233508. numOutputChannelInfos = 0;
  233509. fillInChannelInfo (true);
  233510. fillInChannelInfo (false);
  233511. }
  233512. const StringArray getSources (bool input)
  233513. {
  233514. StringArray s;
  233515. HeapBlock <OSType> types;
  233516. const int num = getAllDataSourcesForDevice (deviceID, types);
  233517. for (int i = 0; i < num; ++i)
  233518. {
  233519. AudioValueTranslation avt;
  233520. char buffer[256];
  233521. avt.mInputData = &(types[i]);
  233522. avt.mInputDataSize = sizeof (UInt32);
  233523. avt.mOutputData = buffer;
  233524. avt.mOutputDataSize = 256;
  233525. UInt32 transSize = sizeof (avt);
  233526. AudioObjectPropertyAddress pa;
  233527. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  233528. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233529. pa.mElement = kAudioObjectPropertyElementMaster;
  233530. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  233531. {
  233532. DBG (buffer);
  233533. s.add (buffer);
  233534. }
  233535. }
  233536. return s;
  233537. }
  233538. int getCurrentSourceIndex (bool input) const
  233539. {
  233540. OSType currentSourceID = 0;
  233541. UInt32 size = sizeof (currentSourceID);
  233542. int result = -1;
  233543. AudioObjectPropertyAddress pa;
  233544. pa.mSelector = kAudioDevicePropertyDataSource;
  233545. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233546. pa.mElement = kAudioObjectPropertyElementMaster;
  233547. if (deviceID != 0)
  233548. {
  233549. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  233550. {
  233551. HeapBlock <OSType> types;
  233552. const int num = getAllDataSourcesForDevice (deviceID, types);
  233553. for (int i = 0; i < num; ++i)
  233554. {
  233555. if (types[num] == currentSourceID)
  233556. {
  233557. result = i;
  233558. break;
  233559. }
  233560. }
  233561. }
  233562. }
  233563. return result;
  233564. }
  233565. void setCurrentSourceIndex (int index, bool input)
  233566. {
  233567. if (deviceID != 0)
  233568. {
  233569. HeapBlock <OSType> types;
  233570. const int num = getAllDataSourcesForDevice (deviceID, types);
  233571. if (((unsigned int) index) < (unsigned int) num)
  233572. {
  233573. AudioObjectPropertyAddress pa;
  233574. pa.mSelector = kAudioDevicePropertyDataSource;
  233575. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233576. pa.mElement = kAudioObjectPropertyElementMaster;
  233577. OSType typeId = types[index];
  233578. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  233579. }
  233580. }
  233581. }
  233582. const String reopen (const BigInteger& inputChannels,
  233583. const BigInteger& outputChannels,
  233584. double newSampleRate,
  233585. int bufferSizeSamples)
  233586. {
  233587. String error;
  233588. log ("CoreAudio reopen");
  233589. callbacksAllowed = false;
  233590. stopTimer();
  233591. stop (false);
  233592. activeInputChans = inputChannels;
  233593. activeInputChans.setRange (inChanNames.size(),
  233594. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  233595. false);
  233596. activeOutputChans = outputChannels;
  233597. activeOutputChans.setRange (outChanNames.size(),
  233598. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  233599. false);
  233600. numInputChans = activeInputChans.countNumberOfSetBits();
  233601. numOutputChans = activeOutputChans.countNumberOfSetBits();
  233602. // set sample rate
  233603. AudioObjectPropertyAddress pa;
  233604. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233605. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233606. pa.mElement = kAudioObjectPropertyElementMaster;
  233607. Float64 sr = newSampleRate;
  233608. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  233609. {
  233610. error = "Couldn't change sample rate";
  233611. }
  233612. else
  233613. {
  233614. // change buffer size
  233615. UInt32 framesPerBuf = bufferSizeSamples;
  233616. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233617. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  233618. {
  233619. error = "Couldn't change buffer size";
  233620. }
  233621. else
  233622. {
  233623. // Annoyingly, after changing the rate and buffer size, some devices fail to
  233624. // correctly report their new settings until some random time in the future, so
  233625. // after calling updateDetailsFromDevice, we need to manually bodge these values
  233626. // to make sure we're using the correct numbers..
  233627. updateDetailsFromDevice();
  233628. sampleRate = newSampleRate;
  233629. bufferSize = bufferSizeSamples;
  233630. if (sampleRates.size() == 0)
  233631. error = "Device has no available sample-rates";
  233632. else if (bufferSizes.size() == 0)
  233633. error = "Device has no available buffer-sizes";
  233634. else if (inputDevice != 0)
  233635. error = inputDevice->reopen (inputChannels,
  233636. outputChannels,
  233637. newSampleRate,
  233638. bufferSizeSamples);
  233639. }
  233640. }
  233641. callbacksAllowed = true;
  233642. return error;
  233643. }
  233644. bool start (AudioIODeviceCallback* cb)
  233645. {
  233646. if (! started)
  233647. {
  233648. callback = 0;
  233649. if (deviceID != 0)
  233650. {
  233651. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233652. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  233653. #else
  233654. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  233655. #endif
  233656. {
  233657. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  233658. {
  233659. started = true;
  233660. }
  233661. else
  233662. {
  233663. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233664. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  233665. #else
  233666. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  233667. audioProcID = 0;
  233668. #endif
  233669. }
  233670. }
  233671. }
  233672. }
  233673. if (started)
  233674. {
  233675. const ScopedLock sl (callbackLock);
  233676. callback = cb;
  233677. }
  233678. if (inputDevice != 0)
  233679. return started && inputDevice->start (cb);
  233680. else
  233681. return started;
  233682. }
  233683. void stop (bool leaveInterruptRunning)
  233684. {
  233685. {
  233686. const ScopedLock sl (callbackLock);
  233687. callback = 0;
  233688. }
  233689. if (started
  233690. && (deviceID != 0)
  233691. && ! leaveInterruptRunning)
  233692. {
  233693. OK (AudioDeviceStop (deviceID, audioIOProc));
  233694. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233695. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  233696. #else
  233697. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  233698. audioProcID = 0;
  233699. #endif
  233700. started = false;
  233701. { const ScopedLock sl (callbackLock); }
  233702. // wait until it's definately stopped calling back..
  233703. for (int i = 40; --i >= 0;)
  233704. {
  233705. Thread::sleep (50);
  233706. UInt32 running = 0;
  233707. UInt32 size = sizeof (running);
  233708. AudioObjectPropertyAddress pa;
  233709. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  233710. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233711. pa.mElement = kAudioObjectPropertyElementMaster;
  233712. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  233713. if (running == 0)
  233714. break;
  233715. }
  233716. const ScopedLock sl (callbackLock);
  233717. }
  233718. if (inputDevice != 0)
  233719. inputDevice->stop (leaveInterruptRunning);
  233720. }
  233721. double getSampleRate() const
  233722. {
  233723. return sampleRate;
  233724. }
  233725. int getBufferSize() const
  233726. {
  233727. return bufferSize;
  233728. }
  233729. void audioCallback (const AudioBufferList* inInputData,
  233730. AudioBufferList* outOutputData)
  233731. {
  233732. int i;
  233733. const ScopedLock sl (callbackLock);
  233734. if (callback != 0)
  233735. {
  233736. if (inputDevice == 0)
  233737. {
  233738. for (i = numInputChans; --i >= 0;)
  233739. {
  233740. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  233741. float* dest = tempInputBuffers [i];
  233742. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  233743. + info.dataOffsetSamples;
  233744. const int stride = info.dataStrideSamples;
  233745. if (stride != 0) // if this is zero, info is invalid
  233746. {
  233747. for (int j = bufferSize; --j >= 0;)
  233748. {
  233749. *dest++ = *src;
  233750. src += stride;
  233751. }
  233752. }
  233753. }
  233754. }
  233755. if (! isSlaveDevice)
  233756. {
  233757. if (inputDevice == 0)
  233758. {
  233759. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  233760. numInputChans,
  233761. tempOutputBuffers,
  233762. numOutputChans,
  233763. bufferSize);
  233764. }
  233765. else
  233766. {
  233767. jassert (inputDevice->bufferSize == bufferSize);
  233768. // Sometimes the two linked devices seem to get their callbacks in
  233769. // parallel, so we need to lock both devices to stop the input data being
  233770. // changed while inside our callback..
  233771. const ScopedLock sl2 (inputDevice->callbackLock);
  233772. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  233773. inputDevice->numInputChans,
  233774. tempOutputBuffers,
  233775. numOutputChans,
  233776. bufferSize);
  233777. }
  233778. for (i = numOutputChans; --i >= 0;)
  233779. {
  233780. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  233781. const float* src = tempOutputBuffers [i];
  233782. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  233783. + info.dataOffsetSamples;
  233784. const int stride = info.dataStrideSamples;
  233785. if (stride != 0) // if this is zero, info is invalid
  233786. {
  233787. for (int j = bufferSize; --j >= 0;)
  233788. {
  233789. *dest = *src++;
  233790. dest += stride;
  233791. }
  233792. }
  233793. }
  233794. }
  233795. }
  233796. else
  233797. {
  233798. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  233799. {
  233800. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  233801. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  233802. + info.dataOffsetSamples;
  233803. const int stride = info.dataStrideSamples;
  233804. if (stride != 0) // if this is zero, info is invalid
  233805. {
  233806. for (int j = bufferSize; --j >= 0;)
  233807. {
  233808. *dest = 0.0f;
  233809. dest += stride;
  233810. }
  233811. }
  233812. }
  233813. }
  233814. }
  233815. // called by callbacks
  233816. void deviceDetailsChanged()
  233817. {
  233818. if (callbacksAllowed)
  233819. startTimer (100);
  233820. }
  233821. void timerCallback()
  233822. {
  233823. stopTimer();
  233824. log ("CoreAudio device changed callback");
  233825. const double oldSampleRate = sampleRate;
  233826. const int oldBufferSize = bufferSize;
  233827. updateDetailsFromDevice();
  233828. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  233829. {
  233830. callbacksAllowed = false;
  233831. stop (false);
  233832. updateDetailsFromDevice();
  233833. callbacksAllowed = true;
  233834. }
  233835. }
  233836. CoreAudioInternal* getRelatedDevice() const
  233837. {
  233838. UInt32 size = 0;
  233839. ScopedPointer <CoreAudioInternal> result;
  233840. AudioObjectPropertyAddress pa;
  233841. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  233842. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233843. pa.mElement = kAudioObjectPropertyElementMaster;
  233844. if (deviceID != 0
  233845. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  233846. && size > 0)
  233847. {
  233848. HeapBlock <AudioDeviceID> devs;
  233849. devs.calloc (size, 1);
  233850. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  233851. {
  233852. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  233853. {
  233854. if (devs[i] != deviceID && devs[i] != 0)
  233855. {
  233856. result = new CoreAudioInternal (devs[i]);
  233857. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  233858. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  233859. if (thisIsInput != otherIsInput
  233860. || (inChanNames.size() + outChanNames.size() == 0)
  233861. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  233862. break;
  233863. result = 0;
  233864. }
  233865. }
  233866. }
  233867. }
  233868. return result.release();
  233869. }
  233870. juce_UseDebuggingNewOperator
  233871. int inputLatency, outputLatency;
  233872. BigInteger activeInputChans, activeOutputChans;
  233873. StringArray inChanNames, outChanNames;
  233874. Array <double> sampleRates;
  233875. Array <int> bufferSizes;
  233876. AudioIODeviceCallback* callback;
  233877. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  233878. AudioDeviceIOProcID audioProcID;
  233879. #endif
  233880. CoreAudioInternal* inputDevice;
  233881. bool isSlaveDevice;
  233882. private:
  233883. CriticalSection callbackLock;
  233884. AudioDeviceID deviceID;
  233885. bool started;
  233886. double sampleRate;
  233887. int bufferSize;
  233888. HeapBlock <float> audioBuffer;
  233889. int numInputChans, numOutputChans;
  233890. bool callbacksAllowed;
  233891. struct CallbackDetailsForChannel
  233892. {
  233893. int streamNum;
  233894. int dataOffsetSamples;
  233895. int dataStrideSamples;
  233896. };
  233897. int numInputChannelInfos, numOutputChannelInfos;
  233898. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  233899. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  233900. CoreAudioInternal (const CoreAudioInternal&);
  233901. CoreAudioInternal& operator= (const CoreAudioInternal&);
  233902. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  233903. const AudioTimeStamp* /*inNow*/,
  233904. const AudioBufferList* inInputData,
  233905. const AudioTimeStamp* /*inInputTime*/,
  233906. AudioBufferList* outOutputData,
  233907. const AudioTimeStamp* /*inOutputTime*/,
  233908. void* device)
  233909. {
  233910. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  233911. return noErr;
  233912. }
  233913. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  233914. {
  233915. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  233916. switch (pa->mSelector)
  233917. {
  233918. case kAudioDevicePropertyBufferSize:
  233919. case kAudioDevicePropertyBufferFrameSize:
  233920. case kAudioDevicePropertyNominalSampleRate:
  233921. case kAudioDevicePropertyStreamFormat:
  233922. case kAudioDevicePropertyDeviceIsAlive:
  233923. intern->deviceDetailsChanged();
  233924. break;
  233925. case kAudioDevicePropertyBufferSizeRange:
  233926. case kAudioDevicePropertyVolumeScalar:
  233927. case kAudioDevicePropertyMute:
  233928. case kAudioDevicePropertyPlayThru:
  233929. case kAudioDevicePropertyDataSource:
  233930. case kAudioDevicePropertyDeviceIsRunning:
  233931. break;
  233932. }
  233933. return noErr;
  233934. }
  233935. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  233936. {
  233937. AudioObjectPropertyAddress pa;
  233938. pa.mSelector = kAudioDevicePropertyDataSources;
  233939. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233940. pa.mElement = kAudioObjectPropertyElementMaster;
  233941. UInt32 size = 0;
  233942. if (deviceID != 0
  233943. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233944. {
  233945. types.calloc (size, 1);
  233946. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  233947. return size / (int) sizeof (OSType);
  233948. }
  233949. return 0;
  233950. }
  233951. };
  233952. class CoreAudioIODevice : public AudioIODevice
  233953. {
  233954. public:
  233955. CoreAudioIODevice (const String& deviceName,
  233956. AudioDeviceID inputDeviceId,
  233957. const int inputIndex_,
  233958. AudioDeviceID outputDeviceId,
  233959. const int outputIndex_)
  233960. : AudioIODevice (deviceName, "CoreAudio"),
  233961. inputIndex (inputIndex_),
  233962. outputIndex (outputIndex_),
  233963. isOpen_ (false),
  233964. isStarted (false)
  233965. {
  233966. internal = 0;
  233967. CoreAudioInternal* device = 0;
  233968. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  233969. {
  233970. jassert (inputDeviceId != 0);
  233971. device = new CoreAudioInternal (inputDeviceId);
  233972. }
  233973. else
  233974. {
  233975. device = new CoreAudioInternal (outputDeviceId);
  233976. if (inputDeviceId != 0)
  233977. {
  233978. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  233979. device->inputDevice = secondDevice;
  233980. secondDevice->isSlaveDevice = true;
  233981. }
  233982. }
  233983. internal = device;
  233984. AudioObjectPropertyAddress pa;
  233985. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233986. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233987. pa.mElement = kAudioObjectPropertyElementWildcard;
  233988. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  233989. }
  233990. ~CoreAudioIODevice()
  233991. {
  233992. AudioObjectPropertyAddress pa;
  233993. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233994. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233995. pa.mElement = kAudioObjectPropertyElementWildcard;
  233996. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  233997. delete internal;
  233998. }
  233999. const StringArray getOutputChannelNames()
  234000. {
  234001. return internal->outChanNames;
  234002. }
  234003. const StringArray getInputChannelNames()
  234004. {
  234005. if (internal->inputDevice != 0)
  234006. return internal->inputDevice->inChanNames;
  234007. else
  234008. return internal->inChanNames;
  234009. }
  234010. int getNumSampleRates()
  234011. {
  234012. return internal->sampleRates.size();
  234013. }
  234014. double getSampleRate (int index)
  234015. {
  234016. return internal->sampleRates [index];
  234017. }
  234018. int getNumBufferSizesAvailable()
  234019. {
  234020. return internal->bufferSizes.size();
  234021. }
  234022. int getBufferSizeSamples (int index)
  234023. {
  234024. return internal->bufferSizes [index];
  234025. }
  234026. int getDefaultBufferSize()
  234027. {
  234028. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  234029. if (getBufferSizeSamples(i) >= 512)
  234030. return getBufferSizeSamples(i);
  234031. return 512;
  234032. }
  234033. const String open (const BigInteger& inputChannels,
  234034. const BigInteger& outputChannels,
  234035. double sampleRate,
  234036. int bufferSizeSamples)
  234037. {
  234038. isOpen_ = true;
  234039. if (bufferSizeSamples <= 0)
  234040. bufferSizeSamples = getDefaultBufferSize();
  234041. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  234042. isOpen_ = lastError.isEmpty();
  234043. return lastError;
  234044. }
  234045. void close()
  234046. {
  234047. isOpen_ = false;
  234048. internal->stop (false);
  234049. }
  234050. bool isOpen()
  234051. {
  234052. return isOpen_;
  234053. }
  234054. int getCurrentBufferSizeSamples()
  234055. {
  234056. return internal != 0 ? internal->getBufferSize() : 512;
  234057. }
  234058. double getCurrentSampleRate()
  234059. {
  234060. return internal != 0 ? internal->getSampleRate() : 0;
  234061. }
  234062. int getCurrentBitDepth()
  234063. {
  234064. return 32; // no way to find out, so just assume it's high..
  234065. }
  234066. const BigInteger getActiveOutputChannels() const
  234067. {
  234068. return internal != 0 ? internal->activeOutputChans : BigInteger();
  234069. }
  234070. const BigInteger getActiveInputChannels() const
  234071. {
  234072. BigInteger chans;
  234073. if (internal != 0)
  234074. {
  234075. chans = internal->activeInputChans;
  234076. if (internal->inputDevice != 0)
  234077. chans |= internal->inputDevice->activeInputChans;
  234078. }
  234079. return chans;
  234080. }
  234081. int getOutputLatencyInSamples()
  234082. {
  234083. if (internal == 0)
  234084. return 0;
  234085. // this seems like a good guess at getting the latency right - comparing
  234086. // this with a round-trip measurement, it gets it to within a few millisecs
  234087. // for the built-in mac soundcard
  234088. return internal->outputLatency + internal->getBufferSize() * 2;
  234089. }
  234090. int getInputLatencyInSamples()
  234091. {
  234092. if (internal == 0)
  234093. return 0;
  234094. return internal->inputLatency + internal->getBufferSize() * 2;
  234095. }
  234096. void start (AudioIODeviceCallback* callback)
  234097. {
  234098. if (internal != 0 && ! isStarted)
  234099. {
  234100. if (callback != 0)
  234101. callback->audioDeviceAboutToStart (this);
  234102. isStarted = true;
  234103. internal->start (callback);
  234104. }
  234105. }
  234106. void stop()
  234107. {
  234108. if (isStarted && internal != 0)
  234109. {
  234110. AudioIODeviceCallback* const lastCallback = internal->callback;
  234111. isStarted = false;
  234112. internal->stop (true);
  234113. if (lastCallback != 0)
  234114. lastCallback->audioDeviceStopped();
  234115. }
  234116. }
  234117. bool isPlaying()
  234118. {
  234119. if (internal->callback == 0)
  234120. isStarted = false;
  234121. return isStarted;
  234122. }
  234123. const String getLastError()
  234124. {
  234125. return lastError;
  234126. }
  234127. int inputIndex, outputIndex;
  234128. juce_UseDebuggingNewOperator
  234129. private:
  234130. CoreAudioInternal* internal;
  234131. bool isOpen_, isStarted;
  234132. String lastError;
  234133. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234134. {
  234135. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234136. switch (pa->mSelector)
  234137. {
  234138. case kAudioHardwarePropertyDevices:
  234139. intern->deviceDetailsChanged();
  234140. break;
  234141. case kAudioHardwarePropertyDefaultOutputDevice:
  234142. case kAudioHardwarePropertyDefaultInputDevice:
  234143. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  234144. break;
  234145. }
  234146. return noErr;
  234147. }
  234148. CoreAudioIODevice (const CoreAudioIODevice&);
  234149. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  234150. };
  234151. class CoreAudioIODeviceType : public AudioIODeviceType
  234152. {
  234153. public:
  234154. CoreAudioIODeviceType()
  234155. : AudioIODeviceType ("CoreAudio"),
  234156. hasScanned (false)
  234157. {
  234158. }
  234159. ~CoreAudioIODeviceType()
  234160. {
  234161. }
  234162. void scanForDevices()
  234163. {
  234164. hasScanned = true;
  234165. inputDeviceNames.clear();
  234166. outputDeviceNames.clear();
  234167. inputIds.clear();
  234168. outputIds.clear();
  234169. UInt32 size;
  234170. AudioObjectPropertyAddress pa;
  234171. pa.mSelector = kAudioHardwarePropertyDevices;
  234172. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234173. pa.mElement = kAudioObjectPropertyElementMaster;
  234174. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  234175. {
  234176. HeapBlock <AudioDeviceID> devs;
  234177. devs.calloc (size, 1);
  234178. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  234179. {
  234180. static bool alreadyLogged = false;
  234181. const int num = size / (int) sizeof (AudioDeviceID);
  234182. for (int i = 0; i < num; ++i)
  234183. {
  234184. char name [1024];
  234185. size = sizeof (name);
  234186. pa.mSelector = kAudioDevicePropertyDeviceName;
  234187. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  234188. {
  234189. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  234190. if (! alreadyLogged)
  234191. log ("CoreAudio device: " + nameString);
  234192. const int numIns = getNumChannels (devs[i], true);
  234193. const int numOuts = getNumChannels (devs[i], false);
  234194. if (numIns > 0)
  234195. {
  234196. inputDeviceNames.add (nameString);
  234197. inputIds.add (devs[i]);
  234198. }
  234199. if (numOuts > 0)
  234200. {
  234201. outputDeviceNames.add (nameString);
  234202. outputIds.add (devs[i]);
  234203. }
  234204. }
  234205. }
  234206. alreadyLogged = true;
  234207. }
  234208. }
  234209. inputDeviceNames.appendNumbersToDuplicates (false, true);
  234210. outputDeviceNames.appendNumbersToDuplicates (false, true);
  234211. }
  234212. const StringArray getDeviceNames (bool wantInputNames) const
  234213. {
  234214. jassert (hasScanned); // need to call scanForDevices() before doing this
  234215. if (wantInputNames)
  234216. return inputDeviceNames;
  234217. else
  234218. return outputDeviceNames;
  234219. }
  234220. int getDefaultDeviceIndex (bool forInput) const
  234221. {
  234222. jassert (hasScanned); // need to call scanForDevices() before doing this
  234223. AudioDeviceID deviceID;
  234224. UInt32 size = sizeof (deviceID);
  234225. // if they're asking for any input channels at all, use the default input, so we
  234226. // get the built-in mic rather than the built-in output with no inputs..
  234227. AudioObjectPropertyAddress pa;
  234228. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  234229. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234230. pa.mElement = kAudioObjectPropertyElementMaster;
  234231. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  234232. {
  234233. if (forInput)
  234234. {
  234235. for (int i = inputIds.size(); --i >= 0;)
  234236. if (inputIds[i] == deviceID)
  234237. return i;
  234238. }
  234239. else
  234240. {
  234241. for (int i = outputIds.size(); --i >= 0;)
  234242. if (outputIds[i] == deviceID)
  234243. return i;
  234244. }
  234245. }
  234246. return 0;
  234247. }
  234248. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  234249. {
  234250. jassert (hasScanned); // need to call scanForDevices() before doing this
  234251. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  234252. if (d == 0)
  234253. return -1;
  234254. return asInput ? d->inputIndex
  234255. : d->outputIndex;
  234256. }
  234257. bool hasSeparateInputsAndOutputs() const { return true; }
  234258. AudioIODevice* createDevice (const String& outputDeviceName,
  234259. const String& inputDeviceName)
  234260. {
  234261. jassert (hasScanned); // need to call scanForDevices() before doing this
  234262. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  234263. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  234264. String deviceName (outputDeviceName);
  234265. if (deviceName.isEmpty())
  234266. deviceName = inputDeviceName;
  234267. if (index >= 0)
  234268. return new CoreAudioIODevice (deviceName,
  234269. inputIds [inputIndex],
  234270. inputIndex,
  234271. outputIds [outputIndex],
  234272. outputIndex);
  234273. return 0;
  234274. }
  234275. juce_UseDebuggingNewOperator
  234276. private:
  234277. StringArray inputDeviceNames, outputDeviceNames;
  234278. Array <AudioDeviceID> inputIds, outputIds;
  234279. bool hasScanned;
  234280. static int getNumChannels (AudioDeviceID deviceID, bool input)
  234281. {
  234282. int total = 0;
  234283. UInt32 size;
  234284. AudioObjectPropertyAddress pa;
  234285. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234286. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234287. pa.mElement = kAudioObjectPropertyElementMaster;
  234288. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234289. {
  234290. HeapBlock <AudioBufferList> bufList;
  234291. bufList.calloc (size, 1);
  234292. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234293. {
  234294. const int numStreams = bufList->mNumberBuffers;
  234295. for (int i = 0; i < numStreams; ++i)
  234296. {
  234297. const AudioBuffer& b = bufList->mBuffers[i];
  234298. total += b.mNumberChannels;
  234299. }
  234300. }
  234301. }
  234302. return total;
  234303. }
  234304. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  234305. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  234306. };
  234307. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  234308. {
  234309. return new CoreAudioIODeviceType();
  234310. }
  234311. #undef log
  234312. #endif
  234313. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  234314. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  234315. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234316. // compiled on its own).
  234317. #if JUCE_INCLUDED_FILE
  234318. #if JUCE_MAC
  234319. #undef log
  234320. #define log(a) Logger::writeToLog(a)
  234321. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  234322. {
  234323. if (err == noErr)
  234324. return true;
  234325. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234326. jassertfalse;
  234327. return false;
  234328. }
  234329. #undef OK
  234330. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  234331. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  234332. {
  234333. String result;
  234334. CFStringRef str = 0;
  234335. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  234336. if (str != 0)
  234337. {
  234338. result = PlatformUtilities::cfStringToJuceString (str);
  234339. CFRelease (str);
  234340. str = 0;
  234341. }
  234342. MIDIEntityRef entity = 0;
  234343. MIDIEndpointGetEntity (endpoint, &entity);
  234344. if (entity == 0)
  234345. return result; // probably virtual
  234346. if (result.isEmpty())
  234347. {
  234348. // endpoint name has zero length - try the entity
  234349. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  234350. if (str != 0)
  234351. {
  234352. result += PlatformUtilities::cfStringToJuceString (str);
  234353. CFRelease (str);
  234354. str = 0;
  234355. }
  234356. }
  234357. // now consider the device's name
  234358. MIDIDeviceRef device = 0;
  234359. MIDIEntityGetDevice (entity, &device);
  234360. if (device == 0)
  234361. return result;
  234362. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  234363. if (str != 0)
  234364. {
  234365. const String s (PlatformUtilities::cfStringToJuceString (str));
  234366. CFRelease (str);
  234367. // if an external device has only one entity, throw away
  234368. // the endpoint name and just use the device name
  234369. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  234370. {
  234371. result = s;
  234372. }
  234373. else if (! result.startsWithIgnoreCase (s))
  234374. {
  234375. // prepend the device name to the entity name
  234376. result = (s + " " + result).trimEnd();
  234377. }
  234378. }
  234379. return result;
  234380. }
  234381. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  234382. {
  234383. String result;
  234384. // Does the endpoint have connections?
  234385. CFDataRef connections = 0;
  234386. int numConnections = 0;
  234387. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  234388. if (connections != 0)
  234389. {
  234390. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  234391. if (numConnections > 0)
  234392. {
  234393. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  234394. for (int i = 0; i < numConnections; ++i, ++pid)
  234395. {
  234396. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  234397. MIDIObjectRef connObject;
  234398. MIDIObjectType connObjectType;
  234399. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  234400. if (err == noErr)
  234401. {
  234402. String s;
  234403. if (connObjectType == kMIDIObjectType_ExternalSource
  234404. || connObjectType == kMIDIObjectType_ExternalDestination)
  234405. {
  234406. // Connected to an external device's endpoint (10.3 and later).
  234407. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  234408. }
  234409. else
  234410. {
  234411. // Connected to an external device (10.2) (or something else, catch-all)
  234412. CFStringRef str = 0;
  234413. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  234414. if (str != 0)
  234415. {
  234416. s = PlatformUtilities::cfStringToJuceString (str);
  234417. CFRelease (str);
  234418. }
  234419. }
  234420. if (s.isNotEmpty())
  234421. {
  234422. if (result.isNotEmpty())
  234423. result += ", ";
  234424. result += s;
  234425. }
  234426. }
  234427. }
  234428. }
  234429. CFRelease (connections);
  234430. }
  234431. if (result.isNotEmpty())
  234432. return result;
  234433. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  234434. return getEndpointName (endpoint, false);
  234435. }
  234436. const StringArray MidiOutput::getDevices()
  234437. {
  234438. StringArray s;
  234439. const ItemCount num = MIDIGetNumberOfDestinations();
  234440. for (ItemCount i = 0; i < num; ++i)
  234441. {
  234442. MIDIEndpointRef dest = MIDIGetDestination (i);
  234443. if (dest != 0)
  234444. {
  234445. String name (getConnectedEndpointName (dest));
  234446. if (name.isEmpty())
  234447. name = "<error>";
  234448. s.add (name);
  234449. }
  234450. else
  234451. {
  234452. s.add ("<error>");
  234453. }
  234454. }
  234455. return s;
  234456. }
  234457. int MidiOutput::getDefaultDeviceIndex()
  234458. {
  234459. return 0;
  234460. }
  234461. static MIDIClientRef globalMidiClient;
  234462. static bool hasGlobalClientBeenCreated = false;
  234463. static bool makeSureClientExists()
  234464. {
  234465. if (! hasGlobalClientBeenCreated)
  234466. {
  234467. String name ("JUCE");
  234468. if (JUCEApplication::getInstance() != 0)
  234469. name = JUCEApplication::getInstance()->getApplicationName();
  234470. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  234471. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  234472. CFRelease (appName);
  234473. }
  234474. return hasGlobalClientBeenCreated;
  234475. }
  234476. class MidiPortAndEndpoint
  234477. {
  234478. public:
  234479. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  234480. : port (port_), endPoint (endPoint_)
  234481. {
  234482. }
  234483. ~MidiPortAndEndpoint()
  234484. {
  234485. if (port != 0)
  234486. MIDIPortDispose (port);
  234487. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  234488. MIDIEndpointDispose (endPoint);
  234489. }
  234490. MIDIPortRef port;
  234491. MIDIEndpointRef endPoint;
  234492. };
  234493. MidiOutput* MidiOutput::openDevice (int index)
  234494. {
  234495. MidiOutput* mo = 0;
  234496. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  234497. {
  234498. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  234499. CFStringRef pname;
  234500. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  234501. {
  234502. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  234503. if (makeSureClientExists())
  234504. {
  234505. MIDIPortRef port;
  234506. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  234507. {
  234508. mo = new MidiOutput();
  234509. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  234510. }
  234511. }
  234512. CFRelease (pname);
  234513. }
  234514. }
  234515. return mo;
  234516. }
  234517. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  234518. {
  234519. MidiOutput* mo = 0;
  234520. if (makeSureClientExists())
  234521. {
  234522. MIDIEndpointRef endPoint;
  234523. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  234524. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  234525. {
  234526. mo = new MidiOutput();
  234527. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  234528. }
  234529. CFRelease (name);
  234530. }
  234531. return mo;
  234532. }
  234533. MidiOutput::~MidiOutput()
  234534. {
  234535. delete (MidiPortAndEndpoint*) internal;
  234536. }
  234537. void MidiOutput::reset()
  234538. {
  234539. }
  234540. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  234541. {
  234542. return false;
  234543. }
  234544. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  234545. {
  234546. }
  234547. void MidiOutput::sendMessageNow (const MidiMessage& message)
  234548. {
  234549. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  234550. if (message.isSysEx())
  234551. {
  234552. const int maxPacketSize = 256;
  234553. int pos = 0, bytesLeft = message.getRawDataSize();
  234554. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  234555. HeapBlock <MIDIPacketList> packets;
  234556. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  234557. packets->numPackets = numPackets;
  234558. MIDIPacket* p = packets->packet;
  234559. for (int i = 0; i < numPackets; ++i)
  234560. {
  234561. p->timeStamp = 0;
  234562. p->length = jmin (maxPacketSize, bytesLeft);
  234563. memcpy (p->data, message.getRawData() + pos, p->length);
  234564. pos += p->length;
  234565. bytesLeft -= p->length;
  234566. p = MIDIPacketNext (p);
  234567. }
  234568. if (mpe->port != 0)
  234569. MIDISend (mpe->port, mpe->endPoint, packets);
  234570. else
  234571. MIDIReceived (mpe->endPoint, packets);
  234572. }
  234573. else
  234574. {
  234575. MIDIPacketList packets;
  234576. packets.numPackets = 1;
  234577. packets.packet[0].timeStamp = 0;
  234578. packets.packet[0].length = message.getRawDataSize();
  234579. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  234580. if (mpe->port != 0)
  234581. MIDISend (mpe->port, mpe->endPoint, &packets);
  234582. else
  234583. MIDIReceived (mpe->endPoint, &packets);
  234584. }
  234585. }
  234586. const StringArray MidiInput::getDevices()
  234587. {
  234588. StringArray s;
  234589. const ItemCount num = MIDIGetNumberOfSources();
  234590. for (ItemCount i = 0; i < num; ++i)
  234591. {
  234592. MIDIEndpointRef source = MIDIGetSource (i);
  234593. if (source != 0)
  234594. {
  234595. String name (getConnectedEndpointName (source));
  234596. if (name.isEmpty())
  234597. name = "<error>";
  234598. s.add (name);
  234599. }
  234600. else
  234601. {
  234602. s.add ("<error>");
  234603. }
  234604. }
  234605. return s;
  234606. }
  234607. int MidiInput::getDefaultDeviceIndex()
  234608. {
  234609. return 0;
  234610. }
  234611. struct MidiPortAndCallback
  234612. {
  234613. MidiInput* input;
  234614. MidiPortAndEndpoint* portAndEndpoint;
  234615. MidiInputCallback* callback;
  234616. MemoryBlock pendingData;
  234617. int pendingBytes;
  234618. double pendingDataTime;
  234619. bool active;
  234620. void processSysex (const uint8*& d, int& size, const double time)
  234621. {
  234622. if (*d == 0xf0)
  234623. {
  234624. pendingBytes = 0;
  234625. pendingDataTime = time;
  234626. }
  234627. pendingData.ensureSize (pendingBytes + size, false);
  234628. uint8* totalMessage = (uint8*) pendingData.getData();
  234629. uint8* dest = totalMessage + pendingBytes;
  234630. while (size > 0)
  234631. {
  234632. if (pendingBytes > 0 && *d >= 0x80)
  234633. {
  234634. if (*d >= 0xfa || *d == 0xf8)
  234635. {
  234636. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  234637. ++d;
  234638. --size;
  234639. }
  234640. else
  234641. {
  234642. if (*d == 0xf7)
  234643. {
  234644. *dest++ = *d++;
  234645. pendingBytes++;
  234646. --size;
  234647. }
  234648. break;
  234649. }
  234650. }
  234651. else
  234652. {
  234653. *dest++ = *d++;
  234654. pendingBytes++;
  234655. --size;
  234656. }
  234657. }
  234658. if (totalMessage [pendingBytes - 1] == 0xf7)
  234659. {
  234660. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  234661. pendingBytes = 0;
  234662. }
  234663. else
  234664. {
  234665. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  234666. }
  234667. }
  234668. };
  234669. namespace CoreMidiCallbacks
  234670. {
  234671. static CriticalSection callbackLock;
  234672. static Array<void*> activeCallbacks;
  234673. }
  234674. static void midiInputProc (const MIDIPacketList* pktlist,
  234675. void* readProcRefCon,
  234676. void* /*srcConnRefCon*/)
  234677. {
  234678. double time = Time::getMillisecondCounterHiRes() * 0.001;
  234679. const double originalTime = time;
  234680. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  234681. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234682. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  234683. {
  234684. const MIDIPacket* packet = &pktlist->packet[0];
  234685. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  234686. {
  234687. const uint8* d = (const uint8*) (packet->data);
  234688. int size = packet->length;
  234689. while (size > 0)
  234690. {
  234691. time = originalTime;
  234692. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  234693. {
  234694. mpc->processSysex (d, size, time);
  234695. }
  234696. else
  234697. {
  234698. int used = 0;
  234699. const MidiMessage m (d, size, used, 0, time);
  234700. if (used <= 0)
  234701. {
  234702. jassertfalse; // malformed midi message
  234703. break;
  234704. }
  234705. else
  234706. {
  234707. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  234708. }
  234709. size -= used;
  234710. d += used;
  234711. }
  234712. }
  234713. packet = MIDIPacketNext (packet);
  234714. }
  234715. }
  234716. }
  234717. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  234718. {
  234719. MidiInput* mi = 0;
  234720. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  234721. {
  234722. MIDIEndpointRef endPoint = MIDIGetSource (index);
  234723. if (endPoint != 0)
  234724. {
  234725. CFStringRef pname;
  234726. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  234727. {
  234728. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  234729. if (makeSureClientExists())
  234730. {
  234731. MIDIPortRef port;
  234732. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  234733. mpc->active = false;
  234734. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  234735. {
  234736. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  234737. {
  234738. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  234739. mpc->callback = callback;
  234740. mpc->pendingBytes = 0;
  234741. mpc->pendingData.ensureSize (128);
  234742. mi = new MidiInput (getDevices() [index]);
  234743. mpc->input = mi;
  234744. mi->internal = mpc;
  234745. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234746. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  234747. }
  234748. else
  234749. {
  234750. OK (MIDIPortDispose (port));
  234751. }
  234752. }
  234753. }
  234754. }
  234755. CFRelease (pname);
  234756. }
  234757. }
  234758. return mi;
  234759. }
  234760. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  234761. {
  234762. MidiInput* mi = 0;
  234763. if (makeSureClientExists())
  234764. {
  234765. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  234766. mpc->active = false;
  234767. MIDIEndpointRef endPoint;
  234768. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  234769. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  234770. {
  234771. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  234772. mpc->callback = callback;
  234773. mpc->pendingBytes = 0;
  234774. mpc->pendingData.ensureSize (128);
  234775. mi = new MidiInput (deviceName);
  234776. mpc->input = mi;
  234777. mi->internal = mpc;
  234778. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234779. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  234780. }
  234781. CFRelease (name);
  234782. }
  234783. return mi;
  234784. }
  234785. MidiInput::MidiInput (const String& name_)
  234786. : name (name_)
  234787. {
  234788. }
  234789. MidiInput::~MidiInput()
  234790. {
  234791. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  234792. mpc->active = false;
  234793. {
  234794. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234795. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  234796. }
  234797. if (mpc->portAndEndpoint->port != 0)
  234798. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  234799. delete mpc->portAndEndpoint;
  234800. delete mpc;
  234801. }
  234802. void MidiInput::start()
  234803. {
  234804. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234805. ((MidiPortAndCallback*) internal)->active = true;
  234806. }
  234807. void MidiInput::stop()
  234808. {
  234809. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234810. ((MidiPortAndCallback*) internal)->active = false;
  234811. }
  234812. #undef log
  234813. #else
  234814. MidiOutput::~MidiOutput()
  234815. {
  234816. }
  234817. void MidiOutput::reset()
  234818. {
  234819. }
  234820. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  234821. {
  234822. return false;
  234823. }
  234824. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  234825. {
  234826. }
  234827. void MidiOutput::sendMessageNow (const MidiMessage& message)
  234828. {
  234829. }
  234830. const StringArray MidiOutput::getDevices()
  234831. {
  234832. return StringArray();
  234833. }
  234834. MidiOutput* MidiOutput::openDevice (int index)
  234835. {
  234836. return 0;
  234837. }
  234838. const StringArray MidiInput::getDevices()
  234839. {
  234840. return StringArray();
  234841. }
  234842. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  234843. {
  234844. return 0;
  234845. }
  234846. #endif
  234847. #endif
  234848. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  234849. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  234850. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234851. // compiled on its own).
  234852. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  234853. #if ! JUCE_QUICKTIME
  234854. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  234855. #endif
  234856. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  234857. class QTCameraDeviceInteral;
  234858. END_JUCE_NAMESPACE
  234859. @interface QTCaptureCallbackDelegate : NSObject
  234860. {
  234861. @public
  234862. CameraDevice* owner;
  234863. QTCameraDeviceInteral* internal;
  234864. int64 firstPresentationTime;
  234865. int64 averageTimeOffset;
  234866. }
  234867. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  234868. - (void) dealloc;
  234869. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  234870. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  234871. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  234872. fromConnection: (QTCaptureConnection*) connection;
  234873. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  234874. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  234875. fromConnection: (QTCaptureConnection*) connection;
  234876. @end
  234877. BEGIN_JUCE_NAMESPACE
  234878. class QTCameraDeviceInteral
  234879. {
  234880. public:
  234881. QTCameraDeviceInteral (CameraDevice* owner, int index)
  234882. {
  234883. const ScopedAutoReleasePool pool;
  234884. session = [[QTCaptureSession alloc] init];
  234885. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  234886. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  234887. input = 0;
  234888. audioInput = 0;
  234889. audioDevice = 0;
  234890. fileOutput = 0;
  234891. imageOutput = 0;
  234892. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  234893. internalDev: this];
  234894. NSError* err = 0;
  234895. [device retain];
  234896. [device open: &err];
  234897. if (err == 0)
  234898. {
  234899. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  234900. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  234901. [session addInput: input error: &err];
  234902. if (err == 0)
  234903. {
  234904. resetFile();
  234905. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  234906. [imageOutput setDelegate: callbackDelegate];
  234907. if (err == 0)
  234908. {
  234909. [session startRunning];
  234910. return;
  234911. }
  234912. }
  234913. }
  234914. openingError = nsStringToJuce ([err description]);
  234915. DBG (openingError);
  234916. }
  234917. ~QTCameraDeviceInteral()
  234918. {
  234919. [session stopRunning];
  234920. [session removeOutput: imageOutput];
  234921. [session release];
  234922. [input release];
  234923. [device release];
  234924. [audioDevice release];
  234925. [audioInput release];
  234926. [fileOutput release];
  234927. [imageOutput release];
  234928. [callbackDelegate release];
  234929. }
  234930. void resetFile()
  234931. {
  234932. [fileOutput recordToOutputFileURL: nil];
  234933. [session removeOutput: fileOutput];
  234934. [fileOutput release];
  234935. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  234936. [session removeInput: audioInput];
  234937. [audioInput release];
  234938. audioInput = 0;
  234939. [audioDevice release];
  234940. audioDevice = 0;
  234941. [fileOutput setDelegate: callbackDelegate];
  234942. }
  234943. void addDefaultAudioInput()
  234944. {
  234945. NSError* err = nil;
  234946. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  234947. if ([audioDevice open: &err])
  234948. [audioDevice retain];
  234949. else
  234950. audioDevice = nil;
  234951. if (audioDevice != 0)
  234952. {
  234953. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  234954. [session addInput: audioInput error: &err];
  234955. }
  234956. }
  234957. void addListener (CameraImageListener* listenerToAdd)
  234958. {
  234959. const ScopedLock sl (listenerLock);
  234960. if (listeners.size() == 0)
  234961. [session addOutput: imageOutput error: nil];
  234962. listeners.addIfNotAlreadyThere (listenerToAdd);
  234963. }
  234964. void removeListener (CameraImageListener* listenerToRemove)
  234965. {
  234966. const ScopedLock sl (listenerLock);
  234967. listeners.removeValue (listenerToRemove);
  234968. if (listeners.size() == 0)
  234969. [session removeOutput: imageOutput];
  234970. }
  234971. void callListeners (CIImage* frame, int w, int h)
  234972. {
  234973. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  234974. Image image (cgImage);
  234975. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  234976. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  234977. CGContextFlush (cgImage->context);
  234978. const ScopedLock sl (listenerLock);
  234979. for (int i = listeners.size(); --i >= 0;)
  234980. {
  234981. CameraImageListener* const l = listeners[i];
  234982. if (l != 0)
  234983. l->imageReceived (image);
  234984. }
  234985. }
  234986. QTCaptureDevice* device;
  234987. QTCaptureDeviceInput* input;
  234988. QTCaptureDevice* audioDevice;
  234989. QTCaptureDeviceInput* audioInput;
  234990. QTCaptureSession* session;
  234991. QTCaptureMovieFileOutput* fileOutput;
  234992. QTCaptureDecompressedVideoOutput* imageOutput;
  234993. QTCaptureCallbackDelegate* callbackDelegate;
  234994. String openingError;
  234995. Array<CameraImageListener*> listeners;
  234996. CriticalSection listenerLock;
  234997. };
  234998. END_JUCE_NAMESPACE
  234999. @implementation QTCaptureCallbackDelegate
  235000. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  235001. internalDev: (QTCameraDeviceInteral*) d
  235002. {
  235003. [super init];
  235004. owner = owner_;
  235005. internal = d;
  235006. firstPresentationTime = 0;
  235007. averageTimeOffset = 0;
  235008. return self;
  235009. }
  235010. - (void) dealloc
  235011. {
  235012. [super dealloc];
  235013. }
  235014. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235015. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235016. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235017. fromConnection: (QTCaptureConnection*) connection
  235018. {
  235019. if (internal->listeners.size() > 0)
  235020. {
  235021. const ScopedAutoReleasePool pool;
  235022. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  235023. CVPixelBufferGetWidth (videoFrame),
  235024. CVPixelBufferGetHeight (videoFrame));
  235025. }
  235026. }
  235027. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235028. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235029. fromConnection: (QTCaptureConnection*) connection
  235030. {
  235031. const Time now (Time::getCurrentTime());
  235032. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  235033. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  235034. #else
  235035. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  235036. #endif
  235037. int64 presentationTime = (hosttime != nil)
  235038. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  235039. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  235040. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  235041. if (firstPresentationTime == 0)
  235042. {
  235043. firstPresentationTime = presentationTime;
  235044. averageTimeOffset = timeDiff;
  235045. }
  235046. else
  235047. {
  235048. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  235049. }
  235050. }
  235051. @end
  235052. BEGIN_JUCE_NAMESPACE
  235053. class QTCaptureViewerComp : public NSViewComponent
  235054. {
  235055. public:
  235056. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  235057. {
  235058. const ScopedAutoReleasePool pool;
  235059. captureView = [[QTCaptureView alloc] init];
  235060. [captureView setCaptureSession: internal->session];
  235061. setSize (640, 480); // xxx need to somehow get the movie size - how?
  235062. setView (captureView);
  235063. }
  235064. ~QTCaptureViewerComp()
  235065. {
  235066. setView (0);
  235067. [captureView setCaptureSession: nil];
  235068. [captureView release];
  235069. }
  235070. QTCaptureView* captureView;
  235071. };
  235072. CameraDevice::CameraDevice (const String& name_, int index)
  235073. : name (name_)
  235074. {
  235075. isRecording = false;
  235076. internal = new QTCameraDeviceInteral (this, index);
  235077. }
  235078. CameraDevice::~CameraDevice()
  235079. {
  235080. stopRecording();
  235081. delete static_cast <QTCameraDeviceInteral*> (internal);
  235082. internal = 0;
  235083. }
  235084. Component* CameraDevice::createViewerComponent()
  235085. {
  235086. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  235087. }
  235088. const String CameraDevice::getFileExtension()
  235089. {
  235090. return ".mov";
  235091. }
  235092. void CameraDevice::startRecordingToFile (const File& file, int quality)
  235093. {
  235094. stopRecording();
  235095. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235096. d->callbackDelegate->firstPresentationTime = 0;
  235097. file.deleteFile();
  235098. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  235099. // out wrong, so we'll put some audio in there too..,
  235100. d->addDefaultAudioInput();
  235101. [d->session addOutput: d->fileOutput error: nil];
  235102. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  235103. for (;;)
  235104. {
  235105. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  235106. if (connection == 0)
  235107. break;
  235108. QTCompressionOptions* options = 0;
  235109. NSString* mediaType = [connection mediaType];
  235110. if ([mediaType isEqualToString: QTMediaTypeVideo])
  235111. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  235112. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  235113. : @"QTCompressionOptions240SizeH264Video"];
  235114. else if ([mediaType isEqualToString: QTMediaTypeSound])
  235115. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  235116. [d->fileOutput setCompressionOptions: options forConnection: connection];
  235117. }
  235118. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  235119. isRecording = true;
  235120. }
  235121. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  235122. {
  235123. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235124. if (d->callbackDelegate->firstPresentationTime != 0)
  235125. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  235126. return Time();
  235127. }
  235128. void CameraDevice::stopRecording()
  235129. {
  235130. if (isRecording)
  235131. {
  235132. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  235133. isRecording = false;
  235134. }
  235135. }
  235136. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  235137. {
  235138. if (listenerToAdd != 0)
  235139. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  235140. }
  235141. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  235142. {
  235143. if (listenerToRemove != 0)
  235144. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  235145. }
  235146. const StringArray CameraDevice::getAvailableDevices()
  235147. {
  235148. const ScopedAutoReleasePool pool;
  235149. StringArray results;
  235150. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235151. for (int i = 0; i < (int) [devs count]; ++i)
  235152. {
  235153. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  235154. results.add (nsStringToJuce ([dev localizedDisplayName]));
  235155. }
  235156. return results;
  235157. }
  235158. CameraDevice* CameraDevice::openDevice (int index,
  235159. int minWidth, int minHeight,
  235160. int maxWidth, int maxHeight)
  235161. {
  235162. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  235163. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  235164. return d.release();
  235165. return 0;
  235166. }
  235167. #endif
  235168. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  235169. #endif
  235170. #endif
  235171. END_JUCE_NAMESPACE
  235172. #endif
  235173. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  235174. #endif
  235175. #endif